diff --git a/apps/control-station/test/vescBmsView.test.mjs b/apps/control-station/test/vescBmsView.test.mjs new file mode 100644 index 00000000..fc20c41f --- /dev/null +++ b/apps/control-station/test/vescBmsView.test.mjs @@ -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'}]); +}); diff --git a/apps/control-station/test/vescCodeProjects.test.mjs b/apps/control-station/test/vescCodeProjects.test.mjs new file mode 100644 index 00000000..8b70b23c --- /dev/null +++ b/apps/control-station/test/vescCodeProjects.test.mjs @@ -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')); +}); diff --git a/apps/control-station/test/vescConfigurationDelivery.test.mjs b/apps/control-station/test/vescConfigurationDelivery.test.mjs new file mode 100644 index 00000000..97256c51 --- /dev/null +++ b/apps/control-station/test/vescConfigurationDelivery.test.mjs @@ -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})); diff --git a/apps/control-station/test/vescControlTransport.test.mjs b/apps/control-station/test/vescControlTransport.test.mjs new file mode 100644 index 00000000..207048c2 --- /dev/null +++ b/apps/control-station/test/vescControlTransport.test.mjs @@ -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)); +}); diff --git a/apps/control-station/test/vescDiagnosticReview.test.mjs b/apps/control-station/test/vescDiagnosticReview.test.mjs new file mode 100644 index 00000000..4e166020 --- /dev/null +++ b/apps/control-station/test/vescDiagnosticReview.test.mjs @@ -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'));} +}); diff --git a/apps/control-station/test/vescFirmwareFiles.test.mjs b/apps/control-station/test/vescFirmwareFiles.test.mjs new file mode 100644 index 00000000..5e02189b --- /dev/null +++ b/apps/control-station/test/vescFirmwareFiles.test.mjs @@ -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'])); +}); diff --git a/apps/control-station/test/vescHallInputs.test.mjs b/apps/control-station/test/vescHallInputs.test.mjs new file mode 100644 index 00000000..72a121e8 --- /dev/null +++ b/apps/control-station/test/vescHallInputs.test.mjs @@ -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'); +}); diff --git a/apps/control-station/test/vescLogAnalysis.test.mjs b/apps/control-station/test/vescLogAnalysis.test.mjs new file mode 100644 index 00000000..2da229a3 --- /dev/null +++ b/apps/control-station/test/vescLogAnalysis.test.mjs @@ -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],'Нет связи'); +}); diff --git a/apps/control-station/test/vescRotorHallReview.test.mjs b/apps/control-station/test/vescRotorHallReview.test.mjs new file mode 100644 index 00000000..370a64ae --- /dev/null +++ b/apps/control-station/test/vescRotorHallReview.test.mjs @@ -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);}); diff --git a/apps/control-station/test/vescSampleReview.test.mjs b/apps/control-station/test/vescSampleReview.test.mjs new file mode 100644 index 00000000..edf94f41 --- /dev/null +++ b/apps/control-station/test/vescSampleReview.test.mjs @@ -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);}}); diff --git a/apps/control-station/test/vescSamples.test.mjs b/apps/control-station/test/vescSamples.test.mjs new file mode 100644 index 00000000..c3d4505c --- /dev/null +++ b/apps/control-station/test/vescSamples.test.mjs @@ -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')); +}); diff --git a/apps/control-station/test/vescSettings.test.mjs b/apps/control-station/test/vescSettings.test.mjs new file mode 100644 index 00000000..32c48eec --- /dev/null +++ b/apps/control-station/test/vescSettings.test.mjs @@ -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); +}); diff --git a/apps/control-station/test/vescTrends.test.mjs b/apps/control-station/test/vescTrends.test.mjs new file mode 100644 index 00000000..cf394137 --- /dev/null +++ b/apps/control-station/test/vescTrends.test.mjs @@ -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); +}); diff --git a/docs/node/17_VESC_INSTALLATION_LEDGER.md b/docs/node/17_VESC_INSTALLATION_LEDGER.md index 2324229b..4cd8f50c 100644 --- a/docs/node/17_VESC_INSTALLATION_LEDGER.md +++ b/docs/node/17_VESC_INSTALLATION_LEDGER.md @@ -2242,3 +2242,1839 @@ Manage availability. One first-click neutral-only preparation completed; explicit Stop confirmed release and both motors zero. 307 samples, no read errors/faults/motion; 938 unit tests, typecheck, architecture and build pass. See 25_OBSERVATION_AND_REMOTE_CONTROL.md and private entry-startup-result.json. + + +## 2026-10-16 — remote throttle and retained current ceiling + +Owner retained the 30 A per-motor ceiling and requested speed adjustment rather +than an unsupported increase to 60 A. Battery is owner-reported 48 V / 120 Ah; +BMS current and exact motor/controller ratings remain unknown. Fresh read-only +backups confirm both PPM inputs use Duty Cycle, approximately 34.2/34.4 A +configured motor limits and 0.95 maximum duty. See the implementation record +in `25_OBSERVATION_AND_REMOTE_CONTROL.md`. + +VESC 0.7.5 adds explicit percent throttle through upstream Tool setDutyCycle, +with existing temporary current reduction, output/input leases, neutral/RC +checks and synchronized reversal retained. Default throttle is 10%; old saved +ERPM values never migrate into full throttle. The UI removes the redundant +standstill switch; the primary action and adjacent instruction remain the +operator admission on a stopped apparatus. No agent-issued arm, movement, +calibration or controller configuration write was used for this delivery. + +Native probe 2851478d88575da76f66f446 compiled on the prepared Ubuntu Mini and +passed offline archive/output-denial checks without hardware access. Node +0.8.49-4 source 278696b0b2e2b953d510ad02 completed the node-only qualification +in 285.54 seconds, including Go race tests and 151 VESC tests. Package SHA-256: +`71016b6f3e4d43e0afb0babeb7a2172df35d755e03669400f241d368cc77698c`. +Core control/transport: 26 tests; frontend: 1096 tests, architecture, TypeScript +and production build passed. A preliminary source was rejected by the existing +Node/driver version consistency test; only the corrected qualified package is +eligible for installation. This is prepared-Ubuntu qualification, not clean-OS +or loaded-motion acceptance. + +The versioned Node installer owns payload replacement and re-preparation of +an already installed VESC profile. No network or firmware reconfiguration is +part of this update. Previous qualified Node 0.8.49-3 and native bundle are +preserved as rollback artifacts; rollback requires stopped motors and the same +owned installer workflow. Private receipts are under +`outputs/rover-006-control-20261016`. + + +Installed 2026-10-16 11:29:05 UTC through owner release +`7e1d42890af25db8f9c81914`; all installer stages succeeded in 19.64 s. APT +upgraded only mission-core-node 0.8.49-3 -> 0.8.49-4 (zero additions/removals). +Read-only verification confirms Node/VESC active, preparation 0.7.5 complete, +and installed native binary hash matches the qualified payload. Core receives +fresh `rpm,duty` capability and both assigned controllers at zero current/ERPM, +fault=0, no control session. Fresh post-install backups have identical motor +and application configuration hashes for both VESCs. + +Browser verification: Gas 10%, current 30 A; 50% accepted without arming, 101% +disables the primary action, 10% restored and retained after Escape/reopen. +Standstill switch absent, primary action present. Canonical Core remains on +8000. No agent-issued arm or movement. Loaded driving, precise ground speed +and physical stopping with the new duty output remain owner-attended tests. + + +## 2026-10-16 — explicit retry after recovered controller + +Installed Node 0.8.49-5 / VESC 0.7.6 at 15:15:27 UTC using owner release +`d24e43f334419d8a3d085161`. This corrects historical terminal-state handling +while a new manually requested session is preparing, and records initiating +native failures with bounded diagnostics. Current-session faults, identity and +standstill checks, current ceiling and output watchdog remain enforced. + +Source `bb066a42d6add9a9571fc069` passed prepared-Ubuntu node qualification: +158 VESC tests and Go race checks, 285.615 seconds. Frontend architecture, +TypeScript, 1124 tests and production build passed. Final package SHA-256: +`3fb41add4d191324a9ca9df179b0cde11f339465dd0175c68fa8b1dec3a9d7f7`. +Installer SHA-256: +`3ad070b27f25976bd735484fc96328f7782f351e5dd8163a90e74912caa9d57e`. + +The installer completed all stages in 23.90 seconds; APT upgraded only the +existing Node package (zero additions/removals). VESC preparation 0.7.6 is +complete; Node/VESC services active; installed source hashes match. Both +controllers report fresh zero current/ERPM and fault=0, observing, no active +session. Wi-Fi DCEXPRESS_DIR_5 remains connected; newer X4 0.1.3-15 preserved. +The standard Core Node installer catalog now serves this qualified release; +previous releases and rollback evidence remain available. Private receipts: +`outputs/rover-control-channel-20261016/stale-fault-*`. + +No agent-issued arm, movement, VESC reset, firmware update or network changes. +Owner trial at 15:18:42 UTC reached ready at 15:18:52 and held the same +session for the remaining 55 seconds of observation, including brief owner +inputs. All 710 samples fresh, zero read errors or VESC fault codes. Field +reliability and recovery from a newly induced hardware failure remain untested. +This software fix does not resolve or diagnose the physical USB lockup. + +## 2026-10-16 — bounded wait for remote idle modulation + +Owner attempt failed at 16:10:20 UTC before the remote output loop with +reported duty 0.002 (0.2%), outside the existing sensorless admission bound +0.001 (0.1%). No native RPC failure was recorded. The pinned upstream FW 5.02 +computes duty from measured phase voltages in its undriven branch; one wire +quantum is not a physical upper bound on estimator noise. The later 150-sample +read-only observation had both devices fresh, zero motor/input current, +zero ERPM/fault and duty in [-0.001, 0.001]. It does not establish the full +electrical state at the earlier rejection. + +Node 0.8.49-6 / VESC 0.7.7 candidate preserves the final admission bound. +Only remote throttle preparation can wait through a sensorless idle duty +transient within the existing generic 1% idle envelope. Both motors must +then complete ten consecutive quiet sampling rounds (100 ms spacing) within +the original 0.1% sensorless bound. A late transient resets the whole-profile +window. Waiting is capped at 30 rounds / three seconds, then fails closed. +Current, voltage, fault, temperature, RC neutral, input lease, identity and +attachment checks remain active throughout; no output or temporary-limit write +is issued while waiting. Hall/calibration/bench admission is unchanged. + +Seven new synthetic full-preparation regressions cover initial/late transient, +persistent modulation, excessive modulation, excessive battery current, RC +preemption and lease expiry, with no-output assertions. Local VESC validation +passed 165 tests. Pytest's imported protocol test_packet helper was excluded +from collection; it is not a test (the first invocation recorded that collection +error). Ubuntu artifact qualification and installation are pending. Private +evidence: outputs/rover-pwm-admission-20261016. + +Installed at 16:26:02–16:26:22 UTC via qualified release +`8a1935e9d4d4b1e228d7e5b4`; all Ubuntu qualification jobs and 165 VESC tests +passed. Package SHA-256: +`555c4e0117a9b29a1464e3c37582ef5638aa62ed31e49b62e003b18c14dcfb79`. +Installer SHA-256: +`9ee8fb7cc02023dd617b2f29b578ce239938db64b83a89d3e0cfc3227f60ef09`. +APT upgraded one existing Node package, added/removed zero packages. The newer +X4 0.1.3-15 was preserved. VESC preparation 0.7.7 is complete; Node/VESC active; +Wi-Fi DCEXPRESS_DIR_5 remains connected. Post-install read-only acceptance had +25/25 fresh samples, both assigned devices, zero current/fault, control off. +No agent-issued arm or movement. The standard installer catalog now carries +this release. The qualified source and installer are retained, all qualification +logs preserved locally; only this artifact's generated remote build scratch +was retired using its own --clean entry point. Physical owner retry pending. + +Additional post-install observation: 292/292 fresh samples over 60 seconds, +all observing, no control session or agent-issued movement. Owner retry was +requested; no arm was observed during this window. + +Owner acceptance follow-up: the requested stationary 30-second trial was +reported successful: control enabled and remained held. This accepts the +reported preparation/session-hold behavior, not physical latency or field +reliability. The subsequent read-only session snapshot is retained privately +in `outputs/rover-pwm-admission-20261016/owner-success.json`. + + +## 2026-10-17 · Recover the read-only VESC observer + +Owner scope: repair telemetry recovery, qualify and install through the normal +Ubuntu Node release, then verify through Core. No motor output, arm, Hall/FOC, +firmware or controller configuration operation is authorized by this work. + +The service journal confirmed an uncaught subprocess.TimeoutExpired terminating +vesc-observer after a native RPC failure: terminate/wait timed out, and the +subsequent kill/wait also timed out. Discovery remained alive and recreated the +native children, so USB inventory still showed both devices while Core retained +one stale sample and no right-side sample. The initiating native/USB timeout +itself is not yet attributed to hardware or networking. + +Node 0.8.49-7 / VESC 0.7.8 bounds both cleanup waits, preserves the original RPC +failure, closes pipe handles and retains any not-yet-exited child until poll +confirms exit. A replacement cannot claim that same tty while the old owner is +still alive. Discovery reaps retired children. Read-only per-device observation +isolates failures and reconnects through discovery; the discovery/observer loops +survive unexpected exceptions with rate-limited diagnostics. Powered operations +are not replayed. Source: native_link.py, service.py, remote_control.py, +server.py and test_observer_recovery.py; plugin/package version declarations +advance accordingly. Existing unrelated working-tree changes are preserved. + +Six new synthetic regressions cover double cleanup timeout, signal race, +original exception preservation, independent peer telemetry and reconnect, +loop recovery/rate limiting, and expired observation interest. Local and Ubuntu +VESC suites each passed 171 tests. Local pytest excluded the pre-existing +imported test_packet helper from collection; Ubuntu unittest needed no exclusion. +All 18 Linux qualification stages passed, including Go race tests, environment, +installer staging, USB unit validation, Node UI and package build. + +Qualified source ID: 27dee7c2e9318dacc2e8e34e. +Package SHA-256: +29bed65c12a98ede41fbfbccb51330f8cfb35c1273c852b13b6429bfc43f1816. +Owner release ID: 28e6de0ab4649d95b7c92826; installer SHA-256: +3554dfbc5117559252fb85b17754ecc75576ce557f1cd4dc46e246a813fb733a. +APT simulation: one existing Node upgrade, zero added/removed packages. +Installed successfully at 15:37:25–15:37:51 UTC through the exact versioned +owner installer. After the owner explicitly supplied credentials for this +installation, the unused graphical sudo prompt was cancelled before it had +children and the same installer ran in an SSH TTY; credentials were not saved +in files or process arguments. Installer session: +ac47f060a100496a998b7d2a778c81b1, state complete, exit code 0. +Newer X4 0.1.3-15 was preserved. Node/VESC are active with zero automatic +restarts. VESC preparation 0.7.8 completed; all five installed runtime file +hashes match the qualified source. Native VESC Tool remains 7.00 at the same +upstream commit; the installed engine hash matches its pinned manifest. + +Read-only Core acceptance: 114/114 fresh paired snapshots over 60.206 seconds, +maximum sample age 212 ms left / 213 ms right, fault_code 0 and motor/battery +current 0 A throughout. Control remained off, observing, session_id null. +Drive profile revision 2 and both UUID bindings exactly match the before state. +The existing browser panel recovered both channels without a Core restart; +left stale/right no-link labels disappeared, both show live voltage and +controller temperature with no VESC fault. The post-install service journal +contains no new observer exception. No physical USB disconnect or powered +trial was performed; real post-install restoration and synthetic fault +recovery are separate acceptance evidence. The first native/USB timeout's +underlying cause remains unproven. The standard fleet installer catalog now +contains 0.8.49-7 and retains the prior installer. + +Private evidence: outputs/vesc-observer-20261017. The qualified input is pinned, +retention apply completed with zero deletions, and only this build's remote +scratch was removed using its own --clean after the verified result transfer. + +## 2026-10-17 · USB lifecycle, stream freshness and reproducible owner payload + +Node 0.8.49-8 / VESC 0.7.9 was installed on ndc-rover-006 through the +versioned owner release. The owner explicitly admits USB removal/reinsertion, +changed tty numbers and swapping controller ports as normal scenarios. Drive +positions remain bound to controller UUID, never port or enumeration order. +No motor, arm, calibration, firmware or controller configuration command was +issued during qualification or acceptance. A pristine Ubuntu installation is +explicitly outside this acceptance, by owner instruction. + +The service retains known UUID identity independently from connection readiness. +A new handshake must confirm its own session before inventory advertises a live +link. Samples belong to the current Device generation; disconnect, replacement, +dead native owner and duplicate UUID invalidate their live authority. Discovery +and observation isolate failures per device. One per-device retry deadline uses +2/4/8/16/30-second backoff; only a successful telemetry read resets it. Existing +bounded native-child retirement remains in force. The observer acquires one +initial read-only values/PPM sample after connection even without a viewer; +further continuous observation requires current watch interest. Removal drops +live samples instead of keeping an unbounded UUID history. No retry worker, +process search script or command replay was added. + +Shared SensorWorkspace uses one InventoryObserver in Core and Node: one SSE, +one in-flight inventory read, cancellation, generation/revision guards, a +20-second independent freshness deadline (Node heartbeat is 15 seconds), and +bounded reconnect/fallback polling. RoverTransport retires a silent socket after +1.5 seconds and reconnects with capped delay. RoverRecovery compares both UUID +and USB session: disappearance/reconnection ends recovery and requires explicit +control admission. Legacy snapshots without USB sessions cannot opt into +automatic recovery. Core adds elapsed receipt time to cached sample ages. +Current Core was rebuilt and its existing LaunchAgent restarted; canonical +port 8000 remained the sole integrated service and recovered health. + +Source ownership: plugins/vesc/runtime/{service,remote_control}.py; +plugins/vesc/frontend/src/model.ts; shared sensor-ui inventory lifecycle; +Core rover transport/recovery/view projection; Node sensor_models.go and +versioned packaging. The first Linux candidate was rejected by the existing +Node/driver version consistency test before installation. The corrected final +source and all final evidence are retained separately; this is not an installed +failure. + +The actual owner installer now carries the two exact TimescaleDB 2.29.2 Ubuntu +24.04/PG16 packages required by Node, verified from the vendor-signed package +index by the artifact-owned Linux job. Both staging and root installation admit +only that fixed dependency set and verify payload hashes. PostgreSQL 16.15 is +available from ordinary noble-updates/noble-security on the declared profile; +standard Ubuntu dependencies still require online APT resolution. The final +manifest keeps clean_image_qualified=false. VESC is the bundled native Tool +7.00 engine and private runtime dependencies, not a full desktop VESC Tool GUI; +the destination does not need a compiler or a repository clone. First-use +preparation remains the versioned action in the application; prepared boards +rerun it on upgrade. No ad-hoc OS repair was applied. + +Validation: 182 synthetic VESC tests, 60 Core rover/backend tests, 1157 frontend +tests, typecheck and production build, 10 packaging tests; all 19 final Linux +qualification jobs passed, including Go race tests, Node UI, device preparation, +installer staging and signed dependency fetch. Synthetic coverage includes port +swap, changed tty, repeated enumeration with two owners, startup/read failures, +backoff, identity admission, duplicate UUID, silent WS/SSE, stale HTTP replies, +unmount cancellation and explicit re-arm after USB generation change. Physical +USB unplug/port swap was not performed; live deployment recovery is separate +evidence from those synthetic tests. + +Final source ID: 1ca7c96398b60e2f245c5cb8; SHA-256: +1fb6c2e717b25e54d285771e08c66caad0ae25f544b772ac7ecc48e0a25d807e. +Node package SHA-256: +f8bd07c62536ecdac09798f8e378571fb981b5ad114b44e8c5a4a9dbbe8330cd. +Owner release ID: 0fffa30e58c50b6376287821; SHA-256: +84b112cf13476fa17c6e5aa4d3a7fe445b6bc8cb94d70f7094da06d3e16bfe84. +APT plan: one Node upgrade, no added or removed packages. Installation session +1ad68be63e0045928b07645be5a61b7d completed at 16:24:49–16:25:07 UTC, exit 0. +Newer X4 0.1.3-15 was preserved. VESC preparation 0.7.9 completed. Installed +runtime hashes match the final source; native engine hash is unchanged. Node +and VESC services are active, NRestarts=0; exactly two native USB owners remain. + +Core acceptance after installation: 114/114 paired fresh snapshots over 60.046 +seconds; maximum age 315 ms left / 312 ms right, both fault codes 0, motor and +battery current 0 A throughout. Each controller retained one new connection +session throughout the interval. Control stayed off, state observing, no motor +session. Drive profile revision 2 and UUID assignments exactly match before +installation. Post-install VESC journal contains only its normal service start. +Browser acceptance confirmed both inventory rows ready for reading and both +telemetry columns fresh; normal/expanded view and Escape were checked. A +concurrent observation-layout save conflict was visible during UI QA; it did +not affect VESC state, and no conflicting layout was forced onto the board. +The standard fleet installer catalog now publishes 0.8.49-8. + +Private evidence: outputs/vesc-observer-20261017/lifecycle-* and +apps/node-agent/build/qualified-vesc-lifecycle-20261017. Final source is pinned +qualified; both owned remote build scratch directories were cleaned only after +terminal jobs and verified evidence transfer. The retention tool retired one +known superseded completed input, preserving qualified and rollback artifacts. + + +### 2026-10-17 — VESC modal and upgrade contract candidate + +Owner expanded the requested surface to full Tool parity, including universal +tools and firmware work, and requested a maintainable upstream update path. +This candidate implements the modal/read/engine-contract foundation; it is not +full Tool parity. Firmware/configuration writes and motor commands are not part +of live acceptance. Fresh-OS testing remains deferred by the owner. + +Candidate Node 0.8.49-9 / VESC 0.8.0 adds canonical FeatureSettingsWindow, native +configuration schema browsing/XML export, bounded hw_status/faults diagnostics, +PPM/CAN inspection, and preserves existing backup/calibration/control features. +The equipment view remains mounted below the modal. Native snapshots are +bounded separately from durable configuration backups and write receipts. + +The single engine profile pins upstream Tool 7.00 / commit +01d5f10901116c311e3fb84d5a1541f663d3ce20. Generated native contract metadata is +verified during qualification, packaging, installer acceptance and USB-owner +startup. Firmware admission remains stable 5.02; an upstream version update +does not change it or flash a controller. Upgrade procedure: node/27_VESC_ENGINE_UPGRADES.md. + +Native qualification artifact d9a3642cca9e3b22e4367fe1 completed all 14 jobs +(expected negative checks exited 1), with original upstream objects unchanged. +Both saved controller configurations decode/serialize byte-exactly. XML is +equivalent by the upstream comparator, but not bit-identical after float text +conversion. Each schema contains 162 motor and 149 application entries, +including non-transmittable schema values. This is not a claim that all entries +were read from physical hardware. No USB or OS/runtime changes occurred during +this bounded unprivileged build. + +Native engine SHA-256: +6c4f579e53a627bb636f3da3613064589abb5177ae3caad89c9b1c25338fb3d6. +Bundle SHA-256: +d176dd3bc50b3dde5aed7d4302d352c3d61a80dfd2183e97cbb8caf14249fef3. +Private evidence and preserved rollback bundle: outputs/vesc-tool-modal-20261017. +Node package qualification, installation and live UI acceptance pending. + + +The first installed candidate 0.8.49-9 passed all 19 Linux jobs and the owner +installer, preserving X4 0.1.3-15. Live Core reading found a terminal-protocol +compatibility issue before release publication: configuration succeeded, but +`hw_status` timed out. FW 5.02 `commands_printf` sends through the last blocking +command reply callback; `COMM_TERMINAL_CMD_SYNC` does not establish it. The +upstream Terminal page uses `sendTerminalCmd`, which does. Candidate 0.8.49-10 / +VESC 0.8.1 aligns the adapter with that path, retaining bounded allowlisted reads. +It also preserves bounded driver failure details in Node receipts passed to +Core instead of discarding them behind a generic error. No motor/configuration +writes occurred. Candidate 0.8.49-9 was not published as an accepted installer. +Final corrected qualification and hardware acceptance remain pending. + + +Live acceptance of 0.8.49-10 confirmed native configuration and the corrected +terminal path, then exposed a separate existing admission race: observer polling +briefly owns `operation_lock`, while operator reads attempted it nonblocking. +The read could therefore fail immediately despite healthy controllers. The +0.8.49-11 / VESC 0.8.2 candidate bounds read-only admission to at most 0.5 s and +remaining deadline budget; powered command admission remains immediate. No +retry workers or future motor start are introduced. Two synthetic contention +checks cover release then exactly-once read and bounded refusal without queued +work; the 194-test VESC suite passed. The native bundle is unchanged from the +corrected terminal release. 0.8.49-10 is not published as an accepted installer. + + +### 2026-10-17 — Accepted modal/read foundation, Node 0.8.49-11 / VESC 0.8.2 + +The corrected release passed all 19 Linux qualification jobs and the standard +versioned owner installer. Source c4ad0711efe9ce26a26c1faf, SHA-256 +11efbb15b7d0672dc982196d2a4de71cce7c7f0d66d21be81e9de5685d8c7c2f; +Node package SHA-256 +845d72a44c64eaa0f12f614ceb372a6b9980440980bee62016c192684ffa5b5a. +Owner release e6f525d9b6b4e3789b5a7d7a, installer SHA-256 +b62aa6c64c094d60388fcd5d1738e94a157ff92243640f0df305d3cccab858c6. +Installer session f1cd52772aaf4e16a5c93f771e044ed9 completed +18:38:12–18:38:31 UTC. The plan upgraded only Node, added/removed no packages, +and preserved X4 0.1.3-15. Native bundle SHA-256 +b76bdace1eb7197f3b80212ca9fd0515fa5fc5b491232f740315c051ea09e246; +installed engine SHA-256 +59173735f48279c64f814b8e02d8da79666672d7c49430f932dee064028586f4. +The corrected native qualification completed all 14 jobs. + +Two original-order passes through Core completed 20/20 read actions: +configuration, diagnostics, PPM, CAN, telemetry for both controllers. Concurrent +observation retained both USB sessions for 153/153 samples over 80 seconds. +Explicit CAN discovery occupied the shared native owner for up to 4.37 seconds; +ordinary polling resumed afterward. This is a bounded observation pause during +CAN discovery, not a claim of uninterrupted sub-second data during that action. +Both motor/application configuration packet hashes are unchanged from the +pre-install read evidence. Both controllers report FW 5.02, HW 75_300_R2, +distinct MCU UUIDs, USB configuration events 1 and USB write timeouts 0, and no +registered faults. HW_NAME and MCU UUID do not establish the commercial brand +or exact PCB revision. No CAN peers were discovered; physical CAN connectivity +is not qualified by a successful empty scan. + +The separate 60.094-second ordinary telemetry check accepted 115/115 paired +snapshots. Maximum age was 381 ms left / 376 ms right, current and faults stayed +zero, control stayed off, and both USB sessions and UUID assignments remained +stable. Final read-only service inspection found both services active, +NRestarts=0, the same two native owner PIDs, matching engine hash and no VESC +error journal entries after installation. No motor start, arm, calibration, +configuration write or firmware upload was performed. + +Core UI acceptance covered the canonical modal, all ten sections, native +parameter groups/subgroups/search/descriptions, XML download, diagnostic text, +CAN/PPM reads, Escape and retained inventory context. Core architecture checks, +typecheck, 1161 frontend tests and production build passed; VESC Python suite +194, focused Go receipt/cache checks and 66 Core backend tests passed. Direct +Node visual inspection was blocked by the browser client for the temporary +SSH-forward URL; its shared UI build/tests and installer HTTP-ready check passed. +The temporary tab and tunnel were closed. Canonical Core remains on port 8000. + +The fleet installer catalog now publishes 0.8.49-11. Private evidence is under +outputs/vesc-tool-modal-20261017 (final-read-round1/2.json, +concurrent-observation.json, final-telemetry-60s.json and install-admission-report.json). +The source input is pinned qualified. Full Tool parity is still outstanding: +typed configuration editing/import/restore, firmware/bootloader upload, +BMS/IMU/PAS/custom-device and advanced developer/data tools. Automatic rollback, +physical unplug/port-swap testing, new firmware support and pristine Ubuntu +acceptance are not claimed. The executable upstream pin/contract and upgrade +procedure are delivered; future releases require qualification before admission. + + +Release closeout: fleet metadata was read back as Node 0.8.49-11 with the exact +installer hash above. The accepted result was recorded in MISSIONCOR-85 without +closing unrelated hardware checks. Final Core listener is PID 3338 on 8000; +8765 and the temporary 18780 forward are absent. Only the two durable operator +containers remain. Artifact-owned remote cleanup removed final build scratch +c4ad0711efe9ce26a26c1faf after verified result transfer. Local retention receipt +0176dc54353842889339af4e5c0138b6 removed three superseded completed input bundles +(538737aa4a1c3bb1ebee10b0, 5fe319a91e18192bf855b193, +e45e542cf193ddea111d2d2b), preserving qualified and rollback sources, all result +evidence, current runtime and owner installers. + +## 2026-10-17 — transactional parameter editor candidate + +Node 0.8.49-12 / VESC 0.9.0 is being qualified through the standard owner +installer. Native adapter candidate 3cdd1abbc434d7560b72d559 completed 38 +offline qualification jobs against both retained firmware 5.02 archives. +Typed edits, exact backup restore, exported XML import and malformed-input +rejection use upstream ConfigParams serialization. No physical controller +write or motor operation is part of this acceptance. Runtime bundle SHA-256 +7db4153ef2e2ff0c9f6ef4be7cc131e3e4602186d750649cb4a5b16351fe2618. + +A RAM-only five-minute preview is bound to UUID, USB session and both current +config hashes. Apply requires explicit stopped/raised drive and isolated-input +confirmation; it durably archives the original before one write, verifies +readback and saves the result. A lost ACK/partial write leaves a persistent +interlock. Reconciliation reads only; a new recovery preview is required to +restore a retained backup. No automatic write retry or rollback is introduced. + +All VESC explanatory paragraphs use the canonical SettingsCard-description +font tokens. Core browser computed style matches the reference: Inter 12px, +400 weight, muted rgba(247,248,244,.48), 16.8px line height. +Core typecheck, architecture and 1162 frontend tests/build passed. Board +installation and end-to-end acceptance are pending below. + +Node0.8.49-12 was installed through owner release b256e8d7d8f64ef7e9d2b5e9; +installer session5707e7f8cb6744c482de470f7dbf7f60 completed19:20:45–19:21:04UTC. +Core accepted14/14 read/preview operations across both controllers with exact +configuration hashes unchanged. Browser testing found restore comparisons +below the long history list. UI follow-up Node0.8.49-13 scrolls the completed +preview/result into view; native/runtime semantics remain VESC0.9.0. + +### Final editor/UI release acceptance + +Node0.8.49-13 / VESC0.9.0 installed and published. Source9483c5cee5c9aa8a2f121d5b +(delta over retained67f69634b63a274368fa13e2), SHA-256 +eb69d864cafa8a222f627587e7ee64a6b827359fc4c4e9eaf58dcd94804eacda. +All19 Ubuntu qualification jobs passed; result SHA-256 +2000b30923707cc938e0906007b4f9c4721dff0d0e7805fa32acc1bef872bd8e. +Owner installer a4ed3e439f7a473f9caff89d, SHA-256 +4f091a3867c2a948dc6654ef7c5356e26eb231a06f43a5711903f398287c3d82. +Package SHA-256 f4f0e2320e56d5408a3a93a14b183515f07ced8d267fddfcd32a42ab50cc555e. +Installer session99e3aa2032a14f0cbcfa0cc63892004e completed +19:36:23–19:36:42UTC; only Node upgraded, no packages added/removed, X4 +0.1.3-15 preserved. The exact installed engine hash remains +4d45d1681e97fd3654d455ea4d6a448b4f6fc07121a3c8659ee16edaa73fa658. + +Core read/preview acceptance passed14/14 on both controllers, including typed +motor changes, unchanged application values, native XML and retained-backup +previews. Motor/application packet hashes remained exact. Browser acceptance +covered the numeric editor, comparison, disabled write without confirmation, +cancel, restore comparison, Escape and placement of the completed comparison +above the history list. All explanatory text matches the canonical description +style; 1162 frontend tests, typecheck and production build passed. + +The final60-second observation captured115/115 fresh paired snapshots, maximum +age310ms left/303ms right, zero motor/battery current, no faults, stable UUID +assignments and USB sessions, control off. An EXTRA strict abs(duty)<0.001 +criterion rejected11 frames: duty reached0.002 left/0.001 right while rejected +frames reported0ERPM. This was not a communication failure. Original failed +strict-gate reports are retained; separate assessment verifies freshness from +all accepted and rejected snapshots. The source of the idle duty indication +is not established. No motor command, config write or firmware upload was +performed; physical config-write, USB-swap and pristine-OS qualification remain +explicitly unclaimed. + +Both services are active with NRestarts0 and exactly two native USB owners. +Core14073 remains on8000, with no8765 backend and only the two durable operator +containers. Source holds were closed qualified; retention receipt +574b0cf54eda4cf1b8803fd65859dff1 removed nothing and preserved qualified inputs +and dependencies. Both own Node build staging directories were cleaned by +their artifact --clean after result verification. Firmware/bootloader and +universal/developer Tool surfaces remain outstanding, as documented in27. + + +## 2026-10-17 — firmware transaction and universal read tools + +VESC0.10.0 retains the pinned original Tool7.00 engine and adds raw-BIN +firmware/bootloader staging, single-use upload intent, durable backup/interlock, +progress/cancel and read-only re-identification. Physical upload is explicitly +unqualified in this session; no motor command or controller configuration write +was used. Original Commands supplies ADC/Nunchuk/IMU/BMS snapshots and an +allowlisted diagnostic terminal. BMS/IMU zero responses are not evidence of +installed peripherals. Upgrade and remaining-parity bounds are in document27. + +Native input1857915822d4425370414b57 completed52 offline jobs with original +objects unchanged. Runtime bundle SHA-256 +e231e47b1c14abe8e9160657f2716159e178d60e6ce7ce18e824f925889893c8; +engine SHA-256 +92e840cef1c2ac337e278b8aa0459d7665b69099045a739a69275a6d7680fb26. +The runtime supports stable5.02 only. The installer carries the native payload +and dependency closure; clean-Ubuntu acceptance remains deferred. + +Node0.8.49-15 sourcee3d0c71f7673b5f261d8f50d passed19 Ubuntu jobs, +including215 VESC runtime tests. Result SHA-256 +bfbf4b88b3778e4a337f7601e424a65ab897338d4178c1ee18184947d64056c5. +Ownerb10e0b58ffc0624d08b62770, SHA-256 +0bc1b2043c5c43e68a1758045dade723fb70b725bd7d4bc9aa3984121bcd10a8, +installed in session3a707b4676e8458f8db49d2843390ef1 at20:35:09–20:35:28UTC. +Only Node13→15 changed; no package added/removed, existing X4.1.3-15 preserved. +Native engine readback matched, both services active with NRestarts0 and two +native device owners. Core restarted through its canonical LaunchAgent. + +Core acceptance passed28/28 operations on both controllers: configuration, +ADC/Nunchuk/IMU/BMS, diagnostic memory, firmware status, synthetic1024-byte BIN +begin/chunk/seal/discard, unchanged configuration hashes and telemetry. +The test image was never applied. A separate60.508s observation accepted116/116 +paired snapshots, maximum age334/366ms, zero current/faults and stable sessions. +Idle duty reached0.001; duty is recorded separately from freshness and no +product motor/write admission threshold was changed. + +Final UI QA confirmed the canonical modal, read tools, hw_status response, +BIN preparation with disabled apply, explicit discard, corrected BMS labels, +missing-value text and Escape. Explanations use the same canonical Inter12px, +400 weight, muted48% and16.8px line-height as the reference description. +Architecture/typecheck,1162 frontend tests and Core production build passed. +The observation center showed current telemetry for both VESC; its separate +layout-save revision conflict was retained as evidence and not overwritten. + +Node0.8.49-14 was qualified but never installed; its result was SHA-verified +before artifact-owned remote cleanup and its hold closed intermediate. +Node15 source is pinned qualified; its remote build staging was cleaned only +after verified transfer. Retention receipt4db5424840734a2cb48968a13984b6ba +removed exactly two superseded completed inputs, preserving qualified releases, +rollback candidates, transitive bases and all result evidence. +Final UI-polish Node0.8.49-16 qualification/install follows below. + + +### Final firmware/tools release acceptance + +Node0.8.49-16 / VESC0.10.0 installed and published. Source +f41850f913cbf602673fa54a, SHA-256 +b7f363d45930c7dae9e5928c60ac448824b1524cae01306385ec2bf76ff9793f, +retains the same native/runtime semantics as15; the UI adds explicit staged-file +discard, translated BMS totals and missing-value descriptions. Its19 Ubuntu +jobs passed; result SHA-256 +16a46f565806fc5fc4224793d7f43761666f526b4ce92feaa30847a3c7002ea5. +Owner installerabe41fc22f807353a82b0bc2, SHA-256 +fe9789540dc865981d712cf0d63615a43a2eede1a67aabb0864bb00de21bab13; +package SHA-256 +7f8a7567d100bccc2c5543b5d3be964f0eae760e06510f381e48852c11728079. +Installer session09119f75e3474336baa5ca6993faf199 completed +20:52:17–20:52:36UTC, only Node15→16, existing X4.1.3-15 preserved. + +Final Core acceptance passed6/6 read actions. Both configuration packet hashes +match the earlier28-operation baseline, firmware status is idle and no fault +was reported. Separate60.361s observation accepted116/116 paired snapshots: +maximum age306ms left/302ms right, zero motor/battery currents and fault codes, +stable sessions and unchanged drive assignment. Duty reached0.001 and remains +separate from the freshness predicate. Native engine readback matches the hash +above; Node/VESC services are active with NRestarts0, exactly two native owners, +and no warning-priority VESC journal entries after installation. + +The Core installer catalog was read back as0.8.49-16 with the exact owner hash. +Canonical Core PID23319 remains on8000; no8765 backend; only the two durable +operator containers remain. Final source hold closed qualified, own remote +staging removed through the artifact after SHA-verified result transfer. +Retention receiptfb757df929064970abc6f4869dcdd018 removed nothing. +Private evidence is in outputs/vesc-firmware-tools-20261017 in the canonical +checkout and corresponding task outputs. Full Tool parity, physical writes, +USB-port swapping and pristine Ubuntu qualification remain explicitly open. + + +## Live telemetry graphs and CSV — 2026-10-18 + +Node0.8.49-18 / VESC0.11.0 installed and published. The pinned original +Tool7.00 engine remains unchanged, SHA-256 +92e840cef1c2ac337e278b8aa0459d7665b69099045a739a69275a6d7680fb26. +The shared modal adds bounded live graphs, statistics and explicit CSV export. +The read-only Node observer endpoint renews watch interest without acquiring a +motor-control lease; Core reads its existing rover projection. + +Source b3d47391df4749f34cc6e7ec, SHA-256 +e729b048f4541127797905227ed94ae42903e13008732b1da6bbca490f516f19, +passed19 Linux jobs including223 VESC tests. Result SHA-256 +2eeb477cf75e2f6b0802b32dd55643b60adeb4f2831b5ad9597d461d6a461662. +Package SHA-256 +090d9fdbf9a5d6197d5ada08149f4649d377f866b9460031eca00baed2705aea. +Owner a24b9fa34097b3adaf6a9a9c, SHA-256 +e311fa863a3fa7d21a7465b9107ae1b62f026b5cf8486078fe03336186291459, +installed in session47201df6260243ada1543c9d91fbffa2 at07:02:12–07:02:31UTC. +The plan changed only Node17→18, with no packages added/removed; X4.1.3-15 +was preserved. Core catalog readback matches the exact18 installer hash. + +Final Core acceptance passed6/6 read operations, with configuration packet +hashes unchanged and firmware status idle. A separate60.245s observation +accepted114/114 paired snapshots, all114 source timestamps unique per device, +maximum age267ms left/295ms right, zero motor/battery currents and fault codes, +stable USB sessions and drive assignments. Idle duty reached0.001 separately. +Node/VESC services are active with NRestarts0 and exactly two native USB owners; +there are no warning-priority VESC journal entries in the acceptance interval. + +UI acceptance confirms both real-controller plots, canonical visible RGB stroke, +440px expanded rendering, pause/resume with a broken line, historical-value +label while paused, CSV download and Escape. Actual CSV contains110 unique +measurements plus one gap, complete identity/source clocks, zero ERPM/current; +SHA-256 d9586889be382a6a0b497c90f1e6756fef579f4174c8985eace7994cb2e7e40c. +Descriptions match Inter12px/400/muted48%/16.8px. Architecture4 checks, typecheck, +1172 frontend tests and Core production build passed. + +Provenance: preliminary input1ab37114a18af7064ab75ca7 was qualified but never +installed and closed intermediate. Inputcdc7e9e6d53a18c9e8cf87aa installed Node17 +through owner5f8fce1c72b59002b6864471, session1d3d8bffdb58439c8dc4e00d4b56001d. +Node17 data/CSV acceptance passed, but live UI QA exposed an invisible stroke +from an absent CSS variable; Node18 fixes the canonical RGB token. Node17 was +not published. Failed UI17 evidence and all qualified provenance are retained. +All three owned remote staging directories were cleaned through their artifacts +after SHA-verified result transfer; source holds are closed. Final retention +removed zero inputs. Core23319 remains on8000, no8765, two durable containers. + +Evidence: outputs/vesc-trends-20261018 in the canonical checkout and chat outputs. +This increment does not complete upstream Tool parity. No motor commands, real +configuration writes, firmware upload, physical port swap or pristine Ubuntu +qualification were performed. Remaining functionality is tracked in document27. + + +## Extended firmware and addressed BMS — 2026-10-18 + +Node0.8.49-19 / VESC0.12.0 installed and published through the standard owner +installer. Original Tool7.00 remains pinned to01d5f10901116c311e3fb84d5a1541f663d3ce20. +The new adapter/native engine SHA-256 is +bd59b60f2abd687c5a03569a5b7a9d98e3f03c983677b4db726b6c6a883d9032; +native bundle SHA-256 b181cf09964ac6a6df8d76e164cd08ea7246b1ee6c51aace81f0808eda7c509b. +Native qualification passed112 jobs/39 checks, including original BMS CAN packet +serialization on addresses0/253, identity guards and route restoration. + +Source50f0543abdcb80a39727bea5, SHA-256 +c65657a0ff0f9a84f0f1eeb4094cfad4895f8532192de6ef23ab391bd7bab24f, +passed19 Linux jobs including249 VESC tests. Result SHA-256 +018f6285351b0fc494f6b959ad7bff270fe194268b805fe333857f1b45f18295. +Node package SHA-256 e6eea898d5af5824563daa65f260d87f52b90a9bf68d0f433a0758cc73516201. +Ownerbcda6616e335273a33c317d8 SHA-256 +757e183917bd5effe81652f086532e6ffcaebb4593d63092c05b0c2d839cd1ad, +installed in session45b8194519864d849a2a7142d3e599d2,08:05:34–08:05:54UTC. +The fresh plan changed only Node18→19: zero additions/removals. Existing +X4.0.1.3-15 was preserved. Core installer-catalog readback matches this hash. + +Both physical VESCs passed24 Core operations: compatible catalog listing, standard +archive preparation/discard, synthetic HEX begin/chunk/seal/discard, BMS proxy +read, CAN discovery, configuration readback, telemetry and firmware-idle status. +Installed-systemd HEX temporary-file handling works. Configuration packet hashes +remain identical to the pre-install baseline. No controller write/apply occurred. +Both CAN scans returned empty; proxy replies contain no cells. This does not +prove absence of an unpowered/misconfigured BMS, and no battery-control hardware +qualification is claimed. BMS control is explicitly sent_unconfirmed, never an +ACK fabricated by the adapter. + +A separate60.378s observation passed116/116 fresh paired snapshots,116 unique +source samples each; max age375ms left/368ms right. Motor/battery currents and +fault codes stayed zero; idle duty max0.001 is a separate measurement. USB +sessions and drive assignment stayed unchanged. Both services are active with +NRestarts0, exactly two USB native owners and no warning-priority journal entries. + +UI acceptance used the installed Node through Core8000: both controllers, archive +selection/preparation/discard, HEX upload and distinct source/normalized hashes, +extra confirmation for no-hardware-limits images, write controls disabled, proxy +empty state, CAN-empty state and Escape. Descriptions are Inter12px/400, muted48%, +line-height16.8px. Shared architecture4 checks, typecheck,1176 frontend tests and +production build passed; browser console has no errors. No physical flashing, +configuration/BMS writes, motor commands, port swap or clean-OS test was performed. + +Preliminary inputa3439de3c2072507c4ea8807 passed but was never installed; it was +closed intermediate after result transfer. Final input closed qualified. Both +owned remote Node build stages were cleaned through their source artifacts. +Retention removed one previously completed unpinned input829b3b805517690c78f7a236 +under the existing two-input policy (receiptcf66568f503549cf937e08d2da20b195); +final receipt0c7ddeac2c1f41198fb07f51de5b2dac removed nothing. Qualified predecessor +Node18 and its native bundle remain available. Core56736 stays on8000, no8765 +backend; only the two durable operator containers remain. + +Private evidence: outputs/vesc-advanced-20261018/release-proof.json in the +canonical checkout and chat outputs. Full original Tool parity remains open +as documented in27; this is accepted extended firmware/BMS scope, not full parity. + + +## VESC composition and imported signal analysis — 2026-10-18 + +Node0.8.49-20 / VESC0.12.1 installed through the standard owner installer and +published in the Core catalog. One VESC gear opens General first, including the +shared name/preparation form. Observation telemetry is a semantic horizontal +comparison with one label column plus each controller, minimum144px per column, +overflow scrolling and expired-value suppression. Independent modal scrollports, +section content reset, muted12px descriptions and aggregate equipment loading +are shared Design Guideline contracts, with registry/docs/catalog coverage. + +The analysis section imports bounded Core and original Tool RT/Log Analysis CSV, +shows up to four synchronized signals and a validated Hann-window FFT with peak, +rate and resolution. Files remain in window RAM; no inferred controller identity, +forward-filled measurements or server upload. Original source formats, limits, +FFT assumptions and remaining full parity are documented in27. + +Source7bd0370842d31d6b479b12a2 SHA-256 +22181ae3bd3e505a582155417f94801ebb5e433fd26bc71967a2aa28e0aeecf4; +result SHA-256 a64a4b8985f6cc2480972ff65e922cbdd89996db3ee02a197506d66f9fb64097. +All20 Linux jobs passed, including249 VESC tests. Node package SHA-256 +8457d4d95c82ae5d2f845f7d28728fb9780cad7f78711d04dcd5d8517b2b9763. +Ownerff890b6d7fa6777743ae1094 SHA-256 +44fed08d9f8bc06eda75ec603b23ac8a82703c69a301c4a8807ac28296748452, +installed in sessionf51c2e2f4bea4b8692f72a8fcfe931fd, +09:00:24–09:00:43UTC. Fresh plan changed only Node19→20, zero additions/removals; +X4.0.1.3-15 preserved. Catalog readback matches the accepted installer hash. +Original Tool7.00 revision and native engine remain unchanged from19. + +Core acceptance passed six read operations on both physical controllers; +configuration packet hashes unchanged, current/ERPM/fault zero and firmware idle. +The60.480s observation passed117/117 paired fresh snapshots,117 unique samples +each, maximum age331ms left/319ms right. Currents/faults stayed zero; idle duty +maximum0.001 is a separate measurement. USB sessions/assignments stable, exactly +two native USB owners, services active withNRestarts0 and no journal warnings. + +1185 frontend tests, four architecture checks, eight DG tests, typecheck and +production build passed. Actual Core8000 UI verified one gear, General first, +independent scroll, section reset, one equipment loader, minimum column widths, +actual telemetry and session replacement. Synthetic imported1024 samples at100Hz +yielded12.5Hz/amplitude1V; four traces, invalid-file recovery and expand/restore +passed. Console errors empty. No motors, physical configuration/firmware/BMS +writes, USB port swap or fresh-Ubuntu test was performed. + +Preliminary input02bce5f17ce9dabe32089555 failed a declared-version consistency +test and was not installed; corrected input passed. Its logs were retained and +hold closed failed. Final hold closed qualified; both owned remote Node stages +cleaned through their artifacts. Retention receipt2ecc8571838e4a16876f67badf33ad9e +removed one superseded unpinned input1ab37114a18af7064ab75ca7. The transferred +result archive was removed only after every extracted member matched its retained +qualified copy. Releases/rollback preserved. Core56736 remains on8000; no8765 +backend or temporary workers, only the two durable operator containers. + +Existing observation-layout revision conflict remains separate; no forced +overwrite of the user's layout. Evidence is in outputs/vesc-ui-analysis-20261018 +in the canonical checkout and chat. Full original Tool parity remains open. + +## Node0.8.49-21 / VESC0.13.0 candidate — CAN/SWD and observation + +Prepared source changes add addressed CAN firmware, declared SWD main-flash +upload with readback, operation-bound configuration download, compact dock +minimums and bounded layout-conflict reconciliation. Native artifact +9118521ad9e3e88972d3904e passed51 offline checks against unchanged Tool7.00. +Engine SHA-256 5e0b756929d05419e2b91fead2d2f972811519f23723250a7bb75226f0cde0c6. +This entry is preparation, not an installation or physical-write acceptance. +Deployment and final read-only acceptance evidence follow after qualification. + +## Accepted Node0.8.49-21 / VESC0.13.0 — 2026-10-18 + +Installed through the standard owner launcher after an APT plan with exactly one +upgrade (Node20 ->21), no additions/removals. Existing X4 0.1.3-15 preserved. +Owner276336ae1d28b14bb088dc4c SHA-256 +7f07de7e78600bc61c5ddc8386cd4cdf7bc141b71c89b5d5e782aeb4506a35bc; +package SHA-25607c1309c16ca378d4b04c1c3d5ae211bba9f3e54a858dc2e017dc5e501a06be9. +Source d6625f7ef5825324daa9bc1b passed21 Ubuntu jobs; installer is published in +Core. Native probe73a915d6a714cd6bd2ab7ce0 passed51 offline checks against unchanged +Tool7.00 pin01d5f10901116c311e3fb84d5a1541f663d3ce20. Installed engine SHA-256 +79f8bc59ec29222642cbab2ab2282ecc7d9519a2aaea7354aab4d2e3d350a8e1. +The earlier911 native candidate is superseded, not the installed native engine. + +Validation:269 VESC Python tests,1190 frontend tests,16 DG geometry/settings tests, +shared architecture/typechecks and production builds. Through Core,6 post-install +reads confirmed both UUIDs and unchanged raw configuration hashes. Another12 +operations covered two empty CAN scans, SWD BIN/HEX stage/seal/discard and idle +status. No firmware apply, SWD connection, configuration/BMS writes or motor +commands. Physical CAN/SWD flashing remains unqualified; clean Ubuntu not tested. + +All114 observations over60 seconds were fresh: maximum age290ms left,283ms right; +no session replacement, zero motor/battery current and fault0. Exactly two native +USB owners, services active with NRestarts0 and no VESC journal warnings. +Actual Core UI shows USB/CAN/SWD; empty CAN scan reports no responders. Telemetry +rows21px, columns120/88/88px, minimum pane320x280. At900x700 all telemetry cells +remain visible. Resize/remount saved revision84 without conflict; the original +user document was restored with guarded revision84->85 and verified unchanged. + +Own build holds closed; final and failed remote Node stages cleaned through +artifacts after evidence transfer. Reviewed retention removed superseded inputs +02bce5f17ce9dabe32089555 and a3439de3c2072507c4ea8807, preserving required bases, +qualified releases and rollback. Duplicate result tar removed only after all49 +members matched the retained qualified directory. Core69207 remains on8000; +no8765 backend or temporary workers; only the two durable operator containers. +Private provenance and screenshots:outputs/vesc-can-swd-20261018/release-proof.json. +Full original Tool parity remains open; current outstanding scope is recorded +in document27 and the progress checkpoint. No new Ops writes in this increment. + + +## Node0.8.49-22 / VESC0.14.0 candidate — 2026-10-18 + +Artifact-owned BMS custom configuration and Lisp/QML programming increment. +Native Tool pin remains unchanged. 71 offline native checks pass, including the +real BMS6.00 schema, native code/import/CRC round trips, malformed XML and unsafe +import rejection. 1192 Core frontend tests pass. No physical motor command, +controller firmware/configuration/BMS write or Lisp execution is part of this +acceptance. Current FW5.02 remains in place. Standard Ubuntu build, owner plan, +owner apply and Core read-only acceptance follow before marking this installed. + +## Accepted Node 0.8.49-22 / VESC 0.14.0 — 2026-10-18 + +Installed through standard owner a652967c1acf435e46a3f605 after APT plan +Node21 ->22 only; no added/removed package, X4 0.1.3-15 preserved. Owner SHA +fc2e1274b732741c79c79782e0aedfcd036e14dd35a2ce57a9c6f2d7968c2fba; +package SHA4eea34e2a0ff79496c7b49a9a0930a9c09994a18fb58df8b2404c8da6254966f. +Source2381101bc20fa7bea463e930 passed21 Ubuntu jobs. Native716c024ef6825511d9dd242e +passed71 offline checks using unchanged Tool7.00 upstream pin. Installed engine +SHA cf65e5f6aebc54dcc833f3a4e97ef01da315f73c3a3c9f42845dc3e922d1fe87. +Installer published to Core.278 VESC runtime tests,1192 frontend tests,14 final +focused UI checks, typecheck and production build passed. + +BMS custom settings and Lisp/QML code workflows described in document27 are +installed. FW6.00 developer operations are a separate explicit profile; this +does not admit its motor/config operations. Both physical controllers stay5.02. +Twelve Core read-only operations verified unchanged raw configuration hashes, +zero motor/battery current and ERPM, fault0, empty CAN scans, and explicit +Lisp/QML unsupported rejection. 115/115 freshness observations passed +over60.1s; exactly two native owners, active services, zero restarts +and no VESC warnings. No controller/config/BMS/firmware writes or Lisp execution. + +UI local project export readback and drafts across sections verified. QML code +editing/read/write is implemented; QtQuick browser rendering is not. Actual BMS +and code writes remain physically unqualified. No clean Ubuntu test, per owner. +Source hold pinned qualified; standard retention and artifact-owned remote +cleanup completed. Preliminaryd98 source completed but was never installed. +Private proof:outputs/vesc-bms-code-20261018/release-proof.json. Full Tool parity +remains open; remaining scope is listed there. User's separate blank3D/camera +report is the next investigation, not explained by this acceptance. + +## Accepted Node 0.8.49-23 / X4 0.1.3-16 — 2026-10-18 + +Node23 packages the qualified X4.16 profile and shared preview recovery. Standard +owner 85485e3de4113a94b9a5c8fe (SHA +d6bcec854959f819e4d2774c74e859c628cfbd2b128a71efb28d3699e735ddd5) +installed after an APT plan changing Node22 to23 only, with no added/removed +packages. X4.16 was preserved as current. Core installer catalogue publishes23. +Source 9cf68d047356306f83febb83 passed all21 Ubuntu jobs. VESC remains0.14.0, +with the unchanged qualified Tool7.00 engine and its71 native checks. + +Twelve Core read-only operations confirmed unchanged raw configuration hashes +on both5.02 controllers, zero motor/battery current and ERPM, fault0, explicit +unsupported Lisp/QML rejection and empty CAN scans. All115 freshness observations +passed over60.3 seconds; maximum age320/311ms. Exactly two USB owners, active +Node/VESC services, zero restarts and no VESC warnings. No motor, controller +configuration, firmware or Lisp execution commands. No clean-OS acceptance. +Camera recovery and historical3D investigation are detailed in document07 and +private outputs/observation-recovery-20261018/release-proof.json. Full VESC Tool +parity remains open as recorded in the preceding BMS/code increment. + +## Accepted Node 0.8.49-24 / VESC 0.15.0 — 2026-10-18 + +The standard owner release a1a6848eedf816376c9bee36 installed Node24 after +an APT plan upgrading Node23 only, with no added/removed packages. X4.16 is +preserved. Installer SHA 01a24580385ebae864fd6fc732f4cd8ed976de5d8215063f9e07c1763012a342 is published in Core. +Source a899b297221634a6c095bc9d passed all21 Ubuntu jobs. The unchanged +Tool7.00 upstream pin now carries the bounded package adapter;122 offline native +checks,294 runtime tests and1195 frontend tests passed, plus typecheck/build. + +The shared Extensions section delivers the41-package pinned catalogue, explicit +author refresh, RCC/vescpkg imports, application/library browsing, documentation, +compatibility and download. Package replacement/recovery and library resolution +are detailed in document28. Application installation never starts Lisp. + +30 Core operations verified both physical5.02 controllers, unchanged +raw configuration hashes, catalogue and compatibility, downloaded hashes, +deduplicated imports and explicit6.00 code-write rejection. All117 +freshness samples passed over60.0s. Exactly two native USB owners, +active services, zero restarts and no VESC warnings were verified. +Browser acceptance includes upstream refresh, filtering, package details and +duplicate import. No motor/configuration/BMS/firmware/code writes or Lisp +execution. No new Ubuntu test. Physical package writes remain unqualified. + +Own build holds closed, final source pinned, artifact-owned remote stages cleaned +and duplicate result archive removed only after complete member equality. Full +Tool parity and QML rendering remain open. Evidence: +outputs/vesc-packages-20261018/release-proof.json. + +## Accepted Node 0.8.49-27 / VESC 0.16.2 — 2026-10-18 + +Owner d1b7298a11de196a3b572e0c installed and published, SHA +a30fbaea81f31b89e52c3bdd3e2baa619813d9662b567dd8c657d4951408143c. APT upgraded Node26 only, no added/removed +packages; X4.16 preserved. Source 2d6a7a948fff043eb27a7f38 completed +21 Ubuntu jobs. Native 129, runtime 303, frontend 1195 and Core queue 3 checks +passed; typecheck/build passed. Native bridge used the actual driver-generated +request against the compiled isolated Qt renderer. Node25's first live preview +failed on missing archive encoding; fixed in26; viewport corrected in27 with a regression assertion. + +Shared QML editor and extension detail now provide real Qt Quick snapshot +rendering, bounded and disconnected from hardware. This is not interactive QML. +Connection transition records preserve old session, attachment and last sample; +failed startup retains stderr/exit status before retry. See document29. + +24 read-only Core operations verified both FW5.02 controllers, +custom and original LogUI rendering, unchanged configuration hashes, and idle +values. All 117 freshness observations passed over +60.1s. Exactly two native USB owners, no remaining +preview workers, zero service restarts, 1GiB service limit and restored-sample +journal events were checked. Browser editor/catalogue preview accepted. + +Historic September23 calibrated motor/app packets match all four current +packets. September24 left Hall four-state failure and right six-state success +are verified historical evidence; current both-side cogging remains unexplained. +No motor start, firmware/configuration writes, Lisp execution or fresh Ubuntu +acceptance. Full Tool parity and high-frequency incident capture remain open. +Own source holds closed and artifact-owned staging cleaned; retained evidence: +outputs/vesc-qml-diagnostics-20261018/release-proof.json. + +## 2026-10-18 — Node28: Sample Data and interactive QML + +Node0.8.49-28 / VESC0.17.0 / Tool7.00, unchanged X4.16. Owner +ca0a7756ef958ac2c478b54b installed and published; SHA cf34844b640b0c7733a1319d42a1dc7d0a4ceae32e95d1cafa53378a7154a7c0. +Source 175e00ba5e8ac1f1ad561f78 completed 21 Ubuntu build jobs. The first +input was rejected before installation because Node's admitted driver version +was stale; the version declaration was corrected and qualification rerun. +APT upgraded Node27 only, with no added/removed packages. Owner27 is retained +for rollback. Runtime hashes match the qualified native bundle. + +Sample Data uses the original Commands serializer and existing USB owner, with +FW5.02 decoding, bounded asynchronous capture, plots/FFT/CSV/JSON. Opening the +view never arms capture. Qt Quick now preserves state and accepts bounded input +in a disconnected process. Default QML opening reads no controller data. An +admitted hardware broker remains required for full QML parity. See document30. + +138 native checks, 340 Python checks, 12 focused frontend tests and production +typecheck/build passed. Seven standalone QML operations passed through Core; +browser clicks/text/state/close were verified. New Core QML receipt payloads +were absent from fleet database/history. Two USB owners, no remaining preview +process, active services and the single canonical Core8000 were checked. + +No motor commands, capture/logging, calibration, controller configuration write, +firmware flash, Lisp execution or fresh-Ubuntu acceptance. No claim about the +physical cause of cogging or USB loss. Full Tool parity remains open. Diagnostic +module priorities are retained in outputs/vesc-samples-20261018/module-audit.txt. +Own source hold closed qualified; owned Node build stage cleaned, retention plan +applied and exact duplicate package files retired with verified retained copies. +Evidence: outputs/vesc-samples-20261018/release-proof.json. + +## 2026-10-18 — Node29: saved Sample Data analysis + +Node0.8.49-29 / VESC0.17.1, unchanged Tool7.00 native bundle and X4.16. +Source 3627731c6690e09ad5316a89; owner 64c46b7473873b1cdbe6956a; +owner SHA256 edce280ebe420a6f4463114e4796275e31aad2e4db5ba273fac302e7e7d7e094. Standard owner installer and catalog publication +completed. Node28 retained for rollback. No new OS dependency or raw board fix. + +Sample Data now imports bounded JSON passports/original CSV, compares two +independent sources, applies original FIR/mean semantics with explicit missing +edges, and supplies cursors/deltas/FFT. Responsive plots keep readable axes. +See document31. 1208 frontend tests, 310 plugin Python tests, 21 Ubuntu jobs, +production build and synthetic UI acceptance passed. Both controllers report +0.17.1 through Core; services and original native hashes verified. + +No motor, capture/logging, calibration, configuration write, flash, Lisp or +clean-Ubuntu test. Full Tool parity and physical fault diagnosis remain open. +A first candidate passed qualification but was superseded before installation +for responsive-axis correction; its reports are retained, stage cleaned and +hold closed intermediate. Final input closed qualified. Exact immutable +installer duplicates share storage while every release/rollback path remains. +Evidence: outputs/vesc-analysis-20261018/release-proof.json. + +## 2026-10-18 — Node30: typed QML read broker + +Node0.8.49-30 / VESC0.18.0, Tool7.00 and X4.16. Source 4a694549a9f16b29f871ccab; +owner 25d9da4a10f703f82be666ae, SHA256 10f47fc1e877340f067e4867022e8bf833e59d8c930e98fbb56d6b8ee2af3bb6. +Native engine ea2e15578b7c338adc5eba6432da7beb48cd58773fe30e13e952cea7f514c0a8. Standard qualification/owner install/catalogue publication completed; Node29 retained. + +See document32 and outputs/vesc-broker-20261018/release-proof.json. 139 native, +323 Python, 1208 frontend, 21 Ubuntu jobs; both controllers answered through +Core/QML. Exactly two native owners; no remaining QML worker. No motors, +capture/logging, configuration write, flashing, Lisp or fresh-OS test. +Full parity and physical fault diagnosis remain open. Intermediate inputs +were not installed; their reports retained and owned Node stage cleaned. + +## 2026-10-18 — Node31: manual diagnostic report review + +Node0.8.49-31, VESC0.18.0 native unchanged from Node30. Source 71b2ee6e8983511ff798a8f6; +owner 09f5ffe2c4c6dcdedd51c99a, SHA256 a8df43d2f1394f22d5f6f27cc5d982a06f4fa73aa8b4b018e2d4acae90e33334. +Standard qualification, owner installer and catalogue publication completed. +Core and Node reuse one diagnostic UI. See document33 and +outputs/vesc-diagnostic-review-20261018/release-proof.json. +1217 frontend tests, final targeted checks, production build, 21 Ubuntu jobs; +manual report comparison and section cleanup verified in Core. +Both controllers online; two native owners, no QML workers. Node30 rollback retained. +No motors, new capture/logging, configuration write, flashing or fresh-OS test. +Full parity and physical fault attribution remain open. + +## 2026-10-18 — Node32: parameter spacing and offline Rotor/Hall review + +Node0.8.49-32, VESC0.18.0 native unchanged. Source 5eb50b498b160d9b97f2bb08; +owner cccfb9c3c2801275a9c2f32c, SHA256 6399cba06efc580be23e3fcca8434baf01dae7155dad4d55117dd6f476e75fa3. +Standard qualification, owner install and catalogue publication completed. +Shared Core/Node parameter layout and saved Sample Data observations delivered. +See document34 and outputs/vesc-hall-review-20261018/release-proof.json. +1229 frontend tests, production build, 21 Ubuntu jobs, synthetic A/B event +review and UI lifecycle passed. Both controllers online, two native USB owners, +no QML workers. Node31 rollback retained. No motors, new capture/logging, +configuration writes, flashing or fresh-OS test. Live Rotor Position admission, +full parity and physical fault attribution remain open. + + +## 2026-10-21 — Node35: shared USB/CAN control transport + +Node0.8.49-35 / VESC0.19.1 / USB-CAN0.2.0 installed through owner release +1d48bc1da05832fd467851d5, SHA256 +43663de64b620c1c98d0fa6459645f8af7c187ec4cf620f4af494c02a572cf27. +Source11cac218df01036bc1705257; installation39c0471878db4a6db0a53d71be7671b7 +completed2026-10-21T15:05:21Z, every step exit0; only Node upgraded. + +The board transport profile is shared by Observation Center and the embedded +VESC Tool. It preserves UUID identity across USB ports, merges USB/CAN endpoints, +and retains offline assignments for settings. Selected connection loss ends the +control session without fallback. Controller configuration is not rewritten by +transport selection. A separately launched upstream desktop Tool keeps its own +connection preferences. See36_VESC_CONTROL_TRANSPORT.md. + +The versioned installer owns the native bridge, SDK owner, Unix API and AF_INET +inside the existing PrivateNetwork=yes namespace. The owner explicitly approved +this isolated internal TCP. Both services active, no restart loops, preparation +versions confirmed. Ubuntu24.04amd64 is the declared profile; clean OS and other +platform qualification were not performed. + +Native140checks, finalNode24qualificationjobs and357VESC unittest cases passed. +Core1289tests passed with one pre-existing build-profile exclusion; actual Core +UI verified on8000. Both assigned controllers and the adapter reach Core; VESCs +currently have no verified link, so the UI shows unavailable and prevents saving +an unverified route. The profile was not changed. Node34's direct-USB-only filter +was found during live acceptance and corrected before catalogue publication. + +No assistant-issued motion, calibration, firmware write, fresh capture or +logging experiment. Physical CAN control remains unqualified. Installer catalogue +readback matches35 and its exact hash. Prior published33 remains available as +rollback. Private receipts:outputs/vesc-control-transport-20261021/release-proof.json. + + +## 2026-10-21 — CAN poll contention and original failure propagation + +Node0.8.49-36/VESC0.19.2 first preserved the underlying bridge failure. The +existing journal then confirmed “poll: adapter busy” after identification, +without initiating a capture or motor command. Node0.8.49-37 keeps active-bridge +status free of vendor USB enumeration, with ownership context on contention. +USB-CAN profile0.2.1 and VESC0.19.2 completed preparation through the normal +installer. No permissions, watchdog deadlines, controller configuration or +selected transport were changed. + +Source7605fbbd3a85fa2f22d695aa passed24 Ubuntu qualification jobs and359 VESC +unit tests;23 local USB-CAN tests passed, including active-claim USB detach. +Release4543e63e88fb7d7771fbe849, SHA256 + e8593bde32da4c4c90d7c75d9dae596a320399ac1f1a9f8df7e26684225c006e, +was installed by sessiond6359e6a8888433b987569a5422b86d0; all steps completed +at2026-10-21T16:04:39Z. Core's installer catalogue returns the same version/hash. +Runtime source hashes match the candidate; Node/VESC/USB-CAN are active with +NRestarts=0. Both direct USB controllers recovered normal zero-speed telemetry. +CAN1 identification remains in the same session for166seconds at final Core +readback, following initial retries. CAN2 remains unverified. No motion, +flashing, fresh sample capture or diagnostic recording was run. The saved +profile remains unchanged and presently selects USB. Clean OS was not tested. + +Private receipts and physical UUID/wiring evidence: +outputs/vesc-control-transport-20261021/release-proof37.json. +Completed build staging and verified duplicate archives36/37 were retired; +qualified results, input holds/pins and required rollback remain preserved. + + +## 2026-10-21 — Both CAN identities; passive-read candidate pending quiescence + +With direct VESC USB disconnected, both CAN channels returned the expected +controller UUIDs. The operator transport profile was saved through Core's +vesc.transport.configure action, revision1; side identity is UUID-based. +Individual telemetry reads succeeded, but normal live observation repeatedly +lost sessions at its 60ms read deadline. Continuous CAN telemetry is not accepted. + +Node0.8.49-38/VESC0.19.3 raises only passive CAN observation to300ms and adds +bounded request/reply counters and latency metadata to existing failure records; +no raw CAN capture, new logger, motor timeout change or transmission retry. +Sourcefaf6d71b40fe086b94d914a8 passed24 Ubuntu jobs and364 VESC tests. +Installer4fac32ee07685e429cc6afa2, SHA256 +ffd70b54c450ddbbffee6993f147a6e769dd19d8207115f72770e84f304acad0, +is qualified and staged but NOT installed: attempt5892aa77fca647c6a1eb336993b5ec8d +was refused by the old and new prerm guard because automatic CAN channels were +running. Node37 remains installed and active. No ad-hoc service stop or guard +bypass was used. Physical adapter USB detach is the pending quiescence step. +Core catalogue remains37 until runtime acceptance. No motor, flashing or capture +operation was initiated. Compact evidence:outputs/vesc-control-transport-20261021/ +release-proof38-pending.json; saved profile:can-profile-save.json. Completed +build38 staging and verified duplicate result archive were retired; qualified +contents, installer and pinned source remain retained. + + +## 2026-10-21 — Node38 installed; live CAN acceptance awaits reconnect + +After the operator disconnected only the USB-CAN adapter USB cable, sysfs/Core +inventory confirmed it absent and both assigned VESC tests inactive. The fresh +owner-installer plan changed only Node37 to38, with no new or removed packages. +The same qualified installer completed through session3332fe7341144c90be8e44873e186cef +at2026-10-21T16:43:12.882077Z. No service guard bypass or ad-hoc board patch was used. + +Installed Node0.8.49-38, VESC preparation0.19.3 and USB-CAN preparation0.2.1 are +confirmed. Seven changed/relevant runtime file hashes match the qualified source; +Node, VESC and USB-CAN services are active with NRestarts=0. Core8000 is healthy, +reports VESC0.19.3 and retains the two-controller CAN profile at revision1. +Both controllers correctly remain offline while the adapter is unplugged. + +Continuous CAN telemetry is still NOT accepted: the next step is physical +adapter USB reconnect followed by ordinary read-only live observation. Core's +installer catalogue remains37 pending that acceptance. No motor command, arm, +calibration, firmware write, raw capture or new diagnostic logging was initiated. +Receipts:outputs/vesc-control-transport-20261021/install-result38.json and +release-proof38-installed.json. The earlier blocked attempt remains recorded. + + +## 2026-10-21 — Node38 live read failed; Node39 qualified + +After adapter USB reconnect, a bounded ordinary Core live-view check returned +zero of27 evaluated snapshots with both UUIDs fresh. No movement or capture was +initiated. Existing failure metadata showed send acceptance around1–2ms and +successful replies around15–16ms, but other requests received no response even +at300ms/2000ms. Node38's passive timeout correction is insufficient. + +The delayed unplug status has a specific software cause: Node admitted the +VESC driver's cached CAN adapter list in the immediate USB event inventory. +The following inventory normally arrives15seconds later (sensor_events.go). +Node39 checks the exact current OS USB generation before admitting a CAN route; +it preserves the assigned offline UUID but clears stale availability/telemetry. +Synthetic Node tests cover stale online metadata after detach and after a new +USB generation appears, including coexistence with direct controller USB. + +USB-CAN0.2.2 uses the vendor's normal transmission only for five exact, +argument-free VESC reads. Other commands retain the preceding single-shot +policy; no application command replay or motor deadline change was introduced. +See docs/node/36_VESC_CONTROL_TRANSPORT.md for the API source and exact guard. +Physical arbitration/error loss remains a hypothesis until runtime verification. + +Node39 source2262fa3bdd9fc85e99db3259 passed24 Ubuntu qualification jobs, +including Node race tests and364 VESC tests. Local USB-CAN tests (288 cases) +and focused Ruff validation passed. Qualified owner installer: +d4a66ee7feb567e40102ac72; SHA256 +6d9b74a56ebc095d0cb1b6e54378c3d423591d55a1457495e94d0b8046bcf71a. +Its versions are Node0.8.49-39, VESC0.19.3, USB-CAN0.2.2. Installation and live +acceptance remain pending; Node38 is still installed and Core catalogue stays37. +No motor command, raw capture, diagnostic recording or firmware write occurred. +Source/qualification/installer receipts remain in +outputs/vesc-control-transport-20261021; can38-read-acceptance.json records the +failed hardware gate. Qualified result files and installer are retained; the +byte-verified duplicate result archive and completed remote build were retired. + + +## 2026-10-21 — Node39 installed; reconnect acceptance pending + +After the operator unplugged only the adapter USB cable, fresh sysfs and Core +inventory confirmed the adapter absent and both VESC tests inactive. The owner +installer plan changed only Node38 to39, with no new or removed packages. +Installer d4a66ee7feb567e40102ac72 completed through session +744b7f463c704308b4e67c1b1637a901 at 2026-10-21T17:09:02.434869Z. +No service guard bypass or ad-hoc board changes were used. + +Node 0.8.49-39, VESC preparation 0.19.3 and USB-CAN preparation 0.2.2 are +installed. Nine runtime source hashes match; Node, VESC and USB-CAN services +are active with NRestarts=0. Core8000 is healthy. Both exact CAN routes remain +unchanged at profile revision1, and both assigned VESCs are offline while the +adapter is unplugged. Private receipts: outputs/vesc-control-transport-20261021/ +install-result39.json and release-proof39-installed.json. + +The next gate is operator USB reconnect and ordinary read-only live observation. +Continuous CAN telemetry, real detach timing and physical control are not yet +accepted for this release. The Core installer catalogue remains37 pending runtime +acceptance. No motor command, arm, calibration, firmware write, raw capture or +new diagnostic recording was initiated. + + +## 2026-10-21 — Node39 CAN reads and physical hotplug accepted + +The ordinary Core live-view check at 17:12:07–17:12:38Z passed: 30 reads, +27/27 evaluated after warm-up with both expected UUIDs fresh, one session per +controller, maximum sample age 311ms, fault code0, no observed motion. +After operator USB detach, the first Core inventory with the adapter offline +also marked both VESCs offline/disconnected/unreadable with telemetry unavailable. +No stale-online inventory was observed; poll spacing was0.5s (the final observed +online-to-offline sampling interval was0.53s). The operator independently +confirmed immediate disappearance in the UI. This is an observation bound, +not a claim of zero physical latency. + +On operator reconnect, both controller sessions renewed automatically while +preserving exact UUID-to-channel routes at revision1. The second normal read +check at17:14:49–17:15:20Z also passed27/27 evaluated snapshots after warm-up; +maximum sample age305ms, fault code0 and one new stable session per UUID. +Node/VESC/USB-CAN services stayed active with NRestarts=0; Core8000 remained +healthy. Node0.8.49-39 is now published in the normal Core installer catalogue, +read back with SHA256 +6d9b74a56ebc095d0cb1b6e54378c3d423591d55a1457495e94d0b8046bcf71a. + +The accepted scope is bounded ordinary CAN reading, immediate inventory +invalidation and automatic recovery after a real USB disconnect/reconnect. +No motion command, arm, firmware write, new capture or diagnostic recording was +initiated. Motion/active command delivery, long-duration bus reliability and +clean-OS installation are not accepted by these checks. The operator reported +approximately17s UI initialization and explicitly accepted that delay; no startup +optimization is requested. Physical arbitration/error loss remains an unproved +explanation of the earlier packet failures. + +Compact evidence: outputs/vesc-control-transport-20261021/ +can39-read-acceptance.json, can39-detach-acceptance.json, +can39-reconnect-read-acceptance.json and release-proof39-installed.json. + + +## 2026-10-21 — Manual CAN preparation exposed an uncovered neighbour query + +The operator started remote-control preparation without direction input after +20:30 Moscow. The existing service journal records COMM_PING_CAN/query62 failing +at2026-10-21T17:31:37.420375Z on CAN1/ID111, with an8000ms native budget and no +reply. Before it, identity, motor/application configuration and telemetry queries +completed in approximately10–34ms. The adapter and native process were present; +the bridge had one unanswered request. Cleanup then closed this session and +ordinary discovery restored telemetry. Core was faulted and not controlling, +with zero current/ERPM and fault code0 on both controllers. Source flow places +this failure before output claiming and temporary motor-limit application. + +The native generic-read API admits six exact commands, but Node39's hardware +normal-transmission allowlist covered five: the required neighbour query62 was +still single-shot. Node40/USB-CAN0.2.3 adds only the exact argument-free62 request; +argument-bearing, forwarded, broadcast and output packets remain single-shot. +No scan check is skipped, no timeout or motion lease is extended, and there is +no application replay. The vendor manual documents single-shot loss after +arbitration/error; the physical loss mechanism on this attempt is not measured. +291 inert USB-CAN cases and focused Ruff passed. Ubuntu qualification and a +separate read-only vesc.can.read acceptance are pending. Node39's ordinary read +and hotplug results remain valid within their recorded scope; CAN remote-control +preparation and movement are still unqualified. No assistant-issued motor, +configuration-write, firmware or capture operation occurred. +Evidence: outputs/vesc-control-transport-20261021/manual-can-trial-analysis.json, +manual-can-trial-vesc-events.json and source40.json. + + +## 2026-10-21 — Node40 installed; exact CAN neighbour query and reading accepted + +The owner installer ba9ba087085cc9195127208f completed at +2026-10-21T17:56:23.543721Z through session9c57d5c5978d4c9ea2f9f12075e1202a. +The operator unplugged the adapter USB before installation; fresh sysfs and +Core checks confirmed no adapter, no online VESC and no active control. The +reviewed APT plan upgraded only Node39 to40, with no new or removed packages. +Node0.8.49-40 / VESC0.19.3 / USB-CAN0.2.3 are installed. Nine deployed runtime +hashes match; all three services are active with NRestarts=0. The exact saved +CAN routes remain at revision1. Installer SHA256: +3fe3d43984d07a75b840c94b36b7a204710b01f8ab205e2e3084b8d7e52d50be. + +After operator USB reconnect, one standard vesc.can.read operation per assigned +controller completed through Core: CAN1/ID111 in2.5935s and CAN2/ID74 in2.5853s, +at18:01:20Z and18:01:25Z. Each returned the expected MCU UUID and an empty +neighbour list, consistent with one controller per isolated adapter channel. +No arm/preparation operation was invoked by the assistant. A subsequent30-read +ordinary live check passed27/27 evaluated snapshots, with one stable session +per UUID, maximum sample age321ms, fault code0 and no observed motion. Profile +revision1 persisted. The normal Core installer catalogue now publishes Node40 +with the exact verified SHA; Core8000 and all three services remain healthy. + +This accepts the previously failing query62 in two bounded read-only operations +and ordinary telemetry recovery. It does not yet accept remote-control preparation, +motor command delivery, long-duration reliability or a clean-OS installation. +Arbitration loss remains a possible underlying packet-loss mechanism, not a +measured physical diagnosis. No assistant motor/lease/configuration-write, +firmware, raw capture or new diagnostic-logging operation was initiated. +The next gate is the operator's own control-preparation retry without direction +input; the assistant observes only existing status and service journals. + +All24 Ubuntu qualification jobs,291 inert USB-CAN cases and focused Ruff passed. +Qualified sourceade244824764ac29d7296ce8 and the installer are retained/pinned; +the55-file result archive was retired only after byte comparison, and the owned +remote build directory was cleaned with the shipped build entry point. Retention +plan/apply preserved all63 inputs and deleted none. Private evidence under +outputs/vesc-control-transport-20261021: release-proof40-installed.json, +can40-neighbour-scan-acceptance.json, can40-read-acceptance.json, +retention40-receipt.json and remote-build40-clean.json. + + +## 2026-10-21 — Human Node40 preparation reaches volatile limits, then fails + +Two operator retries without direction input failed at18:03:24.880168Z and +18:03:56.903853Z. Both reached native method limits / COMM_SET_MCCONF_TEMP48 +on CAN2/ID74; ordinary value and PPM reads immediately beforehand completed +in approximately8–17ms. The emitted request was37 bytes and no ACK arrived in +the native2s exchange. Adapter/native process stayed present; each bridge had +exactly one unanswered request. Source places this before the remote output +loop and output claim. The assistant did not issue motor/lease commands. +Existing recovery closes the failed attachment, so renewed telemetry can coexist +with an inactive/faulted control session. This does not qualify CAN driving. + +The fragmented request still used single-shot sending. Candidate Node41 changes +only the exact37-byte, six-fragment volatile limits packet plus its CRC commit: +store=false, forward=false, ack=true, divide=false; bounded finite data and +current scales in(0,1]. It uses normal hardware arbitration without application +replay or deadline extension. An unacknowledged write closes every claim on that +channel and resets it, so another reader cannot keep an uncertain queued write +alive. Only the exact ACK from the expected controller clears this state. All +motor setpoints, leases and other mutations retain their previous single-shot +policy. The misleading unconditional recovery message about neutral is replaced +with an explicit statement that restoration has not been confirmed. + +319 inert USB-CAN cases and364 VESC cases passed; focused Ruff passed. Firmware +5.02 accepts the37-byte variant and leaves optional battery-current limits +unchanged (official commands.c, COMM_SET_MCCONF_TEMP). Inert bus tests cover +arbitration loss, full-packet CRC/order, wrong ACK, late ACK, deadline interruption +and shared-channel invalidation. The physical loss mechanism is still unmeasured; +these tests do not prove real ACK delivery. Node41 Ubuntu qualification and owner +installation are in progress. The operator unplugged USB for installation. +Evidence: outputs/vesc-control-transport-20261021/manual-can40-trial-events.json, +release-proof40-installed.json, candidate41-checks.json and source41.json. +Official firmware source: https://github.com/vedderb/bldc/blob/5.02/commands.c. + + +## 2026-10-21 — Node41 installed; volatile limits delivery acceptance pending + +The owner installer 1d47f2b6154cd58f65713307 completed at +2026-10-21T18:27:42.638239+00:00 through session c24aec33362645d081fc8fbfdf700c3e. +The operator unplugged only the CAN adapter USB. Fresh OS/Core checks confirmed +no adapter, both VESC offline and no active control before installation. The +reviewed plan upgraded only mission-core-node from0.8.49-40 to0.8.49-41, +with no new or removed OS packages. Installed VESC0.19.4 and USB-CAN0.2.4 +match all nine checked runtime hashes; three services are active with +NRestarts=0. The exact CAN profile remains revision1 and Core8000 is healthy. +Installer SHA256: 3c335315d8d54349b27eefc058b544f718005a1dd593e2a66fd9404380fcf989. + +All24 Ubuntu qualification jobs passed, in addition to319 inert USB-CAN and +364 VESC checks. The source input a5107585cb5941826ba9b1b8 is retained. +This proves packaging and installation of the narrowly classified, acknowledged +volatile-limits transport described above. It does not prove delivery of its +ACK on the physical bus or successful control preparation. USB reconnection, +bounded ordinary telemetry and a human preparation retry remain separate gates. +No assistant motor/lease/configuration-write, firmware, capture or new logger +was invoked. The operator has been asked to reconnect only adapter USB while +leaving the RC and direct VESC USB disconnected and control inactive. +Private evidence: outputs/vesc-control-transport-20261021/qualification41-summary.json, +preinstall41.json, install-result41.json and release-proof41-installed.json. + +Node41 storage closeout completed: its source hold is closed and qualified-pinned; +reviewed retention apply preserved all64 inputs. The shipped build --clean +removed only its owned remote build directory. The duplicate result tar was +retired after SHA verification and byte comparison of all55 retained files. +Receipts: retention41-receipt.json, remote-build41-clean.json and +result41-duplicate-retirement.json in the same private evidence directory. + +After operator USB reconnect, ordinary Core reading on Node41 passed27/27 +evaluated snapshots after warm-up (30 reads total), maximum age296ms, +fault code0 and one stable session per controller UUID. No motion was observed +in those readings. All three services remain active with NRestarts=0. Core8000 +is healthy; its normal installer catalogue publishes the exact Node41 SHA. +The first post-idle snapshot can contain old values: Core view renews a2-second +observation demand (RoverControl.view), and continuous observation is demand-driven. +No new control preparation or volatile write was requested by the assistant. +This accepts bounded normal telemetry only; the human preparation retry is next. +Evidence: can41-read-acceptance.json and release-proof41-installed.json. + +The operator reported enabling control and also trying manual movement. At +18:40:33Z Core reported controlling=true, state=ready, no error, with both +controller connection sessions unchanged and fault_code0. Both controller +tachometer counters had increased compared with the pre-attempt view; direct +VESC USB tty devices are absent and the verified routes remain CAN1/ID111 and +CAN2/ID74. All three services remain active with NRestarts=0. The bounded VESC +service journal since18:38:36Z contains no entries, including no failure entry. +This is not a drive-command trace: no new capture or logger was started. + +State=ready is assigned only after TemporaryLimits.apply succeeds for both +motors, including the native ACK and configuration readback. The formerly +failing preparation stage therefore passed in this human session. Current +telemetry at inspection has zero ERPM/current on both devices. The user was +asked to press the normal Stop control button; session termination and original +limits restoration remain unverified until that human action. The assistant +issued no arm, motor, zero, stop, release or configuration-write command. +This bounded manual result does not establish prolonged driving reliability or +resolve the earlier low-speed motor-stall symptom. Evidence: manual-can41-trial- +current.json, manual-can41-trial-route.json, manual-can41-trial-events.json and +manual-can41-trial-acceptance.json in the same private evidence directory. + +At18:44:09Z, after the operator pressed Stop control, Core reported the same +control session as stopped, controlling=false, release_confirmed=true and +message=null. Both VESC remained in their original CAN connection sessions, +with fresh samples (<150ms), zero motor current/ERPM and fault_code0. Fleet +reports test_active=false and no device recovery error for both; all three +services remain active with NRestarts=0 and the exact CAN profile stays revision1. +Core8000 is healthy. The existing VESC journal since the trial marker remains +empty. In the installed runtime, stopping completes both identity-bound limit +restorations with configuration readback before this terminal state, and any +restoration failure sets a non-null message. Therefore the normal application +restoration passed; no independent extra configuration operation was invoked. + +This accepts one bounded human CAN preparation/movement/stop session on Node41. +It closes the earlier query62 and fragmented command48 preparation blockers +for this trial. No claim is made about prolonged reliability, the physical +origin of previous packet loss, low-speed stall resolution or clean-OS testing. +Evidence: manual-can41-stop-observation.json, manual-can41-stop-acceptance.json, +manual-can41-trial-acceptance.json and release-proof41-installed.json. + +## 2026-10-22 — Node43: CAN installer maintenance with USB connected + +Installed Node0.8.49-43, VESC0.19.5 and USB-CAN0.2.5 through owner release +`f5eb90a18c1826c309fea9e3`, installation session +`68716a7a238644dd9944d5f5fc0afa95`. The reviewed APT plan upgraded Node41 only; +no OS package was added/removed and X4.0.1.3-16 was preserved. Installer SHA256: +`04421bbac0b44e131d03bb8206842503a9694673592df4d51325cb078ad6510e`. +All24 Ubuntu qualification jobs passed. Two earlier source candidates were +rejected by version-consistency and dependency-isolation checks; their failure +reports are retained separately, and neither was installed. + +The USB-CAN adapter stayed connected throughout installation. The exact reviewed +legacy socket transition proved idle, drained VESC, verified stopped CAN channels +and allowed the ordinary package transaction. Receipt state is complete, +maintenance state observation-restored, errors empty. Three service source hashes +match the candidate; Node/VESC/CAN are active with NRestarts=0. No manual service +file, permissions, USB reset or board-only package repair was used. + +The newly installed admission-barrier-v1 path was then exercised once through the +shipped maintenance owner, without repeating APT. Both VESC and CAN returned +safe=true; observation-restored and errors=[] followed. This separately qualifies +the next-update path rather than only its legacy migration. Synthetic tests cover +active-control/operation refusal, observer drain, concurrent request rejection, +timeout recovery, marker-held restarts, pending writes/captures, service ordering, +clean-install release and standard-library-only imports. + +After both transitions, typed read-only requests through Core completed for both +controllers. Final snapshots: left48.2V, right48.0V; both0A,0ERPM,fault0. MCU +identities, CAN profile revision1 and drive layout revision2 remained identical; +connection sessions changed. Core UI also displayed a fresh right-controller +snapshot. Core8000 remains available and its installer catalogue serves43 with +the exact accepted SHA. No assistant motion, control arming, configuration write, +firmware update, Sample Data capture or new diagnostic logger was invoked. + +The candidate includes the prior Hall-view separation: stock5.02 raw H1/H2/H3 +remain explicitly unavailable; passive settings are not represented as sensor +presence. Powered measurement remains separately disclosed and gated. This +installation does not establish whether the repaired Hall contact works. + +Contract and failure boundary: [CAN maintenance](37_CAN_INSTALLER_MAINTENANCE.md). +Private evidence: `outputs/can-maintenance-20261022/` — qualification43-summary, +owner-plan43, install-receipt43, native-maintenance43-acceptance, acceptance-before, +acceptance-after-install, acceptance-after, installed43-proof and catalog43-readback. +The build hold is qualified-pinned; reviewed retention and artifact-owned remote +cleanup completed. The duplicate result archive was retired only after comparing +all retained members byte for byte. New Ubuntu installation was not exercised. + +## 2026-10-22 — Hall ownership conflict; Node44 qualified, not installed + +The owner explicitly authorized one native left Hall measurement and confirmed +that the tracks were suspended. Both controllers passed fresh neutral/identity +checks through Core. The Hall result was lost: the Python supervisor renewed +the target output lease after starting the native procedure; the native guard +rejected it with `Native procedure owns this controller`, and NativeLink retired +that process/CAN bridge. The owner reported no visible rotation. This attempt +does not establish Hall health or prove that no firmware motion command arrived. + +Fresh post-attempt Core readings show both controllers at zero current, ERPM +and duty, fault zero. Independent motor/application readback matches the previous +configuration byte-for-byte on both sides. No table was applied and no second +measurement was dispatched. The unresolved Hall marker remains protected. + +The correction renews output inhibition/releases only for non-target peers +while the native procedure owns the target. Its regression reproduced the +pre-fix conflict; Hall, standstill, motor and native-link checks pass locally. +Node0.8.49-44 / VESC0.19.6 passed all24 standard Ubuntu build/qualification jobs. +Owner release `a841fa1bd10766764e8dde27`, SHA256 +`6b5ac9123f5b0276735efda2f0d5eaf0ef84715cbb8411594acc6acd35a1e5df`, +is prepared but NOT installed. Installed predecessor remains Node43/VESC0.19.5. +Maintenance correctly refuses the unresolved Hall marker; a reviewed standard +recovery path is required before installation or another motor test. No manual +marker deletion or guard bypass was performed. + +Evidence: `outputs/hall-lease-20261022/` contains the incident journal, source +manifest, qualified package,24-job report, owner release and handoff state. +The associated task evidence retains the exact command/receipt, three fresh +zero-output snapshots and independent post-attempt configuration comparisons. + +## 2026-10-22 — Node 45 installed; fresh Hall measurement succeeds on both motors + +- Owner explicitly confirmed all tracks suspended and authorised tests and a + standard update. One native FW 5.02 Hall cycle per controller was executed + through Core after fresh all-controller preflight; no automatic retry, + Hall-table application, FOC-mode change or full motor calibration occurred. +- Node `0.8.49-45`, VESC `0.19.6` fixes the target lease renewal that conflicted + with native Hall ownership. The unchanged upstream Hall routine now retains + its controller until its reply arrives; peers remain separately inhibited. +- The versioned owner installer now reconciles a lost Hall reply only after a + private admission fence, terminal receipt, verified pre-operation backups, + matching firmware/controller set and fresh idle/receiver evidence. Unknown + result remains unknown in an immutable recovery receipt; no hardware command + is replayed. Other pending configuration/calibration/firmware states remain + blocked. See `37_CAN_INSTALLER_MAINTENANCE.md` for the qualified scope. +- Ubuntu qualification: all 24 jobs complete, including 67 environment/installer + tests; package SHA-256 + `3e0126234848ece3993c40fd2020a8623f689f7c4719d4860b22b160febe00de`. + Owner release `9d9325ce3cff1a55a3147560`, archive SHA-256 + `ec0b88287d684c1dd24369f7e70532ef022ca1bace7210db722dbe6c3c987a06`. + Standard installation completed, CAN maintenance restored observation, Node + UI healthy. USB cable remained connected. Clean Ubuntu was not exercised. +- Left measurement: 12.242 s, six valid states 1–6, table + `[255,170,93,133,38,2,61,255]`. Right: 12.246 s, states 1–6, table + `[255,166,87,127,32,2,65,255]`. Both firmware results successful, no issues, + original configuration restored and zero output confirmed. This proves all + three Hall inputs switched during these cycles; it does not prove loaded + low-speed operation or immunity to future intermittent contacts. +- Independent post-read: both motor and application packet hashes remain + identical to the retained October 18 baseline. Left remains FOC Sensorless + (`foc_sensor_mode=0`); right remains Hall (`2`). Measurements alone do not + change the selected feedback mode. A subsequent explicit configuration + review/apply is needed before using the repaired left Hall input for control. +- Private acceptance and exact source/build/install/recovery receipts: + `outputs/hall-lease-20261022/acceptance45.json`. Original failed measurement + evidence remains preserved. Node 43 owner release remains the previous + installed rollback artifact; source build temp is retired with its own + `--clean`, qualified inputs/results are pinned by build retention. + + +## 2026-10-22 — Node 0.8.49-46: confirmed CAN configuration and Hall activation + +- USB-CAN 0.2.6 admits normal CAN arbitration for complete CRC-validated, + destination-bound native motor/application configuration writes (13/16). + Only the matching source/destination/command ACK completes the write. + Partial/expired/unconfirmed transactions retire shared channel claims; + no application-level write replay. Motor outputs retain their existing + single-shot lease rules. VESC runtime stays 0.19.6. +- A previous write timeout was reconciled read-only as unchanged. After the + corrected release, Core preview/apply and independent complete reads proved + exactly seven intended changes on the left: Hall feedback selected and six + measured table entries installed. Right and both application packets stayed + unchanged. Private exact configuration evidence is retained, not Git data. +- Canonical USB-CAN regression suite passed; all 24 Ubuntu qualification jobs + completed. Node package SHA-256: + `49827ec2fffac13ccd02a145327e8994e96900f17fe8ed2f12ff02ed7b391e3e`. + Owner release `7ba15081918f0f0cf481b593`, archive SHA-256: + `075f3329d54a71601faff4068195583c7e4f9cb17010078bd10153e82a5943d9`. +- Standard installer completed with CAN maintenance observation restored, + no motor commands, no USB unplug, all services active and Node UI healthy. + Previous installed Node45 owner release remains the rollback artifact. + No clean-OS qualification was performed. +- Subsequent operator-authorized suspended-track speed checks did not prove + smooth rotation: two left 5 A checks, right 5 A comparison, then left 8 A. + No stable 900 ERPM hold completed; fault codes stayed zero. The 8 A test + stopped on the existing stall guard and its first post-release query did + not confirm zero current. Later snapshots were zero; full readback proved + all temporary limits restored. Do not reclassify that test as passed. +- Private report, original receipts, source/build/install identities, final + configuration hashes and remaining diagnostic limitations: + `outputs/hall-can-configuration-20261022/acceptance46.json` and `REPORT.md`. + The tested Hall inputs switch, but root cause of stutter remains unresolved. + Further powered checks require advance notice and fresh operator readiness. + + +## 2026-10-24 — VESC 0.20.3 / Node 0.8.49-60: startup projection + +Inventory metadata no longer holds the shared service lock. The exclusive +preflight owner publishes its real neutral samples, and both immutable +configuration schemas are prepared before command threads start. Controller +bytes/results are never cached; signature and payload validation remain per read. +This removes two reproduced startup regressions and repeated XML/CRC work near +the existing 25 ms local RPC deadline without changing command TTL, firmware, +current settings or motor command semantics. Complete CAN topology inspection +still owns the bus exclusively and can temporarily age observation samples. + +409 local VESC tests and all 24 Linux qualification stages passed. Node 60 was +installed by the versioned owner release, observation restored without motor +commands; hashes and complete deployment details are in +`07_INSTA360_X4_INSTALLATION_LEDGER.md`. Passive DEV: 45/45 fresh, both ERPM zero, +1151 events without loss, closed and no further writes. The agent did not arm. +First operator startup and the physical cause of E-turn stutter remain open. +During the recorded E segment the command was constant, fault/watchdog trips +were zero, but actual duty intermittently became zero near the configured current +limit. Do not classify that symptom as fixed or infer its physical cause from +this passive acceptance. Evidence: `outputs/rover-startup-drive-20261024/`. + + +## 2026-10-24 — VESC 0.20.4 / Node 0.8.49-62: failed release re-observation + +A single failed cleanup read no longer remains the permanent release status +when later telemetry proves a settled state. The existing passive observer +continues while release is unresolved, including with DEV/viewers closed. +Confirmation requires all original attachment generations, at least three new +sample rounds covering 0.5 seconds, no sample older than 0.5 seconds or gap +longer than that, neutral PPM using its already verified configuration, no VESC +fault, motor/battery current within 1 A, duty within 0.001 and ERPM within 1. +Missing/replaced attachments, cached samples, nonfinite values, live input, +motor work or firmware work cannot confirm release. + +Only the release warning is reconciled. Other failure messages, pending limit/ +configuration journals, motor authority latch and retired command session remain +untouched; no motor/configuration RPC or automatic rearm occurs. DEV retains the +original failure and records a separate release_observed event when enabled. +This is a new passive status proof, not a retroactive successful cleanup ACK. + +The actual passive-observer regression fails on the former implementation and +passes after the fix; the full suite has 415 tests and all 24 Ubuntu build stages +pass. A read-only replay of the retained drive's measurements reaches the new +confirmation 1.404 seconds after cleanup, while earlier nonzero-ERPM/short-window +samples remain unconfirmed. This replay is not a powered hardware experiment. + +Node62 is installed through the existing owner artifact; see the Node ledger +for hashes and receipts. DEV closure and no-motion checks passed. Network +freshness did not: only 27/45 polls were fresh, with up to 1236 ms remote response +delay despite private VESC RPC <=6 ms and CAN replies <=15.282 ms. Smooth +physical driving and E-turn stutter remain unaccepted. No firmware/current-limit/ +Hall changes and no powered tests were performed by the agent in this increment. + + +## 2026-10-24 — VESC 0.20.5 / Node 0.8.49-63: configuration idle proof + +The configuration editor now shares the existing release-observation idle +bounds instead of rejecting stationary controllers solely for a sub-amp current +sensor offset. Before a write it queries three fresh native samples across two +250 ms intervals, requires unchanged finite tachometer, neutral PPM on each +round, motor/input current within 1 A, duty within 0.001, ERPM within 1 and no +fault. Missing/nonfinite data, active procedures and pending-operation guards +still prevent writing. This path sends no motor commands. + +The offset regression fails on the former editor and passes after correction; +418 VESC tests and all 24 Ubuntu qualification stages passed. Node63 is installed +through the versioned owner artifact; runtime hashes match the qualified source. +See the Node ledger for release provenance. Configuration delivery remains slow +and intermittently stale; this is not acceptance of network stability or driving. +The owner-requested Motor Current Max=100 A was then written separately to both +controllers through the Mission Core UI. Both native exact readbacks and separate +full UI reads confirmed the result; every other motor/application parameter +matched its own baseline. Before/after backups are retained. This accepts the +configuration workflow only: 120 A, physical load and network stability remain +unaccepted. Exact identities/receipts are private in +`outputs/rover-current-audit-20261024/traction-100-ui/`. + + +## 2026-10-24 — Node64: bounded adapter confirmation for VESC CAN + +USB-CAN 0.2.7 / VESC 0.20.6 replaces SDK-only success for exact native live +setters/250 ms app-output inhibit with a bounded normal-send adapter echo. +One frame outstanding, no application replay, at most 40 ms inside the caller's +deadline; missing/late/error confirmation retires all shared claims and resets +the channel. Exact reads use the same mechanism, qualified without motion. +Configuration/limits ACK handling is preserved. DEV exposes adapter completion +separately from VESC execution. See 36_VESC_CONTROL_TRANSPORT.md. + +376 USB-CAN and 418 VESC local tests passed; all 24 Ubuntu stages passed. +Node64 was installed through the owner release; six installed runtime hashes +match the qualified source. Passive DEV: 45/45 fresh polls, 196 samples, no +fault/watchdog/output events, sampled echoes 0.148–3.346 ms. File closed with +828 records and zero writer drops. This does not accept loaded motion or prove +the original single-shot loss hypothesis. No firmware/configuration changes or +assistant motor commands occurred. The owner will perform the next drive. +Private report and complete evidence: outputs/rover-can-confirmation-20261024/. + + +## 2026-10-24 — Node65 / VESC 0.20.7: close DEV without continued acquisition + +The owner subsequently accepted the Node64 drive at 100 A / 20% input as smooth, +without jerks or jamming. Before Stop its retained DEV file has 970 native RPCs, +no failed RPC, VESC/CAN fault or native watchdog trip; adapter echoes were +0.144–4.680 ms. This is scoped physical evidence, not universal WAN acceptance. + +The long DEV Stop was traced to a pending Core tail while onboard acquisition +continued. Negotiated stop_tail_v1 now disables acquisition immediately on the +board's receipt, latches the final Core sequence, drains only existing events +and closes once that sequence is acknowledged. Stale enable cannot reopen the +capture. A Core restart marks a lost RAM tail explicitly. Legacy peers retain +compatible behavior; batches are bounded by 64 events and 48 KiB. No session +duration limit, motor/configuration/firmware, watchdog or CAN-order change. + +25 focused Core tests, 418 VESC tests and all 24 Ubuntu qualification stages +passed. The synthetic regression covers the observed 2,323-event backlog, +duplicates/lost replies, stale enable, Unicode byte bounds and restart loss. +The owner installer delivered Node65 without motion. A passive physical DEV +cycle closed in 0.583 s as observed by Core, 1,247 events, zero drops; 50/50 +telemetry checks were fresh. Six later polls confirmed no file growth. Complete +JSONL export has one manifest and one footer; no acquisition follows the board +capture_stopped marker. This does not measure loaded driving with the new UI +or the large backlog over WAN. See outputs/rover-dev-save-20261024/REPORT.md. + + +## 2026-10-25 — Node66 / VESC 0.20.8: reconcile current state after reconnect + +A terminal release proof previously retained an obsolete attachment generation. +The observer may rebind only after the same physical UUIDs are reidentified in +the new sessions, then requires a new complete neutral sample window. Missing, +stale, moving or replaced devices cannot clear the fault. Pending current-limit +restoration remains owned by its existing read-back/restore mechanism. No motion +or configuration writes are added to observation, and the retired lease/latch +remains. last_stop preserves the historical reason; the browser cannot silently +reacquire a terminal failed session when the current status becomes healthy. + +421 local VESC tests and the Ubuntu package qualification passed. Node66 was +installed through the versioned owner release, with CAN barriers and zero motor +commands. Installed runtime hashes match. Passive telemetry was fresh 16/16, +no control session was armed. Physical reconnect/drive fault recovery is covered +by synthetic regression, not asserted as a newly performed powered experiment. +See the Node66 entry in 07_INSTA360_X4_INSTALLATION_LEDGER.md and private report +outputs/rover-state-lifecycle-20261025/REPORT.md for exact artifact provenance. + +## 2026-10-25 — Node69: empty preflight recovery without motor ownership + +The missing-bound-VESC path previously retained a fault indefinitely when no +devices were present to construct the normal release proof. This now has a +read-only, profile-bound recovery requiring verified physical UUIDs/current +attachment generations and the existing continuous neutral observation window. +Pending limit restoration, radio demand or motor/firmware ownership block it. +The history, retired lease and motor latch remain; release_confirmed is not +fabricated. Passive observation runs while recovery is pending, without DEV/UI. + +The additive control_active projection reflects the worker/lease, allowing Node +to release command-pressure reservation after terminal failure while keeping it +for actual control/cleanup. No motor output, current configuration or watchdog +change. Five new cases reproduce the missing recovery against prior code; +426 VESC tests and 24 Ubuntu qualification stages passed. Node69 was installed +through the versioned release without motion; installed hashes match. Fleet-only +acceptance: 45/45 fresh samples, 19 snapshots in90 seconds. The full powered +hotplug lifecycle was not physically retested. Exact artifacts and limitations: +`outputs/vesc-inventory-recovery-20261025/REPORT.md`. + + +## 2026-10-26 — configurable diagnostics installed in Node71 + +The Node71 package carries strict immutable capture options, optional detailed +motor samples, bounded serialized rows and an out-of-band close signal in the +existing VESC diagnostics writer. Accepted rows drain before the footer; queue +pressure and omitted records remain explicit. No output owner, CAN ordering, +lease, release proof, motor limit or watchdog was changed. All 427 VESC tests +passed locally and in the Ubuntu package qualification. The versioned owner +installer restored CAN observation with motor_commands=false. Local-only DEV +recorded 1472 events, closed with zero drops and exported 775574 bytes in 12 +verified chunks. Its manifest disables live/Core trace and its file contains +Node/VESC events only. Physical drive/arm was not attempted. The minimum live +rate accounting defect found in acceptance is corrected by the Node72 follow-up. +See the Node71/X4-22 entry in `07_INSTA360_X4_INSTALLATION_LEDGER.md` and private +`outputs/network-dev-20261026/REPORT.txt`. + + +## 2026-10-26 — Node72 passive minimum-rate and source-selection acceptance + +Node72 is installed through the versioned owner release. Full Ubuntu Go race +and 427 VESC tests passed. CAN maintenance restored observation without motor +commands. Real sample rows reach the 8-kbit/s live view: 13 received rows in +16 fresh Core observations; the full 824-event file has zero drops and verified +chunk hashes. The first pre-capture device sample was 4600 ms old, subsequent +samples at most 602 ms. This distinction is retained in the evidence. + +With detailed motor samples, network events, live and Core trace disabled in +the modal, the 40-second passive file contains only capture_started and +capture_stopped plus manifest/footer, 972 bytes, zero drops. No arm, motor +configuration, CAN-owner or watchdog change occurred. The first observation +under a concurrent engineering SSH download was degraded and is retained; +the repeat paused it. Driving/LTE acceptance remains open. Exact provenance: +Node72 entry in `07_INSTA360_X4_INSTALLATION_LEDGER.md` and +`outputs/network-dev-20261026/REPORT.txt`. + +## 2026-10-26 — Node73 / VESC0.20.9 runtime A/B + +Node source 1d61b0e87f85472f23ee5f9f (SHA-256 67b299bcd089c8982dacfbdfbc861c0f2e1c9b3e6c9a833dc4513a5093f04922) passed all 24 Ubuntu jobs including Go race and VESC checks. Local complete VESC suite: 429 passed. Intermediate source 94a88c5a6d803838eb623f84 also passed but was never installed; final source adds full metadata refresh on driver-instance change and regression coverage. + +Node0.8.49-73 package SHA-256 73a8deb14da45f64406d032d1cc32c7dfe56f7e0a78d5026c3910b977bc9e8d7; owner9231e3f01fbba756513567f8 SHA-256 57669bd4f6d0dddf4429cd5445e20d769c045ff5ac312239b1ccac7ef92d4070. Install receipt70df0a1a0b8b44dbac7af3b3932df858 completed 07:18:47–07:19:09 UTC, both CAN barriers safe, observation-restored, motor_commands=false. Existing prepared VESC0.20.9 preparation completed as part of package postinst. Eleven installed payload hashes match the qualified package. Node72 owner and qualified artifacts remain rollback material. + +Release evidence records per-device send and immediate neutral/non-neutral/invalid/read-failure outcomes, including finite current/duty and error class. Current release null/false/true and historical last_stop remain separate. Motor output, current thresholds, native watchdog, stream guard, lease lifetime, latch and re-arm rules are unchanged. No controller firmware/settings/calibration or motion command was issued. + +Passive comparison: 210/210 fresh Core observations, zero ERPM, five files closed with zero drops; final1109-event export verified whole. New timeline, negotiated static metadata, costs and limitations are documented in docs/node/39_NETWORK_RUNTIME_AB.md. The prior drive's immediate cleanup failure remains unclassified; a new control trace and full operator-confirmed T1–T6/driving gates remain open. Evidence and cleanup: outputs/network-runtime-ab-20261026. + +## 2026-10-26 — Node74 observation clock and passive export + +Node0.8.49-74 source a8251db0db45a59e12c13498, owner bdb8cd18e05ff33f29f7ce37 +(SHA-256 b255bccdb3c0b817120fcaae222cd2be406097bd208bfa3cb2b09d09a95f2ced) +installed through the versioned installer at09:14:45–09:15:06 UTC, receipt +34915a95ad0b479b9b96aecad9e9e6ca. Package SHA-256 +97fd49513e60cbf72cf42c80d2b90777d6abc040eb86ce888bc6f02947c28b97. +Both CAN admission barriers were safe; observation-restored, motor_commands=false. +Eleven installed files match qualification. Existing X4-23 and VESC0.20.9 remain; +no controller/USB/firmware/network change or autonomous arm/drive occurred. +Node73 owner remains rollback. Twenty-four final Ubuntu stages including race +passed (one dependency attempt retried); 61 local Core regressions passed. + +Observation timestamp bounds no longer regress on a late HTTP reply; immutable +metadata revision survives transport delay independently of live expiry. Explicit +export makes bounded progress alongside primary video only while observing, +within the same budget. All watchdogs, leases, current/duty limits, release +criteria, latch and re-arm rules remain. Passive acceptance:109/109 fresh Core +samples, ERPM0, complete305-event/0-drop export. Existing video peer survived, +but remaining codec churn and expired frames are recorded, not declared fixed. +The later drive's immediate release readings1.1/2.38A explain the failed ≤1A +confirmation; later neutral reconciliation did not retroactively confirm it. +Exact provenance, original recording, qualification, release checks and cleanup: +outputs/network-runtime-1052-20261026/REPORT.txt and docs/node/39_NETWORK_RUNTIME_AB.md. +Prepared-host acceptance does not qualify clean Ubuntu, driving or WAN impairment. + + +## 2026-10-26 — Node75 primary-video credit correction + +Node 0.8.49-75 source `0b7e772bfe5a339ec52fd1bb` (SHA-256 +`3a3ca4b0cbfe9290677184a13a195faba7bd0797569bed66184278a07839061d`) passed all 24 final +Ubuntu 24.04 stages, including Go race and 431 VESC unittest cases. The recorded +late-lease regression now uses stdlib unittest, preserving all three measured +late gaps and the timely-delivery case in the shipped qualification runner. +Its first pytest-import failure was preserved; no pytest/system repair was made +on the board, and the complete corrected artifact was rebuilt and retested. + +Package SHA-256 `49deae661c4837b27c887c23177c76374e83c611aff62b5e279fbe13150b0ea2`; +owner `c995ff13b2e43a8d2fd1d01f`, SHA-256 +`0a6dda2df3c0d5f28316df2d7ba4b26db1635bc4040a8aaba0f70b0437033a6d`. Versioned installation +completed 14:09:46–14:10:08 UTC, receipt `190b2b81a2cc41e5b3e3cd4f53325546`. +Both CAN admission barriers returned safe; observation restored, motor_commands=false. +All 1194 regular installed package files match qualification. Node/VESC/USB-CAN/X4 +services remain active with zero automatic restarts; VESC 0.20.9 and X4-23 are unchanged. +Node74 owner remains preserved. No motor, Hall/configuration, firmware or network +settings were changed. + +Only the Node command-pressure credit transition changed in production: repeated +moderate-age samples preserve the selected camera's bounded low-rate packet credit. +The 250-ms emergency gate, 400-ms command TTL, 350-ms stream guard, native watchdog +and release/current rules remain unchanged. Two-minute passive acceptance retained +120/120 fresh observations, 240 motor rows (p95/max age 381/434 ms), ERPM 0 and no control +session. Core's one stream wrote 2054 neutral/observation frames successfully; +gap p95/max 80.24/185.03 ms, write p95/max 13.77/133.60 ms, dispatch max 2.12 ms. +These are Core-side timings, not measurements of Node arrival or end-to-end latency. + +The existing physical X4 source was viewed through one browser video transport +shared by three panes. A single peer remained across two readings 127.17 s apart, +video currentTime advanced 126.89 s; 1280x640 and sampled receiver 11–12 fps were observed. +No cumulative expired frames/datagrams or queue drops appeared in those readings; +encoder reinitializations increased 1→5. The two receiver intervals had zero reported +loss/drop/freeze, which is not a continuous loss-free guarantee. No driving, +induced WAN impairment, clean-Ubuntu or release-current acceptance is claimed. +Exact logs, source identities, returned installer and passive evidence: +`outputs/network-release-75-20261026/REPORT.txt`; see39_NETWORK_RUNTIME_AB.md. diff --git a/docs/node/27_VESC_ENGINE_UPGRADES.md b/docs/node/27_VESC_ENGINE_UPGRADES.md new file mode 100644 index 00000000..8525b3ea --- /dev/null +++ b/docs/node/27_VESC_ENGINE_UPGRADES.md @@ -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. diff --git a/docs/node/28_VESC_PACKAGES.md b/docs/node/28_VESC_PACKAGES.md new file mode 100644 index 00000000..9337ca99 --- /dev/null +++ b/docs/node/28_VESC_PACKAGES.md @@ -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. diff --git a/docs/node/29_VESC_QML_PREVIEW_AND_DIAGNOSTICS.md b/docs/node/29_VESC_QML_PREVIEW_AND_DIAGNOSTICS.md new file mode 100644 index 00000000..354ba568 --- /dev/null +++ b/docs/node/29_VESC_QML_PREVIEW_AND_DIAGNOSTICS.md @@ -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. diff --git a/docs/node/30_VESC_SAMPLE_DATA_AND_INTERACTIVE_QML.md b/docs/node/30_VESC_SAMPLE_DATA_AND_INTERACTIVE_QML.md new file mode 100644 index 00000000..2f8245c4 --- /dev/null +++ b/docs/node/30_VESC_SAMPLE_DATA_AND_INTERACTIVE_QML.md @@ -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. diff --git a/docs/node/31_VESC_SAVED_SAMPLE_ANALYSIS.md b/docs/node/31_VESC_SAVED_SAMPLE_ANALYSIS.md new file mode 100644 index 00000000..6f1d8db4 --- /dev/null +++ b/docs/node/31_VESC_SAVED_SAMPLE_ANALYSIS.md @@ -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. diff --git a/docs/node/32_VESC_QML_READ_BROKER.md b/docs/node/32_VESC_QML_READ_BROKER.md new file mode 100644 index 00000000..2c046d39 --- /dev/null +++ b/docs/node/32_VESC_QML_READ_BROKER.md @@ -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. diff --git a/docs/node/33_VESC_DIAGNOSTIC_REPORT_REVIEW.md b/docs/node/33_VESC_DIAGNOSTIC_REPORT_REVIEW.md new file mode 100644 index 00000000..38365158 --- /dev/null +++ b/docs/node/33_VESC_DIAGNOSTIC_REPORT_REVIEW.md @@ -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. diff --git a/docs/node/34_VESC_ROTOR_HALL_REVIEW.md b/docs/node/34_VESC_ROTOR_HALL_REVIEW.md new file mode 100644 index 00000000..74af60ca --- /dev/null +++ b/docs/node/34_VESC_ROTOR_HALL_REVIEW.md @@ -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. diff --git a/docs/node/36_VESC_CONTROL_TRANSPORT.md b/docs/node/36_VESC_CONTROL_TRANSPORT.md new file mode 100644 index 00000000..47939211 --- /dev/null +++ b/docs/node/36_VESC_CONTROL_TRANSPORT.md @@ -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/. diff --git a/plugins/vesc/frontend/src/FirmwareDestination.tsx b/plugins/vesc/frontend/src/FirmwareDestination.tsx new file mode 100644 index 00000000..ecc55a4e --- /dev/null +++ b/plugins/vesc/frontend/src/FirmwareDestination.tsx @@ -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 + + + {target&&CAN {target.can_id} · {target.hardware} · FW {target.major}.{String(target.minor).padStart(2,'0')} · UUID {target.uuid.toUpperCase()}} + Файл получит только выбранный UUID. При смене устройства на этом CAN-адресе запись отменяется.} + {mode==='swd'&&<> + VESC по USB работает программатором. Проверьте распиновку и допустимые уровни напряжения целевой платы. Подключение SWD останавливает её процессор; запись стирает всю основную flash. Образ должен содержать всё необходимое для запуска. Семейство проверяется перед стиранием; модель платы и её UUID этим протоколом не определяются. + onSwd({...swd,pins})}/> + onSwd({...swd,address:Number(e.target.value)})}/> + onSwd({...swd,flash_bytes:Number(e.target.value)*1024})}/> + Укажите диапазон по документации конкретного процессора. BIN начинается с указанного адреса; HEX должен начинаться там же. Option bytes, UICR и периферия исключены. Каждый записанный блок обязательно читается обратно. + } + ; +} diff --git a/plugins/vesc/frontend/src/SignalPlot.tsx b/plugins/vesc/frontend/src/SignalPlot.tsx new file mode 100644 index 00000000..1d30e5d7 --- /dev/null +++ b/plugins/vesc/frontend/src/SignalPlot.tsx @@ -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!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(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 setExpanded(v=>!v)}>}> + + {[0,.5,1].map(f=>{number(view.high-f*(view.high-view.low))})} + {view.segments.map((line,i)=>line.length===1?: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?{i+1}:null)} + {number(from/xScale)} {xUnit}{number(to/xScale)} {xUnit} + + {!view.count&&В этом интервале нет измерений. Пропуски не заменяются нулями.} + ; +} diff --git a/plugins/vesc/frontend/src/VescBackups.tsx b/plugins/vesc/frontend/src/VescBackups.tsx index 0ada10e4..e44a2fc0 100644 --- a/plugins/vesc/frontend/src/VescBackups.tsx +++ b/plugins/vesc/frontend/src/VescBackups.tsx @@ -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([]); const [next,setNext]=useState(null); @@ -37,15 +43,15 @@ export function VescBackups({deviceId,archive,revision}: {deviceId:string;archiv }catch{setError('Не удалось скачать выбранную версию.');} finally{setDownload(null);} } - return setReload(value=>value+1)}>Обновить историю}> - - {error&&

{error}

} - {!loading&&!items.length&&!error&&

Сохранённых версий пока нет.

} + return <>setReload(value=>value+1)}>Обновить историю}> + + {error&&{error}} + {!loading&&!items.length&&!error&&Сохранённых версий пока нет.} {items.map(item=>
  • void save(item.id)}>Скачать}/> + actions={<>{editor.available&&}}/>
  • )}
    {next&&} -
    ; +
    ; } diff --git a/plugins/vesc/frontend/src/VescBms.tsx b/plugins/vesc/frontend/src/VescBms.tsx new file mode 100644 index 00000000..123a9543 --- /dev/null +++ b/plugins/vesc/frontend/src/VescBms.tsx @@ -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 {reading.state==='not_bms'?'По этому адресу ответило другое устройство. Выберите BMS.':reading.state==='unsupported'?'Чтение BMS не поддерживается текущей прошивкой.':'Ответ BMS не получен.'}; + if(!cells.length)return VESC ответил без данных ячеек. Наличие подключённой BMS не подтверждено.; + return <> + + {reading.source!=='direct_can'&&Это сохранённые сведения из VESC. Прошивка 5.02 не сообщает адрес BMS и возраст этих измерений; наличие связи с батареей по этому ответу определить нельзя.} + {fields.filter(([key])=>key in values).map(([key,label])=>
  • )}
    + {typeof values.status==='string'&&values.status&&{values.status}} +
    + + {summary&&
  • } + {cells.map(cell=>
  • )}
    +
    + + {temps.map((v,i)=>
  • )} +
  • +
    +
    + ; +} +export function VescBms(props:ReadProps){ + const {device,transport,failure}=props,status=vescStatus(device); + const [source,setSource]=useState('proxy'),[reading,setReading]=useState(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(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=(action:string,p:Record={})=>perform(transport,device,action,p,30000); + async function run(work:()=>Promise){ + 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(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('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
    + + {setCanId(v);reset();}}/>} + {scanned&&!options.length&&Устройства CAN не ответили. Проверьте подключение и питание BMS.} + Перед чтением и каждой командой проверяются тип устройства и UUID BMS. Номер CAN сам по себе не определяет батарею. + } + + +
    + {reading?.target&&
  • } + {reading&&} +
    + {source==='direct'&&reading?.target?.hardware_type===1&& + {!reading.commands_supported?Установленное ядро поддерживает команды BMS с прошивкой 6.00. Для этой версии доступно чтение.:<> + ({value:String(i),label:`Конфигурация ${i+1}`}))} disabled={disabled} onChange={v=>{setIndex(v);setValue(null);setDrafts({});clear();}}/>} + + {value?.pending&&<>Результат предыдущей записи не подтверждён. При смене CAN-адреса выберите новый адрес этой BMS.} + {config&&<> + void importXml(e)}/> + + {changes.length>0&&} + } + + {preview&& + {preview.changes.map(c=>
  • )}
    + {!preview.changes.length?Изменений нет.:<>} +
    } + {result&&{result}} + ; +} diff --git a/plugins/vesc/frontend/src/VescBoardSettings.tsx b/plugins/vesc/frontend/src/VescBoardSettings.tsx index 0d6327ec..fcde9291 100644 --- a/plugins/vesc/frontend/src/VescBoardSettings.tsx +++ b/plugins/vesc/frontend/src/VescBoardSettings.tsx @@ -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&&

    {inventory?'Подключите VESC, чтобы получить профиль привода с борта.':'Получение профиля привода…'}

    } - {profile&&!anchor&&

    Профиль показан по последним сведениям с борта. Для изменения нужна связь с VESC и актуальное бортовое приложение.

    } + {!profile&&{inventory?'Подключите VESC, чтобы получить профиль привода с борта.':'Получение профиля привода…'}} + {profile&&!anchor&&Профиль показан по последним сведениям с борта. Для изменения нужна связь с VESC и актуальное бортовое приложение.} {profile?.layout&&<> -

    Стороны — по направлению движения вперёд. Назначения сохраняются автоматически и остаются с контроллером при смене USB-порта.

    + Стороны — по направлению движения вперёд. Назначения сохраняются автоматически и остаются с контроллером при смене USB-порта. {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 })} } + {profile&&controlStatus?.control_transport&&transportAnchor&&!!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; + }}/>}
    ; } diff --git a/plugins/vesc/frontend/src/VescCalibration.tsx b/plugins/vesc/frontend/src/VescCalibration.tsx index 5ee193cd..b59e793b 100644 --- a/plugins/vesc/frontend/src/VescCalibration.tsx +++ b/plugins/vesc/frontend/src/VescCalibration.tsx @@ -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}; } -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(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 -

    Мастер измеряет сопротивление, индуктивность и магнитный поток, определяет датчики и записывает параметры выбранного мотора. Версии до и после сохраняются в истории; настройки аккумулятора и пульта сохраняются.

    + Мастер измеряет сопротивление, индуктивность и магнитный поток, определяет датчики и записывает параметры выбранного мотора. Версии до и после сохраняются в истории; настройки аккумулятора и пульта сохраняются. 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, не номинальная мощность мотора. По нему мастер выбирает токи измерения; предел тока проверки вращения здесь не применяется."/> -

    Мотор будет двигаться и разгоняться. На прошивке 5.02 процедуру нельзя прервать кнопкой или пультом — только отключением силового питания. Оставьте пульт выключенным и приводы вывешенными до завершения; цикл может занять до трёх минут.

    + Мотор будет двигаться и разгоняться. На прошивке 5.02 процедуру нельзя прервать кнопкой или пультом — только отключением силового питания. Оставьте пульт выключенным и приводы вывешенными до завершения; цикл может занять до трёх минут. - {busy&&

    Подготовка и калибровка VESC Tool. Дождитесь результата и снятия тока.

    } + {busy&&Подготовка и калибровка VESC Tool. Дождитесь результата и снятия тока.} {result&&<> -

    {calibrated?'Параметры мотора измерены, записаны и проверены.':result.completed?`Калибровка не принята. Код VESC: ${result.native.code??'не получен'}.`:'Завершение калибровки не подтверждено. Проверьте состояние мотора и питание.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока пока не подтверждено. Перед следующей проверкой верните управление после нейтрали.'} {!result.configuration_verified&&' Проверка конфигурации не завершена; новое движение заблокировано.'}

    + {calibrated?'Параметры мотора измерены, записаны и проверены.':result.completed?`Калибровка не принята. Код VESC: ${result.native.code??'не получен'}.`:'Завершение калибровки не подтверждено. Проверьте состояние мотора и питание.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока пока не подтверждено. Перед следующей проверкой верните управление после нейтрали.'} {!result.configuration_verified&&' Проверка конфигурации не завершена; новое движение заблокировано.'} {calibrated&&<> -

    {result.native.sensor_mode===0?'Выбран режим без датчиков. Холлы не определились; качество запуска нужно проверить вращением.':result.native.sensor_mode===2?'Определены датчики Холла.':'Определён энкодер.'}

    + {result.native.sensor_mode===0?'Выбран режим без датчиков. Холлы не определились; качество запуска нужно проверить вращением.':result.native.sensor_mode===2?'Определены датчики Холла.':'Определён энкодер.'} {parameters&& {([['foc_motor_r','Сопротивление',1000,'мОм'],['foc_motor_l','Индуктивность',1e6,'мкГн'],['foc_motor_flux_linkage','Магнитный поток',1000,'мВб'],['l_current_max','Предел тока мотора',1,'А']] as const).map(([key,title,scale,unit])=>
  • )}
    } diff --git a/plugins/vesc/frontend/src/VescChangeReview.tsx b/plugins/vesc/frontend/src/VescChangeReview.tsx new file mode 100644 index 00000000..353a4f11 --- /dev/null +++ b/plugins/vesc/frontend/src/VescChangeReview.tsx @@ -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; +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(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
    + {pending&& + + } + {editor.preview&& + {editor.preview.changes.map(c=>
  • )}
    + {!editor.preview.changes.length?Параметры совпадают. Запись не требуется.:<> + Изменения записываются в контроллер и влияют на работу привода. Перед записью выключите пульт и физически отключите другие источники команд. Все приводы должны быть вывешены и полностью остановлены. Исходная конфигурация сохраняется автоматически. + + + } + +
    } + {editor.result&& + {editor.result.before_backup_id&&Исходная копия сохранена в истории конфигураций. Управление включается отдельно.} + } +
    ; +} diff --git a/plugins/vesc/frontend/src/VescCodeTools.tsx b/plugins/vesc/frontend/src/VescCodeTools.tsx new file mode 100644 index 00000000..5a163626 --- /dev/null +++ b/plugins/vesc/frontend/src/VescCodeTools.tsx @@ -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({kind,source:'',imports:{},fullscreen:false}),[reading,setReading]=useState(null); + const [preview,setPreview]=useState(null),[confirmed,setConfirmed]=useState(false),[busy,setBusy]=useState(false),[message,setMessage]=useState(''); + const [repl,setRepl]=useState(''),[output,setOutput]=useState(''),[stats,setStats]=useState|null>(null); + const running=useRef(false),mounted=useRef(true),file=useRef(null),attachment=useRef(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=(name:string,p:Record={},timeout=60000)=>perform(props.transport,props.device,'vesc.code.'+name,p,timeout); + function clear(){setPreview(null);setConfirmed(false);setMessage('');} + async function run(work:()=>Promise){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('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('chunk',{upload_id:upload.upload_id,offset:at,data:bytesBase64(chunk)});if(r.offset!==at+chunk.length)throw new Error('Передача проекта не подтверждена.');} + const p=await call('prepare',{upload_id:upload.upload_id});if(mounted.current)setPreview(p); + }); + const prepareAction=(name:string,p:Record)=>run(async()=>{clear();const v=await call(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){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){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
    + + {!supported&&На этом контроллере прошивка {status.identity?.version??'не определена'}. Чтение и запись программ в памяти контроллера доступны для профиля VESC 6.00. Здесь можно открыть, отредактировать и сохранить проект.} + + {kind==='qml'&&} + void open(e)}/> + {setProject(p=>({...p,source:e.target.value}));clear();}}/> + {kind==='qml'&&{setProject(p=>({...p,fullscreen}));clear();}} disabled={disabled}/>} + {kind==='lisp'&&<>void attach(e)}/>В import укажите имя прикреплённого файла без пути к папке или ссылку pkg@ / pkg:: на библиотеку из сохранённого каталога расширений. Исходный код и вложения вместе — до 120 КБ. + {Object.keys(project.imports).map(name=>
  • {setProject(p=>({...p,imports:Object.fromEntries(Object.entries(p.imports).filter(([key])=>key!==name))}));clear();}}>Убрать}/>
  • )}
    } + + + + +
    + {kind==='qml'&&} + {pending&&} + {kind==='lisp'&& + + {setRepl(e.target.value);clear();}}/> + + + {stats&&{[['cpu_use','CPU, %'],['heap_use','Куча, %'],['mem_use','Память, %'],['stack_use','Стек, %'],['done_ctx_r','Результат завершённого контекста']].map(([key,title])=>
  • )}
    } + {output&&} +
    } + {preview&& + {preview.command?(preview.command==='repl'?`REPL: ${preview.text}`:preview.command==='start'?'Запуск сохранённой программы Lisp.':'Остановка Lisp.'):(preview.erase?`Удаление ${label} из контроллера.`:`Запись ${label}: ${preview.bytes} байт. Исходная копия сохраняется автоматически. Lisp не запускается.`)} + + } + {message&&{message}} +
    ; +} diff --git a/plugins/vesc/frontend/src/VescConfiguration.tsx b/plugins/vesc/frontend/src/VescConfiguration.tsx new file mode 100644 index 00000000..987790c6 --- /dev/null +++ b/plugins/vesc/frontend/src/VescConfiguration.tsx @@ -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({}),[editing,setEditing]=useState(null); + const file=useRef(null); + const {value,busy,available,read}=useVescRead(props,'vesc.configuration.read',status.configuration_read_supported===true); + const [group,setGroup]=useState(''),[subgroup,setSubgroup]=useState(''),[query,setQuery]=useState(''),[description,setDescription]=useState(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){ + 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
    + + void read()}>Прочитать параметры}> + {!status.configuration_read_supported&&Для чтения полной конфигурации требуется обновление бортового приложения.} +
    + {!config&&Прочитайте конфигурацию, чтобы увидеть группы, значения, единицы и описания параметров.} + {config&&<> + ({value:item.name,label:groupLabel(item.name)}))]} onChange={value=>{setSubgroup(value);setQuery('');}}/>} + setQuery(event.target.value)}/> + {parameters.length} параметров. Значения относятся к указанному времени чтения. + {parameters.map(parameter=>
  • + {parameter.title||parameter.name}} + description={`${parameter.name} · ${parameterValue(parameter)}${parameter.transmittable?'':' · справочное значение схемы'}`} + actions={<>{editor.available&¶meter.transmittable&¶meter.type!=='undefined'&&}{parameter.description?:null}}/> + {editing===parameter.name&&{editor.clear();setDrafts(old=>({...old,[parameter.name]:draft}));}}/>} + {description===parameter.name&&{plainDescription(parameter.description)}} +
  • )}
    + {!parameters.length&&Параметры не найдены.} +
    + {editor.available&&<> + void importXml(event)}/> + + } +
    + {editor.available&&changed.length>0&&<>Изменено параметров: {changed.length}. Сначала проверьте сравнение с контроллером. +
    +
    + } + + } +
    +
    +
    ; +} diff --git a/plugins/vesc/frontend/src/VescControlTransport.tsx b/plugins/vesc/frontend/src/VescControlTransport.tsx new file mode 100644 index 00000000..f23f3c4e --- /dev/null +++ b/plugins/vesc/frontend/src/VescControlTransport.tsx @@ -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})=>Promise; + 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 +
    + 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 + ({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); + }}/> + ; + })} + Доступность CAN подтверждается ответом назначенного VESC. При обрыве выбранной связи текущий сеанс управления завершается. Смена шины применяется после сохранения. + {active&&Завершите управление перед сменой шины.} + {!allReady&&Один или несколько моторов недоступны по выбранному соединению.} + {stale?:} +
    +
    ; +} diff --git a/plugins/vesc/frontend/src/VescDetail.tsx b/plugins/vesc/frontend/src/VescDetail.tsx index 8b90e6bc..c69a563a 100644 --- a/plugins/vesc/frontend/src/VescDetail.tsx +++ b/plugins/vesc/frontend/src/VescDetail.tsx @@ -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(status.telemetry); const [pending,setPending]=useState(null); const [saved,setSaved]=useState(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
    -
    - {label.label}}> - {!enabled||!device.online?

    Нет свежей связи с контроллером.

    :status.message?

    {status.message}

    :null} - {status.identity? -
  • -
  • -
  • - {status.identity.test_firmware!==null&&status.identity.test_firmware>0&&
  • } -
    :

    Аппаратный идентификатор ещё не подтверждён.

    } -
    + 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 {if(!busy)setSection(value);}} + onClose={()=>{if(!busy)back();}} headerActions={{label.label}}> +
    + {!enabled||!device.online?Нет свежей связи с контроллером. Показаны последние полученные сведения.:status.message?{status.message}:null} + {section==='general'&&} + + +
    + {section==='samples'&&} + + {section==='log-analysis'&&} + {section==='packages'&&} + + + {section==='bms'&&} + {section==='peripherals'&&} + {section==='terminal'&&} + {section==='firmware'&&} + {section==='hardware'&&} + + + + + +
    + ; } diff --git a/plugins/vesc/frontend/src/VescDiagnosticReview.tsx b/plugins/vesc/frontend/src/VescDiagnosticReview.tsx new file mode 100644 index 00000000..d67099ca --- /dev/null +++ b/plugins/vesc/frontend/src/VescDiagnosticReview.tsx @@ -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={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(null),[baseline,setBaseline]=useState(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(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&¤t?compareDiagnostics(baseline,current):null; + const snapshots=baseline&¤t&&baseline!==current?[baseline,current]:current?[current]:[]; + const columns=snapshots.map((s,i)=>({id:String(i),label:s===baseline?'Опорный снимок':'Последний снимок'})); + return
    + void read()}>Прочитать диагностику}> + {!supported&&Для чтения аппаратной диагностики требуется обновление бортового приложения.} + {!current&&{expired?'Снимки удалены из памяти по истечении срока.':'Диагностика ещё не прочитана.'} Команды hw_status и faults не запускают мотор.} + {current&&<> + Прочитано {timestamp(current)}. Ответ терминала завершается после паузы вывода: прошивка не передаёт признак полноты. Отсутствующие поля не считаются нулевыми. + {!current.identityMatches&&UUID в тексте hw_status не совпал с идентификацией контроллера или отсутствует. Сравнение отключено.} +
    + В памяти окна остаются максимум два снимка на пять минут. Смена контроллера, USB-сеанса или закрытие раздела очищает их. Непрерывная запись не включается. + } +
    + {current&&<> + + 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?Для сравнения отметьте этот снимок как опорный, затем прочитайте диагностику ещё раз.:comparison?.reason?{comparison.reason}:comparison&&Изменение от опорного снимка: конфигурирования USB — {number(comparison.configEvents)}; таймауты записи — {number(comparison.writeTimeouts)}.} + Рост счётчика подтверждает событие прошивки, но не определяет его физическую причину. Нулевая разность не исключает пропадание связи, перезапуск или подзаедание без ошибки. + + + {current.faults.state==='none'?'Прошивка сообщает: зарегистрированных ошибок с момента запуска нет.':current.faults.state==='unknown'?'Формат ответа не распознан. Откройте исходный ответ.':`В полученном ответе записей: ${current.faults.entries.length}.`} + {current.faults.entries.map((entry,i)=>({id:key,label:faultFields[key]??key,cells:[value]}))}/>)} + Отсутствие faults не подтверждает исправность двигателя, датчиков или проводки. Смещения токовых каналов без сопоставимого измерения не дают такого заключения. + + + ({id:key,label,cells:[current.read.usb[key]??'Не сообщается']})), + ]}/> + + {raw&&Object.entries(current.read.reports).map(([name,report])=>
    {report.text}
    )} + } +
    ; +} diff --git a/plugins/vesc/frontend/src/VescDiagnostics.tsx b/plugins/vesc/frontend/src/VescDiagnostics.tsx new file mode 100644 index 00000000..d767e633 --- /dev/null +++ b/plugins/vesc/frontend/src/VescDiagnostics.tsx @@ -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 ; +} +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
    + void input.read()}>Прочитать PPM}> + {input.value?
  • :Сигнал ещё не прочитан.} +
    + void can.read()}>Проверить CAN}> + {can.value?<>{can.value.can_ids.length?`Ответили CAN ID: ${can.value.can_ids.join(', ')}`:'Другие контроллеры не ответили.'}Проверено {new Date(can.value.observed_at).toLocaleString('ru-RU')}.:Поиск ещё не выполнен.} + +
    ; +} diff --git a/plugins/vesc/frontend/src/VescFirmware.tsx b/plugins/vesc/frontend/src/VescFirmware.tsx new file mode 100644 index 00000000..f24b98a4 --- /dev/null +++ b/plugins/vesc/frontend/src/VescFirmware.tsx @@ -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={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(null),[canOptions,setCanOptions]=useState<{value:string;label:string}[]>([]); + const [swd,setSwd]=useState({target_code:1,pins:'default',address:0x08000000,flash_bytes:128*1024}); + const [source,setSource]=useState('file'),[catalog,setCatalog]=useState(null),[imageId,setImageId]=useState(''); + const [withoutLimits,setWithoutLimits]=useState(false); + const [kind,setKind]=useState('firmware'),[version,setVersion]=useState(status.identity?.version??''); + const [preview,setPreview]=useState(null),[result,setResult]=useState(null); + const [busy,setBusy]=useState(false),[uploading,setUploading]=useState(false),[progress,setProgress]=useState(null); + const [compatible,setCompatible]=useState(false),[isolated,setIsolated]=useState(false),[cancelling,setCancelling]=useState(false); + const input=useRef(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=(name:string,p:Record={},timeout=30000)=>perform(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('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('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('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('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('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
    + {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();}}/> + + {!status.firmware_update_supported&&Для загрузки прошивки требуется обновление бортового приложения.} + ({value:i.id,label:firmwareVariant(i)}))} disabled={disabled} onChange={value=>{setImageId(value);setPreview(null);setCompatible(false);setWithoutLimits(false);}}/> + :В установленном архиве нет подходящего образа. Можно выбрать свой файл или обновить бортовое приложение.} +
  • + } + :<> + {mode!=='swd'&&({value,label:`Прошивка ${value}`}))} disabled={disabled} + onChange={value=>{setVersion(value);setPreview(null);setCompatible(false);}}/>} + BIN и HEX не подтверждают производителя платы. Выберите образ для {mode==='swd'?'выбранного процессора':hardware??'своего контроллера'} и указанной версии. Проверка структуры и SHA-256 не подтверждает происхождение файла. HEX проверяется оригинальным читателем VESC Tool; адреса и итоговый образ проверяются до записи. Сжатые BIN здесь не принимаются. + {const file=event.target.files?.[0];event.target.value='';if(file)void stage(file);}}/> + + } + {progress!==null&&} +
    + {preview&& + +
  • +
  • +
  • + {preview.image.can_id!==undefined&&
  • } + {preview.image.swd&&
  • } +
  • + {preview.image.source_sha256&&preview.image.source_sha256!==preview.image.sha256&&
  • } + {preview.image.format==='hex'&&
  • } +
    + Подготовка действует до 10 минут и отменяется после переподключения. Запись изменяет постоянную память; не отключайте питание. Старые настройки после смены прошивки автоматически не восстанавливаются. + {preview.image.hardware_limits===false&&<>Этот вариант удаляет аппаратные пределы тока и напряжения из прошивки. Ошибочные настройки могут повредить контроллер или мотор.} + + + + +
    } + {state.state!=='idle'&& + {labels[state.state]??state.state} + {active&&<>} + {state.image&&
  • } + {state.before_backup_id&&<>Исходная конфигурация сохранена по UUID контроллера.} + {!active&&!['identified','not_started'].includes(state.state)&&<> + Управление заблокировано до подтверждения результата. После обрыва или отмены версия контроллера сама по себе не доказывает завершение записи. Автоматического повторения нет. + + } + {state.state==='identified'&&state.image?.swd&&Записанные байты прочитаны обратно и совпали; команда перезапуска подтверждена. Запуск приложения целевой платы ещё необходимо проверить.} + {state.state==='identified'&&!state.image?.swd&&Передача подтверждена, UUID и версия контроллера прочитаны заново. Обратное чтение бинарного образа этим протоколом не выполнено. Перед управлением проверьте настройки.} +
    } +
    ; +} diff --git a/plugins/vesc/frontend/src/VescHall.tsx b/plugins/vesc/frontend/src/VescHall.tsx index 870102d9..fdb17087 100644 --- a/plugins/vesc/frontend/src/VescHall.tsx +++ b/plugins/vesc/frontend/src/VescHall.tsx @@ -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(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(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 -

    Мотор медленно смещается в обе стороны около 12 секунд. Измерение проверяет состояния датчиков и получает таблицу их положения; новая таблица автоматически не записывается.

    -

    На прошивке 5.02 этот цикл нельзя прервать кнопкой или пультом. Для немедленной остановки нужно отключить силовое питание. Пульт должен оставаться выключенным, все приводы — вывешенными. Перед запуском убедитесь, что все моторы полностью остановились: в бессенсорном режиме показание оборотов на остановленном моторе может быть ненулевым.

    - - - {busy&&

    Подготовка и штатное измерение датчиков. Дождитесь результата.

    } - {result&&

    {!result.completed?'Завершение измерения не подтверждено. Проверьте мотор и питание.':result.measurement?.valid_six_states?'Измерение получило шесть состояний Холла.':'Не удалось получить полную таблицу Холла. Возможны отсутствие движения или неисправность датчиков/соединения.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока не подтверждено.'} {result.configuration_restored?'Исходная конфигурация сохранена.':'Возврат исходной конфигурации не подтверждён.'}

    } -
    ; +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
    + + + Пассивный просмотр выше не подаёт ток. Измерение ниже требует вывешенных приводов и выключенного пульта. + + + {expanded&&} +
    ; } diff --git a/plugins/vesc/frontend/src/VescHallInputs.tsx b/plugins/vesc/frontend/src/VescHallInputs.tsx new file mode 100644 index 00000000..533a3941 --- /dev/null +++ b/plugins/vesc/frontend/src/VescHallInputs.tsx @@ -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(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(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 <> + + {!device.online||!enabled?'Нет связи':fw==='5.02'?'Пассивное чтение H1–H3 недоступно':'Пассивное чтение H1–H3 не подтверждено'} + ({id:String(i),label:`H${i}`}))} rows={[ + {id:'level',label:'Уровень 0 / 1',cells:config.inputs.map(()=>'Нет данных')}, + {id:'changes',label:'Переключения',cells:config.transitions.map(()=>'Не измерены')}, + ]}/> + {fw==='5.02'?'Штатная прошивка 5.02 не предоставляет отдельное пассивное чтение этих входов. Код Hall в Sample Data — преобразованная фаза; он не подтверждает уровни H1–H3.':'Для этой прошивки достоверный способ пассивного чтения трёх входов пока не подтверждён.'} + «Нет данных» не означает обрыв. Неподвижный вал не обязан давать переключения; одно состояние не доказывает исправность всех трёх датчиков. Установка пина обратно не меняет режим управления автоматически. + + void read()}>Прочитать настройки датчиков}> + {[ + ['Тип мотора',config.motor],['Режим порта датчиков',config.port],['Режим датчиков FOC',config.mode],['Участие Холлов в управлении',config.use], + ].map(([title,description])=>
  • )}
    + Это выбранные настройки, а не результат обнаружения датчика. Ремонт контакта и правильность переключений ими не подтверждаются. +
    + ; +} diff --git a/plugins/vesc/frontend/src/VescHallMeasurement.tsx b/plugins/vesc/frontend/src/VescHallMeasurement.tsx new file mode 100644 index 00000000..44a0d13c --- /dev/null +++ b/plugins/vesc/frontend/src/VescHallMeasurement.tsx @@ -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(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(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 + Мотор медленно смещается в обе стороны около 12 секунд. Измерение проверяет состояния датчиков и получает таблицу их положения; новая таблица автоматически не записывается. + На прошивке 5.02 этот цикл нельзя прервать кнопкой или пультом. Для немедленной остановки нужно отключить силовое питание. Пульт должен оставаться выключенным, все приводы — вывешенными. Перед запуском убедитесь, что все моторы полностью остановились: в бессенсорном режиме показание оборотов на остановленном моторе может быть ненулевым. + + + + + {busy&&Подготовка и штатное измерение датчиков. Дождитесь результата.} + {result&&{!result.completed?'Завершение измерения не подтверждено. Проверьте мотор и питание.':result.measurement?.valid_six_states?'Измерение получило шесть состояний Холла.':'Не удалось получить полную таблицу Холла. Возможны отсутствие движения или неисправность датчиков/соединения.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока не подтверждено.'} {result.configuration_restored?'Исходная конфигурация сохранена.':'Возврат исходной конфигурации не подтверждён.'}} + ; +} diff --git a/plugins/vesc/frontend/src/VescLimits.tsx b/plugins/vesc/frontend/src/VescLimits.tsx index dfb4adb5..193dba6c 100644 --- a/plugins/vesc/frontend/src/VescLimits.tsx +++ b/plugins/vesc/frontend/src/VescLimits.tsx @@ -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 void read()}>Прочитать ограничения}> -

    Ток мотора задаёт тягу; ток батареи ограничивает потребление. Эти настройки действуют и при управлении с пульта. Паспортные пределы моторов, контроллеров и батареи проверяются отдельно.

    + Ток мотора задаёт тягу; ток батареи ограничивает потребление. Эти настройки действуют и при управлении с пульта. Паспортные пределы моторов, контроллеров и батареи проверяются отдельно. {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 {fields.map(([title,description])=>
  • )}
    ; })} - {!Object.keys(values).length&&

    Прочитайте значения для подключённых контроллеров.

    } + {!Object.keys(values).length&&Прочитайте значения для подключённых контроллеров.}
    ; } diff --git a/plugins/vesc/frontend/src/VescLink.tsx b/plugins/vesc/frontend/src/VescLink.tsx index 1317b63e..b8d9be90 100644 --- a/plugins/vesc/frontend/src/VescLink.tsx +++ b/plugins/vesc/frontend/src/VescLink.tsx @@ -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 void check()}>Проверить связь}> - {busy&&

    Измеряется время ответа контроллеров.

    } - {result&&<>

    {text}

    {Object.entries(result.devices).map(([id,item])=>
  • Измеряется время ответа контроллеров.} + {result&&<>{text}{Object.entries(result.devices).map(([id,item])=>
  • )}
    }
    ; } diff --git a/plugins/vesc/frontend/src/VescLogAnalysis.tsx b/plugins/vesc/frontend/src/VescLogAnalysis.tsx new file mode 100644 index 00000000..840ff3e3 --- /dev/null +++ b/plugins/vesc/frontend/src/VescLogAnalysis.tsx @@ -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(null),[name,setName]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false); + const [keys,setKeys]=useState([]),[from,setFrom]=useState(0),[to,setTo]=useState(0),[fftKey,setFftKey]=useState(''),[fftEnabled,setFftEnabled]=useState(false); + const input=useRef(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
    Сохранённые данные}> + {const file=e.target.files?.[0];e.target.value='';if(file)void open(file);}}/> +
    {log&&}
    + {error&&{error}} + До 4 МиБ и 20 000 строк. Поддерживаются Sample Data, RT CSV и Log Analysis CSV VESC Tool. Пустые ячейки остаются пропусками. При закрытии раздела журнал удаляется из памяти. Импорт не меняет живую телеметрию и настройки контроллера. + {log&&
  • } +
    {log&&<> + + setFrom(Math.min(value,to))} formatValue={v=>`${(v/1000).toFixed(3)} с`}/> + setTo(Math.max(from,value))} formatValue={v=>`${(v/1000).toFixed(3)} с`}/> + {keys.map((key,i)=>
    + Используются последние 32–4096 измерений участка, число округляется вниз до степени двойки. Пропуски и неравномерный шаг блокируют расчёт. Верхняя частота — половина частоты измерений; журнал с частотой 2 Гц не позволяет анализировать быстрые процессы мотора. + {fft?.error&&{fft.error}} + {fft?.value&&{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}} + + {fft?.value&&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}/>} + }
    ; +} diff --git a/plugins/vesc/frontend/src/VescMotor.tsx b/plugins/vesc/frontend/src/VescMotor.tsx index a5a94ddf..55368008 100644 --- a/plugins/vesc/frontend/src/VescMotor.tsx +++ b/plugins/vesc/frontend/src/VescMotor.tsx @@ -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(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 -

    Для вывешенных колёс без нагрузки. При команде с приёмника проверка прекращается; повторный запуск требует явного возврата управления.

    + Для вывешенных колёс без нагрузки. При команде с приёмника проверка прекращается; повторный запуск требует явного возврата управления. {setDirection(value);setClear(false);}}/> -

    Направление относительно настроек VESC. Перед обратным запуском дождитесь полной остановки всех моторов и подтвердите её.

    + Направление относительно настроек VESC. Перед обратным запуском дождитесь полной остановки всех моторов и подтвердите её. 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 плавно разгоняет мотор и удерживает заданную скорость.'}/> 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??'Максимальный ток разгона и удержания скорости. Прежние пределы сохраняются перед тестом и восстанавливаются после него.'}/> 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??'Отсчёт начинается после разгона и стабилизации скорости. Подготовка, разгон и остановки не входят в это время.'}/> -

    Время считается по скорости и тахометру VESC. Если мотор не разгонится за 15 секунд, потеряет скорость или сработает ограничение, результат покажет фактическое время и причину остановки. Показания контроллера нужно сопоставить с видимым вращением.

    - {limits?.stall_timeout_s&&

    При токе выше {limits.stall_current_a} А и отсутствии подтверждённого движения в течение {limits.stall_timeout_s} секунд проверка остановится.

    } -

    Все приводы должны быть вывешены, вращение свободно. Подтверждение требуется перед каждым запуском.

    + Время считается по скорости и тахометру VESC. Если мотор не разгонится за 15 секунд, потеряет скорость или сработает ограничение, результат покажет фактическое время и причину остановки. Показания контроллера нужно сопоставить с видимым вращением. + {limits?.stall_timeout_s&&При токе выше {limits.stall_current_a} А и отсутствии подтверждённого движения в течение {limits.stall_timeout_s} секунд проверка остановится.} + Все приводы должны быть вывешены, вращение свободно. Подтверждение требуется перед каждым запуском. - {blockedReason&&

    {blockedReason}

    } + {blockedReason&&{blockedReason}}
    {rc?: }
    - {result&&

    {result}

    } + {result&&{result}}
    ; } diff --git a/plugins/vesc/frontend/src/VescPackages.tsx b/plugins/vesc/frontend/src/VescPackages.tsx new file mode 100644 index 00000000..0fa3c704 --- /dev/null +++ b/plugins/vesc/frontend/src/VescPackages.tsx @@ -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} +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(null),running=useRef(false),mounted=useRef(true); + const [catalog,setCatalog]=useState(null),[selected,setSelected]=useState(null),[installed,setInstalled]=useState(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(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=(action:string,parameters:Record={},timeout=60000)=>perform(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){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');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('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('inspect',{id});if(mounted.current)setSelected(v);}); + async function importFile(event:ChangeEvent){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('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('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={})=>run(async()=>{clear();const v=await call(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
    + + + + Автор распространяет каталог по HTTP. Перед установкой проверьте описание, совместимость и состав выбранного пакета. + void importFile(e)}/> + + + {!supported&&Прошивка контроллера {status.identity?.version??'не определена'}. Каталог и импорт доступны; запись расширений поддерживается для VESC 6.00. Обновление каталога не меняет прошивку.} + + + + {installed&&{installed.installed?`${installed.installed.name} · ${installed.installed.id.slice(0,12)}`:installed.empty?'Lisp и QML приложения отсутствуют.':'Есть пользовательский код. Его пакет не определён.'}} + {pending&&Предыдущее изменение не подтверждено. Проверьте содержимое или восстановите исходную копию.} + {pending&&} + + + + {selected&& +
  • + {selected.description&&} + {selected.library?Библиотеку используют через import в проекте Lisp. Она не заменяет приложение контроллера. Примеры pkg@ и pkg:: из README работают в редакторе Lisp: вложения берутся из сохранённого каталога.:<> + {selected.compatible==null&&} + Запись заменит Lisp и QML приложения, включая пустые части пакета. Исходная копия сохраняется. Запуск здесь не выполняется; поведение после перезагрузки определяется прошивкой контроллера. + + {selected.fits===false&&Код не помещается во flash текущего профиля.} + } + + {selected.imported&&} +
    } + {selected?.qml_source&&} + {preview&& + {preview.package?`Запись: ${preview.package.name}.`:'Удаление кода приложения или восстановление пользовательского кода.'} При потере связи автоматического повтора не будет. Проверка результата и восстановление доступны выше. + + + } + {message&&{message}} + {catalog&& + setQuery(e.target.value)}/>({label,value:String(i)}))} onChange={onChange} disabled={disabled}/>; + const parsed=parseDraft(p,value),scale=p.type==='number'?(p.editor_scale||1):1; + return 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)}/>; +} diff --git a/plugins/vesc/frontend/src/VescQmlPreview.tsx b/plugins/vesc/frontend/src/VescQmlPreview.tsx new file mode 100644 index 00000000..3d407294 --- /dev/null +++ b/plugins/vesc/frontend/src/VescQmlPreview.tsx @@ -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; +export function VescQmlPreview(props:ReadProps&{source:string;active?:boolean}){ + const [frame,setFrame]=useState(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(null),pointer=useRef([]); + const call=(action:string,parameters:Record)=>perform(props.transport,props.device,'vesc.qml.'+action,parameters,30000); + const canvas=useRef(null),queue=useRef([]); + 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){ + 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('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',{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 + + + {broker?'Доступны показания, параметры мотора и приложения, PPM, ADC, Nunchuk, IMU и BMS по USB. Не более двух чтений за кадр. Фонового опроса нет. Запись, CAN-переадресация, движение и запуск измерений заблокированы.':snapshot?'При открытии однократно читаются конфигурация и показания. Дальше приложение использует этот снимок.':'Интерфейс открывается без чтения данных контроллера. Показания и ответы оборудования отсутствуют.'} Сеанс завершается после минуты без взаимодействия или пяти минут работы. +
    + {frame?.rendered&&frame.png&&<>Интерактивный интерфейс QML. Нажатия и ввод работают внутри приложения.{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&&Снимок данных: {new Date(frame.observed_at).toLocaleString('ru-RU')}.} + {frame.broker_status&&Чтений: {frame.broker_status.reads} · В очереди: {frame.broker_status.pending}. {frame.broker_status.observed_at?`Последний ответ: ${new Date(frame.broker_status.observed_at).toLocaleString('ru-RU')}.`:'Приложение ещё не запросило данные.'}} + setText(e.target.value)} maxLength={1024}/> + } + {!!frame?.discarded_commands&&Заблокировано запросов: {frame.discarded_commands}. {frame.blocked_codes?.length?`Коды: ${frame.blocked_codes.join(", ")}. `:""}Они не отправлялись. Запись настроек, запуск программ и управление выполняются в соответствующих разделах VESC.} + {!!frame?.warnings?.length&&} +
    ; +} diff --git a/plugins/vesc/frontend/src/VescRotorHallReview.tsx b/plugins/vesc/frontend/src/VescRotorHallReview.tsx new file mode 100644 index 00000000..39008d58 --- /dev/null +++ b/plugins/vesc/frontend/src/VescRotorHallReview.tsx @@ -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 + 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))}, + ]}/> + На прошивке 5.02 это преобразованный код Hall, не уровни H1–H3. Разбор не определяет обрыв датчика или заклинивание. Пропуски и делитель частоты могут скрыть переходы; угол FOC не является измерением поворота вала. + {present.some(p=>p.record.complete!==true)&&Полнота записи не подтверждена; положение пропусков неизвестно.} + + {details&&<> + Это смены переданного кода между отсчётами. В штатной 5.02 он получен через таблицу коммутации BLDC; в FOC эта таблица может быть не инициализирована. Коды 0 и 7, изменение нескольких битов или постоянный код не доказывают неисправность. По этому полю нельзя посчитать переключения физических входов Холла. + На FOC прошивки 5.02 угол — электрическая фаза управления, с шагом около 1,44°. Он не подтверждает поворот вала; для других режимов смысл нужно сверять с прошивкой. Шаг угла — кратчайшая разность соседних отсчётов через 0°; движение более чем на 180° между ними не восстанавливается. Остановка или заклинивание по этой таблице не устанавливаются. + {present.some(p=>p.record.complete!==true)&&Полнота хотя бы одной записи не подтверждена. Положение потерь в буфере 5.02 неизвестно; время и соседство отсчётов нельзя считать непрерывной картиной события.} + } + {present.length>1&&{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);}}/>{r&&}
    )}
    + {error&&{error}} + JSON с паспортом Mission Core или CSV Sample Data VESC Tool, до 4 МиБ и 2000 отсчётов на файл. Данные остаются в памяти этого окна не более пяти минут. Импорт ничего не запрашивает у контроллера. + {!!present.length&&({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&&Паспорт взят из файла и не удостоверяет текущий подключённый VESC. Время — от начала каждого буфера; две записи не синхронизированы. У неполного буфера 5.02 положение потери неизвестно, поэтому его временная ось приблизительна.} +
    {!!present.length&&<> + + {signals.map((key,i)=>setFilterValue('kind',v as SampleFilter['kind'])}/> + {filter.kind!=='none'&&<>setFilterValue('hamming',v==='true')}/>} + ({value,label}))}/> +
    =3&&+mode<=6?'Отсчётов до события':'Количество отсчётов'} type="number" min={1} max={2000} value={count} disabled={disabled||!!active||mode==='7'} onChange={e=>setCount(e.target.value)}/>setDecimation(e.target.value)}/>setTimeoutValue(e.target.value)}/>
    + Прошивка 5.02: до 2000 отсчётов; триггер возвращает весь буфер. Третий фазный ток вычисляется из первых двух. Сырые ADC и повтор отдельных пакетов недоступны. Время рассчитано по частоте в пакетах и указанному делителю. + {mode==='7'&&Укажите делитель, с которым был записан последний буфер. Контроллер не сообщает его возраст, UUID события и применённый делитель; принадлежность буфера новому событию не подтверждается.} +
    {state?.state==='stored_wait'&&}
    + Захват включается только этой кнопкой. Максимальное ожидание — 120 секунд. Данные хранятся в памяти до пяти минут; экспорт выполняется отдельно. Триггер ошибки срабатывает на ошибку VESC: подзаедание без ошибки само по себе его не включает. + {state&&{state.received} / {state.expected||'неизвестно'} отсчётов. {state.error??''}{state.state==='incomplete'?' Выборка неполная: разрыв нельзя точно расположить во времени, FFT отключён.':''}} + +
    {!!rows.length&& +
    +
    }; +} diff --git a/plugins/vesc/frontend/src/VescTools.tsx b/plugins/vesc/frontend/src/VescTools.tsx new file mode 100644 index 00000000..0fc46128 --- /dev/null +++ b/plugins/vesc/frontend/src/VescTools.tsx @@ -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={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} +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(props,'vesc.tools.read',vescStatus(props.device).tools_read_supported===true); + return v.value===props.tool)?.label} description="Снимок данных, декодированный ядром VESC Tool. Поддержка команды прошивкой не означает, что соответствующий модуль физически установлен." + actions={}> +
    + {!read.value?Данные ещё не прочитаны.:read.value.state==='unsupported'?Эта команда не поддерживается текущей прошивкой.:read.value.state==='no_response'?Ответ не получен. Проверьте наличие и подключение модуля.:<> + Прочитано {new Date(read.value.observed_at).toLocaleString('ru-RU')}. Нулевые значения сами по себе не подтверждают наличие или исправность датчика. + {Object.entries(read.value.values).filter(([key])=>key!=='mask').map(([key,value])=>
  • )}
    + } +
    +
    ; +} +export function VescTools(props:ReadProps){ + const [tool,setTool]=useState('adc'); + return
    ; +} diff --git a/plugins/vesc/frontend/src/VescTrends.tsx b/plugins/vesc/frontend/src/VescTrends.tsx new file mode 100644 index 00000000..22e28fc5 --- /dev/null +++ b/plugins/vesc/frontend/src/VescTrends.tsx @@ -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('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&&nowkey===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
    {state}}> +
    + ({value,label:value==='300'?'5 минут':`${value} секунд`}))} onChange={setWindow}/> + +
    +
    setExpanded(v=>!v)}>
    + + {[0,.5,1].map(f=>{number(view.high-f*(view.high-view.low))})} + {view.segments.map((line,i)=>line.length===1?:`${p.x},${p.y}`).join(' ')}/>)} + −{windowSeconds} с{paused?'Пауза':'Сейчас'} + + {!view.count&&В выбранном интервале нет измерений этой величины. Отсутствующие значения не заменяются нулями.} +
  • +
  • + Пропуски связи и смена USB-сеанса разделяют линию. Показаны полученные значения контроллера; отключённый температурный датчик может возвращать недостоверную температуру. Мощность питания рассчитана как напряжение × ток, PWM показан в процентах. +
    }> + CSV содержит все доступные величины, UUID, время измерения на борту, USB-сеанс и отдельные строки разрывов. Частота отображения — до 2 Гц; короткие события между полученными измерениями могут не попасть в график. +
    ; +} diff --git a/plugins/vesc/frontend/src/bmsView.ts b/plugins/vesc/frontend/src/bmsView.ts new file mode 100644 index 00000000..a921bac1 --- /dev/null +++ b/plugins/vesc/frontend/src/bmsView.ts @@ -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} +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){ + 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){ + 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}`})):[];} diff --git a/plugins/vesc/frontend/src/configuration.ts b/plugins/vesc/frontend/src/configuration.ts new file mode 100644 index 00000000..f782f54c --- /dev/null +++ b/plugins/vesc/frontend/src/configuration.ts @@ -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={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)&¶meter.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]:[];}); +} diff --git a/plugins/vesc/frontend/src/configurationOperation.ts b/plugins/vesc/frontend/src/configurationOperation.ts new file mode 100644 index 00000000..0e280af6 --- /dev/null +++ b/plugins/vesc/frontend/src/configurationOperation.ts @@ -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; diff --git a/plugins/vesc/frontend/src/controlTransport.ts b/plugins/vesc/frontend/src/controlTransport.ts new file mode 100644 index 00000000..dcdad795 --- /dev/null +++ b/plugins/vesc/frontend/src/controlTransport.ts @@ -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} +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):'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,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(),speeds=new Map(); + 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; +} diff --git a/plugins/vesc/frontend/src/diagnosticReview.ts b/plugins/vesc/frontend/src/diagnosticReview.ts new file mode 100644 index 00000000..20a1ba25 --- /dev/null +++ b/plugins/vesc/frontend/src/diagnosticReview.ts @@ -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; reports:Record; +} +export interface FaultEntry {code:string;fields:Record} +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};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=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]!reason||before[key]===null||after[key]===null?null:after[key]!-before[key]!; + return {reason,configEvents:delta('configEvents'),writeTimeouts:delta('writeTimeouts')}; +} diff --git a/plugins/vesc/frontend/src/editorFiles.ts b/plugins/vesc/frontend/src/editorFiles.ts new file mode 100644 index 00000000..176ed7ca --- /dev/null +++ b/plugins/vesc/frontend/src/editorFiles.ts @@ -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;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);} diff --git a/plugins/vesc/frontend/src/firmwareFiles.ts b/plugins/vesc/frontend/src/firmwareFiles.ts new file mode 100644 index 00000000..7af8f754 --- /dev/null +++ b/plugins/vesc/frontend/src/firmwareFiles.ts @@ -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)})); diff --git a/plugins/vesc/frontend/src/hallInputs.ts b/plugins/vesc/frontend/src/hallInputs.ts new file mode 100644 index 00000000..d0785f3e --- /dev/null +++ b/plugins/vesc/frontend/src/hallInputs.ts @@ -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[]}; +} diff --git a/plugins/vesc/frontend/src/logAnalysis.ts b/plugins/vesc/frontend/src/logAnalysis.ts new file mode 100644 index 00000000..e5a960ec --- /dev/null +++ b/plugins/vesc/frontend/src/logAnalysis.ts @@ -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;gap:boolean} +export interface VescLog {format:string;columns:LogColumn[];points:LogPoint[];duration:number;uuid:string|null;hardware:string|null;firmware:string|null} +const raw:Record={input_voltage:['Напряжение питания','В'],temp_mos_max:['Температура контроллера','°C'],temp_motor:['Температура мотора','°C'],current_motor:['Ток мотора','А'],current_in:['Ток питания','А'],erpm:['Электрические обороты','ERPM'],duty_cycle:['Заполнение PWM','%'],d_axis_current:['Ток FOC d','А'],q_axis_current:['Ток FOC q','А'],d_axis_voltage:['Напряжение FOC d','В'],q_axis_voltage:['Напряжение FOC q','В'],amp_hours_used:['Расход заряда','А·ч'],amp_hours_charged:['Возвращённый заряд','А·ч'],watt_hours_used:['Расход энергии','Вт·ч'],watt_hours_charged:['Возвращённая энергия','Вт·ч'],encoder_position:['Положение ротора','°'],fault_code:['Код ошибки','']}; +const fail=(message:string):never=>{throw new Error(message);}; +export function csvRecords(text:string,delimiter:string):string[][] { + const records:string[][]=[];let row:string[]=[],cell='',quoted=false,closed=false; + function field(){row.push(cell);cell='';closed=false;if(row.length>LOG_MAX_COLUMNS)fail('Слишком много колонок журнала.');} + function record(){field();if(row.some(v=>v!==''))records.push(row);row=[];if(records.length>LOG_MAX_ROWS+1)fail('Журнал превышает 20 000 строк.');} + for(let i=0;i4096)fail('Поле журнала слишком длинное.'); + } + if(quoted)fail('Незакрытые кавычки CSV.'); + if(cell||row.length||closed)record();return records; +} +const numeric=(text:string,line:number):number|null=>{ + if(text.trim()==='')return null; + if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(text.trim()))return fail(`Нечисловое значение в строке ${line}.`); + const n=Number(text);if(!Number.isFinite(n)||Math.abs(n)>1e15)fail(`Значение вне диапазона в строке ${line}.`);return n; +}; +export function parseVescLog(source:string):VescLog { + if(source.length>LOG_MAX_BYTES||new TextEncoder().encode(source).length>LOG_MAX_BYTES)fail('Максимальный размер CSV — 4 МиБ.'); + const text=source.replace(/^\uFEFF/,''); + const first=text.split(/\r?\n/,1)[0]; + const delimiter=first.includes(';')?';':','; + const records=csvRecords(text,delimiter); + if(records.length<2)fail('В журнале нет измерений.'); + // Native Tool logs terminate every row with a semicolon. + if(records.every(row=>row.at(-1)===''))records.forEach(row=>row.pop()); + const header=records[0];if(new Set(header).size!==header.length||header.some(h=>!h))fail('Пустые или повторяющиеся заголовки CSV.'); + if(header[0]==='T')return parseSampleCsv(records); + const core=header[0]==='plot_elapsed_s',rt=header[0]==='ms_today',rich=!core&&!rt&&header[0].includes(':'); + if(!core&&!rt&&!rich)fail('Поддерживаются CSV Mission Core и журналы VESC Tool.'); + const meta=header.map(h=>h.split(':')); + const time=core||rt?0:meta.findIndex(h=>h[0]==='t_day'); + const timeIndex=time>=0?time:meta.findIndex(h=>h[5]==='1'); + if(timeIndex<0)fail('В журнале не указана временная колонка.'); + if(rich&&!['s','ms','сек','с',''].includes(meta[timeIndex][2]??''))fail('Единица временной колонки должна быть s или ms.'); + const timeScale=rt||(rich&&meta[timeIndex][2]==='ms')?1:1000; + const index=(key:string)=>header.indexOf(key); + const stateIndex=index('state'),sessionIndex=index('usb_session'),sourceIndex=index('source_instance'),uuidIndex=index('uuid'); + if(core&&[stateIndex,sessionIndex,sourceIndex,uuidIndex,index('sample_utc')].some(v=>v<0))fail('В CSV Mission Core отсутствуют сведения об источнике.'); + const columns:LogColumn[]=[],indices:number[]=[]; + header.forEach((h,i)=>{ + if(i===timeIndex||core&&!h.includes(' ['))return; + const parts=meta[i],key=rich?parts[0]:h; + if(rich&&parts[5]==='1')return; + const match=core?/^(.*) \[(.*)\]$/.exec(h):null; + columns.push({key,label:rich?parts[1]||key:match?.[1]??raw[key]?.[0]??key,unit:rich?parts[2]??'':match?.[2]??raw[key]?.[1]??''});indices.push(i); + }); + if(!columns.length||new Set(columns.map(c=>c.key)).size!==columns.length)fail('Журнал не содержит однозначных числовых колонок.'); + const identities=new Set(),canIds=new Set();let session='',previous=-Infinity,offset=0,start:number|undefined; + const points:LogPoint[]=[]; + for(let i=1;i=86400000)fail('Время ms_today выходит за пределы суток.'); + let at=clock!*timeScale+offset,rollover=false; + if(at18*3600000&&clock!<6*3600000){offset+=86400000;at+=86400000;rollover=true;}else fail(`Время идёт назад в строке ${i+1}.`);} + if(start===undefined)start=at; + const identity=core?row[uuidIndex]:'';if(identity)identities.add(identity.toLowerCase()); + const canIndex=index('vesc_id');if(rt&&canIndex>=0)canIds.add(row[canIndex]); + if(identities.size>1||canIds.size>1)fail('Журнал содержит разные контроллеры. Выберите журнал одного VESC.'); + const nextSession=core?row[sourceIndex]+'/'+row[sessionIndex]:''; + if(core&&!['sample','gap'].includes(row[stateIndex]))fail(`Неизвестное состояние строки ${i+1}.`); + const gap=core&&row[stateIndex]==='gap'; + if(rollover||(session&&session!==nextSession))points.push({at:at-start!,values:{},gap:true}); + const values:Record={}; + columns.forEach((column,c)=>{let value=numeric(row[indices[c]],i+1);if(rt&&column.key==='duty_cycle'&&value!==null)value*=100;values[column.key]=gap?null:value;}); + points.push({at:at-start!,values,gap});session=nextSession;previous=at; + } + if(!points.some(p=>Object.values(p.values).some(v=>v!==null)))fail('В журнале нет числовых измерений.'); + const unique=(key:string)=>{const n=index(key);if(n<0)return null;const values=new Set(records.slice(1).map(row=>row[n]).filter(Boolean));return values.size===1?[...values][0]:null;}; + return {format:core?'Mission Core':rt?'VESC Tool · RT':'VESC Tool · Log Analysis',columns,points,duration:points.at(-1)!.at,uuid:unique('uuid'),hardware:unique('hardware'),firmware:unique('firmware')}; +} +function parseSampleCsv(records:string[][]):VescLog { + const expected=['T','I1','I2','I3','V1','V2','V3','I_tot','V_zero','Phase']; + const header=records[0];if(expected.some((key,i)=>header[i]!==key)||header.slice(10).some(key=>!['Hall','Commutation','F_sw'].includes(key)))fail('Неизвестные колонки Sample Data.'); + if(records.length>2001)fail('Sample Data превышает 2000 отсчётов.'); + const labels:Record={I1:['Ток фазы 1','А'],I2:['Ток фазы 2','А'],I3:['Ток фазы 3','А'],V1:['Напряжение фазы 1','В'],V2:['Напряжение фазы 2','В'],V3:['Напряжение фазы 3','В'],I_tot:['Ток мотора','А'],V_zero:['Нулевая точка','В'],Phase:['Угол фазы (электрический)','°'],Hall:['Состояние Холла',''],Commutation:['Шаг коммутации',''],F_sw:['Частота до делителя','Гц']}; + const columns=header.slice(1).map(key=>({key,label:labels[key][0],unit:labels[key][1]})); + let previous=-1,start:number|undefined; + const points=records.slice(1).map((row,i)=>{ + // Tool 7.00 adds a trailing delimiter to data rows, but not the header. + if(row.length===header.length+1&&row.at(-1)==='')row=row.slice(0,-1); + if(row.length!==header.length)fail(`Число колонок изменилось в строке ${i+2}.`); + const seconds=numeric(row[0],i+2);if(seconds===null||seconds<0||seconds<=previous)return fail('Неверное время Sample Data.'); + start??=seconds;previous=seconds; + return {at:(seconds-start)*1000,values:Object.fromEntries(columns.map((c,j)=>[c.key,numeric(row[j+1],i+2)])),gap:false}; + }); + return {format:'VESC Tool · Sample Data',columns,points,duration:points.at(-1)!.at,uuid:null,hardware:null,firmware:null}; +} +export function spectrum(points:readonly LogPoint[],key:string,from:number,to:number){ + const selected=points.filter(p=>p.at>=from&&p.at<=to); + if(selected.length<32)fail('Для спектра нужно не менее 32 измерений.'); + const n=2**Math.floor(Math.log2(Math.min(selected.length,4096))),data=selected.slice(-n); + if(data.some(p=>p.gap||p.values[key]===null||p.values[key]===undefined))fail('В выбранном участке есть пропуски. Выберите непрерывный интервал.'); + const dt=(data.at(-1)!.at-data[0].at)/(n-1); + if(!(dt>0)||data.some((p,i)=>i>0&&Math.abs(p.at-data[i-1].at-dt)>dt*.01))fail('Шаг времени неравномерен. Спектр требует равномерных измерений (допуск 1%).'); + const real=new Float64Array(n),imag=new Float64Array(n); + const mean=data.reduce((sum,p)=>sum+p.values[key]!/n,0);let gain=0; + for(let i=0;i>1;for(;j&bit;bit>>=1)j^=bit;j^=bit;if(i({hz:i*rate/n,amplitude:Math.hypot(real[i],imag[i])*(i===0||i===n/2?1:2)/gain})); + const peak=bins.slice(1).reduce((best,v)=>v.amplitude>best.amplitude?v:best,bins[1]); + return {bins,rate,n,from:data[0].at,to:data.at(-1)!.at,peak}; +} diff --git a/plugins/vesc/frontend/src/model.ts b/plugins/vesc/frontend/src/model.ts index eeaa0249..7aad7b40 100644 --- a/plugins/vesc/frontend/src/model.ts +++ b/plugins/vesc/frontend/src/model.ts @@ -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']):Recordtypeof 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;indexto)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((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}; +} diff --git a/plugins/vesc/frontend/src/sampleReview.ts b/plugins/vesc/frontend/src/sampleReview.ts new file mode 100644 index 00000000..ca98c729 --- /dev/null +++ b/plugins/vesc/frontend/src/sampleReview.ts @@ -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{return v!==null&&typeof v==='object'&&!Array.isArray(v)?v as Record: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={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({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;i0; + for(let j=0;j0&&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||atinterval.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}; +} diff --git a/plugins/vesc/frontend/src/samples.ts b/plugins/vesc/frontend/src/samples.ts new file mode 100644 index 00000000..7c95f568 --- /dev/null +++ b/plugins/vesc/frontend/src/samples.ts @@ -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={idle:'Захват не запускался',armed:'Ожидание выборки',stored_wait:'Ожидание события; буфер на контроллере',receiving:'Получение выборки',complete:'Все ожидаемые отсчёты получены',incomplete:'Неполная выборка',timeout:'Срок ожидания истёк',cancelled:'Захват остановлен',unverified:'Последний буфер; событие не подтверждено',expired:'Буфер истёк'}; diff --git a/plugins/vesc/frontend/src/traceObserver.ts b/plugins/vesc/frontend/src/traceObserver.ts new file mode 100644 index 00000000..b7d8fa8c --- /dev/null +++ b/plugins/vesc/frontend/src/traceObserver.ts @@ -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; + constructor(private read:(signal:AbortSignal)=>Promise, + 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();} +} diff --git a/plugins/vesc/frontend/src/trends.ts b/plugins/vesc/frontend/src/trends.ts new file mode 100644 index 00000000..60eda076 --- /dev/null +++ b/plugins/vesc/frontend/src/trends.ts @@ -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>|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)||atFRESH_MS)this.gap(at-FRESH_MS); + at=Math.max(at,this.points.at(-1)?.at??at); + const values:Partial>={}; + 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'; +} diff --git a/plugins/vesc/frontend/src/useVescEditor.ts b/plugins/vesc/frontend/src/useVescEditor.ts new file mode 100644 index 00000000..c9e848dc --- /dev/null +++ b/plugins/vesc/frontend/src/useVescEditor.ts @@ -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(null),[result,setResult]=useState(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(action:string,parameters:Record,timeout=CONFIGURATION_OPERATION_TIMEOUT_MS):Promise{ + if(running.current||props.blocked||!available)return null; + running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null); + try{return await perform(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){ + setPreview(null);setResult(null); + const value=await execute('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('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('vesc.configuration.reconcile',{}); + if(mounted.current){setResult(value);await props.refresh();} + } + return {preview,result,busy,available,prepare,apply,reconcile,clear:()=>{setPreview(null);setResult(null);}}; +} diff --git a/plugins/vesc/frontend/src/useVescRead.ts b/plugins/vesc/frontend/src/useVescRead.ts new file mode 100644 index 00000000..a777f36f --- /dev/null +++ b/plugins/vesc/frontend/src/useVescRead.ts @@ -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(props:ReadProps,action:string,supported=true){ + const {device,transport,enabled,failure,blocked,onBusyChange}=props; + const [value,setValue]=useState(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={}){ + 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(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}; +} diff --git a/plugins/vesc/frontend/src/vesc.css b/plugins/vesc/frontend/src/vesc.css new file mode 100644 index 00000000..165c164c --- /dev/null +++ b/plugins/vesc/frontend/src/vesc.css @@ -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} diff --git a/plugins/vesc/native/bms_native.h b/plugins/vesc/native/bms_native.h new file mode 100644 index 00000000..4a83a8f0 --- /dev/null +++ b/plugins/vesc/native/bms_native.h @@ -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 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"); +} diff --git a/plugins/vesc/native/code_native.h b/plugins/vesc/native/code_native.h new file mode 100644 index 00000000..49b7b8b1 --- /dev/null +++ b/plugins/vesc/native/code_native.h @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include +#include "custom_native.h" +#include "codeloader.h" +#include + +// 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> imports(const QString &source) { + QList> out; QSet 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 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(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(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> ranges;QSet names; + for(int i=0;i0&&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(reinterpret_cast(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 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() 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 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 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 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 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}}; + } +}; diff --git a/plugins/vesc/native/config_edit.h b/plugins/vesc/native/config_edit.h new file mode 100644 index 00000000..7b1eb653 --- /dev/null +++ b/plugins/vesc/native/config_edit.h @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "config_export.h" +#include +#include + +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 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}}; +} diff --git a/plugins/vesc/native/custom_native.h b/plugins/vesc/native/custom_native.h new file mode 100644 index 00000000..6f9a638c --- /dev/null +++ b/plugins/vesc/native/custom_native.h @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include +#include "config_edit.h" +#include "bms_native.h" +#include +#include +#include + +// 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 static void wait(Setup setup, Send send, int ms=1800) { + QEventLoop loop; QTimer timeout; QObject owner; bool done=false; + timeout.setSingleShot(true); + std::function 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(reinterpret_cast(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 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() 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()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 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; + } +}; diff --git a/plugins/vesc/native/engine_main.cpp b/plugins/vesc/native/engine_main.cpp index 9f7d2f54..91e984e2 100644 --- a/plugins/vesc/native/engine_main.cpp +++ b/plugins/vesc/native/engine_main.cpp @@ -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 #include #include #include +#include #include #include #include @@ -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(); 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 &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(); 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); } }); diff --git a/plugins/vesc/native/firmware_image.h b/plugins/vesc/native/firmware_image.h new file mode 100644 index 00000000..8adab177 --- /dev/null +++ b/plugins/vesc/native/firmware_image.h @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "config_export.h" +#include + +// 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(raw.constData()); + const auto reset = qFromLittleEndian(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(raw.constData()+6), raw.size()-6) != qFromBigEndian(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}}; +} diff --git a/plugins/vesc/native/firmware_native.h b/plugins/vesc/native/firmware_native.h new file mode 100644 index 00000000..6a751072 --- /dev/null +++ b/plugins/vesc/native/firmware_native.h @@ -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 +#include +#include + +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{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 route; + FW_RX_PARAMS target=identity; + if(manifest.contains("can_id")) { + route=std::make_shared(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; + } +}; diff --git a/plugins/vesc/native/firmware_source.h b/plugins/vesc/native/firmware_source.h new file mode 100644 index 00000000..ef551e50 --- /dev/null +++ b/plugins/vesc/native/firmware_source.h @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "firmware_image.h" +#include "hexfile.h" +#include +#include +#include + +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 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 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}; +} diff --git a/plugins/vesc/native/offline_main.cpp b/plugins/vesc/native/offline_main.cpp index 91a7cd2a..d906ef79 100644 --- a/plugins/vesc/native/offline_main.cpp +++ b/plugins/vesc/native/offline_main.cpp @@ -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 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) { diff --git a/plugins/vesc/native/package_native.h b/plugins/vesc/native/package_native.h new file mode 100644 index 00000000..6042ea42 --- /dev/null +++ b/plugins/vesc/native/package_native.h @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "code_native.h" +#include +#include +#include +#include +#include + +class NativePackage { +public: + static QByteArray unpackBounded(const QByteArray &data) { + require(data.size()>=5&&data.size()<=1024*1024,"Package size exceeds bound"); + auto size=qFromBigEndian(reinterpret_cast(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(const_cast(data.constData()+4));z.avail_in=data.size()-4; + z.next_out=reinterpret_cast(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 fields; + while(atat&&end-at<=64&&end+5<=raw.size(),"Invalid package field"); + const auto name=raw.mid(at,end-at);const auto length=qFromBigEndian(reinterpret_cast(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 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 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(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> ranges;QSet names; + for(int i=0;i0&&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; + } +}; diff --git a/plugins/vesc/native/qml_broker.h b/plugins/vesc/native/qml_broker.h new file mode 100644 index 00000000..8aa53f34 --- /dev/null +++ b/plugins/vesc/native/qml_broker.h @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "config_export.h" +#include +#include +// Decode intent only. No raw QML payload is ever passed to a device transport. +static bool qmlReadCode(int code) { + return QList{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 pending;QSet 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;} +}; diff --git a/plugins/vesc/native/qml_interactive.h b/plugins/vesc/native/qml_interactive.h new file mode 100644 index 00000000..66b2ccdf --- /dev/null +++ b/plugins/vesc/native/qml_interactive.h @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include +#include +#include +#include +#include + +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 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"); + } +} diff --git a/plugins/vesc/native/qml_preview.cpp b/plugins/vesc/native/qml_preview.cpp new file mode 100644 index 00000000..0c1ff864 --- /dev/null +++ b/plugins/vesc/native/qml_preview.cpp @@ -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 +#include "qml_sandbox.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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("Vedder.vesc.commands",1,0,"Commands"); + qmlRegisterType("Vedder.vesc.configparams",1,0,"ConfigParams"); + qmlRegisterSingletonType("Vedder.vesc.utility",1,0,"Utility",[](QQmlEngine*,QJSEngine*)->QObject*{return new Utility;}); + qRegisterMetaType();qRegisterMetaType();qRegisterMetaType(); + QmlVescInterface vesc;vesc.brokerConnected=broker;vesc.setLoadQmlUiOnConnect(false);vesc.ignoreCanChange(broker); + qmlRegisterSingletonInstance("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 object(component.create());require(bool(object),"QML could not be created"); + auto item=qobject_cast(object.get()); + if(!item) {auto rootWindow=qobject_cast(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(¬ifier,&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" diff --git a/plugins/vesc/native/qml_sandbox.h b/plugins/vesc/native/qml_sandbox.h new file mode 100644 index 00000000..90f23e4c --- /dev/null +++ b/plugins/vesc/native/qml_sandbox.h @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +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 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(filter.size()),filter.data()}; + if(prctl(PR_SET_SECCOMP,SECCOMP_MODE_FILTER,&program)) throw std::runtime_error("Cannot restrict QML system calls"); +} diff --git a/plugins/vesc/native/qml_vesc_interface.h b/plugins/vesc/native/qml_vesc_interface.h new file mode 100644 index 00000000..f9454fea --- /dev/null +++ b/plugins/vesc/native/qml_vesc_interface.h @@ -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(); } +}; diff --git a/plugins/vesc/native/sample_data.h b/plugins/vesc/native/sample_data.h new file mode 100644 index 00000000..afefc6c6 --- /dev/null +++ b/plugins/vesc/native/sample_data.h @@ -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 +#include +#include +#include + +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 +#include + +// 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 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=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}}; +} diff --git a/plugins/vesc/native/test-fixtures/NOTICE b/plugins/vesc/native/test-fixtures/NOTICE new file mode 100644 index 00000000..dc9effaa --- /dev/null +++ b/plugins/vesc/native/test-fixtures/NOTICE @@ -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. diff --git a/plugins/vesc/native/test-fixtures/bms-settings.xml b/plugins/vesc/native/test-fixtures/bms-settings.xml new file mode 100644 index 00000000..7f6c7993 --- /dev/null +++ b/plugins/vesc/native/test-fixtures/bms-settings.xml @@ -0,0 +1,817 @@ + + + + + none + 3 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">TODO</p></body></html> + + main_config_t + 0 + + + VESC BMS + 0 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">This is the VESC BMS. Some hw-specific info will be added here.</span></p></body></html> + + + + BMS ID + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">BMS ID. Used to identify this VESC BMS on the CAN-bus.</span></p></body></html> + CONF_CONTROLLER_ID + 1 + 0 + 255 + -1 + 0 + 1 + 104 + + 1 + + + CAN Status Rate + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">Send status messages on the CAN-bus at this rate.</span></p></body></html> + CONF_SEND_CAN_STATUS_RATE_HZ + 1 + 0 + 2000 + 0 + 0 + 1 + 10 + Hz + 5 + + + CAN Baud Rate + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">CAN-bus baud rate.</span></p></body></html> + CONF_CAN_BAUD_RATE + 2 + CAN_BAUD_125K + CAN_BAUD_250K + CAN_BAUD_500K + CAN_BAUD_1M + CAN_BAUD_10K + CAN_BAUD_20K + CAN_BAUD_50K + CAN_BAUD_75K + + + Balancing Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">Cell Balancing Mode. Options:</span></p> +<p style="-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';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif'; font-weight:600;">BALANCE_MODE_DISABLED</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">Do not balance cells at all.</span></p> +<p style="-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';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif'; font-weight:600;">BALANCE_MODE_CHARGING_ONLY</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">Only balance while charging.</span></p> +<p style="-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';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif'; font-weight:600;">BALANCE_MODE_DURING_AND_AFTER_CHARGING</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">Balance cells during charging and after charging has finished. Balancing will stop as soon as the </span><span style=" font-family:'Sans Serif'; font-style:italic;">balance_max_current</span><span style=" font-family:'Sans Serif';"> is exceeded.</span></p> +<p style="-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';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif'; font-weight:600;">BALANCE_MODE_ALWAYS</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">Always allow balancing.</span></p></body></html> + CONF_BALANCE_MODE + 2 + BALANCE_MODE_DISABLED + BALANCE_MODE_CHARGING_ONLY + BALANCE_MODE_DURING_AND_AFTER_CHARGING + BALANCE_MODE_ALWAYS + + + Number of Cells + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Number of cells in series.</p></body></html> + CONF_CELL_NUM + 1 + 0 + 1000 + 0 + 0 + 1 + 12 + + 4 + + + First Cell Index + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Channel of the first cell.</p></body></html> + CONF_CELL_FIRST_INDEX + 1 + 0 + 1000 + 0 + 0 + 1 + 0 + + 4 + + + Max Balance Channels + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum number of simultaneous balancing channels.</p></body></html> + CONF_MAX_BAL_CH + 1 + 0 + 1000 + 0 + 0 + 1 + 11 + + 4 + + + Distributed Balancing + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Enables distributed balancing between BMSes on the CAN-bus.</p></body></html> + CONF_DIST_BAL + 1 + + + Balance Starting Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Start balancing if cell voltage is this much above the minimum cell voltage.</p></body></html> + CONF_BALANCE_START + 3 + 1 + 0 + 99 + 0 + 0 + 0.001 + 0.015 + 1 + V + 9 + + + Balance End Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Stop balancing when cell voltage is this much above the minimum cell voltage.</p></body></html> + CONF_BALANCE_END + 3 + 1 + 0 + 99 + 0 + 0 + 0.001 + 0.008 + 1 + V + 9 + + + Charge Start Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Start charging when the maximum cell voltage is below this voltage.</p></body></html> + CONF_CHARGE_START + 3 + 1 + 0 + 99 + 0 + 0 + 0.01 + 4.16 + 1 + V + 9 + + + Charge End Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">End charging when the maximum cell voltage is above this voltage.</p></body></html> + CONF_CHARGE_END + 3 + 1 + 0 + 99 + 0 + 0 + 0.01 + 4.21 + 1 + V + 9 + + + Charge Minimum Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Only allow charging if all cells are above this voltage.</p></body></html> + CONF_CHARGE_MIN + 3 + 1 + 0 + 99 + 0 + 0 + 0.01 + 2 + 1 + V + 9 + + + Balance Minimum Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Only allow balancing if all cells are above this voltage.</p></body></html> + CONF_BALANCE_MIN + 3 + 1 + 0 + 99 + 0 + 0 + 0.01 + 3.5 + 1 + V + 9 + + + Balance Maximum Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Only allow balancing when the current magnitude is below this value.</p></body></html> + CONF_BALANCE_MAX_CURRENT + 3 + 1 + 0 + 999 + 0 + 0 + 0.01 + 3 + 1 + A + 9 + + + Minimum Counter Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The current must be above this magnitude for the Ah and Wh couters to run.</p></body></html> + CONF_MIN_CURRENT_AH_WH_CNT + 3 + 1 + 0 + 999 + 0 + 0 + 0.01 + 0.8 + 1 + A + 9 + + + Minimum Sleep Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Enter sleep mode when the current magnitude is below this value.</p></body></html> + CONF_MIN_CURRENT_SLEEP + 3 + 1 + 0 + 999 + 0 + 0 + 0.01 + 0.5 + 1 + A + 9 + + + Charger Detect Threshold Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Start charging when the voltage at the charge port is above this voltage.</p></body></html> + CONF_V_CHARGE_DETECT + 1 + 1 + 0 + 999 + 0 + 0 + 1 + 30 + 1 + V + 9 + + + Charge Max Temp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Disable charging when the cell temperature is above this value.</p></body></html> + CONF_T_CHARGE_MAX + 1 + 1 + 0 + 150 + -15 + 0 + 1 + 45 + 10 + °C + 7 + + + Current Measurement Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current measurement mode. Some BMS versions have optional current measurement, and can instead use the current reported by the VESCs on the CAN-bus.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">BMS</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use BMS current sensor. Might need configuration on hardware with an external PCB.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">VESC</span> <span style=" font-weight:600;">CAN</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use sum of currents reported by VESCs on the CAN-bus.</p></body></html> + CONF_I_MEASURE_MODE + 0 + BMS + VESC CAN + + + Current Shunt Resistance + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current Shunt Resistance.</p></body></html> + CONF_EXT_SHUNT_RES + 3 + 1000 + 0 + 100 + 0 + 0 + 0.1 + 0.0002 + 10 + mΩ + 9 + + + Current Shunt Amp Gain + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current shunt amplifier gain.</p></body></html> + CONF_EXT_SHUNT_GAIN + 3 + 1 + 0 + 10000 + 0 + 0 + 1 + 50 + 10 + + 9 + + + External Precharge R Div Top + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Precharge output top resistor value.</p></body></html> + CONF_EXT_PCH_R_TOP + 2 + 0.001 + 0 + 1e+07 + 0 + 0 + 1 + 520000 + 10 + kΩ + 9 + + + External Precharge R Div Bottom + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Precharge output bottom resistor value.</p></body></html> + CONF_EXT_PCH_R_BOTTOM + 2 + 0.001 + 0 + 1e+07 + 0 + 0 + 1 + 10000 + 10 + kΩ + 9 + + + Min Charge Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Stop charging and disable charge port when the charge current goes below this value.</p></body></html> + CONF_MIN_CHARGE_CURRENT + 2 + 1 + 0 + 999 + 0 + 0 + 0.01 + 0.5 + 1 + A + 9 + + + Max Charge Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum allowed charge current.</p></body></html> + CONF_MAX_CHARGE_CURRENT + 2 + 1 + 0 + 999 + 0 + 0 + 0.1 + 16 + 1 + A + 9 + + + Sleep Timeout Reset Time + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Go to sleep if no keep-awake event has occurred for longer time than this. Examples of keep-awake events are:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Balancing is active</li> +<li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Values are polled over CAN or USB</li> +<li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">USB cable plugged in</li> +<li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Charging is active</li> +<li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Other BMSes on the CAN-bus are charging or balancing</li> +<li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">VESC status messages are received</li> +<li style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current over <span style=" font-style:italic;">min_current_sleep</span> is drawn</li></ul></body></html> + CONF_SLEEP_TIMEOUT_MS + 0.001 + 0 + 9999999 + 0 + 0 + 1 + 240000 + s + 6 + + + SoC Filter Constant + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">State of Charge filter constant. Range 0.1 to 1 000 000. Lower values give more filtering. 1 000 000 disables filtering.</p></body></html> + CONF_SOC_FILTER_CONST + 1 + 1e+06 + 0 + 1 + 0 + 0 + 1 + 1e-05 + 1 + + 9 + + + Temp Bal Lim Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Start limiting the number of balancing channels at this temperature.</p></body></html> + CONF_T_BAL_LIM_START + 1 + 1 + 0 + 200 + 0 + 0 + 1 + 60 + 10 + °C + 7 + + + Temp Bal Lim End + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Disable all balancing channels above this temperature.</p></body></html> + CONF_T_BAL_LIM_END + 1 + 1 + 0 + 200 + 0 + 0 + 1 + 75 + 10 + °C + 7 + + + Charge Min Temp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Disable charging when the cell temperature is below this value.</p></body></html> + CONF_T_CHARGE_MIN + 1 + 1 + 0 + 150 + -45 + 0 + 1 + 0 + 10 + °C + 7 + + + Charge Temp Mon + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Enable temperature monitoring during charging. This can be disabled to allow charging when a temperature sensor is broken or missing.</p></body></html> + CONF_T_CHARGE_MON_EN + 1 + + + + controller_id + send_can_status_rate_hz + can_baud_rate + max_bal_ch + dist_bal + balance_mode + cell_num + cell_first_index + vc_balance_start + vc_balance_end + vc_charge_start + vc_charge_end + vc_charge_min + vc_balance_min + balance_max_current + min_current_ah_wh_cnt + min_current_sleep + v_charge_detect + t_charge_max + i_measure_mode + ext_shunt_res + ext_shunt_gain + ext_pch_r_top + ext_pch_r_bot + min_charge_current + max_charge_current + sleep_timeout_reset_ms + soc_filter_const + t_bal_lim_start + t_bal_lim_end + t_charge_min + t_charge_mon_en + + + + General + + General + + cell_num + cell_first_index + soc_filter_const + + + + Charging + + vc_charge_start + vc_charge_end + vc_charge_min + v_charge_detect + t_charge_min + t_charge_max + t_charge_mon_en + min_charge_current + max_charge_current + + + + Balancing + + balance_mode + vc_balance_start + vc_balance_end + vc_balance_min + balance_max_current + max_bal_ch + dist_bal + t_bal_lim_start + t_bal_lim_end + + + + Sleep + + min_current_sleep + sleep_timeout_reset_ms + + + + Counters + + min_current_ah_wh_cnt + + + + Communication + + controller_id + send_can_status_rate_hz + can_baud_rate + + + + External + + i_measure_mode + ext_shunt_res + ext_shunt_gain + ext_pch_r_top + ext_pch_r_bot + + + + + diff --git a/plugins/vesc/native/tools_native.h b/plugins/vesc/native/tools_native.h new file mode 100644 index 00000000..34e69f1b --- /dev/null +++ b/plugins/vesc/native/tools_native.h @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "config_export.h" +#include +#include +#include + +// Decoding and firmware compatibility belong to Commands. This adapter only +// projects its typed result; it never builds or parses vendor packets. +template static QJsonObject toolNumbers(const T &value) { + QJsonObject out; + for (int i=0; i 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}}; +} diff --git a/plugins/vesc/packaging/build_native_probe.py b/plugins/vesc/packaging/build_native_probe.py index 5e5c0e49..c4842a42 100644 --- a/plugins/vesc/packaging/build_native_probe.py +++ b/plugins/vesc/packaging/build_native_probe.py @@ -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") diff --git a/plugins/vesc/packaging/engine-profile.json b/plugins/vesc/packaging/engine-profile.json new file mode 100644 index 00000000..50222406 --- /dev/null +++ b/plugins/vesc/packaging/engine-profile.json @@ -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" + ] +} diff --git a/plugins/vesc/packaging/engine_profile.py b/plugins/vesc/packaging/engine_profile.py new file mode 100644 index 00000000..ec816b18 --- /dev/null +++ b/plugins/vesc/packaging/engine_profile.py @@ -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 \n#include \n#include \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() diff --git a/plugins/vesc/packaging/fetch_firmware_catalog.py b/plugins/vesc/packaging/fetch_firmware_catalog.py new file mode 100644 index 00000000..8e0a6a96 --- /dev/null +++ b/plugins/vesc/packaging/fetch_firmware_catalog.py @@ -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))) diff --git a/plugins/vesc/packaging/fetch_package_catalog.py b/plugins/vesc/packaging/fetch_package_catalog.py new file mode 100644 index 00000000..5325894e --- /dev/null +++ b/plugins/vesc/packaging/fetch_package_catalog.py @@ -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() diff --git a/plugins/vesc/packaging/firmware-catalog.NOTICE b/plugins/vesc/packaging/firmware-catalog.NOTICE new file mode 100644 index 00000000..8e8bb668 --- /dev/null +++ b/plugins/vesc/packaging/firmware-catalog.NOTICE @@ -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. diff --git a/plugins/vesc/packaging/firmware-catalog.json b/plugins/vesc/packaging/firmware-catalog.json new file mode 100644 index 00000000..4f5bc2af --- /dev/null +++ b/plugins/vesc/packaging/firmware-catalog.json @@ -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 + } + ] +} diff --git a/plugins/vesc/packaging/mission-core-vesc.service b/plugins/vesc/packaging/mission-core-vesc.service index 9a041776..68b1971e 100644 --- a/plugins/vesc/packaging/mission-core-vesc.service +++ b/plugins/vesc/packaging/mission-core-vesc.service @@ -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 diff --git a/plugins/vesc/packaging/native-runtime.json b/plugins/vesc/packaging/native-runtime.json index e155f7f2..b9b38439 100644 --- a/plugins/vesc/packaging/native-runtime.json +++ b/plugins/vesc/packaging/native-runtime.json @@ -2,15 +2,121 @@ "schema": "missioncore.vesc.native-runtime/v1", "upstream_version": "7.00", "upstream_commit": "01d5f10901116c311e3fb84d5a1541f663d3ce20", + "upstream_source_sha256": "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189", + "engine_contract": { + "rpc_version": 1, + "profile_sha256": "b22a241fdc952fbdb670bf4c961f61238e64878e237f56559c101deb15321583", + "control_transports": [ + "usb", + "can" + ], + "code_profiles": [ + { + "hardware_type": 0, + "major": 6, + "minor": 0, + "test_firmware": 0 + } + ], + "firmware_profiles": [ + { + "custom_configs": 0, + "hardware_type": 0, + "major": 5, + "minor": 2, + "test_firmware": 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_targets": [ + "usb", + "can", + "swd" + ], + "firmware_formats": [ + "bin", + "hex" + ], + "bms_profiles": [ + { + "major": 6, + "minor": 0 + } + ] + }, "os": "ubuntu-24.04-amd64", "file": "mission-core-vesc-native-runtime.tar.gz", - "bytes": 50354000, - "sha256": "4473819387682089a814a6c558065e3e6a4c2fe67266c0ed82ad49cea1444aad", - "engine_sha256": "10cfe14cd0eff561a06f0da33c940861b314de077de489908c90204904e4e590", + "bytes": 69068700, + "sha256": "8c08e24dc22faf7b8df9d46ff4eeb5a8450c9e78dc969df8499d76644974d3d8", + "engine_sha256": "7af96a3519b293cb3de1e574783db059b0b5eed2970e28a624d27d847734372e", "files": { "bin/mission-core-vesc-engine": { - "sha256": "10cfe14cd0eff561a06f0da33c940861b314de077de489908c90204904e4e590", - "bytes": 24801840 + "sha256": "7af96a3519b293cb3de1e574783db059b0b5eed2970e28a624d27d847734372e", + "bytes": 25165848 + }, + "bin/mission-core-vesc-qml-preview": { + "sha256": "537c8f8880ac63086dfebe415bb81e7a390c70e1d5d77187b0559752d31bc9cf", + "bytes": 24890176 + }, + "fonts/DejaVuSans-Bold.ttf": { + "sha256": "5c1247acef7f2b8522a31742c76d6adcb5569bacc0be7ceaa4dc39dd252ce895", + "bytes": 708920 + }, + "fonts/DejaVuSans.ttf": { + "sha256": "ae7b7855e115a5966d8b1b3f80f254ccc117ec86f9965e202ee2940453837280", + "bytes": 759720 + }, + "fonts/DejaVuSerif-Bold.ttf": { + "sha256": "847b33e13925f19ff87e4d934d6b3cf7cac35ce16424f6f670e40c2f377cf2df", + "bytes": 356668 + }, + "fonts/DejaVuSerif.ttf": { + "sha256": "8f2c103bfa3fd5de71f1b92b18f21906b5a26871fb7e19a9a4c9af539c3cc7ab", + "bytes": 380660 }, "lib/libGL.so.1": { "sha256": "67f471213576d225d38347a0b6d2a08a231980685301ff6461bd74d3994e5027", @@ -64,10 +170,22 @@ "sha256": "68bebbb6db95909aa2262aa2fa6cfd23547565faaa5bb72c49cfe027ac9caf0b", "bytes": 567600 }, + "lib/libQt5QmlWorkerScript.so.5": { + "sha256": "e1eb56364c337fa03d5b7beaa07551a96be44d84b001e27b40ca435853b90b48", + "bytes": 63720 + }, "lib/libQt5Quick.so.5": { "sha256": "a2d2e45f415baa2c9a251844dd45f67d1d10cf6f15c6270dd49c0d348a431260", "bytes": 5737928 }, + "lib/libQt5QuickControls2.so.5": { + "sha256": "3cb892116a07ae92c1f8d440242debad1b30772c097c0736b1907b08582a8f3d", + "bytes": 218144 + }, + "lib/libQt5QuickTemplates2.so.5": { + "sha256": "a9e4ef4fe25298f3c51c52b788effaa5cf177f1facc5771efbb27944442d2778", + "bytes": 1678856 + }, "lib/libQt5QuickWidgets.so.5": { "sha256": "8e3947729ac17448ed59a0a0a74960d9f09244a2d084c976b1c4af342f87d82e", "bytes": 92384 @@ -245,20 +363,60 @@ "bytes": 755864 }, "licenses/UPSTREAM-SOURCE.txt": { - "sha256": "ff2fbc975e47bffd1e3c488e14f1fbe417c83db82fb5ab41e16a9c1da96edb2a", - "bytes": 293 + "sha256": "45f353f09daec8a90a3d7b0b3b741689007f0728bb92abfd20da7894f77e1202", + "bytes": 314 }, "licenses/VESC-Tool-LICENSE": { "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", "bytes": 35149 }, + "licenses/bms_native.h": { + "sha256": "78c2f9e4a0edd89e18bddfe7b9bc45145fad7c4d40db758fca3eaee1d97ee464", + "bytes": 3070 + }, + "licenses/code_native.h": { + "sha256": "0e898342cec92c73a59e94e955085036ba858ca82345de2e1de912d05dc1fa3e", + "bytes": 14937 + }, + "licenses/config_edit.h": { + "sha256": "f3ea71c80aee3d6c2faccfa8901dceb0032ce318a2df7a1757ea273275ab13ee", + "bytes": 8102 + }, "licenses/config_export.h": { - "sha256": "f0c483aa27b9910bab1bff4f7baf66fe4077461e65a1d3e11169c4a722212756", - "bytes": 4724 + "sha256": "4509fb6ca56a1501fd9723725f0a9fadf3693772cca6569d4d94560aec77d795", + "bytes": 4723 + }, + "licenses/custom_native.h": { + "sha256": "6e748e38caaece5a627b84f4a840bf2a925aa4b5bb95658a0f5957af62cad68e", + "bytes": 7224 + }, + "licenses/engine-profile.json": { + "sha256": "cf93c398e0c12affaa09ac6e691d5b608890ffdd295337c5d6b439c45dcfee7c", + "bytes": 1486 }, "licenses/engine_main.cpp": { - "sha256": "e4b32dc5c9def71208d8daad830d5c47852f39f85a321713abc45dc15173b4fc", - "bytes": 21539 + "sha256": "cf74e72e802130ffb5be9f64c41de17d06755e87cc9c4e36934e2820dad90292", + "bytes": 39562 + }, + "licenses/engine_profile.h": { + "sha256": "dbfcd10ca8c4fde447e15233b5d55a45a16d58a151880bc8d98d358549a10479", + "bytes": 3455 + }, + "licenses/firmware_image.h": { + "sha256": "840706d8c5c19e1efa53899516dc0be96f74eade0268470918bfa06bafffc767", + "bytes": 1665 + }, + "licenses/firmware_native.h": { + "sha256": "47dfae15b7b96b768cb370fbb9ada718b51f232dbef32015706cdb009da28380", + "bytes": 6072 + }, + "licenses/firmware_source.h": { + "sha256": "25cc42ece1f64a61be29be2603b48630a1ca48c1ef773fc7c593398269cbd360", + "bytes": 5414 + }, + "licenses/fonts-dejavu-core.copyright": { + "sha256": "63d3ba759d12804c5b31a9d5940d855c1820d1f5999e6b0872eb1c7ff045fbc9", + "bytes": 3859 }, "licenses/gir1.2-glib-2.0.copyright": { "sha256": "b52574b109fb876dfa71dea7a98b8aee1bb583f6aa90c327d1e4dc0a1d59f211", @@ -576,6 +734,10 @@ "sha256": "5eeaeb1b6e029a0274e1573765bb0bae2926ef96a3679203faa4fd00fdaeaa88", "bytes": 3566 }, + "licenses/package_native.h": { + "sha256": "68bc3e92f9976eb06dc93629b9566a5fcd2fb4bbd5da44493cc62e7ddc62683e", + "bytes": 8166 + }, "licenses/pkgconf-bin.copyright": { "sha256": "676c75e54ff7e3b9892940fbf1b31763cb6f2a6527a5607a3640ac59a2441fba", "bytes": 7501 @@ -588,6 +750,62 @@ "sha256": "51fe4bbadf841c4e4d02ad97ba375bcde0ae11a51da62ae16fdcbe723d3cdad2", "bytes": 2444 }, + "licenses/qml-module-qtgraphicaleffects.copyright": { + "sha256": "1f42962e4335d6d3b6f8aae48e898696f093fa30b9d4abf562a0b9b6550a1a19", + "bytes": 4684 + }, + "licenses/qml-module-qtqml-models2.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/qml-module-qtqml.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/qml-module-qtquick-controls.copyright": { + "sha256": "e1c28bb480e3ca78324996d169e8f642d2dd7ad93f7396848be750a6fb39ecf8", + "bytes": 13464 + }, + "licenses/qml-module-qtquick-controls2.copyright": { + "sha256": "334854f9488a33d1211ded54478a35071369a4addaf86d2581820025b244ae03", + "bytes": 10979 + }, + "licenses/qml-module-qtquick-layouts.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/qml-module-qtquick-templates2.copyright": { + "sha256": "334854f9488a33d1211ded54478a35071369a4addaf86d2581820025b244ae03", + "bytes": 10979 + }, + "licenses/qml-module-qtquick-window2.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/qml-module-qtquick2.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/qml_broker.h": { + "sha256": "e5e6f494d2f6d43f7b6fe87afc8b0f2e3737299e4c90f35e60385c9ec59764fd", + "bytes": 2194 + }, + "licenses/qml_interactive.h": { + "sha256": "2c3ba012111e272ef787d65ac1ff489ed2c6be0852d93c0b43b4ae622426b752", + "bytes": 2543 + }, + "licenses/qml_preview.cpp": { + "sha256": "fd7fcfa8243066fd880ec2e9a2560dfd8be5d48b90b2d13ccabb5a00d3e28fa3", + "bytes": 12531 + }, + "licenses/qml_sandbox.h": { + "sha256": "c521f119c39a27b677620013303050f803fdd45db69c2eadad080e6df3f0a08f", + "bytes": 3734 + }, + "licenses/qml_vesc_interface.h": { + "sha256": "c25f849801001bc6c94a31926947850e773609b93ed446790047629014de726f", + "bytes": 682 + }, "licenses/qt5-qmake-bin.copyright": { "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", "bytes": 131975 @@ -636,6 +854,18 @@ "sha256": "334854f9488a33d1211ded54478a35071369a4addaf86d2581820025b244ae03", "bytes": 10979 }, + "licenses/sample_data.h": { + "sha256": "f03adc6b8a9d69baad6a0c3175f25f1c2acf2fe12a67a2f6b4bac3e417bb9736", + "bytes": 6147 + }, + "licenses/swd_native.h": { + "sha256": "b7a1dfaab849a56ca6eb953829805ed1a201154215f773b4dbeeb29b19ad9829", + "bytes": 3335 + }, + "licenses/tools_native.h": { + "sha256": "a01a98f28ee28b5f2d583449ef47af0aba6d8116be58e320f3322f6b7bb5e8cf", + "bytes": 2858 + }, "licenses/uuid-dev.copyright": { "sha256": "3492fb92cb56cf517d9a899828b4f989038421a38736e49e5525ffbd33196eab", "bytes": 23160 @@ -659,6 +889,3098 @@ "plugins/platforms/libqoffscreen.so": { "sha256": "f2f19a29e816c7e5c60fd52b9d3c1a214634c38e06cd2ffdf9fc88e9f0c49ffd", "bytes": 193880 + }, + "qml/QtGraphicalEffects/Blend.qml": { + "sha256": "92e90129041dc0c3d2436bb26d20a14ce0c92889bbd41bc2dfe8e681bf9fa217", + "bytes": 19292 + }, + "qml/QtGraphicalEffects/BrightnessContrast.qml": { + "sha256": "06f6e5631c11abf1325baa8bc1062853124cc7b9eedc3ade584614cfdee83321", + "bytes": 6391 + }, + "qml/QtGraphicalEffects/ColorOverlay.qml": { + "sha256": "9df6bee56d7ff66245bd85fa71047a3adeacf2ca05fe1b507cadf0ed3680d9e3", + "bytes": 4947 + }, + "qml/QtGraphicalEffects/Colorize.qml": { + "sha256": "e3efb696c39e5c383ce5a5ae0873dd5d9296898867e6c66515a050a0b7a76162", + "bytes": 7638 + }, + "qml/QtGraphicalEffects/ConicalGradient.qml": { + "sha256": "0d0ad50fccfb5f5d0b08df0a82ffeefb90815a3902bd11f259422d72f83e320e", + "bytes": 9931 + }, + "qml/QtGraphicalEffects/Desaturate.qml": { + "sha256": "5b9c4abfad41bf5cbd7ebc5f2e89d6d138585ae0ed358a7be57127915733f063", + "bytes": 4932 + }, + "qml/QtGraphicalEffects/DirectionalBlur.qml": { + "sha256": "563909b3db1b65a16e567bad7a20ef2cf6ba73bdf0ec145d521c88f8aa7fd95a", + "bytes": 10738 + }, + "qml/QtGraphicalEffects/Displace.qml": { + "sha256": "3c9aebbab7db3165efa30e9bb8f77918dab1bfafe56082db45b67fc7894d31c5", + "bytes": 7027 + }, + "qml/QtGraphicalEffects/DropShadow.qml": { + "sha256": "22c8757f09cd4cd1123964f7a663694c02a56eee66195df8161738019ea01448", + "bytes": 12144 + }, + "qml/QtGraphicalEffects/FastBlur.qml": { + "sha256": "ec6833b7f33091fee4b0e1d2f17f7de65fc142ed1482fa2756701f8c817bcfda", + "bytes": 13439 + }, + "qml/QtGraphicalEffects/GammaAdjust.qml": { + "sha256": "c382827c2f3599c03aa70f90e97f7cea0f0f40341150e65f7e3a840017b416c7", + "bytes": 6051 + }, + "qml/QtGraphicalEffects/GaussianBlur.qml": { + "sha256": "8bf2fc9c1365e1122b44c657a80921a1c741600d56614205a633b81fe0d8f18c", + "bytes": 13230 + }, + "qml/QtGraphicalEffects/Glow.qml": { + "sha256": "be39ef59442c546c1538319a9dd16f00e483b2b174f94f0553348aa3f1eb98cc", + "bytes": 9731 + }, + "qml/QtGraphicalEffects/HueSaturation.qml": { + "sha256": "30639658f5bd6bb983a5fe4eac5cb49244918f09312657bdb7dc3e585329a5b5", + "bytes": 7195 + }, + "qml/QtGraphicalEffects/InnerShadow.qml": { + "sha256": "3ce8b5ea5882dea563aa54d82d8a690aaf0e19799437eafd0c0c14d29108d058", + "bytes": 12473 + }, + "qml/QtGraphicalEffects/LevelAdjust.qml": { + "sha256": "2253699883b8294dbc355b4d4cf30620101d3f00b2c6f97873c6aea4343defc6", + "bytes": 15451 + }, + "qml/QtGraphicalEffects/LinearGradient.qml": { + "sha256": "1ddf18f72cbc51aa4e6837e286395cc0ee0d0ca04c42ba469774e9c626fdd85b", + "bytes": 10506 + }, + "qml/QtGraphicalEffects/MaskedBlur.qml": { + "sha256": "a16a6a9d1801f403a2eab05d9a04d66306f3801801d01a19b7ff7190f31108c4", + "bytes": 7589 + }, + "qml/QtGraphicalEffects/OpacityMask.qml": { + "sha256": "6ae8bc878bfd345cea4b6828fc8861b657c4baf3c34fd384856e61630f79ec76", + "bytes": 5423 + }, + "qml/QtGraphicalEffects/RadialBlur.qml": { + "sha256": "e086b7c17fd77f5b4f061ef6b49f1f1482a3429705a3174db77bdd7d1e25a6ea", + "bytes": 12029 + }, + "qml/QtGraphicalEffects/RadialGradient.qml": { + "sha256": "23ec0d4266cf7c54d94f97ae2716ab86940f9cc91e0103c02fad1f530ac54f4a", + "bytes": 13335 + }, + "qml/QtGraphicalEffects/RectangularGlow.qml": { + "sha256": "cd2615ec6aeee49cea962d1469c755997c1d4830191c246f0fe2d6f04e992514", + "bytes": 9036 + }, + "qml/QtGraphicalEffects/RecursiveBlur.qml": { + "sha256": "71c035a51ebf5088026870b21ebe64fd1368a96e07aa580908c4956953626c52", + "bytes": 11320 + }, + "qml/QtGraphicalEffects/ThresholdMask.qml": { + "sha256": "4a6179f3c9e72b4b34ed37f8460a9e2589089133b590430d8a80cf676f296f6c", + "bytes": 7247 + }, + "qml/QtGraphicalEffects/ZoomBlur.qml": { + "sha256": "3bcd36abbf9ca10c1dbcd7b010a5eb1d9f565a57523fe104aa0924d17612f7bb", + "bytes": 11454 + }, + "qml/QtGraphicalEffects/libqtgraphicaleffectsplugin.so": { + "sha256": "da221c77d458eef986c693fe6f7c7b90822e45f158fa3cfa4ec15ac636fdb5dd", + "bytes": 59992 + }, + "qml/QtGraphicalEffects/plugins.qmltypes": { + "sha256": "215f8d515840184ca84953ed05bedf76d924b23c69777941ff3edf56b29b6f60", + "bytes": 316 + }, + "qml/QtGraphicalEffects/private/DropShadowBase.qml": { + "sha256": "75f46cc7f7c5822c0f744223739fa938fdd2e4648c431d7be1c25cf3ca0013eb", + "bytes": 3703 + }, + "qml/QtGraphicalEffects/private/DropShadowBase.qmlc": { + "sha256": "436a2c512caa13be82b4535aa68a640d9f9006e47d67e75d2783b289a2f80763", + "bytes": 7424 + }, + "qml/QtGraphicalEffects/private/FastGlow.qml": { + "sha256": "dc4a0106c97b30ec1e25feac404e5d7ac5618cbfb609f4b7c81c6b860c1fefcf", + "bytes": 9630 + }, + "qml/QtGraphicalEffects/private/FastGlow.qmlc": { + "sha256": "f1451d38667a271bce84c6ef37b121b65aaf48ebd64deb1afa8ee4bfc71e44b6", + "bytes": 21704 + }, + "qml/QtGraphicalEffects/private/FastInnerShadow.qml": { + "sha256": "86656ef613fd9aba12c7bba4741c6404a59b9169fabe05510f07f5ff4678378d", + "bytes": 9764 + }, + "qml/QtGraphicalEffects/private/FastInnerShadow.qmlc": { + "sha256": "9c6e4f32bc331a9fabbd53cc5213053f4c94998b4a01e2f62c9db204b3066c35", + "bytes": 22064 + }, + "qml/QtGraphicalEffects/private/FastMaskedBlur.qml": { + "sha256": "a7606d5d114627905c78f6a42d03b70c3168f56a80262fdf69baa35558949e41", + "bytes": 7669 + }, + "qml/QtGraphicalEffects/private/FastMaskedBlur.qmlc": { + "sha256": "2d277b93c7a83e7f31285e78b8ad6b4112a73f4bdc3b5af658faa05c1e52eda5", + "bytes": 20108 + }, + "qml/QtGraphicalEffects/private/GaussianDirectionalBlur.qml": { + "sha256": "594ac2366b65e9b8321242d0d36b92293c0d60e3a638be0a15c97de9514a263e", + "bytes": 12463 + }, + "qml/QtGraphicalEffects/private/GaussianDirectionalBlur.qmlc": { + "sha256": "bbed991891d192b063eb65f27c0691cb8a95245382dff74b0ad61a8535c0ee14", + "bytes": 26696 + }, + "qml/QtGraphicalEffects/private/GaussianGlow.qml": { + "sha256": "5a8e1826b69bfe72f445ff304e89ab4f0bd24c06ca6995b0df643474fb0223a7", + "bytes": 3725 + }, + "qml/QtGraphicalEffects/private/GaussianGlow.qmlc": { + "sha256": "05cd440539faf37bdca38dd8e8291f43ced7f7b98c880c81d32d455492364771", + "bytes": 7616 + }, + "qml/QtGraphicalEffects/private/GaussianInnerShadow.qml": { + "sha256": "88b96d23014e2bd3957c181e1b7622e532b630faf596ff9cb8da178a457280d7", + "bytes": 4222 + }, + "qml/QtGraphicalEffects/private/GaussianInnerShadow.qmlc": { + "sha256": "3fd744a158d1bdb58b8a3fd2fe8b6b219365f12c7ff45580c44268834fa8b568", + "bytes": 9408 + }, + "qml/QtGraphicalEffects/private/GaussianMaskedBlur.qml": { + "sha256": "32fd9aded4126278c31b5b93130233e5b93c42c4cd0191adcc1a09ca742ea60f", + "bytes": 3937 + }, + "qml/QtGraphicalEffects/private/GaussianMaskedBlur.qmlc": { + "sha256": "1d5759faa1bf36251b041b4a8d585924d411c910a8b4d8e1b0cd095f6b098c4c", + "bytes": 7908 + }, + "qml/QtGraphicalEffects/private/libqtgraphicaleffectsprivate.so": { + "sha256": "90b5c8319a564a88bdc744d2a13a19405e5a16ffac01c04e5cfd4435df3f415b", + "bytes": 64824 + }, + "qml/QtGraphicalEffects/private/qmldir": { + "sha256": "9bc21a10093ae9a83a7aae75ca4b8a468b333356b02642c21047a3f396dd5bb6", + "bytes": 435 + }, + "qml/QtGraphicalEffects/qmldir": { + "sha256": "b11f92e5b896191d58d53c3c32e94efe04028437d9091c89f8e77fbc7e817a9a", + "bytes": 985 + }, + "qml/QtQml/Models.2/libmodelsplugin.so": { + "sha256": "db5847a7bd27977e1364386712fe3128e58e4844b02b42d8b1999cb52b69739d", + "bytes": 18656 + }, + "qml/QtQml/Models.2/plugins.qmltypes": { + "sha256": "d1758ab33c5741f70a7ab6e1dc3de1eff858c90e1c91f45cdefb6b0bccd2b75d", + "bytes": 31557 + }, + "qml/QtQml/Models.2/qmldir": { + "sha256": "a9e5f012654bfe629f8d465071a399feaa4132fbc31841f96db7990df711ec30", + "bytes": 86 + }, + "qml/QtQml/libqmlplugin.so": { + "sha256": "59e368079227e8c6a9f5a6ccb88abcd19a87111cf178e11521c5f4b6168a0a13", + "bytes": 18656 + }, + "qml/QtQml/plugins.qmltypes": { + "sha256": "fdc6e0fd96866417155fca9ae023339b89e40cab3e9c9e593e1c6ecac2a82821", + "bytes": 8979 + }, + "qml/QtQml/qmldir": { + "sha256": "4e9ded07b2a7977c7d963369ef10cd1390fea1de00cb86c2e2444cb0b6a21aae", + "bytes": 136 + }, + "qml/QtQuick/Controls/ApplicationWindow.qml": { + "sha256": "a48cdc370ee30e3ac8ea9d691bbfdda86af737c116a4f889e14f7f1e5efa939e", + "bytes": 9810 + }, + "qml/QtQuick/Controls/ApplicationWindow.qmlc": { + "sha256": "6b49d6879b9f51d70d23388d4e4ac88f98ce352f400410c4d470d5915f6db0c6", + "bytes": 14112 + }, + "qml/QtQuick/Controls/BusyIndicator.qml": { + "sha256": "5d5155fc1fac22de75cea71905fcdd25f1f32a380679953f03c11390a75a2389", + "bytes": 3087 + }, + "qml/QtQuick/Controls/BusyIndicator.qmlc": { + "sha256": "6a57bd3e2d871ae943a89c7d5eb6fc58070c7086d0d52afd78570f60a443cd86", + "bytes": 1840 + }, + "qml/QtQuick/Controls/Button.qml": { + "sha256": "e7cbd5154a5942a067defc3a899e0c76195199d8103853cf8572eb11b9d10ffe", + "bytes": 4588 + }, + "qml/QtQuick/Controls/Button.qmlc": { + "sha256": "708e96365aeef2b5bc8b4712a5b9a821478028363a21b35c6a9ed3ca45935f9b", + "bytes": 6288 + }, + "qml/QtQuick/Controls/Calendar.qml": { + "sha256": "b4921ce869d01227621108fb4b2bb433ef5594081475a47d2c18f3c398cbc6e0", + "bytes": 13597 + }, + "qml/QtQuick/Controls/Calendar.qmlc": { + "sha256": "53707fa1a6909415051e0457a0ee461f2560ae1247a45eb10351cc688580af27", + "bytes": 11360 + }, + "qml/QtQuick/Controls/CheckBox.qml": { + "sha256": "11890a7703be587bedda7ec74a56725e4e51acd873bfb8f723fe4c9f31191ad4", + "bytes": 7020 + }, + "qml/QtQuick/Controls/CheckBox.qmlc": { + "sha256": "799d1687b382ba23fa8fa500e9bebe2082398157a44f35a74cf0b5a5a7525258", + "bytes": 5416 + }, + "qml/QtQuick/Controls/ComboBox.qml": { + "sha256": "3cb9087daf72d5274a025ca5b4e1965b7aa721c34b714d7f1d7bcb918e8df997", + "bytes": 25834 + }, + "qml/QtQuick/Controls/ComboBox.qmlc": { + "sha256": "8cbaba9ffa03679147c28c3bfabbc2784b74d2eb4e1b546aedbd529c37aa5c2b", + "bytes": 32600 + }, + "qml/QtQuick/Controls/GroupBox.qml": { + "sha256": "e4fcf39db77f309a1b672ae5e9da261f124657f68f1dbe9ff4f79e87af39e5d2", + "bytes": 9048 + }, + "qml/QtQuick/Controls/GroupBox.qmlc": { + "sha256": "45ccf36d1554592b46807815850ae676e3113643d821832e441bae644bca209f", + "bytes": 11916 + }, + "qml/QtQuick/Controls/Label.qml": { + "sha256": "9f48486259adfacfaef386b46b6ce7dcceb0a447c732b9b5a1b944bd3cefd908", + "bytes": 3120 + }, + "qml/QtQuick/Controls/Label.qmlc": { + "sha256": "825493606dec6a2624bae8e4cae6bca6f70e2f03efc29a720b5aed8b1f20a4f1", + "bytes": 2456 + }, + "qml/QtQuick/Controls/Menu.qml": { + "sha256": "5a563bcd009f033bf3c81c3adf60c6e8849ef72354c320a37de02204409ac265", + "bytes": 5267 + }, + "qml/QtQuick/Controls/Menu.qmlc": { + "sha256": "c67cffe9dcfb44805f381186d9d80aba3e22e30371d179cad5ff23a938af05c7", + "bytes": 6360 + }, + "qml/QtQuick/Controls/MenuBar.qml": { + "sha256": "cf8143bbe6aa6283f15fd49164e820e745eabe88c5be728ebe35e01b69928592", + "bytes": 12732 + }, + "qml/QtQuick/Controls/MenuBar.qmlc": { + "sha256": "075fb20515c2954aa714d1b55d8c518100a02a19fb75f1d9e87b18c7c5a28b21", + "bytes": 25688 + }, + "qml/QtQuick/Controls/Private/AbstractCheckable.qml": { + "sha256": "0f9fc058c17a035e7c643cae27e0f2dd2609d7caaeec981fb0a86611cff0cee0", + "bytes": 5872 + }, + "qml/QtQuick/Controls/Private/AbstractCheckable.qmlc": { + "sha256": "00e762a402fcd3381ffd2861227c379c74dac679e7d5bafecd4407c894dc1eba", + "bytes": 8988 + }, + "qml/QtQuick/Controls/Private/BasicButton.qml": { + "sha256": "65db46544ff512addc1050ebe1b831b39b54c19a8df3e0ae7f2a451340e73576", + "bytes": 8057 + }, + "qml/QtQuick/Controls/Private/BasicButton.qmlc": { + "sha256": "e2e8bd24ba147b96d0cc2325b66be30a7f41e955f9d3875342d656860e4ee9b7", + "bytes": 14344 + }, + "qml/QtQuick/Controls/Private/BasicTableView.qml": { + "sha256": "50ff5398b395850e4f05a0a9bb169cd18e32ee7bb5621de94311b6ba07560d10", + "bytes": 32410 + }, + "qml/QtQuick/Controls/Private/BasicTableView.qmlc": { + "sha256": "85a08a6c33eb9cf485a0882aab89bf673ae292b484a83e13feae7704dbf0448d", + "bytes": 49524 + }, + "qml/QtQuick/Controls/Private/CalendarHeaderModel.qml": { + "sha256": "5ff284da75d67bf98f496ad0b515d201958b7281d41ac9b47ce5491ad17fe014", + "bytes": 3732 + }, + "qml/QtQuick/Controls/Private/CalendarHeaderModel.qmlc": { + "sha256": "9589b9c4e64ed323eb4f739b989cac4ae58fb4f69e65add116ce3591c07bd160", + "bytes": 4668 + }, + "qml/QtQuick/Controls/Private/CalendarUtils.js": { + "sha256": "52bb237125099dc7ae448d462e4571f06bb7fd4d8a2ebc83bd4a746b3277a0b5", + "bytes": 5577 + }, + "qml/QtQuick/Controls/Private/CalendarUtils.jsc": { + "sha256": "88a73a5b3df8fe714462eae1b85e87735141b07e30860f6042ee0811ff60f2f8", + "bytes": 3384 + }, + "qml/QtQuick/Controls/Private/ColumnMenuContent.qml": { + "sha256": "90db5d6594c639b6467205d98b01fe7b95103892081e5650ea87cbc3439970a8", + "bytes": 9165 + }, + "qml/QtQuick/Controls/Private/ColumnMenuContent.qmlc": { + "sha256": "73a78d0aec215681eaaf33b43da4d1d35b2740be9575d2b2ed74aeff7bf20259", + "bytes": 21192 + }, + "qml/QtQuick/Controls/Private/ContentItem.qml": { + "sha256": "b4a6c972da0e1a4c09f9c8be10c06ef0a6d7e84d5fdaf2a05071021dbd6f7020", + "bytes": 4503 + }, + "qml/QtQuick/Controls/Private/ContentItem.qmlc": { + "sha256": "66db9ef1ce608c06a2c1293c0d6134864e4b4b6261bf1427140f9f335e226a31", + "bytes": 6476 + }, + "qml/QtQuick/Controls/Private/Control.qml": { + "sha256": "94b53b275a2e480f09dc146c22a85da676e2164fb927e29699d0fdca9c643f7a", + "bytes": 3297 + }, + "qml/QtQuick/Controls/Private/Control.qmlc": { + "sha256": "fbb8744f4bb56ce91bdcebd2f4090b16ff5cd8bebcb403fd569ac85ac272540f", + "bytes": 4768 + }, + "qml/QtQuick/Controls/Private/EditMenu.qml": { + "sha256": "b8f0e90d1cab7feba432e4105b481b5b80d49ea454a1913d66754d40e7a716db", + "bytes": 3295 + }, + "qml/QtQuick/Controls/Private/EditMenu.qmlc": { + "sha256": "d7aafa3abafac71d379b0d17dc2b9ec9e55b26c7b758921ad4862ddbe8b49275", + "bytes": 4436 + }, + "qml/QtQuick/Controls/Private/EditMenu_base.qml": { + "sha256": "cc4e0116b25d6a3f04724ab48156f7d0a8e42764de7e7fbb3aca86c74821b1ca", + "bytes": 5816 + }, + "qml/QtQuick/Controls/Private/EditMenu_base.qmlc": { + "sha256": "ca850763368dc3873c7c15a0c1a0bb942edbcdab4ae6bad20daf206c296f1d0f", + "bytes": 14016 + }, + "qml/QtQuick/Controls/Private/FastGlow.qml": { + "sha256": "4e420a28e66b94577fa58d8442b7d0cb1f1da54827daaf230a440abf6074a7c5", + "bytes": 9500 + }, + "qml/QtQuick/Controls/Private/FastGlow.qmlc": { + "sha256": "66ec0c7e3fa4940ccfaa8ecb938b1c392ea07c184b77ab666ea343a83f5b096a", + "bytes": 21368 + }, + "qml/QtQuick/Controls/Private/FocusFrame.qml": { + "sha256": "ef35de4e7eedc923d13cd066de5f0c3b2da4db08053e64f37482493c510e6384", + "bytes": 2586 + }, + "qml/QtQuick/Controls/Private/FocusFrame.qmlc": { + "sha256": "d76836e331454856ecadc3ad72e7565e18983d42c97d7f017809ebf2408906f1", + "bytes": 3948 + }, + "qml/QtQuick/Controls/Private/HoverButton.qml": { + "sha256": "45111696e450b94db9b647b329a38774d0d9b0043adb41ff143007291ba0b033", + "bytes": 2852 + }, + "qml/QtQuick/Controls/Private/HoverButton.qmlc": { + "sha256": "6c1224daceb78288c32fa27583c3805e1b5f24071ee855a485b5cea2282b52d7", + "bytes": 5640 + }, + "qml/QtQuick/Controls/Private/MenuContentItem.qml": { + "sha256": "7402790c709b5ca837a431a32f0209f6350759eff75000732b429c4e7e7c68bd", + "bytes": 10904 + }, + "qml/QtQuick/Controls/Private/MenuContentItem.qmlc": { + "sha256": "6f529be834b87ac2ba33b3ade0e064ca3d6aa3bed3911543eb8a4eca6a895b32", + "bytes": 26160 + }, + "qml/QtQuick/Controls/Private/MenuContentScroller.qml": { + "sha256": "32873ee2b5fa380a53d637216851c339ee54d83efa96586459401ef411dce021", + "bytes": 3073 + }, + "qml/QtQuick/Controls/Private/MenuContentScroller.qmlc": { + "sha256": "83b222421d9dc79a80b6d9ecf6722111bf9879a29743c4984991cc79969ebdd0", + "bytes": 5160 + }, + "qml/QtQuick/Controls/Private/MenuItemSubControls.qml": { + "sha256": "21468f7227f9a0ba7285d04bf80786c3251e04b23e1de55b138ab80780c5f95d", + "bytes": 2172 + }, + "qml/QtQuick/Controls/Private/MenuItemSubControls.qmlc": { + "sha256": "2dfa3d742de7764caa2a9e4e295fb93f49601bfbb35520c351e81043d8eba2fb", + "bytes": 916 + }, + "qml/QtQuick/Controls/Private/ModalPopupBehavior.qml": { + "sha256": "ab03b4d992a33f44b63c00113260277cc346cbf8f33418068f0594359eacc6c3", + "bytes": 4471 + }, + "qml/QtQuick/Controls/Private/ModalPopupBehavior.qmlc": { + "sha256": "f60f85381d09db04c9e34d782b9f5c87b70b55990584ddc330c5eacb148af872", + "bytes": 7412 + }, + "qml/QtQuick/Controls/Private/ScrollBar.qml": { + "sha256": "2e0f77f4479c0ed3b4f0f86175d4a43a8084cf2937a0257593587a8d4740c5cc", + "bytes": 8966 + }, + "qml/QtQuick/Controls/Private/ScrollBar.qmlc": { + "sha256": "6489894a7ac8a42cbf5593447fb956cb2e01f8879932d832dac2b8c1709f4174", + "bytes": 17008 + }, + "qml/QtQuick/Controls/Private/ScrollViewHelper.qml": { + "sha256": "25201775f561639e8cc5de54f696bfd08f7808b2701305ac9deb9b114ea22a34", + "bytes": 9023 + }, + "qml/QtQuick/Controls/Private/ScrollViewHelper.qmlc": { + "sha256": "896199efef8b9ba9456272befba8483ab16c01529b308d865139473469144134", + "bytes": 20956 + }, + "qml/QtQuick/Controls/Private/SourceProxy.qml": { + "sha256": "bcbcb4500aa3c18dbe3306f78c92784b27b671335bbdc64447bd2687b4dbf809", + "bytes": 4737 + }, + "qml/QtQuick/Controls/Private/SourceProxy.qmlc": { + "sha256": "82faad596cf0dea7e8a71349925827ea56fe8af623bccd1ecc9349dfac4b2ca3", + "bytes": 5700 + }, + "qml/QtQuick/Controls/Private/StackView.js": { + "sha256": "2370db5cfa60bc01a044352c0ec414c201beec0243589118962b6e1535facd55", + "bytes": 2295 + }, + "qml/QtQuick/Controls/Private/StackView.jsc": { + "sha256": "8ddf3050d8a80b7e9ab42a460819ba5cff36fa663103726ff454dc03b0a45cda", + "bytes": 1224 + }, + "qml/QtQuick/Controls/Private/StackViewSlideDelegate.qml": { + "sha256": "6b1746caab3f2bfbeee31f49dec698aa79a777ea161c661cf0b88caebcd7cb5d", + "bytes": 4722 + }, + "qml/QtQuick/Controls/Private/StackViewSlideDelegate.qmlc": { + "sha256": "4712c2832ab6d78febbbee5a0d2bdfa385265c828128f02b8ec282087bcc1632", + "bytes": 7956 + }, + "qml/QtQuick/Controls/Private/Style.qml": { + "sha256": "53aface4d7e678215c6567d370d3dfab416d9b48dce93b4d67c1a941b5a36231", + "bytes": 2213 + }, + "qml/QtQuick/Controls/Private/Style.qmlc": { + "sha256": "c0385df8bb853635d91b6295724d4407f25f31ef845a5b2551d37b7ddcd22e64", + "bytes": 1052 + }, + "qml/QtQuick/Controls/Private/SystemPaletteSingleton.qml": { + "sha256": "94b67f786e9bc407ee9fae5d298ebb922890d31fe3c86345a029be43af1f15f5", + "bytes": 3364 + }, + "qml/QtQuick/Controls/Private/SystemPaletteSingleton.qmlc": { + "sha256": "0a795bc9d7a53e1762be085de3a5cffcef4b1ffbc656817890b76433b3580935", + "bytes": 3668 + }, + "qml/QtQuick/Controls/Private/TabBar.qml": { + "sha256": "62a7eec2903e74da26dc351ff35b3f14555fd89b8c22af84b51ee7a7bf871a9d", + "bytes": 12425 + }, + "qml/QtQuick/Controls/Private/TabBar.qmlc": { + "sha256": "6280f49b0cb450295178f98bbd35534553ba2c42ca9d70fdc980e0ef136e6da8", + "bytes": 33936 + }, + "qml/QtQuick/Controls/Private/TableViewItemDelegateLoader.qml": { + "sha256": "5662ab0fc092deab0878948a9f25034765f846c9a562291ed97b66fdf7697cce", + "bytes": 4532 + }, + "qml/QtQuick/Controls/Private/TableViewItemDelegateLoader.qmlc": { + "sha256": "8349f15d61c0e294ec3045a77edd96abec5af945ebb0ec85f9c3a25339d02ad9", + "bytes": 7872 + }, + "qml/QtQuick/Controls/Private/TableViewSelection.qml": { + "sha256": "26638db573ba7118ec7963a080acecc0abd34cd8ec4f3443d0fe238b8c6703f3", + "bytes": 6968 + }, + "qml/QtQuick/Controls/Private/TableViewSelection.qmlc": { + "sha256": "f509a04ef1c4c3cdcbbccce4dd4666d6ed45e43f8009fc957bf19e6445c30fba", + "bytes": 5852 + }, + "qml/QtQuick/Controls/Private/TextHandle.qml": { + "sha256": "b85119821c1521fcb940b5926358a2d38749c4250abd155125a1157aa3ddf828", + "bytes": 5066 + }, + "qml/QtQuick/Controls/Private/TextHandle.qmlc": { + "sha256": "a4b3a933f3f1cab9be92ed288c6d70c34e072be82c74343d431435add7831974", + "bytes": 7640 + }, + "qml/QtQuick/Controls/Private/TextInputWithHandles.qml": { + "sha256": "54652399ab356b81a3eadb97a12b9b9bbea88774a1fa7441da9de1ad00e9bfc4", + "bytes": 8028 + }, + "qml/QtQuick/Controls/Private/TextInputWithHandles.qmlc": { + "sha256": "97f127ddc0ff2e475141580510ae51ec319c3f9698aac772bc340fc652482809", + "bytes": 16656 + }, + "qml/QtQuick/Controls/Private/TextSingleton.qml": { + "sha256": "4363a7c15267566d5e8070dbeba4a1f2df4e836defae0a61928821535a0d8a78", + "bytes": 1977 + }, + "qml/QtQuick/Controls/Private/TextSingleton.qmlc": { + "sha256": "d9f180c553826e8bd7b2f52a3a4e4fd5c76e7a62d10acdcae6a1d43d1bc7c8d9", + "bytes": 516 + }, + "qml/QtQuick/Controls/Private/ToolMenuButton.qml": { + "sha256": "1e57a344b7b951777cdd865e42a6a9975c368a69a57d9ac3c798f5ef1a1d21a6", + "bytes": 4488 + }, + "qml/QtQuick/Controls/Private/ToolMenuButton.qmlc": { + "sha256": "dc7d4c34b38bf295be702911a44b71a8b2bd881a66c768b9f1de226e4a49b77d", + "bytes": 10244 + }, + "qml/QtQuick/Controls/Private/TreeViewItemDelegateLoader.qml": { + "sha256": "8654e12dd22c289985f1e4ed6474a210db16afcbe754c9f9e03f194d9542f04d", + "bytes": 4950 + }, + "qml/QtQuick/Controls/Private/TreeViewItemDelegateLoader.qmlc": { + "sha256": "a4f854ee0b1ff91818b1138d4078e75deaa149911915c24e6953360d77b059db", + "bytes": 10400 + }, + "qml/QtQuick/Controls/Private/qmldir": { + "sha256": "df929d20ecba620e64cdd87759dc163f225c4c99500e0c04542063d642ff5cfa", + "bytes": 1449 + }, + "qml/QtQuick/Controls/Private/style.js": { + "sha256": "63e1f4a5e31c74a90bf3323681fc7fcbe0267c84276db5fbc0eceb2c8b63583b", + "bytes": 2478 + }, + "qml/QtQuick/Controls/Private/style.jsc": { + "sha256": "e97badd38379eb2ab6be35c19131bf303868b4e3fa3f23f428c52bb3e61e8105", + "bytes": 1976 + }, + "qml/QtQuick/Controls/ProgressBar.qml": { + "sha256": "3c41029c0fd235b4b01d12b30994645c8a0a11fa3327c95b79de6f21ff380914", + "bytes": 5525 + }, + "qml/QtQuick/Controls/ProgressBar.qmlc": { + "sha256": "aaa580d90fc690903b7589b4c9585b1a0224b6abb21e459017ca0d675e738c0b", + "bytes": 6284 + }, + "qml/QtQuick/Controls/RadioButton.qml": { + "sha256": "aa7dc292af02e02280bfa89bf1616176d1805949fa6e0a5dbc7490c52ba1e390", + "bytes": 3554 + }, + "qml/QtQuick/Controls/RadioButton.qmlc": { + "sha256": "bf9004c9ddf63def06575b9bbed7ccc255e064df7908d1e916464497119a6aa7", + "bytes": 2432 + }, + "qml/QtQuick/Controls/ScrollView.qml": { + "sha256": "e3bd9b431c39e5a8b8818b39ad9dc9f865309bb52eb4d5173a3463eba2a6feff", + "bytes": 14230 + }, + "qml/QtQuick/Controls/ScrollView.qmlc": { + "sha256": "6dedecc3587137dae8df327b9682c4d22b1018b6995a69137d1caa24b70b2869", + "bytes": 21108 + }, + "qml/QtQuick/Controls/Slider.qml": { + "sha256": "200a916440c9e088c53b34b0e04e8d57a9fb7ec964070d9e0957c9bfad66dc0b", + "bytes": 12003 + }, + "qml/QtQuick/Controls/Slider.qmlc": { + "sha256": "9a771b73cf27b7b7ab83e618b5ffef0ee40ca83343d0bce3e0c3d5053ce8be46", + "bytes": 18972 + }, + "qml/QtQuick/Controls/SpinBox.qml": { + "sha256": "4b0c07f253c1b34f7ebb27630aa0f18d97ba54793f757442c9d16119fb253424", + "bytes": 12884 + }, + "qml/QtQuick/Controls/SpinBox.qmlc": { + "sha256": "d89e8cdfeaeda99341be41f8c559487e93e89704c88b6391137d158afdb384e2", + "bytes": 26356 + }, + "qml/QtQuick/Controls/SplitView.qml": { + "sha256": "b246b0d51ffdacfef77ed24e477b06cf3d93bf95475f2ca46560c83731cf3045", + "bytes": 25109 + }, + "qml/QtQuick/Controls/SplitView.qmlc": { + "sha256": "8dc90ff58472adafc075e094ecc8de26c8953e4dbd77037d0f7a403181819393", + "bytes": 29456 + }, + "qml/QtQuick/Controls/StackView.qml": { + "sha256": "5128b0e95cda42528fb7d87db32ff042159190ca5bbbede595c388774a834582", + "bytes": 42462 + }, + "qml/QtQuick/Controls/StackView.qmlc": { + "sha256": "f275de6ef735ea0247821cb8b387558b6bc1347ea38b3b4c798b0074d623f111", + "bytes": 16788 + }, + "qml/QtQuick/Controls/StackViewDelegate.qml": { + "sha256": "d3b14a853c7feaa3969edc6b3584936cf23ce15dfc61e08e98bdd437fd2de8d9", + "bytes": 3601 + }, + "qml/QtQuick/Controls/StackViewDelegate.qmlc": { + "sha256": "1f9c969ea7fcdc29128d1502775ff840abe247c92b63889a038efc2421c2465c", + "bytes": 1856 + }, + "qml/QtQuick/Controls/StackViewTransition.qml": { + "sha256": "ef42a3b04a57c8b8a450989879ac162b4e078c9574f14d9192ca283a2e8218ba", + "bytes": 2476 + }, + "qml/QtQuick/Controls/StackViewTransition.qmlc": { + "sha256": "4bddb5e3f4001f182896014fb84a2cdc33b0481ec56155451c2b5659bf9278a5", + "bytes": 876 + }, + "qml/QtQuick/Controls/StatusBar.qml": { + "sha256": "6e35bd335955f08e2e204b5793da85c20828a9f8326dd72d5f85c9b84f76ca8e", + "bytes": 6204 + }, + "qml/QtQuick/Controls/StatusBar.qmlc": { + "sha256": "d486ef8ef40a7d95581593f298573ce0028c69e6b71584fd5e40cb51746af105", + "bytes": 8396 + }, + "qml/QtQuick/Controls/Styles/Base/ApplicationWindowStyle.qml": { + "sha256": "b75fef3e535c7402ce150129dca234bfb2dba562c7ab44ea2a01bd0b59ac6bb9", + "bytes": 5059 + }, + "qml/QtQuick/Controls/Styles/Base/ApplicationWindowStyle.qmlc": { + "sha256": "3f3745cbd70f6a9a536b6626eabda8963f5b311bac46c68d28cf49739bd82e2f", + "bytes": 7340 + }, + "qml/QtQuick/Controls/Styles/Base/BasicTableViewStyle.qml": { + "sha256": "e7092e9c82190f58398f55d04ec16d0ea230e8a08e2b89314bd119188b062c96", + "bytes": 6422 + }, + "qml/QtQuick/Controls/Styles/Base/BasicTableViewStyle.qmlc": { + "sha256": "a1c199501fac0c73c60b4297f337d7d48cab3848bfb78de709a112783925afc4", + "bytes": 11796 + }, + "qml/QtQuick/Controls/Styles/Base/BusyIndicatorStyle.qml": { + "sha256": "bf76cf3aa4afb99005b46ca6a1899c937a5996c4e1b26856392b082d51413ca8", + "bytes": 4335 + }, + "qml/QtQuick/Controls/Styles/Base/BusyIndicatorStyle.qmlc": { + "sha256": "9af7d5375def1786a2ccb1390aef90cc191b830e6046b9d5a80eec9bee835106", + "bytes": 6948 + }, + "qml/QtQuick/Controls/Styles/Base/ButtonStyle.qml": { + "sha256": "4118d004b1568dfb706b61c5561137e46e902bef101c0d0ee2feb1bb4ffd0b56", + "bytes": 6646 + }, + "qml/QtQuick/Controls/Styles/Base/ButtonStyle.qmlc": { + "sha256": "4da18f39879958a467eb452c004d4640235bacf7408a4b1cd6631779c6934438", + "bytes": 15648 + }, + "qml/QtQuick/Controls/Styles/Base/CalendarStyle.qml": { + "sha256": "26741b3e199de9d09466a6979e4f3a28ed9d80d6d06a6b2cd62dce4af786450d", + "bytes": 29390 + }, + "qml/QtQuick/Controls/Styles/Base/CalendarStyle.qmlc": { + "sha256": "93e115eac89c43fddf13f0c550cef7f13e05146bee6f1235e87b73a4057d2238", + "bytes": 46884 + }, + "qml/QtQuick/Controls/Styles/Base/CheckBoxStyle.qml": { + "sha256": "a82580f35c8e7a0ec566e54c251c8503855dbe49b98c000cbc1b760b3e2e47ed", + "bytes": 7082 + }, + "qml/QtQuick/Controls/Styles/Base/CheckBoxStyle.qmlc": { + "sha256": "0ff60012d4aae81c9e5dc4717df26fa8e758b91963fb309deecf51bf3cfa0eed", + "bytes": 16588 + }, + "qml/QtQuick/Controls/Styles/Base/CircularButtonStyle.qml": { + "sha256": "7658e0921eedbcbaf0fbad8a1d06780d12ed27822d80f7d71618fa03c1097fa6", + "bytes": 3300 + }, + "qml/QtQuick/Controls/Styles/Base/CircularButtonStyle.qmlc": { + "sha256": "0798c98587d33980e0fbbacc22ab10c7ac56412ef4d9d695ae8995b2ae30ce17", + "bytes": 7332 + }, + "qml/QtQuick/Controls/Styles/Base/CircularGaugeStyle.qml": { + "sha256": "1d1e6139cc09bee255fb11f143a8af6ef39871e3c7e1d3f293d8875525134e94", + "bytes": 18102 + }, + "qml/QtQuick/Controls/Styles/Base/CircularGaugeStyle.qmlc": { + "sha256": "5520b77f10818196507d43e589487faa73c0c40f507f079f875ad07ec596c337", + "bytes": 18432 + }, + "qml/QtQuick/Controls/Styles/Base/CircularTickmarkLabelStyle.qml": { + "sha256": "4ae490716f3664ed912f2c35e5d3326b5828fe36f9c112c92a93b130b10e9a90", + "bytes": 13392 + }, + "qml/QtQuick/Controls/Styles/Base/CircularTickmarkLabelStyle.qmlc": { + "sha256": "1e2fb9448a7523239bd3cf803415d2167cb63e52a33e3ca02a5220aee870cc0e", + "bytes": 24312 + }, + "qml/QtQuick/Controls/Styles/Base/ComboBoxStyle.qml": { + "sha256": "9e80578233d38c3234e7027a10cab2f1a89e2dc8762195e46a103159f810f2fb", + "bytes": 12047 + }, + "qml/QtQuick/Controls/Styles/Base/ComboBoxStyle.qmlc": { + "sha256": "e301896253e4d730f338ac47537942b9d03b5cba8ba88b79eb77fb5962259a85", + "bytes": 25684 + }, + "qml/QtQuick/Controls/Styles/Base/CommonStyleHelper.qml": { + "sha256": "b8055542e0132464300959fba80c8f0961bd1fad00a23df4c2fe083dd561555a", + "bytes": 2629 + }, + "qml/QtQuick/Controls/Styles/Base/CommonStyleHelper.qmlc": { + "sha256": "26deeb897c84a001a599a656f2b1fb11de87e454dc1f1e32dd6e5d506a1cc488", + "bytes": 2564 + }, + "qml/QtQuick/Controls/Styles/Base/DelayButtonStyle.qml": { + "sha256": "022d54ad748c3288413356cc386a07c34afcb2bdad006dc81613de336b2c7034", + "bytes": 7247 + }, + "qml/QtQuick/Controls/Styles/Base/DelayButtonStyle.qmlc": { + "sha256": "ee12bdc5d98336a1e602655050fe0879fdb7dfd493a09988f804f1d26cd07805", + "bytes": 16832 + }, + "qml/QtQuick/Controls/Styles/Base/DialStyle.qml": { + "sha256": "35d082ad555ead87b39f0f5f1f730dcaccecd841e0fd2bcc555dfb6c224186c1", + "bytes": 12950 + }, + "qml/QtQuick/Controls/Styles/Base/DialStyle.qmlc": { + "sha256": "bdba9783dbc098dd4c4f008fad475e480bc52c24c5812784f59e25ed67501f23", + "bytes": 18992 + }, + "qml/QtQuick/Controls/Styles/Base/FocusFrameStyle.qml": { + "sha256": "a261e17e4bb1c69fd6e205f0ff391fcba0d0795c545c37a9f7465d56a5991a24", + "bytes": 2144 + }, + "qml/QtQuick/Controls/Styles/Base/FocusFrameStyle.qmlc": { + "sha256": "797bec50399dea5594b8084f74932b812c1fec703d5a308d19bf70cac06b815c", + "bytes": 796 + }, + "qml/QtQuick/Controls/Styles/Base/GaugeStyle.qml": { + "sha256": "9a800ec8320a5840ef1da4002f260ad1b3fd3fbf49f8968a155fe7f812d7c5b8", + "bytes": 22292 + }, + "qml/QtQuick/Controls/Styles/Base/GaugeStyle.qmlc": { + "sha256": "7d79fe116fec9292dbeb87ea25dbd56a6e193d8ed91a2fd8d5e672b1e9f7a3fd", + "bytes": 30776 + }, + "qml/QtQuick/Controls/Styles/Base/GroupBoxStyle.qml": { + "sha256": "b2087d861a671b8e2f478993241ea0e0182814845f1f1f50b260ee95bdf34f5b", + "bytes": 4813 + }, + "qml/QtQuick/Controls/Styles/Base/GroupBoxStyle.qmlc": { + "sha256": "eea70fb29c829073fed8c795c7b1b46f78c9c4d07c5d48d32c9d65d05a964c9a", + "bytes": 11064 + }, + "qml/QtQuick/Controls/Styles/Base/HandleStyle.qml": { + "sha256": "90d6b93b5b70461ce21e417a0e29d52f19fe0f376760ee2ba1e1584ca754d1f5", + "bytes": 2773 + }, + "qml/QtQuick/Controls/Styles/Base/HandleStyle.qmlc": { + "sha256": "3d8deda914dbaa40b736afdaf29e30e5b97a2e1a0c066c3564613d537a89656a", + "bytes": 3656 + }, + "qml/QtQuick/Controls/Styles/Base/HandleStyleHelper.qml": { + "sha256": "6abe6b7c31a98a51565cb46dc4126053a046a418765ebfbbae9cba1197321da9", + "bytes": 3861 + }, + "qml/QtQuick/Controls/Styles/Base/HandleStyleHelper.qmlc": { + "sha256": "3bcc4c3713f1afb5f2f4a02f46fa676767ae4f9026e8663558f44d6fc03a6bfb", + "bytes": 3404 + }, + "qml/QtQuick/Controls/Styles/Base/MenuBarStyle.qml": { + "sha256": "725768992f5b7bc9f878119d7f377f9dec0dff5c166ba5adc7fd057aca6e3956", + "bytes": 5135 + }, + "qml/QtQuick/Controls/Styles/Base/MenuBarStyle.qmlc": { + "sha256": "4a9fe9c89f1763f449136e16f4e68dd9e66676513e3e9346bcdb6f260d5102c0", + "bytes": 5312 + }, + "qml/QtQuick/Controls/Styles/Base/MenuStyle.qml": { + "sha256": "cbc957a830afd2cd664dc800b60e5db3b435a61d944cf5a33182cd574ad0dea7", + "bytes": 18551 + }, + "qml/QtQuick/Controls/Styles/Base/MenuStyle.qmlc": { + "sha256": "ea9d1345b7f2c1d440165941971916f583d6869570689e6b3651317ea374e061", + "bytes": 27256 + }, + "qml/QtQuick/Controls/Styles/Base/PieMenuStyle.qml": { + "sha256": "13ffdbd42473ccc8adff5f4274d94abd9ab4b0b3029b6e88e3b6d6e476329636", + "bytes": 13215 + }, + "qml/QtQuick/Controls/Styles/Base/PieMenuStyle.qmlc": { + "sha256": "998311fbf380117f121044526d9d974057c271201423a7ae1c4884d708302ac3", + "bytes": 19552 + }, + "qml/QtQuick/Controls/Styles/Base/ProgressBarStyle.qml": { + "sha256": "2086815d90fd12d4d1c296f1a293e35ee8e30e6f5e8ac98796ab89df65a2180b", + "bytes": 9410 + }, + "qml/QtQuick/Controls/Styles/Base/ProgressBarStyle.qmlc": { + "sha256": "2f3991422a9cbea7ecb219a1cd54da20789a533863dc7133bef6d9deb33545cd", + "bytes": 19268 + }, + "qml/QtQuick/Controls/Styles/Base/RadioButtonStyle.qml": { + "sha256": "4f4a83115e6fd205be4806cf69d105f1a347cb587214c371c3acf9ea3654e50b", + "bytes": 6249 + }, + "qml/QtQuick/Controls/Styles/Base/RadioButtonStyle.qmlc": { + "sha256": "37a422f5f5d5a3d76b8debebaf0ee4a10b71771a02538a3a7200f4589358344f", + "bytes": 14128 + }, + "qml/QtQuick/Controls/Styles/Base/ScrollViewStyle.qml": { + "sha256": "436978defd69d49bc922bfebffae339bd6e8851218818a88a37077caa66a86f9", + "bytes": 17142 + }, + "qml/QtQuick/Controls/Styles/Base/ScrollViewStyle.qmlc": { + "sha256": "dfcb288ce3e77aa224f10a4618560b99b32e0878d929b97de52b076fd514c429", + "bytes": 35988 + }, + "qml/QtQuick/Controls/Styles/Base/SliderStyle.qml": { + "sha256": "0c11eff6b53e2fd81e443a9af48f5398a9be969a495553d897f51b0d54f3737f", + "bytes": 8779 + }, + "qml/QtQuick/Controls/Styles/Base/SliderStyle.qmlc": { + "sha256": "856a7abfe6d80d81c645e36dca95a7199336f968b59a9bb46edc65a84e467b6b", + "bytes": 19176 + }, + "qml/QtQuick/Controls/Styles/Base/SpinBoxStyle.qml": { + "sha256": "481ccf65a5e7d95e118a4999d1a78ab3d176829cc43824f2fb969a97f1961c9f", + "bytes": 9425 + }, + "qml/QtQuick/Controls/Styles/Base/SpinBoxStyle.qmlc": { + "sha256": "444515780f64c58fcf0d2a3b0fecb0a2769323ea70205268b4a8524a4c1c41ca", + "bytes": 16484 + }, + "qml/QtQuick/Controls/Styles/Base/StatusBarStyle.qml": { + "sha256": "fc8c3d2029394e090fab232b544da296adb9b24f488a0fd2b027091bf03a1969", + "bytes": 3769 + }, + "qml/QtQuick/Controls/Styles/Base/StatusBarStyle.qmlc": { + "sha256": "effd0e4e6a1e2d3eb078044bab98a14dc7573e262e8f5dcd6ac1723de3f08742", + "bytes": 3764 + }, + "qml/QtQuick/Controls/Styles/Base/StatusIndicatorStyle.qml": { + "sha256": "9846d99bf3aaac6ae982d7b7ccd4479d5846457329ea0ef4b6046af901c8b085", + "bytes": 8856 + }, + "qml/QtQuick/Controls/Styles/Base/StatusIndicatorStyle.qmlc": { + "sha256": "6000b7627885a7a35a0b988aa8f7f5309bc25551c1ae01950c784a44d4e42085", + "bytes": 13600 + }, + "qml/QtQuick/Controls/Styles/Base/SwitchStyle.qml": { + "sha256": "b66aecc18a83a471b8449c3e9a5deeddd1616db81a2a6308bb0d78f8bb127d07", + "bytes": 5869 + }, + "qml/QtQuick/Controls/Styles/Base/SwitchStyle.qmlc": { + "sha256": "714f40aa4c157fc57dd339336d14d9795477563d5e2564ed6ed25ddf9389fd85", + "bytes": 13932 + }, + "qml/QtQuick/Controls/Styles/Base/TabViewStyle.qml": { + "sha256": "806167e4ddd15203d272b89b86ae92b3f0cd2836c1d5dd0be600d7f11563afc5", + "bytes": 7576 + }, + "qml/QtQuick/Controls/Styles/Base/TabViewStyle.qmlc": { + "sha256": "ceacac13d8e4697a10724e05c15b2488b227007e605301f5adf8b05accc47111", + "bytes": 11868 + }, + "qml/QtQuick/Controls/Styles/Base/TableViewStyle.qml": { + "sha256": "0b63ac4cdfe4efa76764cfed2c2ab88f36f9ad87fbf92a8689c2a02ad30bdc8b", + "bytes": 2069 + }, + "qml/QtQuick/Controls/Styles/Base/TableViewStyle.qmlc": { + "sha256": "5b8ed58ad17463c6edaab63d152aa0196b3846ec2f61bed01d057523a2e9d4aa", + "bytes": 1004 + }, + "qml/QtQuick/Controls/Styles/Base/TextAreaStyle.qml": { + "sha256": "55224f133dfd960e4309d7f3b0a3ad71e6cdb95cf761a310a1910e5de5aeed0b", + "bytes": 6034 + }, + "qml/QtQuick/Controls/Styles/Base/TextAreaStyle.qmlc": { + "sha256": "2aec533339103abbae31a9aeb402992df598218990fd2f4a55394685704e439f", + "bytes": 3804 + }, + "qml/QtQuick/Controls/Styles/Base/TextFieldStyle.qml": { + "sha256": "21bc961f37d1da70e47c7a6672bfaa38b10ca5643942e6d0e1a7eaa6847369e1", + "bytes": 8202 + }, + "qml/QtQuick/Controls/Styles/Base/TextFieldStyle.qmlc": { + "sha256": "2f0603995cb98e744258baf6a329181bff1d9b12be9c2ccd3bb0bb9df7d2f2ab", + "bytes": 11912 + }, + "qml/QtQuick/Controls/Styles/Base/ToggleButtonStyle.qml": { + "sha256": "5de663cf32b29ddb07dc4d22e21e2e26d72633f216514e2fe9ab25f6a4362b04", + "bytes": 9968 + }, + "qml/QtQuick/Controls/Styles/Base/ToggleButtonStyle.qmlc": { + "sha256": "0b9243570a82919436abf6c87ce64d2594fb2832766d15a9731fa6b07df366bf", + "bytes": 19112 + }, + "qml/QtQuick/Controls/Styles/Base/ToolBarStyle.qml": { + "sha256": "5bbdc46f85ab9d7d828ed3cd0485d5fe87f89d2f42826eaaccd881e395875fbb", + "bytes": 4322 + }, + "qml/QtQuick/Controls/Styles/Base/ToolBarStyle.qmlc": { + "sha256": "7b463fe65d7108af291db1b34df8e937db5c4e9e00db940f772d170930c35140", + "bytes": 4316 + }, + "qml/QtQuick/Controls/Styles/Base/ToolButtonStyle.qml": { + "sha256": "701849ea72987ab9b835f11953905adebfce8d9209a2fe7c1000e16939bb0f18", + "bytes": 4223 + }, + "qml/QtQuick/Controls/Styles/Base/ToolButtonStyle.qmlc": { + "sha256": "c3f741bbc05ab7803d3ced5909c13c071c01624bb837f5a96e573f75cc803485", + "bytes": 10104 + }, + "qml/QtQuick/Controls/Styles/Base/TreeViewStyle.qml": { + "sha256": "e86957b4df34bc35fc25f107d73d65392aa167d6a14d5416657fdc8b78cc6830", + "bytes": 2745 + }, + "qml/QtQuick/Controls/Styles/Base/TreeViewStyle.qmlc": { + "sha256": "eeaa1c5941af6d88fa064408619e076a8442a02e2cb272888b6a0c03768d6705", + "bytes": 5060 + }, + "qml/QtQuick/Controls/Styles/Base/TumblerStyle.qml": { + "sha256": "11961547f865637ffe30f7f5f0a6df30ab28ae92437083c7df4b4b81ae0b017d", + "bytes": 12539 + }, + "qml/QtQuick/Controls/Styles/Base/TumblerStyle.qmlc": { + "sha256": "2a77298ed5f975cfdb81d28c15f181e2f8ab4d23f62094a00c3199d929a37c9f", + "bytes": 14420 + }, + "qml/QtQuick/Controls/Styles/Base/images/arrow-down.png": { + "sha256": "0d0f06d0e93c8a2f28da6838bb0bdc9b46dc79bbf0876db9db7dfd86b133cb9b", + "bytes": 99 + }, + "qml/QtQuick/Controls/Styles/Base/images/arrow-down@2x.png": { + "sha256": "a44fde0ca4826166ea8ea1089c89f0d45684d8191f0aa0aa55a69dfe97afe34c", + "bytes": 132 + }, + "qml/QtQuick/Controls/Styles/Base/images/arrow-left.png": { + "sha256": "e3ef46a5a48c488f2af7e46440e28cbf292a8e640144dfcaf896682409994c1a", + "bytes": 98 + }, + "qml/QtQuick/Controls/Styles/Base/images/arrow-left@2x.png": { + "sha256": "44c667990e062dda8480aad1946bfeb4037667b1faa31c4279eba5d7d1fc8b62", + "bytes": 128 + }, + "qml/QtQuick/Controls/Styles/Base/images/arrow-right.png": { + "sha256": "ada31cabdf339314064f905eb072a0895ec07232e8287a9a22ba82a34fadd378", + "bytes": 99 + }, + "qml/QtQuick/Controls/Styles/Base/images/arrow-right@2x.png": { + "sha256": "c0d486047fc33f4bcb3a611d7054034f9288281d2d24e1e1bd71a35c7eb5d4ec", + "bytes": 128 + }, + "qml/QtQuick/Controls/Styles/Base/images/arrow-up.png": { + "sha256": "e4dda2989b89e82ddd601b9871f766f45f6783132601eb46f259abc132cf6efd", + "bytes": 107 + }, + "qml/QtQuick/Controls/Styles/Base/images/arrow-up@2x.png": { + "sha256": "faa99e2246aecbf9c12b6ed5e5c1543431f4fabde5ada39356d78e3bc8578f4e", + "bytes": 148 + }, + "qml/QtQuick/Controls/Styles/Base/images/button.png": { + "sha256": "b2d4d7adf8e62360b4c6d0d3bb5ff27508b97379fd4bb6e4c80d31dfb468e849", + "bytes": 540 + }, + "qml/QtQuick/Controls/Styles/Base/images/button_down.png": { + "sha256": "292da1564cea53fc63203d0184fc0f2849c169ac3ec948a0344c31b674ada3ec", + "bytes": 203 + }, + "qml/QtQuick/Controls/Styles/Base/images/check.png": { + "sha256": "f47290e13d80210edbad66771068146d2c2b81fc444448cad4ddc5d5faf733d0", + "bytes": 176 + }, + "qml/QtQuick/Controls/Styles/Base/images/check@2x.png": { + "sha256": "89ddc66a80f7c8bb521ea3bd02a62198ed97e7bb056d88862bc1daea0e175e26", + "bytes": 339 + }, + "qml/QtQuick/Controls/Styles/Base/images/editbox.png": { + "sha256": "de9cd8ab5907a62dae5ffe36de84a78a416d281fb793d8d63a77e8ef6cd9be9f", + "bytes": 393 + }, + "qml/QtQuick/Controls/Styles/Base/images/focusframe.png": { + "sha256": "25926f3de1bbd3bf0794908d3e7f6bb213af1798f5745db13356cda2faa0e2ec", + "bytes": 268 + }, + "qml/QtQuick/Controls/Styles/Base/images/groupbox.png": { + "sha256": "4470e834bf1a8c2eb025d651ed5bbc71681aa898388ae17f8b276e8ad641a0b8", + "bytes": 225 + }, + "qml/QtQuick/Controls/Styles/Base/images/header.png": { + "sha256": "fef52d00a955b35d50faafc08c9f0c6c55d4bc35b01000200e13db44b59ec9bd", + "bytes": 383 + }, + "qml/QtQuick/Controls/Styles/Base/images/knob.png": { + "sha256": "455d05ddf72d76b5a3c8b4633fb19493511da4e04719d308de7a7f152b516b6d", + "bytes": 1703 + }, + "qml/QtQuick/Controls/Styles/Base/images/leftanglearrow.png": { + "sha256": "1ae3b11e257a017248fa3bd7521699d216312012f8801c534f42141d71ab58b0", + "bytes": 152 + }, + "qml/QtQuick/Controls/Styles/Base/images/needle.png": { + "sha256": "de0bd47828ab9c6929a5452d96b5c6ac13b99c0e3fcc159c885ec15a4cd3e2c7", + "bytes": 2036 + }, + "qml/QtQuick/Controls/Styles/Base/images/progress-indeterminate.png": { + "sha256": "be5b4691910a4d754fd2b435421e11f35d4176aaf6034e3fd503d9ea17cd68dd", + "bytes": 1423 + }, + "qml/QtQuick/Controls/Styles/Base/images/rightanglearrow.png": { + "sha256": "81b588fc5973b5bcbfbfbaf268ba62bd75e07c0d759fca35e6cfe86f34154957", + "bytes": 160 + }, + "qml/QtQuick/Controls/Styles/Base/images/scrollbar-handle-horizontal.png": { + "sha256": "ee8c1c4b11e8a4a50b08d7597583a0d3cd74e7cb9b77de47fe8cfee71b3e4b5e", + "bytes": 825 + }, + "qml/QtQuick/Controls/Styles/Base/images/scrollbar-handle-transient.png": { + "sha256": "ad63a2731dabb830e5609b80446b3ebad5dc538451dc8e2d91f4cc938bc1b5b2", + "bytes": 152 + }, + "qml/QtQuick/Controls/Styles/Base/images/scrollbar-handle-vertical.png": { + "sha256": "329501784a775761531c0e82b2e74cc9cba464c0a38e93db3323054c5f117d56", + "bytes": 839 + }, + "qml/QtQuick/Controls/Styles/Base/images/slider-groove.png": { + "sha256": "d2bcb94ddbcb5803b9270f782ed52c7b6e0d1fa9aaf7dbfe6e41971c0cebf46d", + "bytes": 565 + }, + "qml/QtQuick/Controls/Styles/Base/images/slider-handle.png": { + "sha256": "cde58d09bb3bf656b6a9edd558ad4d1cb80593b926591f3aa67f29f138318583", + "bytes": 516 + }, + "qml/QtQuick/Controls/Styles/Base/images/spinner_large.png": { + "sha256": "3d6d254777854c6505ec34fe417a08d0dcb1eadd2034cac946422946805d5d91", + "bytes": 4722 + }, + "qml/QtQuick/Controls/Styles/Base/images/spinner_medium.png": { + "sha256": "0f620f218012ed6ff30809046ced5ca372327454b59c0b4d9501639bbffd3ce0", + "bytes": 1621 + }, + "qml/QtQuick/Controls/Styles/Base/images/spinner_small.png": { + "sha256": "8c31e6f37eee27e6bec02dbfb6452b9f0831d6586e47dce4392e9fbaa07eced5", + "bytes": 998 + }, + "qml/QtQuick/Controls/Styles/Base/images/tab.png": { + "sha256": "57b1ae0988c615082705698ce38d82b0aec46bc11141acc62f16554af1f27820", + "bytes": 390 + }, + "qml/QtQuick/Controls/Styles/Base/images/tab_selected.png": { + "sha256": "787e8a615b2b3a53c79cb1d9f50eaeb68c0abbe5be24ab5a78782212c13f97c6", + "bytes": 434 + }, + "qml/QtQuick/Controls/Styles/Desktop/ApplicationWindowStyle.qml": { + "sha256": "83345664ab0f225c9d83ad2380bea5d15082dc62a038cc757ceb06953db8b13a", + "bytes": 1995 + }, + "qml/QtQuick/Controls/Styles/Desktop/ApplicationWindowStyle.qmlc": { + "sha256": "6c2c4f0c34b7f283492e62e188f81ac8aaa03d5af3034cc21dae1014739b4e01", + "bytes": 580 + }, + "qml/QtQuick/Controls/Styles/Desktop/BusyIndicatorStyle.qml": { + "sha256": "3496f36b2dd87a85d2e19dbca8375a69240c899124f9809e637ad265b76c4485", + "bytes": 1991 + }, + "qml/QtQuick/Controls/Styles/Desktop/BusyIndicatorStyle.qmlc": { + "sha256": "f2dd2eb0b3275f0a485be6eb3d88a67b858c5eb26a42aca8d34a51366c8a012b", + "bytes": 572 + }, + "qml/QtQuick/Controls/Styles/Desktop/ButtonStyle.qml": { + "sha256": "738da67061fb5b86537cf169ea972e92d53ea3d15505ccef969b3ed017359b20", + "bytes": 2666 + }, + "qml/QtQuick/Controls/Styles/Desktop/ButtonStyle.qmlc": { + "sha256": "b4e13a3620f4b061332b53ace8c7735ed112b2f8296a5f6005f310fc653491cc", + "bytes": 3888 + }, + "qml/QtQuick/Controls/Styles/Desktop/CalendarStyle.qml": { + "sha256": "2f3419b59fc234d4b756174178fd83a0afa355dc8c18e2686ce383581fbb4f11", + "bytes": 1985 + }, + "qml/QtQuick/Controls/Styles/Desktop/CalendarStyle.qmlc": { + "sha256": "65e311c502873afa56bceea0149e81f726424eb9a5ea5e7fc3222d389ba1e28c", + "bytes": 564 + }, + "qml/QtQuick/Controls/Styles/Desktop/CheckBoxStyle.qml": { + "sha256": "b515622fc405e77ffb1027a635193536fbe96b7df59b6028307739be03b5dbd6", + "bytes": 3952 + }, + "qml/QtQuick/Controls/Styles/Desktop/CheckBoxStyle.qmlc": { + "sha256": "12b6662d9fe28b7122f49a5b4902dbedd4a60b0a021328eab2ff5de5a0810f80", + "bytes": 10368 + }, + "qml/QtQuick/Controls/Styles/Desktop/ComboBoxStyle.qml": { + "sha256": "00ff23ba6d7bfc7a70856c8ce9d57532f249509304ff29ae44330d24e3037c9a", + "bytes": 5165 + }, + "qml/QtQuick/Controls/Styles/Desktop/ComboBoxStyle.qmlc": { + "sha256": "dba98e05288bc322e521f1e508a6413a9d9ea3aacd2b53e8d87d7dc6d6f434c9", + "bytes": 12384 + }, + "qml/QtQuick/Controls/Styles/Desktop/FocusFrameStyle.qml": { + "sha256": "ad35a74ef8ca8139c6c7083ae502e8721ccba50b1a337afea64e0e8b0120a9e3", + "bytes": 2206 + }, + "qml/QtQuick/Controls/Styles/Desktop/FocusFrameStyle.qmlc": { + "sha256": "66b280c885b6c81d9fbd305aefe2e1d839986c0cd4023c6d141c052b97abaa7a", + "bytes": 1344 + }, + "qml/QtQuick/Controls/Styles/Desktop/GroupBoxStyle.qml": { + "sha256": "dbd7577badd47a8ba8514cf2c828a1f94760c01036502d404222b7b130b0785b", + "bytes": 3154 + }, + "qml/QtQuick/Controls/Styles/Desktop/GroupBoxStyle.qmlc": { + "sha256": "f2ddfc8491636ae0a4a90c7a682fed5f78eab09d0539f87d273e361c142a8edc", + "bytes": 6616 + }, + "qml/QtQuick/Controls/Styles/Desktop/MenuBarStyle.qml": { + "sha256": "3fe1302ecf0eceae84f3295955c4652eb43440cb8f722acb36e145b25a0b6734", + "bytes": 3162 + }, + "qml/QtQuick/Controls/Styles/Desktop/MenuBarStyle.qmlc": { + "sha256": "fe269b35445602ca237ed2ed511789ac2a480b64478fcad243d2d9defb568a89", + "bytes": 5604 + }, + "qml/QtQuick/Controls/Styles/Desktop/MenuStyle.qml": { + "sha256": "bcbf8e2f09ee6942b3eb5c9b62bfbd9372ad4fa268296f69affed28b82c7a0be", + "bytes": 4566 + }, + "qml/QtQuick/Controls/Styles/Desktop/MenuStyle.qmlc": { + "sha256": "c47a700caca39a6be94c4edbcb9e22e26498ca8647a03adc0d02520c918e17dd", + "bytes": 9780 + }, + "qml/QtQuick/Controls/Styles/Desktop/ProgressBarStyle.qml": { + "sha256": "0bc9a343c1a21a0368982a86ca89af43dc99a1b0c8406838e22857ee767a2fdc", + "bytes": 2855 + }, + "qml/QtQuick/Controls/Styles/Desktop/ProgressBarStyle.qmlc": { + "sha256": "d927a1d346f0c7c6652957a3f1d878fdb58c607f2a787499faf2462d44df3a3a", + "bytes": 4212 + }, + "qml/QtQuick/Controls/Styles/Desktop/RadioButtonStyle.qml": { + "sha256": "0e3931db461f401dd4ed3244763d8ce7a742f492f3b34e8424d9b08935646357", + "bytes": 4034 + }, + "qml/QtQuick/Controls/Styles/Desktop/RadioButtonStyle.qmlc": { + "sha256": "e64c7b12cef07486610e5d68a1b028b629a73f1e31d7560d019b413fb3b7193e", + "bytes": 10500 + }, + "qml/QtQuick/Controls/Styles/Desktop/RowItemSingleton.qml": { + "sha256": "6623af3d0c12f34ffa1d6fb8e58378cc2018b2fba7eaa65104775ee46acf997b", + "bytes": 2026 + }, + "qml/QtQuick/Controls/Styles/Desktop/RowItemSingleton.qmlc": { + "sha256": "b5d5a1beb66938893543e77cae6616b05f7ad109a69b925fe9ac181bb3d23631", + "bytes": 684 + }, + "qml/QtQuick/Controls/Styles/Desktop/ScrollViewStyle.qml": { + "sha256": "37d08bf0b7ce6a5a90b06b4e2c085893d645320d451a3b4d5033eef8c57c1ff2", + "bytes": 3821 + }, + "qml/QtQuick/Controls/Styles/Desktop/ScrollViewStyle.qmlc": { + "sha256": "8266e76ec57fdf7cd35b1828b9ed3bef101abf5691787404a716580d3f858fe6", + "bytes": 9328 + }, + "qml/QtQuick/Controls/Styles/Desktop/SliderStyle.qml": { + "sha256": "2674e9335f59822286780945c7935dd44ae58d970d8d8fa6d892e07159ec2c10", + "bytes": 2845 + }, + "qml/QtQuick/Controls/Styles/Desktop/SliderStyle.qmlc": { + "sha256": "28cb97390dbe2fcc83cca327e91d3c164b1c6b68a523c61b5bb06fb7ddcfcd0b", + "bytes": 5956 + }, + "qml/QtQuick/Controls/Styles/Desktop/SpinBoxStyle.qml": { + "sha256": "0fc3de9199de8fc4b3ede9171e7f03c880756016124c9de5b31f8a6272ebf3b4", + "bytes": 5342 + }, + "qml/QtQuick/Controls/Styles/Desktop/SpinBoxStyle.qmlc": { + "sha256": "2d94b1f1371aba5b6ddf5b4fccf1d45b1e21acc525f161ca404201dca6a45023", + "bytes": 14728 + }, + "qml/QtQuick/Controls/Styles/Desktop/StatusBarStyle.qml": { + "sha256": "4b647bf9f8b3edb6e5acdb654e441e826f2a4ecb0dbf705fa344ff433ba07435", + "bytes": 2427 + }, + "qml/QtQuick/Controls/Styles/Desktop/StatusBarStyle.qmlc": { + "sha256": "4c129753818c3c90a973500bfd49a073015c782d5b9fc62ff142e68c0e468b28", + "bytes": 2460 + }, + "qml/QtQuick/Controls/Styles/Desktop/SwitchStyle.qml": { + "sha256": "01f99531a47fdc1467052d97732c0edf81917963217bd6deaca3154841158169", + "bytes": 2067 + }, + "qml/QtQuick/Controls/Styles/Desktop/SwitchStyle.qmlc": { + "sha256": "75173ac42ec7c6fd3a2457b622765014e5b062c581769adaf67faf32f25880c4", + "bytes": 820 + }, + "qml/QtQuick/Controls/Styles/Desktop/TabViewStyle.qml": { + "sha256": "0f44c4cb6c13bbf6ed92ce4f9d3eb5efa71da26c0faf15784e2347303031807a", + "bytes": 5287 + }, + "qml/QtQuick/Controls/Styles/Desktop/TabViewStyle.qmlc": { + "sha256": "884be66995ed30f5861afe8bbb8107b4ce5a1f821eb542b0b27137b53a90f784", + "bytes": 14220 + }, + "qml/QtQuick/Controls/Styles/Desktop/TableViewStyle.qml": { + "sha256": "824762d24050324c7d43d9569479a0cfeb7c778e8a5efbef82e51fd1e2332b09", + "bytes": 5262 + }, + "qml/QtQuick/Controls/Styles/Desktop/TableViewStyle.qmlc": { + "sha256": "e5d1f322532206fba412009a903696e24ad4b078873bd283e6612a4ccfc52569", + "bytes": 13648 + }, + "qml/QtQuick/Controls/Styles/Desktop/TextAreaStyle.qml": { + "sha256": "d0e800ff1b3ecfbc62c802159778ca60a5dbee9a3c798a70dea076d3da46d03e", + "bytes": 2680 + }, + "qml/QtQuick/Controls/Styles/Desktop/TextAreaStyle.qmlc": { + "sha256": "2e53f61b778b82e15e6058351a5c99ee3049266650fdf8ab81b38647f8781f21", + "bytes": 3808 + }, + "qml/QtQuick/Controls/Styles/Desktop/TextFieldStyle.qml": { + "sha256": "f87d6f05ad3cd4f6846ba1b8b5b817213f827ac2c55589e0c9c6c015bfd570eb", + "bytes": 3296 + }, + "qml/QtQuick/Controls/Styles/Desktop/TextFieldStyle.qmlc": { + "sha256": "3f7e9e38fc36cbefa8952277e90118a0754061c24e0416b3752ec563e9e11ea5", + "bytes": 7608 + }, + "qml/QtQuick/Controls/Styles/Desktop/ToolBarStyle.qml": { + "sha256": "94a54ebf53a662e02b3962c2a71553efd40f82901bcdef480913c56462027080", + "bytes": 2495 + }, + "qml/QtQuick/Controls/Styles/Desktop/ToolBarStyle.qmlc": { + "sha256": "84355b6137e982e9c5269c75954b780891106c93540089468dd644e94c4addca", + "bytes": 2784 + }, + "qml/QtQuick/Controls/Styles/Desktop/ToolButtonStyle.qml": { + "sha256": "2e596e43f380153efb90045f10696979d87076e31b52178b12b3544ee363566b", + "bytes": 2615 + }, + "qml/QtQuick/Controls/Styles/Desktop/ToolButtonStyle.qmlc": { + "sha256": "3d3d9590e8931f5d629eb5905261219ebd580d9a0b6cb7cc77fa37065072f2a5", + "bytes": 4156 + }, + "qml/QtQuick/Controls/Styles/Desktop/TreeViewStyle.qml": { + "sha256": "1c645cda72e81f295d03fed5142c502651c9d5f0418788f5f3c53a5720c2351e", + "bytes": 2781 + }, + "qml/QtQuick/Controls/Styles/Desktop/TreeViewStyle.qmlc": { + "sha256": "085e4f6867007438b97c14f3153fb1e9257f2e1a1ba6dbe83301105db6757afb", + "bytes": 3740 + }, + "qml/QtQuick/Controls/Styles/Desktop/qmldir": { + "sha256": "744b972824666b8d9b76eaaff3d1700566fc9120d6c1fa2a4fba769953c26aa2", + "bytes": 70 + }, + "qml/QtQuick/Controls/Styles/Flat/libqtquickextrasflatplugin.so": { + "sha256": "3f94c700e52e1653a44d33e22cbc30e134828e0356d25ac09424224e870b6823", + "bytes": 162752 + }, + "qml/QtQuick/Controls/Styles/Flat/plugins.qmltypes": { + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "bytes": 0 + }, + "qml/QtQuick/Controls/Styles/Flat/qmldir": { + "sha256": "1894e5cdfe7ddddb12533a24478205b64d29e5fca88b20cd06cb3bd7ff14d6f2", + "bytes": 122 + }, + "qml/QtQuick/Controls/Styles/qmldir": { + "sha256": "9e7815c43793cdb76368cff3e5508e1e683d236a040640197bbb93dd83d6dbf1", + "bytes": 1537 + }, + "qml/QtQuick/Controls/Switch.qml": { + "sha256": "d342c114119d0f54bf86095a44ef5895b6596aebb6afb55097614f685a147e99", + "bytes": 5165 + }, + "qml/QtQuick/Controls/Switch.qmlc": { + "sha256": "0b76ad3f1308c959cfcde651c31ad0f4d3451fdc0caf2ca00b73ff732b6bf8ff", + "bytes": 7648 + }, + "qml/QtQuick/Controls/Tab.qml": { + "sha256": "589de75833bf68b3fb4c5f5e8c47c0f948bfb23e16f7da18b84f016636035b69", + "bytes": 2915 + }, + "qml/QtQuick/Controls/Tab.qmlc": { + "sha256": "7f77781ff0d6049f2080bcd8cf37665bf11adb38a9f758203afdf62e984f5fb4", + "bytes": 2212 + }, + "qml/QtQuick/Controls/TabView.qml": { + "sha256": "345f25e31fb7e4106a5880b0a33d7d704ddd49c7656bf8ac8063ed61ffd16bb7", + "bytes": 10446 + }, + "qml/QtQuick/Controls/TabView.qmlc": { + "sha256": "ecbca7153361c1d7aaf5a9fdf5ee28fa5aca9103c065354cc3f0815f9bd259f9", + "bytes": 16284 + }, + "qml/QtQuick/Controls/TableView.qml": { + "sha256": "6da3a4c8079bfaa848cc98d46c1e7a6dcff2be7ec355273220a1386d9215b9eb", + "bytes": 11236 + }, + "qml/QtQuick/Controls/TableView.qmlc": { + "sha256": "16687e3824cba3905b384963bc32ed88f671f7cdff696daacb86ff29b48b216e", + "bytes": 19824 + }, + "qml/QtQuick/Controls/TableViewColumn.qml": { + "sha256": "e6bc2ce248b268fe53d74e52b830929fb84c684d0e1c7a3e5c7347e1274536f4", + "bytes": 6631 + }, + "qml/QtQuick/Controls/TableViewColumn.qmlc": { + "sha256": "afe9b58415d41ac6ded2eae2bd967b6f734bb9f5944cb246cd01d45b52d21c94", + "bytes": 3940 + }, + "qml/QtQuick/Controls/TextArea.qml": { + "sha256": "accaefce99616f0485da074a78a20e6af80f5829adccf2f9f9103cad5c91b090", + "bytes": 35653 + }, + "qml/QtQuick/Controls/TextArea.qmlc": { + "sha256": "1eff2c1f4c44852ec7a17c47d6c12b95dcdfb039ec4a00500a2144f2b01a4b3b", + "bytes": 36040 + }, + "qml/QtQuick/Controls/TextField.qml": { + "sha256": "8e4a151c19cfe545cb5284471a394dfe3eb5373ffca3794cd42192811fbf4b87", + "bytes": 22515 + }, + "qml/QtQuick/Controls/TextField.qmlc": { + "sha256": "2fb831eab3f59538a78fba0eaeac29c3b0337f14a8e2656457dfafdb65f1cc62", + "bytes": 17192 + }, + "qml/QtQuick/Controls/ToolBar.qml": { + "sha256": "1806082dbd55a6c043b404da079499f8ddcf3d703563acb36be9dd3b1887026d", + "bytes": 7262 + }, + "qml/QtQuick/Controls/ToolBar.qmlc": { + "sha256": "bc2c24fd983342ab7a53610dd05e33bc089d27895cb376e25d59cbea8c499d7e", + "bytes": 11004 + }, + "qml/QtQuick/Controls/ToolButton.qml": { + "sha256": "23afca16fd24808d9347b04c7cece6196bf7ed6ab0b0fb4cb2b77252b959e992", + "bytes": 3142 + }, + "qml/QtQuick/Controls/ToolButton.qmlc": { + "sha256": "7abc84bac24c8d7426bf4c9ac08e49f3078b8c31a61833669f690c19c716a75a", + "bytes": 1196 + }, + "qml/QtQuick/Controls/TreeView.qml": { + "sha256": "7db45e9d176a4ce936927f0d01deb0002bab08dbd711bf43021629a827c56bd3", + "bytes": 16646 + }, + "qml/QtQuick/Controls/TreeView.qmlc": { + "sha256": "a54f9bcab866f626cc1dd209bb77dadb260df571a3d09f49b187b2159000be10", + "bytes": 25496 + }, + "qml/QtQuick/Controls/libqtquickcontrolsplugin.so": { + "sha256": "11805bf80eaf20759c369911a67da1166fb2fac412e8ea5d2027a86c84b338d3", + "bytes": 440432 + }, + "qml/QtQuick/Controls/plugins.qmltypes": { + "sha256": "57507acbf69ab0b0df9b9d6ee1958520245bf339a933ae76abc7992b1e8d8f01", + "bytes": 154490 + }, + "qml/QtQuick/Controls/qmldir": { + "sha256": "a433b2373a08e928d12bb1b11918663c871d9f2501da9fa31542fcca84e361ed", + "bytes": 204 + }, + "qml/QtQuick/Controls.2/AbstractButton.qml": { + "sha256": "b369f750f0bdc53e5718acb6b32ad330b681772e41c78ac8cc24844cd0e574f1", + "bytes": 2149 + }, + "qml/QtQuick/Controls.2/Action.qml": { + "sha256": "0a1636a2235e42cc0e88d80076b80d9c91666674b2fdd07f1e6fe407d4776ffb", + "bytes": 1806 + }, + "qml/QtQuick/Controls.2/ActionGroup.qml": { + "sha256": "47cd6bcbde88353eff8e7772e8fce45d7666712d32157ea124e6e2d6837c20b1", + "bytes": 1811 + }, + "qml/QtQuick/Controls.2/ApplicationWindow.qml": { + "sha256": "dd80b561f5e2e9dadb48413f3ba637d1212f57195d32364a26b16f99609aab82", + "bytes": 2151 + }, + "qml/QtQuick/Controls.2/BusyIndicator.qml": { + "sha256": "a1fb654a16e78323c9a8b3e60a83ea0f71f37777f16981a6f9bf13af81cb08ea", + "bytes": 2535 + }, + "qml/QtQuick/Controls.2/Button.qml": { + "sha256": "fecd5ac23371888caf2d7453c628513cf4399a807d5c079eac788297e71802a3", + "bytes": 3517 + }, + "qml/QtQuick/Controls.2/ButtonGroup.qml": { + "sha256": "1ed62b47bce58be9f9b218edb1556fc4554cffba10980e599c3d68f4a7484565", + "bytes": 1811 + }, + "qml/QtQuick/Controls.2/CheckBox.qml": { + "sha256": "043fa812dd6f99b59fdc5b212e64b18982fa88361227baa8ae3e7a68cf5c5271", + "bytes": 3929 + }, + "qml/QtQuick/Controls.2/CheckDelegate.qml": { + "sha256": "f5c0ad39a66bd5305960d5ac0232973e7df5794dbd8bdd3838e90e0af524d070", + "bytes": 4368 + }, + "qml/QtQuick/Controls.2/ComboBox.qml": { + "sha256": "10c7c7f7ed6ccc1249355dd1a67558698903939008bdfb5240597cbb90cacd27", + "bytes": 5792 + }, + "qml/QtQuick/Controls.2/Container.qml": { + "sha256": "53a4cbc38d471ecb080a18dbe46c71f04a415c4c90ea36b0c6b5561675eff554", + "bytes": 2128 + }, + "qml/QtQuick/Controls.2/Control.qml": { + "sha256": "cfd99b6372810d8370ca08ad7d1898a62a5b346cac2a2ec37651894198253770", + "bytes": 2142 + }, + "qml/QtQuick/Controls.2/DelayButton.qml": { + "sha256": "6d6f3f93f28041fdcbb295b631a1a7341dd94ea0907307fc45c4f9e1aded9359", + "bytes": 4058 + }, + "qml/QtQuick/Controls.2/Dial.qml": { + "sha256": "8e4ac3a7e2079fbc95360b0b81f4e38e62d6557b3446771b71c26f5732c118d3", + "bytes": 3414 + }, + "qml/QtQuick/Controls.2/Dialog.qml": { + "sha256": "822d3d0f44598e7f1725b9564e7c2073ef72f01a34c83b71baea28b4d8151b25", + "bytes": 3224 + }, + "qml/QtQuick/Controls.2/DialogButtonBox.qml": { + "sha256": "1970fdc6441e0cf983c62e3c6d2e7bd5f8790d227834e75e27d37f540f7ac12c", + "bytes": 2888 + }, + "qml/QtQuick/Controls.2/Drawer.qml": { + "sha256": "3e1e813b908aa2fb9bc8466aa50d6cae1ce30e9a91d021f8d60fd7a105fd698f", + "bytes": 3222 + }, + "qml/QtQuick/Controls.2/Frame.qml": { + "sha256": "b5c590e9c7e9658d01ae3eba623c53ad2398ee31965f1845e73b72307c8b8f16", + "bytes": 2310 + }, + "qml/QtQuick/Controls.2/Fusion/ApplicationWindow.qml": { + "sha256": "df8292d83c5f57493caa60681373b03ca0412c633dfb289bf3ec90b12e0d3b67", + "bytes": 2105 + }, + "qml/QtQuick/Controls.2/Fusion/BusyIndicator.qml": { + "sha256": "a3aae8376a820e079e9294c7cd425bfedbf631adbb0b5886141ccec69198e4a5", + "bytes": 2793 + }, + "qml/QtQuick/Controls.2/Fusion/Button.qml": { + "sha256": "c6de8e10e8d669200a53f5d621d88b798b2b04d870b304e119b635c3b071916d", + "bytes": 2860 + }, + "qml/QtQuick/Controls.2/Fusion/ButtonPanel.qml": { + "sha256": "df456eb18d65c41c069ef335206dbb2de9633b83e9c64c886e22aa65bfa1955e", + "bytes": 3038 + }, + "qml/QtQuick/Controls.2/Fusion/CheckBox.qml": { + "sha256": "c6570f07ffec9ad4f2067bdd9211b9f80de2f0498d6817abe768010e33f186db", + "bytes": 3127 + }, + "qml/QtQuick/Controls.2/Fusion/CheckDelegate.qml": { + "sha256": "4ddba22889db1d9112b10837b5281fb2eb0d7c9388816e047c22afd4b4e7cec5", + "bytes": 3589 + }, + "qml/QtQuick/Controls.2/Fusion/CheckIndicator.qml": { + "sha256": "7f49691b8f77e707c2471dd81b48c88be9fa33739dd05918c829e3619c9b35a8", + "bytes": 3630 + }, + "qml/QtQuick/Controls.2/Fusion/ComboBox.qml": { + "sha256": "bcfd9c8a52b676b3f44d5b7220b811c0fd96a62a002ffa82294c1d0e3ca0f05e", + "bytes": 6586 + }, + "qml/QtQuick/Controls.2/Fusion/DelayButton.qml": { + "sha256": "f4ad1897c3c1fd97778d085bd4cb67e302ddff16f9bc81870debf6069b5e8e0a", + "bytes": 4437 + }, + "qml/QtQuick/Controls.2/Fusion/Dial.qml": { + "sha256": "3537d70b3db7dd850af74bd6d5cfcdcf925baf08d5732da7cf51032d6792cb63", + "bytes": 3179 + }, + "qml/QtQuick/Controls.2/Fusion/Dialog.qml": { + "sha256": "c7be6655ff290e9f4f993b5ad9762ada3f1733ec015d9e24e6aca9972929aabc", + "bytes": 3504 + }, + "qml/QtQuick/Controls.2/Fusion/DialogButtonBox.qml": { + "sha256": "0617af37ce94cab043e0cf5c8ce103281d851ccdea7552e416febcdb72568ced", + "bytes": 2829 + }, + "qml/QtQuick/Controls.2/Fusion/Drawer.qml": { + "sha256": "b2137c2d0add938a51177ec4b27c47364b06058f53c206f4965a8db862981906", + "bytes": 3584 + }, + "qml/QtQuick/Controls.2/Fusion/Frame.qml": { + "sha256": "b9792962fb23a8c5e20fea3789e649e822e42edc4d680ee3d5cb541d0267fac4", + "bytes": 2416 + }, + "qml/QtQuick/Controls.2/Fusion/GroupBox.qml": { + "sha256": "459c254f1403f7468467eaabd5a2d2c1dd07344805c7e95a667a68a91a339f4f", + "bytes": 3064 + }, + "qml/QtQuick/Controls.2/Fusion/HorizontalHeaderView.qml": { + "sha256": "530d65e74a8f6fbe7903561411e98b4ead6191cd536a2b5a3acf7bb8d50b40ee", + "bytes": 2987 + }, + "qml/QtQuick/Controls.2/Fusion/ItemDelegate.qml": { + "sha256": "6b55ada93bfaa50e82817637b4ba931fc2fecba89c498bc09961a3346b4f8fbc", + "bytes": 3180 + }, + "qml/QtQuick/Controls.2/Fusion/Label.qml": { + "sha256": "71bed6d9861c483918e5eb79b3f3629aa77cb2c3eeeec98ceeab5889bd137f95", + "bytes": 2036 + }, + "qml/QtQuick/Controls.2/Fusion/Menu.qml": { + "sha256": "95bf55f075f9e0f473703df36d3fc4a84a93607bee3f3a22abc361c24fc8a2bb", + "bytes": 3296 + }, + "qml/QtQuick/Controls.2/Fusion/MenuBar.qml": { + "sha256": "ac1961de85656fcac02bf6aa294afe8a14d87daf431da0b2c78c45e939bbafcb", + "bytes": 2825 + }, + "qml/QtQuick/Controls.2/Fusion/MenuBarItem.qml": { + "sha256": "675a912645b0946f5febfabc06ef3ecb05f0626c1ca3851bec2c9c75eb9ce86d", + "bytes": 2998 + }, + "qml/QtQuick/Controls.2/Fusion/MenuItem.qml": { + "sha256": "8a8981dc7b9d220d0e821d4d67516cb0a04521654764df408521be0f3c9e9054", + "bytes": 4209 + }, + "qml/QtQuick/Controls.2/Fusion/MenuSeparator.qml": { + "sha256": "449da7282a1b9d955e9268232687b2cc3b2615ac08a1c3e71eebb97429b68967", + "bytes": 2466 + }, + "qml/QtQuick/Controls.2/Fusion/Page.qml": { + "sha256": "2e993869d902818d73b3402376c4a05bc04eeda53ff09b1ab16b4e2704f8dea4", + "bytes": 2624 + }, + "qml/QtQuick/Controls.2/Fusion/PageIndicator.qml": { + "sha256": "a0bb90e926d03564de7e0d0911d957c026fa90dd5b346a8abc513cbfa01b7ad9", + "bytes": 2771 + }, + "qml/QtQuick/Controls.2/Fusion/Pane.qml": { + "sha256": "0a23b5c813ed01e377c51f5285ff45a4e17a06ce12b892fd8025e95798cef086", + "bytes": 2352 + }, + "qml/QtQuick/Controls.2/Fusion/Popup.qml": { + "sha256": "9439aae83297dd98b7cfb66a66ddc68456d0e108ae494e102d34a3033cd359a9", + "bytes": 2560 + }, + "qml/QtQuick/Controls.2/Fusion/ProgressBar.qml": { + "sha256": "1a170b40aa711ae1dcff92c33b60c6c8ee65032fc167a1b62246c3446548782d", + "bytes": 4328 + }, + "qml/QtQuick/Controls.2/Fusion/RadioButton.qml": { + "sha256": "1664f5aacf3ca7e753782e581f9ef275f3e86f00276bee7c606de54fd2992a74", + "bytes": 3130 + }, + "qml/QtQuick/Controls.2/Fusion/RadioDelegate.qml": { + "sha256": "fc4c912d9dfa43b57fcee7ac4d01c4b44ea148c8e134829f6e4d1a555eb6d615", + "bytes": 3589 + }, + "qml/QtQuick/Controls.2/Fusion/RadioIndicator.qml": { + "sha256": "fd2e040e558e3dd008d687b61869b96ee3cdedcf40db0267135f97275d41a579", + "bytes": 3108 + }, + "qml/QtQuick/Controls.2/Fusion/RangeSlider.qml": { + "sha256": "0c3168ef834c93e8d779c3a233426eba4e052af4ebf54ebccf7b3d748bafaa9d", + "bytes": 3773 + }, + "qml/QtQuick/Controls.2/Fusion/RoundButton.qml": { + "sha256": "798b444f64355aba7cb3dcd32d98cf2575d5ac7e920524199f053413867cb9c8", + "bytes": 4011 + }, + "qml/QtQuick/Controls.2/Fusion/ScrollBar.qml": { + "sha256": "694037e4aafc14fba4cf46af3a388dc797102ce7b9a9b72f72352dc7d153d02c", + "bytes": 3212 + }, + "qml/QtQuick/Controls.2/Fusion/ScrollIndicator.qml": { + "sha256": "53fc70cd872a15b3f5457a90bd27353e0dbf4ced63ad4d3d1c10cc70fea9ccb6", + "bytes": 2982 + }, + "qml/QtQuick/Controls.2/Fusion/Slider.qml": { + "sha256": "674e0d7dc60b296587ee451e5651c800255179f542f09ee6e91bbb95d2e57441", + "bytes": 2963 + }, + "qml/QtQuick/Controls.2/Fusion/SliderGroove.qml": { + "sha256": "b517ce4c73ed698e1cb69053db32e6cf2f9f7c996e070160205805d3aa8c768c", + "bytes": 3677 + }, + "qml/QtQuick/Controls.2/Fusion/SliderHandle.qml": { + "sha256": "80afc508788874662b2843ad200bc3e44f980cfae225c150a5a6e0f233b02dbf", + "bytes": 3095 + }, + "qml/QtQuick/Controls.2/Fusion/SpinBox.qml": { + "sha256": "7ad92947e5af162688c227960675a59d54d28182fa2aed75190c23c37383781a", + "bytes": 6725 + }, + "qml/QtQuick/Controls.2/Fusion/SplitView.qml": { + "sha256": "f77504543c02ae646129c6cef29681a4d1a729c05d8cc3537bcba6975edadde3", + "bytes": 2576 + }, + "qml/QtQuick/Controls.2/Fusion/SwipeDelegate.qml": { + "sha256": "201a743a87376c85ebf31b6df896b850c2faf0759f0bfe6bc3d2d3c70b1578b5", + "bytes": 3285 + }, + "qml/QtQuick/Controls.2/Fusion/Switch.qml": { + "sha256": "35c893c877442ea7fee4e0500a95c69e764f11802ba6c4d6b70f33b1edc38e47", + "bytes": 3120 + }, + "qml/QtQuick/Controls.2/Fusion/SwitchDelegate.qml": { + "sha256": "06b5b5947276d53c0bb9355ced7b596c0c18595ffdcfa82e5dc2f7871027e75f", + "bytes": 3668 + }, + "qml/QtQuick/Controls.2/Fusion/SwitchIndicator.qml": { + "sha256": "e1358000c3f6a9fd6ef19dfa93603046f5f485da0c73e3982913ae9bf00034b4", + "bytes": 4996 + }, + "qml/QtQuick/Controls.2/Fusion/TabBar.qml": { + "sha256": "89db44d711b48d9f0d3c58b4a0cb9e0b318e18baae28195cdb1f5b41e1a438f0", + "bytes": 3041 + }, + "qml/QtQuick/Controls.2/Fusion/TabButton.qml": { + "sha256": "3612bc9acb1c9b5769ea6ce81ea6affbaba7e668c1b78117b43cf9739a06871c", + "bytes": 3765 + }, + "qml/QtQuick/Controls.2/Fusion/TextArea.qml": { + "sha256": "a058945bc46e25e22a15f8f9deabf64bf69c748147a6e97c4f19663ec0785ef1", + "bytes": 3315 + }, + "qml/QtQuick/Controls.2/Fusion/TextField.qml": { + "sha256": "3f828903c1a6827b817320585b9b12baf87e8d6dbdd322e1c3265f4eae2c0b8a", + "bytes": 4017 + }, + "qml/QtQuick/Controls.2/Fusion/ToolBar.qml": { + "sha256": "f732bed89b4eed15d83f4ae1f51212b6e0fffc807184d2a182e1931a4580cddd", + "bytes": 3169 + }, + "qml/QtQuick/Controls.2/Fusion/ToolButton.qml": { + "sha256": "1572e8ffcdc1623bbf7955d5e66d1b9a513219076d565305d8aac0573afb2878", + "bytes": 2847 + }, + "qml/QtQuick/Controls.2/Fusion/ToolSeparator.qml": { + "sha256": "92d23ed1baf07cb778fb2992b1d635f330ad487db9071de7c0be3fcc212cad80", + "bytes": 2690 + }, + "qml/QtQuick/Controls.2/Fusion/ToolTip.qml": { + "sha256": "692b126fa65255d9c503d9d6fa4e553c7867b3e80b5e86cfee18fd533c8b3d69", + "bytes": 2983 + }, + "qml/QtQuick/Controls.2/Fusion/Tumbler.qml": { + "sha256": "c02a9c0344a328db9f8cb636024b097a10d3a98abdd0e01b42503428858b3ea0", + "bytes": 3279 + }, + "qml/QtQuick/Controls.2/Fusion/VerticalHeaderView.qml": { + "sha256": "5efcee7d66ae151e31fc95eb405dea982080047cd91b4f3ad8e97ca67a0f9ff4", + "bytes": 2984 + }, + "qml/QtQuick/Controls.2/Fusion/libqtquickcontrols2fusionstyleplugin.so": { + "sha256": "a60327874ea88764da3a9d5816a02ed260d6d6e2666e7a8a273df1dc9f8124b9", + "bytes": 626024 + }, + "qml/QtQuick/Controls.2/Fusion/plugins.qmltypes": { + "sha256": "a7efbb532161afafc3105b6e7a5040dccc5e9a45dbc7ad8c6f92de616ac6bcb1", + "bytes": 15651 + }, + "qml/QtQuick/Controls.2/Fusion/qmldir": { + "sha256": "d2fe391965135cfac074d7ecee96e4fb250a64961bd0d38eb04de4bbdcb7608a", + "bytes": 145 + }, + "qml/QtQuick/Controls.2/GroupBox.qml": { + "sha256": "e287d4a3d19485d3103ab3722954721911d8a983c588f6c3a634230bc963e811", + "bytes": 2918 + }, + "qml/QtQuick/Controls.2/HorizontalHeaderView.qml": { + "sha256": "1adfdb7e95134eeaa36c900cc54b5a6eb1c0f5dd1798e061f629522a37d91b74", + "bytes": 2768 + }, + "qml/QtQuick/Controls.2/Imagine/ApplicationWindow.qml": { + "sha256": "194050d1e5dade0b585d174307eebdb493b5134be92b92f5e391b9793a7c3229", + "bytes": 2714 + }, + "qml/QtQuick/Controls.2/Imagine/BusyIndicator.qml": { + "sha256": "fa6807ebf140661edfeb20cc5a43d5d44de9065e6e07887b4a9a582d1c32e0b9", + "bytes": 3649 + }, + "qml/QtQuick/Controls.2/Imagine/Button.qml": { + "sha256": "db6330e90ca2ea9b1c3756afc96a6ae43851fef8c737605e0b660c57dc4e8a96", + "bytes": 4273 + }, + "qml/QtQuick/Controls.2/Imagine/CheckBox.qml": { + "sha256": "8e117a1ebce0b83139a6b0d2a332b80c29bd1b7c371bc35c7d40b19fb7853532", + "bytes": 4565 + }, + "qml/QtQuick/Controls.2/Imagine/CheckDelegate.qml": { + "sha256": "c922e6d23a4852e00770ca9a9b137fddb024b65fe7ab015484df8a23fe8945fa", + "bytes": 4906 + }, + "qml/QtQuick/Controls.2/Imagine/ComboBox.qml": { + "sha256": "36c770305deb76acad38e0e70d7bf17904bfb850bdc8fe6fb6054ba203a71db0", + "bytes": 7428 + }, + "qml/QtQuick/Controls.2/Imagine/DelayButton.qml": { + "sha256": "32006040f727519c857817a8f433711d9469aa10a56bdd31fc4ee9a4d1318f9c", + "bytes": 5419 + }, + "qml/QtQuick/Controls.2/Imagine/Dial.qml": { + "sha256": "0bfc38c3ef419862ac88e77aa64b5b5c262e7767ad152bf3142c529d514521ee", + "bytes": 4223 + }, + "qml/QtQuick/Controls.2/Imagine/Dialog.qml": { + "sha256": "f35988dd9070edf40ba58d6b038db4e56a50546d077926a76eff6fbe19be30ae", + "bytes": 4265 + }, + "qml/QtQuick/Controls.2/Imagine/DialogButtonBox.qml": { + "sha256": "c0389167c5f02e9e4df39965fe8c4c1763779c2164dab38ad05f36480d090b45", + "bytes": 3449 + }, + "qml/QtQuick/Controls.2/Imagine/Drawer.qml": { + "sha256": "29e22ebfee920bdd78b64d5579b58f6227d32aec9b8955664f349201a14318b7", + "bytes": 3755 + }, + "qml/QtQuick/Controls.2/Imagine/Frame.qml": { + "sha256": "2d935b3a54d6ce95b9ca414e6d57ea729ee7fd3570b02248e84e697c5c1d7721", + "bytes": 2950 + }, + "qml/QtQuick/Controls.2/Imagine/GroupBox.qml": { + "sha256": "319079ae6fe851ecee4bfd916235ce185a77a741f954ce98b292189e9b434a7a", + "bytes": 3914 + }, + "qml/QtQuick/Controls.2/Imagine/HorizontalHeaderView.qml": { + "sha256": "1adfdb7e95134eeaa36c900cc54b5a6eb1c0f5dd1798e061f629522a37d91b74", + "bytes": 2768 + }, + "qml/QtQuick/Controls.2/Imagine/ItemDelegate.qml": { + "sha256": "351e63630cfe4034b7cf2345513fdcc15b070cbe69da14ecd9a73a820899369a", + "bytes": 3812 + }, + "qml/QtQuick/Controls.2/Imagine/Label.qml": { + "sha256": "929bb2d1bf78ddb4daea8fc7306bf31200e292793e03bd30efc7bcdc7c78a166", + "bytes": 2535 + }, + "qml/QtQuick/Controls.2/Imagine/Menu.qml": { + "sha256": "a316d00b24b054828d894990990c59111b3b1dd649872fa139cdb7939caf03ac", + "bytes": 4066 + }, + "qml/QtQuick/Controls.2/Imagine/MenuItem.qml": { + "sha256": "dc741d25136abec50e9f01df7d3fbcb405a3b6eb45fa9b9832019348818c035a", + "bytes": 5627 + }, + "qml/QtQuick/Controls.2/Imagine/MenuSeparator.qml": { + "sha256": "817001b35a0513998b4c9ee0447072d15730824f98b02edd598848a799480652", + "bytes": 3263 + }, + "qml/QtQuick/Controls.2/Imagine/Page.qml": { + "sha256": "1768920871719aaafe7efe1e75714fb6b57a2f2ba70169d31f65271072ce9e71", + "bytes": 3236 + }, + "qml/QtQuick/Controls.2/Imagine/PageIndicator.qml": { + "sha256": "2bc9ace641b7923891ab10cb9a4d3bdc0a94274538f48871d4c95fce30cceb6d", + "bytes": 3627 + }, + "qml/QtQuick/Controls.2/Imagine/Pane.qml": { + "sha256": "34b01b1cadd9d186784996258bb0ca1e0d5827f18d9ae418d9b58117feec8597", + "bytes": 2948 + }, + "qml/QtQuick/Controls.2/Imagine/Popup.qml": { + "sha256": "a97e4a2e7614871875550c7922c9828e7469deeb446d6166786168b2c8fcdb33", + "bytes": 3394 + }, + "qml/QtQuick/Controls.2/Imagine/ProgressBar.qml": { + "sha256": "a059ebb05b3f17724667c54c3b1d5bf027c81140f716fc294ab037d7ba09f4e2", + "bytes": 5845 + }, + "qml/QtQuick/Controls.2/Imagine/RadioButton.qml": { + "sha256": "806790cdb4d99e96e11a433e96d4188a5868b89a60859baded50824a2c71c378", + "bytes": 4380 + }, + "qml/QtQuick/Controls.2/Imagine/RadioDelegate.qml": { + "sha256": "2e7e5ec0fc2f3b77611c8f76ba72418815c7bc1f722d763ab4e6cb63f667ab84", + "bytes": 4704 + }, + "qml/QtQuick/Controls.2/Imagine/RangeSlider.qml": { + "sha256": "f290f5bf0124e1c2847a512e1f5180a419b3622686125826eeeff87bc8b66a68", + "bytes": 6444 + }, + "qml/QtQuick/Controls.2/Imagine/RoundButton.qml": { + "sha256": "85cef6b3f7e95fbadf882b5c1dd3e1c7ea9e0811ee27d302a34ec709911d430a", + "bytes": 4289 + }, + "qml/QtQuick/Controls.2/Imagine/ScrollBar.qml": { + "sha256": "7d13da04b1fc0167f0fd76d9d4a775988269f506c2feaa5b040a5af245f89aa5", + "bytes": 4757 + }, + "qml/QtQuick/Controls.2/Imagine/ScrollIndicator.qml": { + "sha256": "d08cfa4a87e1942717efb2e956ac3dbd959d3be2a0d4f9e3b36e05b6760ac466", + "bytes": 4263 + }, + "qml/QtQuick/Controls.2/Imagine/Slider.qml": { + "sha256": "03287877c2f5bcd41881f0d625beb1f5e223570fdcdc41784a5ee772bf254b15", + "bytes": 5251 + }, + "qml/QtQuick/Controls.2/Imagine/SpinBox.qml": { + "sha256": "13affbbbf1a6cf48964eb714cc2ed258977871141c7ffdeac272999c35a34c59", + "bytes": 5951 + }, + "qml/QtQuick/Controls.2/Imagine/SplitView.qml": { + "sha256": "dec5335a7346c03c62c87342c0fe6a432ae3928285c377109f1b5ae46182a92f", + "bytes": 2733 + }, + "qml/QtQuick/Controls.2/Imagine/StackView.qml": { + "sha256": "f42f6bc9863add77378c531947c5eb02457eba684da6a46fdf95cd56205cb87b", + "bytes": 3702 + }, + "qml/QtQuick/Controls.2/Imagine/SwipeDelegate.qml": { + "sha256": "fc8f566d376210138e1be4772f14d85a13bf0605e8c5076b3f8be64c4095b1d5", + "bytes": 3918 + }, + "qml/QtQuick/Controls.2/Imagine/SwipeView.qml": { + "sha256": "13015724ebd2d363019d10719cdb4a7f0c533792b337403e66a7992e90c3520c", + "bytes": 3681 + }, + "qml/QtQuick/Controls.2/Imagine/Switch.qml": { + "sha256": "9a0155fbebff5db00c4cc5e2e10eabaefeb36d3bb6ee9871cde3fe3654ae5bad", + "bytes": 5701 + }, + "qml/QtQuick/Controls.2/Imagine/SwitchDelegate.qml": { + "sha256": "66ff359df6b39c3710ceb2a72492685019ccead7fa62a3813869fcdbc942e401", + "bytes": 6187 + }, + "qml/QtQuick/Controls.2/Imagine/TabBar.qml": { + "sha256": "9fb4daa4361634d64e99851ef92400eaac4e710039a63ee61acb6e3158dc5d87", + "bytes": 3576 + }, + "qml/QtQuick/Controls.2/Imagine/TabButton.qml": { + "sha256": "089091caa5644cbd171d7505deabb69861a3f8718ea81a35830f6489c89a3ed8", + "bytes": 3589 + }, + "qml/QtQuick/Controls.2/Imagine/TextArea.qml": { + "sha256": "6b6529f21183d26d45f4ab8325b623372f5246faf4fc46f9a0ceaef3e1dae74e", + "bytes": 4157 + }, + "qml/QtQuick/Controls.2/Imagine/TextField.qml": { + "sha256": "ba74d45b5e76212427d839e1b46703199fe781ec7b1c5b99b3cfa706de71e1be", + "bytes": 4095 + }, + "qml/QtQuick/Controls.2/Imagine/ToolBar.qml": { + "sha256": "abe0fac476eb476e3f58ec4655828e53dadccbec01088095e00f37d4e5473b2d", + "bytes": 3090 + }, + "qml/QtQuick/Controls.2/Imagine/ToolButton.qml": { + "sha256": "8f05d592132dde92d08cac11e6bbd902fe62c7957e5d0a71fa4c8458cb2c74a6", + "bytes": 3735 + }, + "qml/QtQuick/Controls.2/Imagine/ToolSeparator.qml": { + "sha256": "9425fe484681b09ade62b2c2ee01cd8466756e4f9ef9ed2c584789bec21f094d", + "bytes": 3463 + }, + "qml/QtQuick/Controls.2/Imagine/ToolTip.qml": { + "sha256": "ad7adc4a8653b059d304ef4305d031dbdefc37f6ef6fe9fdb65351dd0a7e095a", + "bytes": 3535 + }, + "qml/QtQuick/Controls.2/Imagine/Tumbler.qml": { + "sha256": "91d0f105b5dba3631fef30a8582572c8e8ee0a0d57351ab1a3e7ccf3dde640c2", + "bytes": 3887 + }, + "qml/QtQuick/Controls.2/Imagine/VerticalHeaderView.qml": { + "sha256": "4b0530b34dbb2e48206397b6b0e98bd319b2519c591221ae72c512827170519f", + "bytes": 2765 + }, + "qml/QtQuick/Controls.2/Imagine/libqtquickcontrols2imaginestyleplugin.so": { + "sha256": "9ff36cde5b51ea8391913183b10dd646134582305ee6bfc03d66f49c0a7a2dac", + "bytes": 1646512 + }, + "qml/QtQuick/Controls.2/Imagine/plugins.qmltypes": { + "sha256": "3eb247ad059a9793848632b28fe50934815d388dd36c8fea7805afc83ac91b26", + "bytes": 13301 + }, + "qml/QtQuick/Controls.2/Imagine/qmldir": { + "sha256": "f0abedee843df7f0d0bbdff5dd7cc15f88c7b2367a34da1bddbae5b6b097d751", + "bytes": 179 + }, + "qml/QtQuick/Controls.2/ItemDelegate.qml": { + "sha256": "47fbb35e81b878da119cad513ac280bf955dc168af74a0ff4d833b9a971d26da", + "bytes": 3210 + }, + "qml/QtQuick/Controls.2/Label.qml": { + "sha256": "2d64ba6a95908b9bdd7cf73c672f8a66f0a11b35b3e6ea452104c2a2615fa62d", + "bytes": 1959 + }, + "qml/QtQuick/Controls.2/Material/ApplicationWindow.qml": { + "sha256": "dffcb1385569311ff12113b5a1a277c0accdfe7d5a61e035b2b061fb94de2fb1", + "bytes": 2245 + }, + "qml/QtQuick/Controls.2/Material/BoxShadow.qml": { + "sha256": "0704c5fc37764e1b33c10975815c5c8473fd6926f6c792e43d76817203f77342", + "bytes": 2841 + }, + "qml/QtQuick/Controls.2/Material/BusyIndicator.qml": { + "sha256": "284ad09c72b504bcb2fce05f042017eb17c2ed632bdca9bf94569643fb27dda9", + "bytes": 2579 + }, + "qml/QtQuick/Controls.2/Material/Button.qml": { + "sha256": "fe27fbe672c0164da00bccbc8d2083d07f7bd54a638fec719c83ac05a80d9fca", + "bytes": 4773 + }, + "qml/QtQuick/Controls.2/Material/CheckBox.qml": { + "sha256": "5a3d522ad419d01d88522f6af8e73ab4ebbf5672f4746bb14ffaa7292e6455c2", + "bytes": 3568 + }, + "qml/QtQuick/Controls.2/Material/CheckDelegate.qml": { + "sha256": "733eda446aab8d0a48ee73d0f02cd5f37f6ee3ecd3ea32318b3b8931ca17d3f2", + "bytes": 3967 + }, + "qml/QtQuick/Controls.2/Material/CheckIndicator.qml": { + "sha256": "c81fd772cd9ccdbc619429b6128c37fa153c0fc3b45d1623dfdd6dde2942dd6b", + "bytes": 4034 + }, + "qml/QtQuick/Controls.2/Material/ComboBox.qml": { + "sha256": "e8e6d0df3da7bc27317b8bba312fa672ce8b9b5e6d3ccaf1b7d1de70366d309b", + "bytes": 7469 + }, + "qml/QtQuick/Controls.2/Material/CursorDelegate.qml": { + "sha256": "ea504bca026cfc426c0926c9b859d52b82834997b085448008f15232df669495", + "bytes": 2551 + }, + "qml/QtQuick/Controls.2/Material/DelayButton.qml": { + "sha256": "b4f316fdc1ecd44896f0168054722351325b0be9599ff8d6221017afaccf78bf", + "bytes": 4354 + }, + "qml/QtQuick/Controls.2/Material/Dial.qml": { + "sha256": "a4bb02f82b8ccc64403445775210318ba47c0dfb618a29832fab87ced9b92088", + "bytes": 3458 + }, + "qml/QtQuick/Controls.2/Material/Dialog.qml": { + "sha256": "26887eb7232ad5d5d8cc85079fe4c33075e5affc57eb466fe9e0a25c10f458f9", + "bytes": 4245 + }, + "qml/QtQuick/Controls.2/Material/DialogButtonBox.qml": { + "sha256": "f1eecb29ce9c35a2d0a4c95bb17a7d6ed380b54539db8f424c0b2732d77ccbd7", + "bytes": 3164 + }, + "qml/QtQuick/Controls.2/Material/Drawer.qml": { + "sha256": "6d436f5fbf7192dbd53f38085c940642fd5288aba0b788622a710f595b6f32aa", + "bytes": 3776 + }, + "qml/QtQuick/Controls.2/Material/ElevationEffect.qml": { + "sha256": "a8fd5bb0f254842ae13fc0127606451b9fac32d59bdf9de2fae469db6b610f98", + "bytes": 9751 + }, + "qml/QtQuick/Controls.2/Material/Frame.qml": { + "sha256": "79892596f2ba4fb8d73a03b704ec4e5abe3b10cea1a1d4e3f1c8af3e7a438836", + "bytes": 2647 + }, + "qml/QtQuick/Controls.2/Material/GroupBox.qml": { + "sha256": "26efe5a67de43a5a7c24ad9e89b372ccdb93bdfeeb04b64e7dad6f452f9c9b89", + "bytes": 3327 + }, + "qml/QtQuick/Controls.2/Material/HorizontalHeaderView.qml": { + "sha256": "353e9dc4c6305bfdccc0cfd706112487af1d08c966081327d9be8de992d6ea0b", + "bytes": 2899 + }, + "qml/QtQuick/Controls.2/Material/ItemDelegate.qml": { + "sha256": "4d68f69d0544a3b8cc61512914a04b144937d1bfeab9782bf4d3bd4ca920c33e", + "bytes": 3481 + }, + "qml/QtQuick/Controls.2/Material/Label.qml": { + "sha256": "3c82af535f8803c1d71550caaea674e14c6626fe8b2f40c95519428f61224c8e", + "bytes": 1962 + }, + "qml/QtQuick/Controls.2/Material/Menu.qml": { + "sha256": "d2979683bf77c405c5248d7331bf14c697d6901d3b5b3de02078ffc4c90aac02", + "bytes": 4054 + }, + "qml/QtQuick/Controls.2/Material/MenuBar.qml": { + "sha256": "4443cbeebeb6b469f504d90c39cb38aa909f6af238d9a1355733eefa3fcf9acb", + "bytes": 2539 + }, + "qml/QtQuick/Controls.2/Material/MenuBarItem.qml": { + "sha256": "d37bcaa350fb7ac505d4461f0191300a04719cb94d0bab9e29a6bba3679be7c2", + "bytes": 3353 + }, + "qml/QtQuick/Controls.2/Material/MenuItem.qml": { + "sha256": "f12b781a02be6ac9f951aee134432a1ef8f4d8f5d8eba49322970fd6dcf27343", + "bytes": 4676 + }, + "qml/QtQuick/Controls.2/Material/MenuSeparator.qml": { + "sha256": "52e79af34c684b5481e3868d715e88a67adcec8916d000ea7c378fe1af64a90e", + "bytes": 2344 + }, + "qml/QtQuick/Controls.2/Material/Page.qml": { + "sha256": "23ed26fdd67935be2cdbcbeb7abf690e11791ea1b4582e4150a87cd2c05a04d8", + "bytes": 2532 + }, + "qml/QtQuick/Controls.2/Material/PageIndicator.qml": { + "sha256": "d4e33da8e2907a51eb372f042f791d92ddc10c99eeb199f2c307ada3b8f556f4", + "bytes": 2724 + }, + "qml/QtQuick/Controls.2/Material/Pane.qml": { + "sha256": "e56e135757aaee169d583478e74c5f4ba064b6e06ae2f039b13b3107d118cf89", + "bytes": 2533 + }, + "qml/QtQuick/Controls.2/Material/Popup.qml": { + "sha256": "6f8d9fd444824f488f865d61a79f5d769e7109b13f127cd76f480ecf26fe8e3a", + "bytes": 3379 + }, + "qml/QtQuick/Controls.2/Material/ProgressBar.qml": { + "sha256": "c30bee2dcb19e72cfb7dd023027ffccb0d86c3b9d65d2c03d7c9562da8c38c7e", + "bytes": 2753 + }, + "qml/QtQuick/Controls.2/Material/RadioButton.qml": { + "sha256": "5ba925633952fb7ebf4f65f0c469f1e36b328b70ac2d7c1587821fe175265c98", + "bytes": 3571 + }, + "qml/QtQuick/Controls.2/Material/RadioDelegate.qml": { + "sha256": "9f6832e6213ce2bef9f22bc8dab6a8dc1086b0724bc3593c76ea035732dcdf87", + "bytes": 3967 + }, + "qml/QtQuick/Controls.2/Material/RadioIndicator.qml": { + "sha256": "c001457d64a3a78434f9242622d0a8b78632fb704dd526ee8a0681f643c3f74a", + "bytes": 2457 + }, + "qml/QtQuick/Controls.2/Material/RangeSlider.qml": { + "sha256": "3db98efe388512c21b78acb580e34a87de608693fc278750278737cbe3a9aab5", + "bytes": 4665 + }, + "qml/QtQuick/Controls.2/Material/RectangularGlow.qml": { + "sha256": "930fdfb3fb652e3075d5e8b4c26f0341eecc90716b4467ca5e9e7089b5ff586b", + "bytes": 8069 + }, + "qml/QtQuick/Controls.2/Material/RoundButton.qml": { + "sha256": "a9396266be264a55b85a0d30a2a8501ed06cc3f001a177a675889ed3d38d1277", + "bytes": 4587 + }, + "qml/QtQuick/Controls.2/Material/ScrollBar.qml": { + "sha256": "4d1f363426cd19ea25dcceefe64a189b6da003d86bb08618d2bcd6df5e30fe11", + "bytes": 3682 + }, + "qml/QtQuick/Controls.2/Material/ScrollIndicator.qml": { + "sha256": "6fb415aabbf5eb983e5f4169fc5f9fcd02962c30db558b7e843d0d5491cadd5a", + "bytes": 2892 + }, + "qml/QtQuick/Controls.2/Material/Slider.qml": { + "sha256": "26c4a60d051f36a3b5168b1b1b3068cb715a01f3fa587975aa21bec58ac1acd1", + "bytes": 3882 + }, + "qml/QtQuick/Controls.2/Material/SliderHandle.qml": { + "sha256": "08407c69fa7866e0c0d6114e1608565fed0182f19524f9eb1b9c1f8634ee9e03", + "bytes": 2856 + }, + "qml/QtQuick/Controls.2/Material/SpinBox.qml": { + "sha256": "ad2efb11f26ef11a2b71982dae0f12a4750dea529f665d9616ee72024db43ad0", + "bytes": 6069 + }, + "qml/QtQuick/Controls.2/Material/SplitView.qml": { + "sha256": "e4d3dff0157de402945f268525f8b20c9e09559571d246d98d7b825d7afbe4d4", + "bytes": 3241 + }, + "qml/QtQuick/Controls.2/Material/StackView.qml": { + "sha256": "95af931b09eb7a49b0107a51c916d6334d4518080312d794781db37bcae7dfa3", + "bytes": 3806 + }, + "qml/QtQuick/Controls.2/Material/SwipeDelegate.qml": { + "sha256": "528512993a4e4c17a2de8160d3d58b310b04c70aa76d02349f4aa91a0c9c10e5", + "bytes": 3788 + }, + "qml/QtQuick/Controls.2/Material/SwipeView.qml": { + "sha256": "ecc98f964fc99350cbbd21c292c842cd2d4844179ab4f067f9a7192468e21e89", + "bytes": 2764 + }, + "qml/QtQuick/Controls.2/Material/Switch.qml": { + "sha256": "a3924430017998cd2912632d8494b94bd85d91b7ef2b8a132d8069c96313471e", + "bytes": 3533 + }, + "qml/QtQuick/Controls.2/Material/SwitchDelegate.qml": { + "sha256": "e492b067adb97e9a0358e0789eaccc615a01ac095d34e22d25ff2dbf79f8afe2", + "bytes": 4006 + }, + "qml/QtQuick/Controls.2/Material/SwitchIndicator.qml": { + "sha256": "98a94cd9e74d46a70d479fc8a5c944023d7d8bb848c9b5cb0f2984e107d623a4", + "bytes": 3249 + }, + "qml/QtQuick/Controls.2/Material/TabBar.qml": { + "sha256": "3b6be17e21277841fa741533f69aa2af9241d1a7ad7c303e8a5c1648f613e353", + "bytes": 3348 + }, + "qml/QtQuick/Controls.2/Material/TabButton.qml": { + "sha256": "1aba49685bd2d090170afd1430036287842a079c2aae3113eb6352138a7c84c2", + "bytes": 3129 + }, + "qml/QtQuick/Controls.2/Material/TextArea.qml": { + "sha256": "2d8354c1fb93a78631e54cfb85939773e9a9c5233ea95361e2073c7db9299090", + "bytes": 3643 + }, + "qml/QtQuick/Controls.2/Material/TextField.qml": { + "sha256": "7853e4c8d52167d2ef011c00f4d2399b64b7e3a33399ae45ddd0736d7d74df2f", + "bytes": 3734 + }, + "qml/QtQuick/Controls.2/Material/ToolBar.qml": { + "sha256": "6b628f4d7e84ce391e7e92753a1dcdb0e709c0aa65e9d03bc3018909f1d0ea81", + "bytes": 2590 + }, + "qml/QtQuick/Controls.2/Material/ToolButton.qml": { + "sha256": "c0f77f282d3dfa9bf8d5974b204095a812535c1aaef3324aa29f7b446ebfcc59", + "bytes": 3515 + }, + "qml/QtQuick/Controls.2/Material/ToolSeparator.qml": { + "sha256": "016f52785001216e0e5a789c0fac4f4dbb0768827911d27d39313dc408609cd7", + "bytes": 2432 + }, + "qml/QtQuick/Controls.2/Material/ToolTip.qml": { + "sha256": "80467b9644752705d003c86c67b0443327c2f1e126ea1effe4ff1935d7146a30", + "bytes": 3123 + }, + "qml/QtQuick/Controls.2/Material/Tumbler.qml": { + "sha256": "4e30c66393d0c13f830ff1ad955ac0370aa9c60700fb892a5044d9b8926435fa", + "bytes": 3241 + }, + "qml/QtQuick/Controls.2/Material/VerticalHeaderView.qml": { + "sha256": "0a9604763716bb43a0c4398dbc1d7c0f48634434bc8819d6aa339d55a69082a9", + "bytes": 2896 + }, + "qml/QtQuick/Controls.2/Material/libqqc2materialstyleplugin.so": { + "sha256": "6b8506a3efcd74f56715ca8a31a0a2d812244ace6591fbe92e3e7aff887b831b", + "bytes": 786336 + }, + "qml/QtQuick/Controls.2/Material/plugins.qmltypes": { + "sha256": "9e757b8e6fa0f97a71549439f1e6fe0f067705609dfdcc68342edb4de1fef4b2", + "bytes": 19286 + }, + "qml/QtQuick/Controls.2/Material/qmldir": { + "sha256": "8527a200365dde836f47884de6d511baf8c5eb439e58aecd9e1031e162007bb8", + "bytes": 139 + }, + "qml/QtQuick/Controls.2/Menu.qml": { + "sha256": "c147f959ae881afafc326fdbb4769ec53dbf8f76c5c0bc227fc36ecf0b755737", + "bytes": 3050 + }, + "qml/QtQuick/Controls.2/MenuBar.qml": { + "sha256": "8b4bf0109d9d900e905edbc7282afa9102aebbc3453ce53e9a70e47690a9515b", + "bytes": 2452 + }, + "qml/QtQuick/Controls.2/MenuBarItem.qml": { + "sha256": "db1127e4777776195b577b4d2ed08e4830a040c054eeb811009d6d8c07207d8d", + "bytes": 2917 + }, + "qml/QtQuick/Controls.2/MenuItem.qml": { + "sha256": "e4f17fa9862288f736ea790869ae21895fc053d4d4a3334a33c23982cfaf38f8", + "bytes": 4274 + }, + "qml/QtQuick/Controls.2/MenuSeparator.qml": { + "sha256": "fb19231de5902ea5eeafb76f7c932f4afede2b51568608d7a520913f68d344d6", + "bytes": 2384 + }, + "qml/QtQuick/Controls.2/Page.qml": { + "sha256": "3a031457f1fb1d84d00c931414906d30e372ab8703ffa53dc634dd29a9e13b88", + "bytes": 2547 + }, + "qml/QtQuick/Controls.2/PageIndicator.qml": { + "sha256": "4760878a0f43c12c3e1d92c7b0fbdf6ef275d0d3783b8c5bc052c1a5c080e655", + "bytes": 2691 + }, + "qml/QtQuick/Controls.2/Pane.qml": { + "sha256": "9ce4d599fe5261b31f0c134ac63d4e54dae8aa073f3b89bd3d74fbfe942c0351", + "bytes": 2276 + }, + "qml/QtQuick/Controls.2/Popup.qml": { + "sha256": "d4060f8b94d082779d85212bdf3902117e39358a7c455bf5ba268456e25e2ae2", + "bytes": 2528 + }, + "qml/QtQuick/Controls.2/ProgressBar.qml": { + "sha256": "db55abd92469efc77c7e1182badbfacfed851f35ac8a5a7401b42301edf44bdd", + "bytes": 2668 + }, + "qml/QtQuick/Controls.2/RadioButton.qml": { + "sha256": "aeefe766dd70a8b045387067bfaab5a2985563c17bad0fdfe2008631ba700b42", + "bytes": 3627 + }, + "qml/QtQuick/Controls.2/RadioDelegate.qml": { + "sha256": "97e518c4e3f1d01849c52e3107b909bc7c00d0739321d0765f9bb283ff3a92d9", + "bytes": 4066 + }, + "qml/QtQuick/Controls.2/RangeSlider.qml": { + "sha256": "6ff18dd1b03859e09a71fb7ae6f17c084714370ac2f26b8573ba754c115f0bc4", + "bytes": 4909 + }, + "qml/QtQuick/Controls.2/RoundButton.qml": { + "sha256": "c36990d75f878831caa373a6e576a7fd623023c6f81b08348704de4228831cb3", + "bytes": 3552 + }, + "qml/QtQuick/Controls.2/ScrollBar.qml": { + "sha256": "0932a4df8deb0a17c439d497de8f4ac951f7122e22e76546fa2c958b693cdeb0", + "bytes": 3135 + }, + "qml/QtQuick/Controls.2/ScrollIndicator.qml": { + "sha256": "e5ac4fc6dbe6d075635750f42a348136f1fba0984cac72d3b77f0efe73d6696f", + "bytes": 2905 + }, + "qml/QtQuick/Controls.2/ScrollView.qml": { + "sha256": "cf68717b269deff9b836b416da54261e2b7586bdc244074d9fc394faffdd2387", + "bytes": 2660 + }, + "qml/QtQuick/Controls.2/Slider.qml": { + "sha256": "b1cc14eb757d2032843500265c7470c8dbc71ade92445c75740d20bfe0a3d14a", + "bytes": 3840 + }, + "qml/QtQuick/Controls.2/SpinBox.qml": { + "sha256": "2ad2b32e80e708f243fb7cdad1c1a74a991e27eaad5db33f107a56d005ce12dd", + "bytes": 5230 + }, + "qml/QtQuick/Controls.2/SplitView.qml": { + "sha256": "215ad08d79cd6b68589a62398552641cc65368d6fa5a66b34eb911d7e3a2ff5d", + "bytes": 2550 + }, + "qml/QtQuick/Controls.2/StackView.qml": { + "sha256": "4cdbbcec25a318babfbd78c8a83fb28d8a23814abfd5c47ab72272111efaed64", + "bytes": 2812 + }, + "qml/QtQuick/Controls.2/SwipeDelegate.qml": { + "sha256": "ecd5f15a2546a079b0b4a2066dfeb7b7b4a70d5a871988ff21d51929adcf51c4", + "bytes": 3184 + }, + "qml/QtQuick/Controls.2/SwipeView.qml": { + "sha256": "a489768fd471bae8443a0a4695fc36938ab742368f3327bf4cd86a5d3d63b812", + "bytes": 2755 + }, + "qml/QtQuick/Controls.2/Switch.qml": { + "sha256": "2f76694a1e78c466063aef3f7e4317fd09780b8c0046238d435d86fa150284d2", + "bytes": 3855 + }, + "qml/QtQuick/Controls.2/SwitchDelegate.qml": { + "sha256": "9694548a9b530f55b8fd37b112e5ff0cff9e67d99400c670b31629ac88373f87", + "bytes": 4380 + }, + "qml/QtQuick/Controls.2/TabBar.qml": { + "sha256": "bbc6903fa00ef118f01982a98b5049b75b167b7e9cf6416cefcb63a99b51ae76", + "bytes": 2704 + }, + "qml/QtQuick/Controls.2/TabButton.qml": { + "sha256": "0847b09dd8836edf278fe42f2c6880d234082542c242570103cc501ce049e6a6", + "bytes": 2914 + }, + "qml/QtQuick/Controls.2/TextArea.qml": { + "sha256": "4b9de008239707214295739845498434f90f81459bca76db79e1ff5ee275fdf5", + "bytes": 3238 + }, + "qml/QtQuick/Controls.2/TextField.qml": { + "sha256": "82cc4c4722a44c2ad9ab4050aa6586dbdf0ba9bc25cd949fe9eac70105aa3509", + "bytes": 3488 + }, + "qml/QtQuick/Controls.2/ToolBar.qml": { + "sha256": "2112bedfaae38ae7dac74849c742ef8c25388d9edaed64e0a47307a75643440b", + "bytes": 2289 + }, + "qml/QtQuick/Controls.2/ToolButton.qml": { + "sha256": "6766e054835c137a5e973a1e2b95b5fd1dd5287376e548a7208f836ab2f42b51", + "bytes": 2923 + }, + "qml/QtQuick/Controls.2/ToolSeparator.qml": { + "sha256": "52356a0d3c945bb9f443c8362fa99fd0d880ead778852a98e23910b0be91f710", + "bytes": 2434 + }, + "qml/QtQuick/Controls.2/ToolTip.qml": { + "sha256": "69c9f78c6c03e0e52bbb73c1eeccdcc3db83a77d17507fd816f610a6cce84b2e", + "bytes": 2694 + }, + "qml/QtQuick/Controls.2/Tumbler.qml": { + "sha256": "5db323b1e9029ebb7ba1b6781b86a537bcefbb778b886250d155d2827cf54413", + "bytes": 3214 + }, + "qml/QtQuick/Controls.2/Universal/ApplicationWindow.qml": { + "sha256": "5adebe202bf05df7aec178216a5b7c33b1ea42dd632ae44384121e399bbefc27", + "bytes": 2380 + }, + "qml/QtQuick/Controls.2/Universal/BusyIndicator.qml": { + "sha256": "74447ba98339c10a0ad83281534be02520fad5a4d307eb03b91055e1f63c6151", + "bytes": 2554 + }, + "qml/QtQuick/Controls.2/Universal/Button.qml": { + "sha256": "786e8563877ce2b266a98e5fd24a8cb813e767ef00986344123037043e4822c0", + "bytes": 3521 + }, + "qml/QtQuick/Controls.2/Universal/CheckBox.qml": { + "sha256": "d680a335490e310533f5723775c6fe59b7e287990f332f31a5d1146abadb8abd", + "bytes": 3157 + }, + "qml/QtQuick/Controls.2/Universal/CheckDelegate.qml": { + "sha256": "01be8ca6bfd758558a510a8d454dbd9660ccb189596862a3bfdc3714e63bf8fd", + "bytes": 4092 + }, + "qml/QtQuick/Controls.2/Universal/CheckIndicator.qml": { + "sha256": "454782eae5a41150128ce15a63d67ea69045b54836c83ee64a7f54f8e4661199", + "bytes": 3882 + }, + "qml/QtQuick/Controls.2/Universal/ComboBox.qml": { + "sha256": "ce1d90ea1e3c1dd6b08d80d7b3039d93a555fcb9fafbf1fb0f0d6e3e54c707d8", + "bytes": 6988 + }, + "qml/QtQuick/Controls.2/Universal/DelayButton.qml": { + "sha256": "bde0ad678fc2de5a6ef32fa6d2b75dfc876d6e484e50692bbaeb333b0fc3a237", + "bytes": 3503 + }, + "qml/QtQuick/Controls.2/Universal/Dial.qml": { + "sha256": "f7dda45fcb17c7cd2e0017c9e28be4fcd03103c26000a97c4b696273d1a6d2ed", + "bytes": 3562 + }, + "qml/QtQuick/Controls.2/Universal/Dialog.qml": { + "sha256": "601cfbf807a4f6380d7d19832da2930249f223aee1516c72ccb5a645e6845700", + "bytes": 3453 + }, + "qml/QtQuick/Controls.2/Universal/DialogButtonBox.qml": { + "sha256": "ecd1c90e8ca370376345e2acb1f8e279f99d9cbe499cb625c6df9e76b18de2a8", + "bytes": 3101 + }, + "qml/QtQuick/Controls.2/Universal/Drawer.qml": { + "sha256": "afe4be5a45b5497175b24bb2e1c632ea0beeb193af60b092fc86e85cf923cfdf", + "bytes": 3194 + }, + "qml/QtQuick/Controls.2/Universal/Frame.qml": { + "sha256": "5ce1759a0f2583f7f535ddf894e54f2689cf99d4815f887c5fd8e3255945c121", + "bytes": 2307 + }, + "qml/QtQuick/Controls.2/Universal/GroupBox.qml": { + "sha256": "770f38b32fa418448a1dacc42279d8d817895924e7d419ea2416dbab46a3cd94", + "bytes": 2956 + }, + "qml/QtQuick/Controls.2/Universal/HorizontalHeaderView.qml": { + "sha256": "f4b1bc92ab961295be8f3b3c1f8b92af682bfdf86277aee52fe43349dc9a0a9a", + "bytes": 2929 + }, + "qml/QtQuick/Controls.2/Universal/ItemDelegate.qml": { + "sha256": "7b7553df7bc4adb26d75cae2fdf32316054be67669917840a827190cae68a22b", + "bytes": 3562 + }, + "qml/QtQuick/Controls.2/Universal/Label.qml": { + "sha256": "6827af8ddf661fd409ac2d153fff56ccc49a42ad3ab2d0c09f6459fc3f006b39", + "bytes": 1966 + }, + "qml/QtQuick/Controls.2/Universal/Menu.qml": { + "sha256": "81852376d02c7f48731b40988d68bd0b72b224aadfb879e0077fce2de3fa8ccc", + "bytes": 3105 + }, + "qml/QtQuick/Controls.2/Universal/MenuBar.qml": { + "sha256": "61bc228e82b8c55ca184c8868b03ffbb546d4fa382fe9c14a99b8b927169cd88", + "bytes": 2504 + }, + "qml/QtQuick/Controls.2/Universal/MenuBarItem.qml": { + "sha256": "b6084de3430da0938cef9cdee6eca2838eeeb0823f69e02b7e243af08b46748d", + "bytes": 3488 + }, + "qml/QtQuick/Controls.2/Universal/MenuItem.qml": { + "sha256": "05ee1edb994b97e8d64d5a160f2a00c950d5b7646e2c8480cc13b1a8cd3d87ab", + "bytes": 4958 + }, + "qml/QtQuick/Controls.2/Universal/MenuSeparator.qml": { + "sha256": "1c41525e2f553c09b6e5e0c59124e939c3d9dc7263c68809697abd582a9512f4", + "bytes": 2471 + }, + "qml/QtQuick/Controls.2/Universal/Page.qml": { + "sha256": "9aa49c9084e76b80875e8045fd5ccd97186dc5b32332755fd48dc479e779db17", + "bytes": 2529 + }, + "qml/QtQuick/Controls.2/Universal/PageIndicator.qml": { + "sha256": "9ffd907dfbde00705fc613a72c7f422b21782f61ecdf5c5ba8fafd3e5ff667d1", + "bytes": 2700 + }, + "qml/QtQuick/Controls.2/Universal/Pane.qml": { + "sha256": "9e51b325503493be91b00a6564db6a7df77f1a120d7d7d35bed673ad27ce0a38", + "bytes": 2258 + }, + "qml/QtQuick/Controls.2/Universal/Popup.qml": { + "sha256": "fa9864e11b53a100e77a14689bc544dc8e5dde64d619c7c32d78c3ab9c865b3a", + "bytes": 2554 + }, + "qml/QtQuick/Controls.2/Universal/ProgressBar.qml": { + "sha256": "1a1c7112ed842d5fec003729b4135f33e53c6798fc0cf79f6ceb69392fc25c44", + "bytes": 2715 + }, + "qml/QtQuick/Controls.2/Universal/RadioButton.qml": { + "sha256": "fe4e81ebc1b0d79fe925cd0f97da56640697f560187157872248858fc674677a", + "bytes": 3160 + }, + "qml/QtQuick/Controls.2/Universal/RadioDelegate.qml": { + "sha256": "f52337ad42931ed3aa93f1d97a27ea6aa6fb177c8934138eb2d2ac8d7957598b", + "bytes": 4092 + }, + "qml/QtQuick/Controls.2/Universal/RadioIndicator.qml": { + "sha256": "76e9877a36e37cfa9eeef38ee198e10ed50ee92f2eef1df8f8c78a5b2d956256", + "bytes": 3382 + }, + "qml/QtQuick/Controls.2/Universal/RangeSlider.qml": { + "sha256": "0339bcddcdf50600910fc7bdec09411dea04b6016a069e360bb496c4377a0ea9", + "bytes": 5626 + }, + "qml/QtQuick/Controls.2/Universal/RoundButton.qml": { + "sha256": "1fbd6f4d7ab1074e69b580513d4c729122f4b87f0bb9561990bcc6a6adbb8705", + "bytes": 3559 + }, + "qml/QtQuick/Controls.2/Universal/ScrollBar.qml": { + "sha256": "5de410e5b7487febfaa23a9acbff3e469a4f6f7bf4bec5598b3e86d2cb8cb3a7", + "bytes": 3705 + }, + "qml/QtQuick/Controls.2/Universal/ScrollIndicator.qml": { + "sha256": "478b812bb7b8c495ba7c7f5070ee3e77840fe430b62eb40e5d4b60119a67a28f", + "bytes": 2992 + }, + "qml/QtQuick/Controls.2/Universal/Slider.qml": { + "sha256": "0ef2be6cb3907947ef8048c28d806f87d919b6ca4d3766a50e0aaa72cc64c1b7", + "bytes": 4562 + }, + "qml/QtQuick/Controls.2/Universal/SpinBox.qml": { + "sha256": "1dedc6fad0d3117516de52a8f6d148105a6bc1d84700e21177279540240db4d8", + "bytes": 6500 + }, + "qml/QtQuick/Controls.2/Universal/SplitView.qml": { + "sha256": "65f6e0d321a1f0f7c581b0c8ee24081f82f267a3f5131272ae72b63996ac35ec", + "bytes": 2626 + }, + "qml/QtQuick/Controls.2/Universal/StackView.qml": { + "sha256": "6181aa9093c65caa99cdca9549b410e1cf19d1754f9f4ea50a63dfeae5ab96fa", + "bytes": 3312 + }, + "qml/QtQuick/Controls.2/Universal/SwipeDelegate.qml": { + "sha256": "42b5f5063ceffdd6352b8df8f479ecf5565a7c2fa520674cc2331921533018e4", + "bytes": 3748 + }, + "qml/QtQuick/Controls.2/Universal/Switch.qml": { + "sha256": "ece9bd43fed36b24897d2909ebd0da8abeb535d365d9fd586358fac516294cf7", + "bytes": 3156 + }, + "qml/QtQuick/Controls.2/Universal/SwitchDelegate.qml": { + "sha256": "d3297b1e9c3a436eddd49891c9a3d6b28546b523b4675c1843249a7c8866fcfc", + "bytes": 4094 + }, + "qml/QtQuick/Controls.2/Universal/SwitchIndicator.qml": { + "sha256": "2d2ef715a8aa2802bb96de564f9c95598cfc9a0c8ce20dd501d850f57b2a9723", + "bytes": 3668 + }, + "qml/QtQuick/Controls.2/Universal/TabBar.qml": { + "sha256": "051f165e7443e35b98c474223b668e4c58bf976c33b9d826d6813825470a67bc", + "bytes": 2789 + }, + "qml/QtQuick/Controls.2/Universal/TabButton.qml": { + "sha256": "6087b93bb67ad6cc12364938d86dc065d4fe5ec0fb2fa32e34b6d653f40245a1", + "bytes": 3012 + }, + "qml/QtQuick/Controls.2/Universal/TextArea.qml": { + "sha256": "9cd0305407284230296b7c961ce13f78c2403601b6ca2f303dc3d9a582014f5b", + "bytes": 4242 + }, + "qml/QtQuick/Controls.2/Universal/TextField.qml": { + "sha256": "bf9604aa428252572a31661ed7c03ad9b71c53f5bfb5c80d9affa97273ba3e5d", + "bytes": 4225 + }, + "qml/QtQuick/Controls.2/Universal/ToolBar.qml": { + "sha256": "aee861a271852e9dbf0ab0f37d0fad6e14354a299495fd62a829fc900d63f3db", + "bytes": 2306 + }, + "qml/QtQuick/Controls.2/Universal/ToolButton.qml": { + "sha256": "95786aac8c9994bada082737f3743b336ed337219e1def0a6033bc6fa787286b", + "bytes": 3231 + }, + "qml/QtQuick/Controls.2/Universal/ToolSeparator.qml": { + "sha256": "c6a9baab160c7d3e4f884cc570258181b1cc29b8e4c1d21570d6065513a9181d", + "bytes": 2505 + }, + "qml/QtQuick/Controls.2/Universal/ToolTip.qml": { + "sha256": "1341f09189e3eb33a61941c7a5bc31c61a07640450e13985f2378fe67d704277", + "bytes": 2847 + }, + "qml/QtQuick/Controls.2/Universal/Tumbler.qml": { + "sha256": "a487795930272405b1d3b883249331e82431076babba8eee9e0c16200d38ae1d", + "bytes": 3243 + }, + "qml/QtQuick/Controls.2/Universal/VerticalHeaderView.qml": { + "sha256": "355210ac96386c21baecd7a76f54dd3aa9bdc06b5deb345da8525552636d0149", + "bytes": 2926 + }, + "qml/QtQuick/Controls.2/Universal/libqtquickcontrols2universalstyleplugin.so": { + "sha256": "fb297118ad1f4b228b97d4dcb9b20546c5b50323f6d77bdaafe0b84ba1fa94b4", + "bytes": 630520 + }, + "qml/QtQuick/Controls.2/Universal/plugins.qmltypes": { + "sha256": "812cb5ecc3e8de755149f77d7aff6c018fc2c5c3452d443dcf71b51ad3f3a0cf", + "bytes": 13557 + }, + "qml/QtQuick/Controls.2/Universal/qmldir": { + "sha256": "a8a880ed60e3e217ed874011176d9fa2d533711dc9ca6a44d548040089b926a7", + "bytes": 154 + }, + "qml/QtQuick/Controls.2/VerticalHeaderView.qml": { + "sha256": "4b0530b34dbb2e48206397b6b0e98bd319b2519c591221ae72c512827170519f", + "bytes": 2765 + }, + "qml/QtQuick/Controls.2/designer/AbstractButtonSection.qml": { + "sha256": "0194f996e08274496bb44b8f29a717d8b77170fe3c72bb1c8bc6701f44be6ada", + "bytes": 4134 + }, + "qml/QtQuick/Controls.2/designer/BusyIndicatorSpecifics.qml": { + "sha256": "74e36a0cdf3e064f8341af1abf5309e99cf16e5c3f665e813255a61aa85bf8f4", + "bytes": 2553 + }, + "qml/QtQuick/Controls.2/designer/ButtonSection.qml": { + "sha256": "4af64d76e3cc31c9ced1fc9874a7ecdd189a0801fe28fdc39ea78d4a5c17cd0e", + "bytes": 2589 + }, + "qml/QtQuick/Controls.2/designer/ButtonSpecifics.qml": { + "sha256": "208e10ee8ace1cffad89d2745745909249ba182470f65e6563857c8d77839800", + "bytes": 2129 + }, + "qml/QtQuick/Controls.2/designer/CheckBoxSpecifics.qml": { + "sha256": "8f7c644deaa643354f5cdd97a5a3de5219f8f2967f10212ca8ec82f52752e766", + "bytes": 2162 + }, + "qml/QtQuick/Controls.2/designer/CheckDelegateSpecifics.qml": { + "sha256": "47f3140c4e08d2bf8c1e4af095a7076d1acdb4df6e3072323cdf3836a3d55af2", + "bytes": 2228 + }, + "qml/QtQuick/Controls.2/designer/CheckSection.qml": { + "sha256": "d6c57a8b85b68132f4374bdc497644b3fd57b647ee9951b290c50e0945716757", + "bytes": 2593 + }, + "qml/QtQuick/Controls.2/designer/ComboBoxSpecifics.qml": { + "sha256": "6e66eb05e98b5786c24456aa9f10ffd4adda7eedc6b4dcfc1fd8ba141d83c838", + "bytes": 3971 + }, + "qml/QtQuick/Controls.2/designer/ContainerSection.qml": { + "sha256": "bc25b2a3d8b788799b27f3391836315ff67c62db08b26d0df06983fe13802766", + "bytes": 2277 + }, + "qml/QtQuick/Controls.2/designer/ControlSection.qml": { + "sha256": "fb642ead8e53d20c88313324006a9040fb795a913693ca532c4047fdd1378259", + "bytes": 3773 + }, + "qml/QtQuick/Controls.2/designer/ControlSpecifics.qml": { + "sha256": "8bcc3a8274aef505a0bec07ee1ec9b4eebe4b2c4ed7afa96e808a7b7a77f4cb5", + "bytes": 2011 + }, + "qml/QtQuick/Controls.2/designer/DelayButtonSpecifics.qml": { + "sha256": "d7e2319c43c8095c3827a89f772d865860d788e632ba4eb0f2142f62ed8b83d7", + "bytes": 2655 + }, + "qml/QtQuick/Controls.2/designer/DialSpecifics.qml": { + "sha256": "c0743d6df14a68f8d8a92de7ff863d643c93fbc5bcb40509d1eedc5b7aa8ff0f", + "bytes": 5777 + }, + "qml/QtQuick/Controls.2/designer/FrameSpecifics.qml": { + "sha256": "3acf94a8fa5d2176b640145966e6f94e3d3c08a718c3fb03649523ba798850d2", + "bytes": 2064 + }, + "qml/QtQuick/Controls.2/designer/GroupBoxSpecifics.qml": { + "sha256": "4b746de18f8e593bb8443d3c61b133cf5124ea0d54816b6cda8792c1c8c11b59", + "bytes": 2502 + }, + "qml/QtQuick/Controls.2/designer/InsetSection.qml": { + "sha256": "baadc0d06c0b34c7b48e7768ab497e1dc6ca2445481f74c19fdeded61aeb148d", + "bytes": 3956 + }, + "qml/QtQuick/Controls.2/designer/ItemDelegateSection.qml": { + "sha256": "fbcda9f8dfd76e80d8ffa2e48f8fff34c87744ddec624ce79273605e46412377", + "bytes": 2263 + }, + "qml/QtQuick/Controls.2/designer/ItemDelegateSpecifics.qml": { + "sha256": "91d7772e4a193e91a093d59451508cdb89448eaffb4febda26789777afbacf3d", + "bytes": 2135 + }, + "qml/QtQuick/Controls.2/designer/LabelSpecifics.qml": { + "sha256": "0a7e81847ab5fce8a16087c657f601be3fb6d4adc4936ef0bfd70deb5dfe1efd", + "bytes": 2737 + }, + "qml/QtQuick/Controls.2/designer/PaddingSection.qml": { + "sha256": "8b6163edf23186b091fcf9ab53c74deea3824ad17549b281fb13f1463bbbc32d", + "bytes": 3580 + }, + "qml/QtQuick/Controls.2/designer/PageIndicatorSpecifics.qml": { + "sha256": "3ead45b0f3bff5f4d8f61bcb68f2d8ade74934a70d6e1d7b3f9617134c3eaf13", + "bytes": 3366 + }, + "qml/QtQuick/Controls.2/designer/PageSpecifics.qml": { + "sha256": "73124ef3768f8ef7262a880fe46bc5ade90f9b80fb25e79a706bd11696a7edcb", + "bytes": 3411 + }, + "qml/QtQuick/Controls.2/designer/PaneSection.qml": { + "sha256": "7385545edabb4b593ff7b66ef9107255d1646cd131b1541111185c4519dd4d8c", + "bytes": 2746 + }, + "qml/QtQuick/Controls.2/designer/PaneSpecifics.qml": { + "sha256": "3acf94a8fa5d2176b640145966e6f94e3d3c08a718c3fb03649523ba798850d2", + "bytes": 2064 + }, + "qml/QtQuick/Controls.2/designer/ProgressBarSpecifics.qml": { + "sha256": "71b6f4ad0c2920975edfb74a9980f8e64f474e8ad6d2bfe02ce7fdd78a89f5ec", + "bytes": 4076 + }, + "qml/QtQuick/Controls.2/designer/RadioButtonSpecifics.qml": { + "sha256": "a3fff66cd7217029792e7fce403cc658b0ea03b2d3a2860f57479c8ea6bc1372", + "bytes": 2074 + }, + "qml/QtQuick/Controls.2/designer/RadioDelegateSpecifics.qml": { + "sha256": "91d7772e4a193e91a093d59451508cdb89448eaffb4febda26789777afbacf3d", + "bytes": 2135 + }, + "qml/QtQuick/Controls.2/designer/RangeSliderSpecifics.qml": { + "sha256": "7e8dcc0907972972f07b4708a8f2b0edaf440ad1b76674d019523bb0b92dd8d3", + "bytes": 6577 + }, + "qml/QtQuick/Controls.2/designer/RoundButtonSpecifics.qml": { + "sha256": "551b1228eb023c9a74eb6c49b21084743e5ed36ba7adaacb1dec00b065346cf2", + "bytes": 2673 + }, + "qml/QtQuick/Controls.2/designer/ScrollViewSpecifics.qml": { + "sha256": "5bc64c288d63a81753436722ca560fee64d6ada8de3d6ccbaf21a23261a9924e", + "bytes": 3105 + }, + "qml/QtQuick/Controls.2/designer/SliderSpecifics.qml": { + "sha256": "eeb45f393f91e147dafc449cee6e5a6e0ca927e4c76f51a367370f5d2bf4c103", + "bytes": 5905 + }, + "qml/QtQuick/Controls.2/designer/SpinBoxSpecifics.qml": { + "sha256": "de00ba54c21a5b937ee9338805c7daa1e73bcfd6a4a75e668c38c526b63b9196", + "bytes": 4779 + }, + "qml/QtQuick/Controls.2/designer/StackViewSpecifics.qml": { + "sha256": "8bcc3a8274aef505a0bec07ee1ec9b4eebe4b2c4ed7afa96e808a7b7a77f4cb5", + "bytes": 2011 + }, + "qml/QtQuick/Controls.2/designer/SwipeDelegateSpecifics.qml": { + "sha256": "91d7772e4a193e91a093d59451508cdb89448eaffb4febda26789777afbacf3d", + "bytes": 2135 + }, + "qml/QtQuick/Controls.2/designer/SwipeViewSpecifics.qml": { + "sha256": "43654e2514b6519370f15041670661ab708b878db5c5b499733243c47d9e8d51", + "bytes": 3009 + }, + "qml/QtQuick/Controls.2/designer/SwitchDelegateSpecifics.qml": { + "sha256": "f08ec626939b9bbb1b4c8084dc1cd6edc417125cebe1ae687a8c2bce4f06ec77", + "bytes": 2082 + }, + "qml/QtQuick/Controls.2/designer/SwitchSpecifics.qml": { + "sha256": "a3fff66cd7217029792e7fce403cc658b0ea03b2d3a2860f57479c8ea6bc1372", + "bytes": 2074 + }, + "qml/QtQuick/Controls.2/designer/TabBarSpecifics.qml": { + "sha256": "6a941dff2927a40783da38b2af82840ad2b5774ebb684e5110e8d2945c127a7b", + "bytes": 3568 + }, + "qml/QtQuick/Controls.2/designer/TabButtonSpecifics.qml": { + "sha256": "a3fff66cd7217029792e7fce403cc658b0ea03b2d3a2860f57479c8ea6bc1372", + "bytes": 2074 + }, + "qml/QtQuick/Controls.2/designer/TextAreaSpecifics.qml": { + "sha256": "18b36004f978345706dbb27ec47f657f338f20df5d29c7e932c2a5be5dac5ff1", + "bytes": 3333 + }, + "qml/QtQuick/Controls.2/designer/TextFieldSpecifics.qml": { + "sha256": "e8fe7e436cb0c9e33b7e9fd77135601aba556c85b47b0a65f359af98ef62a204", + "bytes": 3237 + }, + "qml/QtQuick/Controls.2/designer/ToolBarSpecifics.qml": { + "sha256": "7f58fe39e944794193f3e32f0172da0f7e4a3600333174dcae7ec3993c313f4e", + "bytes": 2591 + }, + "qml/QtQuick/Controls.2/designer/ToolButtonSpecifics.qml": { + "sha256": "208e10ee8ace1cffad89d2745745909249ba182470f65e6563857c8d77839800", + "bytes": 2129 + }, + "qml/QtQuick/Controls.2/designer/ToolSeparatorSpecifics.qml": { + "sha256": "0715f3c4a4a888bb169aaf192f64fa318e91f52c0f18b6b3f73084287d6c498c", + "bytes": 2507 + }, + "qml/QtQuick/Controls.2/designer/TumblerSpecifics.qml": { + "sha256": "788102ef2f56f3e6968419dde4844171e410fa937e70e9d1e8cfe5b9da8c7af3", + "bytes": 3408 + }, + "qml/QtQuick/Controls.2/designer/images/busyindicator-icon.png": { + "sha256": "76c07655ca57e6d8e6cf9d692e99bed52c7736a8744375487c5fdd990a4263d4", + "bytes": 312 + }, + "qml/QtQuick/Controls.2/designer/images/busyindicator-icon16.png": { + "sha256": "a2be75321a3d198d92759854aee397e02f7aeafcfde37fee2e341617c08664e4", + "bytes": 229 + }, + "qml/QtQuick/Controls.2/designer/images/busyindicator-icon@2x.png": { + "sha256": "d4f6e4ac20318896f1aef2d6798ef546559af18f92c958fa5b7aae02421a2329", + "bytes": 612 + }, + "qml/QtQuick/Controls.2/designer/images/button-icon.png": { + "sha256": "7e2b84ede028b0b29ef6fb65de3ecc5cd09bdf75e293842505cddae688c0a5a5", + "bytes": 161 + }, + "qml/QtQuick/Controls.2/designer/images/button-icon16.png": { + "sha256": "bebdee848cf1b6041d5fe1e00b064aa16f7cff5117a3ba72511e70e69c52b888", + "bytes": 145 + }, + "qml/QtQuick/Controls.2/designer/images/button-icon@2x.png": { + "sha256": "278cdddf076bc9763cdbe7ad82f8682da93ca9f00805d153bacf631ca7a7d911", + "bytes": 259 + }, + "qml/QtQuick/Controls.2/designer/images/checkbox-icon.png": { + "sha256": "dee1f3053cd8d1ca7d5fa62f84c59724c33ea59cc1cbaf012e67904f6d89fb08", + "bytes": 245 + }, + "qml/QtQuick/Controls.2/designer/images/checkbox-icon16.png": { + "sha256": "453fdcf5f7f370649515363a9b5ed32bd0eedc428a51b7d0a6c569f5e8acb278", + "bytes": 221 + }, + "qml/QtQuick/Controls.2/designer/images/checkbox-icon@2x.png": { + "sha256": "9ee8504df14b79eb4e82395c93b3725ad7d365121cb3eb835aec8acd187dbdf0", + "bytes": 304 + }, + "qml/QtQuick/Controls.2/designer/images/combobox-icon.png": { + "sha256": "1339f0ee67af481730246cde6c2294e75389cbfbd88ae7e92e978e24c5477e1f", + "bytes": 156 + }, + "qml/QtQuick/Controls.2/designer/images/combobox-icon16.png": { + "sha256": "5c8669bbaf53135cd9a908c7de90a765e6aa63291d4f38188b2fd8ceb7d42eb3", + "bytes": 155 + }, + "qml/QtQuick/Controls.2/designer/images/combobox-icon@2x.png": { + "sha256": "12a97b60816fe0d25a795fa2cf17d9201c4f67b11a6c4fab9f8d2ec64d69af80", + "bytes": 181 + }, + "qml/QtQuick/Controls.2/designer/images/delaybutton-icon.png": { + "sha256": "8ddd4dbee799589da7173241ad03d7ca927bac3e0e1c9050b7f652db43c98408", + "bytes": 189 + }, + "qml/QtQuick/Controls.2/designer/images/delaybutton-icon16.png": { + "sha256": "f62ab5573950155f52ae1b7911a7ed547e877785883d77307cd5953ddfaa0d5b", + "bytes": 160 + }, + "qml/QtQuick/Controls.2/designer/images/delaybutton-icon@2x.png": { + "sha256": "8106b548c28837f0b0536e21296b3f13b21cb2ed72b8d5c872420beb21fd5151", + "bytes": 282 + }, + "qml/QtQuick/Controls.2/designer/images/dial-icon.png": { + "sha256": "f599d2b6aef0f4ab198b98c02a12ca805c0ce89c41c9ca84c8dd8e17fa73b6f3", + "bytes": 251 + }, + "qml/QtQuick/Controls.2/designer/images/dial-icon16.png": { + "sha256": "4880fbda5e1f45a77ab6bd10bb70354ec3b63699758bbebff3bbc0dbc385c9fb", + "bytes": 235 + }, + "qml/QtQuick/Controls.2/designer/images/dial-icon@2x.png": { + "sha256": "c0f11784d15ae223bbe0a5fac5a954f4fa64c28e4982e83a5892987e7ee26dac", + "bytes": 470 + }, + "qml/QtQuick/Controls.2/designer/images/frame-icon.png": { + "sha256": "a33f55b6373065674627a273615042178cefcd8a7bf6a971b77b9149aa0d82c6", + "bytes": 120 + }, + "qml/QtQuick/Controls.2/designer/images/frame-icon16.png": { + "sha256": "a4e7b917759a241b00d1aa6ec8f151b7f3c0b8ba1ef776b46ed45daced3bf49a", + "bytes": 93 + }, + "qml/QtQuick/Controls.2/designer/images/frame-icon@2x.png": { + "sha256": "457668fc7504283bf117791edc3ef901818ae857387fde1d0e1f17b420741266", + "bytes": 125 + }, + "qml/QtQuick/Controls.2/designer/images/groupbox-icon.png": { + "sha256": "ff9230939eafdfc03c31f6dbf9b42dc8e5fc6e76904638bd0af04612bb6c3d88", + "bytes": 133 + }, + "qml/QtQuick/Controls.2/designer/images/groupbox-icon16.png": { + "sha256": "cfb92af09b471ba729298b8822a834192b01d58f034192eedec636fb29909305", + "bytes": 105 + }, + "qml/QtQuick/Controls.2/designer/images/groupbox-icon@2x.png": { + "sha256": "8bfaae84606a3b98252bb9036f135730f6fec4b4976a832459dae1014025f385", + "bytes": 136 + }, + "qml/QtQuick/Controls.2/designer/images/itemdelegate-icon.png": { + "sha256": "ab5fbd265a69f34a4aabf064594ce5dd9db497f9e0b78109bbb6cae248ee2e6e", + "bytes": 127 + }, + "qml/QtQuick/Controls.2/designer/images/itemdelegate-icon16.png": { + "sha256": "2ed49e5d10f3eff68cd57f9f5ca18e1649d79d64430cd0c27c2f379c31e2c5ba", + "bytes": 124 + }, + "qml/QtQuick/Controls.2/designer/images/itemdelegate-icon@2x.png": { + "sha256": "35cd190647589d00427e03f347fb9a0e68fbaa18f3556393f8a9978c83287bb8", + "bytes": 133 + }, + "qml/QtQuick/Controls.2/designer/images/label-icon.png": { + "sha256": "e66830233371d21e0dd1613e4cd968c8addddd38459dca332eb1184d30005b2d", + "bytes": 206 + }, + "qml/QtQuick/Controls.2/designer/images/label-icon16.png": { + "sha256": "8ce5fa2c227d57adbf9b68baa42a3765d81e34e8332c413e498e989074be8701", + "bytes": 182 + }, + "qml/QtQuick/Controls.2/designer/images/label-icon@2x.png": { + "sha256": "02e56b6f020e5563651854df102297bfc3782bc73252bfd7798daba6ade98ffe", + "bytes": 281 + }, + "qml/QtQuick/Controls.2/designer/images/page-icon.png": { + "sha256": "671571e519d51393f67c7ef6165abedf2cbcf6a5adec760d62f7477733791610", + "bytes": 190 + }, + "qml/QtQuick/Controls.2/designer/images/page-icon16.png": { + "sha256": "a1104b7c497367b054ea7bb7b13042abcf6e2701b5b4fd2d32e4f0c288c61c8b", + "bytes": 148 + }, + "qml/QtQuick/Controls.2/designer/images/page-icon@2x.png": { + "sha256": "2810d162e5a4be97603a1afc3eafa23cc333b0c335a3c9317979b0ea9917480b", + "bytes": 185 + }, + "qml/QtQuick/Controls.2/designer/images/pageindicator-icon.png": { + "sha256": "559491ded77497c89bbf9f55433dfd75690d73af21a5889de951e772f7c2dcd7", + "bytes": 179 + }, + "qml/QtQuick/Controls.2/designer/images/pageindicator-icon16.png": { + "sha256": "c55198faacceef55982a3ecebe54ee4da5c602de3f25f1ca8a7e0e47390a42d5", + "bytes": 158 + }, + "qml/QtQuick/Controls.2/designer/images/pageindicator-icon@2x.png": { + "sha256": "a7520c3a0a540c167ff95fd7c3c059daaa3492dad481e7cac964df09d33b51d2", + "bytes": 198 + }, + "qml/QtQuick/Controls.2/designer/images/pane-icon.png": { + "sha256": "f685a48ecce386e135631bea5021d952b76f103d9591c5f0a08e3ee128095108", + "bytes": 93 + }, + "qml/QtQuick/Controls.2/designer/images/pane-icon16.png": { + "sha256": "52a9fd93b93d89d52179d59413d9e66c30e4dcb772517d2779b50b333d8bf2bb", + "bytes": 92 + }, + "qml/QtQuick/Controls.2/designer/images/pane-icon@2x.png": { + "sha256": "b72e9b5cdd7cc922817a511e44bd27573868ef7841b456a4c22ff9fc61092d3a", + "bytes": 96 + }, + "qml/QtQuick/Controls.2/designer/images/progressbar-icon.png": { + "sha256": "320ed9826462b227904105518e0200129090eb3d70620673a8717319845c390a", + "bytes": 97 + }, + "qml/QtQuick/Controls.2/designer/images/progressbar-icon16.png": { + "sha256": "44443bd660c3e8d54d1265dd2dd072d871378ab40ed52794ca08c8721c945aa4", + "bytes": 87 + }, + "qml/QtQuick/Controls.2/designer/images/progressbar-icon@2x.png": { + "sha256": "b0349e19850db6205603cc91192c9e77a14779b6f4f47d346b4e345518999d33", + "bytes": 118 + }, + "qml/QtQuick/Controls.2/designer/images/radiobutton-icon.png": { + "sha256": "14e579e057a05ef3e7a2f400527c813a3d989939b14248f3b17f6e4883896f9f", + "bytes": 260 + }, + "qml/QtQuick/Controls.2/designer/images/radiobutton-icon16.png": { + "sha256": "844b6767609428471733c6d4d5e2671b7c7eafd3a8b78b6958ec8aa6015e9b37", + "bytes": 216 + }, + "qml/QtQuick/Controls.2/designer/images/radiobutton-icon@2x.png": { + "sha256": "069896ea800ad3ea2cf9d0bf58aa979e66cb725fecf0a4d76b168d83e7c4701f", + "bytes": 469 + }, + "qml/QtQuick/Controls.2/designer/images/rangeslider-icon.png": { + "sha256": "5b470d7cc1df56b5ecf18a35c455f1ea384da26bad09dcb9cafed87649a8c2b2", + "bytes": 267 + }, + "qml/QtQuick/Controls.2/designer/images/rangeslider-icon16.png": { + "sha256": "749547779171a7b2a19fd49346db58effca6d1255a1028f571063aee65353e3b", + "bytes": 230 + }, + "qml/QtQuick/Controls.2/designer/images/rangeslider-icon@2x.png": { + "sha256": "c9668a6655bc7994fb7f2191f871976f5501775fed14e013d01e5d64c8e6a005", + "bytes": 244 + }, + "qml/QtQuick/Controls.2/designer/images/roundbutton-icon.png": { + "sha256": "61928d1ce175dcfc68aea34d1e7c3ed2299b6325ac9531ac2f68a411c1826234", + "bytes": 216 + }, + "qml/QtQuick/Controls.2/designer/images/roundbutton-icon16.png": { + "sha256": "c97f0189547d8861d6f498f80a3c53769ce466e9fb98470ad5aad84a5568646d", + "bytes": 186 + }, + "qml/QtQuick/Controls.2/designer/images/roundbutton-icon@2x.png": { + "sha256": "9f7ae0cb0e8c23ca5fa2332a135a40b3446e16b3a946afd9560f945324e1cd4d", + "bytes": 370 + }, + "qml/QtQuick/Controls.2/designer/images/scrollview-icon.png": { + "sha256": "95c391220b616e9733a9d4fb8c675430069dd74ca3c37e4def92158c3a1b75e2", + "bytes": 110 + }, + "qml/QtQuick/Controls.2/designer/images/scrollview-icon16.png": { + "sha256": "1e849fe82dc105b8c0820cea95e7f6bba9d93c1fb32ccfbeb7cc6464277939c0", + "bytes": 116 + }, + "qml/QtQuick/Controls.2/designer/images/scrollview-icon@2x.png": { + "sha256": "046e91e191b4db9f38c631004ff261c3a391ed6bd10821fcbd75a367b99045c2", + "bytes": 145 + }, + "qml/QtQuick/Controls.2/designer/images/slider-icon.png": { + "sha256": "62687a61fc08e488563f76deef1c3dfa13a4d46b1b2989ed0b8e97b8ea286a80", + "bytes": 190 + }, + "qml/QtQuick/Controls.2/designer/images/slider-icon16.png": { + "sha256": "a1f3e4c5b3955e27ae26b96ad3611c68ea3a0c821f79e26e3037050f77da30d2", + "bytes": 156 + }, + "qml/QtQuick/Controls.2/designer/images/slider-icon@2x.png": { + "sha256": "e2549f3edf7f059c7386780acb7b837282226713df8e335ea20eaae46d558292", + "bytes": 227 + }, + "qml/QtQuick/Controls.2/designer/images/spinbox-icon.png": { + "sha256": "a4b625cf8a9514fb099bf6ec10bb3e3cb85eec1965e559c7d2a945b4cce9fa07", + "bytes": 144 + }, + "qml/QtQuick/Controls.2/designer/images/spinbox-icon16.png": { + "sha256": "7aad6c549c1fd51ec8aa1ee8b022d45d09394a3ebcd53ea3f33719df11b7940f", + "bytes": 150 + }, + "qml/QtQuick/Controls.2/designer/images/spinbox-icon@2x.png": { + "sha256": "d3289d016477f1bb28d5a130207844a0d0142b72d1feeec9458c59d23326e257", + "bytes": 177 + }, + "qml/QtQuick/Controls.2/designer/images/stackview-icon.png": { + "sha256": "8756b0a58c9234ba22c8799ae08f0b85f1d3bcf8b75ad2a8edf774f2c8275cd0", + "bytes": 160 + }, + "qml/QtQuick/Controls.2/designer/images/stackview-icon16.png": { + "sha256": "0becb6fb56908d6e9923693f0685d0d03e8a14a65a03b823765914baeb07bf2b", + "bytes": 151 + }, + "qml/QtQuick/Controls.2/designer/images/stackview-icon@2x.png": { + "sha256": "8b196affa121b3423b2e552b6c000f4df419dcea9384707de5abcf5eb6d26534", + "bytes": 167 + }, + "qml/QtQuick/Controls.2/designer/images/swipeview-icon.png": { + "sha256": "e5856ad4fa95cbbad49f8d33705550a74a718fdb398eb82e717ed8b7c82f14d1", + "bytes": 163 + }, + "qml/QtQuick/Controls.2/designer/images/swipeview-icon16.png": { + "sha256": "98dd3480608943dbcfdf9c355084f03988bd7a479564c13eee52b603d744c90d", + "bytes": 152 + }, + "qml/QtQuick/Controls.2/designer/images/swipeview-icon@2x.png": { + "sha256": "c6ccb895a1fb51423297a02194e4d9a1ac2e5a7bd690903feca458582f90decd", + "bytes": 184 + }, + "qml/QtQuick/Controls.2/designer/images/switch-icon.png": { + "sha256": "c8f6d4cb1869750b512dcce9a605fe9625edd76117253dc41bae0c3d4dcb0c97", + "bytes": 205 + }, + "qml/QtQuick/Controls.2/designer/images/switch-icon16.png": { + "sha256": "8690393a518700ced00da1322c2438ba6f6498c54afdc309560e8dea1a953119", + "bytes": 160 + }, + "qml/QtQuick/Controls.2/designer/images/switch-icon@2x.png": { + "sha256": "c2a4b5012b355ad96952fd57ba2a9ab08a81558469192252fc4cfae35093b9aa", + "bytes": 307 + }, + "qml/QtQuick/Controls.2/designer/images/textarea-icon.png": { + "sha256": "5a266d70001496c2ea91123ea595228394257e937e0df19f3f3e95ffa00a0c47", + "bytes": 149 + }, + "qml/QtQuick/Controls.2/designer/images/textarea-icon16.png": { + "sha256": "86fd55628bc559bd328dd541bdc73ab9c6291252f1ff616a296a366c51311579", + "bytes": 133 + }, + "qml/QtQuick/Controls.2/designer/images/textarea-icon@2x.png": { + "sha256": "f51ce133dd7cb2ed74c8dab85e775c46e705bfc91d6212a8d04b0c5432c822a1", + "bytes": 163 + }, + "qml/QtQuick/Controls.2/designer/images/textfield-icon.png": { + "sha256": "dd0453fd04ffa9aedf5aac978fd4f2e22107fb46d6f2869cbac4de5903e1500a", + "bytes": 154 + }, + "qml/QtQuick/Controls.2/designer/images/textfield-icon16.png": { + "sha256": "87bf9b0604ef5c98187b70a2d9cc04ac70ca2d3485122eb13c48709853ba6da2", + "bytes": 147 + }, + "qml/QtQuick/Controls.2/designer/images/textfield-icon@2x.png": { + "sha256": "85b8ddbc37078a49f151f2bff080b33db54b6e0c2a8fe6a044b83d9a3148a2db", + "bytes": 172 + }, + "qml/QtQuick/Controls.2/designer/images/toolbar-icon.png": { + "sha256": "db071a5567a491e57e97c77c2c78d47f43ae055db7ed50a083355379f33db533", + "bytes": 110 + }, + "qml/QtQuick/Controls.2/designer/images/toolbar-icon16.png": { + "sha256": "ed1883e22bcde33b1f7685fa76729142942fe0853e53e9027ae056c2ce29f5b0", + "bytes": 104 + }, + "qml/QtQuick/Controls.2/designer/images/toolbar-icon@2x.png": { + "sha256": "286a7e5f47c1f8f67008ff1343ece35cd5236ae9682e6556398c4d19682b2406", + "bytes": 140 + }, + "qml/QtQuick/Controls.2/designer/images/toolbutton-icon.png": { + "sha256": "925d6c1f934919b59e1f3e142b2e7a38b0d4f6d5ca2fe67efb7f237b22c300a0", + "bytes": 141 + }, + "qml/QtQuick/Controls.2/designer/images/toolbutton-icon16.png": { + "sha256": "b9100761582d6e97600b89db4134048ed3145afd8766775206615c66586465f4", + "bytes": 112 + }, + "qml/QtQuick/Controls.2/designer/images/toolbutton-icon@2x.png": { + "sha256": "ab648e389ec4282747300e00a293a1dd7ddb56f63e232da241d9b66a66009590", + "bytes": 158 + }, + "qml/QtQuick/Controls.2/designer/images/toolseparator-icon.png": { + "sha256": "b1198feb502554a254f9c1f3d86c1934e793876606ce1923458d0838ce1ef114", + "bytes": 111 + }, + "qml/QtQuick/Controls.2/designer/images/toolseparator-icon16.png": { + "sha256": "b7b0010f45f586a24225f07576ad4569327ee948c51c58f77445c6709622c5f6", + "bytes": 123 + }, + "qml/QtQuick/Controls.2/designer/images/toolseparator-icon@2x.png": { + "sha256": "5b41b2f5367516b08139e31150ac48c16a256136b96c2d33ecbbb502aa8240ec", + "bytes": 131 + }, + "qml/QtQuick/Controls.2/designer/images/tumbler-icon.png": { + "sha256": "66bc18b0f169cf3c17c1ee95938b4e6a5f517594a7799839eb24468f05ea0511", + "bytes": 132 + }, + "qml/QtQuick/Controls.2/designer/images/tumbler-icon16.png": { + "sha256": "dfa7fd0dca712c77bab4161e6e8d5c2dfeed76d3bfd75b7a194bfd5988eb55e1", + "bytes": 127 + }, + "qml/QtQuick/Controls.2/designer/images/tumbler-icon@2x.png": { + "sha256": "7d2ee15dc2297ae4c6e376de8157b00f1361fc93fe374b2a170f4b9d2f90510e", + "bytes": 153 + }, + "qml/QtQuick/Controls.2/designer/qtquickcontrols2.metainfo": { + "sha256": "09e7bcda3626002443052f9b38e3d5e515f858aee514174445f6ea5bc339b9f4", + "bytes": 15045 + }, + "qml/QtQuick/Controls.2/libqtquickcontrols2plugin.so": { + "sha256": "f2f8d0fb12dc34f3b9b1ea4a83d81a3f7616050c5819f7bde41a26adcc85702f", + "bytes": 712520 + }, + "qml/QtQuick/Controls.2/plugins.qmltypes": { + "sha256": "3124701e4e52a38b6b94b285f333c513ca723e03a4758968a588b5f6e1da2704", + "bytes": 32446 + }, + "qml/QtQuick/Controls.2/qmldir": { + "sha256": "64c558cc0bf6b54b9d30e0472af3a2d6c4bdc510185b507ad2571b7cba861878", + "bytes": 135 + }, + "qml/QtQuick/Layouts/libqquicklayoutsplugin.so": { + "sha256": "5d9e4e208e657bd9ac72adad981abe327629b95e38d99c021a6eeb5c31716edf", + "bytes": 166128 + }, + "qml/QtQuick/Layouts/plugins.qmltypes": { + "sha256": "e19b66b72012afa0cd80d1edcf0d487d36a63310ce4ef7100064f950cca9dc86", + "bytes": 4774 + }, + "qml/QtQuick/Layouts/qmldir": { + "sha256": "36e294e1ea20fc9ee86fa7fc301aa5fdff5946d2f531c1d18e7056cf8c355384", + "bytes": 125 + }, + "qml/QtQuick/Templates.2/libqtquicktemplates2plugin.so": { + "sha256": "b05b24a78f9e836b79f3516df57ea5d82fa2bd2af10f58f4c5fa918f63b0ef87", + "bytes": 560480 + }, + "qml/QtQuick/Templates.2/plugins.qmltypes": { + "sha256": "5a499e54fefde8d3a313be0c54e69eafd1a9892de8f37a659b8533c2a957004d", + "bytes": 126225 + }, + "qml/QtQuick/Templates.2/qmldir": { + "sha256": "565d79b87633cb5c93f53444caa1f3c0df3f1258f8200fd520018c82bc82a557", + "bytes": 137 + }, + "qml/QtQuick/Window.2/libwindowplugin.so": { + "sha256": "665c67769f53d15c870b1cbaf67c9b6683be35d8f2b3894f6e2d9bee6175673d", + "bytes": 59616 + }, + "qml/QtQuick/Window.2/plugins.qmltypes": { + "sha256": "73df254fa19aa35eb6cd7a22d0db32e980ea1c86654c10ab8987fcdbb4418396", + "bytes": 14715 + }, + "qml/QtQuick/Window.2/qmldir": { + "sha256": "d91e660e8bdfcfc661709eb829ba2dfddecba34cae4bf6135f51d78d28659786", + "bytes": 117 + }, + "qml/QtQuick.2/libqtquick2plugin.so": { + "sha256": "82782eb53e10d29f7c12197b3af7b24df1340ac68f55df14484140efb8ff198b", + "bytes": 18656 + }, + "qml/QtQuick.2/plugins.qmltypes": { + "sha256": "a4c18f06fe88baa04cd638cb23cd161dfe015f1abb6af83ff7610a2e4235cfd9", + "bytes": 204541 + }, + "qml/QtQuick.2/qmldir": { + "sha256": "552dd9892fbaf38e8db48a41adb6ad0dab1b052aaae5adb3387e758d56b75dde", + "bytes": 125 } }, "host_libraries": [ diff --git a/plugins/vesc/packaging/native_broker_check.py b/plugins/vesc/packaging/native_broker_check.py new file mode 100644 index 00000000..a91a11ef --- /dev/null +++ b/plugins/vesc/packaging/native_broker_check.py @@ -0,0 +1,100 @@ +"""Real Qt signals, sandbox and read-intent bounds, with synthetic replies only.""" + +import base64 +import json +import os +import select +import struct +import subprocess +import time + + +def broker(binary, env, archive, report): + p = subprocess.Popen( + [str(binary)], + env=env, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + bufsize=0, + ) + buffer = b"" + + def call(value): + nonlocal buffer + p.stdin.write(json.dumps(value).encode() + b"\n") + deadline = time.monotonic() + 7 + while b"\n" not in buffer: + assert select.select([p.stdout], [], [], max(0, deadline - time.monotonic()))[0], ( + "QML broker timeout" + ) + chunk = os.read(p.stdout.fileno(), 65536) + assert chunk, "QML exited" + buffer += chunk + assert len(buffer) < 800 * 1024 + line, buffer = buffer.split(b"\n", 1) + v = json.loads(line) + assert ( + v["ok"] + and v["hardware_access"] is False + and v["sandbox_verified"] + and v["broker"] + and not v["snapshot_only"] + ), v.get("error") + return v + + try: + source = """import QtQuick 2.5 +Rectangle { id: root; property real volts: 0; color: volts > 40 ? "#246834" : "#263343" + Connections { target: VescIf.commands(); onValuesReceived: { root.volts = values.v_in; } } + MouseArea { anchors.fill: parent; onClicked: { + if (VescIf.isPortConnected() && VescIf.fwRx()) { VescIf.commands().getValues(); VescIf.commands().getImuData(511); } + VescIf.commands().setRpm(99); VescIf.commands().sendTerminalCmd("help"); } } +}""" + first = call( + { + **archive, + "source": source, + "width": 640, + "height": 480, + "standalone": False, + "broker": True, + "interactive": True, + "values": base64.b64encode(bytes([4]) + bytes(95)).decode(), + } + ) + clicked = call( + { + "op": "frame", + "events": [{"kind": "down", "x": 20, "y": 20}, {"kind": "up", "x": 20, "y": 20}], + } + ) + assert {"command": 4} in clicked["read_requests"] and { + "command": 65, + "mask": 511, + } in clicked["read_requests"] + assert 8 in clicked["blocked_codes"] and 20 in clicked["blocked_codes"] + raw = bytes([4]) + struct.pack( + ">hhiiiihihiiiiiiB", 250, 250, 0, 0, 0, 0, 0, 0, 480, 0, 0, 0, 0, 0, 0, 0 + ) + replied = call({"op": "frame", "events": [], "packets": [base64.b64encode(raw).decode()]}) + assert replied["png"] != first["png"], "Fresh real Commands signal did not update QML" + assert all( + x["command"] in (0, 4, 14, 17, 31, 32, 33, 65, 96) for x in replied["read_requests"] + ) + p.stdin.write(b'{"op":"close"}\n') + p.wait(timeout=3) + assert p.returncode == 0 + report["checks"].append( + { + "id": "qml-broker-read-signals-write-denied-no-transport", + "ok": True, + "hardware_access": False, + } + ) + finally: + if p.poll() is None: + p.kill() + p.wait(timeout=3) + p.stdin.close() + p.stdout.close() diff --git a/plugins/vesc/packaging/native_bundle.py b/plugins/vesc/packaging/native_bundle.py index a0c3b26f..564529bb 100644 --- a/plugins/vesc/packaging/native_bundle.py +++ b/plugins/vesc/packaging/native_bundle.py @@ -12,11 +12,14 @@ import re import shutil import subprocess import tarfile +from engine_profile import load_profile, contract SYSTEM = {"libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1", "libresolv.so.2", "ld-linux-x86-64.so.2"} -def build(engine, sysroot, source, output): +def build(engine, sysroot, source, output, qml_sysroot): + profile = load_profile((engine.parent / "engine-profile.json").read_bytes()) + upstream = profile["upstream"] output.mkdir(mode=0o700, exist_ok=False) staging = output / "payload" (staging / "bin").mkdir(parents=True) @@ -27,9 +30,17 @@ def build(engine, sysroot, source, output): qtlib = sysroot / "usr/lib/x86_64-linux-gnu" plugin = qtlib / "qt5/plugins/platforms/libqoffscreen.so" shutil.copyfile(plugin, staging / "plugins/platforms/libqoffscreen.so") + renderer = staging / "bin/mission-core-vesc-qml-preview" + shutil.copyfile(engine.parent / renderer.name, renderer); renderer.chmod(0o755) + qml = qml_sysroot / "usr/lib/x86_64-linux-gnu/qt5/qml" + shutil.copytree(qml, staging / "qml") + shutil.copytree(qml_sysroot / "usr/share/fonts/truetype/dejavu", staging / "fonts") + qml_plugins = list((staging / "qml").rglob("*.so")) + if len(qml_plugins) < 5: raise RuntimeError("QML runtime modules missing") + closure_inputs = [engine, renderer, plugin, *qml_plugins] env = dict(os.environ, LD_LIBRARY_PATH=str(qtlib), LC_ALL="C") sources = {} - for executable in (engine, plugin): + for executable in closure_inputs: result = subprocess.run(["/usr/bin/ldd", str(executable)], env=env, capture_output=True, text=True, check=True).stdout if "not found" in result: raise RuntimeError("Native runtime dependency missing") for name, path in re.findall(r"^\s*(\S+) => (/[\S]+) \(", result, re.MULTILINE): @@ -41,7 +52,7 @@ def build(engine, sysroot, source, output): env.update(LD_LIBRARY_PATH=str(staging / "lib"), QT_PLUGIN_PATH=str(staging / "plugins"), QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=str(output / "config"), XDG_CACHE_HOME=str(output / "cache")) # All non-glibc ELF dependencies must now resolve inside the shipped payload. - for executable in (binary, staging / "plugins/platforms/libqoffscreen.so"): + for executable in [binary, renderer, staging / "plugins/platforms/libqoffscreen.so", *qml_plugins]: result = subprocess.run(["/usr/bin/ldd", str(executable)], env=env, capture_output=True, text=True, check=True).stdout if "not found" in result: raise RuntimeError("Bundled native closure incomplete") for name, path in re.findall(r"^\s*(\S+) => (/[\S]+) \(", result, re.MULTILINE): @@ -52,19 +63,22 @@ def build(engine, sysroot, source, output): responses = [json.loads(line) for line in proc.stdout.splitlines()] if len(responses) != 2 or not responses[0]["ready"] or responses[1]["result"]["connected"]: raise RuntimeError("Bundled engine acceptance failed") + info = responses[1]["result"] + if info.get("version") != upstream["version"] or info.get("commit") != upstream["commit"] or info.get("contract") != contract(profile): + raise RuntimeError("Bundled engine version or contract differs from reviewed profile") (output / "offline.stdout").write_bytes(proc.stdout) (output / "offline.stderr").write_bytes(proc.stderr) (staging / "licenses").mkdir() shutil.copyfile(source / "LICENSE", staging / "licenses/VESC-Tool-LICENSE") (staging / "licenses/UPSTREAM-SOURCE.txt").write_text( - "VESC Tool 7.00, unmodified upstream sources and resources:\n" - "https://github.com/vedderb/vesc_tool/tree/01d5f10901116c311e3fb84d5a1541f663d3ce20\n" - "Source archive SHA-256: 4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189\n" - "The process adapter source is included alongside this notice.\n") - for name in ("engine_main.cpp", "config_export.h"): + f"VESC Tool {upstream['version']}, unmodified upstream sources and resources:\n" + f"{upstream['repository']}/tree/{upstream['commit']}\n" + f"Source archive SHA-256: {upstream['source_sha256']}\n" + "The process adapter source and release profile are included alongside this notice.\n") + for name in ("qml_vesc_interface.h", "qml_broker.h", "qml_interactive.h", "sample_data.h", "qml_preview.cpp", "qml_sandbox.h", "engine_main.cpp", "config_export.h", "config_edit.h", "firmware_image.h", "firmware_source.h", "firmware_native.h", "swd_native.h", "tools_native.h", "bms_native.h", "custom_native.h", "code_native.h", "package_native.h", "engine_profile.h", "engine-profile.json"): shutil.copyfile(engine.parent / name, staging / "licenses" / name) # Preserve dependency notices available in the private signed-package sysroot. - for index, path in enumerate(sorted((sysroot / "usr/share/doc").glob("*/copyright"))): + for index, path in enumerate(sorted((sysroot / "usr/share/doc").glob("*/copyright")) + sorted((qml_sysroot / "usr/share/doc").glob("*/copyright"))): shutil.copyfile(path, staging / "licenses" / (path.parent.name + ".copyright")) # Host libraries copied into the closure retain their distribution notices. for library in sources.values(): @@ -80,8 +94,9 @@ def build(engine, sysroot, source, output): with tarfile.open(archive, "w:gz") as stream: for path in sorted(staging.rglob("*")): if path.is_file(): stream.add(path, arcname=str(path.relative_to(staging))) - report = {"schema":"missioncore.vesc.native-runtime/v1", "upstream_version":"7.00", - "upstream_commit":"01d5f10901116c311e3fb84d5a1541f663d3ce20", "os":"ubuntu-24.04-amd64", + report = {"schema":"missioncore.vesc.native-runtime/v1", "upstream_version":upstream["version"], + "upstream_commit":upstream["commit"], "upstream_source_sha256":upstream["source_sha256"], + "engine_contract":contract(profile), "os":profile["environment"], "file":archive.name, "bytes":archive.stat().st_size, "sha256":hashlib.sha256(archive.read_bytes()).hexdigest(), "engine_sha256":hashlib.sha256(binary.read_bytes()).hexdigest(), "files":metadata, "host_libraries":sorted(SYSTEM), "offline_verified":True, "hardware_qualified":False, @@ -91,5 +106,5 @@ def build(engine, sysroot, source, output): if __name__ == "__main__": parser=argparse.ArgumentParser() - for name in ("engine","sysroot","source","output"):parser.add_argument("--"+name,type=Path,required=True) - args=parser.parse_args();build(args.engine,args.sysroot,args.source,args.output) + for name in ("engine","sysroot","source","output","qml-sysroot"):parser.add_argument("--"+name,type=Path,required=True) + args=parser.parse_args();build(args.engine,args.sysroot,args.source,args.output,args.qml_sysroot) diff --git a/plugins/vesc/packaging/native_can_check.py b/plugins/vesc/packaging/native_can_check.py new file mode 100644 index 00000000..0c2f2b20 --- /dev/null +++ b/plugins/vesc/packaging/native_can_check.py @@ -0,0 +1,99 @@ +"""Inert loopback peer for the native CAN transport. No SDK/device access.""" +import base64 +import time +from pathlib import Path +import binascii +import json +import select +import socket +import subprocess +import sys +import threading + +def framed(payload): + width=1 if len(payload)<256 else 2 + return bytes([width+1])+len(payload).to_bytes(width,"big")+payload+binascii.crc_hqx(payload,0).to_bytes(2,"big")+b"\x03" + +def main(): + listener=socket.socket() + listener.bind(("127.0.0.1",0));listener.listen(1);listener.settimeout(5) + frames=[];errors=[] + archive=json.loads(Path(sys.argv[2]).read_text()) + configs={14:base64.b64decode(archive["configs"]["motor"]["payload"]),17:base64.b64decode(archive["configs"]["application"]["payload"])} + def peer(): + try: + conn,_=listener.accept() + with conn: + conn.settimeout(5) + buffer=b"" + while True: + data=conn.recv(16384) + if not data:break + buffer+=data + while len(buffer)>=2: + width=buffer[0]-1 + if width not in (1,2):raise ValueError("Invalid framing") + if len(buffer)30, "Qualification fixture must exercise above-30-A config" + assert rpc("lease")["ok"] + rejected=rpc("duty_limited",duty=.5,current_a=ceiling-1) + assert not rejected["ok"],rejected + accepted=rpc("duty_limited",duty=.5,current_a=ceiling) + assert accepted["ok"] and accepted["control"]["output_kind"]=="duty",accepted + assert rpc("lease")["ok"] + mark=len(frames) + zero=rpc("duty_limited",duty=0,current_a=ceiling) + assert zero["ok"] and "0500000000" in frames[mark:],(zero,frames[mark:]) + assert "0600000000" not in frames[mark:],frames[mark:] + previous=zero["control"]["watchdog_trips"] + time.sleep(.27) + expired=rpc("query",command=0,timeout_ms=1000) + assert expired["ok"] and expired["control"]["watchdog_trips"]>previous,expired + assert expired["control"]["output_kind"]=="watchdog_release",expired + assert not rpc("duty_limited",duty=.5,current_a=ceiling)["ok"] + process.stdin.close();process.wait(timeout=5);thread.join(5) + assert process.returncode==0 and not errors,(process.returncode,errors) + assert any(v.startswith("08") for v in frames),frames + assert frames.count("ff4d434252")>=3,frames + print(json.dumps({"ok":True,"hardware_access":False,"transport":"private-loopback","frames":frames})) + finally: + if process.poll() is None:process.kill();process.wait(timeout=5) + listener.close() +if __name__=="__main__":main() diff --git a/plugins/vesc/packaging/native_check.py b/plugins/vesc/packaging/native_check.py index da34918e..aa312b6b 100644 --- a/plugins/vesc/packaging/native_check.py +++ b/plugins/vesc/packaging/native_check.py @@ -24,7 +24,10 @@ def check(root): replies = [json.loads(line) for line in result.stdout.splitlines()] if (len(replies) != 2 or not replies[0]["ready"] or not replies[1]["ok"] or replies[1]["result"]["hardware_enabled"] or replies[1]["result"]["connected"] - or replies[1]["result"]["commit"] != manifest["upstream_commit"]): + or replies[1]["result"]["commit"] != manifest["upstream_commit"] + or replies[1]["result"]["version"] != manifest["upstream_version"] + or replies[1]["result"].get("contract") != manifest.get("engine_contract") + or manifest.get("engine_contract", {}).get("rpc_version") != 1): raise RuntimeError("Native engine offline check failed") print(json.dumps({"ok":True, "upstream_commit":manifest["upstream_commit"], "hardware_access":False})) diff --git a/plugins/vesc/packaging/native_extensions_check.py b/plugins/vesc/packaging/native_extensions_check.py new file mode 100644 index 00000000..c5a12181 --- /dev/null +++ b/plugins/vesc/packaging/native_extensions_check.py @@ -0,0 +1,28 @@ +"""Offline qualification against pinned upstream BMS schema and CodeLoader.""" +import base64 +import json + + +def check_extensions(execute,target,raw,root,report): + b64=lambda b:base64.b64encode(b).decode() + original=json.loads(raw) + def run(name,fields,expected=0): + value={**original,**fields} + output=json.loads(execute(name,[str(target)],json.dumps(value).encode(),expected=expected)) + if output['ok']!=(expected==0) or output['hardware_access']:raise RuntimeError('Native extension qualification failed: '+name) + report['checks'].append({'id':name,'ok':True,'hardware_access':False}) + return output + schema=(root/'bms-settings.xml').read_bytes() + value=run('custom-bms-schema',{'custom_schema':b64(schema)}) + config=value['custom_configuration'] + assert len(config['parameters'])>=32 and config['round_trip_exact'] and config['groups'] + for name,source,expected in [('typed',{'changes':{'max_bal_ch':2}},0),('xml',{'xml':config['xml']},0),('unknown',{'changes':{'missing_param':12}},1),('bounds',{'changes':{'max_bal_ch':100000}},1),('entity',{'xml':']>&z;'},1)]: + run('custom-'+name,{'custom_schema':b64(schema),'custom_edit':source},expected) + run('custom-schema-dtd',{'custom_schema':b64(b']>&z;')},1) + for kind,source,files in [('lisp','(+ 1 2)',{}),('lisp','(import "test.bin" \'blob)\n(print blob)',{'test.bin':b64(b'\x00\xff\x01')}),('qml','import QtQuick 2.12\nItem { width: 200; height: 100 }',{})]: + run('code-'+kind+'-'+str(len(files)),{'code_project':{'kind':kind,'source':source,'imports':files,'fullscreen':True}}) + for label,source,files in [('parent','(import "../secret" \'x)',{}),('absolute','(import "/etc/passwd" \'x)',{}),('package','(import "pkg::code@x" \'x)',{}),('missing','(import "a.bin" \'x)',{}),('duplicate','(import "a.bin" \'x)\n(import "b.bin" \'x)',{'a.bin':b64(b'a'),'b.bin':b64(b'b')}),('nul','abc\0def',{}),('oversize','x'*122881,{})]: + run('code-reject-'+label,{'code_project':{'kind':'lisp','source':source,'imports':files,'fullscreen':False}},1) + run('code-reject-checksum',{'code_image':{'kind':'lisp','image':b64(b'\0'*10)}},1) + run('code-reject-import-range',{'code_decode':{'kind':'lisp','payload':b64(b'x\0\0\1tag\0\xff\xff\xff\xff\0\0\0\4')}},1) + run('code-reject-qml-inflate',{'code_decode':{'kind':'qml','payload':b64(b'\x7f\xff\xff\xffAAAA')}},1) diff --git a/plugins/vesc/packaging/native_packages_check.py b/plugins/vesc/packaging/native_packages_check.py new file mode 100644 index 00000000..3402ad4b --- /dev/null +++ b/plugins/vesc/packaging/native_packages_check.py @@ -0,0 +1,27 @@ +"""Offline upstream package codec and pure compatibility function qualification.""" +import base64,json,zlib,struct + +def check_packages(execute,target,raw,root,report): + from package_archive import archive + b64=lambda b:base64.b64encode(b).decode() + original=json.loads(raw) + fw={'hardware':'75_300_R2','hardware_type':0,'major':6,'minor':0,'firmware_name':''} + def run(name,package,identity=fw,expected=0): + result=json.loads(execute(name,[str(target)],json.dumps({**original,'package':{'data':b64(package),'identity':identity,'export_library':name.startswith('pkg-official-')}}).encode(),expected=expected)) + assert result['ok']==(expected==0) and not result['hardware_access'] + report['checks'].append({'id':name,'ok':True,'hardware_access':False}) + return result.get('package') + def pkg(desc='',extra=b''): + raw=b'VESC Packet\0'+b'name\0'+struct.pack('>i',4)+b'Test'+b'pkgDescQml\0'+struct.pack('>i',len(desc.encode()))+desc.encode()+extra + return struct.pack('>I',len(raw))+zlib.compress(raw) + assert run('pkg-compatible',pkg('Item { function isCompatible(p) {return p.hwTypeStr()=="VESC" && p.major==6;} }'))['compatible'] is True + assert run('pkg-incompatible',pkg('Item { function isCompatible(p) {return p.hwTypeStr()=="custom module";} }'))['compatible'] is False + for label,source in [('loop','while(true){}'),('no-host','return typeof Qt!=="undefined" || typeof XMLHttpRequest!=="undefined" || typeof VescIf!=="undefined";'),('nonboolean','return "yes";'),('throw','throw Error("failed");')]: + value=run('pkg-js-'+label,pkg('Item { Component.onCompleted: {throw "never";} function isCompatible(p) {'+source+'} }'))['compatible'] + assert value is (False if label=='no-host' else None) + for label,data in [('duplicate',pkg(extra=b'name\0\0\0\0\1x')),('length',pkg(extra=b'bad\0\xff\xff\xff\xff')),('flag',pkg(extra=b'qmlIsFullscreen\0\0\0\0\2\0\0')),('inflate',b'\0\0\0\1'+zlib.compress(b'x'*100000))]:run('pkg-reject-'+label,data,expected=1) + entries=archive((root/'vesc_pkg_all.rcc').read_bytes()) + for i,(name,data) in enumerate(entries.items()): + value=run('pkg-official-'+str(i),data) + assert value['name'] and set(value['images'])=={'lisp','qml'} + if not value['fits']:assert value['images']=={'lisp':'','qml':''} diff --git a/plugins/vesc/packaging/native_probe.py b/plugins/vesc/packaging/native_probe.py index c006fc10..9534335f 100644 --- a/plugins/vesc/packaging/native_probe.py +++ b/plugins/vesc/packaging/native_probe.py @@ -16,8 +16,7 @@ import subprocess import time import zipfile -COMMIT = "01d5f10901116c311e3fb84d5a1541f663d3ce20" -UPSTREAM_SHA256 = "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189" +from engine_profile import load_profile, contract def digest(path): @@ -25,6 +24,10 @@ def digest(path): def run(args): + with zipfile.ZipFile(args.artifact) as bundle: + profile = load_profile(bundle.read("engine-profile.json")) + COMMIT = profile["upstream"]["commit"] + UPSTREAM_SHA256 = profile["upstream"]["source_sha256"] release = platform.freedesktop_os_release() if os.geteuid() == 0 or (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != ("ubuntu", "24.04", "x86_64"): raise RuntimeError("Unprivileged Ubuntu 24.04 amd64 required") @@ -33,7 +36,7 @@ def run(args): if limit == "max" or int(limit) > 3 * 1024**3: raise RuntimeError("A bounded user scope with MemoryMax <= 3G is required") previous = json.loads(args.upstream_report.read_text()) - if previous.get("state") != "complete" or previous.get("source_sha256") != UPSTREAM_SHA256: + if previous.get("state") != "complete" or previous.get("source_sha256") != UPSTREAM_SHA256 or previous.get("source_commit") != COMMIT: raise RuntimeError("Unqualified upstream build") upstream = Path(previous["binary"]) if digest(upstream) != previous["binary_sha256"]: @@ -48,7 +51,7 @@ def run(args): if any(not re.fullmatch(r"[A-Za-z0-9_./-]+", str(p)) for p in (root, source)): raise RuntimeError("Build paths must be make-safe") with zipfile.ZipFile(args.artifact) as bundle: - for name in ("offline_main.cpp", "config_export.h", "engine_main.cpp", "native_bundle.py"): + for name in ("native_can_check.py", "native_broker_check.py", "native_samples_check.py", "qml_vesc_interface.h", "qml_broker.h", "qml_interactive.h", "sample_data.h", "qml_preview.cpp", "qml_sandbox.h", "qml_build.py", "bms-settings.xml", "native_extensions_check.py", "native_packages_check.py", "package_archive.py", "vesc_pkg_all.rcc", "offline_main.cpp", "config_export.h", "config_edit.h", "firmware_image.h", "firmware_source.h", "firmware_native.h", "swd_native.h", "tools_native.h", "bms_native.h", "custom_native.h", "code_native.h", "package_native.h", "engine_main.cpp", "native_bundle.py", "engine_profile.py", "engine_profile.h", "engine-profile.json"): (root / name).write_bytes(bundle.read(name)) report = {"schema": "missioncore.vesc.native-probe/v1", "state": "running", "started_at": datetime.now(timezone.utc).isoformat(), "monotonic_started": time.monotonic(), @@ -101,7 +104,7 @@ def run(args): "mission-core-native-probe:\n" "\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o " + str(root / "offline_main.o") + " " + str(root / "offline_main.cpp") + "\n" "\t$(LINK) $(LFLAGS) -o " + str(target) + " " + str(root / "offline_main.o") + - " $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS)\n") + " $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS) -lz\n") execute("compile-link", ["/usr/bin/make", "-f", str(wrapper), "mission-core-native-probe"], timeout=180) report["binary_sha256"] = digest(target) for index, archive in enumerate(args.archives): @@ -126,6 +129,101 @@ def run(args): "xml_equivalent_by_upstream_comparison": True, "xml_binary_exact": all(native[k]["xml_round_trip_exact"] for k in ("motor", "application")), "legacy_power_loss_correction": True}) + # Exercise the same native preparation used online, without any transport. + edits = [ + ("typed", {"changes": {"l_current_max": 20.0}}, 0), + ("restore", {"payload": json.loads(raw)["configs"]["motor"]["payload"]}, 0), + ("xml", {"xml": native["motor"]["xml"]}, 0), + ("unknown-field", {"changes": {"not_a_parameter": 1}}, 1), + ("outside-range", {"changes": {"l_current_max": 1e12}}, 1), + ("wrong-type", {"changes": {"l_current_max": "20"}}, 1), + ("bad-enum", {"changes": {"motor_type": 500}}, 1), + ("xml-unknown", {"xml": "1"}, 1), + ("xml-metadata", {"xml": "Changed"}, 1), + ("xml-nan", {"xml": "NaN"}, 1), + ("xml-duplicate", {"xml": "2030"}, 1), + ("xml-entity", {"xml": ']>&x;'}, 1), + ] + for label, source_edit, expected in edits: + value = json.loads(raw); value["edit"] = {"kind": "motor", "source": source_edit} + edited = json.loads(execute("edit-%s-%d" % (label, index), [str(target)], json.dumps(value).encode(), expected=expected)) + if edited.get("ok") != (expected == 0) or edited.get("hardware_access"): + raise RuntimeError("Native edit qualification mismatch") + if label == "typed" and not any(p["name"] == "l_current_max" and p["after"] == 20 for p in edited["edit"]["changes"]): + raise RuntimeError("Native edit did not preserve requested value") + if label == "restore" and edited["edit"]["changes"]: + raise RuntimeError("Restoring the identical backup changed parameters") + report["checks"].append({"id": "edit-%s-%d" % (label, index), "ok": True}) + # Test exactly the file inspector used by the USB owner, but with + # synthetic vectors and no transport or firmware upload. + image = bytes.fromhex("0000022001010008") + bytes(1016) + for label, data, kind, expected in ( + ("raw",image,"firmware",0), ("bootloader",image,"bootloader",0), + ("short",image[:100],"firmware",1), ("stack",bytes(1024),"firmware",1), + ("reset",image[:4]+bytes(4)+image[8:],"firmware",1), + ("large-bootloader",image+bytes(65536),"bootloader",1), + ("kind",image,"other",1)): + value = json.loads(raw) + value["firmware_image"] = {"data":base64.b64encode(data).decode(),"kind":kind} + inspected = json.loads(execute("image-%s-%d" % (label,index),[str(target)],json.dumps(value).encode(),expected=expected)) + if inspected.get("ok") != (expected == 0) or inspected.get("hardware_access"): + raise RuntimeError("Firmware image inspection qualification failed") + if expected == 0 and inspected["firmware_image"]["sha256"] != hashlib.sha256(data).hexdigest(): + raise RuntimeError("Firmware image digest changed") + # Original HexFile normalization behind strict container/address bounds. + def hexline(address, kind, data=b''): + record=bytes([len(data),address>>8,address&255,kind])+data + return b':'+(record+bytes([-sum(record)&255])).hex().upper().encode()+b'\n' + def ihex(data, base=0x08000000): + return hexline(0,4,(base>>16).to_bytes(2,'big'))+b''.join(hexline(i,0,data[i:i+16]) for i in range(0,len(data),16))+hexline(0,1) + valid=ihex(image) + gap=hexline(0,4,b'\x08\x00')+hexline(0,0,image[:16])+hexline(1008,0,image[-16:])+hexline(0,1) + reordered=hexline(0,4,b'\x08\x00')+hexline(1008,0,image[-16:])+hexline(0,0,image[:16])+hexline(0,1) + duplicate=valid.replace(hexline(0,1),hexline(0,0,image[:16])+hexline(0,1)) + for label,data,kind,expected in [ + ('valid',valid,'firmware',0),('crlf',valid.replace(b'\n',b'\r\n'),'firmware',0), + ('gap',gap,'firmware',0),('reordered',reordered,'firmware',0), + ('checksum',valid.replace(b':020000040800F2',b':020000040800F3'),'firmware',1), + ('junk',valid.replace(b':10',b':1G',1),'firmware',1),('overlap',duplicate,'firmware',1), + ('truncated',valid.replace(hexline(0,1),b''),'firmware',1), + ('trailing',valid+hexline(16,0,image[16:32]),'firmware',1), + ('wrong-base',ihex(image,0x08010000),'firmware',1), + ('sparse',valid.replace(hexline(0,1),hexline(0,4,b'\x09\x00')+hexline(0,0,image[:16])+hexline(0,1)),'firmware',1), + ('bootloader-address',valid,'bootloader',1)]: + value=json.loads(raw);value['firmware_image']={'data':base64.b64encode(data).decode(),'kind':kind,'format':'hex'} + inspected=json.loads(execute('hex-%s-%d'%(label,index),[str(target)],json.dumps(value).encode(),expected=expected)) + if inspected.get('ok')!=(expected==0):raise RuntimeError('HEX admission failed: '+label) + if expected==0: + actual=inspected['firmware_image'] + normalized=image if label in ('valid','crlf') else image[:16]+b'\xff'*992+image[-16:] + if actual['source_sha256']!=hashlib.sha256(data).hexdigest() or actual['sha256']!=hashlib.sha256(normalized).hexdigest(): + raise RuntimeError('HEX normalized bytes differ') + # Original Commands serialization, disconnected from every transport. + for action,suffix in [('charge_enable','6101'),('charge_disable','6100'),('balance_enable','6401'),('balance_disable','6400'),('reset_ah','630100'),('reset_wh','630001'),('zero_current','65')]: + for can_id in (0,253): + value=json.loads(raw);value['bms_command']={'can_id':can_id,'command':action} + checked=json.loads(execute('bms-%s-%d-%d'%(action,can_id,index),[str(target)],json.dumps(value).encode())) + # COMM_FORWARD_CAN(34), exact target, upstream typed command. + if checked['bms_command']['packet_hex']!='22'+format(can_id,'02x')+suffix: + raise RuntimeError('Unexpected BMS CAN command serialization') + for can_id,command in [(255,'charge_enable'),(-1,'charge_enable'),(1,'motor_run'),(1.5,'reset_ah')]: + value=json.loads(raw);value['bms_command']={'can_id':can_id,'command':command} + execute('bms-reject-%s-%s-%d'%(can_id,command,index),[str(target)],json.dumps(value).encode(),expected=1) + report['checks'].append({'id':'bms-unicast-serialization-%d'%index,'ok':True,'hardware_access':False}) + for name, target_spec, expected in ( + ("stm32",{'target_code':1,'pins':'default','address':0x08000000,'flash_bytes':131072},0), + ("nrf",{'target_code':8,'pins':'nrf5x','address':0,'flash_bytes':1048576},0), + ("uicr",{'target_code':8,'pins':'nrf5x','address':0x10001000,'flash_bytes':1024},1), + ("short-range",{'target_code':1,'pins':'default','address':0x08000000,'flash_bytes':256},1), + ("family",{'target_code':99,'pins':'default','address':0,'flash_bytes':1024},1)): + candidate=json.loads(raw);candidate['swd_image']={'target':target_spec,'data':base64.b64encode(image).decode()} + result=json.loads(execute(f'swd-{name}-{index}',[str(target)],json.dumps(candidate).encode(),expected=expected)) + if result['ok']!=(expected==0) or result['hardware_access']:raise RuntimeError('SWD image boundary failed') + report['checks'].append({'id':f'swd-{name}-{index}','ok':True}) + candidate=json.loads(raw);candidate['can_route']=7 + result=json.loads(execute(f'can-route-{index}',[str(target)],json.dumps(candidate).encode())) + if not result.get('can_route') or result['hardware_access']:raise RuntimeError('CAN route qualification failed') + report['checks'].append({'id':f'can-route-{index}','ok':True}) # Fail closed on archive corruption and unsupported firmware instead # of silently presenting the bundled defaults as actual settings. original = json.loads(raw) @@ -144,6 +242,10 @@ def run(args): if rejected["ok"] or rejected["hardware_access"]: raise RuntimeError("Invalid archive was not rejected") report["checks"].append({"id": "%s-%d" % (name, index), "ok": True}) + from native_packages_check import check_packages + from native_extensions_check import check_extensions + check_extensions(execute,target,raw,root,report) + check_packages(execute,target,raw,root,report) for item in report["link_objects"]: if digest(source / item["file"]) != item["sha256"]: raise RuntimeError("Upstream objects were modified") @@ -152,18 +254,81 @@ def run(args): "\n.PHONY: mission-core-native-engine\nmission-core-native-engine:\n" "\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o " + str(root / "engine_main.o") + " " + str(root / "engine_main.cpp") + "\n" "\t$(LINK) $(LFLAGS) -o " + str(engine) + " " + str(root / "engine_main.o") + - " $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS)\n") + " $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS) -lz\n") execute("engine-compile", ["/usr/bin/make", "-f", str(wrapper), "mission-core-native-engine"], timeout=180) requests = [{"id": 1, "method": "engine"}, {"id": 2, "method": "current", "current_a": 30}, - {"id": 3, "method": "hall_start", "current_a": 5}, {"id": 4, "method": "arbitrary_packet"}] + {"id": 3, "method": "hall_start", "current_a": 5}, {"id": 4, "method": "arbitrary_packet"}, + { "id": 5, "method": "duty", "duty": .5}, + {"id": 6, "method": "configuration_preview"}, {"id": 7, "method": "configuration_apply"}] + requests += [{"id":100+i,"method":method} for i,method in enumerate(profile["methods"]) if method.startswith("sample_") or method.startswith("firmware_") or method == "device_tool" or method.startswith("custom_") or (method.startswith("code_") and method != "code_pack")] responses = [json.loads(line) for line in execute("engine-offline", [str(engine), "--offline"], b"".join(json.dumps(r).encode()+b"\n" for r in requests)).splitlines()] - if (len(responses) != 5 or not responses[0]["ready"] or not responses[1]["ok"] + if (len(responses) != len(requests) + 1 or not responses[0]["ready"] or not responses[1]["ok"] or any(r["ok"] for r in responses[2:]) or responses[1]["result"]["hardware_enabled"]): raise RuntimeError("Native engine offline boundary failed") + if responses[1]["result"].get("contract") != contract(profile): + raise RuntimeError("Native adapter contract differs from release profile") + can_check = json.loads(execute("engine-can-synthetic", ["/usr/bin/python3", str(root / "native_can_check.py"), str(engine), str(args.archives[0])])) + if can_check.get("ok") is not True: raise RuntimeError("Native CAN loopback check failed") + report["checks"].append({"id": "engine-can-synthetic", "ok": True, "hardware_access": False}) + report["engine_contract"] = contract(profile) report["checks"].append({"id": "engine-offline-denies-hardware", "ok": True}) + from native_samples_check import samples, interactive + samples(execute,target,json.loads(args.archives[0].read_bytes()),report) + from qml_build import dependencies + qmlroot = dependencies(root, execute, args.qml_dependency_cache) + renderer = root / "mission-core-vesc-qml-preview" + wrapper.write_text(wrapper.read_text() + + "\n.PHONY: mission-core-qml-preview\nmission-core-qml-preview:\n" + "\t" + str(qtbase / "lib/qt5/bin/moc") + " $(DEFINES) $(INCPATH) " + str(root / "qml_vesc_interface.h") + " -o " + str(root / "qml_vesc_interface.moc") + "\n" + "\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o " + str(root / "qml_preview.o") + " " + str(root / "qml_preview.cpp") + "\n" + "\t$(LINK) $(LFLAGS) -o " + str(renderer) + " " + str(root / "qml_preview.o") + + " $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS) -lz\n") + execute("qml-compile", ["/usr/bin/make", "-f", str(wrapper), "mission-core-qml-preview"], timeout=180) execute("runtime-bundle", ["/usr/bin/python3", str(root / "native_bundle.py"), - "--engine", str(engine), "--sysroot", str(staging / "sysroot"), "--source", str(source), "--output", str(root / "runtime")], timeout=180) + "--qml-sysroot", str(qmlroot), "--engine", str(engine), "--sysroot", str(staging / "sysroot"), "--source", str(source), "--output", str(root / "runtime")], timeout=180) + payload = root / "runtime/payload" + qenv = dict(env, LD_LIBRARY_PATH=str(payload / "lib"), QT_PLUGIN_PATH=str(payload / "plugins")) + interactive(payload / "bin/mission-core-vesc-qml-preview", qenv, report, root) + from native_broker_check import broker + broker(payload / "bin/mission-core-vesc-qml-preview", qenv, json.loads(args.archives[0].read_bytes()), report) + candidate = json.loads(args.archives[0].read_bytes()) + candidate.update(width=640,height=480,values=base64.b64encode(bytes([4])+bytes(95)).decode()) + for label, text, expected in ( + ("fill-viewport", 'import QtQuick 2.5; Rectangle { anchors.fill: parent; color: "#112233"; Rectangle { anchors.right: parent.right; anchors.bottom: parent.bottom; width: 40; height: 40; color: "#c0ffee" } }', True), + ("controls", 'import QtQuick 2.5; import QtQuick.Controls 2.2; Rectangle { color: "#112233"; Label { text: "Snapshot verified"; anchors.centerIn: parent } }', True), + ("motor-command-is-discarded", 'import QtQuick 2.5; Rectangle { Component.onCompleted: VescIf.commands().setRpm(999); color: "#123456" }', True), + ("syntax-error", 'import QtQuick 2.5; BROKEN {', False)): + candidate['source'] = text + checked = subprocess.run([str(payload/'bin/mission-core-vesc-qml-preview')], input=json.dumps(candidate).encode(),env=qenv,capture_output=True,timeout=8) + (root/('qml-'+label+'.stdout')).write_bytes(checked.stdout) + (root/('qml-'+label+'.stderr')).write_bytes(checked.stderr) + result = json.loads(checked.stdout) + if result.get('ok') != expected or result.get('hardware_access') is not False or result.get('sandbox_verified') is not True: + raise RuntimeError('QML qualification failed: '+label+' '+str(result)) + if label == "fill-viewport" and (result.get("root_width"), result.get("root_height")) != (640,480): + raise RuntimeError("Anchored QML root does not fill the viewport") + if expected and (not base64.b64decode(result['png']).startswith(b'\x89PNG\r\n\x1a\n') or (result['width'], result['height']) != (640,480)): + raise RuntimeError('Invalid rendered QML frame') + if label=='motor-command-is-discarded' and result['discarded_commands']<1:raise RuntimeError('QML command was not observed/discarded') + report['checks'].append({'id':'qml-'+label,'ok':True,'hardware_access':False}) + for label, file in (("LogUI", "pkg-official-1.stdout"), ("VL-ABI-Encoder-Config", "pkg-official-38.stdout")): + pkg = json.loads((root/file).read_text())['package'] + candidate['source'] = pkg['qml_source'] + checked = subprocess.run([str(payload/'bin/mission-core-vesc-qml-preview')], input=json.dumps(candidate).encode(),env=qenv,capture_output=True,timeout=8) + (root/('qml-official-'+label+'.stdout')).write_bytes(checked.stdout) + result = json.loads(checked.stdout) + if not result.get('ok') or result.get('hardware_access') is not False or not result.get('sandbox_verified'): + raise RuntimeError('Official QML preview failed: '+label+' '+str(result)) + if label == 'LogUI': + from qml_build import bright_pixels + if bright_pixels(base64.b64decode(result['png']), (10, 200, 124, 295)) < 100: + raise RuntimeError('Original LogUI left labels are absent from the rendered image') + report['checks'].append({'id':'qml-official-'+label,'ok':True,'source_sha256':result['source_sha256'],'warnings':result['warnings'],'hardware_access':False}) + candidate['source'] = 'import QtQuick 2.5; Item { Component.onCompleted: {while(true){}} }' + checked = subprocess.run([str(payload/'bin/mission-core-vesc-qml-preview')], input=json.dumps(candidate).encode(),env=qenv,capture_output=True,timeout=6) + if checked.returncode != -9:raise RuntimeError('Infinite QML did not stop at CPU limit') + report['checks'].append({'id':'qml-infinite-loop-terminated','ok':True,'hardware_access':False}) report["native_runtime"] = json.loads((root / "runtime/bundle.json").read_text()) report.update(state="complete", binary=str(target), upstream_objects_unchanged=True) except Exception as error: @@ -180,6 +345,7 @@ def main(): parser.add_argument("--artifact", type=Path, required=True) parser.add_argument("--upstream-report", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--qml-dependency-cache", type=Path) parser.add_argument("--archives", type=Path, nargs="+", required=True) run(parser.parse_args()) diff --git a/plugins/vesc/packaging/native_samples_check.py b/plugins/vesc/packaging/native_samples_check.py new file mode 100644 index 00000000..c49f2c96 --- /dev/null +++ b/plugins/vesc/packaging/native_samples_check.py @@ -0,0 +1,191 @@ +"""Disconnected qualification of Sample Data and persistent Qt input.""" + +import base64 +import copy +import json +import select +import struct +import subprocess +import time + + +def samples(execute, target, archive, report): + def packet(third=False, indexed=False): + values = [1.25, -0.25] + ([-0.75] if third else []) + [12.0, 13.0, 14.0, 15.0, 2.0, 20000.0] + return ( + (struct.pack(">h", 7) if indexed else b"") + + struct.pack(">" + str(len(values)) + "f", *values) + + bytes([5 | (3 << 3), 125]) + + (struct.pack(">i", 7) if indexed else b"") + ) + + for label, raw in [ + ("legacy", packet()), + ("third-current", packet(True)), + ("indexed", packet(True, True)), + ]: + candidate = copy.deepcopy(archive) + candidate["sample_test"] = { + "packet": base64.b64encode(raw).decode(), + "decimation": 4, + "packets": [base64.b64encode(packet()).decode()] * 2, + } + v = json.loads(execute("samples-" + label, [str(target)], json.dumps(candidate).encode())) + s = v["sample"] + assert ( + s["i1"] == 1.25 + and s["i3"] == (-1.0 if label == "legacy" else -0.75) + and s["hall"] == 3 + and s["phase_deg"] == 180 + and s["dt_s"] == 0.0002 + ) + assert s["index"] == (7 if label == "indexed" else 0) + assert v["sample_state"]["state"] == "complete" and len(v["sample_state"]["rows"]) == 2 + assert all(base64.b64decode(p)[0] == 19 for p in v["sample_commands"]) + assert base64.b64decode(v["sample_commands"][0]) == bytes([19, 1, 0, 2, 3, 0]) + report["checks"].append({"id": "samples-" + label, "ok": True, "hardware_access": False}) + for label, raw in [ + ("truncated", packet()[:-1]), + ("bad-frequency", packet()[:-6] + struct.pack(">f", 0) + packet()[-2:]), + ("index-mismatch", packet(True, True)[:-4] + struct.pack(">i", 8)), + ]: + candidate = copy.deepcopy(archive) + candidate["sample_test"] = {"packet": base64.b64encode(raw).decode()} + v = json.loads( + execute( + "samples-reject-" + label, [str(target)], json.dumps(candidate).encode(), expected=1 + ) + ) + assert v["ok"] is False + report["checks"].append( + {"id": "samples-reject-" + label, "ok": True, "hardware_access": False} + ) + candidate = copy.deepcopy(archive) + candidate["sample_test"] = { + "packets": [base64.b64encode(packet()).decode(), base64.b64encode(b"bad").decode()] + } + v = json.loads(execute("samples-incomplete", [str(target)], json.dumps(candidate).encode())) + assert ( + v["sample_state"]["state"] == "incomplete" + and v["sample_state"]["received"] == 1 + and v["sample_state"]["malformed"] == 1 + ) + assert base64.b64decode(v["sample_commands"][-1]) == bytes([19, 0, 0, 0, 1, 0]) + report["checks"].append( + { + "id": "samples-incomplete-stops-without-motor-command", + "ok": True, + "hardware_access": False, + } + ) + candidate = copy.deepcopy(archive) + candidate["sample_test"] = {"mode": 4, "wait_timeout": True} + v = json.loads(execute("samples-timeout", [str(target)], json.dumps(candidate).encode())) + assert v["sample_state"]["state"] == "timeout" and v["sample_state"]["received"] == 0 + assert base64.b64decode(v["sample_commands"][-1]) == bytes([19, 0, 0, 0, 1, 0]) + report["checks"].append( + {"id": "samples-timer-stops-untriggered-capture", "ok": True, "hardware_access": False} + ) + + +def interactive(binary, env, report, root): + source = """import QtQuick 2.5 +Rectangle { property int count: 0; + color: count === 0 ? "#112233" : count === 1 ? "#224466" : "#336699" + Rectangle { x:20; y:20; width:120; height:50; color:"#ffffff" + MouseArea { anchors.fill: parent; + onClicked: { parent.parent.count++; VescIf.commands().setRpm(123); } } } + TextInput { x:20; y:90; width:400; height:40; font.pixelSize:24; + color:"#ffffff"; cursorDelegate: Item {} } +}""" + process = subprocess.Popen( + [str(binary)], + env=env, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + bufsize=0, + ) + buffer = b"" + + def call(request): + nonlocal buffer + process.stdin.write(json.dumps(request).encode() + b"\n") + process.stdin.flush() + deadline = time.monotonic() + 7 + while b"\n" not in buffer: + if not select.select([process.stdout], [], [], max(0, deadline - time.monotonic()))[0]: + raise RuntimeError("Interactive QML timeout") + import os + + chunk = os.read(process.stdout.fileno(), 65536) + if not chunk: + raise RuntimeError( + "Interactive QML exited " + process.stderr.read().decode(errors="replace") + ) + buffer += chunk + if len(buffer) > 800 * 1024: + raise RuntimeError("QML response bound") + line, buffer = buffer.split(b"\n", 1) + v = json.loads(line) + assert ( + v["ok"] and v["interactive"] and v["hardware_access"] is False and v["sandbox_verified"] + ) + return v + + def click(x, y): + return [{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}] + + try: + first = call( + {"source": source, "standalone": True, "interactive": True, "width": 640, "height": 480} + ) + second = call({"op": "frame", "events": click(50, 40)}) + third = call({"op": "frame", "events": click(50, 40)}) + fourth = call({"op": "frame", "events": []}) + assert ( + len({v["png"] for v in (first, second, third)}) == 3 and third["png"] == fourth["png"] + ) + assert third["discarded_commands"] >= 2 + blank = call({"op": "frame", "events": click(40, 100)}) + typed = call({"op": "frame", "events": [{"kind": "text", "text": "Synthetic input"}]}) + erased = call( + { + "op": "frame", + "events": [ + {"kind": "key", "key": "SelectAll"}, + {"kind": "key", "key": "Backspace"}, + ], + } + ) + assert blank["png"] != typed["png"] and erased["png"] == blank["png"] + (root / "qml-interactive.stdout").write_text( + json.dumps( + { + "frames": 7, + "clicks_change_state": True, + "state_survives_frames": True, + "text_input_and_selection": True, + "discarded_commands": third["discarded_commands"], + "hardware_access": False, + } + ) + ) + (root / "qml-interactive.png").write_bytes(base64.b64decode(typed["png"])) + process.stdin.write(b'{"op":"close"}\n') + process.stdin.flush() + process.wait(timeout=3) + assert process.returncode == 0 + report["checks"].append( + { + "id": "qml-interactive-click-key-text-state-close", + "ok": True, + "hardware_access": False, + } + ) + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=3) + for stream in (process.stdin, process.stdout, process.stderr): + stream.close() diff --git a/plugins/vesc/packaging/package-catalog.json b/plugins/vesc/packaging/package-catalog.json new file mode 100644 index 00000000..f064762e --- /dev/null +++ b/plugins/vesc/packaging/package-catalog.json @@ -0,0 +1,9 @@ +{ + "schema": "missioncore.vesc.package-catalog/v1", + "source": "http://home.vedder.se/vesc_pkg/vesc_pkg_all.rcc", + "source_repository": "https://github.com/vedderb/vesc_pkg", + "observed_at": "2026-10-18", + "sha256": "47f75c9f4ed650c58acf4d8cd44c800968735c12f47e1de5d3f6003bdd52f40c", + "bytes": 947043, + "items": 41 +} diff --git a/plugins/vesc/packaging/payload.py b/plugins/vesc/packaging/payload.py index c5894750..b545812f 100644 --- a/plugins/vesc/packaging/payload.py +++ b/plugins/vesc/packaging/payload.py @@ -11,6 +11,12 @@ def payload(): for p in sorted((root / "runtime").glob("*.py"))] files.extend(("usr/lib/mission-core-vesc/runtime/" + str(p.relative_to(root / "runtime")), p.read_bytes(), 0o644) for p in sorted((root / "runtime/schemas").rglob("*")) if p.is_file()) + files.append(("usr/lib/mission-core-vesc/runtime/diagnostic_options.py", + (root.parents[1] / "packages/plugin-sdk/python/missioncore_plugin_sdk/diagnostic_options.py").read_bytes(), 0o644)) + files.append(("usr/lib/mission-core-vesc/runtime/bounded_diagnostics.py", + (root.parents[1] / "packages/plugin-sdk/python/missioncore_plugin_sdk/bounded_diagnostics.py").read_bytes(), 0o644)) + files.append(("usr/lib/mission-core-vesc/runtime/maintenance.py", + (root.parents[1] / "packages/plugin-sdk/python/missioncore_plugin_sdk/maintenance.py").read_bytes(), 0o644)) files.append(("usr/lib/mission-core-vesc/runtime/archive.py", (root.parents[1] / "src/k1link/device_plugins/vesc/archive.py").read_bytes(), 0o644)) for name in ("mission-core-vesc.service", "mission-core-node-vesc-prepare.service"): @@ -20,6 +26,15 @@ def payload(): files.append(("usr/share/mission-core-node/profiles/vesc/70-mission-core-vesc.rules", (root / "packaging/70-mission-core-vesc.rules").read_bytes(), 0o644)) manifest = json.loads((root / "packaging/native-runtime.json").read_text()) + # Refuse to ship a stale native binary after changing the reviewed source pin. + import sys + sys.path.insert(0, str(root / "packaging")) + from engine_profile import load_profile, contract + profile = load_profile() + if (manifest.get("engine_contract") != contract(profile) + or manifest.get("upstream_commit") != profile["upstream"]["commit"] + or manifest.get("upstream_version") != profile["upstream"]["version"]): + raise ValueError("Requalify native engine after changing its release profile") bundle = root / "build/native-runtime" / manifest["file"] data = bundle.read_bytes() if len(data) != manifest["bytes"] or hashlib.sha256(data).hexdigest() != manifest["sha256"]: @@ -46,4 +61,24 @@ def payload(): (root / "packaging/native-runtime.json").read_bytes(), 0o644)) files.append(("usr/lib/mission-core-vesc/native_check.py", (root / "packaging/native_check.py").read_bytes(), 0o644)) + catalog = json.loads((root / "packaging/firmware-catalog.json").read_text()) + if len(catalog["items"]) > 512 or sum(i["bytes"] for i in catalog["items"]) > 64 * 1024**2: + raise ValueError("Firmware catalog exceeds payload bounds") + blobs = {} + for item in catalog["items"]: + digest = item["sha256"] + if len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest): + raise ValueError("Invalid firmware digest") + content = (root / "build/firmware-catalog" / (digest + ".bin")).read_bytes() + if len(content) != item["bytes"] or hashlib.sha256(content).hexdigest() != digest: + raise ValueError("Pinned firmware catalog changed") + blobs[digest] = content + files.extend(("usr/lib/mission-core-vesc/firmware-catalog/" + digest + ".bin", data, 0o644) for digest,data in blobs.items()) + files.append(("usr/lib/mission-core-vesc/firmware-catalog/catalog.json", (root / "packaging/firmware-catalog.json").read_bytes(), 0o644)) + files.append(("usr/lib/mission-core-vesc/firmware-catalog/NOTICE", (root / "packaging/firmware-catalog.NOTICE").read_bytes(), 0o644)) + package_catalog = json.loads((root / "packaging/package-catalog.json").read_text()) + data = (root / "build/package-catalog/vesc_pkg_all.rcc").read_bytes() + if len(data) != package_catalog["bytes"] or hashlib.sha256(data).hexdigest() != package_catalog["sha256"]:raise ValueError("Pinned extension catalogue changed") + files.append(("usr/lib/mission-core-vesc/package-catalog/vesc_pkg_all.rcc",data,0o644)) + files.append(("usr/lib/mission-core-vesc/package-catalog/catalog.json",(root / "packaging/package-catalog.json").read_bytes(),0o644)) return files diff --git a/plugins/vesc/packaging/prepare.py b/plugins/vesc/packaging/prepare.py index ebae1002..7410211d 100644 --- a/plugins/vesc/packaging/prepare.py +++ b/plugins/vesc/packaging/prepare.py @@ -32,7 +32,7 @@ def prepare(): lock = os.open(STATE / "prepare.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) report = {"schema": "missioncore.node.device-preparation/v1", "model_id": "vesc.controller", - "version": "0.7.4", "run_id": uuid.uuid4().hex, "started_at": time.time(), + "version": "0.20.11", "run_id": uuid.uuid4().hex, "started_at": time.time(), "monotonic_started": time.monotonic(), "state": "running", "steps": []} def publish(): diff --git a/plugins/vesc/packaging/qml_build.py b/plugins/vesc/packaging/qml_build.py new file mode 100644 index 00000000..9af30f74 --- /dev/null +++ b/plugins/vesc/packaging/qml_build.py @@ -0,0 +1,167 @@ +"""Private signed Ubuntu QML dependencies and offline renderer qualification.""" + +import hashlib +import json +import shutil +import subprocess +from pathlib import Path + +PACKAGES = ( + "qml-module-qtquick2", + "qml-module-qtquick-controls2", + "qml-module-qtquick-templates2", + "qml-module-qtquick-controls", + "qml-module-qtquick-layouts", + "qml-module-qtquick-window2", + "qml-module-qtgraphicaleffects", + "qml-module-qtqml", + "qml-module-qtqml-models2", + "fonts-dejavu-core", +) + + +def dependencies(root, execute, cache=None): + target = root / "qml-deps" + target.mkdir() + downloads = target / "packages" + downloads.mkdir() + if cache is not None: + records = json.loads((cache / "packages.json").read_text()) + if len(records) != len(PACKAGES) or {p["file"].split("_")[0] for p in records} != set( + PACKAGES + ): + raise RuntimeError("Invalid QML dependency cache") + sysroot = target / "sysroot" + sysroot.mkdir() + for record in records: + name = record["file"] + if Path(name).name != name or not name.endswith(".deb"): + raise RuntimeError("Invalid cached package path") + path = cache / "packages" / name + if hashlib.sha256(path.read_bytes()).hexdigest() != record["sha256"]: + raise RuntimeError("Changed QML cache archive") + shutil.copyfile(path, downloads / name) + subprocess.run( + ["/usr/bin/dpkg-deb", "--extract", str(downloads / name), str(sysroot)], + check=True, + timeout=30, + ) + (target / "packages.json").write_text(json.dumps(records, indent=2) + "\n") + return sysroot + apt = target / "apt" + apt.mkdir() + for name in ("lists", "lists/partial", "archives", "archives/partial"): + (apt / name).mkdir() + sources = apt / "sources.list" + sources.write_text( + "".join( + "deb [signed-by=/usr/share/keyrings/ubuntu-archive-keyring.gpg] " + + url + + " " + + suite + + " main universe\n" + for url, suite in ( + ("https://archive.ubuntu.com/ubuntu", "noble"), + ("https://archive.ubuntu.com/ubuntu", "noble-updates"), + ("https://security.ubuntu.com/ubuntu", "noble-security"), + ) + ) + ) + config = apt / "apt.conf" + config.write_text( + 'Dir::Etc::Parts "-";\nDir::Etc::main "-";\nDir::Etc::sourceparts "-";\n' + f'Dir::Etc::sourcelist "{sources}";\n' + f'Dir::State::lists "{apt / "lists"}";\n' + f'Dir::Cache::archives "{apt / "archives"}";\n' + 'Dir::Cache::pkgcache "";\nDir::Cache::srcpkgcache "";\n' + 'Acquire::Languages "none";\nDebug::NoLocking "true";\n' + "#clear APT::Update::Post-Invoke;\n#clear APT::Update::Post-Invoke-Success;\n" + ) + # Execute accepts an argv, never a shell. Only the task's private APT paths change. + execute( + "qml-private-indexes", + ["/usr/bin/env", "APT_CONFIG=" + str(config), "/usr/bin/apt-get", "update"], + timeout=180, + ) + for name in PACKAGES: + execute( + "qml-download-" + name, + [ + "/usr/bin/env", + "-C", + str(downloads), + "APT_CONFIG=" + str(config), + "/usr/bin/apt-get", + "download", + name, + ], + timeout=90, + ) + sysroot = target / "sysroot" + sysroot.mkdir() + packages = [] + for p in sorted(downloads.glob("*.deb")): + packages.append({"file": p.name, "sha256": hashlib.sha256(p.read_bytes()).hexdigest()}) + subprocess.run( + ["/usr/bin/dpkg-deb", "--extract", str(p), str(sysroot)], check=True, timeout=30 + ) + if len(packages) != len(PACKAGES): + raise RuntimeError("QML package inventory incomplete") + (target / "packages.json").write_text(json.dumps(packages, indent=2) + "\n") + return sysroot + + +def bright_pixels(png, rectangle): + """Count visible light glyph pixels in a fixed native-render regression region.""" + import struct + import zlib + + if png[:8] != b"\x89PNG\r\n\x1a\n": + raise ValueError("Invalid QML test image") + cursor, data, shape = 8, bytearray(), None + while cursor < len(png): + length = struct.unpack_from(">I", png, cursor)[0] + tag, value = png[cursor + 4 : cursor + 8], png[cursor + 8 : cursor + 8 + length] + if tag == b"IHDR": + shape = struct.unpack(">IIBBBBB", value) + if tag == b"IDAT": + data.extend(value) + cursor += length + 12 + width, height, depth, colour, compression, filtering, interlace = shape + if depth != 8 or colour not in (2, 6) or compression or filtering or interlace: + raise ValueError("Unsupported native QML test image encoding") + channels = 4 if colour == 6 else 3 + stride = width * channels + raw = zlib.decompress(data) + if len(raw) != height * (stride + 1): + raise ValueError("Invalid native QML image size") + prior, count = bytearray(stride), 0 + x0, y0, x1, y1 = rectangle + for y in range(height): + at = y * (stride + 1) + mode, row = raw[at], bytearray(raw[at + 1 : at + 1 + stride]) + for i in range(stride): + left = row[i - channels] if i >= channels else 0 + up = prior[i] + corner = prior[i - channels] if i >= channels else 0 + if mode == 0: + prediction = 0 + elif mode == 1: + prediction = left + elif mode == 2: + prediction = up + elif mode == 3: + prediction = (left + up) // 2 + elif mode == 4: + p = left + up - corner + prediction = min((left, up, corner), key=lambda value: abs(p - value)) + else: + raise ValueError("Invalid PNG filter") + row[i] = (row[i] + prediction) & 255 + if y0 <= y < y1: + for x in range(x0, min(x1, width)): + pixel = row[x * channels : (x + 1) * channels] + if min(pixel[:3]) > 180 and (channels == 3 or pixel[3] > 200): + count += 1 + prior = row + return count diff --git a/plugins/vesc/packaging/tool_build.py b/plugins/vesc/packaging/tool_build.py index 9b2f740b..1da29124 100644 --- a/plugins/vesc/packaging/tool_build.py +++ b/plugins/vesc/packaging/tool_build.py @@ -18,8 +18,10 @@ import tarfile import time from datetime import datetime, timezone -COMMIT = "01d5f10901116c311e3fb84d5a1541f663d3ce20" -ARCHIVE_SHA256 = "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189" +from engine_profile import load_profile +PROFILE = load_profile() +COMMIT = PROFILE["upstream"]["commit"] +ARCHIVE_SHA256 = PROFILE["upstream"]["source_sha256"] DEPS = ( "qtbase5-dev", "qtbase5-private-dev", "qtdeclarative5-dev", "qtquickcontrols2-5-dev", "libqt5serialport5-dev", "qtconnectivity5-dev", @@ -165,7 +167,7 @@ def build(archive, root, dependency_cache=None, resume=None): "VT_GIT_COMMIT=" + COMMIT[:8], "INCLUDEPATH += " + str(qtbase / "include") + " " + str(qtbase / "include/x86_64-linux-gnu"), "QMAKE_LIBDIR += " + str(qtbase / "lib/x86_64-linux-gnu")], source) run("compile", ["/usr/bin/make", "-j2"], source, timeout=1800) - binary = source / "build/lin/vesc_tool_7.00" + binary = source / ("build/lin/vesc_tool_" + PROFILE["upstream"]["version"]) result = run("version", [str(binary), "--version"], source, timeout=30) report.update(state="complete", binary=str(binary), binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(), version_output=result, runtime_installed=False, hardware_qualified=False) diff --git a/plugins/vesc/runtime/__init__.py b/plugins/vesc/runtime/__init__.py index 5cf80798..a85e49b0 100644 --- a/plugins/vesc/runtime/__init__.py +++ b/plugins/vesc/runtime/__init__.py @@ -1,5 +1,5 @@ """Onboard VESC discovery, archive and bounded motor identification service.""" -VERSION = "0.7.4" +VERSION = "0.20.11" MODEL = "vesc.controller" SCHEMA = "missioncore.nodedc/plugin-sdk/v0alpha2" diff --git a/plugins/vesc/runtime/bms.py b/plugins/vesc/runtime/bms.py new file mode 100644 index 00000000..5e62b663 --- /dev/null +++ b/plugins/vesc/runtime/bms.py @@ -0,0 +1,85 @@ +"""Explicit CAN BMS operations; never use the VESC's implicitly selected proxy. + +Upstream BMS control has no ACK. Durable intent and consumed previews prevent +replay; a sent command is not represented as an applied setting. +""" +from collections import OrderedDict +import math +import re +import time +import uuid + +from .motor_test import Rejected + +PREFIX='vesc.bms.' +ACTIONS=frozenset(PREFIX+n for n in ('read','prepare','apply')) +COMMANDS=frozenset(('charge_enable','charge_disable','balance_enable','balance_disable','reset_ah','reset_wh','zero_current')) + + +def validate(action,p): + name=action.removeprefix(PREFIX) + if name in ('read','prepare'): + if set(p)!=({'can_id','command'} if name=='prepare' else {'can_id'}) or type(p.get('can_id')) is not int or not 0<=p['can_id']<=253: + raise ValueError('Exact unicast CAN address required') + if name=='prepare' and p['command'] not in COMMANDS:raise ValueError('Unknown BMS command') + elif name=='apply': + if set(p)!={'preview_id','confirmed','inputs_isolated'} or p['confirmed'] is not True or p['inputs_isolated'] is not True or not isinstance(p['preview_id'],str) or not re.fullmatch(r'bms_[0-9a-f]{32}',p['preview_id']): + raise ValueError('Fresh BMS preview and explicit confirmation required') + else:raise ValueError('Unknown BMS operation') + + +class BmsControl: + def __init__(self,service,atomic,utc,clock=time.monotonic): + self.service,self.atomic,self.utc,self.clock=service,atomic,utc,clock + self.plans=OrderedDict() + + def read(self,device,can_id): + result=device.link.bms_read(can_id) + if result.get('state')=='received': + target=result.get('target',{});values=result.get('values',{}) + if target.get('can_id')!=can_id or not re.fullmatch(r'[0-9a-f]{24}',target.get('uuid','')): + raise ValueError('Invalid BMS target') + if target.get('hardware_type')==1 and (not isinstance(values.get('v_cells'),list) or not 1<=len(values['v_cells'])<=96): + raise Rejected('BMS ответила без напряжений ячеек. Управление недоступно.') + return {**result,'observed_at':self.utc()} + + def prepare(self,device,p): + value=self.read(device,p['can_id']) + if value.get('state')!='received' or value.get('commands_supported') is not True: + raise Rejected('Адресная BMS с поддерживаемой прошивкой не подтверждена.') + self.plans=OrderedDict((k,v) for k,v in self.plans.items() if self.clock()-v['at']<60) + while len(self.plans)>=4:self.plans.popitem(last=False) + identifier='bms_'+uuid.uuid4().hex + plan={'at':self.clock(),'device_id':device.id,'session':device.session,'identity':dict(device.identity), + 'target':value['target'],'command':p['command']} + self.plans[identifier]=plan + return {'preview_id':identifier,'expires_in_s':60,'target':plan['target'],'command':p['command']} + + def apply(self,device,p,operation): + plan=self.plans.get(p['preview_id']) + if not plan or self.clock()-plan['at']>=60 or plan['device_id']!=device.id or plan['session']!=device.session or plan['identity']!=device.identity: + raise Rejected('Подтверждение BMS истекло или сеанс изменился. Подготовьте команду заново.') + if self.service.config_editor.pending(device) or self.service.firmware_update.pending(device): + raise Rejected('Сначала подтвердите результат предыдущего изменения VESC.') + self.service.config_editor.idle(device,self.service.config_editor.read(device)) + fresh=self.read(device,plan['target']['can_id']) + if fresh.get('state')!='received' or fresh.get('target')!=plan['target'] or fresh.get('commands_supported') is not True: + raise Rejected('BMS изменилась после подтверждения. Команда отменена.') + if plan['command']=='zero_current': + readings=[fresh.get('values',{}).get(k) for k in ('i_in','i_in_ic')] + if any(type(v) not in (int,float) or not math.isfinite(v) or abs(v)>0.1 for v in readings): + raise Rejected('Для калибровки нуля отключите зарядку и нагрузку: оба тока должны быть меньше 0,1 А.') + record={'schema':'missioncore.vesc.bms-command/v1','operation_id':operation,'target':plan['target'], + 'command':plan['command'],'state':'unknown','acknowledged':False,'started_at':self.utc()} + path=self.service.root/('bms-command-'+operation+'.json') + self.atomic(path,record) + self.plans.pop(p['preview_id']) + try: + result=device.link.bms_command(plan['target'],plan['command']) + if result.get('sent') is not True:raise OSError('BMS command was not emitted') + record['state']='sent_unconfirmed' + except (OSError,ValueError,TimeoutError) as error: + record['error']=str(error)[:512] + record['finished_at']=self.utc() + self.atomic(path,record) + return record diff --git a/plugins/vesc/runtime/bms_configuration.py b/plugins/vesc/runtime/bms_configuration.py new file mode 100644 index 00000000..9251c340 --- /dev/null +++ b/plugins/vesc/runtime/bms_configuration.py @@ -0,0 +1,153 @@ +"""Schema-driven BMS configuration, UUID-bound preview and durable readback barrier.""" +from collections import OrderedDict +import base64 +import hashlib +import json +import re +import time +import uuid +from .motor_test import Rejected + +PREFIX = 'vesc.bms.configuration.' +ACTIONS = frozenset(PREFIX+n for n in ('read', 'preview', 'apply', 'reconcile', 'restore')) +READS = ACTIONS - {PREFIX+'apply'} +HASH = re.compile(r'[0-9a-f]{64}') + + +def validate(action, p): + name = action.removeprefix(PREFIX) + if name == 'apply': + if (set(p) != {'preview_id', 'confirmed', 'inputs_isolated'} or p['confirmed'] is not True + or p['inputs_isolated'] is not True or not isinstance(p['preview_id'], str) + or not re.fullmatch(r'bcfg_[0-9a-f]{32}', p['preview_id'])): + raise ValueError('Explicit BMS configuration preview confirmation required') + return + if type(p.get('can_id')) is not int or not 0 <= p['can_id'] <= 253 or type(p.get('index')) is not int or not 0 <= p['index'] < 8: + raise ValueError('Unicast CAN address and configuration index required') + base = {'can_id', 'index'} + if name in ('read', 'reconcile', 'restore'): + if set(p) != base: raise ValueError('Unsupported BMS configuration request') + elif name == 'preview': + choices = set(p) - base - {'baseline', 'schema_sha256'} + if len(choices) != 1 or not choices <= {'changes', 'xml', 'defaults'}: + raise ValueError('One configuration source required') + if any(not isinstance(p.get(k), str) or not HASH.fullmatch(p[k]) for k in ('baseline', 'schema_sha256')): + raise ValueError('Exact baseline and schema required') + if 'changes' in p and (not isinstance(p['changes'], dict) or not 1 <= len(p['changes']) <= 512): raise ValueError('Invalid edit') + if 'xml' in p and (not isinstance(p['xml'], str) or not 0 < len(p['xml'].encode()) <= 32768): raise ValueError('Invalid XML size') + if 'defaults' in p and p['defaults'] is not True: raise ValueError('Invalid default request') + else: raise ValueError('Unknown BMS configuration operation') + + +def same_target(a, b): + return {k:v for k,v in a.items() if k != 'can_id'} == {k:v for k,v in b.items() if k != 'can_id'} + + +class BmsConfiguration: + def __init__(self, service, atomic, utc, clock=time.monotonic): + self.service, self.atomic, self.utc, self.clock = service, atomic, utc, clock + self.plans = OrderedDict() + + def path(self, device): + return self.service.root / ('bms-configuration-pending-' + (device if isinstance(device, str) else device.id) + '.json') + + def pending(self, device): + path = self.path(device) + return json.loads(path.read_text()) if path.exists() else None + + def read(self, device, p): + value = device.link.rpc('custom_read', timeout=28, **p) + raw = base64.b64decode(value['payload'], validate=True) + if (value['index'] != p['index'] or value['target']['can_id'] != p['can_id'] + or hashlib.sha256(raw).hexdigest() != value['configuration']['packet_sha256']): + raise ValueError('BMS snapshot identity or content mismatch') + return value + + def preview(self, device, p, recovery=False): + pending = self.pending(device) + if pending and not recovery: + raise Rejected('Сначала проверьте предыдущую запись BMS или восстановите исходную копию.') + args = dict(p) + if recovery: + if not pending: raise Rejected('Нет незавершённой записи BMS.') + current = self.read(device, p) + if (pending['identity'] != device.identity or not same_target(pending['before']['target'], current['target']) + or pending['before']['index'] != p['index'] or pending['before']['schema_sha256'] != current['schema_sha256']): + raise Rejected('Исходная копия относится к другой BMS, прошивке или схеме.') + args.update(baseline=current['configuration']['packet_sha256'], schema_sha256=current['schema_sha256'], source={'payload':pending['before']['payload']}) + else: + args['source'] = {k:args.pop(k) for k in ('changes', 'xml') if k in args} + value = device.link.rpc('custom_preview', timeout=30, **args) + now = self.clock() + self.plans = OrderedDict((k,v) for k,v in self.plans.items() if now-v['at'] < 300) + while len(self.plans) >= 4: self.plans.popitem(last=False) + key = 'bcfg_' + uuid.uuid4().hex + self.plans[key] = {'at':now, 'identity':dict(device.identity), 'session':device.session, 'device_id':device.id, + 'value':value, 'recovery':recovery} + return {'preview_id':key, 'expires_in_s':300, 'target':value['target'], 'changes':value['candidate']['changes']} + + def apply(self, device, p, operation, deadline): + from datetime import datetime, timezone + plan = self.plans.get(p['preview_id']) + if (not plan or self.clock()-plan['at'] >= 300 or plan['identity'] != device.identity + or plan['session'] != device.session or plan['device_id'] != device.id): + raise Rejected('Сравнение BMS истекло или изменился сеанс.') + if self.pending(device) and not plan['recovery']: raise Rejected('Предыдущая запись BMS не подтверждена.') + if self.service.config_editor.pending(device) or self.service.firmware_update.pending(device): raise Rejected('Сначала подтвердите предыдущее изменение VESC.') + self.service.config_editor.idle(device, self.service.config_editor.read(device)) + # Confirm battery load independently of the USB gateway's idle motor. + battery = self.service.bms.read(device, plan['value']['target']['can_id']) + if battery.get('target') != plan['value']['target'] or battery.get('state') != 'received': raise Rejected('BMS изменилась после сравнения.') + import math + currents = [battery.get('values', {}).get(k) for k in ('i_in','i_in_ic')] + if any(type(v) not in (int,float) or not math.isfinite(v) or abs(v) > .1 for v in currents): raise Rejected('Отключите зарядку и нагрузку BMS перед записью параметров.') + if (deadline-datetime.now(timezone.utc)).total_seconds() < 45: raise Rejected('Недостаточно времени для записи и проверки BMS.') + value = plan['value']; candidate = value['candidate'] + before = self.read(device, {'can_id':value['target']['can_id'], 'index':value['index']}) + if (before['target'] != value['target'] or before['schema_sha256'] != value['schema_sha256'] + or before['configuration']['packet_sha256'] != candidate['before_sha256']): raise Rejected('Параметры или схема BMS изменились после сравнения.') + record = {'schema':'missioncore.vesc.bms-configuration/v1','operation_id':operation, 'identity':device.identity, + 'before':before, 'expected':candidate['after_sha256'], 'started_at':self.utc(), 'state':'unknown'} + self.atomic(self.service.root / ('bms-configuration-backup-'+operation+'.json'), record) + self.atomic(self.path(device), record) + self.plans.pop(p['preview_id']) + self.service.motor.state('rc') + try: + result = device.link.rpc('custom_apply', timeout=42, can_id=value['target']['can_id'], index=value['index'], target=value['target'], + baseline=candidate['before_sha256'], schema_sha256=value['schema_sha256'], after_sha256=candidate['after_sha256'], source={'payload':candidate['payload']}) + if result.get('verified') is not True: raise ValueError('Missing readback') + self.finish(device, record, 'applied') + return {'verified':True, 'outcome':'applied'} + except (ValueError, OSError, TimeoutError) as error: + record['failure_type'] = type(error).__name__; self.atomic(self.path(device),record) + return {'verified':False, 'outcome':'unknown', 'message':'Итог записи неизвестен. Автоповтора нет. Если менялся CAN-адрес, выберите новый адрес и проверьте запись.'} + + def finish(self, device, record, outcome): + self.atomic(self.service.root / ('bms-configuration-result-'+record['operation_id']+'.json'), + {**record,'state':'verified','outcome':outcome,'finished_at':self.utc()}) + self.path(device).unlink() + import os + fd = os.open(self.service.root,os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + + def reconcile(self, device, p): + record = self.pending(device) + if not record: return {'verified':True,'outcome':'no_pending_write'} + current = self.read(device,p);before = record['before'] + if (record['identity'] != device.identity or not same_target(before['target'],current['target']) + or before['index'] != current['index'] or before['schema_sha256'] != current['schema_sha256']): raise Rejected('UUID, прошивка или схема BMS изменились.') + actual = current['configuration']['packet_sha256'] + outcome = 'applied' if actual == record['expected'] else 'unchanged' if actual == before['configuration']['packet_sha256'] else 'different' + if outcome != 'different': self.finish(device,record,outcome) + return {'verified':outcome != 'different', 'outcome':outcome, 'configuration':current['configuration']} + + def execute(self, device, action, p, operation, deadline): + name = action.removeprefix(PREFIX) + if not device.readable: raise Rejected('Бортовой VESC не поддерживает адресную настройку BMS.') + if name == 'read': + value = self.read(device,p) + return {**value,'pending':bool(self.pending(device))} + if name in ('preview','restore'): return self.preview(device,p,name=='restore') + if name == 'apply': return self.apply(device,p,operation,deadline) + return self.reconcile(device,p) diff --git a/plugins/vesc/runtime/can_bridge.py b/plugins/vesc/runtime/can_bridge.py new file mode 100644 index 00000000..2bf55f73 --- /dev/null +++ b/plugins/vesc/runtime/can_bridge.py @@ -0,0 +1,208 @@ +"""Private loopback transport for upstream VESC Tool; never generates motor commands.""" + +import contextlib +import http.client +import json +import select +import socket +import threading +import time +from dataclasses import dataclass + +from .can_protocol import Reassembly, fragment, serial_frame +from .protocol import Decoder +from .serial import device_id + + +@dataclass(frozen=True) +class Attachment: + adapter: str + adapter_session: str + channel: int + target: int + bitrate: int + sender: int + expected_uuid: str + + @property + def binding(self): + return ( + f"can:{self.adapter}:{self.adapter_session}:{self.channel}:" + f"{self.target}:{self.bitrate}:{self.sender}" + ) + + @property + def id(self): + return device_id("uuid:" + self.expected_uuid) + + @property + def usb(self): + return f"CAN{self.channel + 1} · ID {self.target}" + + @property + def address(self): + return self.adapter_session + + @property + def tty(self): + return self.binding + + @property + def speed(self): + return f"{self.bitrate // 1000} кбит/с" + + @property + def route(self): + return { + "kind": "can", + "uuid": self.expected_uuid, + "adapter_id": self.adapter, + "channel": self.channel, + "can_id": self.target, + "bitrate": self.bitrate, + } + + +class LocalHTTP(http.client.HTTPConnection): + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(self.timeout) + self.sock.connect("/run/mission-core-usb-can/driver.sock") + + +def inventory(): + c = LocalHTTP("local", timeout=0.5) + try: + c.request("GET", "/bridge-inventory") + r = c.getresponse() + data = json.loads(r.read(196608)) + if r.status != 200: + raise OSError(data.get("error", "CAN inventory unavailable")) + return data["items"] + finally: + c.close() + + +class Bridge: + def __init__(self, attachment): + self.attachment, self.error, self.client = attachment, None, None + self.metrics = {"requests": 0, "responses": 0, "rx_frames": 0, + "last_request": None, "last_response": None, + "send_ms": None, "response_ms": None, + "tx_confirmation": None} + self.sent_at = None + self.stop = threading.Event() + self.token = self.call( + "open", + { + "channel": attachment.channel, + "bitrate": attachment.bitrate, + "receive_id": attachment.sender, + }, + )["token"] + self.listener = socket.socket() + try: + self.listener.bind(("127.0.0.1", 0)) + self.listener.listen(1) + self.port = self.listener.getsockname()[1] + self.thread = threading.Thread(target=self.run, daemon=True, name="vesc-can-bridge") + self.thread.start() + except BaseException: + self.listener.close() + self.call("close", {"token": self.token}) + raise + + def call(self, action, parameters): + c = LocalHTTP("local", timeout=0.6) + try: + body = json.dumps( + { + "adapter": self.attachment.adapter, + "session": self.attachment.adapter_session, + "action": action, + "parameters": parameters, + } + ) + c.request("POST", "/bridge", body, {"Content-Type": "application/json"}) + r = c.getresponse() + data = json.loads(r.read(196608)) + if r.status != 200: + raise OSError(action + ": " + data.get("error", "CAN transport failed")) + return data + finally: + c.close() + + def diagnostics(self): + # Bounded counters and timing only; never retain CAN payloads or samples. + return dict(self.metrics, error=self.error) + + def received(self, frame, rx): + self.metrics["rx_frames"] += 1 + packet = rx.feed(frame) + if packet: + self.metrics["responses"] += 1 + self.metrics["last_response"] = packet[0] + self.metrics["response_ms"] = ( + (time.monotonic() - self.sent_at) * 1000 if self.sent_at else None + ) + if self.client: + self.client.sendall(serial_frame(packet)) + + def run(self): + decoder = Decoder() + rx = Reassembly(self.attachment.target, self.attachment.sender) + try: + while not self.stop.is_set(): + if self.client is None: + if select.select([self.listener], [], [], 0.01)[0]: + self.client, _ = self.listener.accept() + self.client.settimeout(0.2) + self.client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + elif select.select([self.client], [], [], 0.005)[0]: + data = self.client.recv(16384) + if not data: + return + for payload in decoder.feed(data): + if payload == b"\xffMCBR": + # FIFO barrier follows bridge.send completion. Exact + # native setters now wait for their adapter TX echo. + # This is still not a VESC application-level ACK. + self.client.sendall(serial_frame(payload)) + continue + self.sent_at = time.monotonic() + self.metrics["requests"] += 1 + self.metrics["last_request"] = payload[0] + result = self.call( + "send", + { + "token": self.token, + "frames": fragment( + payload, self.attachment.target, self.attachment.sender + ), + "deadline": time.monotonic() + 0.2, + }, + ) + self.metrics["send_ms"] = (time.monotonic() - self.sent_at) * 1000 + self.metrics["tx_confirmation"] = result.get("tx_confirmation") + for frame in result["frames"]: + self.received(frame, rx) + result = self.call("poll", {"token": self.token}) + for frame in result["frames"]: + self.received(frame, rx) + except (OSError, ValueError, KeyError) as error: + self.error = str(error) + finally: + self.stop.set() + if self.client: + self.client.close() + with contextlib.suppress(OSError, ValueError): + self.call("close", {"token": self.token}) + self.listener.close() + + def check(self): + if self.stop.is_set() or not self.thread.is_alive(): + raise OSError(self.error or "CAN connection closed") + + def close(self): + self.stop.set() + self.thread.join(1) diff --git a/plugins/vesc/runtime/can_protocol.py b/plugins/vesc/runtime/can_protocol.py new file mode 100644 index 00000000..47c88cf3 --- /dev/null +++ b/plugins/vesc/runtime/can_protocol.py @@ -0,0 +1,95 @@ +"""VESC CAN fragmentation: upstream comm_can.c, packet IDs 5..8. +Commands themselves remain generated by the pinned upstream VESC Tool. +""" + +import binascii +import time + +MAX_PAYLOAD = 10000 + + +def fragment(payload, target, sender): + if ( + not 1 <= len(payload) <= MAX_PAYLOAD + or not 0 <= target < 255 + or not 0 <= sender < 255 + or target == sender + ): + raise ValueError("Invalid VESC CAN endpoint/payload") + + def f(code, data): + return {"id": (code << 8) | target, "data": data.hex()} + + if len(payload) <= 6: + return [f(8, bytes((sender, 0)) + payload)] + result, offset = [], 0 + while offset < len(payload): + width, size, code = (1, 7, 5) if offset <= 255 else (2, 6, 6) + chunk = payload[offset : offset + size] + result.append(f(code, offset.to_bytes(width, "big") + chunk)) + offset += len(chunk) + result.append( + f( + 7, + bytes((sender, 0)) + + len(payload).to_bytes(2, "big") + + binascii.crc_hqx(payload, 0).to_bytes(2, "big"), + ) + ) + return result + + +def serial_frame(payload): + width = 1 if len(payload) < 256 else 2 + return ( + bytes((width + 1,)) + + len(payload).to_bytes(width, "big") + + payload + + binascii.crc_hqx(payload, 0).to_bytes(2, "big") + + b"\x03" + ) + + +class Reassembly: + def __init__(self, target, sender, clock=time.monotonic): + self.target, self.sender, self.clock = target, sender, clock + self.buffer, self.until = bytearray(), 0 + + def feed(self, frame): + if ( + not frame.get("extended") + or frame.get("fd") + or frame.get("rtr") + or frame.get("error") + or frame["id"] & 255 != self.sender + ): + return None + data, code = bytes.fromhex(frame["data"]), frame["id"] >> 8 + if len(data) > 8: + raise ValueError("Invalid classic CAN frame") + if self.clock() >= self.until: + self.buffer.clear() + if code in (5, 6): + width = 1 if code == 5 else 2 + if len(data) <= width: + raise ValueError("Empty CAN fragment") + offset = int.from_bytes(data[:width], "big") + if offset == 0: + self.buffer.clear() + if offset != len(self.buffer) or offset + len(data) - width > MAX_PAYLOAD: + self.buffer.clear() + raise ValueError("CAN fragment sequence lost") + self.buffer.extend(data[width:]) + self.until = self.clock() + 1 + elif code in (7, 8): + if len(data) < (6 if code == 7 else 3) or data[0] != self.target or data[1] != 1: + return None + payload = bytes(self.buffer) if code == 7 else data[2:] + self.buffer.clear() + if code == 7 and ( + len(payload) != int.from_bytes(data[2:4], "big") + or binascii.crc_hqx(payload, 0) != int.from_bytes(data[4:6], "big") + ): + raise ValueError("CAN response length/CRC mismatch") + return payload + return None diff --git a/plugins/vesc/runtime/code_tools.py b/plugins/vesc/runtime/code_tools.py new file mode 100644 index 00000000..683f5228 --- /dev/null +++ b/plugins/vesc/runtime/code_tools.py @@ -0,0 +1,183 @@ +"""Bounded code projects and explicit programming transactions. No automatic run.""" +from collections import OrderedDict +import base64 +import hashlib +import json +import re +import time +import uuid +from datetime import datetime, timezone +from .motor_test import Rejected + +PREFIX='vesc.code.' +NAMES=('read','begin','chunk','prepare','erase_prepare','apply','reconcile','control_prepare','control_apply','stats','restore') +ACTIONS=frozenset(PREFIX+n for n in NAMES) +READS=ACTIONS-{PREFIX+'apply',PREFIX+'control_apply'} +KINDS={'lisp','qml','qml_hw'} +ID=re.compile(r'code_[0-9a-f]{32}') +HASH=re.compile(r'[0-9a-f]{64}') + + +def validate(action,p): + n=action.removeprefix(PREFIX) + shapes={'read':{'kind'},'begin':{'kind','size','sha256'},'chunk':{'upload_id','offset','data'},'prepare':{'upload_id'}, + 'erase_prepare':{'kind'},'apply':{'preview_id','confirmed','inputs_isolated'},'reconcile':{'kind'}, + 'control_prepare':{'command','text'},'control_apply':{'preview_id','confirmed','inputs_isolated'},'stats':set(),'restore':{'kind'}} + if n not in shapes or set(p)!=shapes[n]:raise ValueError('Invalid code operation parameters') + if 'kind' in p and (p['kind'] not in KINDS or (n not in ('read',) and p['kind']=='qml_hw')):raise ValueError('Invalid writable code kind') + for key in ('upload_id','preview_id'): + if key in p and (not isinstance(p[key],str) or not ID.fullmatch(p[key])):raise ValueError('Invalid code project identity') + if n=='begin' and (type(p['size']) is not int or not 1<=p['size']<=256*1024 or not isinstance(p['sha256'],str) or not HASH.fullmatch(p['sha256'])):raise ValueError('Invalid project size/hash') + if n=='chunk': + if type(p['offset']) is not int or p['offset']<0 or not isinstance(p['data'],str) or not 016384 or base64.b64encode(raw).decode()!=p['data']:raise ValueError('Invalid code fragment encoding') + if n in ('apply','control_apply') and (p['confirmed'] is not True or p['inputs_isolated'] is not True):raise ValueError('Explicit isolated-input confirmation required') + if n=='control_prepare' and (p['command'] not in ('start','stop','repl') or not isinstance(p['text'],str) or len(p['text'].encode())>1024 or '\0' in p['text'] or (p['command']=='repl')!=bool(p['text'])):raise ValueError('Invalid Lisp control') + + +class CodeTools: + def __init__(self,service,atomic,utc,clock=time.monotonic): + self.service,self.atomic,self.utc,self.clock=service,atomic,utc,clock + self.uploads=OrderedDict();self.plans=OrderedDict() + + @staticmethod + def supported(device): + i=device.identity or {} + return i.get('major')==6 and i.get('minor')==0 and i.get('hardware_type')==0 and i.get('test_firmware')==0 + + def path(self,device,kind='pending'): + return self.service.root/('code-'+kind+'-'+(device if isinstance(device,str) else device.id)+'.json') + + def pending(self,device): + path=self.path(device) + return json.loads(path.read_text()) if path.exists() else None + + def blocked(self,device):return self.path(device).exists() or self.path(device,'execution').exists() or (self.service.root/('package-pending-'+device.id+'.json')).exists() + + def identity(self,device):return {'identity':dict(device.identity),'device_id':device.id,'session':device.session} + + def match(self,device,record):return all(record.get(k)==v for k,v in self.identity(device).items()) and self.clock()-record['at']<300 + + def remember(self,store,value): + now=self.clock() + for k,v in list(store.items()): + if now-v['at']>=300:del store[k] + while len(store)>=2:store.popitem(last=False) + key='code_'+uuid.uuid4().hex;store[key]={'at':now,**value};return key + + def clear(self,path): + if not path.exists():return + path.unlink() + import os + fd=os.open(self.service.root,os.O_RDONLY) + try:os.fsync(fd) + finally:os.close(fd) + + def idle(self,device,allow_package=False): + if not allow_package and (self.service.root/("package-pending-"+device.id+".json")).exists():raise Rejected("Сначала проверьте установку расширения.") + if self.service.motor.active or self.service.motor.limits.pending(device):raise Rejected('Завершите управление приводом.') + if self.service.config_editor.pending(device) or self.service.firmware_update.pending(device) or self.service.bms_configuration.pending(device):raise Rejected('Сначала проверьте предыдущее изменение устройства.') + if any((self.service.root/n).exists() for n in ('hall-pending.json','calibration-pending.json')):raise Rejected('Процедура мотора не завершена.') + + def read(self,device,kind):return device.link.rpc('code_read',timeout=30,kind=kind) + + def preview(self,device,kind,image,erase=False,recovery=False): + if self.pending(device) and not recovery:raise Rejected('Сначала проверьте предыдущую запись кода или восстановите копию.') + before=self.read(device,kind) + key=self.remember(self.plans,{**self.identity(device),'kind':kind,'image':image,'erase':erase,'before':before,'recovery':recovery}) + data=base64.b64decode(image) if image else b'' + return {'preview_id':key,'kind':kind,'bytes':len(data),'sha256':hashlib.sha256(data[8:]).hexdigest(), + 'before_sha256':before['sha256'],'erase':erase,'expires_in_s':300,'running_requested':False} + + def execute(self,device,action,p,operation,deadline): + name=action.removeprefix(PREFIX) + if not self.supported(device):raise Rejected('Lisp/QML требуют поддерживаемой прошивки 6.00. Установка ядра Tool не меняет прошивку VESC.') + if name=='read':return {**self.read(device,p['kind']),'pending':bool(self.pending(device)),'execution_pending':self.path(device,'execution').exists()} + if name=='stats':return device.link.rpc('code_stats',timeout=4) + if name=='begin': + key=self.remember(self.uploads,{**self.identity(device),**p,'data':bytearray()}) + return {'upload_id':key,'chunk_bytes':16384} + if name in ('chunk','prepare'): + upload=self.uploads.get(p['upload_id']) + if not upload or not self.match(device,upload):raise Rejected('Передача проекта истекла или изменился контроллер.') + if name=='chunk': + data=base64.b64decode(p['data'],validate=True);offset=p['offset'] + if offsetupload['size']:raise ValueError('Code chunk offset/size mismatch') + upload['data'].extend(data);return {'offset':len(upload['data'])} + raw=bytes(upload['data']) + if len(raw)!=upload['size'] or hashlib.sha256(raw).hexdigest()!=upload['sha256']:raise ValueError('Code project checksum mismatch') + project=json.loads(raw) + if not isinstance(project,dict) or set(project)!={'kind','source','imports','fullscreen'} or project['kind']!=upload['kind'] or not isinstance(project['source'],str) or not isinstance(project['imports'],dict) or type(project['fullscreen']) is not bool:raise ValueError('Invalid code project') + project=self.service.packages.resolve_imports(device,project) + packed=device.link.rpc('code_pack',timeout=8,project=project) + result=self.preview(device,project['kind'],packed['image']);self.uploads.pop(p['upload_id']);return result + if name=='erase_prepare':return self.preview(device,p['kind'],'',True) + if name=='restore': + record=self.pending(device) + if not record or record['identity']!=device.identity or record['kind']!=p['kind']:raise Rejected('Нет исходной копии для этой прошивки и вида кода.') + # Repack the captured project through the upstream codec. Original + # application flags are retained in the saved project. + project=record['before']['project'];packed=device.link.rpc('code_pack',timeout=8,project=project) if project['source'] else {'image':''} + return self.preview(device,p['kind'],packed['image'],not bool(packed['image']),True) + if name=='reconcile':return self.reconcile(device,p['kind']) + if name=='control_prepare': + if p['command']!='stop': self.idle(device) + if self.pending(device) and p['command']!='stop':raise Rejected('Сначала проверьте запись кода.') + before=self.read(device,'lisp') if p['command']!='stop' else {'sha256':None} + key=self.remember(self.plans,{**self.identity(device),**p,'baseline':before['sha256'],'control':True}) + return {'preview_id':key,'command':p['command'],'text':p['text'],'expires_in_s':300} + plan=self.plans.get(p['preview_id']) + if not plan or not self.match(device,plan) or bool(plan.get('control'))!=(name=='control_apply'):raise Rejected('Подтверждение кода истекло или сеанс изменился.') + if name=='control_apply':return self.control(device,p['preview_id'],plan,operation) + return self.apply(device,p['preview_id'],plan,operation,deadline) + + def control(self,device,key,plan,operation): + if plan['command']!='stop': self.idle(device) + if self.pending(device) and plan['command']!='stop':raise Rejected('Сначала проверьте запись кода.') + if plan['command']!='stop' and self.read(device,'lisp')['sha256']!=plan['baseline']:raise Rejected('Lisp изменился после подтверждения.') + record={'schema':'missioncore.vesc.code-execution/v1','identity':device.identity,'operation_id':operation,'command':plan['command'],'state':'unknown','started_at':self.utc()} + self.atomic(self.path(device,'execution'),record);self.plans.pop(key);self.service.motor.state('rc') + try: + result=device.link.rpc('code_control',timeout=8,command=plan['command'],text=plan['text']) + record.update(result,state='acknowledged' if result.get('acknowledged') else 'sent_unconfirmed') + self.atomic(self.service.root/('code-control-result-'+operation+'.json'),record) + if plan['command']=='stop' and result.get('acknowledged'):self.clear(self.path(device,'execution')) + else:self.atomic(self.path(device,'execution'),record) + return record + except (OSError,ValueError,TimeoutError):return {**record,'message':'Итог выполнения неизвестен. Автоповтора нет; остановите Lisp отдельной командой.'} + + def apply(self,device,key,plan,operation,deadline): + self.idle(device) + if self.path(device,"execution").exists():raise Rejected("Остановите Lisp перед записью кода.") + if self.pending(device) and not plan['recovery']:raise Rejected('Предыдущая запись кода не подтверждена.') + if (deadline-datetime.now(timezone.utc)).total_seconds()<100:raise Rejected('Недостаточно времени для записи кода и проверки.') + current=self.read(device,plan['kind']) + if current['sha256']!=plan['before']['sha256'] or current['project']['fullscreen']!=plan['before']['project']['fullscreen']:raise Rejected('Код изменился после сравнения.') + data=base64.b64decode(plan['image']) if plan['image'] else b'' + record={'schema':'missioncore.vesc.code-write/v1','operation_id':operation,'identity':device.identity,'kind':plan['kind'], + 'before':current,'expected_fullscreen':len(data)>7 and data[7]==2,'expected':hashlib.sha256(data[8:]).hexdigest(),'state':'unknown','started_at':self.utc()} + self.atomic(self.service.root/('code-backup-'+operation+'.json'),record);self.atomic(self.path(device),record) + self.plans.pop(key);self.service.motor.state('rc') + try: + result=device.link.rpc('code_write',timeout=100,kind=plan['kind'],image=plan['image'],erase=plan['erase'],baseline=current['sha256'],baseline_fullscreen=current['project']['fullscreen']) + if result.get('verified') is not True:raise ValueError('Missing code readback') + self.finish(device,record,'applied') + if plan['kind']=='lisp':self.clear(self.path(device,'execution')) + return {'verified':True,'outcome':'applied','running_requested':False} + except (OSError,ValueError,TimeoutError) as error: + record['failure_type']=type(error).__name__;self.atomic(self.path(device),record) + return {'verified':False,'outcome':'unknown','message':'Запись могла выполниться частично. Автоповтора нет. Прочитайте результат или восстановите исходную копию.'} + + def finish(self,device,record,outcome): + self.atomic(self.service.root/('code-result-'+record['operation_id']+'.json'),{**record,'state':'verified','outcome':outcome,'finished_at':self.utc()});self.clear(self.path(device)) + + def reconcile(self,device,kind): + record=self.pending(device) + if not record:return {'verified':True,'outcome':'no_pending_write'} + if record['identity']!=device.identity or record['kind']!=kind:raise Rejected('Незавершённая запись относится к другой прошивке или виду кода.') + current=self.read(device,kind) + outcome='applied' if current['sha256']==record['expected'] and current['project']['fullscreen']==record['expected_fullscreen'] else 'unchanged' if current['sha256']==record['before']['sha256'] and current['project']['fullscreen']==record['before']['project']['fullscreen'] else 'different' + if outcome!='different':self.finish(device,record,outcome) + return {'verified':outcome!='different','outcome':outcome} diff --git a/plugins/vesc/runtime/config_editor.py b/plugins/vesc/runtime/config_editor.py new file mode 100644 index 00000000..22114f8a --- /dev/null +++ b/plugins/vesc/runtime/config_editor.py @@ -0,0 +1,214 @@ +"""Session-bound preview -> explicit write -> exact readback, using native codecs. + +No automatic retry or rollback of flash writes. Incomplete transactions leave +an identity-bound interlock that survives a process restart. Reconciliation is +read-only; recovery requires a new preview of the retained pre-write backup. +""" +import base64 +from collections import OrderedDict +import hashlib +import json +import math +import re +import time +import uuid +from datetime import datetime, timezone + +from .configuration import decode +from .motor_test import Rejected +from .protocol import firmware, values, ppm +from .receiver import active, neutral_band +from .release_observation import IDLE_BOUNDS + +ACTIONS = frozenset({'vesc.configuration.preview', 'vesc.configuration.apply', 'vesc.configuration.reconcile'}) +KINDS = {'motor': 14, 'application': 17} +HASH = re.compile(r'[0-9a-f]{64}') +OP = re.compile(r'op_[0-9a-f]{32}') + + +def validate(action, p): + if action == 'vesc.configuration.preview': + if set(p) == {'backup_id'}: + if not isinstance(p['backup_id'], str) or not OP.fullmatch(p['backup_id']): + raise ValueError('Invalid backup ID') + elif set(p) in ({'kind', 'baseline', 'changes'}, {'kind', 'baseline', 'xml'}): + if p['kind'] not in KINDS or not isinstance(p['baseline'], dict) or set(p['baseline']) != set(KINDS): + raise ValueError('Full baseline and configuration kind required') + if any(not isinstance(v, str) or not HASH.fullmatch(v) for v in p['baseline'].values()): + raise ValueError('Invalid baseline hash') + if 'changes' in p and (not isinstance(p['changes'], dict) or not 1 <= len(p['changes']) <= 512): + raise ValueError('Empty or oversized edit') + if 'xml' in p and (not isinstance(p['xml'], str) or not 0 < len(p['xml'].encode()) <= 32768): + raise ValueError('XML import exceeds its bound') + else: + raise ValueError('Unsupported configuration preview') + elif action == 'vesc.configuration.apply': + if (set(p) != {'preview_id', 'rig_clear', 'inputs_isolated'} + or not isinstance(p['preview_id'], str) or not re.fullmatch(r'cfg_[0-9a-f]{32}', p['preview_id']) + or p['rig_clear'] is not True or p['inputs_isolated'] is not True): + raise ValueError('Preview and explicit isolated-input/raised-rig confirmation required') + elif p: + raise ValueError('Reconciliation takes no parameters') + + +def packet_hashes(raw): + return {k: hashlib.sha256(v).hexdigest() for k, v in raw.items()} + + +class ConfigEditor: + def __init__(self, service, atomic, utc, clock=time.monotonic): + self.service, self.atomic, self.utc, self.clock = service, atomic, utc, clock + self.plans = OrderedDict() + + def pending_path(self, device): + return self.service.root / ('configuration-pending-' + (device if isinstance(device, str) else device.id) + '.json') + + def pending(self, device): + path = self.pending_path(device) + return json.loads(path.read_text()) if path.exists() else None + + def read(self, device): + if device.link is None or firmware(device.link.query(0)) != device.identity: + raise Rejected('Контроллер изменился или отключён. Обновите устройства.') + raw = {k: device.link.query(code) for k, code in KINDS.items()} + if firmware(device.link.query(0)) != device.identity: + raise Rejected('Личность контроллера изменилась во время чтения.') + return raw + + def backup(self, device, raw): + op = 'op_' + uuid.uuid4().hex + value = {'schema': 'missioncore.vesc.config-backup/v1', 'identity': device.identity, + 'device_id': device.id, 'observed_at': self.utc(), 'operation_id': op, + 'decoded': False, 'configs': {k: {'encoding': 'base64', 'payload': base64.b64encode(v).decode(), + 'bytes': len(v), 'sha256': hashlib.sha256(v).hexdigest(), 'signature_hex': v[1:5].hex()} + for k, v in raw.items()}} + self.service.archive.add('local', value) + device.backup = {'observed_at': value['observed_at'], 'operation_id': op, + 'configs': {k: {'bytes': v['bytes'], 'sha256': v['sha256']} for k, v in value['configs'].items()}} + return op + + def preview(self, device, p): + pending = self.pending(device) + if pending and p.get('backup_id') != pending['before_backup_id']: + raise Rejected('Итог предыдущей записи не подтверждён. Проверьте его или выберите исходную резервную копию для восстановления.') + if 'backup_id' in p: + backup = self.service.archive.read('local', device.id, p['backup_id']) + if backup['identity'] != device.identity: + raise Rejected('Резервная копия относится к другому контроллеру или прошивке.') + sources = {k: {'payload': v['payload']} for k, v in backup['configs'].items()} + else: + sources = {p['kind']: {k: p[k] for k in ('xml', 'changes') if k in p}} + native = device.link.configuration_preview(sources) + if 'baseline' in p and native['baseline'] != p['baseline']: + raise Rejected('Конфигурация изменилась после чтения. Прочитайте параметры заново.') + if firmware(device.link.query(0)) != device.identity: + raise Rejected('Контроллер изменился во время сравнения.') + now = self.clock() + self.plans = OrderedDict((k, v) for k, v in self.plans.items() if now - v['at'] < 300) + while len(self.plans) >= 4: + self.plans.popitem(last=False) + if len(json.dumps(native).encode()) > 256 * 1024: + raise ValueError('Native preview exceeds bound') + identifier = 'cfg_' + uuid.uuid4().hex + self.plans[identifier] = {'at': now, 'identity': dict(device.identity), 'device_id': device.id, + 'session': device.session, 'native': native, 'recovery': p.get('backup_id')} + return {'preview_id': identifier, 'expires_in_s': 300, 'identity': device.identity, + 'baseline': native['baseline'], 'changes': [{**change, 'kind': k} + for k, v in native['configs'].items() for change in v['changes']]} + + def idle(self, device, raw): + if self.service.motor.active or self.service.motor.limits.pending(device): + raise Rejected('Завершите управление и восстановление временных пределов перед настройкой.') + for name in ('hall-pending.json', 'calibration-pending.json'): + if (self.service.root / name).exists(): + raise Rejected('Предыдущая процедура мотора ещё не завершена.') + app = decode(raw['application'], 'application') + tachometer = None + # Query fresh native values on every round; never admit a cached UI + # sample. Two waits prove a half-second neutral window before any write. + for sample in range(3): + if sample: + time.sleep(.25) + state = values(device.link.query(4)) + if any(not math.isfinite(state[key]) or abs(state[key]) > bound + for key, bound in IDLE_BOUNDS): + raise Rejected('Перед записью требуется остановленный привод без выходной мощности и ошибок.') + count = state['tachometer'] + if not math.isfinite(count) or (tachometer is not None and count != tachometer): + raise Rejected('Привод движется. Дождитесь полной остановки перед записью.') + tachometer = count + if app['app_to_use'] in (1, 4) and active(ppm(device.link.query(31))['level'], neutral_band(app)): + raise Rejected('Приёмник передаёт команду. Отключите входы управления перед записью.') + + def apply(self, device, p, operation, deadline): + if self.service.firmware_update.pending(device): + raise Rejected('Сначала подтвердите результат загрузки прошивки.') + plan = self.plans.get(p['preview_id']) + if (not plan or self.clock() - plan['at'] >= 300 or plan['identity'] != device.identity + or plan['device_id'] != device.id or plan['session'] != device.session): + raise Rejected('Сравнение истекло или сеанс изменился. Подготовьте изменения заново.') + pending = self.pending(device) + if pending and plan['recovery'] != pending['before_backup_id']: + raise Rejected('Требуется проверить предыдущую запись или восстановить её исходную копию.') + before = self.read(device) + if packet_hashes(before) != plan['native']['baseline']: + raise Rejected('Настройки изменились после сравнения. Запись отменена.') + self.idle(device, before) + if (deadline - datetime.now(timezone.utc)).total_seconds() < 25: + raise Rejected('Недостаточно времени для записи и проверки. Повторите предварительное сравнение.') + expected = dict(plan['native']['baseline']) + expected.update({k: v['after_sha256'] for k, v in plan['native']['configs'].items()}) + if expected == packet_hashes(before): + self.plans.pop(p['preview_id']) + return {'outcome': 'unchanged', 'verified': True} + backup_id = self.backup(device, before) + record = {'operation_id': operation, 'identity': device.identity, + 'before_backup_id': backup_id, 'before': packet_hashes(before), 'expected': expected, + 'started_at': self.utc(), 'state': 'unknown'} + self.atomic(self.pending_path(device), record) + self.plans.pop(p['preview_id']) # A consumed plan never grants another write. + self.service.motor.state('rc') # A new explicit control admission is required. + try: + for kind, target in plan['native']['configs'].items(): + if target['before_sha256'] == target['after_sha256']: + continue + device.link.configuration_apply(kind, target) + after = self.read(device) + if packet_hashes(after) != expected: + raise ValueError('Final readback differs from the preview') + after_id = self.backup(device, after) + record.update(state='verified', after_backup_id=after_id, finished_at=self.utc()) + self.atomic(self.service.root / ('configuration-result-' + operation + '.json'), record) + self.clear(device) + device.sample = device.telemetry = None + return {'outcome': 'applied', 'verified': True, 'before_backup_id': backup_id, 'after_backup_id': after_id} + except (OSError, ValueError, TimeoutError) as error: + record['failure_type'] = type(error).__name__ + self.atomic(self.pending_path(device), record) + return {'outcome': 'unknown', 'verified': False, 'before_backup_id': backup_id, + 'message': 'Запись могла выполниться частично. Автоповтора нет. Проверьте итог перед дальнейшим управлением.'} + + def clear(self, device): + import os + self.pending_path(device).unlink() + fd = os.open(self.service.root, os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + + def reconcile(self, device): + pending = self.pending(device) + if not pending: + return {'outcome': 'no_pending_write', 'verified': True} + if pending['identity'] != device.identity: + raise Rejected('Прошивка или личность контроллера отличается от незавершённой записи.') + raw = self.read(device) + actual = packet_hashes(raw) + self.idle(device, raw) + outcome = 'applied' if actual == pending['expected'] else 'unchanged' if actual == pending['before'] else 'different' + if outcome != 'different': + archive = self.backup(device, raw) + self.atomic(self.service.root / ('configuration-result-' + pending['operation_id'] + '.json'), + {**pending, 'state': 'verified', 'outcome': outcome, 'after_backup_id': archive, 'finished_at': self.utc()}) + self.clear(device) + return {'outcome': outcome, 'verified': outcome != 'different', 'before_backup_id': pending['before_backup_id'], + 'message': 'Параметры отличаются и от исходных, и от ожидаемых. Доступно восстановление исходной копии.' if outcome == 'different' else 'Итог подтверждён повторным чтением. Управление включается отдельно.'} diff --git a/plugins/vesc/runtime/configuration.py b/plugins/vesc/runtime/configuration.py index 68ccfabc..d62ef2e4 100644 --- a/plugins/vesc/runtime/configuration.py +++ b/plugins/vesc/runtime/configuration.py @@ -1,8 +1,9 @@ """Exact, read-only firmware configuration decoder. Never serializes a write.""" import math -from pathlib import Path import struct import xml.etree.ElementTree as ET +from functools import lru_cache +from pathlib import Path def crc32c(data): @@ -14,14 +15,25 @@ def crc32c(data): return value ^ 0xffffffff -def decode(data, kind): +@lru_cache(maxsize=2) +def _schema(kind): + """Installed schemas are immutable for the lifetime of this process. + + Parse/sign the definition once, not while accepting a 25 ms input RPC. + Controller bytes and decoded results are never cached. + """ code, name = {"motor": (14, "mcconf"), "application": (17, "appconf")}[kind] xml = ET.parse(Path(__file__).parent / "schemas/5.02" / ("parameters_" + name + ".xml")).getroot() params = {p.tag: p for p in xml.find("Params")} order = [p.text for p in xml.find("SerOrder")] signature = "".join(n + params[n].findtext("type", "0") + params[n].findtext("vTx", "0") + "".join(x.text or "" for x in params[n].findall("enumNames")) for n in order) - if len(data) < 5 or data[0] != code or int.from_bytes(data[1:5], "big") != crc32c(signature.encode()): + return code, params, tuple(order), crc32c(signature.encode()) + + +def decode(data, kind): + code, params, order, signature = _schema(kind) + if len(data) < 5 or data[0] != code or int.from_bytes(data[1:5], "big") != signature: raise ValueError("Configuration signature differs from firmware 5.02 schema") offset, result = 5, {} for name in order: @@ -44,3 +56,9 @@ def decode(data, kind): result[name] = value if offset != len(data): raise ValueError("Unexpected configuration tail") return result + + +# Load before the service starts its input/observation threads. Lazy warming +# in the first arm would leave one avoidable XML/CRC pause in that session. +for _kind in ("motor", "application"): + _schema(_kind) diff --git a/plugins/vesc/runtime/control_transport.py b/plugins/vesc/runtime/control_transport.py new file mode 100644 index 00000000..62ea3954 --- /dev/null +++ b/plugins/vesc/runtime/control_transport.py @@ -0,0 +1,131 @@ +"""Persisted operator transport choices. Pure metadata: no device I/O. + +A route never falls back to another bus. A control session must pin revision, +controller UUID and attachment session before it obtains output authority. +""" + +import copy +import json +import re + +SCHEMA = "missioncore.vesc.control-transport/v1" +BITRATES = (125000, 250000, 500000, 1000000) + + +def validate_routes(routes, drive): + bindings = {b["device_id"]: b["uuid"] for b in drive["bindings"].values()} + if not isinstance(routes, dict) or set(routes) != set(bindings) or not bindings: + raise ValueError("Выберите шину для каждого назначенного мотора.") + channels, addresses = {}, set() + for device, route in routes.items(): + if not isinstance(route, dict) or route.get("kind") not in ("usb", "can"): + raise ValueError("Неизвестная шина управления.") + keys = {"kind", "uuid"} + if route["kind"] == "can": + keys |= {"adapter_id", "channel", "can_id", "bitrate"} + if set(route) != keys or route["uuid"] != bindings[device]: + raise ValueError("Назначение мотора изменилось. Обновите настройки.") + if not re.fullmatch(r"[0-9a-f]{24}", str(route["uuid"])): + raise ValueError("Не подтверждён UUID контроллера.") + if route["kind"] == "can": + if ( + not re.fullmatch(r"usbcan_[0-9a-f]{32}", str(route["adapter_id"])) + or type(route["channel"]) is not int + or route["channel"] not in (0, 1) + or type(route["can_id"]) is not int + or not 0 <= route["can_id"] < 255 + or type(route["bitrate"]) is not int + or route["bitrate"] not in BITRATES + ): + raise ValueError("Проверьте адаптер, канал, CAN ID и скорость.") + channel = (route["adapter_id"], route["channel"]) + address = (*channel, route["can_id"]) + if address in addresses: + raise ValueError("Один CAN-адрес назначен нескольким моторам.") + if channel in channels and channels[channel] != route["bitrate"]: + raise ValueError("На одном CAN-канале нужна одинаковая скорость.") + addresses.add(address) + channels[channel] = route["bitrate"] + return copy.deepcopy(routes) + + +class ControlTransport: + def __init__(self, root, atomic): + self.path, self.atomic = root / "control-transport.json", atomic + self.value = ( + json.loads(self.path.read_text()) + if self.path.exists() + else {"schema": SCHEMA, "revision": 0, "routes": {}} + ) + if ( + self.value.get("schema") != SCHEMA + or type(self.value.get("revision")) is not int + or self.value["revision"] < 0 + or not isinstance(self.value.get("routes"), dict) + ): + raise ValueError("Профиль шины управления повреждён.") + + def snapshot(self, drive, available=None): + # Preserve legacy USB only for a controller never explicitly configured. + # An explicit CAN choice cannot revert to USB after hotplug or restart. + routes = {} + for binding in drive["bindings"].values(): + identifier, uid = binding["device_id"], binding["uuid"] + route = self.value["routes"].get(identifier) + if route is None: + if available is None: + route = {"kind": "usb", "uuid": uid} + else: + candidates = [a["route"] for a in available if a.get("device_id") == identifier + and a.get("uuid") == uid and a.get("verified") is True] + usb = [r for r in candidates if r["kind"] == "usb"] + if len(usb) == 1: route = usb[0] + elif len(candidates) == 1: route = candidates[0] + if route is not None: routes[identifier] = copy.deepcopy(route) + return {**copy.deepcopy(self.value), "routes": routes} + + def update(self, parameters, drive, *, active=False): + if active: + raise ValueError("Остановите удалённое управление перед сменой шины.") + if ( + not isinstance(parameters, dict) + or set(parameters) != {"revision", "drive_revision", "routes"} + or type(parameters["revision"]) is not int + or type(parameters["drive_revision"]) is not int + or parameters["revision"] != self.value["revision"] + or parameters["drive_revision"] != drive["revision"] + ): + raise ValueError("Профиль изменился. Обновите настройки.") + routes = validate_routes(parameters["routes"], drive) + value = {"schema": SCHEMA, "revision": self.value["revision"] + 1, "routes": routes} + self.atomic(self.path, value) + self.value = value + return copy.deepcopy(value) + + def pin(self, drive, available): + """Select exact verified attachments. Caller owns output admission/lease.""" + profile = self.snapshot(drive, available) + routes = validate_routes(profile["routes"], drive) + pinned = {} + for device, route in routes.items(): + matches = [ + a + for a in available + if a.get("device_id") == device + and a.get("uuid") == route["uuid"] + and a.get("verified") is True + and a.get("route") == route + and a.get("session_id") + ] + if len(matches) != 1: + raise ValueError("Выбранная шина мотора недоступна или его UUID не подтверждён.") + pinned[device] = copy.deepcopy(matches[0]) + return { + "revision": profile["revision"], + "drive_revision": drive["revision"], + "devices": pinned, + } + + def assert_pinned(self, pinned, drive, available): + if self.pin(drive, available) != pinned: + raise ValueError("Подключение или профиль изменился. Начните новый сеанс управления.") diff --git a/plugins/vesc/runtime/controller_diagnostics.py b/plugins/vesc/runtime/controller_diagnostics.py new file mode 100644 index 00000000..47c9c817 --- /dev/null +++ b/plugins/vesc/runtime/controller_diagnostics.py @@ -0,0 +1,18 @@ +"""Bounded, read-only firmware diagnostics and exact-attachment USB descriptors.""" +from pathlib import Path +from .serial import check_attachment + + +def read_diagnostics(device): + attachment = device.attachment + check_attachment(attachment) + path = Path('/sys/bus/usb/devices') / attachment.usb + usb = {"port": attachment.usb, "tty": attachment.tty, "speed": attachment.speed} + for field in ('idVendor', 'idProduct', 'bcdDevice', 'manufacturer', 'product', 'serial'): + try: + usb[field] = (path / field).read_text()[:256].strip() + except OSError: + usb[field] = None + reports = {name: device.link.diagnostic(name) for name in ('hw_status', 'faults')} + check_attachment(attachment) + return {"usb": usb, "reports": reports} diff --git a/plugins/vesc/runtime/diagnostics.py b/plugins/vesc/runtime/diagnostics.py new file mode 100644 index 00000000..852293a2 --- /dev/null +++ b/plugins/vesc/runtime/diagnostics.py @@ -0,0 +1,87 @@ +"""Bounded failure evidence in the service journal, never in the drive loop.""" + +import json +import logging +import time +from datetime import UTC, datetime + +LOGGER = logging.getLogger("missioncore.vesc.failure") + + +def failure(error, phase, *, device=None, session_id=None, release_confirmed=None): + # NativeLink attaches the original RPC and recent calls to the exception. + # Cleanup uses the same link and replaces last_rpc; reading it afterwards + # would record 'process not running' instead of the initiating timeout. + try: + record = { + "event": "vesc_failure", + "at": datetime.now(UTC).isoformat(), + "monotonic": time.monotonic(), + "phase": phase, + "error": str(error)[:512], + "type": type(error).__name__, + "violation": getattr(error,"violation",None), + "device_id": getattr(error,"device_id",None), + "session_id": session_id, + "release_confirmed": release_confirmed, + "native_rpc": getattr(error, "native_rpc", None), + "native_startup": getattr(error, "native_startup", None), + "can_bridge": getattr(error, "can_bridge", None), + "native_history": list(getattr(error, "native_history", []))[-8:], + } + if device is not None: + record["device_id"] = device.id + record["attachment"] = { + key: getattr(device.attachment, key) for key in ("usb", "address", "tty") + } + raw = json.dumps(record, ensure_ascii=False, allow_nan=False) + if len(raw.encode()) > 16000: + record["native_history"] = [] + record["history_omitted"] = True + raw = json.dumps(record, ensure_ascii=False, allow_nan=False) + if len(raw.encode()) > 16000: + record["native_rpc"] = None + record["rpc_omitted"] = True + raw = json.dumps(record, ensure_ascii=False, allow_nan=False) + if len(raw.encode()) > 16000: + record["native_startup"] = None + record["startup_omitted"] = True + raw = json.dumps(record, ensure_ascii=False, allow_nan=False) + LOGGER.warning("%s", raw) + except Exception: + # Journal failure must never bypass release/fault/ownership cleanup. + pass + + +def connection(event, device, error=None): + """One event per lifecycle transition, before its session/sample is cleared.""" + try: + sample = device.sample + record = { + "event": "vesc_connection", + "transition": event, + "at": datetime.now(UTC).isoformat(), + "monotonic": time.monotonic(), + "device_id": device.id, + "session_id": device.session, + "identity": device.identity, + "attachment": { + key: getattr(device.attachment, key) for key in ("usb", "address", "tty") + }, + "last_sample_at": sample.get("observed_at") if sample else None, + "last_sample_age_s": max(0.0, time.monotonic() - sample["sampled_at"]) + if sample + else None, + "error": str(error)[:512] if error else None, + "error_type": type(error).__name__ if error else None, + } + if sample: + record["last_values"] = { + k: sample["values"].get(k) + for k in ("erpm", "motor_current_a", "input_voltage_v", "duty", "fault_code") + } + raw = json.dumps(record, ensure_ascii=False, allow_nan=False) + if len(raw.encode()) <= 4096: + LOGGER.info("%s", raw) + except Exception: + pass diff --git a/plugins/vesc/runtime/drive_diagnostics.py b/plugins/vesc/runtime/drive_diagnostics.py new file mode 100644 index 00000000..ed4a19cd --- /dev/null +++ b/plugins/vesc/runtime/drive_diagnostics.py @@ -0,0 +1,85 @@ +"""No-I/O recorder for existing reads/commands; opt-in never changes ownership.""" +try: + from .bounded_diagnostics import BoundedDiagnostics +except ModuleNotFoundError: + import runpy + from pathlib import Path + BoundedDiagnostics=runpy.run_path(str(Path(__file__).resolve().parents[3]/ + "packages/plugin-sdk/python/missioncore_plugin_sdk/bounded_diagnostics.py"))["BoundedDiagnostics"] + +try: + from .diagnostic_options import LEGACY_OPTIONS, diagnostic_options +except ModuleNotFoundError: + import runpy + from pathlib import Path + _options=runpy.run_path(str(Path(__file__).resolve().parents[3]/ + "packages/plugin-sdk/python/missioncore_plugin_sdk/diagnostic_options.py")) + LEGACY_OPTIONS,diagnostic_options=_options["LEGACY_OPTIONS"],_options["diagnostic_options"] + +class DriveDiagnostics(BoundedDiagnostics): + def __init__(self,root): + super().__init__('vesc') + from .session_log import SessionLog + self.log=SessionLog(root) + self.stop_after=None + self.options=dict(LEGACY_OPTIONS) + + def add(self,event,**data): + if not self.active():return + row=super().add(event,**data) + if row is not None: + try:self.log.append(row) + except Exception:self.rejected+=1 + + def exchange(self,body): + if not isinstance(body,dict) or set(body)-{'id','enabled','after','vehicle','core_events','relay_events','export','stop_after','options'}: + raise ValueError('Invalid diagnostic request') + if type(body.get('enabled')) is not bool or type(body.get('after')) is not int or body['after']<0: + raise ValueError('Invalid diagnostic state') + stop_after=body.get('stop_after') + if 'stop_after' in body and (type(stop_after) is not int or not 0<=stop_after<=2**53-1 or body['enabled']): + raise ValueError('Invalid diagnostic stop cursor') + options=diagnostic_options(body.get('options')) + if body['id']==self.id and options!=self.options: + raise ValueError('Diagnostic capture options changed') + previous=self.id + self.options=options + if body['enabled'] or body['id']!=self.id: + try:self.log.start(body['id'],body.get('vehicle','Rover'),create=body['enabled'],options=options) + except OSError as error: + self.log.id=body['id'];self.log.error=type(error).__name__;self.log.closed=True + self.configure(body['id'],False) + return {**self.snapshot(body['after'],24),'id':body['id'],'storage':self.log.status()} + if previous!=body['id']:self.stop_after=None + if stop_after is not None: + if self.stop_after is not None and self.stop_after!=stop_after: + raise ValueError('Diagnostic stop cursor changed') + self.stop_after=stop_after + stop_after=self.stop_after + if options['core_trace']:self.log.external('core',body.get('core_events',[])) + self.log.external('node',body.get('relay_events',[])) + if not body['enabled'] and self.active():self.add('capture_stopped') + self.configure(body['id'],body['enabled'] and stop_after is None and not self.log.closed and not self.log.closing and not self.log.error) + # Stop acquisition now; preserve only the already-created Core/browser + # tail until its final sequence has been accepted by the disk writer. + draining=stop_after is not None and self.log.external_ack.get('core',0) 65536: + raise ValueError('Bootloader exceeds bound') + if 'transfer_id' in p and (not isinstance(p['transfer_id'],str) or not re.fullmatch(r'fw_[0-9a-f]{32}',p['transfer_id'])): + raise ValueError('Invalid firmware transfer') + if name == 'chunk': + if type(p['offset']) is not int or not 0 <= p['offset'] < MAX_SOURCE or not isinstance(p['data'],str) or len(p['data']) > 43700: + raise ValueError('Invalid firmware chunk') + data = base64.b64decode(p['data'],validate=True) + if not 1 <= len(data) <= 32768: + raise ValueError('Invalid firmware chunk size') + if name == 'apply' and any(p[key] is not True for key in ('rig_clear','inputs_isolated','compatible_image_confirmed')): + raise ValueError('Image compatibility and stopped, isolated drive confirmation required') + if name in ('cancel','backup') and (not isinstance(p['operation_id'],str) or not re.fullmatch(r'op_[0-9a-f]{32}',p['operation_id'])): + raise ValueError('Exact upload operation required') + + +class FirmwareUpdate: + def __init__(self, service, atomic, utc, clock=time.monotonic, sleep=time.sleep): + self.service, self.atomic, self.utc, self.clock, self.sleep = service, atomic, utc, clock, sleep + self.transfers = OrderedDict() + self.lock = threading.RLock() + self.active = None + self.cancel_event = threading.Event() + + def path(self, device): + return self.service.root / ('firmware-pending-' + (device if isinstance(device,str) else device.id) + '.json') + + def pending(self, device): + path = self.path(device) + if path.exists():return json.loads(path.read_text()) + identifier=device if isinstance(device,str) else device.id + # An uncertain CAN write follows the target UUID if it later appears + # directly on USB. Changing transports must never remove its interlock. + for candidate in self.service.root.glob('firmware-pending-vesc_*.json'): + record=json.loads(candidate.read_text()) + if record.get('image',{}).get('target') and record.get('before_backup_device_id')==identifier:return record + return None + + def owns(self, device): + with self.lock: + active=self.active + if not active:return False + return active['device_id']==device.id or (active.get('image',{}).get('target',{}).get('uuid') is not None + and active['image']['target']['uuid']==(device.identity or {}).get('uuid')) + + def require_can_owner(self, device, target): + with self.service.lock: + peers=list(self.service.devices.values()) + if any(d.identity and d.identity.get('uuid')==target['uuid'] for d in peers): + raise Rejected('Этот CAN-контроллер уже подключён по USB. Откройте его собственные настройки и выберите USB.') + + def status(self, device_id): + with self.lock: + if self.active and self.active['device_id'] == device_id: + return dict(self.active) + record = self.pending(device_id) + if record and record['state'] == 'uploading': + return {**record,'state':'unknown','message':'Загрузка прервана. Итог записи не подтверждён.'} + return record or {'state':'idle'} + + def cancel(self, device_id, operation): + with self.lock: + if not self.active or self.active['device_id'] != device_id or self.active['operation_id'] != operation: + raise Rejected('Эта загрузка уже не выполняется. Обновите её состояние.') + self.cancel_event.set() + return {'cancel_requested':True,'operation_id':operation} + + def get(self, device, identifier): + now = self.clock() + self.transfers = OrderedDict((k,v) for k,v in self.transfers.items() if now-v['at'] < 600) + value = self.transfers.get(identifier) + if not value or value['identity'] != device.identity or value['device_id'] != device.id or value['session'] != device.session: + raise Rejected('Файл истёк или контроллер переподключён. Загрузите файл заново.') + return value + + def stage(self, device, action, p): + name = action.removeprefix(PREFIX) + if name=='backup': + record=self.pending(device) + if not record or record.get('operation_id')!=p['operation_id']: + path=self.service.root/('firmware-result-'+p['operation_id']+'.json') + record=json.loads(path.read_text()) if path.exists() else None + if not record or record.get('device_id')!=device.id or record.get('identity',{}).get('uuid')!=device.identity['uuid']: + raise Rejected('Копия не относится к этому сеансу прошивания.') + return {'backup':self.service.archive.read('local',record.get('before_backup_device_id',device.id),record['before_backup_id'])} + if name=='target':return {'target':firmware_target.target(device,p['can_id'])} + selected=firmware_target.target(device,p['can_id']) if name in ('begin','catalog','catalog_prepare') and 'can_id' in p else None + from types import SimpleNamespace + view=SimpleNamespace(identity=firmware_target.identity(selected),link=device.link) if selected else device + if name == 'catalog': + return firmware_catalog.compatible(view) + if name == 'catalog_prepare': + item,data=firmware_catalog.image(view,p['image_id']) + manifest={'name':item['name'],'bytes':item['bytes'],'sha256':item['sha256'],'kind':'firmware', + 'hardware':view.identity['hardware'],'target_version':item['version'],**({'can_id':p['can_id'],'target':selected} if selected else {})} + identifier=self.stage(device,PREFIX+'begin',manifest)['transfer_id'] + self.transfers[identifier]['data'].extend(data) + self.transfers[identifier]['manifest'].update(catalog_image_id=item['id'],hardware_limits=item['hardware_limits']) + return self.stage(device,PREFIX+'seal',{'transfer_id':identifier}) + if name == 'begin': + if selected:self.require_can_owner(device,selected) + if p['name'].lower().endswith('.hex') and 'hex' not in getattr(device.link,'engine',{}).get('contract',{}).get('firmware_formats',[]): + raise Rejected('Для HEX требуется обновление ядра VESC Tool на борту.') + if selected and p['target']!=selected:raise Rejected('CAN-контроллер изменился после выбора.') + if p['hardware'] != view.identity['hardware'] or view.identity['hardware_type'] != 0: + raise Rejected('Выбранная аппаратная конфигурация не совпадает с контроллером.') + profiles = getattr(device.link,'engine',{}).get('contract',{}).get('firmware_profiles',[]) + versions = {f"{v['major']}.{v['minor']:02}" for v in profiles} or {device.identity['version']} + if 'swd' in p and 'swd' not in getattr(device.link,'engine',{}).get('contract',{}).get('firmware_targets',[]):raise Rejected('Обновите ядро для SWD.') + if 'swd' not in p and (p['target_version'] not in versions or (p['kind'] == 'bootloader' and p['target_version'] != view.identity['version'])): + raise Rejected('Целевая версия не поддерживается этим выпуском бортового приложения.') + self.transfers = OrderedDict((k,v) for k,v in self.transfers.items() if self.clock()-v['at'] < 600) + # One candidate per UUID; a replaced candidate can no longer apply. + self.transfers = OrderedDict((k,v) for k,v in self.transfers.items() if v['device_id'] != device.id) + if len(self.transfers) >= 2: + raise Rejected('Уже подготовлены два образа. Удалите один из них.') + identifier = 'fw_' + uuid.uuid4().hex + self.transfers[identifier] = {'at':self.clock(),'identity':dict(device.identity), + 'device_id':device.id,'session':device.session,'manifest':dict(p),'data':bytearray(),'sealed':False} + return {'transfer_id':identifier,'offset':0,'expires_in_s':600} + value = self.get(device,p['transfer_id']) + if name == 'discard': + del self.transfers[p['transfer_id']] + return {'discarded':True} + if name == 'chunk': + data = base64.b64decode(p['data'],validate=True) + if value['sealed'] or p['offset'] != len(value['data']) or len(value['data'])+len(data) > value['manifest']['bytes']: + raise Rejected('Порядок или размер частей файла изменился. Начните загрузку заново.') + value['data'].extend(data) + return {'transfer_id':p['transfer_id'],'offset':len(value['data'])} + if name != 'seal': + raise ValueError('Unknown staging operation') + raw, manifest = bytes(value['data']),value['manifest'] + if len(raw) != manifest['bytes'] or hashlib.sha256(raw).hexdigest() != manifest['sha256']: + raise Rejected('Размер или контрольная сумма файла не совпадают.') + # Native upstream file validation; staging never issues USB writes. + device.link.firmware_rpc('begin',**{k:manifest[k] for k in ('kind','bytes','sha256','hardware')},uuid=manifest.get('target',device.identity)['uuid'],**({'can_id':manifest['can_id']} if 'can_id' in manifest else {}),**({'swd':manifest['swd']} if 'swd' in manifest else {}),format='hex' if manifest['name'].lower().endswith('.hex') else 'bin') + for offset in range(0,len(raw),32768): + device.link.firmware_rpc('chunk',offset=offset,data=base64.b64encode(raw[offset:offset+32768]).decode()) + info = device.link.firmware_rpc('seal') + if (info.get('source_sha256',info.get('sha256')) != manifest['sha256'] + or info.get('source_bytes',info.get('bytes')) != len(raw) + or not isinstance(info.get('sha256'),str) or not re.fullmatch(r'[0-9a-f]{64}',info['sha256']) + or type(info.get('bytes')) is not int or not 256<=info['bytes']<=(65536 if manifest['kind']=='bootloader' else MAX_IMAGE)): + raise ValueError('Native image inspection mismatch') + manifest.update(source_sha256=manifest['sha256'],source_bytes=manifest['bytes'], + sha256=info['sha256'],bytes=info['bytes'],format=info.get('source_format','bin'),base_address=info.get('base_address')) + value['sealed'] = True + # The native owner retains the sealed bytes. Python needs only metadata. + value['data'].clear() + return {'transfer_id':p['transfer_id'],'image':manifest,'inspection':info,'identity':firmware_target.identity(manifest['target']) if 'target' in manifest else device.identity, + 'expires_in_s':max(0,600-int(self.clock()-value['at']))} + + def apply(self, device, p, operation, deadline): + plan = self.get(device,p['transfer_id']) + if plan['manifest'].get('hardware_limits') is False and p.get('hardware_limits_removed_confirmed') is not True: + raise Rejected('Этот образ отключает аппаратные пределы. Требуется отдельное подтверждение.') + if 'swd' in plan['manifest'] and p.get('swd_target_confirmed') is not True:raise Rejected('Подтвердите физическую цель SWD, распиновку и размер её flash.') + if not plan['sealed']: + raise Rejected('Сначала проверьте полный образ.') + if self.service.config_editor.pending(device): + raise Rejected('Сначала завершите проверку предыдущей записи конфигурации.') + previous = self.pending(device) + if previous and previous['device_id']!=device.id: + raise Rejected('Завершите прежнее прошивание в карточке USB-контроллера, через который оно начато.') + if previous and previous['state'] == 'uploading': + # On service restart the in-memory active operation is absent. An + # uncertain write can only be replaced by another explicit upload. + if self.active: + raise Rejected('Прошивка уже загружается.') + before = self.service.config_editor.read(device) + self.service.config_editor.idle(device,before) + if (deadline-datetime.now(timezone.utc)).total_seconds() < 270: + raise Rejected('Для загрузки требуется полный срок операции. Подготовьте команду заново.') + view=device + if 'target' in plan['manifest']: + self.require_can_owner(device,plan['manifest']['target']) + view,before=firmware_target.snapshot(device,plan['manifest']['target']) + self.service.config_editor.idle(view,before) + backup = self.service.config_editor.backup(view,before) + record = {'schema':'missioncore.vesc.firmware-update/v1','device_id':device.id, + 'session_id':device.session,'identity':dict(device.identity),'image':plan['manifest'], + 'operation_id':operation,'before_backup_id':backup,'before_backup_device_id':view.id,'started_at':self.utc(), + 'state':'uploading','progress':0,'write_started':False,'before':packet_hashes(before),'upload_confirmed':False,'binary_readback_verified':False} + if previous: + self.atomic(self.service.root/('firmware-result-'+previous['operation_id']+'.json'),previous) + self.atomic(self.path(device),record) # durable interlock before any erase + self.transfers.pop(p['transfer_id']) # consume once, including uncertain start + self.service.motor.state('rc') + self.cancel_event.clear() + with self.lock: self.active = dict(record) + try: + record['write_started'] = True + self.atomic(self.path(device),record) + device.link.firmware_rpc('start',sha256=plan['manifest']['sha256']) + limit = self.clock()+250 + while self.clock() < limit: + if self.cancel_event.is_set(): + device.link.firmware_rpc('cancel') + self.cancel_event.clear() + value = device.link.firmware_rpc('status') + with self.lock: + self.active.update(progress=value.get('progress',0),message=value.get('message','')) + if value.get('state') in ('uploaded','unknown'): + record.update(state='awaiting_identity' if value.get('upload_confirmed') else 'unknown', + upload_confirmed=value.get('upload_confirmed') is True, + progress=value.get('progress',0),message=value.get('message',''), + binary_readback_verified=value.get('binary_readback_verified') is True, + reboot_confirmed=value.get('reboot_confirmed') is True,boot_verified=False) + break + self.sleep(.5) + else: + try: device.link.firmware_rpc('cancel') + except (OSError,ValueError,TimeoutError): pass + record.update(state='unknown',message='Срок загрузки истёк. Итог не подтверждён.') + except (OSError,ValueError,TimeoutError) as error: + record.update(state='unknown',message='Связь во время загрузки потеряна. Итог записи не подтверждён.',error=str(error)[:512]) + finally: + record['finished_at'] = self.utc() + try: + self.atomic(self.path(device),record) + finally: + with self.lock: self.active = None + # Force fresh identification even if the result journal cannot + # be updated. The earlier durable pending record stays unsafe. + link,device.link = device.link,None + device.sample = device.telemetry = None + device.session = 'vesc_'+uuid.uuid4().hex + device.retry_at = time.monotonic()+2 + if link: link.close() + return record + + def reconcile(self, device): + record = self.pending(device) + if not record: + return {'state':'idle'} + gateway = firmware(device.link.query(0)) + if gateway['uuid']!=record['identity']['uuid'] or gateway['hardware']!=record['identity']['hardware']: + raise Rejected('USB-контроллер изменился.') + expected=record['image'].get('target') + identity=firmware_target.identity(firmware_target.target(device,expected['can_id'])) if expected else gateway + expected_identity=expected or record['identity'] + if identity['uuid'] != expected_identity['uuid'] or identity['hardware'] != expected_identity['hardware']: + raise Rejected('Ответил другой контроллер. Привязка прошивки не подтверждена.') + # Successful native ACKs plus a fresh identity can settle the upload + # workflow, including bootloader transfer. Neither proves binary readback. + # Identity alone cannot settle an interrupted/uncertain upload. + record['observed_identity'] = identity + not_started=False + if record.get('write_started') is False: + before=firmware_target.snapshot(device,expected)[1] if expected else self.service.config_editor.read(device) + not_started=packet_hashes(before)==record.get('before') + swd_done='swd' in record['image'] and record.get('binary_readback_verified') is True and record.get('reboot_confirmed') is True + if not_started or (record['upload_confirmed'] and (swd_done or ('swd' not in record['image'] and identity['version'] == record['image']['target_version']))): + record.update(state='not_started' if not_started else 'identified',finished_at=self.utc()) + self.atomic(self.service.root/('firmware-result-'+record['operation_id']+'.json'),record) + self.path(device).unlink() + import os + fd = os.open(self.service.root,os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + else: + record['state'] = 'unknown' + self.atomic(self.path(device),record) + return record diff --git a/plugins/vesc/runtime/hall_detection.py b/plugins/vesc/runtime/hall_detection.py index c2b79e48..49777aa6 100644 --- a/plugins/vesc/runtime/hall_detection.py +++ b/plugins/vesc/runtime/hall_detection.py @@ -51,9 +51,14 @@ def measure(owner, devices, target, original, backups, unchanged, preflight): if "rc_during_native_cycle" not in issues: issues.append("rc_during_native_cycle") sample = values(target.link.query(4, timeout=0.06)) samples.append({"at": owner.monotonic() - started, "values": sample}) - for device in devices: device.link.test_command("claim") + # The native Hall procedure exclusively owns the target. + # Renewing its output lease is rejected by the native guard + # and retires its transport before the result can arrive. + # Only keep non-target controllers inhibited and released. for device in devices: - if device is not target: device.link.test_command("release") + if device is not target: + device.link.test_command("claim") + device.link.test_command("release") except (OSError, ValueError, TimeoutError): if "communication_unconfirmed" not in issues: issues.append("communication_unconfirmed") if owner.stop.is_set() and "stop_requested_during_native_cycle" not in issues: diff --git a/plugins/vesc/runtime/maintenance_state.py b/plugins/vesc/runtime/maintenance_state.py new file mode 100644 index 00000000..d1e10d0d --- /dev/null +++ b/plugins/vesc/runtime/maintenance_state.py @@ -0,0 +1,39 @@ +"""Quiescence proof excludes every powered/pending owner; closes transport only.""" + + +def idle(service): + remote = service.remote + trace=getattr(remote,"trace",None) + if trace and (trace.active() or not trace.log.closed): + return "diagnostic-capture-active" + with remote.lock: + if remote.lease.live() or (remote.thread and remote.thread.is_alive()): + return "control-active" + if remote.release_confirmed is False: + return "release-unconfirmed" + if service.motor.active: + return "motor-procedure-active" + with service.firmware_update.lock: + if service.firmware_update.active: + return "firmware-active" + patterns = ("limits_*.json", "*pending*.json", "code-execution-*.json") + if any(any(service.root.glob(pattern)) for pattern in patterns): + return "device-change-unresolved" + with service.lock: + devices = list(service.devices.values()) + if any(service.samples.active(d) for d in devices): + return "sample-capture-active" + return None + + +def quiesce(service): + # Admission is closed and both discovery/observer callbacks have drained. + # No stop/current/lease/release/configuration RPC is issued here. + with service.lock: + devices = list(service.devices.values()) + service.devices.clear() + for device in devices: + device.close() + with service.remote.lock: + service.remote.primed = False + service.remote.state = "observing" diff --git a/plugins/vesc/runtime/motor_test.py b/plugins/vesc/runtime/motor_test.py index d6766df5..49eff73c 100644 --- a/plugins/vesc/runtime/motor_test.py +++ b/plugins/vesc/runtime/motor_test.py @@ -33,7 +33,7 @@ class LimitExceeded(Rejected): super().__init__(f"Тест остановлен: {label} {number(value)} {unit}; диапазон проверки {number(low)}…{number(high)} {unit}.") -def check_configuration(identity, motor, app): +def check_configuration(identity, motor, app, *, remote=False): if (identity["version"], identity["hardware"], identity["test_firmware"], identity["hardware_type"]) != ("5.02", "75_300_R2", 0, 0): raise Rejected("Тест поддерживает только проверенный профиль VESC 75_300_R2 / 5.02.") if (motor["motor_type"] != 2 or app["app_to_use"] not in (1, 4) @@ -41,18 +41,39 @@ def check_configuration(identity, motor, app): or app["timeout_brake_current"] != 0 or app["app_ppm_conf.ctrl_type"] != 4 or not 0.01 <= app["app_ppm_conf.hyst"] <= 0.3): raise Rejected("Настройки FOC, PPM или тайм-аута не подходят для короткой проверки.") - if not 2 <= motor["l_current_max"] <= 100 or not 2 <= motor["l_in_current_max"] <= 100: + if any(not math.isfinite(motor[k]) or motor[k] < 2 for k in ("l_current_max", "l_in_current_max")) or (not remote and + (motor["l_current_max"] > 100 or motor["l_in_current_max"] > 100)): raise Rejected("Нужна проверка токовых ограничений.") -def check_values(value, moving=False, current_a=2, motor=None, *, standstill_confirmed=False): +def check_values(value, moving=False, current_a=2, motor=None, *, standstill_confirmed=False, + configured_drive=False, settling=False): current_limit = max(5, current_a * 1.2 + 2) if moving else 1 speed_limit = TEST_LIMITS["max_erpm"] if moving else 30 duty_limit = TEST_LIMITS["max_duty"] if moving else 0.01 + if configured_drive and moving: + # Remote throttle uses the installed controller's operating envelope; + # the separate raised-rig tests retain their 6000 ERPM / 25% bounds. + if motor is None: + raise Rejected("Пределы контроллера не прочитаны.") + speed_limit = min(motor["l_max_erpm"], -motor["l_min_erpm"]) + duty_limit = motor["l_max_duty"] + if not math.isfinite(speed_limit) or speed_limit <= 0 or not 0 < duty_limit <= 1: + raise Rejected("Некорректные пределы движения контроллера.") if moving and motor is not None: - current_limit = min(current_limit, motor["l_current_max"]) + # The operating current is regulated inside VESC, not a sampled trip + # threshold. Short overshoot/measurement quantization must not kill a + # remote session. Firmware fault remains authoritative; retain its + # independent absolute-current envelope as a telemetry sanity bound. + current_limit = motor["l_abs_current_max"] if configured_drive else min(current_limit, motor["l_current_max"]) + if not math.isfinite(current_limit) or current_limit <= 0: + raise Rejected("Некорректный абсолютный предел тока VESC.") speed_limit = min(speed_limit, motor["l_max_erpm"], -motor["l_min_erpm"]) duty_limit = min(duty_limit, motor["l_max_duty"]) + if configured_drive: + # GET_VALUES quantizes duty to 1/1000, whereas MCCONF uses float32 + # (e.g. 0.949999988). Do not fault at the same configured endpoint. + duty_limit = math.ceil(duty_limit * 1000) / 1000 # FW 5.02 continues its observer/PLL while undriven. Sensorless ERPM and # tachometer share that estimate, so neither proves physical standstill. # Only explicitly attended Hall/speed/release operations may substitute @@ -66,7 +87,10 @@ def check_values(value, moving=False, current_a=2, motor=None, *, standstill_con # one idle quantum is not proof that PWM is enabled. Permit at most # that quantum only with fresh operator-confirmed physical standstill. # Current/voltage/temperature/fault and neutral-window guards remain. - duty_limit = 0.001 + # Remote preparation may wait through a small idle-estimator transient, + # within the ordinary 1% idle bound. This does NOT admit output: the + # subsequent whole-profile window still requires <=0.1% continuously. + duty_limit = 0.01 if settling else 0.001 bounds = ( ("fault_code", 0, 0, "код ошибки VESC", "", 1), ("input_voltage_v", 20, 60, "напряжение питания", "В", 1), @@ -115,11 +139,14 @@ class MotorTest: self.stop.set() def neutral(self, devices): + receivers = {} for device in devices: value = ppm(device.link.query(31, timeout=0.06)) + receivers[device.id] = value if self.receiver_active(device.id, value["level"]): self.state("rc") raise Rejected("Приёмник передаёт команду. Управление удерживается за пультом.") + return receivers def receiver_active(self, identifier, level): if identifier not in self.receiver_bands: @@ -132,7 +159,8 @@ class MotorTest: duration = command["parameters"]["duration_s"] current_a = command["parameters"]["current_a"] group_mode = command["action_id"] == "vesc.drive.run" - speed_mode = command["action_id"] in ("vesc.motor.run", "vesc.drive.run") + remote_duty = remote is not None and "max_duty_percent" in command["parameters"] + speed_mode = command["action_id"] in ("vesc.motor.run", "vesc.drive.run") and not remote_duty moving = [target] if group_mode: from .group_test import targets @@ -153,8 +181,13 @@ class MotorTest: if (deadline - datetime.now(timezone.utc)).total_seconds() < budget + 5: raise Rejected("Не хватило времени для проверки всех контроллеров. Ток не подавался.") attachments = {d.attachment for d in devices} + hub = getattr(self.service, "transports", None) + pinned = self.service.transport.pin(self.service.drive.value, hub.endpoints()) if hub and remote is not None else None def unchanged(): - if set(self.service.discover_fn()) != attachments: + if hub: + try: hub.assert_devices(devices, pinned) + except (OSError, ValueError) as error: raise Rejected(str(error)) from error + elif set(self.service.discover_fn()) != attachments: raise Rejected("Подключение VESC изменилось. Обновите устройства.") with self.stop_lock: if self.cancelled_at is not None and requested <= self.cancelled_at: @@ -174,11 +207,17 @@ class MotorTest: raise Rejected("Возврат управления пока невозможен: итог калибровки, конфигурация или нулевой ток не подтверждены.") from error identities, applications, backups, originals = {}, {}, [], {} motors, idle_samples = {}, [] - observed_standstill = (hall_mode or speed_mode or release) and command["parameters"].get("standstill_confirmed") is True + observed_standstill = (hall_mode or speed_mode or remote_duty or release) and command["parameters"].get("standstill_confirmed") is True target_motor, target_raw = None, None for device in devices: preflight() if device.link is None: raise Rejected("Один из контроллеров отключён.") + if self.service.bms_configuration.pending(device) or self.service.code_tools.blocked(device): + raise Rejected("Сначала проверьте запись BMS/кода и остановите Lisp.") + if self.service.firmware_update.pending(device): + raise Rejected("Итог загрузки прошивки не подтверждён. Управление заблокировано.") + if self.service.config_editor.pending(device): + raise Rejected("Итог записи конфигурации ещё не подтверждён. Проверьте его в настройках VESC.") if self.limits.pending(device): raise Rejected("Восстановление временных токовых пределов ещё не подтверждено.") if (self.service.root / "hall-pending.json").exists(): @@ -191,10 +230,13 @@ class MotorTest: originals[device.id] = configs motor, app = decode(configs["motor"], "motor"), decode(configs["application"], "application") motors[device.id] = motor - check_configuration(identity, motor, app) + if remote is not None: + from .remote_limits import publish + publish(device, motor) + check_configuration(identity, motor, app, remote=remote is not None) self.receiver_bands[device.id] = neutral_band(app) if device in moving: - if not foc_mode and current_a > min(motor["l_current_max"], motor["l_in_current_max"]): + if remote is None and not foc_mode and current_a > min(motor["l_current_max"], motor["l_in_current_max"]): raise Rejected("Ток проверки превышает настроенный предел выбранного контроллера.") if not (motor["l_max_erpm"] > 0 and motor["l_min_erpm"] < 0 and 0 < motor["l_max_duty"] <= 1): raise Rejected("Нужна проверка настроенных пределов оборотов и PWM.") @@ -208,7 +250,7 @@ class MotorTest: if speed_mode and abs(command["parameters"]["erpm"]) < motor["s_pid_min_erpm"]: raise Rejected(f"Минимальная скорость регулятора этого VESC: {motor['s_pid_min_erpm']:g} ERPM.") check_values(values(device.link.query(4)), motor=motor, - standstill_confirmed=observed_standstill) + standstill_confirmed=observed_standstill, settling=remote_duty) identities[device.id], applications[device.id] = identity, app identifier = "op_" + uuid.uuid4().hex backup = {"schema": "missioncore.vesc.config-backup/v1", "device_id": device.id, @@ -236,17 +278,30 @@ class MotorTest: raise Rejected("На CAN обнаружено другое устройство. Нужна проверка схемы.") if foc_mode and len(peers) != 1: raise Rejected("Этот профиль калибрует VESC по отдельным USB без CAN-соседей. Требуется профиль связанного CAN-борта.") - for _ in range(10): + stable, attempts = 0, 0 + settle_until = self.monotonic() + 3 + while stable < 10: preflight() unchanged() - self.neutral(devices) + receivers = self.neutral(devices) + quiet = True + attempts += 1 if observed_standstill: for device in devices: sample = values(device.link.query(4, timeout=0.06)) check_values(sample, motor=motors[device.id], - standstill_confirmed=observed_standstill) + standstill_confirmed=observed_standstill, settling=remote_duty) + if remote_duty and motors[device.id]["foc_sensor_mode"] == 0: + quiet = quiet and abs(sample["duty"]) <= 0.001 + if remote is not None: + # Reuse the exclusive owner's actual reads. No extra + # CAN traffic and no renewal of an old sample clock. + remote._publish(device, sample, receivers[device.id]) idle_samples.append({"device_id": device.id, "at": self.monotonic(), "sensor_mode": motors[device.id]["foc_sensor_mode"], "values": sample}) + stable = stable + 1 if quiet else 0 + if remote_duty and stable < 10 and (attempts >= 30 or self.monotonic() >= settle_until): + raise Rejected("Подготовка остановлена: показатель PWM не стабилизировался за 3 секунды. Проверьте остановку ровера и нейтраль пульта.") self.sleep(0.1) preflight_record = {"standstill_confirmed": observed_standstill, "samples": idle_samples} if release: diff --git a/plugins/vesc/runtime/native_link.py b/plugins/vesc/runtime/native_link.py index e15b421d..649ee137 100644 --- a/plugins/vesc/runtime/native_link.py +++ b/plugins/vesc/runtime/native_link.py @@ -12,62 +12,127 @@ from pathlib import Path import select import subprocess import time +import threading from .serial import check_attachment +# A process stuck in kernel USB I/O may outlive SIGKILL. Keep its ownership +# until poll confirms exit; do not accumulate replacement owners or waiter threads. +_retiring = {} +_retiring_lock = threading.Lock() + + +def reap_retired(tty=None): + with _retiring_lock: + for key, process in list(_retiring.items()): + if process.poll() is not None: + del _retiring[key] + if tty in _retiring: + raise OSError("Previous native USB owner has not exited") + + class NativeLink: def __init__(self, attachment): self.attachment = attachment self.process = None + self.bridge = None self.buffer = b"" self.sequence = 0 self.hall_pending = False self.history = deque(maxlen=32) + reap_retired(attachment.tty) + from .can_bridge import Attachment, Bridge + if isinstance(attachment, Attachment): + self.bridge = Bridge(attachment) self.check() root = Path("/usr/lib/mission-core-vesc/native") config = Path("/run/mission-core-vesc/native") / hashlib.sha256(attachment.binding.encode()).hexdigest()[:24] config.mkdir(parents=True, mode=0o700, exist_ok=True) env = dict(os.environ, QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=str(config), XDG_CACHE_HOME=str(config / "cache"), LD_LIBRARY_PATH=str(root / "lib"), - QT_PLUGIN_PATH=str(root / "plugins")) + QT_PLUGIN_PATH=str(root / "plugins"), TMPDIR=str(config)) + target = "--can-bridge=" + str(self.bridge.port) if self.bridge else "/dev/" + attachment.tty # Preserve native startup diagnostics in the private runtime directory. - with (config / "engine.log").open("wb") as diagnostic: - self.process = subprocess.Popen([str(root / "bin/mission-core-vesc-engine"), "/dev/" + attachment.tty], + try: + with (config / "engine.log").open("wb") as diagnostic: + self.process = subprocess.Popen([str(root / "bin/mission-core-vesc-engine"), target], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=diagnostic, env=env, bufsize=0, close_fds=True) + except BaseException: + if self.bridge: self.bridge.close() + raise try: hello = self._receive(time.monotonic() + 6) if hello.get("ready") is not True or not hello.get("engine", {}).get("connected"): raise OSError("Native VESC Tool did not connect") self.engine = hello["engine"] + manifest = json.loads((root / "manifest.json").read_bytes()) + if (self.engine.get("contract", {}).get("rpc_version") != 1 + or self.engine.get("contract") != manifest.get("engine_contract") + or self.engine.get("version") != manifest.get("upstream_version") + or self.engine.get("commit") != manifest.get("upstream_commit")): + raise OSError("Native engine contract does not match the installed release") self.check() - except BaseException: + except BaseException as error: + # Preserve this attempt's evidence before close/retry replaces it. + try: + with (config / "engine.log").open("rb") as diagnostic: + diagnostic.seek(0, os.SEEK_END) + size = diagnostic.tell() + diagnostic.seek(max(0, size - 4096)) + tail = diagnostic.read(4096).decode("utf-8", errors="replace") + error.native_startup = {"pid": self.process.pid, + "exit_code": self.process.poll(), "stderr_tail": tail, + "stderr_truncated": size > 4096} + except Exception: + pass + if self.bridge: + error.can_bridge = self.bridge.diagnostics() self.close() raise @property def alive(self): - return self.process is not None and self.process.poll() is None + return (self.process is not None and self.process.poll() is None + and not (getattr(self, "bridge", None) and self.bridge.stop.is_set())) def check(self): - check_attachment(self.attachment) + if getattr(self, "bridge", None): + self.bridge.check() + else: + check_attachment(self.attachment) + + def failure_error(self): + bridge = getattr(self, "bridge", None) + if bridge and bridge.error: + return OSError("CAN bridge: " + str(bridge.error)[:512]) + code = self.process.poll() if self.process is not None else None + return OSError(f"Native transport exited (code={code})") def _receive(self, deadline): while b"\n" not in self.buffer: - if not self.alive or not select.select([self.process.stdout], [], [], max(0, deadline-time.monotonic()))[0]: + if not self.alive: + raise self.failure_error() + if not select.select([self.process.stdout], [], [], max(0, deadline-time.monotonic()))[0]: + if not self.alive: + raise self.failure_error() raise TimeoutError("Native VESC Tool response timed out") data = os.read(self.process.stdout.fileno(), 65536) - if not data: raise OSError("Native VESC Tool exited") + if not data: raise self.failure_error() self.buffer += data if len(self.buffer) > 2 * 1024 * 1024: raise ValueError("Native response exceeds bound") line, self.buffer = self.buffer.split(b"\n", 1) return json.loads(line) def rpc(self, method, timeout=2, **parameters): + # These two methods only inspect/cancel the already-owned native job. + # They must survive the expected USB detach caused by fwUpload itself; + # no other method may bypass exact-attachment validation. + detached_status = method in ('firmware_status','firmware_cancel') self.sequence += 1 request = json.dumps({"id": self.sequence, "method": method, **parameters}, allow_nan=False).encode()+b"\n" - if len(request) > 65536: raise ValueError("Native request exceeds bound") + if len(request) > (2*1024*1024 if method == "package_unpack" else 512*1024 if method in ("code_pack", "code_write") else 65536): raise ValueError("Native request exceeds bound") started = time.monotonic() deadline = started + timeout trace = {"method": method, "command": parameters.get("command"), @@ -76,14 +141,19 @@ class NativeLink: "tty": self.attachment.tty}} try: trace["stage"] = "attachment_before" - self.check() + if not detached_status: self.check() trace["attachment_before_ms"] = (time.monotonic()-started)*1000 trace["stage"] = "request_write" if not self.alive: raise OSError("Native VESC Tool is not running") if not select.select([], [self.process.stdin], [], max(0, deadline-time.monotonic()))[1]: raise TimeoutError("Native VESC Tool request timed out") - if os.write(self.process.stdin.fileno(), request) != len(request): - raise OSError("Native request write incomplete") + offset = 0 + while offset < len(request): + if not select.select([], [self.process.stdin], [], max(0, deadline-time.monotonic()))[1]: + raise TimeoutError("Native request write timed out") + written = os.write(self.process.stdin.fileno(), request[offset:offset+4096]) + if written <= 0: raise OSError("Native request write incomplete") + offset += written sent_at = time.monotonic() trace["request_write_ms"] = (sent_at-started)*1000-trace["attachment_before_ms"] trace["stage"] = "native_response" @@ -92,12 +162,14 @@ class NativeLink: trace["native_response_ms"] = (received_at-sent_at)*1000 if not isinstance(response, dict): raise ValueError("Invalid native response") if response.get("id") != self.sequence: raise ValueError("Native response identity mismatch") + if isinstance(response.get("control"), dict): trace["control"] = response["control"] + if getattr(self, "bridge", None): trace["can_bridge"] = self.bridge.diagnostics() if response.get("ok") is not True: if isinstance(response.get("diagnostics"), dict): trace["transport"] = response["diagnostics"] raise OSError(response.get("error", "Native operation failed")) trace["stage"] = "attachment_after" - self.check() + if not detached_status: self.check() trace["attachment_after_ms"] = (time.monotonic()-received_at)*1000 trace["stage"] = "complete" result = response.get("result") @@ -112,11 +184,13 @@ class NativeLink: process_alive=self.alive, error=str(error)) try: self.check(); trace["attachment_present"] = True except OSError: trace["attachment_present"] = False + if getattr(self, "bridge", None): + trace["can_bridge"] = self.bridge.diagnostics() self.last_rpc = trace if hasattr(self, "history"): self.history.append(trace) error.native_rpc = trace error.native_history = list(getattr(self, "history", [])) - self.close() + trace["cleanup"] = self.close() raise def query(self, command, timeout=2): @@ -133,13 +207,40 @@ class NativeLink: def test_speed(self, erpm): self.rpc("rpm", timeout=0.1, erpm=erpm) + def drive_duty(self, duty, current_a): + self.rpc("duty_limited", timeout=0.1, duty=duty, current_a=current_a) + def set_temporary_limits(self, config): from .temporary_limits import FIELDS self.rpc("limits", timeout=2.2, parameters={k: config[k] for k in FIELDS}) + def diagnostic(self, command): + return self.rpc("diagnostic", timeout=3.5, command=command) + + def device_tool(self, tool): + return self.rpc("device_tool",timeout=3,tool=tool) + + def bms_read(self, can_id): + return self.rpc("bms_read", timeout=6, can_id=can_id) + + def bms_command(self, target, command): + return self.rpc("bms_command", timeout=3, can_id=target['can_id'], target=target, command=command) + def configuration(self): return self.rpc("configuration", timeout=5) + def configuration_preview(self, sources): + return self.rpc("configuration_preview", timeout=6, sources=sources) + + def configuration_apply(self, kind, target): + return self.rpc("configuration_apply", timeout=9, kind=kind, + **{k: target[k] for k in ("payload", "before_sha256", "after_sha256")}) + + def firmware_rpc(self, action, **parameters): + if action not in ('begin','chunk','seal','start','status','cancel','target','snapshot'): + raise ValueError('Unknown firmware operation') + return self.rpc('firmware_' + action, timeout=11 if action=='snapshot' else 4, **parameters) + def detect_hall(self): if self.hall_pending: raise ValueError("Hall measurement already pending") self.hall_pending = True @@ -160,12 +261,35 @@ class NativeLink: return base64.b64decode(result["payload"], validate=True) def close(self): + if getattr(self, "bridge", None): + self.bridge.close() process, self.process = self.process, None if process is None: return - if process.poll() is None: - process.terminate() - try: process.wait(timeout=1) - except subprocess.TimeoutExpired: - process.kill(); process.wait(timeout=1) - for stream in (process.stdin, process.stdout): - if stream: stream.close() + result = {"exit_confirmed": False} + try: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + process.kill() + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + # SIGKILL cannot finish uninterruptible kernel I/O. + # Retire the owner below without masking the original RPC. + pass + except OSError as error: + result["error"] = str(error)[:256] + finally: + result["exit_confirmed"] = process.poll() is not None + if not result["exit_confirmed"]: + with _retiring_lock: + _retiring[self.attachment.tty] = process + for stream in (process.stdin, process.stdout): + if stream: + try: + stream.close() + except OSError as error: + result["pipe_error"] = str(error)[:256] + return result diff --git a/plugins/vesc/runtime/package_archive.py b/plugins/vesc/runtime/package_archive.py new file mode 100644 index 00000000..9e066fed --- /dev/null +++ b/plugins/vesc/runtime/package_archive.py @@ -0,0 +1,85 @@ +"""Bounded Qt RCC and VESC package containers. Never evaluates QML or Lisp.""" +import hashlib +import re +import struct +import zlib + +MAX_ARCHIVE=8*1024*1024 +MAX_PACKAGE=1024*1024 +MAX_EXPANDED=4*1024*1024 + +def digest(data):return hashlib.sha256(data).hexdigest() + +def uncompress(data,limit=MAX_EXPANDED): + if len(data)<5:raise ValueError('Truncated Qt compressed data') + size=int.from_bytes(data[:4],'big') + if not 0len(raw):raise ValueError('Invalid package field') + name=raw[at:end].decode('ascii');size=struct.unpack_from('>i',raw,end+1)[0];at=end+5 + if name in out or size<0 or size>len(raw)-at or len(out)>=32:raise ValueError('Duplicate, truncated or excessive package field') + out[name]=raw[at:at+size];at+=size + if not out.get('name') or len(out['name'])>256:raise ValueError('Package name required') + for k in ('name','description','description_md','qmlFile','pkgDescQml'): + if k in out and b'\0' in out[k]:raise ValueError('Invalid text field') + if k in out:out[k].decode('utf-8') + if out.get('qmlIsFullscreen',b'\0') not in (b'\0',b'\1'):raise ValueError('Invalid fullscreen flag') + return out + +def metadata(data,path='import.vescpkg'): + f=fields(data) + return {'id':digest(data),'path':path,'name':f['name'].decode(),'library':path.split('/')[0].startswith('lib_'), + 'bytes':len(data),'lisp_bytes':len(f.get('lispData',b'')),'qml_bytes':len(f.get('qmlFile',b'')), + 'description':f.get('description_md',b'').decode()[:65536], 'has_compatibility':bool(f.get('pkgDescQml'))} + +def archive(data): + if not 24<=len(data)<=MAX_ARCHIVE or data[:4]!=b'qres':raise ValueError('Invalid Qt package archive') + version,tree,blobs,names,features=struct.unpack_from('>5I',data,4) + if version not in (2,3) or features!=0 or not 24<=blobs5:raise ValueError('Invalid RCC tree') + seen.add(index);at=tree+index*22;name_offset,flags=struct.unpack_from('>IH',data,at) + if flags&~3:raise ValueError('Unsupported RCC compression') + if index==0:path='' + else: + n=names+name_offset + if not names<=ntree:raise ValueError('RCC name exceeds bound') + name=data[n+6:n+6+size*2].decode('utf-16-be') + if not re.fullmatch(r'[A-Za-z0-9_. -]{1,128}',name) or name in ('.','..'):raise ValueError('Invalid RCC path') + path=parent+'/'+name if parent else name + if flags&2: + children,first=struct.unpack_from('>II',data,at+6) + if children<1 or first+children>count:raise ValueError('Invalid RCC children') + for i in range(first,first+children):visit(i,path,depth+1) + else: + offset=int.from_bytes(data[at+10:at+14],'big');pos=blobs+offset + if not blobs<=posnames:raise ValueError('Invalid RCC file size') + blob=data[pos+4:pos+4+size] + if flags&1:blob=uncompress(blob,MAX_PACKAGE) + if not path.startswith('vesc_packages/') or not path.endswith('.vescpkg') or path in out:raise ValueError('Unexpected RCC member') + total+=len(blob) + if total>MAX_ARCHIVE or len(out)>=128:raise ValueError('Catalog exceeds bound') + fields(blob);out[path.removeprefix('vesc_packages/')]=blob + visit(0,'',0) + if len(seen)!=count or not out:raise ValueError('Incomplete RCC tree') + return out diff --git a/plugins/vesc/runtime/package_catalog.py b/plugins/vesc/runtime/package_catalog.py new file mode 100644 index 00000000..df27c396 --- /dev/null +++ b/plugins/vesc/runtime/package_catalog.py @@ -0,0 +1,65 @@ +"""One pinned catalogue plus one bounded, operator-imported replacement.""" +import base64 +import json +from pathlib import Path +from .package_archive import archive,metadata,digest,MAX_ARCHIVE,MAX_PACKAGE + +ROOT=Path('/usr/lib/mission-core-vesc/package-catalog') + +class PackageCatalog: + def __init__(self,root,atomic,builtin=ROOT):self.root,self.atomic,self.builtin=root,atomic,builtin;self.cached=None;self.cache_key=None + def load(self): + path=self.root/'package-catalog.json' + key=(path.stat().st_mtime_ns,path.stat().st_size) if path.exists() else None + if self.cached is not None and key==self.cache_key:return self.cached + if path.exists(): + if path.stat().st_size>12*1024*1024:raise ValueError('Package catalogue exceeds storage bound') + value=json.loads(path.read_text());data=base64.b64decode(value['data'],validate=True) + if digest(data)!=value['sha256']:raise ValueError('Stored package catalogue changed') + else: + value=json.loads((self.builtin/'catalog.json').read_text());data=(self.builtin/'vesc_pkg_all.rcc').read_bytes() + if len(data)!=value['bytes'] or digest(data)!=value['sha256']:raise ValueError('Bundled package catalogue changed') + entries=archive(data);self.cached=(value,entries);self.cache_key=key;return self.cached + def imports(self): + path=self.root/'package-imports.json' + if not path.exists():return {} + if path.stat().st_size>12*1024*1024:raise ValueError('Imported packages exceed storage bound') + values=json.loads(path.read_text()) + if len(values)>16:raise ValueError('Too many imported packages') + return values + def listing(self): + version,entries=self.load();items=[metadata(v,k) for k,v in entries.items()] + items+=[{**metadata(base64.b64decode(v['data'],validate=True),v['name']),'library':v['library'],'imported':True} for v in self.imports().values()] + items=[{**i,'description':i['description'][:160]} for i in items] + return {'sha256':version['sha256'],'source':version.get('source','import'),'items':sorted(items,key=lambda i:(i['library'],i['name'].lower()))} + def get(self,key): + _,entries=self.load() + for path,data in entries.items(): + if digest(data)==key:return metadata(data,path),data + item=self.imports().get(key) + if item: + data=base64.b64decode(item['data'],validate=True) + if digest(data)!=key:raise ValueError('Imported package changed') + return {**metadata(data,item['name']),'library':item['library'],'imported':True},data + raise ValueError('Пакет отсутствует в текущем каталоге. Обновите список.') + def save(self,path,value): + size=len(json.dumps(value,ensure_ascii=False).encode()) + occupied=sum(p.stat().st_size for p in self.root.glob('*.json') if p!=path) + if occupied+size>24*1024*1024:raise ValueError('Хранилище каталога заполнено; сохранён резерв для журнала и восстановления.') + self.atomic(path,value) + def publish(self,data,kind,name,library,source): + if kind=='catalog': + items=archive(data);value={'schema':'missioncore.vesc.package-catalog/v1','sha256':digest(data),'bytes':len(data),'source':source,'data':base64.b64encode(data).decode()} + self.save(self.root/'package-catalog.json',value);self.cached=None + return {'count':len(items),'sha256':digest(data)} + if len(data)>MAX_PACKAGE:raise ValueError('Package exceeds bound') + item=metadata(data,name) + _,entries=self.load() + if any(digest(v)==item['id'] for v in entries.values()):return {'id':item['id'],'existing':True} + values=self.imports();values[item['id']]={'name':name,'library':library,'data':base64.b64encode(data).decode()} + if len(values)>16 or sum(len(base64.b64decode(v['data'])) for v in values.values())>MAX_ARCHIVE:raise ValueError('Хранилище импортов заполнено. Удалите ненужный импорт из списка.') + self.save(self.root/'package-imports.json',values);return {'id':item['id']} + def forget(self,key): + values=self.imports() + if key not in values:raise ValueError('Удалять из списка можно только отдельные импорты.') + values.pop(key);self.save(self.root/'package-imports.json',values);return {'removed':True} diff --git a/plugins/vesc/runtime/package_tools.py b/plugins/vesc/runtime/package_tools.py new file mode 100644 index 00000000..778857e1 --- /dev/null +++ b/plugins/vesc/runtime/package_tools.py @@ -0,0 +1,170 @@ +"""Catalogue and whole-extension transactions; no automatic program execution.""" +from collections import OrderedDict +import base64 +import binascii +import json +import re +from datetime import datetime,timezone +from .code_tools import ID,HASH +from .motor_test import Rejected +from .package_archive import digest,MAX_ARCHIVE,MAX_PACKAGE +from .package_catalog import PackageCatalog + +PREFIX='vesc.packages.' +NAMES=('catalog','inspect','download','begin','chunk','load','forget','status','prepare','remove_prepare','restore','apply','reconcile') +ACTIONS=frozenset(PREFIX+n for n in NAMES) +READS=ACTIONS-{PREFIX+'apply'} + +def validate(action,p): + n=action.removeprefix(PREFIX) + shapes={'catalog':set(),'inspect':{'id'},'download':{'id','offset'},'begin':{'kind','name','size','sha256','library','source'},'chunk':{'upload_id','offset','data'},'load':{'upload_id'},'forget':{'id'},'status':set(),'prepare':{'id','compatibility_confirmed'},'remove_prepare':set(),'restore':set(),'apply':{'preview_id','confirmed','inputs_isolated'},'reconcile':set()} + if n not in shapes or set(p)!=shapes[n]:raise ValueError('Invalid package operation parameters') + if 'id' in p and (not isinstance(p['id'],str) or not HASH.fullmatch(p['id'])):raise ValueError('Invalid package digest') + for k in ('upload_id','preview_id'): + if k in p and (not isinstance(p[k],str) or not ID.fullmatch(p[k])):raise ValueError('Invalid package transaction') + if n=='begin': + if p['kind'] not in ('catalog','package') or not isinstance(p['name'],str) or not re.fullmatch(r'[A-Za-z0-9_. -]{1,128}',p['name']) or p['name'] in ('.','..') or type(p['library']) is not bool or p['source'] not in ('import','upstream'):raise ValueError('Invalid package import metadata') + if type(p['size']) is not int or not 5<=p['size']<=(MAX_ARCHIVE if p['kind']=='catalog' else MAX_PACKAGE) or not isinstance(p['sha256'],str) or not HASH.fullmatch(p['sha256']):raise ValueError('Invalid package size/hash') + if 'offset' in p and (type(p['offset']) is not int or p['offset']<0):raise ValueError('Invalid package offset') + if n=='chunk': + if not isinstance(p['data'],str) or not 032:raise ValueError('Too many package imports') + _,entries=self.catalog.load();files=dict(project['imports']);cached={} + def replace(match): + path=match[3] + if path not in entries:raise Rejected('Библиотека не найдена в сохранённом каталоге: '+path) + if path not in cached: + data=entries[path];cached[path]=device.link.rpc('package_unpack',timeout=4,data=base64.b64encode(data).decode(),identity=device.identity,export_library=True) + value=cached[path] + if value['compatible'] is False:raise Rejected('Библиотека несовместима с контроллером: '+path) + tag=match[2].split('@',1)[0].removeprefix('pkg::') if match[2].startswith('pkg::') else None + if tag: + payload=value['library']['imports'].get(tag) + if payload is None:raise Rejected('В библиотеке нет вложения '+tag) + else:payload=base64.b64encode(value['library']['source'].encode()).decode() + name='pkg_'+digest(entries[path])[:16]+'_'+match[5]+'.bin' + if name in files and files[name]!=payload:raise ValueError('Package attachment name collision') + files[name]=payload + return match[1]+'"'+name+'"'+match[4] + source=pattern.sub(replace,project['source']) + return {**project,'source':source,'imports':files} + def supported(self,device): + if not self.code.supported(device):raise Rejected('Установка расширений требует поддерживаемого профиля VESC 6.00. Каталог и импорт доступны без смены прошивки.') + def preview(self,device,images,meta,recovery=False): + self.supported(device);self.code.idle(device,allow_package=True) + if self.code.blocked(device) and not (recovery and self.record(device)):raise Rejected('Сначала проверьте предыдущую запись и остановите Lisp.') + before=self.read(device);key=self.code.remember(self.plans,{**self.code.identity(device),'before':before,'images':images,'meta':meta,'recovery':recovery}) + return {'preview_id':key,'package':meta,'before':{k:{x:v[x] for x in ('sha256','bytes','fullscreen')} for k,v in before.items()},'after':expected(images),'expires_in_s':300,'running_requested':False} + def execute(self,device,action,p,operation,deadline): + n=action.removeprefix(PREFIX) + if n=='catalog':return self.catalog.listing() + if n=='inspect': + value=self.inspect(device,p['id']);value.pop('images');return value + if n=='download': + meta,data=self.catalog.get(p['id']);at=p['offset'] + if at>len(data):raise ValueError('Download offset exceeds package') + return {'id':p['id'],'name':meta['path'].split('/')[-1],'bytes':len(data),'offset':at,'data':base64.b64encode(data[at:at+16384]).decode()} + if n=='forget':return self.catalog.forget(p['id']) + if n=='begin':return {'upload_id':self.code.remember(self.uploads,{**self.code.identity(device),**p,'data':bytearray()}),'chunk_bytes':16384} + if n in ('chunk','load'): + upload=self.uploads.get(p['upload_id']) + if not upload or not self.code.match(device,upload):raise Rejected('Передача истекла или изменился сеанс контроллера.') + if n=='chunk': + raw=base64.b64decode(p['data'],validate=True);at=p['offset'] + if atupload['size']:raise ValueError('Package fragment offset/size mismatch') + upload['data'].extend(raw);upload['at']=self.code.clock();return {'offset':len(upload['data'])} + data=bytes(upload['data']) + if len(data)!=upload['size'] or digest(data)!=upload['sha256']:raise ValueError('Package import checksum mismatch') + value=self.catalog.publish(data,upload['kind'],upload['name'],upload['library'],upload['source']);self.uploads.pop(p['upload_id']);return value + self.supported(device) + if n=='status': + current=self.read(device);installed=self.record(device,'installed');known=bool(installed and installed['identity']==device.identity and same(current,installed['expected'])) + return {'pending':bool(self.record(device)),'installed':installed['meta'] if known else None,'recognized':known,'empty':all(v['bytes']==0 for v in current.values()),'current':{k:{x:v[x] for x in ('sha256','bytes','fullscreen')} for k,v in current.items()}} + if n=='prepare': + value=self.inspect(device,p['id']) + if value['library']:raise Rejected('Библиотека используется как import в Lisp; отдельно на контроллер не устанавливается.') + if value['compatible'] is False:raise Rejected('Автор пакета исключил этот тип контроллера или прошивку.') + if value['compatible'] is None and not p['compatibility_confirmed']:raise Rejected('В пакете нет проверяемых условий совместимости. Подтвердите совместимость по документации автора.') + if not value['fits']:raise Rejected('Размер кода превышает предел flash этого профиля.') + return self.preview(device,value['images'],{k:value[k] for k in ('id','path','name')}) + if n=='remove_prepare':return self.preview(device,{'lisp':'','qml':''},None) + if n=='restore': + record=self.record(device,'backup') + if not record or record['identity']!=device.identity:raise Rejected('Нет исходной копии для этого контроллера и прошивки.') + return self.preview(device,{k:image(v,k) for k,v in record['before'].items()},record.get('previous_meta'),True) + if n=='reconcile':return self.reconcile(device) + plan=self.plans.get(p['preview_id']) + if not plan or not self.code.match(device,plan):raise Rejected('Подтверждение истекло или изменился контроллер.') + return self.apply(device,p['preview_id'],plan,operation,deadline) + def apply(self,device,key,plan,operation,deadline): + self.code.idle(device,allow_package=True) + if self.code.path(device).exists() or self.code.path(device,'execution').exists():raise Rejected('Сначала проверьте запись кода и остановите Lisp.') + if self.record(device) and not plan['recovery']:raise Rejected('Предыдущее изменение расширения не подтверждено.') + if (deadline-datetime.now(timezone.utc)).total_seconds()<330:raise Rejected('Недостаточно времени для записи расширения и проверки.') + before=self.read(device) + if not same(before,plan['before']):raise Rejected('Код изменился после предварительного просмотра.') + installed=self.record(device,'installed');previous=installed['meta'] if installed and installed['identity']==device.identity and same(before,installed['expected']) else None + record={'schema':'missioncore.vesc.package-write/v1','identity':device.identity,'operation_id':operation,'before':before,'expected':expected(plan['images']),'meta':plan['meta'],'previous_meta':previous,'recovery':plan['recovery'],'state':'unknown','started_at':self.utc()} + # One durable recovery copy per controller, retained across restart. + # A recovery attempt must never replace the original backup with a partial result. + if not plan['recovery']:self.atomic(self.path(device,'backup'),record) + self.atomic(self.path(device),record);self.plans.pop(key);self.service.motor.state('rc') + try: + stopped=device.link.rpc('code_control',timeout=8,command='stop',text='') + if stopped.get('acknowledged') is not True:raise ValueError('Lisp stop not acknowledged') + for kind in ('qml','lisp'): + raw=plan['images'][kind] + r=device.link.rpc('code_write',timeout=100,kind=kind,image=raw,erase=not bool(raw),baseline=before[kind]['sha256'],baseline_fullscreen=before[kind]['fullscreen']) + if r.get('verified') is not True:raise ValueError('Missing package readback') + if not same(self.read(device),record['expected']):raise ValueError('Whole package readback mismatch') + self.finish(device,record,'applied');return {'verified':True,'outcome':'applied','running_requested':False} + except (OSError,ValueError,TimeoutError) as error: + record['failure_type']=type(error).__name__;self.atomic(self.path(device),record) + return {'verified':False,'outcome':'unknown','message':'Запись могла выполниться частично. Автоповтора нет. Проверьте содержимое или восстановите исходную копию.'} + def finish(self,device,record,outcome): + if outcome=='applied':self.atomic(self.path(device,'installed'),{'identity':device.identity,'meta':record['meta'],'expected':record['expected']}) + self.atomic(self.path(device,'result'),{'operation_id':record['operation_id'],'outcome':outcome,'finished_at':self.utc()});self.code.clear(self.path(device)) + def reconcile(self,device): + record=self.record(device) + if not record:return {'verified':True,'outcome':'no_pending_write'} + if record['identity']!=device.identity:raise Rejected('Незавершённая запись относится к другой прошивке или контроллеру.') + current=self.read(device);outcome='applied' if same(current,record['expected']) else 'unchanged' if not record.get('recovery') and same(current,record['before']) else 'different' + if outcome!='different':self.finish(device,record,outcome) + return {'verified':outcome!='different','outcome':outcome} diff --git a/plugins/vesc/runtime/preflight_recovery.py b/plugins/vesc/runtime/preflight_recovery.py new file mode 100644 index 00000000..9f9a44ae --- /dev/null +++ b/plugins/vesc/runtime/preflight_recovery.py @@ -0,0 +1,40 @@ +"""Read-only recovery of missing bound devices before motor ownership began.""" +import copy +import re + +from .release_observation import ReleaseObservation + + +class PreflightRecovery: + def __init__(self, profile): + self.profile = copy.deepcopy(profile) + self.proof = None + + def reset(self): + self.proof = None + + def check(self, profile, devices, now, receiver_active, limits_pending): + if profile != self.profile: + self.reset() + return False + selected = [] + for binding in self.profile["bindings"].values(): + matches = [d for d in devices if d.id == binding["device_id"]] + if len(matches) != 1: + self.reset() + return False + d = matches[0] + expected = binding.get("uuid", "") + if (not re.fullmatch(r"[0-9a-f]{24}", expected) + or d.identity.get("uuid") != expected + or getattr(d, "identified_session", None) != d.session + or not d.link or not getattr(d.link, "alive", True) + or limits_pending(d)): + self.reset() + return False + selected.append(d) + if not selected: + return False + if self.proof is None: + self.proof = ReleaseObservation(selected, now) + return self.proof.check(selected, now, receiver_active) diff --git a/plugins/vesc/runtime/qml_broker.py b/plugins/vesc/runtime/qml_broker.py new file mode 100644 index 00000000..e0e7e211 --- /dev/null +++ b/plugins/vesc/runtime/qml_broker.py @@ -0,0 +1,91 @@ +"""Typed, rate-limited reads between isolated QML and the sole USB owner. + +No raw packet forwarding, writes, terminal, CAN routing, captures or code execution. +No background acquisition: a bounded batch is serviced on an operator frame request. +""" + +import base64 +from collections import OrderedDict + +from .motor_test import Rejected + +READ_CODES = frozenset((0, 4, 14, 17, 31, 32, 33, 65, 96)) + + +def read_intent(value): + if not isinstance(value, dict): + raise ValueError("Invalid QML read intent") + command = value.get("command") + if type(command) is not int or command not in READ_CODES: + raise ValueError("QML command is not a permitted read") + if set(value) != ({"command", "mask"} if command == 65 else {"command"}): + raise ValueError("Invalid QML read shape") + if command == 65 and (type(value["mask"]) is not int or not 0 <= value["mask"] <= 65535): + raise ValueError("Invalid IMU mask") + return dict(value) + + +class QmlBroker: + def __init__(self, clock): + self.clock = clock + self.pending = OrderedDict() + self.last = {} + self.batch_at = float("-inf") + self.reads = 0 + self.observed_at = None + + def enqueue(self, frame): + requests = frame.get("read_requests", []) + if not isinstance(requests, list) or len(requests) > 9: + raise ValueError("QML read queue exceeded") + # Validate the entire untrusted batch before any USB operation. + intents = [read_intent(v) for v in requests] + for intent in intents: + self.pending[intent["command"]] = intent + + def exchange(self, device, service, worker, frame): + self.enqueue(frame) + now = self.clock() + packets = [] + if self.pending and now - self.batch_at >= 0.5: + service.code_tools.idle(device) + if not device.readable or not device.link: + raise Rejected("Контроллер недоступен для чтения QML.") + if ( + service.code_tools.pending(device) + or service.code_tools.path(device, "execution").exists() + ): + raise Rejected("Сначала проверьте предыдущее действие программы VESC.") + self.batch_at = now + for code, intent in list(self.pending.items()): + cooldown = 10 if code in (0, 14, 17) else 1 + if now - self.last.get(code, float("-inf")) < cooldown: + continue + # Existing owner builds a typed upstream request; never raw bytes from QML. + result = device.link.rpc("qml_read", timeout=1.2, intent=intent) + packet = base64.b64decode(result["payload"], validate=True) + if not 1 <= len(packet) <= 32768 or packet[0] != code: + raise ValueError("QML read response does not match request") + packets.append(base64.b64encode(packet).decode()) + del self.pending[code] + self.last[code] = self.clock() + self.reads += 1 + self.observed_at = service.qml_utc() + if len(packets) == 2: + break + if packets: + frame = worker.exchange({"op": "frame", "events": [], "packets": packets}) + self.enqueue(frame) + return { + **frame, + "hardware_access": True, + "direct_hardware_access": False, + "broker_status": { + "mode": "read_only", + "reads": self.reads, + "pending": len(self.pending), + "observed_at": self.observed_at, + "max_reads_per_frame": 2, + "background_reads": False, + }, + } diff --git a/plugins/vesc/runtime/qml_preview.py b/plugins/vesc/runtime/qml_preview.py new file mode 100644 index 00000000..ce135192 --- /dev/null +++ b/plugins/vesc/runtime/qml_preview.py @@ -0,0 +1,316 @@ +"""Bounded Qt Quick sessions with an optional typed read-only hardware broker.""" + +import base64 +import hashlib +import json +import subprocess +import tempfile +import time +import uuid +from collections import OrderedDict +from pathlib import Path + +from .motor_test import Rejected +from .qml_broker import QmlBroker +from .qml_session import QmlSession + +PREFIX = "vesc.qml." +ACTIONS = frozenset(PREFIX + n for n in ("begin", "chunk", "render", "open", "frame", "close")) + + +def validate(action, p): + name = action.removeprefix(PREFIX) + shapes = { + "begin": {"size", "sha256"}, + "chunk": {"upload_id", "offset", "data"}, + "render": {"upload_id"}, + "open": {"upload_id", "snapshot"}, + "frame": {"qml_id", "events"}, + "close": {"qml_id"}, + } + if name not in shapes or set(p) not in ( + [shapes[name], shapes[name] | {"broker"}] if name == "open" else [shapes[name]] + ): + raise ValueError("Invalid QML preview parameters") + + def identifier(value, prefix, size): + return ( + isinstance(value, str) + and value.startswith(prefix) + and len(value) == len(prefix) + size + and all(c in "0123456789abcdef" for c in value[len(prefix) :]) + ) + + if name == "begin" and ( + type(p["size"]) is not int + or not 1 <= p["size"] <= 120 * 1024 + or not identifier(p["sha256"], "", 64) + ): + raise ValueError("Invalid QML preview size/hash") + if "upload_id" in p and not identifier(p["upload_id"], "qml_", 32): + raise ValueError("Invalid QML upload identity") + if name == "open" and type(p["snapshot"]) is not bool: + raise ValueError("Invalid snapshot selection") + if "broker" in p and (type(p["broker"]) is not bool or (p["broker"] and not p["snapshot"])): + raise ValueError("QML broker requires controller context") + if "qml_id" in p and not identifier(p["qml_id"], "view_", 32): + raise ValueError("Invalid QML session identity") + if name == "frame": + events = p["events"] + if not isinstance(events, list) or len(events) > 32: + raise ValueError("Too many QML input events") + keys = { + "Enter", + "Tab", + "Backspace", + "Delete", + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "Home", + "End", + "Escape", + "SelectAll", + } + for event in events: + if not isinstance(event, dict): + raise ValueError("Invalid QML input") + kind = event.get("kind") + fields = { + "down": {"x", "y"}, + "up": {"x", "y"}, + "move": {"x", "y"}, + "wheel": {"x", "y", "delta"}, + "text": {"text"}, + "key": {"key"}, + } + if kind not in fields or set(event) != fields[kind] | {"kind"}: + raise ValueError("Invalid QML input shape") + for axis, limit in (("x", 640), ("y", 480)): + if axis in event and ( + type(event[axis]) not in (int, float) or not 0 <= event[axis] < limit + ): + raise ValueError("QML input outside frame") + if kind == "wheel" and (type(event["delta"]) is not int or abs(event["delta"]) > 1200): + raise ValueError("Invalid wheel delta") + if kind == "text" and ( + not isinstance(event["text"], str) + or len(event["text"]) > 1024 + or "\0" in event["text"] + ): + raise ValueError("Invalid QML text") + if kind == "key" and event["key"] not in keys: + raise ValueError("Invalid QML key") + if name == "chunk": + if ( + type(p["offset"]) is not int + or p["offset"] < 0 + or not isinstance(p["data"], str) + or not 0 < len(p["data"]) <= 22000 + ): + raise ValueError("Invalid QML fragment") + data = base64.b64decode(p["data"], validate=True) + if not 0 < len(data) <= 16384 or base64.b64encode(data).decode() != p["data"]: + raise ValueError("Invalid QML fragment encoding") + + +def render_native(request): + group = Path("/sys/fs/cgroup") / Path("/proc/self/cgroup").read_text().strip().split("::", 1)[ + 1 + ].lstrip("/") + maximum = (group / "memory.max").read_text().strip() + current = int((group / "memory.current").read_text()) + if maximum == "max" or int(maximum) < 1024**3 or current > 384 * 1024**2: + raise Rejected("Недостаточно свободной памяти в службе для предпросмотра QML.") + root = Path("/usr/lib/mission-core-vesc/native") + env = { + "PATH": "/usr/bin:/bin", + "LANG": "C", + "LC_ALL": "C", + "HOME": "/nonexistent", + "LD_LIBRARY_PATH": str(root / "lib"), + "QT_PLUGIN_PATH": str(root / "plugins"), + "QT_QPA_PLATFORM": "offscreen", + "QT_QUICK_BACKEND": "software", + "QML_DISABLE_DISK_CACHE": "1", + "QV4_FORCE_INTERPRETER": "1", + } + try: + # One child, synchronous bounded lifetime; communicate kills and reaps on timeout. + with tempfile.TemporaryDirectory(prefix="qml-", dir="/run/mission-core-vesc") as runtime: + env["XDG_RUNTIME_DIR"] = runtime + p = subprocess.run( + [str(root / "bin/mission-core-vesc-qml-preview")], + input=json.dumps(request).encode(), + capture_output=True, + env=env, + timeout=6, + close_fds=True, + ) + except subprocess.TimeoutExpired as error: + raise Rejected( + "Предпросмотр QML остановлен: код не завершился за отведённое время." + ) from error + if len(p.stdout) > 800 * 1024 or len(p.stderr) > 8192: + raise Rejected("Предпросмотр QML превысил размер ответа.") + try: + result = json.loads(p.stdout) + except (ValueError, UnicodeError) as error: + raise Rejected("Qt Quick не смог построить предпросмотр.") from error + if result.get("hardware_access") is not False or result.get("snapshot_only") is not True: + raise ValueError("QML preview contract mismatch") + if not result.get("ok") or p.returncode: + return { + "rendered": False, + "warnings": result.get("warnings", [])[:16], + "error": result.get("error", "Qt Quick не построил кадр."), + } + raw = base64.b64decode(result["png"], validate=True) + if ( + len(raw) > 512 * 1024 + or not raw.startswith(b"\x89PNG\r\n\x1a\n") + or (result["width"], result["height"]) != (640, 480) + ): + raise ValueError("Invalid QML frame") + return {**result, "rendered": True} + + +class QmlPreview: + def __init__(self, service, renderer=render_native, clock=time.monotonic): + self.service, self.renderer, self.clock = service, renderer, clock + self.uploads = OrderedDict() + self.session = None + self.session_factory = QmlSession + + def close_session(self): + if self.session: + self.session["worker"].close() + self.session = None + + def maintain(self, devices): + if self.session and ( + self.session["worker"].expired() + or not any( + d.id == self.session["device"] + and d.session == self.session["session"] + and d.link is not None + for d in devices + ) + ): + self.close_session() + + def execute(self, device, action, p): + now = self.clock() + for key, value in list(self.uploads.items()): + if now - value["at"] >= 300: + del self.uploads[key] + name = action.removeprefix(PREFIX) + identity = {"device": device.id, "session": device.session} + if name in ("frame", "close"): + session = self.session + if ( + not session + or session["id"] != p["qml_id"] + or any(session[k] != v for k, v in identity.items()) + ): + raise Rejected("Сеанс QML истёк или контроллер переподключён.") + if name == "close": + self.close_session() + return {"closed": True} + if session["worker"].expired(): + self.close_session() + raise Rejected("Сеанс QML завершён. Откройте интерфейс заново.") + try: + frame = session["worker"].exchange({"op": "frame", "events": p["events"]}) + if session.get("broker"): + frame = session["broker"].exchange( + device, self.service, session["worker"], frame + ) + return {**frame, "qml_id": session["id"], "observed_at": session["observed_at"]} + except BaseException: + self.close_session() + raise + if name == "begin": + while len(self.uploads) >= 2: + self.uploads.popitem(last=False) + key = "qml_" + uuid.uuid4().hex + self.uploads[key] = {**identity, **p, "at": now, "data": bytearray()} + return {"upload_id": key, "chunk_bytes": 16384} + upload = self.uploads.get(p["upload_id"]) + if not upload or any(upload[k] != v for k, v in identity.items()): + raise Rejected("Передача QML истекла или сеанс контроллера изменился.") + if name == "chunk": + raw = base64.b64decode(p["data"], validate=True) + offset = p["offset"] + if offset < len(upload["data"]) and upload["data"][offset : offset + len(raw)] == raw: + return {"offset": len(upload["data"])} + if offset != len(upload["data"]) or offset + len(raw) > upload["size"]: + raise ValueError("QML fragment offset/size mismatch") + upload["data"].extend(raw) + return {"offset": len(upload["data"])} + raw = bytes(upload["data"]) + if len(raw) != upload["size"] or hashlib.sha256(raw).hexdigest() != upload["sha256"]: + raise ValueError("QML source checksum mismatch") + source = raw.decode("utf-8") + if not source.strip() or "\0" in source: + raise ValueError("Empty or invalid QML source") + if name == "open": + self.close_session() + broker = p.get("broker", False) + if broker and "qml_read" not in (getattr(device.link, "engine", None) or {}).get( + "contract", {} + ).get("methods", []): + raise Rejected("Обновите бортовое ядро для аппаратного QML-брокера.") + snapshot = name == "render" or p.get("snapshot", False) + if snapshot: + self.service.code_tools.idle(device) + if snapshot and not device.readable: + raise Rejected("Для предпросмотра нужна поддерживаемая схема контроллера.") + configs = {} + for kind, command in (("motor", 14), ("application", 17)) if snapshot else (): + packet = device.link.query(command) + configs[kind] = { + "encoding": "base64", + "payload": base64.b64encode(packet).decode(), + "bytes": len(packet), + "sha256": hashlib.sha256(packet).hexdigest(), + } + value = device.link.query(4) if snapshot else b"" + observed_at = self.service.qml_utc() + del self.uploads[p["upload_id"]] + request = { + "identity": dict(device.identity), + "configs": configs, + "values": base64.b64encode(value).decode(), + "source": source, + "width": 640, + "height": 480, + "standalone": not snapshot, + "broker": broker, + } + if name == "open": + worker = self.session_factory(request) + key = "view_" + uuid.uuid4().hex + self.session = { + **identity, + "id": key, + "worker": worker, + "observed_at": observed_at, + "broker": QmlBroker(self.clock) if broker else None, + } + try: + frame = worker.initial + if broker: + frame = self.session["broker"].exchange(device, self.service, worker, frame) + return {**frame, "qml_id": key, "observed_at": observed_at} + except BaseException: + self.close_session() + raise + result = self.renderer(request) + return { + **result, + "observed_at": observed_at, + "source_sha256": upload["sha256"], + "snapshot_only": True, + } diff --git a/plugins/vesc/runtime/qml_session.py b/plugins/vesc/runtime/qml_session.py new file mode 100644 index 00000000..8778d69b --- /dev/null +++ b/plugins/vesc/runtime/qml_session.py @@ -0,0 +1,162 @@ +"""One bounded Qt Quick child with no device FD; broker intents are parent-validated.""" + +import base64 +import json +import os +import select +import subprocess +import tempfile +import time +from pathlib import Path + +from .motor_test import Rejected + + +def environment(): + group = Path("/sys/fs/cgroup") / Path("/proc/self/cgroup").read_text().strip().split("::", 1)[ + 1 + ].lstrip("/") + maximum = (group / "memory.max").read_text().strip() + if ( + maximum == "max" + or int(maximum) < 1024**3 + or int((group / "memory.current").read_text()) > 384 * 1024**2 + ): + raise Rejected("Недостаточно свободной памяти в службе для QML.") + root = Path("/usr/lib/mission-core-vesc/native") + return root, { + "PATH": "/usr/bin:/bin", + "LANG": "C", + "LC_ALL": "C", + "HOME": "/nonexistent", + "LD_LIBRARY_PATH": str(root / "lib"), + "QT_PLUGIN_PATH": str(root / "plugins"), + "QT_QPA_PLATFORM": "offscreen", + "QT_QUICK_BACKEND": "software", + "QML_DISABLE_DISK_CACHE": "1", + "QV4_FORCE_INTERPRETER": "1", + } + + +def checked_frame(result): + if ( + not isinstance(result, dict) + or result.get("hardware_access") is not False + or type(result.get("snapshot_only")) is not bool + or result["snapshot_only"] == (result.get("broker") is True) + or result.get("sandbox_verified") is not True + ): + raise Rejected("Не подтверждена изоляция QML.") + if not result.get("ok"): + raise Rejected(str(result.get("error", "Qt Quick не построил кадр."))[:320]) + raw = base64.b64decode(result["png"], validate=True) + if ( + len(raw) > 512 * 1024 + or not raw.startswith(b"\x89PNG\r\n\x1a\n") + or (result["width"], result["height"]) != (640, 480) + ): + raise Rejected("Некорректный кадр QML.") + return {**result, "rendered": True} + + +class QmlSession: + def __init__(self, request): + self.process = None + self.directory = None + self.buffer = b"" + self.at = self.used = time.monotonic() + self.count = 0 + self.broker = request.get("broker", False) + root, env = environment() + try: + self.directory = tempfile.TemporaryDirectory( + prefix="qml-", dir="/run/mission-core-vesc" + ) + env["XDG_RUNTIME_DIR"] = self.directory.name + self.process = subprocess.Popen( + [str(root / "bin/mission-core-vesc-qml-preview")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + env=env, + close_fds=True, + bufsize=0, + ) + os.set_blocking(self.process.stdin.fileno(), False) + os.set_blocking(self.process.stdout.fileno(), False) + self.initial = self.exchange({**request, "interactive": True}) + except BaseException: + self.close() + raise + + def alive(self): + return self.process is not None and self.process.poll() is None + + def expired(self): + return ( + not self.alive() + or time.monotonic() - self.at >= 300 + or time.monotonic() - self.used >= 60 + or self.count >= 240 + ) + + def exchange(self, request): + deadline = time.monotonic() + 6 + try: + raw = json.dumps(request, allow_nan=False).encode() + b"\n" + if len(raw) > 512 * 1024: + raise ValueError("QML request exceeds bound") + while raw: + if ( + not self.alive() + or not select.select( + [], [self.process.stdin], [], max(0, deadline - time.monotonic()) + )[1] + ): + raise TimeoutError("QML input timed out") + size = os.write(self.process.stdin.fileno(), raw[:4096]) + if size <= 0: + raise OSError("QML input closed") + raw = raw[size:] + while b"\n" not in self.buffer: + if ( + not self.alive() + or not select.select( + [self.process.stdout], [], [], max(0, deadline - time.monotonic()) + )[0] + ): + raise TimeoutError("QML frame timed out") + chunk = os.read(self.process.stdout.fileno(), 65536) + if not chunk: + raise OSError("QML process exited") + self.buffer += chunk + if len(self.buffer) > 800 * 1024: + raise ValueError("QML response exceeds bound") + line, self.buffer = self.buffer.split(b"\n", 1) + result = checked_frame(json.loads(line)) + if ( + result.get("interactive") is not True + or (result.get("broker") is True) != self.broker + ): + raise ValueError("Interactive QML protocol missing") + self.used = time.monotonic() + self.count += 1 + return result + except (ValueError, KeyError, OSError, TimeoutError, Rejected) as error: + self.close() + raise Rejected("Сеанс QML завершён: " + str(error)[:240]) from error + + def close(self): + if self.process: + if self.alive(): + self.process.kill() + try: + self.process.wait(timeout=2) + except subprocess.TimeoutExpired as error: + raise Rejected("Прежний процесс QML ещё завершается.") from error + for stream in (self.process.stdin, self.process.stdout): + if stream: + stream.close() + if self.directory: + self.directory.cleanup() + self.directory = None diff --git a/plugins/vesc/runtime/read_cache.py b/plugins/vesc/runtime/read_cache.py new file mode 100644 index 00000000..8dd9c9b3 --- /dev/null +++ b/plugins/vesc/runtime/read_cache.py @@ -0,0 +1,37 @@ +"""Bounded snapshots, separate from durable configuration backups and write receipts.""" +from collections import OrderedDict +import json +import time + +SNAPSHOT_ACTIONS = frozenset({"vesc.tools.read", "vesc.terminal.read", "vesc.firmware.status", "vesc.configuration.read", "vesc.configuration.preview", "vesc.diagnostics.read"}) +EXPIRED = {"state": "error", "error": "Снимок больше не хранится. Прочитайте данные заново."} + + +class ReadCache: + def __init__(self, *, count=8, bytes_limit=8 * 1024**2, ttl=600, clock=time.monotonic): + self.items = OrderedDict() + self.count, self.bytes_limit, self.ttl, self.clock = count, bytes_limit, ttl, clock + self.bytes = 0 + + def prune(self): + for key, (at, size, _) in list(self.items.items()): + if self.clock() - at >= self.ttl: + del self.items[key] + self.bytes -= size + + def put(self, key, receipt): + raw = json.dumps(receipt, ensure_ascii=False, allow_nan=False).encode() + if len(raw) > self.bytes_limit: + raise ValueError("Read snapshot exceeds cache bound") + self.prune() + if key in self.items: + self.bytes -= self.items.pop(key)[1] + while self.items and (len(self.items) >= self.count or self.bytes + len(raw) > self.bytes_limit): + self.bytes -= self.items.popitem(last=False)[1][1] + self.items[key] = (self.clock(), len(raw), raw) + self.bytes += len(raw) + + def get(self, key): + self.prune() + entry = self.items.get(key) + return json.loads(entry[2]) if entry else dict(EXPIRED) diff --git a/plugins/vesc/runtime/release_observation.py b/plugins/vesc/runtime/release_observation.py new file mode 100644 index 00000000..71d11eb4 --- /dev/null +++ b/plugins/vesc/runtime/release_observation.py @@ -0,0 +1,132 @@ +"""Read-only evidence of settled release, tied to the stopped attachments. + +GET_VALUES current averages span reads. A failed immediate cleanup read is not +a permanent description of the controller. Require a new whole-profile neutral +window; never extend a command lease or transfer motor authority here. +""" + +import math +import re + +# The same electrical standstill envelope is used by release observation and +# configuration writes. GET_VALUES may report sub-amp idle sensor offset. +IDLE_BOUNDS = ( + ("motor_current_a", 1), + ("input_current_a", 1), + ("duty", 0.001), + ("erpm", 1), + ("fault_code", 0), +) + +NOTICE = "Снятие тока не подтверждено. Проверьте фактическое состояние моторов." + + +def settlement_pending(evidence): + """A successful release with finite readback may still be settling. + + This classifies a normal input-ended cleanup only. It does not confirm + release, grant authority, or excuse transport/configuration/device faults. + """ + devices = (evidence or {}).get("devices", {}) + return bool(devices) and all( + item.get("send", {}).get("sent") is True + and item.get("reason") in ("neutral_readback", "non_neutral_readback") + and all(type(item.get("values", {}).get(k)) in (int, float) + and math.isfinite(item["values"][k]) + for k in ("motor_current_a", "input_current_a", "duty", "erpm", "fault_code")) + and item["values"]["fault_code"] == 0 + for item in devices.values() + ) + + +class ReleaseObservation: + def __init__(self, devices, started_at): + self.attachments = {d.id: getattr(d, "session", None) for d in devices} + self.identities = {d.id: (getattr(d, "identity", None) or {}).get("uuid") for d in devices} + self.started_at = started_at + self.reset() + + def reset(self): + self.since = None + self.previous = {} + self.count = 0 + + def faulted(self, devices, now): + """Retain a real firmware fault seen while waiting for settlement.""" + for d in devices: + try: + s = d.sample + code = s["values"]["fault_code"] + if (d.session == self.attachments.get(d.id) == s["session_id"] + and d.link and getattr(d.link, "alive", True) + and self.started_at <= s["sampled_at"] <= now + and now - s["sampled_at"] <= .5 + and math.isfinite(code) and code != 0): + return True + except (KeyError, TypeError, ValueError, AttributeError): + continue + return False + + def check(self, devices, now, receiver_active): + stamps = {} + try: + if ( + not self.attachments + or len(devices) != len(self.attachments) + or {d.id for d in devices} != set(self.attachments) + ): + raise ValueError("Incomplete release observation") + # A new attachment can prove CURRENT neutral state only after its + # physical UUID was identified again. It never confirms old output. + for d in devices: + expected = self.identities[d.id] + if expected and (getattr(d, "identity", None) or {}).get("uuid") != expected: + raise ValueError("Controller identity changed") + if any(d.session != self.attachments[d.id] for d in devices): + if not all(re.fullmatch(r"[0-9a-f]{24}", self.identities[d.id] or "") + and getattr(d, "identified_session", None) == d.session + and d.link and getattr(d.link, "alive", True) for d in devices): + raise ValueError("New attachment identity is not verified") + self.attachments = {d.id: d.session for d in devices} + self.started_at = now + self.reset() + return False + for d in devices: + sample = d.sample + if ( + not self.attachments[d.id] + or d.session != self.attachments[d.id] + or not d.link + or not getattr(d.link, "alive", True) + or not sample + or sample["session_id"] != d.session + ): + raise ValueError("Attachment changed") + at = sample["sampled_at"] + if ( + not math.isfinite(at) + or at < self.started_at + or not 0 <= now - at <= 0.5 + or at <= self.previous.get(d.id, -math.inf) + ): + raise ValueError("No new release sample") + value = sample["values"] + if any( + not math.isfinite(value[k]) or abs(value[k]) > bound + for k, bound in IDLE_BOUNDS + ): + raise ValueError("Controller is not idle") + if receiver_active(d.id, sample["receiver"]["level"]): + raise ValueError("Receiver requests output") + stamps[d.id] = at + # Gaps restart the proof; old samples cannot bridge missing data. + if self.previous and any(stamps[k] - self.previous[k] > 0.5 for k in stamps): + self.reset() + except (KeyError, TypeError, ValueError, AttributeError): + self.reset() + return False + if self.since is None: + self.since = max(stamps.values()) + self.previous = stamps + self.count += 1 + return self.count >= 3 and min(stamps.values()) - self.since >= 0.5 diff --git a/plugins/vesc/runtime/remote_control.py b/plugins/vesc/runtime/remote_control.py index 9966af1a..11defcd5 100644 --- a/plugins/vesc/runtime/remote_control.py +++ b/plugins/vesc/runtime/remote_control.py @@ -15,6 +15,13 @@ from datetime import datetime, timedelta, timezone from .group_test import batch from .protocol import ppm, values from .drive_profile import LAYOUTS, slot_label +from .remote_duty import DutyOutput +from .configuration import decode +from .diagnostics import failure +from .drive_diagnostics import DriveDiagnostics +from . import remote_limits +from .release_observation import NOTICE as RELEASE_NOTICE, ReleaseObservation, settlement_pending +from .preflight_recovery import PreflightRecovery class ControlEnded(ValueError): @@ -28,6 +35,7 @@ class InputLease: self.sequence = -1 self.until = 0 self.demand = (0., 0.) + self.settings = None self.retired = set() def accept(self, command): @@ -40,10 +48,12 @@ class InputLease: or not 0 < command["ttl_ms"] <= 400): raise ValueError("Invalid control bounds") s = command["settings"] - if (not isinstance(s, dict) or set(s) != {"standstill_confirmed","current_a","max_erpm"} + duty = isinstance(s, dict) and "max_duty_percent" in s + speed_key, low, high = ("max_duty_percent", 1, 100) if duty else ("max_erpm", 300, 3000) + if (not isinstance(s, dict) or set(s) != {"standstill_confirmed","current_a",speed_key} or s["standstill_confirmed"] is not True - or type(s["current_a"]) not in (int,float) or not .5 <= s["current_a"] <= 30 - or type(s["max_erpm"]) not in (int,float) or not 300 <= s["max_erpm"] <= 3000): + or type(s["current_a"]) not in (int,float) or not math.isfinite(s["current_a"]) or s["current_a"] < .5 + or type(s[speed_key]) not in (int,float) or not low <= s[speed_key] <= high): raise ValueError("Invalid control settings") if command["id"] in self.retired: return False @@ -52,7 +62,11 @@ class InputLease: return False if self.id == command["id"] and command["sequence"] <= self.sequence: return False # Repeated frames cannot extend a lease. + if self.id == command["id"] and s != self.settings: + self.stop() + raise ValueError("Control settings changed during the session") self.id, self.sequence = command["id"], command["sequence"] + self.settings = copy.deepcopy(s) self.until = self.clock()+command["ttl_ms"]/1000 self.demand = (command["left"], command["right"]) return True @@ -73,6 +87,7 @@ class InputLease: class RemoteControl: def __init__(self, service): self.service = service + self.trace = DriveDiagnostics(getattr(service,"root","/tmp/mission-core-vesc-test")) self.lock = threading.RLock() self.lease = InputLease() self.instance = uuid.uuid4().hex @@ -82,8 +97,11 @@ class RemoteControl: self.watch_until = 0 self.state = "observing" self.message = None - self.readings = {} self.release_confirmed = None + self.release_evidence = None + self.pending_release = None + self.pending_availability = None + self.last_stop = None def feed(self, body): if (set(body) != {"watch","command","relay_id"} or type(body["watch"]) is not bool @@ -91,6 +109,7 @@ class RemoteControl: raise ValueError("Invalid relay") with self.lock: if self.relay != body["relay_id"]: + self.trace.add("relay_changed", session_id=self.lease.id) self.lease.stop() self.relay = body["relay_id"] self.primed = False @@ -98,6 +117,7 @@ class RemoteControl: self.watch_until = time.monotonic()+2 command = body["command"] if command is None: + if self.lease.live():self.trace.add("intent_retired",session_id=self.lease.id,sequence=self.lease.sequence) self.primed = True self.lease.stop() elif not self.primed: @@ -108,20 +128,68 @@ class RemoteControl: self.lease.id = None self.lease.sequence = -1 accepted = self.lease.accept(command) + self.trace.add("input",session_id=command["id"],sequence=command["sequence"], + ttl_ms=command["ttl_ms"],left=command["left"],right=command["right"],accepted=accepted, + state=self.state,lease_remaining_ms=max(0,(self.lease.until-time.monotonic())*1000)) if accepted and not running: self.state, self.message = "preparing", None + # This new lease has not applied output or checked release + # yet. Never inherit the previous session's failed release, + # nor claim success: normal neutral/pending-limit preflight + # must still complete before drive() can take ownership. + self.release_confirmed = None + self.release_evidence = None + self.pending_release = None + self.pending_availability = None self.thread = threading.Thread(target=self._prepare, args=(copy.deepcopy(command),), daemon=True, name="vesc-remote-control") self.thread.start() return self.snapshot() + def observe_snapshot(self): + """Renew read interest only. Never change relay, input lease or outputs.""" + with self.lock: + self.watch_until = time.monotonic() + 2 + return self.snapshot() + def snapshot(self): with self.lock: - readings = [{**copy.deepcopy(v), "age_ms": int((time.monotonic()-v["sampled_at"])*1000)} for v in self.readings.values()] - for v in readings: v.pop("sampled_at", None) - return {"supported": True, "instance": self.instance, "state": self.state, + # Samples belong to a live attachment generation, never a UUID cache. + # Discovery removes old generations before closing them; no serial lock + # or I/O is taken while projecting a snapshot. + with self.service.lock: + devices = [{**d.__dict__, "readable": getattr(d, "readable", False)} + for d in self.service.devices.values()] + ids = [d["id"] for d in devices] + profile = self.service.drive.value + readings = [] + initializing = [] + for d in devices: + sample = d.get("sample") + # Identity and the initial sample are distinct milestones of + # this live attachment. Cached inventory/old generations cannot + # claim initialization, nor can a failed/disconnected reader. + if (d.get("session") and ids.count(d["id"]) == 1 + and d.get("identified_session") == d["session"] + and d["link"] and getattr(d["link"], "alive", True) + and d["readable"] and not d.get("error") + and (not sample or sample["session_id"] != d["session"])): + initializing.append(d["id"]) + if (not sample or sample["session_id"] != d["session"] or ids.count(d["id"]) != 1 + or not d["link"] or not getattr(d["link"], "alive", True)): + continue + slot = next((k for k, v in profile["bindings"].items() if v["device_id"] == d["id"]), None) + readings.append({"id": d["id"], "uuid": d["identity"]["uuid"], "slot": slot, + "label": slot_label(profile["layout"], slot) if slot else "VESC " + d["identity"]["uuid"][:6].upper(), + "session_id": sample["session_id"], "sample_time_ms": sample["sampled_at"] * 1000, + "observed_at": sample.get("observed_at"), "values": copy.deepcopy(sample["values"]), + "receiver": copy.deepcopy(sample["receiver"]), "current_limits": remote_limits.projection(d), + "age_ms": max(0, int((time.monotonic() - sample["sampled_at"]) * 1000))}) + return {"supported": True, "control_modes": ["rpm", "duty"], "instance": self.instance, "state": self.state, + "control_active": self.lease.live() or bool(self.thread and self.thread.is_alive()), "session_id": self.lease.id, "message": self.message, "devices": readings, - "release_confirmed": self.release_confirmed, + "observation": {"initializing_devices": initializing}, + "release_confirmed": self.release_confirmed, "last_stop": copy.deepcopy(self.last_stop), "profile": copy.deepcopy(self.service.drive.value)} def observe(self): @@ -130,31 +198,121 @@ class RemoteControl: # the control worker is waiting to become the exclusive owner. if self.thread is not None and self.thread.is_alive(): return - if time.monotonic() >= self.watch_until or not self.service.operation_lock.acquire(False): + firmware_owner = None + with self.service.firmware_update.lock: + if self.service.firmware_update.active: + firmware_owner = self.service.firmware_update.active['device_id'] + operation_owned = self.service.operation_lock.acquire(False) + if not operation_owned and firmware_owner is None: return try: - with self.service.lock: devices = [d for d in self.service.devices.values() if d.link and d.readable] - # Reading is explicit window interest, never discovery-port reset. + with self.service.lock: devices = [d for d in self.service.devices.values() if not self.service.firmware_update.owns(d) and d.link and d.readable] + ids = [d.id for d in devices] + # One initial read per connection even without an open viewer. Further + # reads require live window interest; discovery never resets USB ports. for d in devices: + if ids.count(d.id) != 1 or (d.sample is not None and time.monotonic() >= self.watch_until + and not self.trace.active() and self.pending_release is None + and self.pending_availability is None): continue if not d.lock.acquire(False): continue try: - self._publish(d, values(d.link.query(4, timeout=.06)), ppm(d.link.query(31, timeout=.06))) - except (OSError, ValueError, TimeoutError): - pass # Old values retain age; a read failure is never zero. + # Passive observation has no output lease. A CAN send may take + # up to 200 ms across the bounded SDK owner; the USB motor + # loop's 60 ms budget is not a valid observer deadline here. + from .can_bridge import Attachment as CanAttachment + timeout = .3 if isinstance(d.attachment, CanAttachment) else .06 + self._publish(d, values(d.link.query(4, timeout=timeout)), ppm(d.link.query(31, timeout=timeout))) + known = getattr(d, "drive_limits", None) + if (d.identity.get("version") == "5.02" and (not known or known["session_id"] != d.session + or time.monotonic() - known["sampled_at"] > 30)): + remote_limits.publish(d, decode(d.link.query(14), "motor")) + except Exception as error: + d.failed(error, "observation") finally: d.lock.release() - finally: self.service.operation_lock.release() + if operation_owned: + self._reconcile_release(devices) + self._reconcile_preflight(devices) + finally: + if operation_owned: self.service.operation_lock.release() + + def _await_release(self, devices): + with self.lock: + self.pending_release = ReleaseObservation(devices, time.monotonic()) + + def _reconcile_preflight(self, devices): + # Only the missing-device preflight path creates this observer. No + # motor output/configuration was attempted, so it cannot invent a + # historical release ACK or clear an unrelated execution fault. + with self.lock: + pending = self.pending_availability + if pending is None: + return + with self.service.firmware_update.lock: + firmware_active = self.service.firmware_update.active is not None + if (self.lease.live() or (self.thread and self.thread.is_alive()) + or self.service.motor.active or firmware_active): + pending.reset() + return + if not pending.check(self.service.drive.value, devices, time.monotonic(), + self.service.motor.receiver_active, self.service.motor.limits.pending): + return + self.pending_availability = None + self.state, self.message = "stopped", None + if self.last_stop is not None: + self.last_stop["recovered_at"] = datetime.now(timezone.utc).isoformat() + self.trace.add("preflight_availability_recovered", session_id=self.lease.id) + + def _reconcile_release(self, devices): + # Called under the existing observer's operation lock, after passive + # reads. A newly starting control worker may still hold a live lease; + # it must win over this status-only reconciliation. + with self.lock: + pending = self.pending_release + if pending is None: + return + with self.service.firmware_update.lock: + firmware_active = self.service.firmware_update.active is not None + if (self.lease.live() or (self.thread and self.thread.is_alive()) + or self.service.motor.active or firmware_active): + pending.reset() + return + if self.state == "stopping" and pending.faulted(devices, time.monotonic()): + self.state = "fault" + self.message = "VESC сообщил об ошибке. Проверьте состояние перед включением." + if self.last_stop is not None: + self.last_stop.update(state="fault", message=self.message) + self.trace.add("release_settlement_fault", session_id=self.lease.id) + if not pending.check(devices, time.monotonic(), self.service.motor.receiver_active): + return + newly_observed = self.release_confirmed is not True + self.release_confirmed = True + self.message = (self.message or "").replace(RELEASE_NOTICE, "", 1).strip() or None + if newly_observed: + self.trace.add("release_observed", session_id=self.lease.id, + attachments=pending.attachments, samples=pending.count, + window_ms=(min(pending.previous.values()) - pending.since) * 1000) + # Configuration ACK/read-back belongs to the existing restoration + # owner. Observation cannot assert success or write configuration. + if any(self.service.motor.limits.pending(d) for d in devices): + return + if self.last_stop is not None: + self.last_stop["recovered_at"] = datetime.now(timezone.utc).isoformat() + self.pending_release = None + if self.last_stop is not None: + self.message = None + if self.state in ("fault", "stopping") and self.message is None: + self.state = "stopped" + # Keep the motor latch and retired lease. Only explicit new arm may + # take authority after a hardware fault; observation never rearms. def _publish(self, device, value, receiver): - profile = self.service.drive.value - slot = next((k for k,b in profile["bindings"].items() if b["device_id"]==device.id), None) - with self.lock: - self.readings[device.id] = {"id": device.id,"uuid":device.identity["uuid"], - "slot":slot,"label":slot_label(profile["layout"],slot) if slot else "VESC "+device.identity["uuid"][:6].upper(), - "values":value,"receiver":receiver,"sampled_at":time.monotonic()} + device.publish_sample(value, receiver) + self.trace.sample(device,value,receiver,getattr(self.service.motor,"mode",None) or "receiver_or_idle") def _prepare(self, envelope): owner = self.service.motor acquired = False + devices = [] try: # Observation also owns this lock. A nonblocking attempt made # arming depend on which thread happened to read first. Wait only @@ -172,43 +330,73 @@ class RemoteControl: slots = LAYOUTS.get(profile["layout"], ()) if not slots or set(profile["bindings"]) != set(slots): raise ValueError("Назначьте все моторы в настройках борта.") - if not devices or any(not d.link for d in devices): + required = {binding["device_id"] for binding in profile["bindings"].values()} + if (not devices or any(not d.link for d in devices) + or not required.issubset({d.id for d in devices})): + with self.lock: + self.pending_availability = PreflightRecovery(profile) raise ValueError("Один из VESC недоступен.") now = datetime.now(timezone.utc) settings = envelope["settings"] + output = ({"max_duty_percent": settings["max_duty_percent"]} if "max_duty_percent" in settings + else {"erpm": settings["max_erpm"]}) command = {"action_id":"vesc.drive.run","operation_id":"op_"+uuid.uuid4().hex, "requested_at":now.isoformat(),"deadline_at":(now+timedelta(seconds=300)).isoformat(), - "parameters":{"current_a":settings["current_a"],"duration_s":30,"erpm":settings["max_erpm"], + "parameters":{"current_a":settings["current_a"],"duration_s":30,**output, "standstill_confirmed":True,"profile_revision":profile["revision"], "device_ids":[profile["bindings"][s]["device_id"] for s in slots]}} owner.run(command, devices, devices[0], remote=self) - except ControlEnded: + except ControlEnded as error: + self.trace.add("control_ended",reason=str(error),session_id=envelope["id"],release_confirmed=self.release_confirmed) with self.lock: - self.state = "fault" if self.message or self.release_confirmed is False else "stopped" + # drive() classifies only successful, finite release readback + # as pending. Keep that state while the passive observer proves + # standstill; an expired input is never granted more lifetime. + if self.state != "stopping" or not settlement_pending(self.release_evidence): + self.state = "fault" if self.message or self.release_confirmed is False else "stopped" except (OSError, ValueError, TimeoutError, KeyError) as error: with self.lock: self.state = "fault" self.message = str(error) if self.message is None else self.message + " " + str(error) + self.trace.add("failure",error_type=type(error).__name__,reason=str(error)[:512], + violation=getattr(error,"violation",None),device_id=getattr(error,"device_id",None),session_id=envelope["id"]) + failure(error, "remote_control", session_id=envelope["id"], + release_confirmed=self.release_confirmed) finally: - with self.lock: self.lease.stop() + with self.lock: + self.lease.stop() + self.last_stop = {"session_id": envelope["id"], "state": self.state, + "message": self.message, "release_confirmed": self.release_confirmed, + "release_evidence": copy.deepcopy(self.release_evidence), + "at": datetime.now(timezone.utc).isoformat()} + if ((self.state == "fault" or self.message) and devices and self.pending_release is None + and self.pending_availability is None): + self._await_release(devices) if acquired: self.service.operation_lock.release() def ensure_live(self): with self.lock: - if not self.lease.live(): raise ControlEnded("Управление остановлено: команда больше не подтверждается.") + if not self.lease.live(): + self.trace.add("lease_expired",session_id=self.lease.id,sequence=self.lease.sequence, + remaining_ms=(self.lease.until-time.monotonic())*1000) + raise ControlEnded("Управление остановлено: команда больше не подтверждается.") def drive(self, owner, command, devices, moving, originals, unchanged): from .motor_test import check_values limit = command["parameters"]["current_a"] - maximum = command["parameters"]["erpm"] + maximum = command["parameters"].get("erpm", 0) + duty_percent = command["parameters"].get("max_duty_percent") + duty = None profile = copy.deepcopy(self.service.drive.value) sides = {b["device_id"]:0 if slot.startswith("left.") else 1 for slot,b in profile["bindings"].items()} configs, minimum_speeds, claimed, neutral_since = {}, {}, False, None previous, speeds = time.monotonic(), {d.id:0. for d in moving} last_sign, undriven_since = {}, None self.release_confirmed = None + self.release_evidence = None owner.active, owner.mode = True, "remote" receiver = False + input_ended = False zero_seen = False stalls = {} with ThreadPoolExecutor(max_workers=min(16,len(devices)),thread_name_prefix="vesc-remote") as pool: @@ -216,6 +404,14 @@ class RemoteControl: for d in moving: self.ensure_live() configs[d.id] = owner.limits.apply(d, originals[d.id]["motor"], limit) + if self.trace.active():self.trace.add("limits_applied",device_id=d.id,requested_current_a=limit, + motor={k:configs[d.id].get(k) for k in ("l_current_min","l_current_max", + "l_current_min_scale","l_current_max_scale","l_max_duty","foc_sensor_mode","s_pid_min_erpm")}, + application={k:decode(originals[d.id]["application"],"application").get(k) for k in + ("app_to_use","app_ppm_conf.ctrl_type","app_ppm_conf.hyst","app_ppm_conf.ramp_time_pos","app_ppm_conf.ramp_time_neg")}) + if duty_percent is not None: + minimum_speeds[d.id] = 0 + continue minimum = configs[d.id]["s_pid_min_erpm"] if not math.isfinite(minimum) or minimum < 0: raise ValueError("Некорректный минимальный порог регулятора VESC.") @@ -224,6 +420,9 @@ class RemoteControl: minimum_speeds[d.id] = max(1, math.ceil(minimum)) if maximum < minimum_speeds[d.id]: raise ValueError(f"Минимальная скорость регулятора этого VESC: {minimum_speeds[d.id]} ERPM.") + if duty_percent is not None: + duty = DutyOutput(configs, {d.id: decode(originals[d.id]["application"], "application") + for d in moving}, duty_percent) self.state = "ready" while True: cycle = time.monotonic() @@ -256,8 +455,12 @@ class RemoteControl: targets = {} for d in moving: value=readouts[d.id][0] - check_values(value,moving=True,current_a=limit,motor=configs[d.id]) - target=demand[sides[d.id]]*maximum + try:check_values(value,moving=True,current_a=limit,motor=configs[d.id],configured_drive=duty is not None) + except ValueError as error: + error.device_id=d.id + self.trace.add("guard_failed",device_id=d.id,violation=getattr(error,"violation",None),reason=str(error),values=value) + raise + target=duty.target(d.id,demand[sides[d.id]]) if duty else demand[sides[d.id]]*maximum minimum = minimum_speeds[d.id] # A small analogue request must never be rounded UP to # a faster requested speed. Release below the operable @@ -274,7 +477,8 @@ class RemoteControl: if undriven_since is None: undriven_since = now else: undriven_since = None reversing = any(sign and last_sign.get(key,sign)!=sign for key,sign in signs.items()) - if reversing and (undriven_since is None or now-undriven_since<.5): + reversal_wait = reversing and (undriven_since is None or now-undriven_since<.5) + if reversal_wait: # One shared barrier: after a turn, the side keeping its # direction must not drive while the other waits to reverse. targets = dict.fromkeys(targets, 0.) @@ -284,9 +488,12 @@ class RemoteControl: value=readouts[d.id][0] target=targets[d.id] minimum=minimum_speeds[d.id] - # Zero is immediate release, never an RPM hold/brake. + # Zero removes demand immediately; send() distinguishes an idle + # side during a duty turn from releasing the whole drive. if target==0: speeds[d.id]=0 + elif duty: + speeds[d.id]=duty.advance(d.id,speeds[d.id],target,dt) else: step=600*dt speeds[d.id]+=max(-step,min(step,target-speeds[d.id])) @@ -296,7 +503,9 @@ class RemoteControl: # immediately, then keep the existing ramp above it. if abs(speeds[d.id]) < minimum: speeds[d.id] = math.copysign(minimum, target) - if abs(value["motor_current_a"])>5: + # A zero-duty side can brake while the other side turns; + # stationary braking is not a failed motion command. + if abs(value["motor_current_a"])>5 and (not duty or target != 0): at,tacho=stalls.setdefault(d.id,(now,value["tachometer"])) if abs(value["erpm"])>=60 and abs(value["tachometer"]-tacho)>=3: stalls[d.id]=(now,value["tachometer"]) elif now-at>=2: raise ValueError("Мотор не движется при токе выше 5 А.") @@ -309,35 +518,74 @@ class RemoteControl: if not receiver: self.ensure_live() def send(d): if not receiver: self.ensure_live() - if owner.stop.is_set() or receiver or abs(speeds.get(d.id,0))<1: d.link.test_command("release") + if owner.stop.is_set() or receiver or d not in moving or (not any(speeds.values()) if duty else abs(speeds.get(d.id,0))<1): d.link.test_command("release") + elif duty: d.link.drive_duty(speeds[d.id], limit) else: d.link.test_speed(speeds[d.id]) + self.trace.add("output_attempt",session_id=self.lease.id,sequence=self.lease.sequence, + demand=list(demand),targets=targets,outputs=speeds.copy(),mode="duty" if duty else "rpm", + zero_seen=zero_seen,receiver=receiver,quiet=quiet,reversal_wait=reversal_wait, + quiet_ms=None if undriven_since is None else (now-undriven_since)*1000, + read_elapsed_ms=(now-cycle)*1000,cycle_elapsed_ms=(time.monotonic()-cycle)*1000) batch(pool,devices,send) + self.trace.add("output_sent",session_id=self.lease.id,sequence=self.lease.sequence, + elapsed_ms=(time.monotonic()-cycle)*1000, + rpc={d.id:{k:getattr(d.link,"last_rpc",{}).get(k) for k in ("method","elapsed_ms","ok","control","can_bridge")} for d in devices}) if not receiver: self.state="driving" if any(speeds.values()) else "ready" owner.sleep(max(0,.1-(time.monotonic()-cycle))) + except ControlEnded: + input_ended = True + raise finally: self.state="stopping" def release(d): - try: d.link.test_command("release") - except (OSError,ValueError,TimeoutError): pass - if claimed: batch(pool,devices,release) + try: + d.link.test_command("release") + self.trace.add("release_sent",device_id=d.id) + return {"sent": True} + except (OSError,ValueError,TimeoutError) as error: + self.trace.add("release_send_failed",device_id=d.id,error_type=type(error).__name__) + return {"sent": False, "error_type": type(error).__name__} + if claimed: sent = batch(pool,devices,release) if claimed: owner.sleep(.3) def released(d): try: value = values(d.link.query(4, timeout=.1)) - return all(math.isfinite(value[k]) and abs(value[k]) <= 1 - for k in ("motor_current_a", "input_current_a")) and abs(value["duty"]) < .01 - except (OSError, ValueError, TimeoutError): return False - self.release_confirmed = all(batch(pool, devices, released).values()) + self.trace.add("release_readback",device_id=d.id,values=value) + confirmed = all(math.isfinite(value[k]) and abs(value[k]) <= 1 + for k in ("motor_current_a", "input_current_a")) and abs(value["duty"]) < .01 + keys = ("motor_current_a", "input_current_a", "duty", "erpm", "fault_code") + finite = all(math.isfinite(value[k]) for k in keys) + return {"confirmed": confirmed, + "reason": "neutral_readback" if confirmed else "non_neutral_readback" if finite else "invalid_readback", + "values": {k: value[k] if math.isfinite(value[k]) else None for k in keys}} + except (OSError, ValueError, TimeoutError) as error: + self.trace.add("release_read_failed",device_id=d.id,error_type=type(error).__name__) + return {"confirmed": False, "reason": "read_failed", "error_type": type(error).__name__} + readback = batch(pool, devices, released) + # Publish only after every read completes. This diagnostic record + # does not change release thresholds, waits, outputs or authority. + self.release_evidence = {"schema": "missioncore.release-evidence/v1", + "sample_mono_ms": time.monotonic() * 1000, + "devices": {key: {"send": sent[key], **value} for key, value in readback.items()}} + self.release_confirmed = all(value["confirmed"] for value in readback.values()) if not self.release_confirmed: - self.message = "Снятие тока не подтверждено. Проверьте фактическое состояние моторов." + self.message = RELEASE_NOTICE owner.state("rc") for d in moving: - try: owner.limits.restore(d) - except (OSError,ValueError,TimeoutError): - notice="Восстановление пределов ожидает нейтрали." + try: + owner.limits.restore(d) + self.trace.add("limits_restored",device_id=d.id) + except (OSError,ValueError,TimeoutError) as error: + self.trace.add("limits_restore_failed",device_id=d.id,error_type=type(error).__name__,reason=str(error)[:512]) + notice="Восстановление токовых пределов не подтверждено." self.message=(self.message+" " if self.message else "")+notice owner.state("rc") owner.active,owner.mode=False,None - self.state="fault" if self.release_confirmed is False else "receiver" if receiver else "stopped" + if self.release_confirmed is False: + self._await_release(devices) + pending = (input_ended and not receiver and self.release_confirmed is False + and self.message == RELEASE_NOTICE and settlement_pending(self.release_evidence)) + self.state=("stopping" if pending else "fault") if self.release_confirmed is False else "receiver" if receiver else "stopped" + self.trace.add("cleanup_complete",session_id=self.lease.id,release_confirmed=self.release_confirmed,state=self.state,message=self.message) if not receiver and not owner.latched: owner.state("ready") diff --git a/plugins/vesc/runtime/remote_duty.py b/plugins/vesc/runtime/remote_duty.py new file mode 100644 index 00000000..5242bf97 --- /dev/null +++ b/plugins/vesc/runtime/remote_duty.py @@ -0,0 +1,43 @@ +"""Remote throttle matching the admitted FW 5.02 PPM Duty Cycle profile. + +Percent is an output request, not ground speed or a manufacturer rating. +Zero always releases; the caller retains lease, neutral and reversal ownership. +""" +import math + + +class DutyOutput: + def __init__(self, motors, applications, percent): + if type(percent) not in (int, float) or not 1 <= percent <= 100: + raise ValueError("Газ должен быть в диапазоне 1–100%.") + self.fraction = percent / 100 + self.maxima = {} + positive, negative = [], [] + for identifier, motor in motors.items(): + app = applications[identifier] + maximum = motor["l_max_duty"] + if (app["app_ppm_conf.ctrl_type"] != 4 or not math.isfinite(maximum) + or not 0 < maximum <= 1): + raise ValueError("Для управления газом требуется профиль PPM Duty Cycle.") + self.maxima[identifier] = maximum + for field, target in (("ramp_time_pos", positive), ("ramp_time_neg", negative)): + value = app["app_ppm_conf." + field] + if not math.isfinite(value) or not 0 <= value <= 60: + raise ValueError("Некорректная плавность газа в настройках пульта.") + target.append(value) + # One normalised ramp for both tracks, no side outruns the other due + # to unequal receiver settings. Never faster than either configured ramp. + self.positive = max(positive) + self.negative = max(negative) + + def target(self, identifier, demand): + return demand * self.fraction * self.maxima[identifier] + + def advance(self, identifier, previous, target, dt): + if target == 0: + return 0.0 + ramp = self.positive if abs(target) > abs(previous) else self.negative + if ramp <= .01: + return target + step = self.maxima[identifier] * max(0, min(.15, dt)) / ramp + return previous + max(-step, min(step, target - previous)) diff --git a/plugins/vesc/runtime/remote_limits.py b/plugins/vesc/runtime/remote_limits.py new file mode 100644 index 00000000..2588a881 --- /dev/null +++ b/plugins/vesc/runtime/remote_limits.py @@ -0,0 +1,19 @@ +"""Read-only operating-current projection; never a configuration writer.""" +import math +import time + +def publish(device, motor): + fields = ("l_current_max", "l_current_min", "l_current_max_scale", "l_current_min_scale") + if any(type(motor.get(k)) not in (int, float) or not math.isfinite(motor[k]) for k in fields): + raise ValueError("Invalid motor current configuration") + if not (motor["l_current_min"] < 0 < motor["l_current_max"] and + 0 < motor["l_current_max_scale"] <= 1 and 0 < motor["l_current_min_scale"] <= 1): + raise ValueError("Invalid motor current scales") + device.drive_limits = {"session_id": device.session, "sampled_at": time.monotonic(), + "motor_a": motor["l_current_max"] * motor["l_current_max_scale"], + "brake_a": -motor["l_current_min"] * motor["l_current_min_scale"]} + +def projection(device): + limits = device.get("drive_limits") + if not limits or limits["session_id"] != device["session"]: return None + return {k: limits[k] for k in ("motor_a", "brake_a")} diff --git a/plugins/vesc/runtime/sample_data.py b/plugins/vesc/runtime/sample_data.py new file mode 100644 index 00000000..4985027f --- /dev/null +++ b/plugins/vesc/runtime/sample_data.py @@ -0,0 +1,92 @@ +"""Explicit, bounded native Sample Data; never starts a motor or a background logger.""" + +import re +import time + +from .motor_test import Rejected + +PREFIX = "vesc.samples." +ACTIONS = frozenset(PREFIX + n for n in ("start", "status", "fetch", "stop", "read")) + + +def validate(action, p): + name = action.removeprefix(PREFIX) + shapes = { + "start": {"mode", "count", "decimation", "timeout_s", "raw"}, + "status": set(), + "fetch": {"capture_id"}, + "stop": {"capture_id"}, + "read": {"capture_id", "offset"}, + } + if name not in shapes or set(p) != shapes[name]: + raise ValueError("Invalid Sample Data parameters") + if "capture_id" in p and ( + not isinstance(p["capture_id"], str) + or not re.fullmatch(r"sample_[0-9a-f]{32}", p["capture_id"]) + ): + raise ValueError("Invalid capture identity") + for key, lo, hi in ( + ("mode", 1, 7), + ("count", 1, 2000), + ("decimation", 1, 255), + ("timeout_s", 2, 120), + ("offset", 0, 2000), + ): + if key in p and (type(p[key]) is not int or not lo <= p[key] <= hi): + raise ValueError("Sample Data argument outside bounds") + if "raw" in p and p["raw"] is not False: + raise ValueError("FW5.02 does not support raw ADC samples") + + +class SampleData: + def __init__(self, service): + self.service = service + self.pending = {} + + def active(self, device): + state = self.pending.get(device.id) + return bool(state and state[0] == device.session and time.monotonic() < state[1]) + + def maintain(self, devices): + current = {d.id: d for d in devices} + for key in list(self.pending): + if key not in current or not self.active(current[key]): + del self.pending[key] + + def execute(self, device, action, p): + if not device.readable or device.identity["version"] != "5.02": + raise Rejected("Для этой прошивки формат Sample Data ещё не подтверждён.") + name = action.removeprefix(PREFIX) + if name == "start": + s = self.service + if ( + s.firmware_update.pending(device) + or s.bms_configuration.pending(device) + or s.code_tools.blocked(device) + or s.config_editor.pending_path(device.id).exists() + ): + raise Rejected("Сначала завершите изменение прошивки, конфигурации или кода.") + # Sampling must also work during an ordinary drive. It neither + # claims an output lease nor changes app/current/motor settings. + if any( + (s.root / n).exists() for n in ("hall-pending.json", "calibration-pending.json") + ): + raise Rejected("Дождитесь завершения измерения мотора.") + result = device.link.rpc("sample_" + name, **p) + if result.get("accepted") is False: + raise Rejected(result.get("reason", "Sample Data занят.")) + if name == "start" and result.get("state") in ("armed", "stored_wait", "receiving"): + self.pending[device.id] = (device.session, time.monotonic() + p["timeout_s"] + 2) + elif name == "fetch" and result.get("state") == "armed": + self.pending[device.id] = (device.session, time.monotonic() + 32) + elif result.get("state") in ( + "complete", + "incomplete", + "timeout", + "cancelled", + "unverified", + "expired", + "idle", + ): + self.pending.pop(device.id, None) + return result diff --git a/plugins/vesc/runtime/server.py b/plugins/vesc/runtime/server.py index 25bb2e5e..1ace6a6f 100644 --- a/plugins/vesc/runtime/server.py +++ b/plugins/vesc/runtime/server.py @@ -1,19 +1,46 @@ """Private Unix socket endpoint; peer UID must be the installed Node service.""" import json +import logging import os -from pathlib import Path import pwd import re import socket import socketserver import struct import threading +import time from http.server import BaseHTTPRequestHandler -from urllib.parse import urlsplit, parse_qs +from pathlib import Path +from urllib.parse import parse_qs, urlsplit -from .service import Service +from .diagnostics import failure from .remote_control import RemoteControl +from .maintenance_state import idle, quiesce +from .service import Service +try: + from .maintenance import Maintenance # Same SDK file copied by payload.py. +except ModuleNotFoundError: # Source checkout, never needed on installed Node. + import runpy + Maintenance = runpy.run_path(str(Path(__file__).resolve().parents[3] / + "packages/plugin-sdk/python/missioncore_plugin_sdk/maintenance.py"))["Maintenance"] + + +def poll_readonly(callback, stop, interval, phase, maintenance=None): + """Keep discovery/observation alive; never retry a powered operation here.""" + next_report = 0.0 + while not stop.is_set(): + try: + if maintenance is None: + callback() + else: + with maintenance.work(background=True) as admitted: + if admitted: callback() + except Exception as error: + if time.monotonic() >= next_report: + next_report = time.monotonic() + 30 + failure(error, phase) + stop.wait(interval) class Handler(BaseHTTPRequestHandler): @@ -27,14 +54,46 @@ class Handler(BaseHTTPRequestHandler): self.dispatch() def dispatch(self): + _, uid, _ = struct.unpack("3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) + if uid == 0: + result = None + if self.command == "POST" and self.path == "/maintenance/enter": + result = self.server.maintenance.enter(self.server.idle, self.server.quiesce) + elif self.command == "POST" and self.path == "/maintenance/leave": + try: result = self.server.maintenance.leave() + except ValueError: result = {"resumed": False} + elif self.command == "GET" and self.path == "/prepare-safe": + result = {"safe": self.server.maintenance.closed and self.server.idle() is None} + if result is not None: + data = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(data) + return + self.send_error(403) + return + with self.server.maintenance.work() as admitted: + if not admitted: + self.send_error(503, "Device service is under maintenance") + return + self.dispatch_admitted() + + def dispatch_admitted(self): self.connection.settimeout(10) status = 200 try: node = self.headers.get("X-Node-Id", "") - if not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node) or self.headers.get("Transfer-Encoding"): + if not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node) or self.headers.get( + "Transfer-Encoding" + ): raise ValueError("Invalid request") if self.command == "GET" and self.path == "/inventory": result = self.server.service.inventory(node) + elif self.command == "GET" and self.path == "/observe": + result = self.server.service.remote.observe_snapshot() elif self.command == "GET" and self.path.startswith("/archives/"): url = urlsplit(self.path) parts = url.path.split("/") @@ -49,19 +108,26 @@ class Handler(BaseHTTPRequestHandler): elif self.command == "GET" and self.path.startswith("/archive-export?"): after = int(parse_qs(urlsplit(self.path).query).get("after", ["0"])[0]) result = self.server.service.archive.export("local", after) - elif self.command == "POST" and self.path in ("/operation", "/remote"): + elif self.command == "POST" and self.path in ("/operation", "/remote", "/drive-trace"): size = int(self.headers.get("Content-Length", "0")) if not 0 < size <= 65536 or self.headers.get("Content-Type") != "application/json": raise ValueError("Invalid command") raw = self.rfile.read(size) if len(raw) != size: raise ValueError("Truncated command") - result = (self.server.service.execute(json.loads(raw)) if self.path == "/operation" - else self.server.service.remote.feed(json.loads(raw))) + result = ( + self.server.service.execute(json.loads(raw)) + if self.path == "/operation" + else self.server.service.remote.trace.exchange(json.loads(raw)) if self.path == "/drive-trace" + else self.server.service.remote.feed(json.loads(raw)) + ) else: raise ValueError("Unknown route") except (ValueError, KeyError, TypeError, OSError): - status, result = 400, {"error": "Запрос VESC отклонён. Обновите сведения об устройстве."} + status, result = ( + 400, + {"error": "Запрос VESC отклонён. Обновите сведения об устройстве."}, + ) data = json.dumps(result, ensure_ascii=False, allow_nan=False).encode() self.send_response(status) self.send_header("Content-Type", "application/json") @@ -95,40 +161,42 @@ class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): self.slots.release() def verify_request(self, request, address): - _, uid, _ = struct.unpack("3i", request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) - return uid == self.node_uid + _, uid, _ = struct.unpack( + "3i", request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12) + ) + return uid in (0, self.node_uid) def main(): + logging.basicConfig(level=logging.INFO, format="%(message)s") if os.geteuid() == 0: raise RuntimeError("VESC must run as its own unprivileged user") os.umask(0o007) service = Service("/var/lib/mission-core-vesc") service.remote = RemoteControl(service) stop = threading.Event() - - def scan(): - while not stop.is_set(): - try: - service.scan() - except OSError: - # A transient sysfs race must not silently kill discovery. - pass - stop.wait(2) - - def observe(): - while not stop.is_set(): - service.remote.observe() - stop.wait(.2) + maintenance = Maintenance() path = Path("/run/mission-core-vesc/driver.sock") path.unlink(missing_ok=True) with Server(str(path), Handler) as server: server.node_uid = pwd.getpwnam("mission-core-node").pw_uid server.service = service - thread = threading.Thread(target=scan, daemon=True) - thread.start() - threading.Thread(target=observe, daemon=True, name="vesc-observer").start() + server.maintenance = maintenance + server.idle = lambda: idle(service) + server.quiesce = lambda: quiesce(service) + threading.Thread( + target=poll_readonly, + args=(service.scan, stop, 2, "discovery-loop", maintenance), + daemon=True, + name="vesc-discovery", + ).start() + threading.Thread( + target=poll_readonly, + args=(service.remote.observe, stop, 0.2, "observation-loop", maintenance), + daemon=True, + name="vesc-observer", + ).start() try: server.serve_forever() finally: diff --git a/plugins/vesc/runtime/service.py b/plugins/vesc/runtime/service.py index 3774ade8..7db49f8a 100644 --- a/plugins/vesc/runtime/service.py +++ b/plugins/vesc/runtime/service.py @@ -16,16 +16,39 @@ from . import MODEL, SCHEMA, VERSION from .protocol import firmware, values, ppm, TEST_LIMITS, SPEED_LIMITS from .motor_test import MotorTest, Rejected from .drive_profile import DriveProfile, slot_label, validate as validate_drive +from .control_transport import ControlTransport, validate_routes +from .transport_hub import TransportHub, Missing +from .can_bridge import Attachment as CanAttachment from .serial import device_id, discover -from .native_link import NativeLink +from .native_link import NativeLink, reap_retired +from .diagnostics import failure, connection +from .read_cache import ReadCache, SNAPSHOT_ACTIONS, EXPIRED +from .bms_configuration import BmsConfiguration, ACTIONS as BMS_CONFIG_ACTIONS, READS as BMS_CONFIG_READS, validate as validate_bms_config +from .package_tools import PackageTools, ACTIONS as PACKAGE_ACTIONS, READS as PACKAGE_READS, validate as validate_packages +from .sample_data import SampleData, ACTIONS as SAMPLE_ACTIONS, validate as validate_samples +from .qml_preview import QmlPreview, ACTIONS as QML_ACTIONS, validate as validate_qml +from .code_tools import CodeTools, ACTIONS as CODE_ACTIONS, READS as CODE_READS, validate as validate_code +from .bms import BmsControl, ACTIONS as BMS_ACTIONS, validate as validate_bms +from .firmware_update import FirmwareUpdate, ACTIONS as FIRMWARE_ACTIONS, SNAPSHOTS as FIRMWARE_SNAPSHOTS, validate as validate_firmware try: from .archive import Archive except ImportError: # Source checkout; packaging copies this exact shared file. from k1link.device_plugins.vesc.archive import Archive -ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release"}) +ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.configuration.read", "vesc.configuration.preview", "vesc.configuration.apply", "vesc.configuration.reconcile", "vesc.diagnostics.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.transport.configure", "vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release"}) +ACTIONS = ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_ACTIONS | BMS_CONFIG_ACTIONS | CODE_ACTIONS | BMS_ACTIONS | FIRMWARE_ACTIONS | {"vesc.tools.read", "vesc.terminal.read"} + +READ_ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read", + "vesc.limits.read", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.read", "vesc.diagnostics.read", + "vesc.config.backup", "vesc.configuration.preview", "vesc.configuration.reconcile", "vesc.input.read", "vesc.can.read"}) + +SNAPSHOT_ACTIONS = SNAPSHOT_ACTIONS | FIRMWARE_SNAPSHOTS +READ_ACTIONS = READ_ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_READS | BMS_CONFIG_READS | CODE_READS | {"vesc.bms.read", "vesc.bms.prepare"} +SNAPSHOT_ACTIONS = SNAPSHOT_ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_READS | BMS_CONFIG_READS | CODE_READS | {"vesc.bms.read", "vesc.bms.prepare"} +READ_ACTIONS = READ_ACTIONS | (FIRMWARE_ACTIONS - {'vesc.firmware.apply','vesc.firmware.cancel','vesc.firmware.status'}) + def utc(): return datetime.now(timezone.utc).isoformat() @@ -62,11 +85,15 @@ class Device: self.backup = None self.lock = threading.Lock() self.retry_at = 0 + self.failure_at = 0 + self.failures = 0 + self.sample = None + self.identified_session = None @property def readable(self): identity = self.identity - return self.readable_identity(identity) + return self.readable_identity(identity) and getattr(self.link,"engine",{}).get("firmware_admitted",True) @staticmethod def readable_identity(identity): @@ -77,23 +104,64 @@ class Device: with self.lock: try: self.session = "vesc_" + uuid.uuid4().hex + self.opened = utc() + self.identified_session = None + self.sample = self.telemetry = None self.link = factory(self.attachment) identity = firmware(self.link.query(0)) + if isinstance(self.attachment, CanAttachment) and identity["uuid"] != self.attachment.expected_uuid: + raise ValueError("На этом CAN-адресе другой UUID VESC.") self.identity = identity self.id = device_id("uuid:" + identity["uuid"]) + self.identified_session = self.session self.error = None - except (OSError, ValueError, TimeoutError): - if self.link: - self.link.close() - self.link = None - self.error = "Контроллер не ответил. Проверьте питание, USB и доступность порта." - self.retry_at = time.monotonic() + 15 + connection("identified", self) + # A firmware reply alone does not reset repeated read failures. + except Exception as error: + self.failed(error, "connection") + + def failed(self, error, phase): + """Called with device.lock held. One retry deadline, no retry worker.""" + previous_session = self.session + if self.link is not None or self.sample is not None: + connection("read_failed", self, error) + link, self.link = self.link, None + self.sample = self.telemetry = None + self.session = "vesc_" + uuid.uuid4().hex + self.failures = min(self.failures + 1, 5) + self.retry_at = time.monotonic() + min(2 ** self.failures, 30) + self.error = "Нет ответа VESC. Повторное подключение выполняется автоматически." + try: + if link: link.close() + except Exception as cleanup_error: + if time.monotonic() >= self.failure_at: + failure(cleanup_error, "connection-cleanup", device=self) + if time.monotonic() >= self.failure_at: + self.failure_at = time.monotonic() + 30 + failure(error, phase, device=self, session_id=previous_session) + + def publish_sample(self, value, receiver): + restored = self.sample is None + self.sample = {"session_id": self.session, "values": value, + "receiver": receiver, "sampled_at": time.monotonic(), "observed_at": utc()} + self.failures = 0 + self.retry_at = 0 + self.error = None + if restored: + connection("sample_restored", self) def close(self): with self.lock: - if self.link: - self.link.close() - self.link = None + connection("usb_detached", self) + link, self.link = self.link, None + self.sample = self.telemetry = None + self.session = "vesc_" + uuid.uuid4().hex + try: + if link: link.close() + except Exception as error: + if time.monotonic() >= self.failure_at: + self.failure_at = time.monotonic() + 30 + failure(error, "connection-close", device=self) class Service: @@ -108,31 +176,35 @@ class Service: self.lock = threading.RLock() self.operation_lock = threading.Lock() self.journal_lock = threading.Lock() + self.read_cache = ReadCache() self.motor = MotorTest(self, atomic, utc) + from .config_editor import ConfigEditor + self.config_editor = ConfigEditor(self, atomic, utc) + self.firmware_update = FirmwareUpdate(self, atomic, utc) + self.bms = BmsControl(self, atomic, utc) + self.bms_configuration = BmsConfiguration(self, atomic, utc) + self.code_tools = CodeTools(self, atomic, utc) + self.samples = SampleData(self) + self.qml = QmlPreview(self) + self.qml_utc = utc + self.packages = PackageTools(self, atomic, utc) self.drive = DriveProfile(self.root, atomic) self.instance = "vesc_" + uuid.uuid4().hex self.revision = 0 + self.device_type = Device + self.transport = ControlTransport(self.root, atomic) + self.transports = TransportHub(self, atomic) def scan(self): - attachments = {item.binding: item for item in self.discover_fn()} - with self.lock: - removed = [self.devices.pop(k) for k, d in list(self.devices.items()) - if attachments.get(k) != d.attachment] - for key, item in attachments.items(): - if key not in self.devices: - self.devices[key] = Device(item) - devices = list(self.devices.values()) - for device in removed: - device.close() - for device in devices: - if device.link is not None and not getattr(device.link, "alive", True): - device.close() - if device.link is None and time.monotonic() >= device.retry_at: - device.connect(self.link_factory) + reap_retired() + self.transports.scan() + with self.lock: devices = list(self.devices.values()) if self.operation_lock.acquire(blocking=False): try: + self.qml.maintain(devices) + self.samples.maintain(devices) for device in devices: - if device.link is not None and self.motor.limits.pending(device): + if device.link is not None and not self.firmware_update.pending(device) and not self.bms_configuration.pending(device) and not self.code_tools.blocked(device) and self.motor.limits.pending(device): with device.lock: try: self.motor.limits.restore(device) @@ -149,32 +221,36 @@ class Service: # Copy each generation before counting identities. Serial I/O never # holds the inventory lock; it can complete during this projection. devices = [d.__dict__.copy() for d in self.devices.values()] - keys = [device_id("uuid:" + d["identity"]["uuid"]) if d["identity"] and d["link"] else d["attachment"].id for d in devices] - items = [] - for d, key in zip(devices, keys): - identity, attachment = d["identity"], d["attachment"] - unique = keys.count(key) == 1 and identity is not None and d["link"] is not None - identifier = key if unique else attachment.id - message = d["error"] if keys.count(key) == 1 else "Контроллеры сообщили одинаковый UUID. Настройка недоступна." - items.append({"id": identifier, "attachment_id": attachment.id, - "name": "VESC " + (identity["uuid"][:6].upper() if unique else "· USB " + attachment.usb), - "model": identity["hardware"] if unique else "VESC · USB", "kind": MODEL, - "firmware": identity["version"] if unique else None, - "initializable": True, "prepared": True, "configured": unique, "verified": unique, - "preparation_safe": True, "online": True, "usb": attachment.speed, - "connection_label": "USB " + attachment.usb + next((" · " + slot_label(self.drive.value["layout"], slot) for slot, binding in self.drive.value["bindings"].items() if binding["device_id"] == identifier), ""), "layers": [], - "vesc_status": {"identity": identity if unique else None, "readable": unique and Device.readable_identity(identity), - "engine": getattr(d["link"], "engine", None), "message": message, "telemetry": d["telemetry"], "backup": d["backup"], "board_settings_supported": True, "group_test_supported": True, "link_check_supported": True, "test_supported": unique and identity["version"] == "5.02" and identity["hardware"] == "75_300_R2", "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "speed_limits": SPEED_LIMITS, "hall_measurement": {"current_a": 5, "interruptible": False, "standstill_confirmation_required": True}, "foc_calibration": {"min_power_loss_w": 10, "max_power_loss_w": 150, "interruptible": False}, "test_mode": self.motor.mode, "test_active": self.motor.active, "rc_latched": self.motor.latched}, - "snapshot": {"context": {"session_id": d["session"], - "device": {"device_id": identifier, "model": {"plugin_id": "missioncore.vesc", - "plugin_version": VERSION, "model_id": MODEL}, - "stability": "stable" if unique else "provisional", - "basis": "hardware-identifier" if unique else "transport-local"}, - "execution": {"node_id": node_id, "agent_instance_id": self.instance, "platform": "linux"}, - "opened_at": d["opened"]}, "revision": self.revision, "observed_at": utc(), - "enrollment": "enrolled" if unique else "empty", "acquisition": "idle", - "connectivity": "connected" if unique else "degraded", "message": message}}) - return {"items": items} + keys = [device_id("uuid:" + d["identity"]["uuid"]) if d["identity"] else d["attachment"].id for d in devices] + items = [] + for d, key in zip(devices, keys): + identity, attachment = d["identity"], d["attachment"] + unique = keys.count(key) == 1 and identity is not None + available = (unique and d["identified_session"] == d["session"] + and d["link"] is not None and getattr(d["link"], "alive", True)) + sample = d["sample"] if available and d["sample"] and d["sample"]["session_id"] == d["session"] else None + identifier = key if unique else attachment.id + message = d["error"] if keys.count(key) == 1 else "Контроллеры сообщили одинаковый UUID. Настройка недоступна." + items.append({"id": identifier, "attachment_id": attachment.id, + "name": "VESC " + (identity["uuid"][:6].upper() if unique else "· USB " + attachment.usb), + "model": identity["hardware"] if unique else "VESC · USB", "kind": MODEL, + "firmware": identity["version"] if unique else None, + "initializable": True, "prepared": True, "configured": unique, "verified": bool(available), + "preparation_safe": True, "online": bool(available) if isinstance(attachment, CanAttachment) else not isinstance(attachment, Missing), "usb": attachment.speed, + "connection_label": (attachment.usb if isinstance(attachment, CanAttachment) else "Недоступно" if isinstance(attachment, Missing) else "USB " + attachment.usb) + next((" · " + slot_label(self.drive.value["layout"], slot) for slot, binding in self.drive.value["bindings"].items() if binding["device_id"] == identifier), ""), "layers": [], + "vesc_status": {"identity": identity if unique else None, "readable": bool(available) and Device.readable_identity(identity) and getattr(d["link"],"engine",{}).get("firmware_admitted",True), + "connected": bool(available), "telemetry_ready": sample is not None, + "engine": getattr(d["link"], "engine", None), "message": message, "telemetry": d["telemetry"] if available else None, "backup": d["backup"], "configuration_read_supported": True, "configuration_edit_supported": True, "firmware_update_supported": True, "tools_read_supported": True, "terminal_read_supported": True, "firmware_update": self.firmware_update.status(identifier), "configuration_pending": self.config_editor.pending_path(identifier).exists(), "bms_configuration_pending": self.bms_configuration.path(identifier).exists(), "package_pending": self.packages.path(identifier).exists(), "code_pending": self.code_tools.path(identifier).exists(), "code_execution_pending": self.code_tools.path(identifier,"execution").exists(), "diagnostics_read_supported": True, "qml_preview_supported": True, "qml_interactive_supported": True, "qml_broker_supported": "qml_read" in (getattr(d["link"], "engine", None) or {}).get("contract", {}).get("methods", []), "sample_data_supported": bool(identity and identity["version"] == "5.02"), "board_settings_supported": True, "group_test_supported": True, "link_check_supported": True, "test_supported": bool(available) and identity["version"] == "5.02" and identity["hardware"] == "75_300_R2", "control_transport": self.transports.profile(), "control_endpoints": self.transports.endpoints(), "control_adapters": [{**a, "label": a["name"]} for a in self.transports.adapters], "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "speed_limits": SPEED_LIMITS, "hall_measurement": {"current_a": 5, "interruptible": False, "standstill_confirmation_required": True}, "foc_calibration": {"min_power_loss_w": 10, "max_power_loss_w": 150, "interruptible": False}, "test_mode": self.motor.mode, "test_active": self.motor.active, "rc_latched": self.motor.latched}, + "snapshot": {"context": {"session_id": d["session"], + "device": {"device_id": identifier, "model": {"plugin_id": "missioncore.vesc", + "plugin_version": VERSION, "model_id": MODEL}, + "stability": "stable" if unique else "provisional", + "basis": "hardware-identifier" if unique else "transport-local"}, + "execution": {"node_id": node_id, "agent_instance_id": self.instance, "platform": "linux"}, + "opened_at": d["opened"]}, "revision": self.revision, "observed_at": utc(), + "enrollment": "enrolled" if unique else "empty", "acquisition": "idle", + "connectivity": "connected" if available else "degraded", "message": message}}) + return {"items": items} def validate(self, command): if not isinstance(command, dict) or command.get("api_version") != SCHEMA or command.get("kind") != "OperationRequest": @@ -211,9 +287,36 @@ class Service: raise ValueError("Explicit observation of all motors at standstill required") if action == "vesc.foc.calibrate" and (type(params["max_power_loss_w"]) not in (int,float) or not 10 <= params["max_power_loss_w"] <= 150): raise ValueError("Heating budget must be between 10 and 150 W") + elif action == "vesc.tools.read": + if set(params) != {'tool'} or params['tool'] not in ('adc','chuk','imu','bms'): + raise ValueError('Unknown peripheral tool') + elif action == "vesc.terminal.read": + if set(params) != {'command'} or params['command'] not in ("hw_status", "faults", "fault", "ping", "mem", "threads", "rpm", "tacho", "volt", "uptime", "help"): + raise ValueError('Only admitted read-only terminal commands are supported') + elif action in BMS_CONFIG_ACTIONS: + validate_bms_config(action, params) + elif action in PACKAGE_ACTIONS: + validate_packages(action, params) + elif action in SAMPLE_ACTIONS: + validate_samples(action, params) + elif action in QML_ACTIONS: + validate_qml(action, params) + elif action in CODE_ACTIONS: + validate_code(action, params) + elif action in BMS_ACTIONS: + validate_bms(action, params) + elif action in FIRMWARE_ACTIONS: + validate_firmware(action, params) + elif action.startswith("vesc.configuration.") and action != "vesc.configuration.read": + from .config_editor import validate + validate(action, params) elif action == "vesc.link.check": if set(params) != {"sessions"} or not isinstance(params["sessions"], dict) or not 1 <= len(params["sessions"]) <= 128: raise ValueError("Controller sessions required") + elif action == "vesc.transport.configure": + if not isinstance(params, dict) or set(params) != {"revision", "drive_revision", "routes"}: + raise ValueError("Invalid control transport profile") + validate_routes(params["routes"], self.drive.value) elif action in ("vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout"): validate_drive(action, params) elif params != {}: @@ -228,6 +331,29 @@ class Service: deadline = self.validate(command) path = self.root / (command["operation_id"] + ".json") digest = hashlib.sha256(json.dumps(command, sort_keys=True).encode()).hexdigest() + if command["action_id"] in ("vesc.firmware.status", "vesc.firmware.cancel"): + # Status/cancel are RAM/file operations and remain available while + # the uploading request holds the exclusive hardware lock. + with self.journal_lock: + if path.exists(): + previous = json.loads(path.read_text()) + if previous['digest'] != digest: raise ValueError('Operation identity conflict') + return self.read_cache.get(command['operation_id']) if previous.get('snapshot_only') else previous['receipt'] + if deadline <= datetime.now(timezone.utc): raise ValueError('Operation expired') + identifier = command['session']['device_id'] + with self.lock: + if not any(d.id == identifier for d in self.devices.values()): + raise ValueError('Device no longer present') + result = (self.firmware_update.status(identifier) if command['action_id'].endswith('.status') + else self.firmware_update.cancel(identifier, command['parameters']['operation_id'])) + receipt = {'state':'complete','result':result} + if command['action_id'].endswith('.status'): + if sum(p.stat().st_size for p in self.root.glob('*.json')) > 32 * 1024 * 1024: + raise ValueError('Read journal is full') + self.read_cache.put(command['operation_id'], receipt) + atomic(path, {'digest':digest,'snapshot_only':True,'receipt':EXPIRED}) + else: atomic(path, {'digest':digest,'receipt':receipt}) + return receipt if command["action_id"] == "vesc.motor.stop": with self.journal_lock: if path.exists(): @@ -239,13 +365,19 @@ class Service: result = {"state": "complete", "result": {"stop_requested": True, "interruptible": self.motor.mode not in ("hall", "foc"), "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "test_active": self.motor.active}} atomic(path, {"digest": digest, "receipt": result}) return result - if not self.operation_lock.acquire(blocking=False): + # Observer samples own the same lock for a short exchange. Read requests + # wait at most half a second, within their remaining read budget. + # Powered operations keep immediate admission; no delayed motor start. + wait = max(0.0, min(.5, (deadline-datetime.now(timezone.utc)).total_seconds()-8)) if command["action_id"] in READ_ACTIONS or command["action_id"] == "vesc.transport.configure" else 0.0 + if not self.operation_lock.acquire(timeout=wait): raise ValueError("Another VESC operation is running") try: if path.exists(): previous = json.loads(path.read_text()) if previous["digest"] != digest: raise ValueError("Operation identity conflict") + if command["action_id"] in SNAPSHOT_ACTIONS and previous.get("snapshot_only"): + return self.read_cache.get(command["operation_id"]) return previous["receipt"] if deadline <= datetime.now(timezone.utc): raise ValueError("Operation expired") @@ -262,6 +394,12 @@ class Service: if path.exists(): raise ValueError("Operation identity already reserved") atomic(path, record) try: + if self.samples.active(device) and command["action_id"] in { + "vesc.firmware.apply", "vesc.firmware.target", "vesc.firmware.backup", "vesc.configuration.apply", + "vesc.bms.configuration.apply", "vesc.bms.configuration.read", "vesc.bms.configuration.preview", + "vesc.bms.read", "vesc.bms.apply", "vesc.code.apply", "vesc.code.control_apply", + "vesc.packages.apply", "vesc.hall.measure", "vesc.foc.calibrate"}: + raise Rejected("Сначала остановите Sample Data или дождитесь окончания захвата.") if command["action_id"] == "vesc.link.check": from .link_check import measure with self.lock: devices = list(self.devices.values()) @@ -269,6 +407,15 @@ class Service: record["receipt"] = {"state": "complete", "result": result} atomic(path, record) return record["receipt"] + if command["action_id"] == "vesc.transport.configure": + try: + result = self.transport.update(command["parameters"], self.drive.value, active=self.motor.active or (getattr(self, "remote", None) is not None and self.remote.state == "preparing")) + self.transports.select() + except ValueError as error: + raise Rejected(str(error)) from error + record["receipt"] = {"state": "complete", "result": {"control_transport": result}} + atomic(path, record) + return record["receipt"] if command["action_id"] in ("vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout"): if device.identity is None: raise Rejected("Сначала подтвердите личность VESC.") try: @@ -296,10 +443,18 @@ class Service: with device.lock: if device.link is None: raise OSError("Device disconnected") + if command["action_id"] not in READ_ACTIONS | CODE_ACTIONS | BMS_CONFIG_ACTIONS | PACKAGE_ACTIONS and (self.bms_configuration.pending(device) or self.code_tools.blocked(device)): + raise Rejected("Сначала подтвердите изменение BMS/кода и остановите Lisp.") remaining = (deadline - datetime.now(timezone.utc)).total_seconds() if remaining < 8: raise TimeoutError("Insufficient time for bounded read") - actual = firmware(device.link.query(0)) + # Local QML staging/input never interrogates USB; retain + # the binding to this exact live attachment and session. + if command["action_id"] in QML_ACTIONS: + device.link.check() + actual = device.identity + else: + actual = firmware(device.link.query(0)) if actual != device.identity: device.link.close() device.link = None @@ -308,11 +463,60 @@ class Service: raise ValueError("Controller identity changed") result = {"identity": actual, "device_id": device.id, "observed_at": utc()} action = command["action_id"] - if action in {"vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup"} and not device.readable: + if action in {"vesc.telemetry.read", "vesc.limits.read", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.read", "vesc.diagnostics.read", "vesc.config.backup"} and not device.readable: raise ValueError("Firmware read layout is unsupported") if action == "vesc.telemetry.read": result.update(values=values(device.link.query(4)), monotonic_at=time.monotonic()) device.telemetry = result + elif action == 'vesc.tools.read': + result.update(device.link.device_tool(command['parameters']['tool'])) + if command['parameters']['tool']=='bms': + # FW5.02 proxy omits these fields. Native decoder defaults + # are not measurements or evidence of a connected BMS. + result['source']='controller_cache' + result['source_age_known']=False + if actual['version']=='5.02': + for key in ('can_id','ah_cnt_chg_total','wh_cnt_chg_total','ah_cnt_dis_total','wh_cnt_dis_total','pressure','data_version','status'): + result.get('values',{}).pop(key,None) + elif action == 'vesc.terminal.read': + result.update(device.link.diagnostic(command['parameters']['command'])) + elif action in BMS_CONFIG_ACTIONS: + if action.endswith(".apply") and self.code_tools.blocked(device): raise Rejected("Сначала подтвердите запись кода и остановите Lisp.") + result.update(self.bms_configuration.execute(device,action,command["parameters"],command["operation_id"],deadline)) + elif action in PACKAGE_ACTIONS: + result.update(self.packages.execute(device,action,command["parameters"],command["operation_id"],deadline)) + elif action in SAMPLE_ACTIONS: + result.update(self.samples.execute(device, action, command["parameters"])) + elif action in QML_ACTIONS: + result.update(self.qml.execute(device, action, command["parameters"])) + elif action in CODE_ACTIONS: + result.update(self.code_tools.execute(device,action,command["parameters"],command["operation_id"],deadline)) + elif action in BMS_ACTIONS: + if not device.readable:raise Rejected('Бортовой VESC не поддерживает адресный BMS.') + if action=='vesc.bms.read': result.update(self.bms.read(device,command['parameters']['can_id'])) + elif action=='vesc.bms.prepare': result.update(self.bms.prepare(device,command['parameters'])) + else: result.update(self.bms.apply(device,command['parameters'],command['operation_id'])) + elif action in FIRMWARE_ACTIONS: + if action == 'vesc.firmware.apply': + result.update(self.firmware_update.apply(device,command['parameters'],command['operation_id'],deadline)) + elif action == 'vesc.firmware.reconcile': + result.update(self.firmware_update.reconcile(device)) + else: result.update(self.firmware_update.stage(device,action,command['parameters'])) + elif action == "vesc.configuration.read": + result["configuration"] = device.link.configuration() + if firmware(device.link.query(0)) != actual: + raise ValueError("Controller changed during configuration read") + elif action == "vesc.configuration.preview": + result.update(self.config_editor.preview(device, command["parameters"])) + elif action == "vesc.configuration.apply": + result.update(self.config_editor.apply(device, command["parameters"], command["operation_id"], deadline)) + elif action == "vesc.configuration.reconcile": + result.update(self.config_editor.reconcile(device)) + elif action == "vesc.diagnostics.read": + from .controller_diagnostics import read_diagnostics + result.update(read_diagnostics(device)) + if firmware(device.link.query(0)) != actual: + raise ValueError("Controller changed during diagnostic read") elif action == "vesc.limits.read": from .limits_view import read_limits result.update(parameters=read_limits(device.link)) @@ -357,7 +561,11 @@ class Service: "type": type(error).__name__, "native_rpc": error.native_rpc, "native_history": getattr(error, "native_history", []), }} - atomic(path, record) + if command["action_id"] in SNAPSHOT_ACTIONS: + self.read_cache.put(command["operation_id"], record["receipt"]) + atomic(path, {"digest": digest, "snapshot_only": True, "receipt": EXPIRED}) + else: + atomic(path, record) return record["receipt"] finally: diff --git a/plugins/vesc/runtime/session_log.py b/plugins/vesc/runtime/session_log.py new file mode 100644 index 00000000..514b34a2 --- /dev/null +++ b/plugins/vesc/runtime/session_log.py @@ -0,0 +1,160 @@ +"""Opt-in onboard JSONL evidence. Disk never runs on the motor worker. + +RAM is bounded; full files have no duration/size cutoff and are never rotated. +Backpressure and I/O failures are explicit, rather than silently losing evidence. +""" +import base64 +import hashlib +import json +import os +import queue +import re +import threading +import time +from datetime import datetime, timezone +from pathlib import Path + +class SessionLog: + SYNC_INTERVAL = 1.0 + MAX_RECORD_BYTES = 8192 + MAX_QUEUE_BYTES = 4 * 1024 * 1024 + def __init__(self,root): + self.root=Path(root)/'Session Logs' + self.lock=threading.RLock();self.queue=queue.Queue(maxsize=4096) + self.path=None;self.id=None;self.thread=None + self.error=None;self.dropped=0;self.written=0;self.closed=True;self.closing=False + self.external_ack={} + self.queued_bytes=0;self.drop_reasons={} + + def start(self,identifier,vehicle,create=True,options=None): + if not isinstance(identifier,str) or not re.fullmatch(r'[a-f0-9]{32}',identifier):raise ValueError('Invalid capture ID') + with self.lock: + if self.id==identifier:return # A closed capture can never reopen. + if not self.closed:raise ValueError('Finish the current diagnostic session first') + label=re.sub(r'[^A-Za-z0-9А-Яа-яЁё_. -]','_',str(vehicle))[:100].strip(' .') or 'Rover' + folder=self.root/label + if create:folder.mkdir(parents=True,exist_ok=True,mode=0o700) + if folder.is_symlink():raise ValueError('Invalid log directory') + prior=list(folder.glob('*_'+identifier+'.jsonl')) + self.id=identifier;self.external_ack={};self.dropped=self.written=0 + self.path=None;self.error=None;self.closed=True;self.closing=False + if prior: + self.path=prior[0];self.error='CaptureInterrupted' + # Inspect only a bounded tail. Never append, repair or scan an hour-long file. + with self.path.open('rb') as stream: + stream.seek(max(0,self.path.stat().st_size-16384));tail=stream.read(16384) + try: + end=json.loads(tail.splitlines()[-1]) if tail.endswith(b'\n') else {} + if end.get('type')=='session_end': + self.written=int(end['written_records']);self.dropped=int(end['dropped_records']);self.error=None + except (ValueError,KeyError,IndexError,TypeError):pass + return + if not create:self.error='CaptureNotFound';return + stamp=datetime.now(timezone.utc).strftime('%Y-%m-%d_%H-%M-%S_UTC') + self.path=folder/(stamp+'_'+identifier+'.jsonl') + fd=os.open(self.path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|getattr(os,'O_NOFOLLOW',0),0o600) + self.file=os.fdopen(fd,'wb',buffering=65536) + self.error=None;self.closed=False;self.closing=False + self.queue=queue.Queue(maxsize=4096) + self.queued_bytes=0;self.drop_reasons={} + self.file.write((json.dumps({'type':'manifest','schema':'missioncore.rover-session/v1', + 'capture_id':identifier,'options':options,'vehicle':str(vehicle)[:128],'started_at':datetime.now(timezone.utc).isoformat(), + 'clock_note':'UTC and monotonic clocks are per source; receive order is not synchronized measurement.'},ensure_ascii=False)+'\n').encode()) + self.file.flush();os.fsync(self.file.fileno()) + self.thread=threading.Thread(target=self._write,daemon=True,name='vesc-session-log');self.thread.start() + + def append(self,row): + with self.lock: + if self.closed or self.closing or self.error:return False + try:raw=(json.dumps(row,ensure_ascii=False,allow_nan=False,separators=(',',':'))+'\n').encode() + except (ValueError,TypeError): + self._drop('invalid_record');return False + if len(raw)>self.MAX_RECORD_BYTES: + self._drop('record_too_large');return False + if self.queued_bytes+len(raw)>self.MAX_QUEUE_BYTES or self.queue.full(): + self._drop('queue_full');return False + try:self.queue.put_nowait(raw) + except queue.Full:self._drop('queue_full');return False + self.queued_bytes+=len(raw) + return True + + def _drop(self,reason): + self.dropped+=1;self.drop_reasons[reason]=self.drop_reasons.get(reason,0)+1 + + def _write(self): + last_sync=time.monotonic();dirty=False + try: + while True: + # Finish is an out-of-band signal, so a full data queue cannot + # lose it. Every accepted record drains before the footer. + with self.lock: + if self.closing and self.queue.empty():break + try:row=self.queue.get(timeout=.5) + except queue.Empty: + if dirty and time.monotonic()-last_sync>=self.SYNC_INTERVAL: + self.file.flush();os.fsync(self.file.fileno());last_sync=time.monotonic();dirty=False + continue + if isinstance(row,threading.Event): + self.file.flush();row.set();continue + with self.lock:self.queued_bytes-=len(row) + self.file.write(row) + self.written+=1;dirty=True + if time.monotonic()-last_sync>=self.SYNC_INTERVAL: + self.file.flush();os.fsync(self.file.fileno());last_sync=time.monotonic();dirty=False + self.file.write((json.dumps({'type':'session_end','at_utc':datetime.now(timezone.utc).isoformat(), + 'written_records':self.written,'dropped_records':self.dropped,'drop_reasons':self.drop_reasons})+'\n').encode()) + self.file.flush();os.fsync(self.file.fileno()) + except (OSError,ValueError,TypeError) as error:self.error=type(error).__name__ + finally: + try:self.file.close() + except OSError as error:self.error=type(error).__name__ + finally:self.closed=True + + def finish(self): + with self.lock: + if self.closed or self.closing:return + self.closing=True + # Completion is polled. Never hold a request or a motor worker for disk. + + def external(self,origin,rows): + if not isinstance(rows,list) or len(rows)>64:raise ValueError('Invalid external trace') + for row in rows: + if not isinstance(row,dict) or type(row.get('record_sequence')) is not int:continue + seq=row['record_sequence'];previous=self.external_ack.get(origin,0) + if seq<=previous:continue + if len(json.dumps(row))>8192:continue + if seq>previous+1 and origin=='core': + if not self.append({'source':'recorder','event':'transport_gap','origin':origin,'after':previous,'before':seq}):break + if not self.append(row):break + self.external_ack[origin]=seq + + def status(self): + return {'file':str(self.path.relative_to(self.root)) if self.path else None, + 'closed':self.closed,'error':self.error,'written':self.written,'dropped':self.dropped, + 'external_ack':dict(self.external_ack),'queued_bytes':self.queued_bytes, + 'queued_records':self.queue.qsize(),'drop_reasons':dict(self.drop_reasons)} + + def chunk(self,identifier,offset,total=None,*,limit=4096,snapshot=None): + if identifier!=self.id or self.path is None:raise ValueError('Unknown session log') + if type(limit) is not int or not 1<=limit<=65536:raise ValueError('Invalid export block size') + if type(offset) is not int or offset<0:raise ValueError('Invalid file offset') + if self.closing and not self.closed: + self.thread.join(1) + if not self.closed:raise OSError("Writer is closing") + if total is None and not self.closed: + flushed=threading.Event() + self.queue.put(flushed,timeout=1) + if not flushed.wait(1):raise OSError('Writer flush timed out') + size=self.path.stat().st_size + if total is None:total=size + if type(total) is not int or not 0<=offset<=total<=size:raise ValueError('Invalid export snapshot') + with self.path.open('rb') as stream: + stat=os.fstat(stream.fileno()) + prefix=stream.read(min(4096,total)) + identity=hashlib.sha256(f'{identifier}:{stat.st_dev}:{stat.st_ino}:{total}:'.encode()+prefix).hexdigest() + if snapshot is not None and snapshot!=identity:raise ValueError('Export snapshot changed') + stream.seek(offset);raw=stream.read(min(limit,total-offset)) + if len(raw)!=min(limit,total-offset):raise OSError('Export snapshot truncated') + return {'capture_id':identifier,'offset':offset,'total_bytes':total,'next':offset+len(raw), + 'data':base64.b64encode(raw).decode(),'file':self.path.name, + 'snapshot':identity,'sha256':hashlib.sha256(raw).hexdigest()} diff --git a/plugins/vesc/runtime/swd.py b/plugins/vesc/runtime/swd.py new file mode 100644 index 00000000..d6dba078 --- /dev/null +++ b/plugins/vesc/runtime/swd.py @@ -0,0 +1,20 @@ +"""Declared main-flash SWD jobs. Staging never connects or halts a target.""" +TARGETS=[(1,'STM32F40x',2048),(2,'NRF51822 · 128K / 16K',128), + (3,'NRF51822 · 256K / 16K',256),(4,'NRF51822 · 256K / 32K',256), + (5,'NRF52832 · 256K / 32K',256),(6,'NRF52832 · 256K / 64K',256), + (7,'NRF52832 · 512K / 64K',512),(8,'NRF52840 · 1M / 256K',1024), + (9,'STM32F30x',2048),(10,'STM32L47x',2048),(11,'STM32G43',2048), + (12,'STM32G47',2048),(13,'STM32G49',2048)] + + +def validate(p): + if not isinstance(p,dict) or set(p)!={'target_code','pins','address','flash_bytes'}: + raise ValueError('Exact SWD target, pins and main flash range required') + code=p['target_code'] + if type(code) is not int or not 1<=code<=13 or p['pins'] not in ('default','nrf5x'): + raise ValueError('Unsupported SWD target or pin mapping') + base=0 if 2<=code<=8 else 0x08000000 + cap=TARGETS[code-1][2]*1024 + if (type(p['address']) is not int or type(p['flash_bytes']) is not int or p['address']base+cap): + raise ValueError('SWD image must remain inside declared main flash') diff --git a/plugins/vesc/runtime/transport_hub.py b/plugins/vesc/runtime/transport_hub.py new file mode 100644 index 00000000..23bd4a63 --- /dev/null +++ b/plugins/vesc/runtime/transport_hub.py @@ -0,0 +1,226 @@ +"""Physical transports and stable controller projections; no movement commands.""" + +import base64 +import contextlib +import copy +import json +import time +from dataclasses import dataclass + +from .can_bridge import Attachment as CanAttachment +from .can_bridge import inventory +from .configuration import decode +from .serial import device_id + +BAUD = (125000, 250000, 500000, 1000000, 10000, 20000, 50000, 75000, 100000) + + +@dataclass(frozen=True) +class Missing: + uuid: str + + @property + def id(self): + return device_id("uuid:" + self.uuid) + + @property + def binding(self): + return "missing:" + self.uuid + + usb = "—" + address = "unavailable" + tty = "unavailable" + speed = "—" + + +class TransportHub: + def __init__(self, service, atomic, can_inventory=None): + self.s, self.atomic = service, atomic + self.fetch = can_inventory or ( + inventory + if getattr(service.link_factory, "__name__", "") == "NativeLink" + else lambda: [] + ) + self.pool = service.devices + self.missing = {} + self.adapters = [] + self.hint_retry = {} + self.path = service.root / "controller-identities.json" + self.known = json.loads(self.path.read_text()) if self.path.exists() else {} + # Reuse verified immutable backups to find a previously USB-connected VESC. + for binding in service.drive.value["bindings"].values(): + identifier = binding["device_id"] + if identifier in self.known: + continue + records = service.archive.listing("local", identifier)["items"] + if not records: + continue + document = service.archive.read("local", identifier, records[0]["id"]) + try: + config = decode( + base64.b64decode(document["configs"]["application"]["payload"]), "application" + ) + self.remember(document["identity"], config) + except (KeyError, ValueError, IndexError): + pass + + def remember(self, identity, config=None): + identifier = device_id("uuid:" + identity["uuid"]) + value = {**self.known.get(identifier, {}), "identity": copy.deepcopy(identity)} + if config is not None: + value.update( + can_id=int(config["controller_id"]), bitrate=BAUD[int(config["can_baud_rate"])] + ) + if self.known.get(identifier) != value: + self.known[identifier] = value + self.atomic(self.path, self.known) + + @staticmethod + def route(device): + a = device.attachment + if isinstance(a, CanAttachment): + return a.route + return {"kind": "usb", "uuid": device.identity["uuid"]} if device.identity else None + + def endpoints(self): + return [ + { + "device_id": d.id, + "attachment_id": d.attachment.id, + "uuid": d.identity["uuid"], + "route": self.route(d), + "verified": bool( + d.link and getattr(d.link, "alive", True) and d.identified_session == d.session + ), + "session_id": d.session, + } + for d in list(self.pool.values()) + if d.identity + ] + + def select(self): + s = self.s + profile = s.transport.snapshot(s.drive.value, self.endpoints()) + assigned = {b["device_id"]: b for b in s.drive.value["bindings"].values()} + chosen = { + k: d + for k, d in self.pool.items() + if d.id not in assigned and not isinstance(d.attachment, CanAttachment) + } + for identifier, binding in assigned.items(): + matches = [ + (k, d) + for k, d in self.pool.items() + if d.id == identifier and self.route(d) == profile["routes"].get(identifier) + ] + if matches: + chosen.update(matches) + else: + if identifier not in self.missing: + d = self.s.device_type(Missing(binding["uuid"])) + d.identity = copy.deepcopy(self.known.get(identifier, {}).get("identity")) + d.id = identifier + d.error = "Выбранное подключение недоступно." + self.missing[identifier] = d + chosen[self.missing[identifier].attachment.binding] = self.missing[identifier] + with s.lock: + s.devices = {k: chosen[k] for k in self.pool if k in chosen} + s.devices.update({k: d for k, d in chosen.items() if k not in self.pool}) + + def scan(self): + s = self.s + usb = {a.binding: a for a in s.discover_fn()} + try: + self.adapters = self.fetch() + except (OSError, ValueError, KeyError): + self.adapters = [] + wanted = dict(usb) + bindings = s.drive.value["bindings"] + explicit = s.transport.value["routes"] + from .control_transport import BITRATES + + for i, b in enumerate(bindings.values()): + known = self.known.get(b["device_id"], {}) + route = explicit.get(b["device_id"], {}) + for adapter in self.adapters: + candidates = [] + if route.get("kind") == "can" and route["adapter_id"] == adapter["id"]: + candidates.append((route["channel"], route["can_id"], route["bitrate"])) + elif "can_id" in known and known["bitrate"] in BITRATES: + candidates.extend( + (ch, known["can_id"], known["bitrate"]) for ch in range(adapter["channels"]) + ) + for ch, target, bitrate in candidates: + sender = 254 - i + if sender == target: + sender = 245 - i + a = CanAttachment( + adapter["id"], adapter["session_id"], ch, target, bitrate, sender, b["uuid"] + ) + wanted[a.binding] = a + removed = [ + self.pool.pop(k) for k, d in list(self.pool.items()) if wanted.get(k) != d.attachment + ] + for key, a in wanted.items(): + if key not in self.pool: + d = s.device_type(a) + if isinstance(a, CanAttachment): + d.identity = copy.deepcopy(self.known.get(a.id, {}).get("identity")) + self.pool[key] = d + self.select() # Invalidate old generations before waiting on a hardware lock. + for d in removed: + d.close() + owned = s.operation_lock.acquire(False) + if not owned: + return + try: + can_attempted = False + for d in list(self.pool.values()): + if d.link and not getattr(d.link, "alive", True): + with d.lock: + error = (d.link.failure_error() if hasattr(d.link, "failure_error") + else OSError("Native transport exited")) + d.failed(error, "connection-exit") + if d.link is None and time.monotonic() >= d.retry_at: + is_can = isinstance(d.attachment, CanAttachment) + if is_can and can_attempted: + continue + can_attempted |= is_can + d.connect(s.link_factory) + if d.identity and d.link: + self.remember(d.identity) + if ( + self.adapters + and d.id in {b["device_id"] for b in bindings.values()} + and not isinstance(d.attachment, CanAttachment) + and d.identity["version"] == "5.02" + and time.monotonic() >= self.hint_retry.get(d.session, 0) + ): + self.hint_retry = { + d.session: time.monotonic() + 60, + **{k: v for k, v in self.hint_retry.items() if v > time.monotonic()}, + } + with d.lock, contextlib.suppress(OSError, ValueError, KeyError, IndexError): + self.remember(d.identity, decode(d.link.query(17), "application")) + self.select() + finally: + s.operation_lock.release() + + def profile(self): + return self.s.transport.snapshot(self.s.drive.value, self.endpoints()) + + def assert_devices(self, devices, pinned): + if pinned is not None: + self.s.transport.assert_pinned(pinned, self.s.drive.value, self.endpoints()) + usb = set(self.s.discover_fn()) + if all(not isinstance(d.attachment, CanAttachment) for d in devices) and usb != { + d.attachment for d in devices + }: + raise ValueError("Состав USB-контроллеров изменился.") + for d in devices: + if not d.link: + raise ValueError("Выбранное подключение недоступно.") + if isinstance(d.attachment, CanAttachment): + d.link.check() + elif d.attachment not in usb: + raise ValueError("Подключение USB изменилось.") diff --git a/plugins/vesc/tests/test_bms.py b/plugins/vesc/tests/test_bms.py new file mode 100644 index 00000000..aa4b5a8f --- /dev/null +++ b/plugins/vesc/tests/test_bms.py @@ -0,0 +1,79 @@ +"""BMS command intent/fault coverage; no batteries, USB or motor operations.""" +import copy +import unittest +from unittest.mock import patch +import test_config_editor +from runtime.bms import validate + + +class BmsTests(unittest.TestCase): + def setUp(self): + self.base=test_config_editor.ConfigEditorTests();self.base.setUp() + self.service,self.device=self.base.service,self.base.device + self.clock=[0.];self.service.bms.clock=lambda:self.clock[0] + self.target={'can_id':17,'uuid':'ab'*12,'hardware':'SYNTHETIC_BMS','major':6,'minor':0,'hardware_type':1,'test_firmware':0} + self.data={'state':'received','commands_supported':True,'target':self.target,'values':{'v_cells':[3.7,3.8],'i_in':0.,'i_in_ic':0.}} + self.calls=[] + self.device.link.bms_read=lambda can_id:copy.deepcopy(self.data) + self.device.link.bms_command=self.native + def tearDown(self):self.base.tearDown() + def native(self,target,command): + records=list(self.service.root.glob('bms-command-op_*.json')) + self.assertEqual(len(records),1) # intent durable before the first send + self.calls.append((target,command));return {'sent':True} + def command(self,name,params): + c=self.base.command(action='vesc.bms.'+name);c['parameters']=params;return c + def call(self,name,params):return self.service.execute(self.command(name,params)) + def prepare(self,command='charge_disable'): + r=self.call('prepare',{'can_id':17,'command':command});self.assertEqual(r['state'],'complete',r) + return r['result']['preview_id'] + def apply_command(self,plan):return self.command('apply',{'preview_id':plan,'confirmed':True,'inputs_isolated':True}) + def test_preview_reads_only_and_apply_is_sent_not_acknowledged(self): + plan=self.prepare();self.assertEqual(self.calls,[]) + c=self.apply_command(plan);result=self.service.execute(c) + self.assertEqual(result['result']['state'],'sent_unconfirmed',result) + self.assertFalse(result['result']['acknowledged']) + self.assertEqual(self.service.execute(c),result) + self.assertEqual(len(self.calls),1) + self.assertEqual(self.service.execute(self.apply_command(plan))['state'],'error') + def test_timeout_consumes_preview_without_retry(self): + def lost(target,command):self.calls.append(command);raise TimeoutError('synthetic disconnect') + self.device.link.bms_command=lost + plan=self.prepare();c=self.apply_command(plan) + r=self.service.execute(c);self.assertEqual(r['result']['state'],'unknown') + self.assertEqual(self.service.execute(c),r) + self.assertEqual(self.service.execute(self.apply_command(plan))['state'],'error') + self.assertEqual(len(self.calls),1) + def test_changed_bms_or_controller_session_cannot_receive_old_intent(self): + for change in ('uuid','session','expired'): + plan=self.prepare() + original=copy.deepcopy(self.target);session=self.device.session + if change=='uuid':self.target['uuid']='cd'*12 + if change=='session':self.device.session='new' + if change=='expired':self.clock[0]+=60 + self.assertEqual(self.service.execute(self.apply_command(plan))['state'],'error') + self.target.update(original);self.device.session=session + self.assertEqual(self.calls,[]) + def test_wrong_type_or_missing_cells_never_prepare_write(self): + self.data['commands_supported']=False;self.data['state']='not_bms' + self.assertEqual(self.call('prepare',{'can_id':17,'command':'charge_enable'})['state'],'error') + self.data.update(state='received',commands_supported=True);self.data['values']['v_cells']=[] + self.assertEqual(self.call('prepare',{'can_id':17,'command':'charge_enable'})['state'],'error') + self.assertEqual(self.calls,[]) + def test_calibration_rejects_battery_load_and_pending_config(self): + plan=self.prepare('zero_current');self.data['values']['i_in_ic']=1. + self.assertEqual(self.service.execute(self.apply_command(plan))['state'],'error') + with patch.object(self.service.config_editor,'pending',return_value={'state':'unknown'}): + self.assertEqual(self.service.execute(self.apply_command(plan))['state'],'error') + self.assertEqual(self.calls,[]) + def test_snapshot_payload_is_volatile(self): + import json + c=self.command('read',{'can_id':17});self.assertEqual(self.service.execute(c)['state'],'complete') + persisted=json.loads((self.service.root/(c['operation_id']+'.json')).read_text()) + self.assertTrue(persisted['snapshot_only']);self.assertNotIn('values',str(persisted)) + def test_validation_rejects_broadcast_motor_actions_and_unconfirmed_writes(self): + for address in (-1,254,255,True,'17',1.5): + with self.assertRaises(ValueError):validate('vesc.bms.read',{'can_id':address}) + for command in ('motor_run','set_duty','charge_enable\nset_current 10'): + with self.assertRaises(ValueError):validate('vesc.bms.prepare',{'can_id':17,'command':command}) + with self.assertRaises(ValueError):validate('vesc.bms.apply',{'preview_id':'bms_'+'a'*32,'confirmed':False,'inputs_isolated':True}) diff --git a/plugins/vesc/tests/test_can_transport.py b/plugins/vesc/tests/test_can_transport.py new file mode 100644 index 00000000..e0be79f5 --- /dev/null +++ b/plugins/vesc/tests/test_can_transport.py @@ -0,0 +1,328 @@ +"""Synthetic CAN fixtures. No real sockets, adapters or motors.""" + +import copy +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from runtime.can_bridge import Attachment +from runtime.can_protocol import Reassembly, fragment, serial_frame +from runtime.protocol import Decoder +from runtime.serial import Attachment as UsbAttachment +from runtime.serial import device_id +from runtime.service import Device, Service +from test_motor_test import configuration +from test_reader import FakeLink, fw + + +def replies(payload, target=74, sender=254): + frames = fragment(payload, sender, target) + for f in frames: + if f["id"] >> 8 in (7, 8): + data = bytearray.fromhex(f["data"]) + data[1] = 1 + f["data"] = data.hex() + f.update(extended=True, fd=False, rtr=False, error=False) + return frames + + +def hub_service(tmp_path): + usb = [UsbAttachment("1-2", "1", "ttyACM0", "12")] + + class Link: + def __init__(self, a): + self.attachment = a + self.alive = True + + def query(self, code, timeout=2): + if code == 0: + return b"\x00\x05\x02" + fw(1)[3:] + if code == 17: + return configuration("application", {"controller_id": 74, "can_baud_rate": 2}) + raise ValueError("Unexpected hardware operation in inert fixture") + + def close(self): + self.alive = False + + def check(self): + if not self.alive: + raise OSError("detached") + + s = Service(tmp_path, lambda: usb, Link) + s.scan() + d = next(iter(s.devices.values())) + s.drive.value = { + "revision": 1, + "layout": "1x1", + "bindings": {"left.1": {"device_id": d.id, "uuid": d.identity["uuid"]}}, + } + adapter = { + "id": "usbcan_" + "a" * 32, + "session_id": "one", + "name": "Synthetic CAN", + "channels": 1, + } + s.transports.fetch = lambda: [adapter] + s.scan() + s.scan() + return (s, usb, d, adapter) + + +import tempfile +import unittest +from unittest.mock import patch +import test_reader as command_helpers + + +class TransportTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.tmp_path = Path(temporary.name) + + def test_upstream_short_long_crc_roundtrip_1(self): + size = 1 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_upstream_short_long_crc_roundtrip_2(self): + size = 6 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_upstream_short_long_crc_roundtrip_3(self): + size = 7 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_upstream_short_long_crc_roundtrip_4(self): + size = 255 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_upstream_short_long_crc_roundtrip_5(self): + size = 256 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_upstream_short_long_crc_roundtrip_6(self): + size = 259 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_upstream_short_long_crc_roundtrip_7(self): + size = 260 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_upstream_short_long_crc_roundtrip_8(self): + size = 1000 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_upstream_short_long_crc_roundtrip_9(self): + size = 10000 + data = bytes((i % 251 for i in range(size))) + rx = Reassembly(74, 254) + values = [rx.feed(f) for f in replies(data)] + assert [v for v in values if v is not None] == [data] + assert Decoder().feed(serial_frame(data)) == [data] + + def test_bridge_diagnostics_count_replies_without_retaining_payloads(self): + import time + from runtime.can_bridge import Bridge + bridge = object.__new__(Bridge) + bridge.error = None + bridge.client = None + bridge.sent_at = time.monotonic() - .08 + bridge.metrics = {"requests": 1, "responses": 0, "rx_frames": 0, + "last_request": 4, "last_response": None, + "send_ms": 20, "response_ms": None} + rx = Reassembly(74, 254) + for f in replies(bytes([4]) + bytes(80)): + bridge.received(f, rx) + diagnostic = bridge.diagnostics() + self.assertEqual(diagnostic["responses"], 1) + self.assertEqual(diagnostic["last_response"], 4) + self.assertGreaterEqual(diagnostic["response_ms"], 80) + self.assertNotIn("frames", diagnostic) + self.assertNotIn("payload", diagnostic) + self.assertNotIn("data", diagnostic) + diagnostic["responses"] = 999 + self.assertEqual(bridge.diagnostics()["responses"], 1) + + def test_missing_fragment_crc_and_stale_response_are_rejected(self): + data = b"a" * 300 + fs = replies(data) + rx = Reassembly(74, 254) + rx.feed(fs[0]) + with self.assertRaises(ValueError): + rx.feed(fs[2]) + clock = [0.0] + rx = Reassembly(74, 254, lambda: clock[0]) + for f in fs[:-1]: + rx.feed(f) + clock[0] = 2 + with self.assertRaises(ValueError): + rx.feed(fs[-1]) + rx = Reassembly(74, 254) + for f in fs[:-1]: + rx.feed(f) + broken = copy.deepcopy(fs[-1]) + broken["data"] = broken["data"][:-2] + "ff" + with self.assertRaises(ValueError): + rx.feed(broken) + + def test_other_target_and_remote_frame_never_become_reply(self): + rx = Reassembly(74, 254) + assert rx.feed(replies(b"\x00", target=111)[0]) is None + f = replies(b"\x00")[0] + f["rtr"] = True + assert rx.feed(f) is None + + def test_dead_can_link_preserves_original_failure_before_cleanup(self): + s, usb, d, adapter = hub_service(self.tmp_path) + can = next(x for x in s.transports.pool.values() if isinstance(x.attachment, Attachment)) + can.link.alive = False + can.link.failure_error = lambda: OSError("CAN bridge: poll: adapter busy") + can.retry_at = float("inf") + with patch("runtime.service.failure") as report: + s.scan() + assert can.link is None + assert any("poll: adapter busy" in str(call.args[0]) for call in report.call_args_list) + + def test_can_controller_uuid_must_match_binding(self): + a = Attachment("usbcan_" + "a" * 32, "one", 0, 74, 500000, 254, "02" * 12) + d = Device(a) + + class Wrong(FakeLink): + def query(self, *a): + return fw(1) + + d.connect(Wrong) + assert d.link is None and d.identified_session is None + assert d.id == device_id("uuid:" + "02" * 12) + + def test_same_uuid_is_one_device_and_saved_can_ignores_usb_detach(self): + s, usb, d, adapter = hub_service(self.tmp_path) + endpoints = s.transports.endpoints() + assert {e["route"]["kind"] for e in endpoints} == {"usb", "can"} + assert len(s.inventory("synthetic")["items"]) == 1 + route = next((e["route"] for e in endpoints if e["route"]["kind"] == "can")) + s.transport.update( + {"revision": 0, "drive_revision": 1, "routes": {d.id: route}}, s.drive.value + ) + s.transports.select() + selected = next(iter(s.devices.values())) + assert isinstance(selected.attachment, Attachment) + pin = s.transport.pin(s.drive.value, s.transports.endpoints()) + usb.clear() + s.scan() + s.transports.assert_devices([selected], pin) + adapter["session_id"] = "replacement" + s.scan() + with self.assertRaises(ValueError): + s.transports.assert_devices([selected], pin) + + def test_no_endpoints_is_unavailable_and_offline_assignment_stays_editable(self): + s, usb, d, adapter = hub_service(self.tmp_path) + usb.clear() + s.transports.fetch = lambda: [] + s.scan() + assert s.transports.profile()["routes"] == {} + item = s.inventory("synthetic")["items"][0] + assert item["id"] == d.id and (not item["online"]) and (not item["verified"]) + assert item["vesc_status"]["board_settings_supported"] + + def test_implicit_only_can_and_explicit_usb_do_not_fall_back(self): + s, usb, d, adapter = hub_service(self.tmp_path) + usb.clear() + s.scan() + assert s.transports.profile()["routes"][d.id]["kind"] == "can" + s.transport.update( + { + "revision": 0, + "drive_revision": 1, + "routes": {d.id: {"kind": "usb", "uuid": d.identity["uuid"]}}, + }, + s.drive.value, + ) + s.transports.select() + assert not next(iter(s.devices.values())).link + with self.assertRaises(ValueError): + s.transport.pin(s.drive.value, s.transports.endpoints()) + + def test_tool_reads_follow_board_selection_and_retire_old_session(self): + s, usb, initial, adapter = hub_service(self.tmp_path) + helper = command_helpers.ServiceTests() + helper.service = s + for kind in ("can", "usb"): + old = helper.command(action="details") + route = next(e["route"] for e in s.transports.endpoints() if e["route"]["kind"] == kind) + save = helper.command(action="vesc.transport.configure") + save["parameters"] = { + "revision": s.transport.value["revision"], + "drive_revision": 1, + "routes": {initial.id: route}, + } + self.assertEqual(s.execute(save)["state"], "complete") + with self.assertRaisesRegex(ValueError, "Device session changed"): + s.execute(old) + selected = next(iter(s.devices.values())) + unselected = next(d for d in s.transports.pool.values() if d is not selected) + with ( + patch.object( + unselected.link, "query", side_effect=AssertionError("Wrong transport") + ), + patch.object( + selected.link, + "device_tool", + create=True, + return_value={"values": {"synthetic": True}}, + ) as read, + ): + command = helper.command(action="vesc.tools.read") + command["parameters"] = {"tool": "adc"} + result = s.execute(command) + self.assertEqual(result["state"], "complete", result) + self.assertTrue(result["result"]["values"]["synthetic"]) + read.assert_called_once_with("adc") + + def test_selected_can_loss_keeps_offline_settings_without_online_status(self): + s, usb, d, adapter = hub_service(self.tmp_path) + route = next(e["route"] for e in s.transports.endpoints() if e["route"]["kind"] == "can") + s.transport.update( + {"revision": 0, "drive_revision": 1, "routes": {d.id: route}}, s.drive.value + ) + s.transports.select() + selected = next(iter(s.devices.values())) + selected.close() + item = s.inventory("synthetic")["items"][0] + assert item["id"] == d.id + assert not item["online"] and not item["verified"] + assert item["vesc_status"]["control_transport"]["routes"][d.id] == route + assert item["vesc_status"]["board_settings_supported"] diff --git a/plugins/vesc/tests/test_config_editor.py b/plugins/vesc/tests/test_config_editor.py new file mode 100644 index 00000000..5285b16a --- /dev/null +++ b/plugins/vesc/tests/test_config_editor.py @@ -0,0 +1,204 @@ +"""Synthetic transaction fault injection; never touches hardware.""" +import base64 +import hashlib +import struct +import unittest +from unittest.mock import call, patch + +import test_reader +from test_motor_test import configuration +from runtime.config_editor import ConfigEditor, packet_hashes +from runtime.protocol import firmware + + +class ConfigEditorTests(unittest.TestCase): + setUpBase = test_reader.ServiceTests.setUp + tearDown = test_reader.ServiceTests.tearDown + command = test_reader.ServiceTests.command + + def setUp(self): + self.setUpBase() + self.device = next(iter(self.service.devices.values())) + self.raw_identity = b'\0\5\2SYNTHETIC\0' + b'\1'*12 + bytes(4) + self.device.identity = firmware(self.raw_identity) + self.raw = {'motor': configuration('motor', {'l_current_max':30}), + 'application': configuration('application', {'app_to_use':1,'app_ppm_conf.ctrl_type':4,'app_ppm_conf.hyst':.15})} + self.writes = [] + self.clock = [0] + self.editor = self.service.config_editor + self.editor.clock = lambda:self.clock[0] + self.device.link.query = self.query + self.device.link.configuration_preview = self.preview_native + self.device.link.configuration_apply = self.write_native + + def query(self, code, timeout=2): + if code == 0: return self.raw_identity + if code in (14,17): return self.raw['motor' if code==14 else 'application'] + if code == 31: return bytes([31])+struct.pack('>ii',0,1500000) + if code == 4: return bytes([4])+struct.pack('>hhiiiihihiiiiiiB',250,250,0,0,0,0,0,0,480,0,0,0,0,0,0,0) + raise AssertionError(code) + + def preview_native(self, sources): + configs={} + for kind,source in sources.items(): + after=base64.b64decode(source['payload']) if 'payload' in source else configuration(kind,{'l_current_max':20}) + configs[kind]={'before_sha256':hashlib.sha256(self.raw[kind]).hexdigest(), + 'after_sha256':hashlib.sha256(after).hexdigest(),'payload':base64.b64encode(after).decode(), + 'changes':[{'name':'l_current_max','before':30,'after':20}]} + return {'configs':configs,'baseline':packet_hashes(self.raw)} + + def write_native(self, kind, target): + self.assertTrue(self.editor.pending(self.device)) + self.assertTrue(self.service.motor.latched) + self.writes.append(kind) + self.raw[kind]=base64.b64decode(target['payload']) + return {'verified':True} + + def preview(self): + command=self.command(action='vesc.configuration.preview') + command['parameters']={'kind':'motor','baseline':packet_hashes(self.raw),'changes':{'l_current_max':20}} + result=self.service.execute(command) + self.assertEqual(result['state'],'complete',result) + return result['result']['preview_id'] + + def apply_command(self, identifier): + command=self.command(action='vesc.configuration.apply') + command['parameters']={'preview_id':identifier,'rig_clear':True,'inputs_isolated':True} + return command + + def test_preview_never_writes_and_commit_backs_up_then_verifies_once(self): + identifier=self.preview() + self.assertEqual(self.writes,[]) + command=self.apply_command(identifier) + result=self.service.execute(command) + self.assertEqual(result['result']['outcome'],'applied',result) + self.assertIsNone(self.editor.pending(self.device)) + self.assertEqual(len(self.service.archive.listing('local',self.device.id)['items']),2) + self.assertEqual(self.service.execute(command),result) + self.assertEqual(self.writes,['motor']) + repeated=self.service.execute(self.apply_command(identifier)) + self.assertEqual(repeated['state'],'error') + self.assertEqual(self.writes,['motor']) + + def test_stale_configuration_and_session_cannot_write(self): + identifier=self.preview() + self.raw['application']=configuration('application',{'controller_id':99}) + self.assertEqual(self.service.execute(self.apply_command(identifier))['state'],'error') + self.assertEqual(self.writes,[]) + self.device.session='new-session' + self.assertEqual(self.service.execute(self.apply_command(identifier))['state'],'error') + self.assertEqual(self.writes,[]) + + def test_expired_preview_and_missing_confirmation_never_write(self): + identifier=self.preview();self.clock[0]=301 + self.assertEqual(self.service.execute(self.apply_command(identifier))['state'],'error') + command=self.apply_command(identifier);command['parameters']['inputs_isolated']=False + with self.assertRaises(ValueError):self.service.execute(command) + self.assertEqual(self.writes,[]) + + def test_lost_ack_persists_interlock_across_restart_and_read_only_reconciles(self): + identifier=self.preview() + def write(kind,target): + self.write_native(kind,target) + raise TimeoutError('lost ack') + self.device.link.configuration_apply=write + command=self.apply_command(identifier) + result=self.service.execute(command) + self.assertEqual(result['result']['outcome'],'unknown') + self.assertIsNotNone(self.editor.pending(self.device)) + self.service.config_editor=ConfigEditor(self.service,self.editor.atomic,self.editor.utc) + result=self.service.execute(self.command(action='vesc.configuration.reconcile')) + self.assertEqual(result['result']['outcome'],'applied') + self.assertIsNone(self.service.config_editor.pending(self.device)) + self.assertEqual(self.writes,['motor']) + self.assertEqual(self.service.execute(command)['result']['outcome'],'unknown') + self.assertEqual(self.writes,['motor']) + + def test_unknown_external_result_remains_blocked_and_retains_backup(self): + identifier=self.preview() + def write(kind,target): + self.writes.append(kind) + self.raw[kind]=configuration(kind,{'l_current_max':17}) + raise TimeoutError('partial') + self.device.link.configuration_apply=write + result=self.service.execute(self.apply_command(identifier)) + original=result['result']['before_backup_id'] + result=self.service.execute(self.command(action='vesc.configuration.reconcile')) + self.assertEqual(result['result']['outcome'],'different') + self.assertEqual(result['result']['before_backup_id'],original) + self.assertIsNotNone(self.editor.pending(self.device)) + command=self.command(action='vesc.configuration.preview');command['parameters']={'backup_id':original} + self.assertEqual(self.service.execute(command)['state'],'complete') + self.assertEqual(self.writes,['motor']) + + def test_archive_failure_or_nonzero_current_prevents_write(self): + identifier=self.preview() + with patch.object(self.service.archive,'add',side_effect=OSError('disk full')): + self.assertEqual(self.service.execute(self.apply_command(identifier))['state'],'error') + self.assertEqual(self.writes,[]) + self.service.motor.active=True + self.assertEqual(self.service.execute(self.apply_command(identifier))['state'],'error') + self.assertEqual(self.writes,[]) + + def idle_value(self, **changes): + return {"motor_current_a": -0.85, "input_current_a": 0.0, + "duty": 0.0, "erpm": 0.0, "fault_code": 0, "tachometer": 17, + **changes} + + def test_configuration_accepts_three_settled_offset_samples_before_single_write(self): + identifier = self.preview() + readings = [self.idle_value(motor_current_a=x) for x in (-0.85, -0.83, -0.86)] + with patch('runtime.config_editor.values', side_effect=readings) as read, \ + patch('runtime.config_editor.time.sleep') as sleep: + result = self.service.execute(self.apply_command(identifier)) + self.assertEqual(result['state'], 'complete', result) + self.assertEqual(result['result']['outcome'], 'applied') + self.assertEqual(read.call_count, 3) + self.assertEqual(sleep.call_args_list, [call(.25)] * 2) + self.assertEqual(self.writes, ['motor']) + + def test_configuration_rejects_output_motion_fault_nonfinite_or_interrupted_sample(self): + unsafe = [self.idle_value(**{key: value}) for key, value in ( + ('motor_current_a', 1.01), ('motor_current_a', -1.01), + ('input_current_a', 1.01), ('input_current_a', -1.01), + ('duty', .002), ('erpm', 2), ('fault_code', 1), + ('motor_current_a', float('nan')), ('input_current_a', float('inf')), + ('duty', float('nan')), ('erpm', float('nan')), + ('fault_code', float('nan')), ('tachometer', 18), + ('tachometer', float('nan')))] + unsafe.append(TimeoutError('sample missing')) + for middle in unsafe: + with self.subTest(middle=middle): + identifier = self.preview() + readings = [self.idle_value(), middle, self.idle_value()] + with patch('runtime.config_editor.values', side_effect=readings), \ + patch('runtime.config_editor.time.sleep'): + result = self.service.execute(self.apply_command(identifier)) + self.assertEqual(result['state'], 'error', result) + self.assertEqual(self.writes, []) + self.assertIsNone(self.editor.pending(self.device)) + + def test_configuration_rechecks_receiver_during_standstill_window(self): + identifier = self.preview() + with patch('runtime.config_editor.values', side_effect=[self.idle_value()] * 3), \ + patch('runtime.config_editor.ppm', side_effect=[{'level': 0}, {'level': .8}]), \ + patch('runtime.config_editor.time.sleep'): + result = self.service.execute(self.apply_command(identifier)) + self.assertEqual(result['state'], 'error', result) + self.assertEqual(self.writes, []) + + def test_preview_cache_is_bounded_and_evicted_plan_never_grants_write(self): + first=self.preview() + for _ in range(5): self.preview() + self.assertEqual(len(self.editor.plans),4) + self.assertEqual(self.service.execute(self.apply_command(first))['state'],'error') + self.assertEqual(self.writes,[]) + + def test_preview_baseline_conflict_and_foreign_backup_rejected(self): + command=self.command(action='vesc.configuration.preview') + command['parameters']={'kind':'motor','baseline':dict.fromkeys(('motor','application'),'0'*64),'changes':{'l_current_max':20}} + self.assertEqual(self.service.execute(command)['state'],'error') + backup=self.editor.backup(self.device,self.raw) + self.device.identity={**self.device.identity,'version':'6.00'} + with self.assertRaises(ValueError):self.editor.preview(self.device,{'backup_id':backup}) + self.assertEqual(self.writes,[]) diff --git a/plugins/vesc/tests/test_configuration_schema_cache.py b/plugins/vesc/tests/test_configuration_schema_cache.py new file mode 100644 index 00000000..615493c4 --- /dev/null +++ b/plugins/vesc/tests/test_configuration_schema_cache.py @@ -0,0 +1,39 @@ +"""Only immutable schema work may be reused; each controller reply is decoded.""" +import importlib +import unittest +from unittest.mock import patch + +from runtime import configuration as module +from test_motor_test import configuration + + +class SchemaTests(unittest.TestCase): + def test_cached_definition_does_not_cache_readback_or_skip_signature(self): + first = configuration('motor', {'l_current_max': 35}) + second = configuration('motor', {'l_current_max': 40}) + module._schema.cache_clear() + with patch.object(module.ET, 'parse', wraps=module.ET.parse) as parse, \ + patch.object(module, 'crc32c', wraps=module.crc32c) as crc: + a = module.decode(first, 'motor') + a['l_current_max'] = 999 + self.assertEqual(module.decode(first, 'motor')['l_current_max'], 35) + self.assertEqual(module.decode(second, 'motor')['l_current_max'], 40) + bad = first[:1] + bytes([first[1] ^ 1]) + first[2:] + with self.assertRaisesRegex(ValueError, 'signature'): + module.decode(bad, 'motor') + with self.assertRaisesRegex(ValueError, 'Truncated'): + module.decode(first[:-1], 'motor') + with self.assertRaisesRegex(ValueError, 'tail'): + module.decode(first + b'\0', 'motor') + self.assertEqual(parse.call_count, 1) + self.assertEqual(crc.call_count, 1) + self.assertEqual(module._schema.cache_info().maxsize, 2) + + def test_both_definitions_are_ready_before_the_first_controller_read(self): + with patch.object(module.ET, 'parse', wraps=module.ET.parse) as parse: + importlib.reload(module) + self.assertEqual(parse.call_count, 2) + self.assertEqual(module._schema.cache_info().currsize, 2) + raw = configuration('application', {'app_to_use': 1}) + with patch.object(module.ET, 'parse', side_effect=AssertionError('late schema I/O')): + self.assertEqual(module.decode(raw, 'application')['app_to_use'], 1) diff --git a/plugins/vesc/tests/test_control_transport.py b/plugins/vesc/tests/test_control_transport.py new file mode 100644 index 00000000..03d3c2a8 --- /dev/null +++ b/plugins/vesc/tests/test_control_transport.py @@ -0,0 +1,217 @@ +"""Pure profile tests: no sockets, native SDK, board or motor access.""" + +import copy +import importlib.util +import json +from pathlib import Path + +spec = importlib.util.spec_from_file_location( + "control_transport_test_module", + Path(__file__).resolve().parents[1] / "runtime/control_transport.py", +) +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) +UUIDS = ("1" * 24, "2" * 24) +DRIVE = { + "revision": 4, + "bindings": { + "left.1": {"device_id": "left", "uuid": UUIDS[0]}, + "right.1": {"device_id": "right", "uuid": UUIDS[1]}, + }, +} + + +def profile(tmp_path): + return m.ControlTransport(tmp_path, lambda p, v: p.write_text(json.dumps(v))) + + +def routes(): + return { + "left": { + "kind": "can", + "uuid": UUIDS[0], + "adapter_id": "usbcan_" + "a" * 32, + "channel": 0, + "can_id": 74, + "bitrate": 500000, + }, + "right": {"kind": "usb", "uuid": UUIDS[1]}, + } + + +def update(p, value=None, **kw): + return p.update( + {"revision": p.value["revision"], "drive_revision": 4, "routes": value or routes()}, + DRIVE, + **kw, + ) + + +def attachments(value): + return [ + {"device_id": k, "uuid": v["uuid"], "route": v, "verified": True, "session_id": k + "-one"} + for k, v in value.items() + ] + + +import tempfile +import unittest + + +class TransportTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.tmp_path = Path(temporary.name) + + def test_legacy_defaults_to_usb_without_writing(self): + p = profile(self.tmp_path) + assert {r["kind"] for r in p.snapshot(DRIVE)["routes"].values()} == {"usb"} + assert not p.path.exists() + + def test_mixed_selection_survives_restart_and_input_is_not_aliased(self): + p = profile(self.tmp_path) + value = routes() + update(p, value) + value["left"]["kind"] = "usb" + assert profile(self.tmp_path).snapshot(DRIVE)["routes"] == routes() + + def test_active_session_rejects_save(self): + p = profile(self.tmp_path) + with self.assertRaisesRegex(ValueError, "Остановите"): + update(p, active=True) + assert not p.path.exists() + + def test_stale_revision_rejects_save_1(self): + field = "revision" + p = profile(self.tmp_path) + value = {"revision": 0, "drive_revision": 4, "routes": routes()} + value[field] += 1 + with self.assertRaises(ValueError): + p.update(value, DRIVE) + assert not p.path.exists() + + def test_stale_revision_rejects_save_2(self): + field = "drive_revision" + p = profile(self.tmp_path) + value = {"revision": 0, "drive_revision": 4, "routes": routes()} + value[field] += 1 + with self.assertRaises(ValueError): + p.update(value, DRIVE) + assert not p.path.exists() + + def test_duplicate_address_rejected_but_independent_channels_allowed(self): + p = profile(self.tmp_path) + value = routes() + value["right"] = {**value["left"], "uuid": UUIDS[1]} + with self.assertRaises(ValueError): + update(p, value) + value["right"]["channel"] = 1 + update(p, value) + + def test_different_bitrates_on_same_bus_rejected(self): + p = profile(self.tmp_path) + value = routes() + value["right"] = {**value["left"], "uuid": UUIDS[1], "can_id": 111, "bitrate": 250000} + with self.assertRaises(ValueError): + update(p, value) + + def test_invalid_binding_rejected_1(self): + field = "can_id" + value = 255 + p = profile(self.tmp_path) + selected = routes() + selected["left"][field] = value + with self.assertRaises(ValueError): + update(p, selected) + + def test_invalid_binding_rejected_2(self): + field = "can_id" + value = True + p = profile(self.tmp_path) + selected = routes() + selected["left"][field] = value + with self.assertRaises(ValueError): + update(p, selected) + + def test_invalid_binding_rejected_3(self): + field = "channel" + value = 2 + p = profile(self.tmp_path) + selected = routes() + selected["left"][field] = value + with self.assertRaises(ValueError): + update(p, selected) + + def test_invalid_binding_rejected_4(self): + field = "channel" + value = False + p = profile(self.tmp_path) + selected = routes() + selected["left"][field] = value + with self.assertRaises(ValueError): + update(p, selected) + + def test_invalid_binding_rejected_5(self): + field = "bitrate" + value = 123456 + p = profile(self.tmp_path) + selected = routes() + selected["left"][field] = value + with self.assertRaises(ValueError): + update(p, selected) + + def test_invalid_binding_rejected_6(self): + field = "uuid" + value = "3" * 24 + p = profile(self.tmp_path) + selected = routes() + selected["left"][field] = value + with self.assertRaises(ValueError): + update(p, selected) + + def test_no_fallback_to_present_usb_after_can_disconnect(self): + p = profile(self.tmp_path) + update(p) + available = attachments(routes()) + pin = p.pin(DRIVE, available) + available[0]["route"] = {"kind": "usb", "uuid": UUIDS[0]} + with self.assertRaises(ValueError): + p.assert_pinned(pin, DRIVE, available) + assert p.value["routes"]["left"]["kind"] == "can" + + def test_can_id_without_verified_uuid_cannot_control(self): + p = profile(self.tmp_path) + update(p) + available = attachments(routes()) + available[0]["verified"] = False + with self.assertRaises(ValueError): + p.pin(DRIVE, available) + available[0]["verified"] = True + available[0]["uuid"] = "3" * 24 + with self.assertRaises(ValueError): + p.pin(DRIVE, available) + + def test_duplicate_or_reconnected_attachment_retires_pin(self): + p = profile(self.tmp_path) + update(p) + available = attachments(routes()) + pin = p.pin(DRIVE, available) + with self.assertRaises(ValueError): + p.pin(DRIVE, available + [copy.deepcopy(available[0])]) + available[0]["session_id"] = "new-generation" + with self.assertRaises(ValueError): + p.assert_pinned(pin, DRIVE, available) + + def test_whole_profile_save_and_motor_reassignment_invalidate_pin(self): + p = profile(self.tmp_path) + update(p) + available = attachments(routes()) + pin = p.pin(DRIVE, available) + update(p) + with self.assertRaises(ValueError): + p.assert_pinned(pin, DRIVE, available) + drive = copy.deepcopy(DRIVE) + drive["bindings"]["left.1"]["uuid"] = "3" * 24 + with self.assertRaises(ValueError): + p.pin(drive, available) diff --git a/plugins/vesc/tests/test_diagnostics.py b/plugins/vesc/tests/test_diagnostics.py new file mode 100644 index 00000000..873d1ea9 --- /dev/null +++ b/plugins/vesc/tests/test_diagnostics.py @@ -0,0 +1,106 @@ +"""Failure evidence survives cleanup without granting hardware authority.""" + +import json +import sys +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "src")) +from runtime.diagnostics import failure +from runtime.serial import Attachment +from runtime.service import Device + + +class FailureTests(unittest.TestCase): + def test_original_transport_failure_and_bounded_preceding_calls(self): + error = OSError("Native query timed out or disconnected") + error.native_rpc = {"command": 31, "attachment_present": True, + "transport": {"request_emitted": True, "packets_received": 0}} + error.native_history = [{"command": i} for i in range(32)] + with self.assertLogs("missioncore.vesc.failure") as capture: + failure(error, "remote_control", session_id="a" * 32, release_confirmed=False) + record = json.loads(capture.records[0].getMessage()) + self.assertEqual(record["native_rpc"], error.native_rpc) + self.assertEqual(record["native_history"], error.native_history[-8:]) + self.assertIs(record["release_confirmed"], False) + self.assertEqual(record["session_id"], "a" * 32) + + def test_native_startup_evidence_survives_cleanup(self): + error = OSError("Native VESC Tool exited") + error.native_startup = {"pid": 123, "exit_code": 1, + "stderr_tail": "synthetic missing runtime component", + "stderr_truncated": False} + with self.assertLogs("missioncore.vesc.failure") as capture: + failure(error, "connection") + record = json.loads(capture.records[0].getMessage()) + self.assertEqual(record["native_startup"], error.native_startup) + error.native_startup = {"stderr_tail": "x" * 64000} + with self.assertLogs("missioncore.vesc.failure") as capture: + failure(error, "connection") + self.assertLess(len(capture.records[0].getMessage().encode()), 16000) + + def test_journal_size_bound_preserves_summary(self): + error = OSError("x" * 20000) + error.native_rpc = {"unexpected": "x" * 32000} + error.native_history = [{"unexpected": "x" * 32000}] * 32 + with self.assertLogs("missioncore.vesc.failure") as capture: + failure(error, "remote_control") + raw = capture.records[0].getMessage() + self.assertLess(len(raw.encode()), 16000) + record = json.loads(raw) + self.assertTrue(record["history_omitted"]) + self.assertTrue(record["rpc_omitted"]) + self.assertEqual(record["type"], "OSError") + + def test_logging_failure_cannot_prevent_owner_cleanup(self): + with patch("runtime.diagnostics.LOGGER.warning", + side_effect=OSError("journal unavailable")): + failure(OSError("read failed"), "remote_control") + failure(OSError("read failed"), "connection", device=SimpleNamespace()) + + def test_connection_failures_remain_backed_off_and_rate_limited(self): + device = Device(Attachment("1-2", "3", "ttyACM0", "12")) + def factory(_): + raise OSError("Native VESC Tool did not connect") + with (patch("runtime.service.time.monotonic", return_value=100), + self.assertLogs("missioncore.vesc.failure") as capture): + device.connect(factory) + device.connect(factory) + self.assertEqual(len(capture.records), 1) + record = json.loads(capture.records[0].getMessage()) + self.assertEqual(record["attachment"]["tty"], "ttyACM0") + self.assertIsNone(device.link) + self.assertEqual(device.retry_at, 104) + + +class ConnectionEvidenceTests(unittest.TestCase): + def test_detach_keeps_old_uuid_session_and_last_sample(self): + device = Device(Attachment("1-2", "3", "ttyACM0", "12")) + device.identity = {"uuid": "a"*24, "version": "5.02"} + device.link = SimpleNamespace(close=lambda: None) + device.publish_sample({"erpm": 0, "fault_code": 0}, None) + old_session = device.session + with self.assertLogs("missioncore.vesc.failure", level="INFO") as capture: + device.close() + data = json.loads(capture.records[0].getMessage()) + self.assertEqual(data["transition"], "usb_detached") + self.assertEqual(data["session_id"], old_session) + self.assertEqual(data["identity"]["uuid"], "a"*24) + self.assertEqual(data["last_values"]["erpm"], 0) + self.assertIsNone(device.sample) + self.assertNotEqual(device.session, old_session) + + def test_recovery_logs_first_sample_only_and_failure_keeps_old_session(self): + device = Device(Attachment("1-2", "3", "ttyACM0", "12")) + device.link = SimpleNamespace(close=lambda: None) + old = device.session + with self.assertLogs("missioncore.vesc.failure", level="INFO") as capture: + device.publish_sample({"erpm":0}, None) + device.publish_sample({"erpm":0}, None) + device.failed(OSError("USB went away"), "observation") + data = [json.loads(x.getMessage()) for x in capture.records] + self.assertEqual([x.get("transition") for x in data], ["sample_restored", "read_failed", None]) + self.assertTrue(all(x["session_id"] == old for x in data)) diff --git a/plugins/vesc/tests/test_drive_diagnostics.py b/plugins/vesc/tests/test_drive_diagnostics.py new file mode 100644 index 00000000..870c0b13 --- /dev/null +++ b/plugins/vesc/tests/test_drive_diagnostics.py @@ -0,0 +1,149 @@ +import base64 +import json +import tempfile +import unittest +from pathlib import Path +from runtime.drive_diagnostics import DriveDiagnostics +from runtime.session_log import SessionLog + +class DiagnosticsTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) + self.trace=DriveDiagnostics(self.tmp.name);self.id='a'*32 + self.body={'id':self.id,'enabled':True,'after':0,'vehicle':'Rover 006'} + self.addCleanup(self.close) + def close(self): + self.trace.log.finish() + if self.trace.log.thread:self.trace.log.thread.join(2) + def test_off_has_no_file_and_invalid_session_does_not_enable(self): + self.trace.add('motor',left=1) + self.assertFalse(list(Path(self.tmp.name).rglob('*'))) + with self.assertRaises(ValueError):self.trace.exchange({**self.body,'id':'../../x'}) + self.assertFalse(self.trace.active()) + def test_complete_file_outlives_ram_and_has_no_hour_limit(self): + self.trace.MAX_ROWS=3;self.trace.exchange(self.body) + now=[0];self.trace.clock=lambda:now[0] + for n in range(10): + now[0]=n*3600;self.trace.add('sample',index=n) + self.assertTrue(self.trace.active());self.assertEqual(len(self.trace.snapshot()['frames']),3) + self.trace.exchange({**self.body,'enabled':False});self.close() + before=self.trace.log.path.read_bytes() + self.trace.add('late');self.trace.exchange(self.body) + self.assertFalse(self.trace.active());self.assertEqual(before,self.trace.log.path.read_bytes()) + rows=[json.loads(line) for line in before.splitlines()] + self.assertEqual([r['index'] for r in rows if 'index' in r],list(range(10))) + self.assertEqual(rows[-1]['type'],'session_end') + self.assertEqual(len(list(Path(self.tmp.name).rglob('*.jsonl'))),1) + self.assertEqual(self.trace.log.path.stat().st_mode&0o777,0o600) + def test_export_flushes_live_file_then_keeps_snapshot_size(self): + self.trace.exchange(self.body) + for n in range(30):self.trace.add('sample',value='x'*3000,index=n) + first=self.trace.log.chunk(self.id,0) + self.trace.add('later',value='not_in_snapshot') + chunks=[base64.b64decode(first['data'])];offset=first['next'] + while offset'}} + if method=='custom_read':return current + after=base64.b64decode(p['source']['payload']) if p.get('source',{}).get('payload') else b'BMS-after' + if method=='custom_preview':return {**current,'candidate':{'before_sha256':sha(self.payload),'after_sha256':sha(after),'payload':b64(after),'changes':[{'name':'max_bal_ch','before':4,'after':2}]}} + if method=='custom_apply': + assert self.service.bms_configuration.pending(self.device) + assert list(self.service.root.glob('bms-configuration-backup-*')) + self.payload=after + if self.lost:raise TimeoutError('ACK lost') + return {'verified':True} + if method=='code_read':return {'sha256':sha(self.code),'bytes':len(self.code),'source':self.code.decode(),'imports':{},'project':{'kind':p['kind'],'source':self.code.decode(),'imports':{},'fullscreen':self.fullscreen}} + if method=='code_pack':return {'image':b64(b'12345678'+p['project']['source'].encode())} + if method=='code_write': + assert self.service.code_tools.pending(self.device) + assert list(self.service.root.glob('code-backup-*')) + self.code=base64.b64decode(p['image'])[8:] + if self.lost:raise TimeoutError('ACK lost') + return {'verified':True} + if method=='code_control': + assert self.service.code_tools.path(self.device,'execution').exists() + if self.lost:raise TimeoutError('control lost') + return {'acknowledged':True,'command':p['command']} + raise AssertionError(method) + def preview(self): + r=self.call('vesc.bms.configuration.preview',{'can_id':17,'index':0,'baseline':sha(self.payload),'schema_sha256':self.schema,'changes':{'max_bal_ch':2}}) + self.assertEqual(r['state'],'complete',r);return r['result']['preview_id'] + def apply_bms(self,key):return self.command('vesc.bms.configuration.apply',{'preview_id':key,'confirmed':True,'inputs_isolated':True}) + def test_bms_no_preview_write_once_and_backup(self): + key=self.preview();self.assertNotIn('custom_apply',self.calls) + command=self.apply_bms(key);r=self.service.execute(command);self.assertTrue(r['result']['verified'],r) + self.assertEqual(self.service.execute(command),r);self.assertEqual(self.calls.count('custom_apply'),1) + self.assertEqual(self.service.execute(self.apply_bms(key))['state'],'error') + def test_bms_unknown_restores_barrier_after_restart_reconciles_new_address(self): + key=self.preview();self.lost=True;r=self.service.execute(self.apply_bms(key));self.assertEqual(r['result']['outcome'],'unknown') + old=self.service.bms_configuration;self.service.bms_configuration=BmsConfiguration(self.service,old.atomic,old.utc) + self.target['can_id']=18 + r=self.call('vesc.bms.configuration.reconcile',{'can_id':18,'index':0});self.assertTrue(r['result']['verified'],r) + self.assertFalse(self.service.bms_configuration.pending(self.device));self.assertEqual(self.calls.count('custom_apply'),1) + def test_bms_schema_target_changed_and_loaded_battery_reject_before_write(self): + for change in ('schema','uuid','payload','load','session'): + key=self.preview();old=(self.schema,dict(self.target),self.payload,self.device.session) + if change=='schema':self.schema='bb'*32 + if change=='uuid':self.target['uuid']='cd'*12 + if change=='payload':self.payload=b'else' + if change=='session':self.device.session='changed' + if change=='load':self.device.link.bms_read=lambda _: {'state':'received','target':dict(self.target),'values':{'v_cells':[3.8],'i_in':2,'i_in_ic':2}} + r=self.service.execute(self.apply_bms(key));self.assertEqual(r['state'],'error',(change,r)) + self.schema,self.target,self.payload,self.device.session=old + self.assertNotIn('custom_apply',self.calls) + def code_device(self): + self.base.raw_identity=b'\0\6\0SYNTHETIC\0'+b'\1'*12+bytes(4) + from runtime.protocol import firmware + self.device.identity=firmware(self.base.raw_identity) + def code_preview(self): + raw=json.dumps({'kind':'lisp','source':'(+ 1 2)','imports':{},'fullscreen':False}).encode() + r=self.call('vesc.code.begin',{'kind':'lisp','size':len(raw),'sha256':sha(raw)});self.assertEqual(r['state'],'complete',r);key=r['result']['upload_id'] + r=self.call('vesc.code.chunk',{'upload_id':key,'offset':0,'data':b64(raw)});self.assertEqual(r['result']['offset'],len(raw),r) + r=self.call('vesc.code.prepare',{'upload_id':key});self.assertEqual(r['state'],'complete',r);return r['result']['preview_id'] + def test_fw502_denies_code_before_any_native_call(self): + for action,p in [('read',{'kind':'lisp'}),('control_prepare',{'command':'start','text':''}),('erase_prepare',{'kind':'qml'})]: + self.assertEqual(self.call('vesc.code.'+action,p)['state'],'error') + self.assertEqual(self.calls,[]) + def test_code_staging_never_runs_upload_lost_ack_and_readback(self): + self.code_device();key=self.code_preview();self.assertNotIn('code_control',self.calls);self.assertNotIn('code_write',self.calls) + self.lost=True;c=self.command('vesc.code.apply',{'preview_id':key,'confirmed':True,'inputs_isolated':True});r=self.service.execute(c) + self.assertEqual(r['result']['outcome'],'unknown',r);self.assertEqual(self.service.execute(c),r) + old=self.service.code_tools;self.service.code_tools=CodeTools(self.service,old.atomic,old.utc) + r=self.call('vesc.code.reconcile',{'kind':'lisp'});self.assertTrue(r['result']['verified'],r) + self.assertEqual(self.calls.count('code_write'),1);self.assertNotIn('code_control',self.calls) + def test_repl_start_barrier_survives_restart_stop_clears_only_execution(self): + self.code_device() + p=self.call('vesc.code.control_prepare',{'command':'start','text':''})['result']['preview_id'] + r=self.call('vesc.code.control_apply',{'preview_id':p,'confirmed':True,'inputs_isolated':True});self.assertEqual(r['state'],'complete',r) + old=self.service.code_tools;self.service.code_tools=CodeTools(self.service,old.atomic,old.utc);self.assertTrue(self.service.code_tools.blocked(self.device)) + p=self.call('vesc.code.control_prepare',{'command':'stop','text':''})['result']['preview_id'] + self.call('vesc.code.control_apply',{'preview_id':p,'confirmed':True,'inputs_isolated':True});self.assertFalse(self.service.code_tools.blocked(self.device)) + def test_staged_code_stale_session_rejected_and_invalid_chunk_bounded(self): + self.code_device();raw=b'{}';r=self.call('vesc.code.begin',{'kind':'lisp','size':2,'sha256':sha(raw)});key=r['result']['upload_id'] + self.assertEqual(self.call('vesc.code.chunk',{'upload_id':key,'offset':1,'data':b64(raw)})['state'],'error') + self.device.session='changed';self.assertEqual(self.call('vesc.code.chunk',{'upload_id':key,'offset':0,'data':b64(raw)})['state'],'error') + with self.assertRaises(ValueError):validate_code('vesc.code.begin',{'kind':'lisp','size':300000,'sha256':'a'*64}) + with self.assertRaises(ValueError):validate_bms('vesc.bms.configuration.read',{'can_id':255,'index':0}) + def test_pending_extension_blocks_generic_configuration_write(self): + key=self.base.preview();self.service.bms_configuration.path(self.device).write_text('{"state":"unknown"}') + r=self.service.execute(self.base.apply_command(key));self.assertEqual(r['state'],'error',r);self.assertEqual(self.base.writes,[]) + def test_code_snapshot_not_persisted_to_read_journal(self): + self.code_device();c=self.command('vesc.code.read',{'kind':'lisp'});r=self.service.execute(c);self.assertEqual(r['state'],'complete',r) + persisted=json.loads((self.service.root/(c['operation_id']+'.json')).read_text());self.assertTrue(persisted['snapshot_only']);self.assertNotIn('project',str(persisted)) diff --git a/plugins/vesc/tests/test_firmware_files.py b/plugins/vesc/tests/test_firmware_files.py new file mode 100644 index 00000000..a13d35e7 --- /dev/null +++ b/plugins/vesc/tests/test_firmware_files.py @@ -0,0 +1,78 @@ +"""Container, catalogue and transaction bounds; no physical writes.""" +import base64 +import hashlib +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +import test_firmware_update +from runtime import firmware_catalog +from runtime.firmware_update import validate + +class CatalogueTests(unittest.TestCase): + def test_installed_catalogue_is_filtered_verified_and_never_downloaded(self): + with tempfile.TemporaryDirectory() as folder: + root=Path(folder);data=b'X'*512;sha=hashlib.sha256(data).hexdigest() + item={'id':'fwimg_'+'1'*32,'name':'VESC_default.bin','sha256':sha,'bytes':len(data),'hardware':['75_300_R2'],'version':'5.02','kind':'firmware','hardware_limits':True} + value={'schema':'missioncore.vesc.firmware-catalog/v1','repository':'https://github.com/vedderb/vesc_fw_archive','commit':'a'*40,'admitted_versions':['5.02'],'items':[item]} + (root/'catalog.json').write_text(json.dumps(value));(root/(sha+'.bin')).write_bytes(data) + device=type('Device',(),{'identity':{'hardware':'75_300_R2','version':'5.02'},'link':object()})() + self.assertEqual(firmware_catalog.compatible(device,root)['items'],[item]) + self.assertEqual(firmware_catalog.image(device,item['id'],root),(item,data)) + with self.assertRaises(ValueError):firmware_catalog.image(device,'fwimg_'+'2'*32,root) + device.identity['hardware']='OTHER' + self.assertEqual(firmware_catalog.compatible(device,root)['items'],[]) + device.identity['hardware']='75_300_R2';(root/(sha+'.bin')).write_bytes(b'Y'*512) + with self.assertRaises(ValueError):firmware_catalog.image(device,item['id'],root) + value['items'].append(dict(item));(root/'catalog.json').write_text(json.dumps(value)) + with self.assertRaises(ValueError):firmware_catalog.catalogue(root) + + def test_hex_and_catalog_inputs_remain_bounded(self): + p={'name':'source.hex','kind':'firmware','bytes':8*1024**2,'sha256':'1'*64,'hardware':'75_300_R2','target_version':'5.02'} + validate('vesc.firmware.begin',p) + for change in ({'bytes':p['bytes']+1},{'name':'../source.hex'},{'name':'file.zip'},{'name':'huge.bin'},{'bytes':True}): + with self.assertRaises(ValueError):validate('vesc.firmware.begin',p|change) + for value in ('../escape','latest','fwimg_'+'g'*32): + with self.assertRaises(ValueError):validate('vesc.firmware.catalog_prepare',{'image_id':value}) + +class ExtendedFirmwareTests(test_firmware_update.FirmwareUpdateTests): + def test_hex_preview_binds_source_hash_to_normalized_native_image(self): + source=b':synthetic HEX source fixture\n'*32 + digest=hashlib.sha256(source).hexdigest() + self.device.link.engine={'contract':{'firmware_formats':['bin','hex']}} + old=self.device.link.firmware_rpc + def native(name,**p): + if name=='seal':return {'source_bytes':len(source),'source_sha256':digest,'sha256':self.digest,'bytes':len(self.image),'source_format':'hex','base_address':0x08000000} + return old(name,**p) + self.device.link.firmware_rpc=native + result=self.call('begin',{'name':'fixture.hex','kind':'firmware','bytes':len(source),'sha256':digest,'hardware':self.device.identity['hardware'],'target_version':'5.02'}) + identifier=result['result']['transfer_id'] + self.assertEqual(self.call('chunk',{'transfer_id':identifier,'offset':0,'data':base64.b64encode(source).decode()})['state'],'complete') + result=self.call('seal',{'transfer_id':identifier}) + self.assertEqual(result['result']['image']['sha256'],self.digest) + self.assertEqual(result['result']['image']['source_sha256'],digest) + self.assertEqual(result['result']['image']['bytes'],len(self.image)) + self.assertNotIn('start',self.calls) + + def test_old_native_engine_does_not_silently_accept_hex(self): + p={'name':'image.hex','kind':'firmware','bytes':1024,'sha256':'0'*64,'hardware':self.device.identity['hardware'],'target_version':'5.02'} + self.assertEqual(self.call('begin',p)['state'],'error') + self.assertEqual(self.calls,[]) + + def test_catalog_selection_stages_but_never_writes_and_unlimited_needs_extra_confirmation(self): + item={'id':'fwimg_'+'2'*32,'name':'VESC_default_no_hw_limits.bin','sha256':self.digest,'bytes':len(self.image),'version':'5.02','hardware_limits':False} + with patch.object(firmware_catalog,'image',return_value=(item,self.image)): + result=self.call('catalog_prepare',{'image_id':item['id']}) + self.assertEqual(result['state'],'complete',result) + self.assertFalse(result['result']['image']['hardware_limits']) + identifier=result['result']['transfer_id'] + self.assertEqual(self.service.execute(self.apply(identifier))['state'],'error') + self.assertNotIn('start',self.calls) + + def test_catalog_reads_use_volatile_snapshot_receipts(self): + with patch.object(firmware_catalog,'compatible',return_value={'items':[]}): + result=self.call('catalog') + self.assertEqual(result['state'],'complete',result) + self.assertNotIn('start',self.calls) diff --git a/plugins/vesc/tests/test_firmware_targets.py b/plugins/vesc/tests/test_firmware_targets.py new file mode 100644 index 00000000..48066a43 --- /dev/null +++ b/plugins/vesc/tests/test_firmware_targets.py @@ -0,0 +1,77 @@ +import base64 +import unittest +from unittest.mock import patch +import test_firmware_update as fixture +from runtime.firmware_update import validate +from runtime import swd + +class TargetTests(fixture.FirmwareUpdateTests): + def setUp(self): + super().setUp() + self.target={**{k:v for k,v in self.device.identity.items() if k!='version'},'can_id':7,'uuid':'aa'*12} + self.device.link.engine={'contract':{'firmware_targets':['usb','can','swd'],'firmware_formats':['bin','hex'],'firmware_profiles':[{'major':5,'minor':2}]}} + native=self.native + self.changed=False;self.rpc=[];self.verified=False + def call(name,**p): + self.rpc.append((name,p)) + if name=='target':return {'target':dict(self.target),'admitted':True} + if name=='snapshot':return {'target':{**self.target,'uuid':'03'*12} if self.changed else dict(self.target),'packets':{str(k):base64.b64encode(self.base.query(k)).decode() for k in (4,14,17,31)}} + if name=='start' and 'target' in self.updater.pending(self.device)['image']: + self.calls.append(name);record=self.updater.pending(self.device) + self.assertTrue(self.service.motor.latched) + self.assertEqual(len(self.service.archive.listing('local',record['before_backup_device_id'])['items']),1) + return {} + result=native(name,**p) + if name=='status' and self.verified:result.update(binary_readback_verified=True,reboot_confirmed=True) + return result + self.device.link.firmware_rpc=call + def stage_target(self,extra): + p={'name':'synthetic.bin','bytes':len(self.image),'sha256':self.digest,'hardware':'SYNTHETIC','target_version':'5.02','kind':'firmware',**extra} + result=self.call('begin',p);self.assertEqual(result['state'],'complete',result);identifier=result['result']['transfer_id'] + self.call('chunk',{'transfer_id':identifier,'offset':0,'data':base64.b64encode(self.image).decode()}) + result=self.call('seal',{'transfer_id':identifier});self.assertEqual(result['state'],'complete',result) + return identifier + def test_can_snapshot_rejects_replaced_target_before_any_write(self): + transfer=self.stage_target({'can_id':7,'target':self.target});self.changed=True + result=self.service.execute(self.apply(transfer));self.assertEqual(result['state'],'error',result) + self.assertNotIn('start',self.calls);self.assertIsNone(self.updater.pending(self.device)) + def test_can_archive_is_bound_to_remote_uuid_and_native_has_exact_address(self): + transfer=self.stage_target({'can_id':7,'target':self.target}) + manifest=next(p for name,p in self.rpc if name=='begin') + self.assertEqual(manifest['can_id'],7);self.assertEqual(manifest['uuid'],self.target['uuid']) + result=self.service.execute(self.apply(transfer));self.assertEqual(result['state'],'complete',result);self.assertEqual(result['result']['state'],'awaiting_identity',result) + backup=self.service.archive.read('local',result['result']['before_backup_device_id'],result['result']['before_backup_id']) + self.assertEqual(backup['identity']['uuid'],self.target['uuid']);self.assertNotEqual(backup['identity']['uuid'],self.device.identity['uuid']) + def test_swd_staging_does_not_connect_requires_confirmation_and_preserves_readback(self): + target={'target_code':1,'pins':'default','address':0x08000000,'flash_bytes':131072} + transfer=self.stage_target({'swd':target});self.assertNotIn('start',self.calls) + self.assertEqual(self.service.execute(self.apply(transfer))['state'],'error');self.assertNotIn('start',self.calls) + cmd=self.apply(transfer);cmd['parameters']['swd_target_confirmed']=True;self.verified=True + result=self.service.execute(cmd)['result'];self.assertTrue(result['binary_readback_verified']);self.assertTrue(result['reboot_confirmed']);self.assertFalse(result['boot_verified']) + def test_swd_false_readback_never_settles_by_gateway_version(self): + transfer=self.stage_target({'swd':{'target_code':1,'pins':'default','address':0x08000000,'flash_bytes':131072}}) + cmd=self.apply(transfer);cmd['parameters']['swd_target_confirmed']=True + self.service.execute(cmd) + self.device.link=type('Link',(),{'query':lambda _,code:self.base.raw_identity})() + self.assertEqual(self.updater.reconcile(self.device)['state'],'unknown');self.assertIsNotNone(self.updater.pending(self.device)) + def test_swd_and_can_validation_excludes_broadcast_bool_uicr_and_unbounded_range(self): + for can_id in (-1,254,255,True,1.5): + with self.assertRaises(ValueError):validate('vesc.firmware.target',{'can_id':can_id}) + good={'target_code':8,'pins':'nrf5x','address':0,'flash_bytes':1024*1024};swd.validate(good) + for bad in ({'address':0x10001000},{'flash_bytes':2*1024*1024},{'target_code':True},{'pins':'other'}): + with self.assertRaises(ValueError):swd.validate({**good,**bad}) + + def test_second_usb_owner_blocks_can_staging(self): + peer=next(d for d in self.service.devices.values() if d is not self.device) + peer.identity={**self.device.identity,'uuid':self.target['uuid']} + result=self.call('begin',{'name':'a.bin','bytes':1024,'sha256':self.digest,'hardware':'SYNTHETIC','target_version':'5.02','kind':'firmware','can_id':7,'target':self.target}) + self.assertEqual(result['state'],'error');self.assertNotIn('begin',self.calls) + def test_can_interlock_follows_target_when_later_attached_by_usb(self): + transfer=self.stage_target({'can_id':7,'target':self.target}) + result=self.service.execute(self.apply(transfer))['result'] + from types import SimpleNamespace + alias=SimpleNamespace(id=result['before_backup_device_id'],identity={**self.device.identity,'uuid':self.target['uuid']}) + self.assertEqual(self.updater.pending(alias)['operation_id'],result['operation_id']) + self.updater.active=result + self.assertTrue(self.updater.owns(alias));self.assertTrue(self.updater.owns(self.device)) + self.updater.active=None diff --git a/plugins/vesc/tests/test_firmware_update.py b/plugins/vesc/tests/test_firmware_update.py new file mode 100644 index 00000000..6fcab455 --- /dev/null +++ b/plugins/vesc/tests/test_firmware_update.py @@ -0,0 +1,185 @@ +"""Offline lifecycle/fault injection, never a real firmware upload.""" +import base64 +from datetime import timedelta +import hashlib +import json +import unittest + +import test_config_editor +from runtime.firmware_update import FirmwareUpdate, validate + + +class FirmwareUpdateTests(unittest.TestCase): + def setUp(self): + self.base=test_config_editor.ConfigEditorTests();self.base.setUp() + self.service,self.device=self.base.service,self.base.device + self.updater=self.service.firmware_update + self.clock=[0.] + self.updater.clock=lambda:self.clock[0] + self.updater.sleep=lambda s:self.clock.__setitem__(0,self.clock[0]+s) + self.image=bytes.fromhex('0000022001010008')+bytes(1016) + self.digest=hashlib.sha256(self.image).hexdigest() + self.calls=[];self.cancel_on_start=False;self.lose_start=False + self.device.link.firmware_rpc=self.native + self.initial_session=self.device.session + def tearDown(self):self.base.tearDown() + def command(self,name,p=None): + cmd=self.base.command(action='vesc.firmware.'+name) + cmd['parameters']=p or {} + from datetime import datetime + cmd['deadline_at']=(datetime.fromisoformat(cmd['requested_at'])+timedelta(seconds=300)).isoformat() + return cmd + def call(self,name,p=None):return self.service.execute(self.command(name,p)) + def native(self,name,**p): + self.calls.append(name) + if name=='seal':return {'bytes':len(self.image),'sha256':self.digest} + if name=='start': + record=self.updater.pending(self.device) + self.assertEqual(record['state'],'uploading') + self.assertEqual(len(self.service.archive.listing('local',self.device.id)['items']),1) + self.assertTrue(self.service.motor.latched) + if self.cancel_on_start:self.updater.cancel(self.device.id,record['operation_id']) + if self.lose_start:raise TimeoutError('Synthetic lost start ACK') + if name=='status':return {'state':'unknown' if self.cancel_on_start else 'uploaded','upload_confirmed':not self.cancel_on_start,'progress':1} + return {} + def prepare(self): + result=self.call('begin',{'name':'synthetic.bin','bytes':len(self.image),'sha256':self.digest, + 'hardware':self.device.identity['hardware'],'target_version':'5.02','kind':'firmware'}) + self.assertEqual(result['state'],'complete',result) + identifier=result['result']['transfer_id'] + for offset in range(0,len(self.image),512): + self.assertEqual(self.call('chunk',{'transfer_id':identifier,'offset':offset, + 'data':base64.b64encode(self.image[offset:offset+512]).decode()})['state'],'complete') + self.assertEqual(self.call('seal',{'transfer_id':identifier})['state'],'complete') + self.assertNotIn('start',self.calls) + return identifier + def apply(self,identifier): + return self.command('apply',{'transfer_id':identifier,'rig_clear':True,'inputs_isolated':True,'compatible_image_confirmed':True}) + def test_stage_is_readonly_apply_once_and_requires_fresh_identity(self): + identifier=self.prepare();cmd=self.apply(identifier) + result=self.service.execute(cmd) + self.assertEqual(result['result']['state'],'awaiting_identity',result) + self.assertFalse(result['result']['binary_readback_verified']) + self.assertNotEqual(self.device.session,self.initial_session) + self.assertIsNone(self.device.link) + self.assertEqual(self.service.execute(cmd),result) + self.assertEqual(self.calls.count('start'),1) + self.assertNotIn(identifier,self.updater.transfers) + def test_lost_ack_survives_restart_and_cannot_be_settled_by_version_alone(self): + identifier=self.prepare();self.lose_start=True + result=self.service.execute(self.apply(identifier)) + self.assertEqual(result['result']['state'],'unknown') + restarted=FirmwareUpdate(self.service,self.updater.atomic,self.updater.utc) + self.assertEqual(restarted.status(self.device.id)['state'],'unknown') + self.device.link=type('Link',(),{'query':lambda _,code:self.base.raw_identity})() + self.assertEqual(restarted.reconcile(self.device)['state'],'unknown') + self.assertIsNotNone(restarted.pending(self.device)) + def test_confirmed_upload_reconciles_uuid_and_version_without_binary_claim(self): + result=self.service.execute(self.apply(self.prepare())) + self.device.link=type('Link',(),{'query':lambda _,code:self.base.raw_identity})() + result=self.updater.reconcile(self.device) + self.assertEqual(result['state'],'identified') + self.assertFalse(result['binary_readback_verified']) + self.assertIsNone(self.updater.pending(self.device)) + def test_cancel_is_exact_and_persists_unknown(self): + identifier=self.prepare();self.cancel_on_start=True + result=self.service.execute(self.apply(identifier)) + self.assertIn('cancel',self.calls) + self.assertEqual(result['result']['state'],'unknown') + with self.assertRaises(ValueError):self.updater.cancel(self.device.id,'op_'+'0'*32) + def test_expiry_session_change_and_missing_confirmation_never_start(self): + identifier=self.prepare();self.clock[0]=601 + self.assertEqual(self.service.execute(self.apply(identifier))['state'],'error') + self.assertNotIn('start',self.calls) + identifier=self.prepare();self.device.session='new-session' + self.assertEqual(self.service.execute(self.apply(identifier))['state'],'error') + cmd=self.apply(identifier);cmd['parameters']['rig_clear']=False + with self.assertRaises(ValueError):self.service.execute(cmd) + self.assertNotIn('start',self.calls) + def test_bad_offset_digest_and_foreign_hardware_never_stage_native(self): + begin={'name':'a.bin','bytes':len(self.image),'sha256':'0'*64,'hardware':self.device.identity['hardware'],'target_version':'5.02','kind':'firmware'} + identifier=self.call('begin',begin)['result']['transfer_id'] + data=base64.b64encode(self.image).decode() + self.assertEqual(self.call('chunk',{'transfer_id':identifier,'offset':1,'data':data})['state'],'error') + self.assertEqual(self.call('chunk',{'transfer_id':identifier,'offset':0,'data':data})['state'],'complete') + self.assertEqual(self.call('seal',{'transfer_id':identifier})['state'],'error') + self.assertEqual(self.calls,[]) + self.assertEqual(self.call('begin',{**begin,'hardware':'FOREIGN'})['state'],'error') + def test_pending_configuration_or_active_drive_prevents_erase(self): + identifier=self.prepare() + self.updater.atomic(self.service.config_editor.pending_path(self.device),{'state':'unknown'}) + self.assertEqual(self.service.execute(self.apply(identifier))['state'],'error') + self.assertNotIn('start',self.calls) + def test_status_works_while_hardware_lock_is_owned(self): + self.service.operation_lock.acquire() + try: + result=self.call('status') + self.assertEqual(result['result']['state'],'idle') + finally:self.service.operation_lock.release() + def test_validation_bounds(self): + for params in ({'transfer_id':'fw_'+'a'*32,'offset':True,'data':'AA=='}, + {'transfer_id':'fw_'+'a'*32,'offset':0,'data':'?'}, + {'transfer_id':'../escape','offset':0,'data':'AA=='}, + {'transfer_id':'fw_'+'a'*32,'offset':0,'data':base64.b64encode(bytes(32769)).decode()}): + with self.assertRaises(ValueError):validate('vesc.firmware.chunk',params) + + def test_tool_reads_and_terminal_cannot_smuggle_control(self): + self.device.link.device_tool=lambda tool:{'tool':tool,'state':'received','values':{'level':0}} + self.device.link.diagnostic=lambda command:{'command':command,'text':'synthetic read'} + for action,params in [('vesc.tools.read',{'tool':'adc'}),('vesc.terminal.read',{'command':'mem'})]: + cmd=self.base.command(action=action);cmd['parameters']=params + self.assertEqual(self.service.execute(cmd)['state'],'complete') + for action,params in [('vesc.tools.read',{'tool':'set_current'}),('vesc.terminal.read',{'command':'stop'}),('vesc.terminal.read',{'command':'mem\nfoc_openloop 5 100'}),('vesc.terminal.read',{'command':'measure_res'})]: + cmd=self.base.command(action=action);cmd['parameters']=params + with self.assertRaises(ValueError):self.service.execute(cmd) + + def test_native_progress_survives_expected_usb_detach_but_reads_do_not(self): + from runtime.native_link import NativeLink + from types import SimpleNamespace + from unittest.mock import Mock,patch + link=NativeLink.__new__(NativeLink) + link.sequence=0;link.attachment=SimpleNamespace(usb='synthetic',address=1,tty='synthetic') + link.process=SimpleNamespace(stdin=Mock(fileno=lambda:0),stdout=object(),poll=lambda:None) + link.check=Mock(side_effect=OSError('synthetic detached')) + link.close=Mock(return_value={'exit_confirmed':True}) + link._receive=lambda deadline:{'id':link.sequence,'ok':True,'result':{'state':'uploaded'}} + with patch('runtime.native_link.select.select',return_value=([],[object()],[])),patch('runtime.native_link.os.write',side_effect=lambda fd,data:len(data)): + self.assertEqual(link.rpc('firmware_status')['state'],'uploaded') + link.check.assert_not_called() + with self.assertRaises(OSError):link.rpc('query',command=0,timeout_ms=500) + self.assertGreater(link.check.call_count,0) + + def test_other_controller_keeps_telemetry_during_firmware_upload(self): + from runtime.remote_control import RemoteControl + from unittest.mock import Mock + remote=RemoteControl(self.service) + peer=next(d for d in self.service.devices.values() if d is not self.device) + peer.link.query=self.base.query + self.device.link.query=Mock(side_effect=AssertionError('Uploading controller must not be polled')) + self.updater.active={'device_id':self.device.id} + self.service.operation_lock.acquire() + try: + remote.observe() + self.assertIsNotNone(peer.sample) + self.assertIsNone(self.device.sample) + self.device.link.query.assert_not_called() + self.assertTrue(self.service.operation_lock.locked()) + finally: + self.updater.active=None + self.service.operation_lock.release() + + def test_staging_waits_for_bounded_observer_exchange(self): + import threading,time + self.service.operation_lock.acquire() + released=threading.Event() + def observer(): + time.sleep(.05) + self.service.operation_lock.release() + released.set() + thread=threading.Thread(target=observer);thread.start() + try: + result=self.call('begin',{'name':'synthetic.bin','bytes':len(self.image),'sha256':self.digest, + 'hardware':self.device.identity['hardware'],'target_version':'5.02','kind':'firmware'}) + self.assertEqual(result['state'],'complete') + self.assertTrue(released.is_set()) + finally:thread.join(1) diff --git a/plugins/vesc/tests/test_maintenance.py b/plugins/vesc/tests/test_maintenance.py new file mode 100644 index 00000000..ee25e994 --- /dev/null +++ b/plugins/vesc/tests/test_maintenance.py @@ -0,0 +1,46 @@ +"""Maintenance observes ownership and closes links without motor RPCs.""" +import sys +import tempfile +import threading +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from runtime.maintenance_state import idle, quiesce + + +class IdleProof(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup) + self.device = Mock() + remote = SimpleNamespace(lock=threading.RLock(), lease=Mock(), thread=None, release_confirmed=None, primed=True, state='stopped') + remote.lease.live.return_value = False + self.service = SimpleNamespace(remote=remote, motor=SimpleNamespace(active=False), + firmware_update=SimpleNamespace(lock=threading.RLock(), active=None), root=Path(self.tmp.name), + lock=threading.RLock(), devices={'synthetic': self.device}, samples=Mock()) + self.service.samples.active.return_value = False + + def test_control_lease_refuses_even_before_motor_thread_starts(self): + self.service.remote.lease.live.return_value = True + self.assertEqual(idle(self.service), 'control-active') + self.device.close.assert_not_called() + + def test_capture_and_unresolved_changes_refuse(self): + self.service.samples.active.return_value = True + self.assertEqual(idle(self.service), 'sample-capture-active') + self.service.samples.active.return_value = False + (self.service.root / 'limits_synthetic.json').touch() + self.assertEqual(idle(self.service), 'device-change-unresolved') + + def test_close_only_retires_transport_and_requires_fresh_control_prime(self): + self.assertIsNone(idle(self.service)) + quiesce(self.service) + self.assertEqual(self.device.mock_calls, [unittest.mock.call.close()]) + self.assertEqual(self.service.devices, {}) + self.assertFalse(self.service.remote.primed) + self.service.remote.lease.stop.assert_not_called() + + +if __name__ == '__main__': unittest.main() diff --git a/plugins/vesc/tests/test_motor_test.py b/plugins/vesc/tests/test_motor_test.py index 3e0d9920..d00690eb 100644 --- a/plugins/vesc/tests/test_motor_test.py +++ b/plugins/vesc/tests/test_motor_test.py @@ -10,7 +10,7 @@ import xml.etree.ElementTree as ET sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from runtime.configuration import decode, crc32c from runtime.motor_test import Rejected, LimitExceeded, check_configuration, check_values -from runtime.protocol import Decoder, test_packet, ppm, current_packet +from runtime.protocol import Decoder, test_packet as encode_test_packet, ppm, current_packet import test_reader from runtime.protocol import firmware from test_reader import telemetry @@ -78,10 +78,10 @@ class PulseTests(test_reader.ServiceTests): return c def test_fixed_wire_commands_no_broadcast_and_no_parameters(self): - self.assertEqual(Decoder().feed(test_packet('claim')),[bytes([63,0])+struct.pack('>i',250)]) - self.assertEqual(Decoder().feed(test_packet('current')),[bytes([6])+struct.pack('>i',2000)]) + self.assertEqual(Decoder().feed(encode_test_packet('claim')),[bytes([63,0])+struct.pack('>i',250)]) + self.assertEqual(Decoder().feed(encode_test_packet('current')),[bytes([6])+struct.pack('>i',2000)]) self.assertEqual(Decoder().feed(current_packet(5)),[bytes([6])+struct.pack('>i',5000)]) - with self.assertRaises(KeyError):test_packet('arbitrary') + with self.assertRaises(KeyError):encode_test_packet('arbitrary') with self.assertRaises(ValueError):ppm(bytes([31])+bytes(7)) def test_only_selected_motor_receives_current_and_receipt_never_replays(self): diff --git a/plugins/vesc/tests/test_native_link.py b/plugins/vesc/tests/test_native_link.py index a5770b9e..d5f1769d 100644 --- a/plugins/vesc/tests/test_native_link.py +++ b/plugins/vesc/tests/test_native_link.py @@ -23,6 +23,20 @@ class NativeBoundaryTests(unittest.TestCase): self.addCleanup(value.close) return value + def test_can_failure_survives_native_exit_and_receive_boundary(self): + from types import SimpleNamespace + import threading + link = object.__new__(NativeLink) + stopped = threading.Event(); stopped.set() + link.bridge = SimpleNamespace(stop=stopped, error="poll: adapter busy") + link.process = SimpleNamespace(poll=lambda: None) + link.buffer = b"" + self.assertFalse(link.alive) + with self.assertRaisesRegex(OSError, "CAN bridge: poll: adapter busy"): + link._receive(0) + link.process = SimpleNamespace(poll=lambda: 1) + self.assertIn("poll: adapter busy", str(link.failure_error())) + def test_success_returns_upstream_payload_and_keeps_one_process(self): link = self.link('print(json.dumps({"id":r["id"],"ok":True,"result":{"payload":"BA=="}}),flush=True)') pid = link.process.pid @@ -91,3 +105,36 @@ class NativeBoundaryTests(unittest.TestCase): self.assertEqual(caught.exception.native_rpc['transport'], detail) self.assertEqual(link.sequence, 1) self.assertFalse(link.alive) + + +class NativeStartupEvidenceTests(unittest.TestCase): + def test_startup_error_captures_bounded_stderr_before_cleanup(self): + import tempfile + from pathlib import Path as RealPath + from types import SimpleNamespace + from unittest.mock import patch + from runtime.native_link import NativeLink + with tempfile.TemporaryDirectory() as directory: + root = RealPath(directory) + def remap(value): + return root / ("config" if str(value).startswith("/run/") else "runtime") + def process(*args, **kwargs): + kwargs["stderr"].write(b"old" * 3000 + b"synthetic startup failure") + kwargs["stderr"].flush() + return SimpleNamespace(pid=123, poll=lambda: 5) + def cleanup(*args): + for p in root.glob("config/*/engine.log"): + p.write_text("next attempt") + with (patch("runtime.native_link.Path", side_effect=remap), + patch.object(NativeLink, "check"), + patch("runtime.native_link.reap_retired"), + patch("runtime.native_link.subprocess.Popen", side_effect=process), + patch.object(NativeLink, "_receive", side_effect=OSError("native exited")), + patch.object(NativeLink, "close", side_effect=cleanup)): + with self.assertRaises(OSError) as captured: + NativeLink(SimpleNamespace(binding="synthetic", tty="ttyACM0")) + record = captured.exception.native_startup + self.assertEqual(record["exit_code"], 5) + self.assertTrue(record["stderr_truncated"]) + self.assertEqual(len(record["stderr_tail"]), 4096) + self.assertTrue(record["stderr_tail"].endswith("synthetic startup failure")) diff --git a/plugins/vesc/tests/test_network_stop_recovery.py b/plugins/vesc/tests/test_network_stop_recovery.py new file mode 100644 index 00000000..b16ed173 --- /dev/null +++ b/plugins/vesc/tests/test_network_stop_recovery.py @@ -0,0 +1,53 @@ +"""Ten isolated neutral-only cycles through the real driver and release observer. + +Serial links and readback are simulated; no device files or hardware are opened. +The injected current is evidence of settling, never a requested output. +""" +import threading +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import test_remote_control as drive_fixture +import test_release_observation as release_fixture + + +class NetworkStopRecoveryBench(unittest.TestCase): + def test_ten_expiries_delayed_settlements_and_terminal_negative_controls(self): + for run in range(10): + with self.subTest(run=run + 1): + log, _, remote, owner, error = drive_fixture.DriveBoundaryTests().run_drive( + 'expire-settling', through_prepare=True, neutral_only=True) + assert error is None and remote.state == 'stopping' + assert remote.release_confirmed is False and not remote.lease.live() + assert all(row[2] not in ('rpm', 'duty') or row[3] == 0 for row in log) + assert remote.last_stop['release_evidence']['devices']['left']['values']['motor_current_a'] == 7.01 + retired = remote.lease.id + assert not remote.lease.accept(drive_fixture.envelope(seq=100)) + devices = list(remote.service.devices.values()) + for d in devices: + d.session = d.id + '-attachment' + d.identity = {'uuid': d.id} + remote.service.firmware_update = SimpleNamespace(lock=threading.Lock(), active=None) + owner.limits.pending = lambda _: False + with patch('runtime.remote_control.time.monotonic', return_value=10): + remote._await_release(devices) + # A longer wait and stale/duplicate reads never count as proof. + for step in range(run + 1): + release_fixture.observe(remote, devices, 10.1 + step * .2, motor_current_a=3.05) + assert remote.state == 'stopping' and not remote.release_confirmed + start = 11 + run * .2 + release_fixture.observe(remote, devices, start) + with patch('runtime.remote_control.time.monotonic', return_value=start + .2): + remote._reconcile_release(devices) + assert not remote.release_confirmed + for delta in (.4, .6, .8, 1.0): + release_fixture.observe(remote, devices, start + delta) + assert remote.state == 'stopped' and remote.release_confirmed is True + assert remote.last_stop['state'] == 'stopping' and remote.last_stop['recovered_at'] + assert not remote.lease.live() and retired in remote.lease.retired and owner.latched + # The same recovery path must NOT forgive a missing controller. + _, _, failed, _, _ = drive_fixture.DriveBoundaryTests().run_drive( + 'lost', broken_read=True, through_prepare=True, neutral_only=True) + assert failed.state == 'fault' and failed.last_stop['state'] == 'fault' + assert not failed.release_confirmed and not failed.lease.live() diff --git a/plugins/vesc/tests/test_observer_recovery.py b/plugins/vesc/tests/test_observer_recovery.py new file mode 100644 index 00000000..72721df8 --- /dev/null +++ b/plugins/vesc/tests/test_observer_recovery.py @@ -0,0 +1,276 @@ +"""Observer recovery without motor output or real USB access.""" +import io +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "src")) +from runtime import native_link +from runtime.native_link import NativeLink +from runtime.remote_control import RemoteControl +from runtime.server import poll_readonly +from runtime.service import Service +from runtime.serial import Attachment +from test_reader import FakeLink, telemetry + + +class RetirementTests(unittest.TestCase): + def setUp(self): + self.pool = patch.dict(native_link._retiring, {}, clear=True) + self.pool.start(); self.addCleanup(self.pool.stop) + self.process = Mock() + self.process.stdin, self.process.stdout = io.BytesIO(), io.BytesIO() + self.process.poll.return_value = None + self.process.wait.side_effect = subprocess.TimeoutExpired("synthetic-engine", 1) + self.link = object.__new__(NativeLink) + self.link.attachment = Attachment("1-2", "3", "ttyACM0", "12") + self.link.process = self.process + + def test_both_wait_timeouts_close_pipes_and_hold_usb_until_exit(self): + result = self.link.close() + self.assertFalse(result["exit_confirmed"]) + self.assertEqual(self.process.wait.call_count, 2) + self.process.terminate.assert_called_once() + self.process.kill.assert_called_once() + self.assertTrue(self.process.stdin.closed and self.process.stdout.closed) + self.assertFalse(self.link.alive) + with patch.object(NativeLink, "check"), patch.object(native_link.subprocess, "Popen") as spawn: + with self.assertRaisesRegex(OSError, "Previous native USB owner"): + NativeLink(self.link.attachment) + spawn.assert_not_called() + native_link.reap_retired("ttyACM1") # The healthy peer is independent. + self.process.poll.return_value = -9 + native_link.reap_retired("ttyACM0") + self.assertEqual(native_link._retiring, {}) + self.link.close() # Repeated cleanup never signals an unrelated/new process. + self.process.kill.assert_called_once() + + def test_signal_race_still_closes_pipes_and_retains_live_owner(self): + self.process.terminate.side_effect = ProcessLookupError("exit race") + result = self.link.close() + self.assertFalse(result["exit_confirmed"]) + self.assertTrue(self.process.stdout.closed) + self.assertIn("ttyACM0", native_link._retiring) + + def test_original_rpc_failure_survives_double_cleanup_timeout(self): + self.link.sequence = 0 + self.link.check = lambda: None + self.link._receive = lambda deadline: {"id": 1, "ok": False, "error": "original native failure"} + with patch.object(native_link.select, "select", return_value=([], [self.process.stdin], [])), \ + patch.object(native_link.os, "write", side_effect=lambda fd, data: len(data)), \ + patch.object(self.process.stdin, "fileno", return_value=123): + with self.assertRaisesRegex(OSError, "original native failure") as caught: + self.link.rpc("query", command=4) + self.assertFalse(caught.exception.native_rpc["cleanup"]["exit_confirmed"]) + self.assertEqual(caught.exception.native_rpc["command"], 4) + self.assertEqual(self.link.sequence, 1) + + +class ObservationRecoveryTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup) + self.attachments = [Attachment("1-2", "1", "ttyACM0", "12"), + Attachment("1-3", "2", "ttyACM1", "12")] + self.links = [] + links = self.links + class Link(FakeLink): + def __init__(self, attachment): + super().__init__(attachment); self.alive = True; self.error = None + links.append(self) + def query(self, code, timeout=2): + self.commands.append(code) + if self.error: raise self.error + if code == 4: return telemetry() + if code == 31: return b"\x1f" + (0).to_bytes(4,"big") + (1500000).to_bytes(4,"big") + return super().query(code, timeout) + def close(self): + self.closed = True; self.alive = False + self.service = Service(self.temp.name, lambda: self.attachments, Link) + self.service.scan() + self.remote = RemoteControl(self.service) + self.remote.feed({"watch": True, "command": None, "relay_id": "a" * 32}) + + def test_one_failed_device_does_not_starve_peer_and_reconnects(self): + first, peer = list(self.service.devices.values()) + self.remote.observe() + self.assertEqual(len(self.remote.snapshot()["devices"]), 2) + before = first.sample["sampled_at"] + old_session = first.session + self.links[0].error = subprocess.TimeoutExpired("synthetic-engine", 1) + with patch("runtime.remote_control.failure"): + self.remote.observe() + self.assertFalse(self.links[0].alive) + self.assertIsNone(first.sample) + self.assertEqual(len(self.remote.snapshot()["devices"]), 1) + self.assertGreaterEqual(peer.sample["sampled_at"], before) + first.retry_at = 0 + self.service.scan() + self.remote.observe() + self.assertNotEqual(first.session, old_session) + self.assertGreater(first.sample["sampled_at"], before) + self.assertEqual(len(self.remote.snapshot()["devices"]), 2) + self.assertTrue(all(set(link.commands) <= {0, 4, 31} for link in self.links)) + self.assertIsNone(self.remote.snapshot()["session_id"]) + self.assertEqual(self.remote.snapshot()["state"], "observing") + self.assertFalse(self.service.operation_lock.locked()) + + def test_worker_survives_unexpected_failure_and_reports_at_bounded_rate(self): + stop = threading.Event(); calls = [] + def tick(): + calls.append(1) + if len(calls) < 3: raise RuntimeError("synthetic observer error") + self.remote.observe(); stop.set() + with patch("runtime.server.failure") as report: + poll_readonly(tick, stop, .001, "observation-loop") + self.assertEqual(len(calls), 3) + report.assert_called_once() + self.assertEqual(len(self.remote.snapshot()["devices"]), 2) + self.assertIsNone(self.remote.snapshot()["session_id"]) + + def test_can_passive_read_budget_does_not_change_usb_or_start_output(self): + from runtime.can_bridge import Attachment as CanAttachment + devices = list(self.service.devices.values()) + can, usb = devices + can.attachment = CanAttachment("usbcan_" + "a" * 32, "one", 0, 74, 500000, + 254, can.identity["uuid"]) + calls = [] + for device in devices: + original = device.link.query + def query(code, timeout=2, original=original, device=device): + calls.append((device.id, code, timeout)) + # Emulate an SDK dispatch that is within its 200 ms deadline, + # but longer than the former 60 ms USB observer budget. + if device is can and timeout < .2: + raise TimeoutError("CAN dispatch still in flight") + return original(code, timeout) + device.link.query = query + self.remote.observe() + self.assertEqual(len(self.remote.snapshot()["devices"]), 2) + self.assertEqual({timeout for id, _, timeout in calls if id == can.id}, {.3}) + self.assertEqual({timeout for id, _, timeout in calls if id == usb.id}, {.06}) + self.assertEqual({code for _, code, _ in calls}, {4, 31}) + self.assertIsNone(self.remote.snapshot()["session_id"]) + self.assertFalse(self.service.motor.active) + + def test_expired_watch_does_not_start_background_usb_queries(self): + self.remote.observe() + self.remote.watch_until = 0 + before = [len(link.commands) for link in self.links] + self.remote.observe() + self.assertEqual(before, [len(link.commands) for link in self.links]) + + +class LifecycleTests(ObservationRecoveryTests): + def test_initial_sample_without_viewer_then_no_background_reads(self): + self.remote.watch_until = 0 + self.remote.observe() + self.assertEqual(len(self.remote.snapshot()["devices"]), 2) + before = [len(link.commands) for link in self.links] + self.remote.observe() + self.assertEqual(before, [len(link.commands) for link in self.links]) + + def test_dead_owner_immediately_loses_readiness_and_sample(self): + self.remote.observe() + device = next(iter(self.service.devices.values())) + self.links[0].alive = False + item = next(i for i in self.service.inventory("synthetic")["items"] if i["id"] == device.id) + self.assertTrue(item["configured"]) # Known identity is not transport readiness. + self.assertFalse(item["verified"]) + self.assertFalse(item["vesc_status"]["readable"]) + self.assertFalse(item["vesc_status"]["telemetry_ready"]) + self.assertEqual(len(self.remote.snapshot()["devices"]), 1) + + def test_port_swap_keeps_roles_but_never_inherits_old_sample_or_session(self): + self.remote.observe() + old = list(self.service.devices.values()) + profile = {"layout":"1x1", "revision":7, "bindings":{ + "left.1":{"device_id":old[0].id,"uuid":old[0].identity["uuid"]}, + "right.1":{"device_id":old[1].id,"uuid":old[1].identity["uuid"]}}} + self.service.drive.value = profile + identities = {"1-2":2,"1-3":1} + with patch.dict(FakeLink.identities, identities, clear=True): + self.attachments[:] = [Attachment("1-2","5","ttyACM9","12"), Attachment("1-3","6","ttyACM8","12")] + self.service.scan() + self.assertEqual(self.remote.snapshot()["devices"], []) + self.remote.observe() + current = self.remote.snapshot() + self.assertEqual(current["profile"], profile) + by_id = {d["id"]:d for d in current["devices"]} + self.assertEqual(by_id[old[0].id]["slot"], "left.1") + self.assertEqual(by_id[old[1].id]["slot"], "right.1") + self.assertTrue(all(by_id[d.id]["session_id"] != d.session for d in old)) + self.assertTrue(all(not link.alive for link in self.links[:2])) + self.assertEqual(sum(link.alive for link in self.links), 2) + self.assertIsNone(current["session_id"]) + self.assertTrue(all(set(link.commands) <= {0,4,31} for link in self.links)) + + def test_repeated_reenumeration_has_two_owners_and_bounded_live_samples(self): + with patch.dict(FakeLink.identities,{"1-2":1,"1-3":2},clear=True): + for index in range(20): + self.attachments[:] = [Attachment("1-2",str(10+index*2),"ttyACM3","12"),Attachment("1-3",str(11+index*2),"ttyACM2","12")] + self.service.scan();self.remote.observe() + self.assertEqual(sum(link.alive for link in self.links), 2) + self.assertEqual(len(self.remote.snapshot()["devices"]), 2) + before = len(self.links) + for _ in range(10):self.service.scan() + self.assertEqual(len(self.links), before) + + def test_unexpected_connect_failure_isolated_and_backoff_is_capped(self): + for d in self.service.devices.values():d.close() + original = self.service.link_factory + calls = [] + def factory(attachment): + calls.append(attachment.usb) + if attachment.usb == "1-2":raise RuntimeError("synthetic startup failure") + return original(attachment) + self.service.link_factory = factory + first, peer = self.service.devices.values() + with patch("runtime.service.failure"), patch("runtime.service.time.monotonic",return_value=100): + for delay in (2,4,8,16,30,30): + first.retry_at=0;self.service.scan() + self.assertEqual(first.retry_at,100+delay) + attempts=len(calls) + for _ in range(20):self.service.scan() + self.assertEqual(len(calls),attempts) + self.assertIsNotNone(peer.link) + self.assertFalse(first.link) + + def test_read_failures_keep_backoff_until_successful_sample(self): + first = next(iter(self.service.devices.values())) + with patch("runtime.service.failure"), patch("runtime.service.time.monotonic",return_value=100): + for delay in (2,4,8,16,30): + first.link.error = TimeoutError("synthetic read failure") + self.remote.observe() + self.assertEqual(first.retry_at,100+delay) + first.retry_at=0;self.service.scan() + self.remote.observe() + self.assertEqual(first.failures,0) + self.assertIsNotNone(first.sample) + + def test_duplicate_uuid_does_not_publish_authoritative_telemetry(self): + first, second = self.service.devices.values() + self.remote.observe() + second.id=first.id;second.identity=first.identity + self.assertEqual(self.remote.snapshot()["devices"], []) + + +class IdentityAdmissionTests(unittest.TestCase): + def test_cached_identity_is_not_ready_during_new_handshake(self): + with tempfile.TemporaryDirectory() as root: + attachment=Attachment("1-2","1","ttyACM0","12") + service=Service(root,lambda:[attachment],FakeLink);service.scan() + device=next(iter(service.devices.values()));device.close() + seen=[] + class Link(FakeLink): + def query(self,code,timeout=2): + seen.append(service.inventory("synthetic")["items"][0]) + return super().query(code,timeout) + service.link_factory=Link;service.scan() + self.assertFalse(seen[0]["verified"]) + self.assertFalse(seen[0]["vesc_status"]["connected"]) + self.assertTrue(service.inventory("synthetic")["items"][0]["verified"]) diff --git a/plugins/vesc/tests/test_packages.py b/plugins/vesc/tests/test_packages.py new file mode 100644 index 00000000..73822f8a --- /dev/null +++ b/plugins/vesc/tests/test_packages.py @@ -0,0 +1,126 @@ +"""Package transactions under fault injection. No hardware access.""" +import base64,copy,struct,zlib +from datetime import datetime,timedelta,timezone +import unittest +import test_config_editor +from runtime.package_archive import archive,fields,metadata,digest +from runtime.package_tools import PackageTools,validate,image +from runtime.protocol import firmware +b64=lambda b:base64.b64encode(b).decode() +def package(extra=b''): + raw=b'VESC Packet\0name\0\0\0\0\4Test'+extra + return struct.pack('>I',len(raw))+zlib.compress(raw) +def snap(data,fullscreen=False):return {'payload':b64(data),'sha256':digest(data),'bytes':len(data),'fullscreen':fullscreen} + +class PackageTests(unittest.TestCase): + def setUp(self): + self.base=test_config_editor.ConfigEditorTests();self.base.setUp();self.service,self.device=self.base.service,self.base.device + self.data=package();self.key=digest(self.data);self.current={'lisp':snap(b'old-lisp'),'qml':snap(b'old-qml',True)} + self.calls=[];self.lost=None;self.compatible=True;self.fits=True;self.library=False + self.service.packages.catalog.get=lambda key:({'id':self.key,'path':'test.vescpkg','name':'Test','library':self.library},self.data) + self.device.link.rpc=self.native + self.service.packages.catalog.load=lambda:({}, {}) + def tearDown(self):self.base.tearDown() + def supported(self): + self.base.raw_identity=b'\0\6\0SYNTHETIC\0'+b'\1'*12+bytes(4);self.device.identity=firmware(self.base.raw_identity) + def command(self,n,p={}): + c=self.base.command(action='vesc.packages.'+n);c['parameters']=p;c['deadline_at']=(datetime.now(timezone.utc)+timedelta(seconds=350)).isoformat();return c + def call(self,n,p={}):return self.service.execute(self.command(n,p)) + def native(self,method,timeout=2,**p): + self.calls.append((method,p)) + if method=='package_unpack':return {'name':'Test','compatible':self.compatible,'fits':self.fits,'images':{k:image(snap(('new-'+k).encode()),k) for k in ('lisp','qml')}} + if method=='code_snapshot':return copy.deepcopy(self.current[p['kind']]) + if method=='code_control': + assert self.service.packages.record(self.device);assert p['command']=='stop';return {'acknowledged':True} + if method=='code_write': + assert self.service.packages.record(self.device);assert self.service.packages.record(self.device,'backup') + if self.lost=='before':raise TimeoutError('write not acknowledged') + data=base64.b64decode(p['image']);self.current[p['kind']]=snap(data[8:],bool(data and data[7]==2)) + if self.lost==p['kind']:raise TimeoutError('ACK lost') + return {'verified':True} + raise AssertionError(method) + def preview(self): + r=self.call('prepare',{'id':self.key,'compatibility_confirmed':False});self.assertEqual(r['state'],'complete',r);return r['result']['preview_id'] + def apply(self,key):return self.command('apply',{'preview_id':key,'confirmed':True,'inputs_isolated':True}) + def test_fw502_read_only_inspection(self): + self.assertEqual(self.call('inspect',{'id':self.key})['state'],'complete') + self.assertEqual(self.call('prepare',{'id':self.key,'compatibility_confirmed':True})['state'],'error') + self.assertEqual([c[0] for c in self.calls],['package_unpack']) + def test_backup_replay_and_no_start(self): + self.supported();key=self.preview();self.assertNotIn('code_write',[c[0] for c in self.calls]) + command=self.apply(key);r=self.service.execute(command);self.assertTrue(r['result']['verified'],r) + self.assertEqual(self.service.execute(command),r);self.assertEqual(len([c for c in self.calls if c[0]=='code_write']),2) + self.assertEqual([c[1]['command'] for c in self.calls if c[0]=='code_control'],['stop']) + self.assertTrue(self.call('status')['result']['recognized']);self.assertFalse(self.service.code_tools.blocked(self.device)) + def test_partial_survives_restart_recovers_exactly(self): + self.supported();before=copy.deepcopy(self.current);key=self.preview();self.lost='qml' + r=self.service.execute(self.apply(key));self.assertFalse(r['result']['verified']);self.assertTrue(self.service.code_tools.blocked(self.device)) + old=self.service.packages;self.service.packages=PackageTools(self.service,old.atomic,old.utc) + self.assertFalse(self.call('reconcile')['result']['verified']);self.assertTrue(self.service.code_tools.blocked(self.device)) + restore=self.call('restore')['result']['preview_id'];self.lost=None + r=self.service.execute(self.apply(restore));self.assertTrue(r['result']['verified'],r);self.assertEqual(self.current,before) + def test_lost_final_ack_reconciles_without_retry(self): + self.supported();key=self.preview();self.lost='lisp';self.assertFalse(self.service.execute(self.apply(key))['result']['verified']) + self.assertTrue(self.call('reconcile')['result']['verified']);self.assertEqual(len([c for c in self.calls if c[0]=='code_write']),2) + def test_failed_recovery_keeps_original(self): + self.supported();original=copy.deepcopy(self.current);key=self.preview();self.lost='qml';self.service.execute(self.apply(key)) + key=self.call('restore')['result']['preview_id'];self.lost='before';self.service.execute(self.apply(key)) + self.assertEqual(self.service.packages.record(self.device,'backup')['before'],original) + self.assertFalse(self.call('reconcile')['result']['verified']) + def test_external_change_invalidates_installed_label(self): + self.supported();self.service.execute(self.apply(self.preview()));self.current['lisp']=snap(b'other');self.assertFalse(self.call('status')['result']['recognized']) + def test_changed_baseline_and_session_reject_before_write(self): + self.supported();key=self.preview();self.current['lisp']=snap(b'changed');self.assertEqual(self.service.execute(self.apply(key))['state'],'error') + key=self.preview();self.device.session='other';self.assertEqual(self.service.execute(self.apply(key))['state'],'error');self.assertNotIn('code_write',[c[0] for c in self.calls]) + def test_library_incompatible_size_and_unknown(self): + self.supported() + for f in ('library','compatible','fits'): + self.library=False;self.compatible=True;self.fits=True;setattr(self,f,f=='library') + self.assertEqual(self.call('prepare',{'id':self.key,'compatibility_confirmed':True})['state'],'error') + self.fits=True;self.compatible=None + self.assertEqual(self.call('prepare',{'id':self.key,'compatibility_confirmed':False})['state'],'error') + self.assertEqual(self.call('prepare',{'id':self.key,'compatibility_confirmed':True})['state'],'complete') + def test_remove_restore(self): + self.supported();before=copy.deepcopy(self.current);p=self.call('remove_prepare')['result']['preview_id'] + self.assertTrue(self.service.execute(self.apply(p))['result']['verified']);self.assertTrue(self.call('status')['result']['empty']) + p=self.call('restore')['result']['preview_id'];self.assertTrue(self.service.execute(self.apply(p))['result']['verified']);self.assertEqual(self.current,before) + def test_upload_checksum_replay_and_session(self): + p={'kind':'package','name':'test.vescpkg','size':len(self.data),'sha256':self.key,'library':True,'source':'import'} + key=self.call('begin',p)['result']['upload_id'];chunk={'upload_id':key,'offset':0,'data':b64(self.data)} + self.assertEqual(self.call('chunk',chunk)['state'],'complete');self.assertEqual(self.call('chunk',chunk)['state'],'complete');self.assertEqual(self.call('load',{'upload_id':key})['state'],'complete') + self.assertTrue(self.service.packages.catalog.imports()[self.key]['library']) + key=self.call('begin',p)['result']['upload_id'];self.device.session='changed';self.assertEqual(self.call('load',{'upload_id':key})['state'],'error') + def test_parsers_fail_closed(self): + for raw in (b'junk',b'\0\0\0\4badzlib',self.data[:-1],self.data+b'x',b'\0\0\0\1'+zlib.compress(b'x'*10000),package(b'name\0\0\0\0\1x'),package(b'bad\0\xff\xff\xff\xff')): + with self.assertRaises(ValueError):fields(raw) + for raw in (b'qres',bytes(100)): + with self.assertRaises(ValueError):archive(raw) + self.assertEqual(metadata(self.data)['name'],'Test') + def test_other_pending_blocks_write(self): + self.supported();key=self.preview();self.service.code_tools.path(self.device).write_text('{}') + self.assertEqual(self.service.execute(self.apply(key))['state'],'error');self.assertNotIn('code_write',[c[0] for c in self.calls]) + def test_library_import_resolves_pinned_catalogue_only(self): + self.service.packages.catalog.load=lambda:({}, {'lib_test/test.vescpkg':self.data}) + def rpc(method,**p): + self.assertEqual(method,'package_unpack');self.assertTrue(p['export_library']) + return {'compatible':True,'library':{'source':'(+ 1 2)','imports':{'native':b64(b"binary")}}} + self.device.link.rpc=rpc + project={'kind':'lisp','source':'(import "pkg::native@://vesc_packages/lib_test/test.vescpkg" \'blob)\n(print blob)','imports':{},'fullscreen':False} + out=self.service.packages.resolve_imports(self.device,project) + self.assertEqual(list(out['imports'].values()),[b64(b'binary')]);self.assertNotIn('pkg::',out['source']) + project['source']=project['source'].replace('lib_test','lib_absent') + with self.assertRaises(ValueError):self.service.packages.resolve_imports(self.device,project) + def test_reimport_of_bundled_package_does_not_duplicate_catalogue(self): + self.service.packages.catalog.load=lambda:({}, {'lib_test/test.vescpkg':self.data}) + result=self.service.packages.catalog.publish(self.data,'package','test.vescpkg',False,'import') + self.assertTrue(result['existing']);self.assertEqual(self.service.packages.catalog.imports(),{}) + def test_catalogue_preserves_journal_and_backup_headroom(self): + from unittest.mock import patch + target=self.service.root/'package-imports.json' + fake=type('File',(),{'stat':lambda _:type('Stat',(),{'st_size':24*1024*1024})()})() + with patch('pathlib.Path.glob',return_value=[fake]): + with self.assertRaises(ValueError):self.service.packages.catalog.publish(self.data,'package','test.vescpkg',True,'import') + self.assertFalse(target.exists()) + def test_invalid_parameters(self): + for n,p in [('apply',{'preview_id':'code_'+'1'*32,'confirmed':True,'inputs_isolated':False}),('download',{'id':'1'*64,'offset':-1}),('inspect',{'id':'../secret'}),('refresh',{'url':'http://localhost'})]: + with self.assertRaises(ValueError):validate('vesc.packages.'+n,p) diff --git a/plugins/vesc/tests/test_preflight_recovery.py b/plugins/vesc/tests/test_preflight_recovery.py new file mode 100644 index 00000000..2534fb31 --- /dev/null +++ b/plugins/vesc/tests/test_preflight_recovery.py @@ -0,0 +1,106 @@ +"""Failed arming before motor ownership must recover availability without rearming.""" +import copy +import sys +import threading +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from runtime.remote_control import RemoteControl + + +def fixture(): + bindings = {side+'.1': {'device_id':side, 'uuid':str(i)*24} + for i, side in enumerate(('left','right'), 1)} + profile = {'layout':'1x1', 'revision':2, 'bindings':bindings} + motor = SimpleNamespace(active=False, receiver_active=lambda _, v:abs(v)>.15, + limits=SimpleNamespace(pending=lambda _:False), run=Mock(), latched=True) + service = SimpleNamespace(motor=motor, lock=threading.RLock(), operation_lock=threading.Lock(), + devices={}, drive=SimpleNamespace(value=profile), + firmware_update=SimpleNamespace(lock=threading.Lock(), active=None)) + remote = RemoteControl(service) + remote.ensure_live = Mock() # Only exercise preflight; no real lease/thread/device calls. + remote.lease.id='a'*32 + remote._prepare({'id':'a'*32}) + devices=[SimpleNamespace(id=b['device_id'], identity={'uuid':b['uuid']}, session=b['device_id']+'-new', + identified_session=b['device_id']+'-new', link=SimpleNamespace(alive=True), + sample=None) for b in bindings.values()] + return remote, devices + + +def observe(remote, devices, at): + for d in devices: + d.sample={'session_id':d.session,'sampled_at':at, + 'values':{'motor_current_a':0.,'input_current_a':0.,'duty':0.,'erpm':0.,'fault_code':0}, + 'receiver':{'level':0.}} + with patch('runtime.remote_control.time.monotonic', return_value=at): + remote._reconcile_preflight(devices) + + +class PreflightRecoveryTests(unittest.TestCase): + def test_empty_preflight_recovers_with_fresh_bound_pair_and_preserves_history(self): + remote, devices=fixture() + self.assertEqual(remote.state,'fault') + old=copy.deepcopy(remote.last_stop) + for at in (10.,10.2,10.4,10.6,10.8):observe(remote,devices,at) + self.assertEqual(remote.state,'stopped') + self.assertIsNone(remote.message) + self.assertIsNone(remote.release_confirmed) # No output happened; no fabricated release ACK. + self.assertIsNone(remote.pending_availability) + self.assertEqual(remote.last_stop['message'],old['message']) + self.assertIn('recovered_at',remote.last_stop) + self.assertFalse(remote.lease.live()) + self.assertIn('a'*32,remote.lease.retired) + self.assertTrue(remote.service.motor.latched) + remote.service.motor.run.assert_not_called() + + def test_missing_wrong_uuid_unverified_and_changed_profile_do_not_clear_fault(self): + for case in ('missing','uuid','unverified','profile','limits','motor','firmware'): + with self.subTest(case=case): + remote,devices=fixture() + if case=='missing':devices=devices[:1] + if case=='uuid':devices[0].identity['uuid']='f'*24 + if case=='unverified':devices[0].identified_session='old' + if case=='profile':remote.service.drive.value['revision']+=1 + if case=='limits':remote.service.motor.limits.pending=lambda _:True + if case=='motor':remote.service.motor.active=True + if case=='firmware':remote.service.firmware_update.active={'device_id':'left'} + for at in (10.,10.2,10.4,10.6,10.8):observe(remote,devices,at) + self.assertEqual(remote.state,'fault') + self.assertFalse(remote.lease.live()) + + def test_interrupted_pair_requires_a_new_whole_neutral_window(self): + remote,devices=fixture() + for at in (10.,10.2,10.4):observe(remote,devices,at) + observe(remote,devices[:1],10.6) + for at in (10.8,11.,11.2): + observe(remote,devices,at) + self.assertEqual(remote.state,'fault') + for at in (11.4,11.6):observe(remote,devices,at) + self.assertEqual(remote.state,'stopped') + + def test_fault_label_does_not_report_control_after_worker_and_lease_end(self): + remote,_=fixture() + remote.thread=SimpleNamespace(is_alive=lambda:False) + self.assertIs(remote.snapshot()['control_active'],False) + remote.thread=SimpleNamespace(is_alive=lambda:True) + self.assertIs(remote.snapshot()['control_active'],True) + + def test_recovery_observer_runs_without_viewer_or_dev_interest(self): + remote,devices=fixture() + service=remote.service + service.firmware_update.owns=lambda _:False + service.devices={d.id:d for d in devices} + remote.trace=SimpleNamespace(active=lambda:False) + remote._publish=Mock() + remote._reconcile_preflight=Mock() + remote._reconcile_release=Mock() + for d in devices: + d.readable=True;d.lock=threading.Lock();d.attachment=object() + d.sample={'old':True};d.link=SimpleNamespace(query=Mock(return_value=b'')) + with patch('runtime.remote_control.values',return_value={}), patch('runtime.remote_control.ppm',return_value={}): + remote.observe() + self.assertEqual(remote._publish.call_count,2) + remote._reconcile_preflight.assert_called_once() diff --git a/plugins/vesc/tests/test_qml_broker.py b/plugins/vesc/tests/test_qml_broker.py new file mode 100644 index 00000000..846b14ea --- /dev/null +++ b/plugins/vesc/tests/test_qml_broker.py @@ -0,0 +1,168 @@ +"""No physical I/O: adversarial intents, pacing, failure and session fencing.""" + +import base64 +import unittest +from types import SimpleNamespace +from unittest.mock import Mock + +from runtime.motor_test import Rejected +from runtime.qml_broker import READ_CODES, QmlBroker, read_intent +from runtime.qml_preview import validate +from runtime.qml_session import checked_frame +from test_qml_interactive import InteractiveTests + + +class BrokerTests(unittest.TestCase): + def setUp(self): + self.now = [0.0] + self.broker = QmlBroker(lambda: self.now[0]) + self.service = Mock() + self.service.code_tools.pending.return_value = False + self.service.code_tools.path.return_value.exists.return_value = False + self.service.qml_utc.return_value = "2026-10-18T12:00:00Z" + self.device = SimpleNamespace(readable=True, link=Mock()) + self.device.link.rpc.side_effect = lambda _, **kw: { + "payload": base64.b64encode(bytes([kw["intent"]["command"], 0])).decode() + } + self.worker = Mock() + self.worker.exchange.return_value = {"read_requests": []} + + def run_frame(self, *codes): + return self.broker.exchange( + self.device, + self.service, + self.worker, + {"read_requests": [{"command": c} for c in codes]}, + ) + + def test_every_unadmitted_command_and_shape_fails(self): + for code in range(256): + if code not in READ_CODES: + with self.assertRaises(ValueError): + read_intent({"command": code}) + for value in ( + {"command": True}, + {"command": 4, "payload": "anything"}, + {"command": 65}, + {"command": 65, "mask": True}, + {"command": 65, "mask": 65536}, + {"command": 65.0, "mask": 1}, + ): + with self.assertRaises(ValueError): + read_intent(value) + self.assertEqual(read_intent({"command": 65, "mask": 0x1FF})["mask"], 0x1FF) + + def test_valid_prefix_cannot_smuggle_write_in_same_batch(self): + with self.assertRaises(ValueError): + self.run_frame(4, 8) + self.device.link.rpc.assert_not_called() + + def test_rate_batch_cooldown_coalescing_and_no_background(self): + first = self.run_frame(4, 14, 17, 31, 32, 33) + self.assertEqual(first["broker_status"]["reads"], 2) + self.assertTrue(first["hardware_access"]) + self.assertFalse(first["direct_hardware_access"]) + self.assertEqual(first["broker_status"]["pending"], 4) + self.run_frame(4, 4) + self.assertEqual(self.device.link.rpc.call_count, 2) + self.now[0] = 0.5 + self.run_frame() + self.assertEqual(self.device.link.rpc.call_count, 4) + self.now[0] = 1 + self.run_frame() + self.assertEqual(self.device.link.rpc.call_count, 6) + self.now[0] = 1.5 + self.run_frame(14) + self.assertEqual( + self.device.link.rpc.call_count, 7 + ) # values repeat, config waits ten seconds + self.assertEqual(list(self.broker.pending), [14]) + self.now[0] = 10 + self.assertEqual(self.device.link.rpc.call_count, 7) # time alone performs no I/O + self.run_frame() + self.assertEqual(self.device.link.rpc.call_count, 8) + for call in self.worker.exchange.call_args_list: + self.assertEqual(call.args[0]["events"], []) + self.assertLessEqual(len(call.args[0]["packets"]), 2) + + def test_response_mismatch_and_busy_never_reach_renderer(self): + self.device.link.rpc.return_value = None + self.device.link.rpc.side_effect = lambda *a, **k: {"payload": "CA=="} + with self.assertRaises(ValueError): + self.run_frame(4) + self.worker.exchange.assert_not_called() + self.service.code_tools.idle.side_effect = RuntimeError("busy") + self.now[0] = 1 + self.device.link.rpc.reset_mock() + with self.assertRaises(RuntimeError): + self.run_frame(4) + self.device.link.rpc.assert_not_called() + + def test_open_contract_never_accepts_broker_without_context(self): + p = {"upload_id": "qml_" + "a" * 32, "snapshot": True, "broker": True} + validate("vesc.qml.open", p) + for value in (False, 1, None): + with self.assertRaises(ValueError): + validate("vesc.qml.open", {**p, "snapshot": value}) + with self.assertRaises(ValueError): + validate("vesc.qml.open", {**p, "broker": "true"}) + + def test_child_cannot_claim_unisolated_frame(self): + frame = dict( + hardware_access=False, + sandbox_verified=True, + snapshot_only=False, + broker=True, + ok=True, + width=640, + height=480, + png=base64.b64encode(b"\x89PNG\r\n\x1a\n").decode(), + ) + self.assertTrue(checked_frame(frame)["rendered"]) + for change in ( + {"hardware_access": True}, + {"sandbox_verified": False}, + {"snapshot_only": True}, + ): + with self.assertRaises(Rejected): + checked_frame({**frame, **change}) + + +class BrokerSessionTests(InteractiveTests): + def open(self): + self.device.link.engine = {"contract": {"methods": ["qml_read"]}} + original = self.call + + def call(name, p): + if name == "open": + p = {**p, "snapshot": True, "broker": True} + return original(name, p) + + self.call = call + try: + return super().open() + finally: + self.call = original + + # Inherited default-no-read test covers the standalone suite, not this mode. + def test_open_and_input_never_query_hardware_and_close_reaps(self): + self.worker.initial = {"read_requests": [{"command": 4}]} + self.worker.exchange.return_value = {"read_requests": []} + self.device.link.rpc = Mock( + return_value={"payload": base64.b64encode(self.base.query(4)).decode()} + ) + key = self.open() + self.device.link.rpc.assert_called_once_with("qml_read", timeout=1.2, intent={"command": 4}) + self.device.session += "-reconnected" + result = self.call("frame", {"qml_id": key, "events": []}) + self.assertEqual(result["state"], "error") + self.assertEqual(self.device.link.rpc.call_count, 1) + self.service.qml.maintain([]) + self.worker.close.assert_called_once() + + def test_untrusted_request_failure_closes_worker(self): + self.worker.initial = {"read_requests": [{"command": 8}]} + with self.assertRaises(AssertionError): + self.open() # helper expects success; actual result is error + self.worker.close.assert_called_once() + self.assertIsNone(self.service.qml.session) diff --git a/plugins/vesc/tests/test_qml_interactive.py b/plugins/vesc/tests/test_qml_interactive.py new file mode 100644 index 00000000..f8817f86 --- /dev/null +++ b/plugins/vesc/tests/test_qml_interactive.py @@ -0,0 +1,83 @@ +"""Stateful QML remains local to an isolated child, using no live reads by default.""" + +import base64 +import hashlib +import unittest +from unittest.mock import Mock, patch + +import test_config_editor +from runtime.qml_preview import validate + + +class InteractiveTests(unittest.TestCase): + def setUp(self): + self.base = test_config_editor.ConfigEditorTests() + self.base.setUp() + self.service, self.device = self.base.service, self.base.device + self.device.link.check = Mock() + self.worker = Mock() + self.worker.expired.return_value = False + self.worker.initial = { + "rendered": True, + "png": "synthetic", + "hardware_access": False, + "standalone": True, + } + self.worker.exchange.return_value = self.worker.initial + self.service.qml.session_factory = Mock(return_value=self.worker) + + def tearDown(self): + self.base.tearDown() + + def call(self, name, p): + c = self.base.command(action="vesc.qml." + name) + c["parameters"] = p + return self.service.execute(c) + + def open(self): + raw = b"import QtQuick 2.5; Item {}" + key = self.call("begin", {"size": len(raw), "sha256": hashlib.sha256(raw).hexdigest()})[ + "result" + ]["upload_id"] + self.call("chunk", {"upload_id": key, "offset": 0, "data": base64.b64encode(raw).decode()}) + result = self.call("open", {"upload_id": key, "snapshot": False}) + self.assertEqual(result["state"], "complete", result) + return result["result"]["qml_id"] + + def test_open_and_input_never_query_hardware_and_close_reaps(self): + with patch.object( + self.device.link, "query", side_effect=AssertionError("Unexpected hardware query") + ): + key = self.open() + result = self.call( + "frame", {"qml_id": key, "events": [{"kind": "text", "text": "abc"}]} + ) + self.assertEqual(result["state"], "complete", result) + self.assertEqual(self.call("close", {"qml_id": key})["state"], "complete") + self.worker.exchange.assert_called_once_with( + {"op": "frame", "events": [{"kind": "text", "text": "abc"}]} + ) + self.worker.close.assert_called_once() + self.assertEqual(self.base.writes, []) + + def test_replacement_detach_and_expiry_close_child(self): + self.open() + self.open() + self.assertEqual(self.worker.close.call_count, 1) + self.service.qml.maintain([]) + self.assertEqual(self.worker.close.call_count, 2) + key = self.open() + self.worker.expired.return_value = True + self.assertEqual(self.call("frame", {"qml_id": key, "events": []})["state"], "error") + self.assertIsNone(self.service.qml.session) + + def test_malformed_input_cannot_escape(self): + for event in ( + {"kind": "text", "text": "x" * 1025}, + {"kind": "down", "x": True, "y": 0}, + {"kind": "down", "x": 640, "y": 0}, + {"kind": "wheel", "x": 0, "y": 0, "delta": 1201}, + {"kind": "exec", "command": "anything"}, + ): + with self.assertRaises(ValueError): + validate("vesc.qml.frame", {"qml_id": "view_" + "1" * 32, "events": [event]}) diff --git a/plugins/vesc/tests/test_qml_preview.py b/plugins/vesc/tests/test_qml_preview.py new file mode 100644 index 00000000..267be212 --- /dev/null +++ b/plugins/vesc/tests/test_qml_preview.py @@ -0,0 +1,102 @@ +"""QML staging is bound to a live session; only fixed read queries reach USB.""" + +import base64 +import hashlib +import unittest +from unittest.mock import patch + +import test_config_editor +from runtime.qml_preview import validate + + +class QmlPreviewTests(unittest.TestCase): + def setUp(self): + self.base = test_config_editor.ConfigEditorTests() + self.base.setUp() + self.service, self.device = self.base.service, self.base.device + self.device.link.check = lambda: None + self.rendered = [] + self.service.qml.renderer = lambda request: ( + self.rendered.append(request) or {"rendered": True, "png": "synthetic"} + ) + + def tearDown(self): + self.base.tearDown() + + def call(self, name, params): + c = self.base.command(action="vesc.qml." + name) + c["parameters"] = params + return self.service.execute(c) + + def upload(self, raw=b"import QtQuick 2.5; Item {}"): + p = self.call("begin", {"size": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}) + self.assertEqual(p["state"], "complete", p) + key = p["result"]["upload_id"] + r = self.call( + "chunk", {"upload_id": key, "offset": 0, "data": base64.b64encode(raw).decode()} + ) + self.assertEqual(r["state"], "complete", r) + return key + + def test_502_render_reads_snapshot_and_never_writes_or_persists_source(self): + source = b'import QtQuick 2.5; Item { property string marker: "PRIVATE_QML_SOURCE" }' + key = self.upload(source) + with patch.object(self.device.link, "query", wraps=self.base.query) as query: + result = self.call("render", {"upload_id": key}) + self.assertEqual(result["state"], "complete", result) + self.assertEqual(self.base.writes, []) + self.assertEqual([c.args[0] for c in query.call_args_list], [14, 17, 4]) + self.assertEqual(self.rendered[0]["source"], source.decode()) + for kind, code in (("motor", 14), ("application", 17)): + entry = self.rendered[0]["configs"][kind] + self.assertEqual(entry["encoding"], "base64") + raw = base64.b64decode(entry["payload"], validate=True) + self.assertEqual(raw, self.base.query(code)) + self.assertEqual(entry["bytes"], len(raw)) + self.assertEqual(entry["sha256"], hashlib.sha256(raw).hexdigest()) + self.assertNotIn(key, self.service.qml.uploads) + for p in self.service.root.glob("op_*.json"): + raw = p.read_text() + self.assertNotIn("PRIVATE_QML_SOURCE", raw) + self.assertNotIn("synthetic", raw) + + def test_changed_session_or_expired_upload_cannot_render(self): + key = self.upload() + self.device.session += "changed" + self.assertEqual(self.call("render", {"upload_id": key})["state"], "error") + self.assertEqual(self.rendered, []) + key = self.upload() + self.service.qml.clock = lambda: 10**15 + self.assertEqual(self.call("render", {"upload_id": key})["state"], "error") + + def test_partial_hash_mismatch_and_duplicate_chunk(self): + raw = b"abc" + key = self.upload(raw) + params = {"upload_id": key, "offset": 0, "data": base64.b64encode(raw).decode()} + self.assertEqual(self.call("chunk", params)["result"]["offset"], len(raw)) + self.service.qml.uploads[key]["sha256"] = "0" * 64 + self.assertEqual(self.call("render", {"upload_id": key})["state"], "error") + self.assertEqual(self.rendered, []) + + def test_preview_does_not_run_during_drive_and_error_cannot_leave_a_worker(self): + key = self.upload() + self.service.motor.active = True + self.assertEqual(self.call("render", {"upload_id": key})["state"], "error") + self.assertEqual(self.rendered, []) + self.service.motor.active = False + self.service.qml.renderer = lambda _: (_ for _ in ()).throw(OSError("renderer terminated")) + self.assertEqual(self.call("render", {"upload_id": key})["state"], "error") + self.assertNotIn(key, self.service.qml.uploads) + self.assertEqual(self.base.writes, []) + + def test_bounds_and_cross_upload_memory(self): + for params in ( + {"size": True, "sha256": "0" * 64}, + {"size": 122881, "sha256": "0" * 64}, + {"size": 1, "sha256": "x" * 64}, + ): + with self.assertRaises(ValueError): + validate("vesc.qml.begin", params) + for _ in range(4): + self.upload() + self.assertEqual(len(self.service.qml.uploads), 2) diff --git a/plugins/vesc/tests/test_read_admission.py b/plugins/vesc/tests/test_read_admission.py new file mode 100644 index 00000000..d6d5629f --- /dev/null +++ b/plugins/vesc/tests/test_read_admission.py @@ -0,0 +1,53 @@ +"""Read admission against concurrent observation; no hardware access.""" +import unittest +import test_reader as reader +FakeLink = reader.FakeLink + +class ReadAdmissionTests(unittest.TestCase): + setUp = reader.ServiceTests.setUp + tearDown = reader.ServiceTests.tearDown + command = reader.ServiceTests.command + + def test_read_waits_for_observer_then_executes_exactly_once(self): + import threading + command = self.command() + entered = threading.Event() + underlying = threading.Lock() + underlying.acquire() + class Guard: + def acquire(self, *args, **kwargs): + entered.set() + return underlying.acquire(*args, **kwargs) + def release(self): underlying.release() + self.service.operation_lock = Guard() + results = [] + worker = threading.Thread(target=lambda: results.append(self.service.execute(command))) + worker.start() + try: + self.assertTrue(entered.wait(1)) + finally: + underlying.release() + worker.join(2) + self.assertFalse(worker.is_alive()) + self.assertEqual(results[0]["state"], "complete") + self.assertEqual(FakeLink.instances[0].commands.count(4), 1) + self.assertEqual(self.service.execute(command), results[0]) + self.assertEqual(FakeLink.instances[0].commands.count(4), 1) + + def test_read_admission_is_bounded_and_never_leaves_future_work(self): + import time + command = self.command() + self.service.operation_lock.acquire() + before = list(FakeLink.instances[0].commands) + started = time.monotonic() + try: + with self.assertRaisesRegex(ValueError, "Another VESC operation"): + self.service.execute(command) + finally: + self.service.operation_lock.release() + self.assertLess(time.monotonic()-started, 1.5) + self.assertEqual(FakeLink.instances[0].commands, before) + self.assertFalse((self.service.root / (command["operation_id"]+".json")).exists()) + self.assertEqual(self.service.execute(command)["state"], "complete") + self.assertEqual(FakeLink.instances[0].commands.count(4), 1) + diff --git a/plugins/vesc/tests/test_reader.py b/plugins/vesc/tests/test_reader.py index f5abbf25..91bec818 100644 --- a/plugins/vesc/tests/test_reader.py +++ b/plugins/vesc/tests/test_reader.py @@ -107,6 +107,21 @@ class ServiceTests(unittest.TestCase): "requested_at": now.isoformat(), "deadline_at": (now + timedelta(seconds=60)).isoformat(), "action_id": action, "parameters": {}} + def test_configuration_snapshot_is_bounded_and_retry_never_reexecutes(self): + from unittest.mock import patch + command = self.command(action="vesc.configuration.read") + with patch.object(FakeLink, "configuration", create=True, return_value={"motor": {"xml": "synthetic"}}) as read: + result = self.service.execute(command) + self.assertEqual(result["state"], "complete") + self.assertEqual(self.service.execute(command), result) + self.assertEqual(read.call_count, 1) + journal = json.loads((self.service.root / (command["operation_id"] + ".json")).read_text()) + self.assertTrue(journal["snapshot_only"]) + self.assertNotIn("synthetic", json.dumps(journal)) + self.service.read_cache.items.clear() + self.assertEqual(self.service.execute(command)["state"], "error") + self.assertEqual(read.call_count, 1) + def test_two_attachments_promote_independently(self): items = self.service.inventory("node_synthetic")["items"] self.assertEqual(len({i["id"] for i in items}), 2) @@ -149,6 +164,10 @@ class ServiceTests(unittest.TestCase): process = FakeLink.instances[0] process.alive = False self.service.scan() + self.assertTrue(process.closed) + self.assertFalse(self.service.inventory("node_synthetic")["items"][0]["verified"]) + next(iter(self.service.devices.values())).retry_at = 0 + self.service.scan() current = next(i for i in self.service.inventory("node_synthetic")["items"] if i["id"] == old["id"]) self.assertTrue(process.closed) self.assertNotEqual(current["snapshot"]["context"]["session_id"], old["snapshot"]["context"]["session_id"]) diff --git a/plugins/vesc/tests/test_recorded_gap.py b/plugins/vesc/tests/test_recorded_gap.py new file mode 100644 index 00000000..12d48165 --- /dev/null +++ b/plugins/vesc/tests/test_recorded_gap.py @@ -0,0 +1,42 @@ +"""Virtual replay of the observed lease boundary, without hardware or sleeping. + +The recorded pair had 223.464946ms remaining and the next input after +225.146509ms. This is a conditional fixed-arrival model, not a network emulator: +a fresh halfway sample fits the same carrier, while an old-frame repeat cannot +extend expiry. Real paired runs separately qualify delivery after the change. +""" +from runtime.remote_control import InputLease + + +def command(sequence, ttl): + return dict(id="a" * 32, sequence=sequence, ttl_ms=ttl, left=0, right=0, + settings=dict(standstill_confirmed=True, current_a=30, max_erpm=2000)) + + +def test_recorded_boundary_retires_the_old_input_and_cannot_revive(): + now = [0.0] + lease = InputLease(lambda: now[0]) + assert lease.accept(command(1, 223.464946269989)) + now[0] = 225.14650900103152 / 1000 + assert not lease.accept(command(2, 97.169508934021)) + assert not lease.live() + assert not lease.accept(command(3, 400)) + + +def test_halfway_fresh_intent_survives_same_arrival_gap_with_original_expiry(): + now = [0.0] + lease = InputLease(lambda: now[0]) + # The current carrier carries a genuinely newer sample generated 50ms later, + # whose creation-time+400ms expiry is also 50ms later. No timeout is enlarged. + ttl = 223.464946269989 + 50 + assert lease.accept(command(2, ttl)) + now[0] = 225.14650900103152 / 1000 + assert lease.live() + assert lease.accept(command(3, 97.169508934021)) + until = lease.until + now[0] += .04 + assert not lease.accept(command(3, 400)) + assert lease.until == until + now[0] = until + .000001 + assert not lease.live() + assert not lease.accept(command(4, 400)) diff --git a/plugins/vesc/tests/test_recorded_lease_gaps.py b/plugins/vesc/tests/test_recorded_lease_gaps.py new file mode 100644 index 00000000..7785ab40 --- /dev/null +++ b/plugins/vesc/tests/test_recorded_lease_gaps.py @@ -0,0 +1,68 @@ +"""Replay measured receipt intervals using production InputLease and virtual time. + +Only scalar leases are constructed: no service, transport, device or motor owner. +The fixture contains timings, not real device or session identities. Use stdlib +unittest so the versioned Ubuntu qualification executes the same regressions. +""" + +import unittest + +from runtime.remote_control import InputLease + + +class RecordedLeaseGapTests(unittest.TestCase): + def test_recorded_delay_retires_lease_and_burst_cannot_resume(self): + for previous_ttl, gap, next_ttl in ( + (315.3427047729492, 339.64408599957824, 74.66824197769165), + (314.2937664985657, 324.4391710013151, 83.09043550491333), + (316.37342500686646, 325.0489139985293, 190.74263620376587), + # Node75 operator drive: the next distinct intent arrived after expiry. + (312.36106967926025, 349.7367709996179, 167.06609201431274), + # Paired operator capture: almost-expired intent during preparation. + (18.767090320587158, 22.299001002684236, 63.74395513534546), + ): + with self.subTest(previous_ttl=previous_ttl, gap=gap, next_ttl=next_ttl): + now = [0.0] + lease = InputLease(lambda now=now: now[0]) + + def command(sequence, ttl): + return dict( + id="a" * 32, + sequence=sequence, + ttl_ms=ttl, + left=1, + right=-1, + settings=dict(standstill_confirmed=True, current_a=30, max_erpm=2000), + ) + + self.assertTrue(lease.accept(command(1, previous_ttl))) + now[0] = gap / 1000 + self.assertFalse(lease.accept(command(2, next_ttl))) + self.assertFalse(lease.live()) + self.assertEqual(lease.demand, (0, 0)) + self.assertFalse(lease.accept(command(3, 300))) + self.assertFalse(lease.live()) + + def test_timely_delivery_retains_authority_until_original_deadline(self): + now = [0.0] + lease = InputLease(lambda now=now: now[0]) + for n in range(1, 20): + now[0] = (n - 1) * 0.1 + self.assertTrue( + lease.accept( + dict( + id="a" * 32, + sequence=n, + ttl_ms=315, + left=0, + right=0, + settings=dict(standstill_confirmed=True, current_a=30, max_erpm=2000), + ) + ) + ) + now[0] += 0.316 + self.assertFalse(lease.live()) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/vesc/tests/test_release_observation.py b/plugins/vesc/tests/test_release_observation.py new file mode 100644 index 00000000..6e19bea3 --- /dev/null +++ b/plugins/vesc/tests/test_release_observation.py @@ -0,0 +1,338 @@ +"""A failed cleanup read must not permanently override later measured idle.""" + +import threading +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from runtime.remote_control import RemoteControl + +NOTICE = "Снятие тока не подтверждено. Проверьте фактическое состояние моторов." + + +def fixture(): + devices = [ + SimpleNamespace( + id=name, + session=name + "-attachment", + link=SimpleNamespace(alive=True), + sample=None, + readable=True, + lock=threading.Lock(), + ) + for name in ("left", "right") + ] + owner = SimpleNamespace( + active=False, + mode=None, + receiver_active=lambda _, level: abs(level) > 0.15, + latched=True, + state=Mock(), + limits=SimpleNamespace(pending=lambda _: False), + ) + service = SimpleNamespace( + motor=owner, + lock=threading.RLock(), + operation_lock=threading.Lock(), + devices={d.id: d for d in devices}, + firmware_update=SimpleNamespace(lock=threading.Lock(), active=None), + ) + remote = RemoteControl(service) + service.remote = remote + remote.release_confirmed = False + remote.state = "fault" + remote.message = NOTICE + remote.lease.id = "a" * 32 + remote.lease.stop() + if hasattr(remote, "_await_release"): + remote._await_release(devices) + return remote, devices + + +def sample(devices, at, **override): + for d in devices: + d.sample = dict( + session_id=d.session, + sampled_at=at, + values=dict(motor_current_a=0.8, input_current_a=0.0, duty=0.0, erpm=0.0, fault_code=0), + receiver=dict(level=0.01), + ) + d.sample["values"].update(override) + + +def observe(remote, devices, at, **override): + sample(devices, at, **override) + with patch("runtime.remote_control.time.monotonic", return_value=at): + remote._reconcile_release(devices) + + +class ReleaseObservationTests(unittest.TestCase): + def test_firmware_fault_during_pending_settlement_remains_terminal_after_it_clears(self): + with patch('runtime.remote_control.time.monotonic', return_value=10.0): + remote, devices = fixture() + remote.state = 'stopping' + remote.last_stop = {'session_id': 'a' * 32, 'state': 'stopping', 'message': NOTICE} + observe(remote, devices, 10.1, fault_code=1) + assert remote.state == 'fault' and remote.last_stop['state'] == 'fault' + for at in (10.3, 10.5, 10.7, 10.9): + observe(remote, devices, at) + assert remote.release_confirmed is True + assert remote.last_stop['state'] == 'fault' + assert not remote.lease.live() + + def test_settlement_classification_never_excuses_missing_invalid_or_failed_release(self): + import copy + from runtime.release_observation import settlement_pending + evidence = {'devices': {'left': {'send': {'sent': True}, 'reason': 'non_neutral_readback', + 'values': {'motor_current_a': 7.01, 'input_current_a': 1.55, 'duty': 0, 'erpm': 0, 'fault_code': 0}}}} + assert settlement_pending(evidence) + for change in ('send', 'read', 'invalid', 'missing', 'fault'): + candidate = copy.deepcopy(evidence) + d = candidate['devices']['left'] + if change == 'send': d['send']['sent'] = False + if change == 'read': d['reason'] = 'read_failed' + if change == 'invalid': d['values']['motor_current_a'] = float('nan') + if change == 'missing': del d['values']['erpm'] + if change == 'fault': d['values']['fault_code'] = 1 + assert not settlement_pending(candidate), change + assert not settlement_pending(None) + assert not settlement_pending({'devices': {}}) + + def test_pending_network_stop_settles_without_erasing_its_history_or_rearming(self): + with patch('runtime.remote_control.time.monotonic', return_value=10.0): + remote, devices = fixture() + remote.state = 'stopping' + remote.last_stop = {'session_id': 'a' * 32, 'state': 'stopping', 'message': NOTICE} + for at in (10.1, 10.3, 10.5, 10.7): + observe(remote, devices, at) + assert remote.state == 'stopped' + assert remote.release_confirmed is True + assert remote.last_stop['state'] == 'stopping' + assert 'recovered_at' in remote.last_stop + assert not remote.lease.live() and remote.service.motor.latched + remote.service.motor.state.assert_not_called() + + def test_verified_reconnection_restarts_proof_for_same_physical_pair(self): + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + for index, d in enumerate(devices): + d.identity = {"uuid": str(index) * 24} + d.identified_session = d.session + remote._await_release(devices) + remote.last_stop = {"session_id": "a" * 32, "state": "fault", "message": NOTICE} + observe(remote, devices, 10.1) + for d in devices: + d.session += "-reconnected" + d.identified_session = d.session + for at in (10.3, 10.5, 10.7, 10.9): + observe(remote, devices, at) + assert remote.release_confirmed is False + observe(remote, devices, 11.1) + assert remote.release_confirmed is True and remote.state == "stopped" + assert remote.last_stop["message"] == NOTICE + assert "recovered_at" in remote.last_stop + assert not remote.lease.live() and remote.service.motor.latched + remote.service.motor.state.assert_not_called() + + def test_replacement_or_unverified_identity_never_rebinds_release_proof(self): + for replacement in (True, False): + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + for index, d in enumerate(devices): + d.identity = {"uuid": str(index) * 24} + d.identified_session = d.session + remote._await_release(devices) + devices[1].session += "-new" + if replacement: + devices[1].identity = {"uuid": "f" * 24} + devices[1].identified_session = devices[1].session + for at in (10.1, 10.3, 10.5, 10.7, 10.9): + observe(remote, devices, at) + assert remote.release_confirmed is False + + def test_terminal_fault_clears_only_after_neutral_and_limits_receipt(self): + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + remote.last_stop = {"session_id": "a" * 32, "state": "fault", "message": NOTICE} + remote.service.motor.limits.pending = lambda _: True + for at in (10.1, 10.3, 10.5, 10.7): + observe(remote, devices, at) + assert remote.release_confirmed is True and remote.state == "fault" + assert remote.pending_release is not None + remote.service.motor.limits.pending = lambda _: False + observe(remote, devices, 10.9) + assert remote.state == "stopped" and remote.message is None + assert remote.last_stop["state"] == "fault" + + def test_failed_release_recovers_only_after_a_new_stable_window_without_rearming(self): + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + for at in (10.1, 10.3, 10.5): + observe(remote, devices, at) + assert remote.release_confirmed is False + observe(remote, devices, 10.7) + assert remote.release_confirmed is True + assert remote.state == "stopped" and remote.message is None + assert not remote.lease.live() and "a" * 32 in remote.lease.retired + assert remote.service.motor.latched is True + remote.service.motor.state.assert_not_called() + + def test_other_fault_and_limit_restoration_message_are_preserved(self): + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + remote.message += " Восстановление токовых пределов не подтверждено. Broken transport." + for at in (10.1, 10.3, 10.5, 10.7): + observe(remote, devices, at) + assert remote.release_confirmed is True and remote.state == "fault" + assert ( + remote.message == "Восстановление токовых пределов не подтверждено. Broken transport." + ) + + def test_non_neutral_stale_missing_changed_and_nonfinite_samples_never_confirm(self): + cases = ( + "current", + "input-current", + "duty", + "rpm", + "fault", + "nan", + "ppm", + "missing", + "stale", + "generation", + "duplicate", + ) + for case in cases: + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + for at in (10.1, 10.3, 10.5, 10.7, 10.9): + sample(devices, at) + v = devices[1].sample["values"] + if case == "current": + v["motor_current_a"] = 1.1 + if case == "input-current": + v["input_current_a"] = -1.1 + if case == "duty": + v["duty"] = 0.01 + if case == "rpm": + v["erpm"] = 50 + if case == "fault": + v["fault_code"] = 1 + if case == "nan": + v["motor_current_a"] = float("nan") + if case == "ppm": + devices[1].sample["receiver"]["level"] = 0.4 + if case == "stale": + devices[1].sample["sampled_at"] = 9.0 + if case == "generation": + devices[1].session = "new-generation" + inputs = ( + devices[:1] + if case == "missing" + else devices + [devices[1]] + if case == "duplicate" + else devices + ) + with patch("runtime.remote_control.time.monotonic", return_value=at): + remote._reconcile_release(inputs) + assert remote.release_confirmed is False, case + + def test_repeated_cached_samples_and_a_read_gap_do_not_count_as_stability(self): + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + observe(remote, devices, 10.1) + for at in (10.3, 10.5, 10.7): + with patch("runtime.remote_control.time.monotonic", return_value=at): + remote._reconcile_release(devices) + assert remote.release_confirmed is False + observe(remote, devices, 11.0) + observe(remote, devices, 11.2) + assert remote.release_confirmed is False + + def test_control_or_motor_or_firmware_owner_blocks_reconciliation(self): + for case in ("lease", "thread", "motor", "firmware"): + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + if case == "lease": + remote.lease.live = lambda: True + if case == "thread": + remote.thread = SimpleNamespace(is_alive=lambda: True) + if case == "motor": + remote.service.motor.active = True + if case == "firmware": + remote.service.firmware_update.active = {"device_id": "left"} + for at in (10.1, 10.3, 10.5, 10.7): + observe(remote, devices, at) + assert remote.release_confirmed is False, case + + def test_passive_observer_rechecks_without_viewer_or_dev_and_enables_maintenance(self): + from pathlib import Path + from tempfile import TemporaryDirectory + + from runtime.maintenance_state import idle + + with patch("runtime.remote_control.time.monotonic", return_value=10.0): + remote, devices = fixture() + service = remote.service + service.firmware_update.owns = lambda _: False + service.samples = SimpleNamespace(active=lambda _: False) + remote.trace = SimpleNamespace( + active=lambda: False, add=Mock(), log=SimpleNamespace(closed=True) + ) + remote.watch_until = 0 + events = [] + current = [19.39] + for d in devices: + d.identity = {"version": "other"} + d.attachment = object() + d.link.query = lambda code, timeout: ( + { + "motor_current_a": current[0], + "input_current_a": 0.0, + "erpm": 0.0, + "duty": 0.0, + "fault_code": 0, + } + if code == 4 + else {"level": 0.01} + ) + d.failed = Mock() + + def publish(d, value, receiver): + import time + + events.append(d.id) + d.sample = dict( + session_id=d.session, sampled_at=time.monotonic(), values=value, receiver=receiver + ) + + remote._publish = publish + with TemporaryDirectory() as tmp: + service.root = Path(tmp) + assert idle(service) == "release-unconfirmed" + for at in (10.1, 10.3, 10.5): + with ( + patch("runtime.remote_control.time.monotonic", return_value=at), + patch("runtime.remote_control.values", lambda v: v), + patch("runtime.remote_control.ppm", lambda v: v), + ): + remote.observe() + assert remote.release_confirmed is False + current[0] = 0.8 + for at in (10.7, 10.9, 11.1, 11.3): + with ( + patch("runtime.remote_control.time.monotonic", return_value=at), + patch("runtime.remote_control.values", lambda v: v), + patch("runtime.remote_control.ppm", lambda v: v), + ): + remote.observe() + for d in devices: + d.failed.assert_not_called() + assert remote.release_confirmed is True + assert len(events) == 14 + assert idle(service) is None + (service.root / "limits_unresolved.json").touch() + assert idle(service) == "device-change-unresolved" + service.motor.state.assert_not_called() + assert remote.lease.id in remote.lease.retired + remote.trace.add.assert_called_once() diff --git a/plugins/vesc/tests/test_remote_control.py b/plugins/vesc/tests/test_remote_control.py index cb5abe91..e51685f9 100644 --- a/plugins/vesc/tests/test_remote_control.py +++ b/plugins/vesc/tests/test_remote_control.py @@ -65,7 +65,7 @@ class PreparationHandoffTests(unittest.TestCase): 'left.1': {'device_id': 'left'}, 'right.1': {'device_id': 'right'}}} service = SimpleNamespace(operation_lock=ObservedLock(), lock=threading.Lock(), motor=SimpleNamespace(run=run), drive=SimpleNamespace(value=profile), - devices={'left': SimpleNamespace(link=object()), 'right': SimpleNamespace(link=object())}) + devices={'left': SimpleNamespace(id='left',link=object()), 'right': SimpleNamespace(id='right',link=object())}) self.remote = RemoteControl(service) self.remote.lease = InputLease(lambda: self.now[0]) self.relay = 'b' * 32 @@ -96,6 +96,32 @@ class PreparationHandoffTests(unittest.TestCase): self.assertEqual(self.remote.state, 'stopped') self.assertFalse(self.operation.locked()) + def test_new_lease_does_not_inherit_failed_release_or_claim_success(self): + self.remote.state = 'fault' + self.remote.message = 'Old USB failure' + self.remote.release_confirmed = False + self.remote.release_evidence = {'old': True} + self.start() + snapshot = self.remote.snapshot() + self.assertEqual(snapshot['state'], 'preparing') + self.assertIsNone(snapshot['message']) + self.assertIsNone(snapshot['release_confirmed']) + self.assertIsNone(self.remote.release_evidence) + self.assertEqual(self.calls, [], 'preflight still waits for hardware ownership') + self.finish() + self.assertEqual(self.calls, ['prepare']) + + def test_new_session_preflight_failure_remains_terminal(self): + def run(*args, **kwargs): + raise ValueError('Motor is not neutral') + self.remote.service.motor.run = run + self.remote.release_confirmed = False + self.start() + self.finish() + self.assertEqual(self.remote.state, 'fault') + self.assertIn('Motor is not neutral', self.remote.message) + self.assertFalse(self.remote.lease.live()) + def test_stop_while_waiting_never_starts_preparation(self): self.start() self.remote.feed({'watch': True, 'command': None, 'relay_id': self.relay}) @@ -128,9 +154,28 @@ class PreparationHandoffTests(unittest.TestCase): self.finish() self.assertEqual(self.calls, ['prepare']) + def test_remote_native_failure_is_recorded_after_release_without_rearm(self): + import json + error = OSError('Native query timed out or disconnected') + error.native_rpc = {'command': 31, 'transport': {'serial_bytes_written': 6}} + def run(*args, **kwargs): + self.remote.release_confirmed = False + self.remote.message = 'Release unconfirmed' + raise error + self.remote.service.motor.run = run + with self.assertLogs('missioncore.vesc.failure') as capture: + self.start() + self.finish() + record = json.loads(capture.records[0].getMessage()) + self.assertEqual(record['native_rpc'], error.native_rpc) + self.assertIs(record['release_confirmed'], False) + self.assertEqual(self.remote.state, 'fault') + self.assertFalse(self.remote.lease.live()) + self.assertFalse(self.operation.locked()) + class DriveBoundaryTests(unittest.TestCase): """Synthetic two-controller run: verify the actual output loop and cleanup.""" - def run_drive(self, scenario, *, broken_read=False, through_prepare=False, minimum_erpm=900): + def run_drive(self, scenario, *, broken_read=False, through_prepare=False, minimum_erpm=900, duty_percent=None, neutral_only=False): now=[0.]; logs=[]; restored=[] profile={'layout':'1x1','revision':1,'bindings':{ 'left.1':{'device_id':'left','uuid':'left'}, @@ -148,24 +193,33 @@ class DriveBoundaryTests(unittest.TestCase): if broken_read and self.name=='right' and now[0]>=.2:raise TimeoutError('lost right controller') if code==4: result=value() + if (owner.stop.is_set() or not remote.lease.live()) and self.name == 'right': + if scenario == 'non-neutral-release': result['motor_current_a'] = 2 + if scenario == 'invalid-release': result['duty'] = float('nan') + if scenario == 'expire-settling' and not remote.lease.live(): + result['motor_current_a'] = 7.01 if self.name == 'left' else 3.05 + result['input_current_a'] = 1.55 if self.name == 'left' else 1.01 + if scenario=='right-only-braking' and self.name=='left' and .2<=now[0]<2.5:result['motor_current_a']=6 if scenario=='coasting' and self.name=='right' and .4<=now[0]<.8:result['erpm']=1000 return result return {'level':.8 if scenario=='receiver' and .2<=now[0]<.5 else 0} def test_command(self,name):logs.append((now[0],self.name,name,0)) def test_speed(self,rpm):logs.append((now[0],self.name,'rpm',rpm)) + def drive_duty(self,duty,current_a):logs.append((now[0],self.name,'duty',duty)) devices=[SimpleNamespace(id=name,link=Link(name)) for name in ('left','right')] owner=SimpleNamespace(stop=threading.Event(),latched=False,active=False,mode=None) def state(s):owner.latched=s=='rc' owner.state=state owner.receiver_active=lambda _,level:abs(level)>.15 - owner.limits=SimpleNamespace(apply=lambda d,*a:dict(l_current_max=35,l_max_erpm=100000,l_min_erpm=-100000,l_max_duty=.95, + owner.limits=SimpleNamespace(apply=lambda d,*a:dict(l_abs_current_max=160,l_current_max=35,l_max_erpm=100000,l_min_erpm=-100000,l_max_duty=.95, s_pid_min_erpm=minimum_erpm[d.id] if isinstance(minimum_erpm,dict) else minimum_erpm),restore=lambda d:restored.append(d.id)) def sleep(delta): now[0]+=delta - if now[0]>=2:owner.stop.set() + if now[0]>=(3 if scenario=='right-only-braking' else 2):owner.stop.set() if remote.lease.live(): - if scenario!='expire': remote.lease.until=now[0]+.4 + if scenario not in ('expire', 'expire-settling'): remote.lease.until=now[0]+.4 remote.lease.demand=((-1,-1) if scenario=='reverse' and now[0]>=.4 else (1,1)) + if scenario in ('right-only','right-only-braking'): remote.lease.demand=(0,1) if scenario=='small': remote.lease.demand=(.2,-.2) if scenario=='turn': remote.lease.demand=(-1,1) if scenario=='release' and now[0]>=.4: remote.lease.demand=(0,0) @@ -175,20 +229,60 @@ class DriveBoundaryTests(unittest.TestCase): remote.lease.demand=(1,1) if now[0]<.4 else (0,0) if now[0]<1.2 else (-1,-1) if scenario=='cancel-reverse': remote.lease.demand=(-1,-1) if .4<=now[0]<.6 else (1,1) + if neutral_only: remote.lease.demand=(0,0) owner.sleep=sleep - command={'parameters':{'current_a':30,'erpm':2000}} - originals={d.id:{'motor':b'config'} for d in devices} + command={'parameters':{'current_a':30,**({'erpm':2000} if duty_percent is None else {'max_duty_percent':duty_percent})}} + application={'app_ppm_conf.ctrl_type':4,'app_ppm_conf.ramp_time_pos':.5,'app_ppm_conf.ramp_time_neg':.5} + originals={d.id:{'motor':b'config','application':application} for d in devices} service.motor=owner;service.operation_lock=threading.Lock();service.lock=threading.Lock() service.devices={d.id:d for d in devices} owner.run=lambda command,devices,target,remote:remote.drive(owner,command,devices,devices,originals,lambda:None) error=None - with patch('runtime.remote_control.time.monotonic',lambda:now[0]),patch('runtime.remote_control.values',lambda v:v),patch('runtime.remote_control.ppm',lambda v:v): + with patch('runtime.remote_control.time.monotonic',lambda:now[0]),patch('runtime.remote_control.values',lambda v:v),patch('runtime.remote_control.ppm',lambda v:v),patch('runtime.remote_control.decode',lambda v,k:v): try: if through_prepare: remote._prepare(envelope()) else: remote.drive(owner,command,devices,devices,originals,lambda:None) except (ValueError,TimeoutError) as e:error=e return logs,restored,remote,owner,error + def test_stationary_braking_side_is_not_a_stalled_motion_request(self): + _,restored,_,_,error=self.run_drive('right-only-braking',duty_percent=100) + self.assertIsNone(error) + self.assertEqual(set(restored),{'left','right'}) + + def test_single_side_turn_keeps_ppm_zero_duty_on_other_side(self): + log,restored,_,_,error=self.run_drive('right-only',duty_percent=100) + self.assertIsNone(error) + self.assertTrue(any(t>.1 and name=='left' and method=='duty' and value==0 for t,name,method,value in log)) + self.assertTrue(any(name=='right' and method=='duty' and value>0 for _,name,method,value in log)) + self.assertEqual(set(restored),{'left','right'}) + for name in ('left','right'): + self.assertEqual([v for v in log if v[1]==name][-1][2],'release') + + def test_throttle_reaches_selected_fraction_without_bench_duty_or_pid_floor(self): + for percent in (1,10,50,100): + log,restored,_,_,error=self.run_drive('forward',duty_percent=percent) + self.assertIsNone(error) + self.assertEqual(set(restored),{'left','right'}) + self.assertFalse(any(v[2]=='rpm' for v in log)) + outputs=[v[3] for v in log if v[2]=='duty'] + self.assertTrue(outputs) + self.assertAlmostEqual(max(outputs),.95*percent/100) + self.assertTrue(all(0=cutoff for v in log)) + self.assertEqual(set(restored),{'left','right'}) + for name in ('left','right'):self.assertEqual([v[2] for v in log if v[1]==name][-1],'release') + log,_,_,_,error=self.run_drive('turn-forward',duty_percent=50) + self.assertIsNone(error) + self.assertFalse(any(v[2]=='duty' and .4<=v[0]<.9 for v in log)) + for name in ('left','right'): + self.assertGreaterEqual(next(v[0] for v in log if v[2]=='duty' and v[1]==name and v[0]>=.4),.9) + def test_start_enters_each_configured_pid_range_without_dead_ramp(self): log,_,_,_,error=self.run_drive('forward',minimum_erpm={'left':900,'right':1100.1}) self.assertIsNone(error) @@ -273,11 +367,25 @@ class DriveBoundaryTests(unittest.TestCase): self.assertEqual(set(restored),{'left','right'}) self.assertFalse(remote.service.operation_lock.locked()) + def test_expired_input_keeps_release_settlement_pending_without_reviving_authority(self): + log, restored, remote, owner, error = self.run_drive('expire-settling', through_prepare=True) + self.assertIsNone(error) + self.assertEqual(remote.state, 'stopping') + self.assertEqual(remote.last_stop['state'], 'stopping') + self.assertFalse(remote.release_confirmed) + self.assertIsNotNone(remote.pending_release) + self.assertFalse(remote.lease.live()) + self.assertIn(remote.lease.id, remote.lease.retired) + self.assertFalse(any(row[2] == 'rpm' and row[0] >= .4 for row in log)) + self.assertEqual(set(restored), {'left', 'right'}) + self.assertFalse(remote.service.operation_lock.locked()) + def test_session_wrapper_preserves_unconfirmed_release_fault(self): _,_,remote,owner,error=self.run_drive('lost',broken_read=True,through_prepare=True) self.assertEqual(remote.state,'fault') self.assertFalse(remote.release_confirmed) self.assertIn('не подтверждено',remote.message) + self.assertIsNotNone(remote.pending_release) self.assertFalse(remote.service.operation_lock.locked()) def test_receiver_first_gesture_holds_zero_until_neutral(self): @@ -304,4 +412,30 @@ class DriveBoundaryTests(unittest.TestCase): self.assertTrue(owner.latched) self.assertEqual(remote.state,'fault') self.assertIn('не подтверждено',remote.message) + self.assertIsNotNone(remote.pending_release) self.assertEqual(set(restored),{'left','right'}) + + def test_release_evidence_distinguishes_read_failure_from_non_neutral(self): + for scenario, broken, expected in [('lost', True, 'read_failed'), + ('non-neutral-release', False, 'non_neutral_readback'), + ('invalid-release', False, 'invalid_readback')]: + with self.subTest(scenario=scenario): + _,_,remote,_,_ = self.run_drive(scenario, broken_read=broken, through_prepare=True) + evidence = remote.last_stop['release_evidence'] + self.assertFalse(remote.last_stop['release_confirmed']) + self.assertEqual(evidence['devices']['right']['reason'], expected) + self.assertEqual(evidence['devices']['left']['reason'], 'neutral_readback') + self.assertTrue(evidence['devices']['right']['send']['sent']) + if broken: + self.assertEqual(evidence['devices']['right']['error_type'], 'TimeoutError') + if scenario == 'invalid-release': + self.assertIsNone(evidence['devices']['right']['values']['duty']) + import json + json.dumps(evidence, allow_nan=False) + + def test_release_evidence_keeps_verified_cleanup_and_is_copied_to_stop(self): + _,_,remote,_,_ = self.run_drive('expire', through_prepare=True) + self.assertTrue(remote.release_confirmed) + self.assertEqual(set(remote.last_stop['release_evidence']['devices']), {'left', 'right'}) + remote.release_evidence['devices']['left']['reason'] = 'changed' + self.assertEqual(remote.last_stop['release_evidence']['devices']['left']['reason'], 'neutral_readback') diff --git a/plugins/vesc/tests/test_remote_current.py b/plugins/vesc/tests/test_remote_current.py new file mode 100644 index 00000000..8749625d --- /dev/null +++ b/plugins/vesc/tests/test_remote_current.py @@ -0,0 +1,34 @@ +"""Operator current is a ceiling inside the existing VESC configuration.""" +import tempfile +from pathlib import Path +from types import SimpleNamespace +import unittest +from test_motor_test import configuration +from runtime.configuration import decode +from runtime.temporary_limits import TemporaryLimits, FIELDS +from runtime.remote_limits import publish, projection + +class CurrentTests(unittest.TestCase): + def test_readback_clamps_each_motor_and_preserves_battery_and_base_limits(self): + for requested in (12,35,100,120,150): + for base in (34.213497,34.407795,100,120): + with self.subTest(requested=requested,base=base),tempfile.TemporaryDirectory() as folder: + # Traction may be raised independently of braking. A lower + # brake limit must not become a hidden traction ceiling. + original=configuration('motor',dict(l_current_max=base,l_current_min=-34.213497, + l_current_max_scale=1,l_current_min_scale=1,l_in_current_max=18,l_in_current_min=-10)) + old=decode(original,'motor');writes=[];raw=[original] + def write(changed): + writes.append(changed) + raw[0]=configuration('motor',changed) + link=SimpleNamespace(set_temporary_limits=write,query=lambda code:raw[0]) + d=SimpleNamespace(id='synthetic',identity={},link=link,session='generation-1') + limits=TemporaryLimits(SimpleNamespace(root=Path(folder)),lambda path,value:path.write_text('intent')) + actual=limits.apply(d,original,requested) + self.assertAlmostEqual(actual['l_current_max']*actual['l_current_max_scale'],min(requested,old['l_current_max']),places=4) + self.assertAlmostEqual(-actual['l_current_min']*actual['l_current_min_scale'],min(requested,-old['l_current_min']),places=4) + for k in old: + if k not in ('l_current_max_scale','l_current_min_scale'): self.assertEqual(actual[k],old[k],k) + self.assertEqual(len(writes),1) + publish(d,old);self.assertEqual(projection(vars(d))['motor_a'],old['l_current_max']) + d.session='new-generation';self.assertIsNone(projection(vars(d))) diff --git a/plugins/vesc/tests/test_remote_duty.py b/plugins/vesc/tests/test_remote_duty.py new file mode 100644 index 00000000..b02598ed --- /dev/null +++ b/plugins/vesc/tests/test_remote_duty.py @@ -0,0 +1,60 @@ +import unittest +from runtime.remote_duty import DutyOutput +from runtime.remote_control import InputLease +from runtime.motor_test import check_values, LimitExceeded + + +class DutyTests(unittest.TestCase): + def output(self, percent=100): + motors={'left':{'l_max_duty':.95},'right':{'l_max_duty':.8}} + applications={key:{'app_ppm_conf.ctrl_type':4,'app_ppm_conf.ramp_time_pos':ramp, + 'app_ppm_conf.ramp_time_neg':ramp} for key,ramp in [('left',.4),('right',.5)]} + return DutyOutput(motors,applications,percent) + + def test_ramp_preserves_normalised_tracks_and_limits(self): + output=self.output(50) + for key,maximum in [('left',.95),('right',.8)]: + target=output.target(key,-1) + self.assertAlmostEqual(target,-maximum*.5) + self.assertAlmostEqual(output.advance(key,0,target,.1),-maximum*.2) + self.assertEqual(output.advance(key,target,0,.1),0) + self.assertEqual(output.advance(key,0,target,-1),0) + + def test_invalid_percent_never_admitted(self): + for value in (True,0,-1,100.1,float('nan'),float('inf'),'50'): + with self.subTest(value=value),self.assertRaises(ValueError):self.output(value) + + def test_input_envelope_keeps_current_cap_and_distinguishes_units(self): + request=dict(id='a'*32,sequence=0,ttl_ms=400,left=0,right=0, + settings=dict(standstill_confirmed=True,current_a=30,max_duty_percent=50)) + self.assertTrue(InputLease().accept(request)) + for current in (35,60,100,120,150): + self.assertTrue(InputLease().accept({**request,'settings':{**request['settings'],'current_a':current}})) + for change in ({'current_a':float('inf')},{'current_a':float('nan')},{'current_a':.49},{'current_a':True},{'max_erpm':2000},{'max_duty_percent':101}, + {'max_duty_percent':True},{'max_duty_percent':float('nan')}): + with self.subTest(change=change),self.assertRaises(ValueError): + InputLease().accept({**request,'settings':{**request['settings'],**change}}) + + def test_renewal_cannot_change_throttle_or_units(self): + lease=InputLease() + request=dict(id='a'*32,sequence=0,ttl_ms=400,left=0,right=0, + settings=dict(standstill_confirmed=True,current_a=30,max_duty_percent=10)) + lease.accept(request) + with self.assertRaises(ValueError): + lease.accept({**request,'sequence':1,'settings':{**request['settings'],'max_duty_percent':100}}) + self.assertFalse(lease.live()) + + def test_drive_uses_configured_bounds_but_bench_remains_restricted(self): + value=dict(fault_code=0,input_voltage_v=48,mos_temperature_c=25,motor_current_a=20, + input_current_a=10,erpm=9000,duty=.5) + motor=dict(l_abs_current_max=160,l_current_max=34,l_max_erpm=20000,l_min_erpm=-20000,l_max_duty=.95) + check_values(value,True,30,motor,configured_drive=True) + # Recorded RC peaks are above the operating setting; this is not a fault. + check_values({**value,'motor_current_a':35.41},True,35,motor,configured_drive=True) + check_values({**value,'motor_current_a':-35.41},True,35,motor,configured_drive=True) + check_values({**value,'duty':.95},True,30,{**motor,'l_max_duty':.949999988},configured_drive=True) + with self.assertRaises(LimitExceeded):check_values(value,True,30,motor) + for change in ({'duty':.951},{'erpm':20001},{'erpm':-20001},{'fault_code':1}, + {'motor_current_a':160.01},{'mos_temperature_c':70},{'input_voltage_v':float('nan')}): + with self.subTest(change=change),self.assertRaises(LimitExceeded): + check_values({**value,**change},True,30,motor,configured_drive=True) diff --git a/plugins/vesc/tests/test_remote_idle_settling.py b/plugins/vesc/tests/test_remote_idle_settling.py new file mode 100644 index 00000000..e50a5bd8 --- /dev/null +++ b/plugins/vesc/tests/test_remote_idle_settling.py @@ -0,0 +1,104 @@ +"""Real preparation path waits for quiet readings; never writes during settling.""" +import struct +import unittest +from types import SimpleNamespace + +import test_group_test +from test_motor_test import configuration +from runtime.configuration import decode +from runtime.motor_test import Rejected + + +class RemoteIdleTests(unittest.TestCase): + def setUp(self): + self.rig = test_group_test.GroupTests('test_pair_and_four_motors_run_one_common_interval_and_restore') + self.rig.setUp() + self.addCleanup(self.rig.doCleanups) + self.case = self.rig.case + self.ready = [] + self.duty = lambda device, count: 0 + self.extra = lambda raw: raw + self.liveness = lambda: None + for device in self.case.devices: + self.rig.configs[device.id] = configuration('motor', { + **decode(self.rig.configs[device.id], 'motor'), 'foc_sensor_mode': 0}) + original = device.link.query + counter = [0] + def read(code, timeout=2, original=original, device=device, counter=counter): + raw = original(code, timeout) + if code == 4: + counter[0] += 1 + raw = raw[:21] + struct.pack('>h', self.duty(device, counter[0])) + raw[23:] + raw = self.extra(raw) + return raw + device.link.query = read + def ensure(): + self.assertEqual(self.case.sent, []) + self.assertEqual(self.rig.sets, []) + self.liveness() + def drive(*args): + self.ready.append(self.case.clock.now) + return {'prepared': True} + self.remote = SimpleNamespace(ensure_live=ensure, drive=drive, + _publish=lambda device, value, receiver: device.publish_sample(value, receiver)) + + def run_prepare(self): + command = self.rig.command() + del command['parameters']['erpm'] + command['parameters']['max_duty_percent'] = 10 + return self.case.service.motor.run(command, self.case.devices, + self.case.devices[0], remote=self.remote) + + def assert_no_output(self): + self.assertEqual(self.ready, []) + self.assertEqual(self.case.sent, []) + self.assertEqual(self.rig.sets, []) + self.assertEqual(self.rig.commands, []) + + def test_initial_two_quantum_transient_waits_for_full_quiet_window(self): + self.duty = lambda device, count: 2 if count == 1 else 0 + self.assertTrue(self.run_prepare()['prepared']) + self.assertGreaterEqual(self.ready[0], .99) + + def test_late_peer_transient_restarts_whole_profile_window(self): + self.duty = lambda device, count: -2 if device is self.case.devices[1] and count == 6 else 0 + self.assertTrue(self.run_prepare()['prepared']) + self.assertGreaterEqual(self.ready[0], 1.49) + + def test_persistent_small_pwm_never_admits_output(self): + self.duty = lambda device, count: 2 + with self.assertRaisesRegex(Rejected, 'не стабилизировался'): + self.run_prepare() + self.assertLessEqual(self.case.clock.now, 3.1) + self.assert_no_output() + + def test_large_pwm_rejected_immediately(self): + self.duty = lambda device, count: 11 + with self.assertRaisesRegex(Rejected, 'PWM'): + self.run_prepare() + self.assertEqual(self.case.clock.now, 0) + self.assert_no_output() + + def test_small_pwm_cannot_hide_excess_input_current(self): + self.duty = lambda device, count: 2 + self.extra = lambda raw: raw[:9] + struct.pack('>i', 101) + raw[13:] + with self.assertRaisesRegex(Rejected, 'ток батареи'): + self.run_prepare() + self.assert_no_output() + + def test_receiver_command_still_preempts_during_wait(self): + self.duty = lambda device, count: 2 + self.case.changed = True + with self.assertRaisesRegex(Rejected, 'Приёмник'): + self.run_prepare() + self.assert_no_output() + + def test_lease_expiry_during_wait_never_reaches_drive(self): + self.duty = lambda device, count: 2 + def expire(): + if self.case.clock.now >= .2: + raise Rejected('lease expired') + self.liveness = expire + with self.assertRaisesRegex(Rejected, 'lease expired'): + self.run_prepare() + self.assert_no_output() diff --git a/plugins/vesc/tests/test_remote_startup_projection.py b/plugins/vesc/tests/test_remote_startup_projection.py new file mode 100644 index 00000000..4f34837e --- /dev/null +++ b/plugins/vesc/tests/test_remote_startup_projection.py @@ -0,0 +1,96 @@ +"""Preparation/inventory must not hide samples or stall the input projection. + +Synthetic ports only. No control session is armed by the inventory test. +""" +import threading +from unittest.mock import patch + +from test_observer_recovery import ObservationRecoveryTests +from test_remote_idle_settling import RemoteIdleTests + + +class InventoryProjectionTests(ObservationRecoveryTests): + def test_attachment_without_session_cannot_claim_initialization(self): + for device in self.service.devices.values(): + device.session = None + device.identified_session = None + self.assertEqual(self.remote.snapshot()["observation"]["initializing_devices"], []) + + def test_first_read_initialization_is_attachment_owned_and_ends_on_sample(self): + devices = list(self.service.devices.values()) + before = self.remote.snapshot() + self.assertEqual(set(before["observation"]["initializing_devices"]), + {d.id for d in devices}) + self.remote.observe() + self.assertEqual(self.remote.snapshot()["observation"]["initializing_devices"], []) + self.assertIsNone(self.remote.thread) + self.assertFalse(self.remote.lease.live()) + + def test_cached_identity_failure_and_dead_link_are_not_initialization(self): + for device in self.service.devices.values(): + device.identified_session = "previous-attachment" + self.assertEqual(self.remote.snapshot()["observation"]["initializing_devices"], []) + for device in self.service.devices.values(): + device.identified_session = device.session + device.link.alive = False + self.assertEqual(self.remote.snapshot()["observation"]["initializing_devices"], []) + for device in self.service.devices.values(): + device.link.alive = True + device.error = "Read failure" + self.assertEqual(self.remote.snapshot()["observation"]["initializing_devices"], []) + + def test_slow_inventory_metadata_does_not_block_passive_remote_feed(self): + self.remote.observe() + entered, release, completed = threading.Event(), threading.Event(), threading.Event() + errors = [] + original = self.service.firmware_update.status + + def status(identifier): + entered.set() + if not release.wait(2): + raise TimeoutError('test cleanup deadline') + return original(identifier) + + def inventory(): + try: + self.service.inventory('test-node') + except Exception as error: + errors.append(error) + + def feed(): + self.remote.feed({'watch': True, 'command': None, 'relay_id': 'b' * 32}) + completed.set() + + with patch.object(self.service.firmware_update, 'status', side_effect=status): + worker = threading.Thread(target=inventory) + worker.start() + self.assertTrue(entered.wait(1)) + reader = threading.Thread(target=feed) + reader.start() + try: + self.assertTrue( + completed.wait(.2), 'inventory metadata holds the live projection lock') + finally: + release.set() + worker.join(2) + reader.join(2) + self.assertEqual(errors, []) + self.assertIsNone(self.remote.thread) + self.assertFalse(self.remote.lease.live()) + + +class PreparationProjectionTests(RemoteIdleTests): + def test_existing_neutral_samples_are_published_before_drive(self): + published = [] + def publish(device, value, receiver): + published.append((device.id, self.case.clock.now, value, receiver)) + device.publish_sample(value, receiver) + self.remote._publish = publish + self.run_prepare() + for device in self.case.devices: + samples = [r for r in published if r[0] == device.id] + self.assertGreaterEqual(len(samples), 10, 'preparation discards real readings') + self.assertGreaterEqual(samples[-1][1], .89) + self.assertIsNotNone(device.sample) + self.assertEqual(self.case.sent, []) + self.assertEqual(self.rig.sets, []) diff --git a/plugins/vesc/tests/test_samples.py b/plugins/vesc/tests/test_samples.py new file mode 100644 index 00000000..0f87bc73 --- /dev/null +++ b/plugins/vesc/tests/test_samples.py @@ -0,0 +1,68 @@ +"""Synthetic operation routing; no acquisition or motor commands.""" + +import unittest +from unittest.mock import Mock, patch + +import test_config_editor +from runtime.sample_data import validate + + +class SampleDataTests(unittest.TestCase): + def setUp(self): + self.base = test_config_editor.ConfigEditorTests() + self.base.setUp() + self.service, self.device = self.base.service, self.base.device + self.device.link.rpc = Mock( + return_value={"capture_id": "sample_" + "1" * 32, "state": "armed", "received": 0} + ) + + def tearDown(self): + self.base.tearDown() + + def call(self, name, p): + c = self.base.command(action="vesc.samples." + name) + c["parameters"] = p + return self.service.execute(c) + + def test_start_is_explicit_and_uses_existing_owner_without_motor_command(self): + self.assertEqual(self.device.link.rpc.call_count, 0) + p = {"mode": 4, "count": 500, "decimation": 2, "timeout_s": 30, "raw": False} + with patch.object(self.device.link, "query", wraps=self.base.query) as query: + result = self.call("start", p) + self.assertEqual(result["state"], "complete", result) + self.device.link.rpc.assert_called_once_with("sample_start", **p) + self.assertEqual([c.args[0] for c in query.call_args_list], [0]) + self.assertEqual(self.base.writes, []) + + def test_no_automatic_capture_on_status_and_pages_do_not_persist(self): + self.device.link.rpc.return_value = {"state": "complete", "rows": ["PRIVATE_SAMPLE_DATA"]} + result = self.call("read", {"capture_id": "sample_" + "1" * 32, "offset": 0}) + self.assertEqual(result["state"], "complete", result) + self.device.link.rpc.assert_called_once_with( + "sample_read", capture_id="sample_" + "1" * 32, offset=0 + ) + for p in self.service.root.glob("op_*.json"): + self.assertNotIn("PRIVATE_SAMPLE_DATA", p.read_text()) + + def test_bad_parameters_never_reach_native(self): + base = {"mode": 1, "count": 2, "decimation": 1, "timeout_s": 30, "raw": False} + for key, value in [ + ("mode", 0), + ("mode", 8), + ("count", True), + ("count", 2001), + ("decimation", 0), + ("timeout_s", 121), + ("raw", True), + ]: + with self.assertRaises(ValueError): + validate("vesc.samples.start", {**base, key: value}) + self.assertEqual(self.device.link.rpc.call_count, 0) + + def test_native_busy_is_rejection_not_usb_failure(self): + self.device.link.rpc.return_value = {"accepted": False, "reason": "Capture active"} + result = self.call( + "start", {"mode": 1, "count": 2, "decimation": 1, "timeout_s": 30, "raw": False} + ) + self.assertEqual(result["state"], "error") + self.assertIsNotNone(self.device.link) diff --git a/plugins/vesc/tests/test_speed_and_hall.py b/plugins/vesc/tests/test_speed_and_hall.py index 320b8329..c6582919 100644 --- a/plugins/vesc/tests/test_speed_and_hall.py +++ b/plugins/vesc/tests/test_speed_and_hall.py @@ -136,6 +136,36 @@ class RunTests(unittest.TestCase): self.assertEqual(self.case.service.execute(command),receipt) self.assertEqual(started,self.hall_started) + def test_native_hall_keeps_target_procedure_ownership_until_result(self): + target, peer = self.case.devices + commands = [] + for device in self.case.devices: + original = device.link.test_command + def send(action, device=device, original=original): + running = self.hall_started is not None and target.link.hall_result is None + commands.append((device.id, action, running)) + if device is target and running and action == 'claim': + raise OSError('Native procedure owns this controller') + return original(action) + device.link.test_command = send + command = self.case.command(action='vesc.hall.measure') + command['parameters'] = {'rig_clear': True, 'standstill_confirmed': True, + 'native_cycle_confirmed': True, + 'sessions': {d.id:d.session for d in self.case.devices}} + result = self.case.service.execute(command)['result'] + self.assertTrue(result['completed'], result) + self.assertTrue(result['measurement']['valid_six_states']) + self.assertEqual(result['issues'], []) + self.assertTrue(result['release_confirmed']) + self.assertTrue(result['configuration_restored']) + self.assertFalse(any(d == target.id and a == 'claim' and running + for d, a, running in commands)) + self.assertTrue(any(d == peer.id and a == 'claim' and running + for d, a, running in commands)) + self.assertTrue(any(d == peer.id and a == 'release' and running + for d, a, running in commands)) + self.assertFalse((self.case.service.root / 'hall-pending.json').exists()) + def test_native_hall_requires_its_own_explicit_confirmation(self): command=self.case.command(action='vesc.hall.measure') command['parameters']={'rig_clear':True,'standstill_confirmed':True,'native_cycle_confirmed':False, diff --git a/plugins/vesc/tests/test_trace_projection.py b/plugins/vesc/tests/test_trace_projection.py new file mode 100644 index 00000000..c5739a85 --- /dev/null +++ b/plugins/vesc/tests/test_trace_projection.py @@ -0,0 +1,35 @@ +"""Read-interest projection never acquires control or polls the hardware itself.""" +import copy +from unittest.mock import patch +from test_observer_recovery import ObservationRecoveryTests + + +class TraceProjectionTests(ObservationRecoveryTests): + def test_projection_keeps_sample_clock_and_does_not_renew_lease(self): + self.remote.observe() + before = [len(link.commands) for link in self.links] + lease = copy.deepcopy(self.remote.lease.__dict__) + relay = self.remote.relay + first = self.remote.observe_snapshot() + with patch('runtime.remote_control.time.monotonic', return_value=10**8): + second = self.remote.observe_snapshot() + self.assertEqual(before, [len(link.commands) for link in self.links]) + self.assertEqual(self.remote.lease.__dict__, lease) + self.assertEqual(self.remote.relay, relay) + for a, b in zip(first['devices'], second['devices']): + self.assertEqual(a['sample_time_ms'], b['sample_time_ms']) + self.assertEqual(a['observed_at'], b['observed_at']) + self.assertGreater(b['age_ms'], a['age_ms']) + self.assertIn('T', a['observed_at']) + b['values']['erpm'] = 12345 + self.assertNotEqual(self.remote.snapshot()['devices'][0]['values']['erpm'], 12345) + + def test_local_watch_expires_without_viewer_and_does_not_touch_relay(self): + self.remote.watch_until = 0 + self.remote.observe_snapshot() + self.remote.observe() + self.assertEqual(len(self.remote.snapshot()['devices']), 2) + before = [len(link.commands) for link in self.links] + self.remote.watch_until = 0 + self.remote.observe() + self.assertEqual(before, [len(link.commands) for link in self.links])