feat(vesc): extend motor diagnostics, configuration and transport recovery
Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import {Button,Description,TextField,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import {swdTargets,type CanFirmwareTarget,type SwdTarget} from './firmwareFiles';
|
||||
export function FirmwareDestination({mode,onMode,disabled,targets,options,canId,onCanId,scan,read,target,swd,onSwd}:{
|
||||
mode:string;onMode:(v:string)=>void;disabled:boolean;targets:string[];options:{value:string;label:string}[];canId:string;onCanId:(v:string)=>void;
|
||||
scan:()=>void;read:()=>void;target:CanFirmwareTarget|null;swd:SwdTarget;onSwd:(v:SwdTarget)=>void;
|
||||
}){
|
||||
return <SettingsCard title="Куда записать прошивку" description="Подготовка файла не изменяет flash и не подключает отладчик. Запись начинается только после отдельного подтверждения.">
|
||||
<Select label="Подключение" value={mode} disabled={disabled} options={[{value:'usb',label:'Этот VESC · USB'},...(targets.includes('can')?[{value:'can',label:'Один контроллер по CAN'}]:[]),...(targets.includes('swd')?[{value:'swd',label:'Внешний процессор по SWD'}]:[])]} onChange={onMode}/>
|
||||
{mode==='can'&&<><Button disabled={disabled} onClick={scan}>Найти устройства CAN</Button>
|
||||
<Select label="Адрес CAN" value={canId} disabled={disabled||!options.length} options={options} onChange={onCanId}/>
|
||||
<Button disabled={disabled||!canId} onClick={read}>Определить контроллер</Button>
|
||||
{target&&<Description>CAN {target.can_id} · {target.hardware} · FW {target.major}.{String(target.minor).padStart(2,'0')} · UUID {target.uuid.toUpperCase()}</Description>}
|
||||
<Description>Файл получит только выбранный UUID. При смене устройства на этом CAN-адресе запись отменяется.</Description></>}
|
||||
{mode==='swd'&&<>
|
||||
<Description>VESC по USB работает программатором. Проверьте распиновку и допустимые уровни напряжения целевой платы. Подключение SWD останавливает её процессор; запись стирает всю основную flash. Образ должен содержать всё необходимое для запуска. Семейство проверяется перед стиранием; модель платы и её UUID этим протоколом не определяются.</Description>
|
||||
<Select label="Целевой процессор" value={String(swd.target_code)} options={swdTargets} disabled={disabled} onChange={v=>onSwd({...swd,target_code:Number(v),address:Number(v)>=2&&Number(v)<=8?0:0x08000000,flash_bytes:128*1024})}/>
|
||||
<Select label="Распиновка программатора" value={swd.pins} options={[{value:'default',label:'Стандартная SWD'},{value:'nrf5x',label:'NRF5x'}]} disabled={disabled} onChange={pins=>onSwd({...swd,pins})}/>
|
||||
<TextField label="Начальный адрес записи, байт" type="number" value={String(swd.address)} disabled={disabled} onChange={e=>onSwd({...swd,address:Number(e.target.value)})}/>
|
||||
<TextField label="Доступно от этого адреса, КиБ" type="number" value={String(swd.flash_bytes/1024)} disabled={disabled} onChange={e=>onSwd({...swd,flash_bytes:Number(e.target.value)*1024})}/>
|
||||
<Description>Укажите диапазон по документации конкретного процессора. BIN начинается с указанного адреса; HEX должен начинаться там же. Option bytes, UICR и периферия исключены. Каждый записанный блок обязательно читается обратно.</Description>
|
||||
</>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {useEffect,useMemo,useRef,useState} from 'react';
|
||||
import {Description,Icon,IconButton,SettingsCard} from '@nodedc/ui-react';
|
||||
export interface SignalPoint {at:number;value:number|null}
|
||||
const number=(n:number|null)=>n===null?'—':n.toLocaleString('ru-RU',{maximumFractionDigits:3});
|
||||
export function signalView(points:readonly SignalPoint[],from:number,to:number,height=180,width=800){
|
||||
const span=Math.max(1,width-84);
|
||||
const visible=points.filter(p=>p.at>=from&&p.at<=to),valid=visible.filter(p=>p.value!==null&&Number.isFinite(p.value));
|
||||
let min:number|null=null,max:number|null=null,mean=0;
|
||||
for(const p of valid){min=min===null?p.value!:Math.min(min,p.value!);max=max===null?p.value!:Math.max(max,p.value!);mean+=p.value!/valid.length;}
|
||||
const pad=Math.max(((max??1)-(min??0))*.1,Math.abs(max??0)*.01,.001),low=(min??0)-pad,high=(max??1)+pad;
|
||||
const segments:SignalPoint[][]=[];let line:SignalPoint[]=[];
|
||||
const flush=()=>{if(line.length)segments.push(line);line=[];};
|
||||
for(const p of visible){if(p.value===null||!Number.isFinite(p.value))flush();else line.push(p);}flush();
|
||||
// Min/max per pixel bucket preserves spikes; gaps are never joined.
|
||||
const render=segments.map(segment=>{const out:SignalPoint[]=[];let bucket:SignalPoint[]=[];let previous=-1;
|
||||
const emit=()=>{if(!bucket.length)return;const values=[bucket[0],bucket.reduce((a,b)=>a.value!<b.value!?a:b),bucket.reduce((a,b)=>a.value!>b.value!?a:b),bucket.at(-1)!];out.push(...[...new Set(values)].sort((a,b)=>a.at-b.at));bucket=[];};
|
||||
for(const p of segment){const x=Math.floor((p.at-from)/Math.max(Number.EPSILON,to-from)*span);if(x!==previous){emit();previous=x;}bucket.push(p);}emit();
|
||||
return out.map(p=>({x:64+(p.at-from)/Math.max(Number.EPSILON,to-from)*span,y:20+(1-(p.value!-low)/(high-low))*height}));});
|
||||
return {segments:render,min,max,mean:valid.length?mean:null,count:valid.length,low,high};
|
||||
}
|
||||
export function SignalPlot({title,unit,points,from,to,xUnit='с',xScale=1000,cursors=[],step=false}:{title:string;unit:string;points:readonly SignalPoint[];from:number;to:number;xUnit?:string;xScale?:number;cursors?:readonly number[];step?:boolean}){
|
||||
const [expanded,setExpanded]=useState(false),[width,setWidth]=useState(800),height=expanded?384:160,span=Math.max(1,width-84);
|
||||
const svg=useRef<SVGSVGElement>(null);
|
||||
useEffect(()=>{const element=svg.current;if(!element)return;const observer=new ResizeObserver(entries=>{const next=Math.max(160,Math.round(entries[0].contentRect.width));setWidth(old=>old===next?old:next);});observer.observe(element);return()=>observer.disconnect();},[]);
|
||||
const view=useMemo(()=>signalView(points,from,to,height,width),[points,from,to,height,width]);
|
||||
return <SettingsCard title={title} description={`Минимум: ${number(view.min)} · максимум: ${number(view.max)} · среднее: ${number(view.mean)} ${unit} · ${view.count} измерений`}
|
||||
actions={<div className="nodedc-viewport-controls"><IconButton label={expanded?`Свернуть: ${title}`:`Развернуть: ${title}`} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div>}>
|
||||
<svg ref={svg} style={{height:height+56}} className={`vesc-trend-plot${expanded?' vesc-trend-plot--expanded':''}`} viewBox={`0 0 ${width} ${height+56}`} role="img" aria-label={`${title}, ${unit}; ${view.count} измерений`}>
|
||||
{[0,.5,1].map(f=><g key={f}><line className="vesc-trend-grid" x1="64" x2={width-20} y1={20+f*height} y2={20+f*height}/><text x="56" y={24+f*height} textAnchor="end">{number(view.high-f*(view.high-view.low))}</text></g>)}
|
||||
{view.segments.map((line,i)=>line.length===1?<circle key={i} className="vesc-trend-point" cx={line[0].x} cy={line[0].y} r="2"/>:<polyline key={i} className="vesc-trend-line" points={line.flatMap((p,j)=>step&&j?[`${p.x},${line[j-1].y}`,`${p.x},${p.y}`]:[`${p.x},${p.y}`]).join(' ')}/>)}
|
||||
{cursors.map((at,i)=>at>=from&&at<=to?<g key={i}><line className="vesc-trend-cursor" x1={64+(at-from)/Math.max(Number.EPSILON,to-from)*span} x2={64+(at-from)/Math.max(Number.EPSILON,to-from)*span} y1="20" y2={height+20}/><text x={64+(at-from)/Math.max(Number.EPSILON,to-from)*span} y="14" textAnchor="middle">{i+1}</text></g>:null)}
|
||||
<text x="64" y={height+47}>{number(from/xScale)} {xUnit}</text><text x={width-20} y={height+47} textAnchor="end">{number(to/xScale)} {xUnit}</text>
|
||||
</svg>
|
||||
{!view.count&&<Description>В этом интервале нет измерений. Пропуски не заменяются нулями.</Description>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Button,LoadingRegion,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
|
||||
import {useVescEditor} from './useVescEditor';
|
||||
import {VescChangeReview} from './VescChangeReview';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {vescStatus} from './model';
|
||||
import type {ConfigurationVersion,SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
|
||||
|
||||
export function VescBackups({deviceId,archive,revision}: {deviceId:string;archive:SensorTransport['configurationArchive'];revision:string|null}) {
|
||||
export function VescBackups({deviceId,archive,revision,editorProps}: {deviceId:string;archive:SensorTransport['configurationArchive'];revision:string|null;editorProps:ReadProps}) {
|
||||
const editor=useVescEditor(editorProps);
|
||||
const [reload,setReload]=useState(0);
|
||||
const [items,setItems]=useState<ConfigurationVersion[]>([]);
|
||||
const [next,setNext]=useState<string|null>(null);
|
||||
@@ -37,15 +43,15 @@ export function VescBackups({deviceId,archive,revision}: {deviceId:string;archiv
|
||||
}catch{setError('Не удалось скачать выбранную версию.');}
|
||||
finally{setDownload(null);}
|
||||
}
|
||||
return <SettingsCard title="История конфигураций" description="Сохранённые версии остаются на борту и передаются в Core при подключении." actions={<Button disabled={loading||!archive} onClick={()=>setReload(value=>value+1)}>Обновить историю</Button>}>
|
||||
<LoadingRegion loading={loading&&!items.length} label="Загрузка версий конфигурации">
|
||||
{error&&<p role="alert">{error}</p>}
|
||||
{!loading&&!items.length&&!error&&<p>Сохранённых версий пока нет.</p>}
|
||||
return <><VescChangeReview editor={editor} pending={vescStatus(editorProps.device).configuration_pending} blocked={editorProps.blocked}/><SettingsCard title="История конфигураций" description="Сохранённые версии остаются на борту и передаются в Core при подключении." actions={<Button disabled={loading||!archive} onClick={()=>setReload(value=>value+1)}>Обновить историю</Button>}>
|
||||
<LoadingRegion className="sensor-content" loading={loading&&!items.length} label="Загрузка версий конфигурации">
|
||||
{error&&<Description role="alert">{error}</Description>}
|
||||
{!loading&&!items.length&&!error&&<Description>Сохранённых версий пока нет.</Description>}
|
||||
<ResourceList aria-label="Версии конфигурации VESC">{items.map(item=><li key={item.id}>
|
||||
<ResourceRow title={new Date(item.observed_at).toLocaleString()} description={`Прошивка ${item.firmware} · мотор и входы`}
|
||||
actions={<Button disabled={download!==null} loading={download===item.id} onClick={()=>void save(item.id)}>Скачать</Button>}/>
|
||||
actions={<><Button disabled={download!==null} loading={download===item.id} onClick={()=>void save(item.id)}>Скачать</Button>{editor.available&&<Button disabled={editor.busy||editorProps.blocked} onClick={()=>void editor.prepare({backup_id:item.id})}>Сравнить и восстановить</Button>}</>}/>
|
||||
</li>)}</ResourceList>
|
||||
</LoadingRegion>
|
||||
{next&&<Button loading={loading} disabled={loading} onClick={()=>void more()}>Ещё версии</Button>}
|
||||
</SettingsCard>;
|
||||
</SettingsCard></>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Checker,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {VescBmsConfiguration} from './VescBmsConfiguration';
|
||||
import {vescStatus} from './model';
|
||||
import {bmsCommands,bmsNumber,bmsCells,bmsCellSummary,bmsTemperature,bmsCanOptions,type BmsReading,type BmsPreview} from './bmsView';
|
||||
|
||||
const fields=[['v_tot','Напряжение батареи, В'],['v_charge','Напряжение зарядки, В'],['i_in','Ток батареи, А'],['i_in_ic','Ток измерителя, А'],['ah_cnt','Счётчик заряда, А·ч'],['wh_cnt','Счётчик энергии, Вт·ч'],['soc','Заряд, %'],['soh','Остаточная ёмкость, %'],['ah_cnt_chg_total','Заряжено всего, А·ч'],['ah_cnt_dis_total','Разряжено всего, А·ч'],['wh_cnt_chg_total','Энергия заряда всего, Вт·ч'],['wh_cnt_dis_total','Энергия разряда всего, Вт·ч'],['humidity','Влажность, %'],['pressure','Давление, Па']] as const;
|
||||
function Values({reading}:{reading:BmsReading}){
|
||||
const values=reading.values??{},cells=bmsCells(values),summary=bmsCellSummary(values),temps=Array.isArray(values.temps)?values.temps.slice(0,32):[];
|
||||
if(reading.state!=='received')return <SettingsCard title="Ответ BMS"><Description>{reading.state==='not_bms'?'По этому адресу ответило другое устройство. Выберите BMS.':reading.state==='unsupported'?'Чтение BMS не поддерживается текущей прошивкой.':'Ответ BMS не получен.'}</Description></SettingsCard>;
|
||||
if(!cells.length)return <SettingsCard title="Данные батареи"><Description>VESC ответил без данных ячеек. Наличие подключённой BMS не подтверждено.</Description></SettingsCard>;
|
||||
return <>
|
||||
<SettingsCard title="Батарея" description={`Снимок получен ${new Date(reading.observed_at).toLocaleString('ru-RU')}. Он не обновляется автоматически.`}>
|
||||
{reading.source!=='direct_can'&&<Description>Это сохранённые сведения из VESC. Прошивка 5.02 не сообщает адрес BMS и возраст этих измерений; наличие связи с батареей по этому ответу определить нельзя.</Description>}
|
||||
<ResourceList aria-label="Показатели батареи">{fields.filter(([key])=>key in values).map(([key,label])=><li key={key}><ResourceRow title={label} description={bmsNumber(values[key],3,key==='soc'||key==='soh'?100:1)}/></li>)}</ResourceList>
|
||||
{typeof values.status==='string'&&values.status&&<Description>{values.status}</Description>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Ячейки" description="Номер соответствует порядку ячеек в ответе BMS. Балансировка показана на момент чтения.">
|
||||
{summary&&<ResourceList aria-label="Разброс напряжений"><li><ResourceRow title="Минимум / максимум" description={`${bmsNumber(summary.min)} / ${bmsNumber(summary.max)} В`}/></li><li><ResourceRow title="Разброс" description={`${bmsNumber(summary.spreadMv,1)} мВ`}/></li></ResourceList>}
|
||||
<ResourceList aria-label="Напряжения ячеек">{cells.map(cell=><li key={cell.index}><ResourceRow title={`Ячейка ${cell.index+1}`} description={`${bmsNumber(cell.voltage)} В · ${cell.balancing===null?'балансировка не сообщается':cell.balancing?'балансируется':'не балансируется'}`}/></li>)}</ResourceList>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Температуры">
|
||||
<ResourceList aria-label="Температуры батареи">{temps.map((v,i)=><li key={i}><ResourceRow title={`Датчик ${i+1}`} description={bmsTemperature(v)}/></li>)}
|
||||
<li><ResourceRow title="Измеритель" description={bmsTemperature(values.temp_ic)}/></li><li><ResourceRow title="Самая горячая ячейка" description={bmsTemperature(values.temp_cells_highest)}/></li><li><ResourceRow title="Датчик влажности" description={bmsTemperature(values.temp_hum_sensor)}/></li>
|
||||
</ResourceList>
|
||||
</SettingsCard>
|
||||
</>;
|
||||
}
|
||||
export function VescBms(props:ReadProps){
|
||||
const {device,transport,failure}=props,status=vescStatus(device);
|
||||
const [source,setSource]=useState('proxy'),[reading,setReading]=useState<BmsReading|null>(null);
|
||||
const [options,setOptions]=useState<{value:string;label:string}[]>([]),[canId,setCanId]=useState(''),[scanned,setScanned]=useState(false);
|
||||
const [busy,setBusy]=useState(false),[command,setCommand]=useState('charge_disable');
|
||||
const [preview,setPreview]=useState<BmsPreview|null>(null),[confirmed,setConfirmed]=useState(false),[isolated,setIsolated]=useState(false);
|
||||
const [result,setResult]=useState<{state:string;command:string;target:{can_id:number;uuid:string}}|null>(null);
|
||||
const running=useRef(false),mounted=useRef(true);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
const supported=status.engine?.contract?.methods.includes('bms_read')===true;
|
||||
const available=props.enabled&&device.online&&device.verified&&status.readable;
|
||||
const disabled=!available||props.blocked||busy;
|
||||
const call=<T,>(action:string,p:Record<string,unknown>={})=>perform<T>(transport,device,action,p,30000);
|
||||
async function run(work:()=>Promise<void>){
|
||||
if(running.current||disabled)return;running.current=true;setBusy(true);props.onBusyChange(true);failure(null);
|
||||
try{await work();}catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
function reset(){setReading(null);setPreview(null);setConfirmed(false);setIsolated(false);setResult(null);}
|
||||
const scan=()=>run(async()=>{const value=await call<{can_ids:number[]}>('vesc.can.read');if(mounted.current){const choices=bmsCanOptions(value.can_ids);setOptions(choices);setCanId(choices[0]?.value??'');setScanned(true);reset();}});
|
||||
const read=()=>run(async()=>{reset();const value=await call<BmsReading>(source==='proxy'?'vesc.tools.read':'vesc.bms.read',source==='proxy'?{tool:'bms'}:{can_id:Number(canId)});if(mounted.current)setReading(value);});
|
||||
const prepare=()=>run(async()=>{setPreview(null);setResult(null);setConfirmed(false);setIsolated(false);const value=await call<BmsPreview>('vesc.bms.prepare',{can_id:Number(canId),command});if(mounted.current)setPreview(value);});
|
||||
const apply=()=>run(async()=>{if(!preview||!confirmed||!isolated)return;const plan=preview;setPreview(null);setConfirmed(false);setIsolated(false);setReading(null);const value=await call<{state:string;command:string;target:{can_id:number;uuid:string}}>('vesc.bms.apply',{preview_id:plan.preview_id,confirmed:true,inputs_isolated:true});if(mounted.current)setResult(value);});
|
||||
return <div className="sensor-content">
|
||||
<SettingsCard title="Аккумулятор BMS" description="Данные батареи и адресные команды через CAN выбранного контроллера.">
|
||||
<Select label="Источник данных" value={source} options={[{value:'proxy',label:'Сведения через VESC'},...(supported?[{value:'direct',label:'BMS по CAN-адресу'}]:[])]} disabled={disabled} onChange={v=>{setSource(v);reset();}}/>
|
||||
{source==='direct'&&<>
|
||||
<Button disabled={disabled} loading={busy} onClick={()=>void scan()}>Найти устройства CAN</Button>
|
||||
{options.length>0&&<Select label="Адрес устройства" value={canId} options={options} disabled={disabled} onChange={v=>{setCanId(v);reset();}}/>}
|
||||
{scanned&&!options.length&&<Description>Устройства CAN не ответили. Проверьте подключение и питание BMS.</Description>}
|
||||
<Description>Перед чтением и каждой командой проверяются тип устройства и UUID BMS. Номер CAN сам по себе не определяет батарею.</Description>
|
||||
</>}
|
||||
<Button disabled={disabled||(source==='direct'&&!canId)} loading={busy} onClick={()=>void read()}>Прочитать батарею</Button>
|
||||
</SettingsCard>
|
||||
<div className="sensor-content">
|
||||
{reading?.target&&<SettingsCard title="Устройство на CAN"><ResourceList aria-label="Идентификация BMS"><li><ResourceRow title={`CAN ${reading.target.can_id} · ${reading.target.hardware}`} description={`FW ${reading.target.major}.${String(reading.target.minor).padStart(2,'0')} · UUID ${reading.target.uuid.toUpperCase()}`}/></li></ResourceList></SettingsCard>}
|
||||
{reading&&<Values reading={reading}/>}
|
||||
</div>
|
||||
{source==='direct'&&reading?.target?.hardware_type===1&&<SettingsCard title="Управление BMS" description="Каждая команда выполняется отдельно. Повторного выполнения после потери связи нет.">
|
||||
{!reading.commands_supported?<Description>Установленное ядро поддерживает команды BMS с прошивкой 6.00. Для этой версии доступно чтение.</Description>:<>
|
||||
<Select label="Действие" value={command} options={bmsCommands} disabled={disabled} onChange={v=>{setCommand(v);setPreview(null);setConfirmed(false);setIsolated(false);}}/>
|
||||
<Description>{command==='zero_current'?'Калибровка сохраняет смещение измерителя. Отключите зарядку и нагрузку; процедура занимает около двух секунд.':command.startsWith('reset_')?'Обнуляется текущий счётчик. Ранее накопленное значение не восстанавливается этой командой.':command.startsWith('balance_')?'BMS управляет балансировкой по своей конфигурации и состоянию ячеек. Разрешение не означает немедленное включение всех каналов.':'Разрешение зарядки влияет на работу батареи. Перед командой проверьте зарядное устройство и условия зарядки.'}</Description>
|
||||
<Button disabled={disabled} loading={busy} onClick={()=>void prepare()}>Подготовить команду</Button>
|
||||
</>}
|
||||
</SettingsCard>}
|
||||
{source==='direct'&&reading?.commands_supported&&reading.target&&(reading.target.custom_configs??0)>0&&<VescBmsConfiguration {...props} key={`${canId}-${reading.target.uuid}`} canId={Number(canId)} count={reading.target.custom_configs??0}/>}
|
||||
{preview&&<SettingsCard title="Подтверждение команды BMS" description="Подтверждение действует одну минуту и только для текущего сеанса.">
|
||||
<Description>{bmsCommands.find(c=>c.value===preview.command)?.label} · CAN {preview.target.can_id} · UUID {preview.target.uuid.toUpperCase()}</Description>
|
||||
<Checker label="Подтверждаю команду для этой батареи" checked={confirmed} onChange={setConfirmed} disabled={disabled}/>
|
||||
<Checker label="Входы управления отключены, нагрузка и зарядка проверены" checked={isolated} onChange={setIsolated} disabled={disabled}/>
|
||||
<Button variant="primary" disabled={disabled||!confirmed||!isolated} onClick={()=>void apply()}>Отправить команду BMS</Button>
|
||||
</SettingsCard>}
|
||||
{result&&<SettingsCard title="Результат команды BMS"><Description role="status">{result.state==='sent_unconfirmed'?'Команда отправлена. BMS не возвращает подтверждение выполнения.':'Итог команды неизвестен: связь прервалась.'} Автоматического повторения нет. Прочитайте батарею заново и проверьте её состояние.</Description><ResourceList aria-label="Адресат команды BMS"><li><ResourceRow title={`CAN ${result.target.can_id}`} description={result.target.uuid.toUpperCase()}/></li></ResourceList></SettingsCard>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import {useEffect,useRef,useState,type ChangeEvent} from 'react';
|
||||
import {Button,Checker,Description,ResourceList,ResourceRow,Select,SettingsCard,TextField} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {groupedParameters,groupLabel,parameterValue,type VescConfig} from './configuration';
|
||||
import {VescParameterEditor,initialDraft,parseDraft,type Drafts} from './VescParameterEditor';
|
||||
import {plainDescription,downloadText} from './editorFiles';
|
||||
|
||||
interface Snapshot {configuration:VescConfig;schema_sha256:string;pending:boolean}
|
||||
interface Preview {preview_id:string;changes:{name:string;title:string;before:unknown;after:unknown}[]}
|
||||
export function VescBmsConfiguration(props:ReadProps&{canId:number;count:number}){
|
||||
const [index,setIndex]=useState('0'),[value,setValue]=useState<Snapshot|null>(null),[group,setGroup]=useState('all'),[query,setQuery]=useState('');
|
||||
const [drafts,setDrafts]=useState<Drafts>({}),[editing,setEditing]=useState<string|null>(null),[description,setDescription]=useState<string|null>(null);
|
||||
const [preview,setPreview]=useState<Preview|null>(null),[confirmed,setConfirmed]=useState(false),[busy,setBusy]=useState(false),[result,setResult]=useState('');
|
||||
const running=useRef(false),mounted=useRef(true),file=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
const disabled=busy||props.blocked||!props.enabled||!props.device.online||!props.device.verified;
|
||||
const call=<T,>(name:string,p:Record<string,unknown>,timeout=60000)=>perform<T>(props.transport,props.device,'vesc.bms.configuration.'+name,p,timeout);
|
||||
const target={can_id:props.canId,index:Number(index)};
|
||||
function clear(){setPreview(null);setConfirmed(false);setResult('');}
|
||||
async function run(work:()=>Promise<void>){if(running.current||disabled)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);try{await work();}catch(e){if(mounted.current)props.failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}}
|
||||
async function read(){await run(async()=>{const v=await call<Snapshot>('read',target);if(mounted.current){setValue(v);setDrafts({});setEditing(null);clear();}});}
|
||||
async function prepare(source:Record<string,unknown>){if(!value)return;await run(async()=>{clear();const p=await call<Preview>('preview',{...target,baseline:value.configuration.packet_sha256,schema_sha256:value.schema_sha256,...source});if(mounted.current)setPreview(p);});}
|
||||
async function apply(){if(!preview||!confirmed)return;const id=preview.preview_id;await run(async()=>{clear();const r=await call<{verified:boolean;message?:string}>('apply',{preview_id:id,confirmed:true,inputs_isolated:true},120000);if(mounted.current){setValue(v=>v?{...v,pending:!r.verified}:null);setResult(r.verified?'Параметры записаны и проверены повторным чтением. Прочитайте новую конфигурацию.':r.message??'Итог записи неизвестен.');setDrafts({});}});}
|
||||
async function recover(restore:boolean){await run(async()=>{clear();if(restore){const p=await call<Preview>('restore',target);if(mounted.current)setPreview(p);}else{const r=await call<{verified:boolean;outcome:string}>('reconcile',target);if(mounted.current){setValue(v=>v?{...v,pending:!r.verified}:null);setResult(r.verified?'Итог записи подтверждён.':'Значения отличаются от исходных и ожидаемых. Можно восстановить исходную копию.');}}});}
|
||||
async function importXml(event:ChangeEvent<HTMLInputElement>){const f=event.target.files?.[0];event.target.value='';if(!f)return;try{if(f.size>32768)throw new Error('XML превышает 32 КБ.');await prepare({xml:await f.text()});}catch(e){props.failure(e);}}
|
||||
const config=value?.configuration,parameters=config?groupedParameters(config,group,query):[];
|
||||
const changes=Object.entries(drafts).flatMap(([name,draft])=>{const p=config?.parameters.find(p=>p.name===name);return p?[{name,...parseDraft(p,draft)}]:[];});
|
||||
return <>
|
||||
<SettingsCard title="Расширенные настройки BMS" description="Группы, типы, единицы и допустимые значения предоставляет прошивка выбранной BMS. Заводские значения сначала показываются для сравнения.">
|
||||
{props.count>1&&<Select label="Конфигурация BMS" value={index} options={Array.from({length:Math.min(props.count,8)},(_,i)=>({value:String(i),label:`Конфигурация ${i+1}`}))} disabled={disabled} onChange={v=>{setIndex(v);setValue(null);setDrafts({});clear();}}/>}
|
||||
<Button disabled={disabled} loading={busy} onClick={()=>void read()}>Прочитать настройки BMS</Button>
|
||||
{value?.pending&&<><Description>Результат предыдущей записи не подтверждён. При смене CAN-адреса выберите новый адрес этой BMS.</Description><Button disabled={disabled} onClick={()=>void recover(false)}>Проверить запись BMS</Button><Button disabled={disabled} onClick={()=>void recover(true)}>Сравнить с исходной копией</Button></>}
|
||||
{config&&<>
|
||||
<Select label="Группа BMS" value={group} options={[{value:'all',label:'Все группы'},...config.groups.map(g=>({value:g.name,label:groupLabel(g.name)}))]} onChange={setGroup}/>
|
||||
<TextField label="Поиск параметра BMS" value={query} onChange={e=>setQuery(e.target.value)}/>
|
||||
<ResourceList aria-label="Параметры BMS">{parameters.map(p=><li key={p.name}><ResourceRow title={p.title||p.name} description={`${p.name} · ${parameterValue(p)}`} actions={<>{p.transmittable&&p.type!=='undefined'&&<Button disabled={disabled||value.pending} onClick={()=>{clear();setEditing(editing===p.name?null:p.name);}}>Изменить</Button>}{p.description&&<Button variant="ghost" onClick={()=>setDescription(description===p.name?null:p.name)}>Описание</Button>}</>}/>
|
||||
{editing===p.name&&<VescParameterEditor parameter={p} value={drafts[p.name]??initialDraft(p)} disabled={disabled||value.pending} onChange={v=>{clear();setDrafts(old=>({...old,[p.name]:v}));}}/>}
|
||||
{description===p.name&&<Description>{plainDescription(p.description)}</Description>}
|
||||
</li>)}</ResourceList>
|
||||
{!parameters.length&&<Description>Параметры не найдены.</Description>}
|
||||
<Button onClick={()=>downloadText(`bms-${props.canId}-${index}.xml`,config.xml,'application/xml')}>Скачать XML BMS</Button>
|
||||
<input hidden type="file" accept=".xml" ref={file} onChange={e=>void importXml(e)}/><Button disabled={disabled||value.pending} onClick={()=>file.current?.click()}>Импортировать XML BMS</Button>
|
||||
<Button disabled={disabled||value.pending} onClick={()=>void prepare({defaults:true})}>Сравнить с заводскими значениями</Button>
|
||||
{changes.length>0&&<Button disabled={disabled||value.pending||changes.some(c=>c.error!==null)} onClick={()=>void prepare({changes:Object.fromEntries(changes.map(c=>[c.name,c.value]))})}>Сравнить изменения BMS ({changes.length})</Button>}
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{preview&&<SettingsCard title="Сравнение параметров BMS" description="Исходная копия сохраняется перед записью. CAN-адрес и скорость CAN могут повлиять на связь после записи.">
|
||||
<ResourceList aria-label="Изменения BMS">{preview.changes.map(c=><li key={c.name}><ResourceRow title={c.title||c.name} description={`${String(c.before)} → ${String(c.after)}`}/></li>)}</ResourceList>
|
||||
{!preview.changes.length?<Description>Изменений нет.</Description>:<><Checker label="Подтверждаю изменения; зарядка, нагрузка и входы управления отключены" checked={confirmed} onChange={setConfirmed} disabled={disabled}/><Button variant="primary" disabled={disabled||!confirmed} onClick={()=>void apply()}>Записать настройки BMS</Button></>}
|
||||
</SettingsCard>}
|
||||
{result&&<SettingsCard title="Результат настройки BMS"><Description role="status">{result}</Description></SettingsCard>}
|
||||
</>;
|
||||
}
|
||||
@@ -1,14 +1,19 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useRef,useState} from 'react';
|
||||
import {Button,InspectorSelectField,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {SensorBoardSettingsProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import {perform,type Sensor} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import {drivePositions,vescStatus,type DriveProfile} from './model';
|
||||
import {VescControlTransport} from './VescControlTransport';
|
||||
import type {ControlTransportProfile} from './controlTransport';
|
||||
import {VescLimits} from './VescLimits';
|
||||
|
||||
export function VescBoardSettings({inventory,transport,enabled,refresh,failure,openDevice}:SensorBoardSettingsProps){
|
||||
const controllers=inventory?.items.filter(device=>device.kind==='vesc.controller')??[];
|
||||
const profile=controllers.map(device=>vescStatus(device).drive_profile).filter((value):value is DriveProfile=>!!value).sort((a,b)=>b.revision-a.revision)[0];
|
||||
const anchor=controllers.find(device=>device.online&&device.verified&&vescStatus(device).board_settings_supported);
|
||||
const transportAnchor=controllers.find(device=>!!vescStatus(device).control_transport);
|
||||
const controlStatus=transportAnchor?vescStatus(transportAnchor):null;
|
||||
const [busy,setBusy]=useState(false);const running=useRef(false);
|
||||
const active=inventory?.operations?.some(value=>['queued','running'].includes(value.state)&&controllers.some(device=>device.id===value.device_id));
|
||||
const blocked=!enabled||!anchor||busy||active||!profile;
|
||||
@@ -26,10 +31,10 @@ export function VescBoardSettings({inventory,transport,enabled,refresh,failure,o
|
||||
{value:'1x1',label:'1×1 · 2 мотора',disabled:!!profile?.bindings['left.2']||!!profile?.bindings['right.2']},
|
||||
{value:'2x2',label:'2×2 · 4 мотора'},
|
||||
]} onChange={layout=>{if(anchor)void change(anchor,'vesc.drive.layout',{layout});}}/>
|
||||
{!profile&&<p>{inventory?'Подключите VESC, чтобы получить профиль привода с борта.':'Получение профиля привода…'}</p>}
|
||||
{profile&&!anchor&&<p>Профиль показан по последним сведениям с борта. Для изменения нужна связь с VESC и актуальное бортовое приложение.</p>}
|
||||
{!profile&&<Description>{inventory?'Подключите VESC, чтобы получить профиль привода с борта.':'Получение профиля привода…'}</Description>}
|
||||
{profile&&!anchor&&<Description>Профиль показан по последним сведениям с борта. Для изменения нужна связь с VESC и актуальное бортовое приложение.</Description>}
|
||||
{profile?.layout&&<>
|
||||
<p>Стороны — по направлению движения вперёд. Назначения сохраняются автоматически и остаются с контроллером при смене USB-порта.</p>
|
||||
<Description>Стороны — по направлению движения вперёд. Назначения сохраняются автоматически и остаются с контроллером при смене USB-порта.</Description>
|
||||
{Object.entries(positions).map(([slot,label])=>{
|
||||
const bound=profile.bindings[slot];
|
||||
const missing=bound&&!controllers.some(device=>device.id===bound.device_id);
|
||||
@@ -49,6 +54,13 @@ export function VescBoardSettings({inventory,transport,enabled,refresh,failure,o
|
||||
})}</ResourceList>
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{profile&&controlStatus?.control_transport&&transportAnchor&&<VescControlTransport drive={profile} profile={controlStatus.control_transport}
|
||||
adapters={controlStatus.control_adapters??[]} endpoints={controlStatus.control_endpoints??[]}
|
||||
enabled={enabled&&!busy} active={!!active||controllers.some(d=>!!vescStatus(d).test_active)} failure={failure}
|
||||
save={async parameters=>{
|
||||
const result=await perform<{control_transport:ControlTransportProfile}>(transport,transportAnchor,'vesc.transport.configure',parameters);
|
||||
await refresh();return result.control_transport;
|
||||
}}/>}
|
||||
<VescLimits controllers={controllers} transport={transport} enabled={enabled&&!busy&&!active} failure={failure}/>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {useRef,useState} from 'react';
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Checker,ResourceList,ResourceRow,SettingsCard,TextField} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
@@ -9,11 +10,12 @@ interface CalibrationResult {
|
||||
native:{success?:boolean;code?:number;sensor_mode?:number;parameters?:Record<string,number>};
|
||||
}
|
||||
|
||||
export function VescCalibration({device,transport,enabled,refresh,failure,blocked,onBusyChange}:SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void}){
|
||||
export function VescCalibration({device,transport,enabled,refresh,failure,blocked,onBusyChange,active=true}:SensorDetailProps&{active?:boolean;blocked:boolean;onBusyChange:(busy:boolean)=>void}){
|
||||
const [loss,setLoss]=useState('50');
|
||||
const [confirmed,setConfirmed]=useState(false);
|
||||
const [busy,setBusy]=useState(false);
|
||||
const [result,setResult]=useState<CalibrationResult|null>(null);
|
||||
useEffect(()=>{if(!active)setConfirmed(false);},[active]);
|
||||
const running=useRef(false);
|
||||
const limits=vescStatus(device).foc_calibration;
|
||||
const power=Number(loss);
|
||||
@@ -37,16 +39,16 @@ export function VescCalibration({device,transport,enabled,refresh,failure,blocke
|
||||
const parameters=result?.native.parameters;
|
||||
const calibrated=result?.native.success===true&&result.configuration_verified;
|
||||
return <SettingsCard title="Калибровка мотора" description={`${device.name} · штатное автоопределение FOC в VESC Tool.`}>
|
||||
<p>Мастер измеряет сопротивление, индуктивность и магнитный поток, определяет датчики и записывает параметры выбранного мотора. Версии до и после сохраняются в истории; настройки аккумулятора и пульта сохраняются.</p>
|
||||
<Description>Мастер измеряет сопротивление, индуктивность и магнитный поток, определяет датчики и записывает параметры выбранного мотора. Версии до и после сохраняются в истории; настройки аккумулятора и пульта сохраняются.</Description>
|
||||
<TextField type="number" label="Допустимые потери в моторе, Вт" value={loss} onChange={event=>setLoss(event.target.value)} disabled={busy||blocked||!limits} min={limits?.min_power_loss_w} max={limits?.max_power_loss_w} step="5" aria-invalid={!valid} description="Параметр нагрева для мастера VESC Tool, не номинальная мощность мотора. По нему мастер выбирает токи измерения; предел тока проверки вращения здесь не применяется."/>
|
||||
<p>Мотор будет двигаться и разгоняться. На прошивке 5.02 процедуру нельзя прервать кнопкой или пультом — только отключением силового питания. Оставьте пульт выключенным и приводы вывешенными до завершения; цикл может занять до трёх минут.</p>
|
||||
<Description>Мотор будет двигаться и разгоняться. На прошивке 5.02 процедуру нельзя прервать кнопкой или пультом — только отключением силового питания. Оставьте пульт выключенным и приводы вывешенными до завершения; цикл может занять до трёх минут.</Description>
|
||||
<Checker checked={confirmed} onChange={setConfirmed} disabled={busy||blocked} label="Наблюдаю мотор, питание могу отключить"/>
|
||||
<Button disabled={!available||blocked||!confirmed||!valid||busy} loading={busy} onClick={()=>void calibrate()}>Откалибровать мотор</Button>
|
||||
{busy&&<p role="status">Подготовка и калибровка VESC Tool. Дождитесь результата и снятия тока.</p>}
|
||||
{busy&&<Description role="status">Подготовка и калибровка VESC Tool. Дождитесь результата и снятия тока.</Description>}
|
||||
{result&&<>
|
||||
<p role="status">{calibrated?'Параметры мотора измерены, записаны и проверены.':result.completed?`Калибровка не принята. Код VESC: ${result.native.code??'не получен'}.`:'Завершение калибровки не подтверждено. Проверьте состояние мотора и питание.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока пока не подтверждено. Перед следующей проверкой верните управление после нейтрали.'} {!result.configuration_verified&&' Проверка конфигурации не завершена; новое движение заблокировано.'}</p>
|
||||
<Description role="status">{calibrated?'Параметры мотора измерены, записаны и проверены.':result.completed?`Калибровка не принята. Код VESC: ${result.native.code??'не получен'}.`:'Завершение калибровки не подтверждено. Проверьте состояние мотора и питание.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока пока не подтверждено. Перед следующей проверкой верните управление после нейтрали.'} {!result.configuration_verified&&' Проверка конфигурации не завершена; новое движение заблокировано.'}</Description>
|
||||
{calibrated&&<>
|
||||
<p>{result.native.sensor_mode===0?'Выбран режим без датчиков. Холлы не определились; качество запуска нужно проверить вращением.':result.native.sensor_mode===2?'Определены датчики Холла.':'Определён энкодер.'}</p>
|
||||
<Description>{result.native.sensor_mode===0?'Выбран режим без датчиков. Холлы не определились; качество запуска нужно проверить вращением.':result.native.sensor_mode===2?'Определены датчики Холла.':'Определён энкодер.'}</Description>
|
||||
{parameters&&<ResourceList aria-label="Результат калибровки">
|
||||
{([['foc_motor_r','Сопротивление',1000,'мОм'],['foc_motor_l','Индуктивность',1e6,'мкГн'],['foc_motor_flux_linkage','Магнитный поток',1000,'мВб'],['l_current_max','Предел тока мотора',1,'А']] as const).map(([key,title,scale,unit])=><li key={key}><ResourceRow title={title} description={`${(parameters[key]*scale).toLocaleString('ru-RU',{maximumFractionDigits:3})} ${unit}`}/></li>)}
|
||||
</ResourceList>}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useState,useRef} from 'react';
|
||||
import {Button,Checker,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {useVescEditor} from './useVescEditor';
|
||||
|
||||
type Editor=ReturnType<typeof useVescEditor>;
|
||||
function value(v:number|string|boolean,scale:number,suffix:string){
|
||||
return typeof v==='number'?`${(v*(scale||1)).toLocaleString('ru-RU',{maximumSignificantDigits:9})} ${suffix}`:typeof v==='boolean'?(v?'Включено':'Выключено'):v;
|
||||
}
|
||||
export function VescChangeReview({editor,pending,blocked=false}:{editor:Editor;pending?:boolean;blocked?:boolean}){
|
||||
const [confirmed,setConfirmed]=useState(false);
|
||||
const review=useRef<HTMLDivElement>(null);
|
||||
useEffect(()=>setConfirmed(false),[editor.preview?.preview_id]);
|
||||
useEffect(()=>{if(editor.preview||editor.result)review.current?.scrollIntoView({block:'nearest'});},[editor.preview?.preview_id,editor.result]);
|
||||
if(!pending&&!editor.preview&&!editor.result)return null;
|
||||
return <div ref={review} className="sensor-content" role="region" aria-label="Сравнение и результат конфигурации">
|
||||
{pending&&<SettingsCard title="Проверить незавершённую запись" description="До проверки результата управление заблокировано. Повторное чтение не меняет контроллер.">
|
||||
<Button disabled={editor.busy||blocked||!editor.available} loading={editor.busy} onClick={()=>void editor.reconcile()}>Проверить результат записи</Button>
|
||||
</SettingsCard>}
|
||||
{editor.preview&&<SettingsCard title="Изменения перед записью" description={`VESC ${editor.preview.identity.uuid.toUpperCase()} · сравнение действует пять минут.`}>
|
||||
<ResourceList aria-label="Изменения конфигурации">{editor.preview.changes.map(c=><li key={`${c.kind}:${c.name}`}><ResourceRow title={c.title||c.name}
|
||||
description={`${c.kind==='motor'?'Мотор':'Входы'} · ${c.name}: ${value(c.before,c.editor_scale,c.suffix)} → ${value(c.after,c.editor_scale,c.suffix)}`}/></li>)}</ResourceList>
|
||||
{!editor.preview.changes.length?<Description>Параметры совпадают. Запись не требуется.</Description>:<>
|
||||
<Description>Изменения записываются в контроллер и влияют на работу привода. Перед записью выключите пульт и физически отключите другие источники команд. Все приводы должны быть вывешены и полностью остановлены. Исходная конфигурация сохраняется автоматически.</Description>
|
||||
<Checker checked={confirmed} onChange={setConfirmed} label="Входы отключены, приводы вывешены и остановлены" disabled={editor.busy}/>
|
||||
<Button variant="primary" disabled={!confirmed||editor.busy||blocked||!editor.available} loading={editor.busy} onClick={()=>{setConfirmed(false);void editor.apply();}}>Записать и проверить</Button>
|
||||
</>}
|
||||
<Button variant="ghost" disabled={editor.busy} onClick={editor.clear}>Отменить изменения</Button>
|
||||
</SettingsCard>}
|
||||
{editor.result&&<SettingsCard title={editor.result.verified?'Результат подтверждён':'Требуется проверка результата'}
|
||||
description={editor.result.message??(editor.result.outcome==='no_pending_write'?'Незавершённых записей нет.':editor.result.outcome==='unchanged'?'Конфигурация не изменилась.':'Параметры записаны и подтверждены повторным чтением. Прочитайте их заново перед следующим редактированием.')}>
|
||||
{editor.result.before_backup_id&&<Description>Исходная копия сохранена в истории конфигураций. Управление включается отдельно.</Description>}
|
||||
</SettingsCard>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import {useEffect,useRef,useState,type ChangeEvent} from 'react';
|
||||
import {Button,Checker,Description,ResourceList,ResourceRow,SettingsCard,TextAreaField,TextField} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {vescStatus} from './model';
|
||||
import {VescQmlPreview} from './VescQmlPreview';
|
||||
import {bytesBase64,downloadText,validateProject,type CodeProject} from './editorFiles';
|
||||
interface Preview {preview_id:string;kind?:string;bytes?:number;sha256?:string;erase?:boolean;command?:string;text?:string}
|
||||
interface Reading {project:CodeProject;bytes:number;sha256:string;pending:boolean;execution_pending:boolean}
|
||||
export function VescCodeTools(props:ReadProps&{kind:'lisp'|'qml';active?:boolean}){
|
||||
const {kind}=props,status=vescStatus(props.device),label=kind==='lisp'?'LispBM':'QML';
|
||||
const [project,setProject]=useState<CodeProject>({kind,source:'',imports:{},fullscreen:false}),[reading,setReading]=useState<Reading|null>(null);
|
||||
const [preview,setPreview]=useState<Preview|null>(null),[confirmed,setConfirmed]=useState(false),[busy,setBusy]=useState(false),[message,setMessage]=useState('');
|
||||
const [repl,setRepl]=useState(''),[output,setOutput]=useState(''),[stats,setStats]=useState<Record<string,unknown>|null>(null);
|
||||
const running=useRef(false),mounted=useRef(true),file=useRef<HTMLInputElement>(null),attachment=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
const supported=status.identity?.version==='6.00'&&status.identity.hardware_type===0&&status.identity.test_firmware===0&&status.engine?.contract?.methods.includes('code_read')===true;
|
||||
const available=props.enabled&&props.device.online&&props.device.verified&&supported;
|
||||
const disabled=busy||props.blocked,unavailable=disabled||!available;
|
||||
const call=<T,>(name:string,p:Record<string,unknown>={},timeout=60000)=>perform<T>(props.transport,props.device,'vesc.code.'+name,p,timeout);
|
||||
function clear(){setPreview(null);setConfirmed(false);setMessage('');}
|
||||
async function run(work:()=>Promise<void>){if(running.current||unavailable)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);try{await work();}catch(e){if(mounted.current)props.failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}}
|
||||
const read=(hardware=false)=>run(async()=>{clear();const v=await call<Reading>('read',{kind:hardware?'qml_hw':kind});if(mounted.current){setReading(v);setProject(v.project);setMessage(hardware?'Прочитан встроенный QML. Его можно сохранить или использовать как основу приложения.':'Код прочитан. Загрузка и запуск выполняются отдельно.');}});
|
||||
const prepare=()=>run(async()=>{
|
||||
clear();const checked=validateProject(project,kind),data=new TextEncoder().encode(JSON.stringify(checked));
|
||||
const sha256=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data))).map(v=>v.toString(16).padStart(2,'0')).join('');
|
||||
const upload=await call<{upload_id:string;chunk_bytes:number}>('begin',{kind,size:data.length,sha256});
|
||||
for(let at=0;at<data.length;at+=upload.chunk_bytes){const chunk=data.slice(at,at+upload.chunk_bytes),r=await call<{offset:number}>('chunk',{upload_id:upload.upload_id,offset:at,data:bytesBase64(chunk)});if(r.offset!==at+chunk.length)throw new Error('Передача проекта не подтверждена.');}
|
||||
const p=await call<Preview>('prepare',{upload_id:upload.upload_id});if(mounted.current)setPreview(p);
|
||||
});
|
||||
const prepareAction=(name:string,p:Record<string,unknown>)=>run(async()=>{clear();const v=await call<Preview>(name,p);if(mounted.current)setPreview(v);});
|
||||
const apply=()=>run(async()=>{if(!preview||!confirmed)return;const p=preview;clear();const r=await call<{verified?:boolean;outcome?:string;message?:string;acknowledged?:boolean;command?:string;output?:string}>(p.command?'control_apply':'apply',{preview_id:p.preview_id,confirmed:true,inputs_isolated:true},180000);if(mounted.current){if(r.output)setOutput(r.output);setMessage(r.message??(p.command?(r.acknowledged?'Смена состояния Lisp подтверждена.':'Команда REPL отправлена. Вывод относится только к этому запросу; завершение программы не подтверждается.'):r.verified?'Код записан и проверен. Запуск не выполнялся.':'Итог записи неизвестен.'));if(!p.command)setReading(v=>v?{...v,pending:!r.verified}:null);}await props.refresh();});
|
||||
const reconcile=()=>run(async()=>{clear();const v=await call<{verified:boolean;outcome:string}>('reconcile',{kind});if(mounted.current){setMessage(v.verified?'Содержимое подтверждено повторным чтением.':'Содержимое отличается от исходного и ожидаемого. Доступно восстановление копии.');setReading(r=>r?{...r,pending:!v.verified}:null);}await props.refresh();});
|
||||
async function open(event:ChangeEvent<HTMLInputElement>){const f=event.target.files?.[0];event.target.value='';if(!f)return;try{if(f.size>256*1024)throw new Error('Файл превышает 256 КБ.');const text=await f.text();const value=f.name.endsWith('.json')?validateProject(JSON.parse(text),kind):validateProject({kind,source:text,imports:{},fullscreen:false},kind);setProject(value);clear();}catch(e){props.failure(e);}}
|
||||
async function attach(event:ChangeEvent<HTMLInputElement>){const files=Array.from(event.target.files??[]);event.target.value='';try{const imports={...project.imports};for(const f of files){if(f.size>120*1024)throw new Error('Вложение слишком велико.');imports[f.name]=bytesBase64(new Uint8Array(await f.arrayBuffer()));}setProject(validateProject({...project,imports},kind));clear();}catch(e){props.failure(e);}}
|
||||
const pending=reading?.pending||status.code_pending;
|
||||
return <div className="sensor-content">
|
||||
<SettingsCard title={`${label} · редактор`} description={kind==='lisp'?'Исходный код и вложения LispBM. Запись во flash и запуск программы — отдельные действия.':'Исходный код интерфейса Qt Quick. Доступны чтение и запись QML приложения; встроенный QML читается отдельно.'}>
|
||||
{!supported&&<Description role="status">На этом контроллере прошивка {status.identity?.version??'не определена'}. Чтение и запись программ в памяти контроллера доступны для профиля VESC 6.00. Здесь можно открыть, отредактировать и сохранить проект.</Description>}
|
||||
<Button disabled={unavailable} loading={busy} onClick={()=>void read()}>Прочитать {label}</Button>
|
||||
{kind==='qml'&&<Button disabled={unavailable} onClick={()=>void read(true)}>Прочитать встроенный QML</Button>}
|
||||
<input hidden ref={file} type="file" accept={kind==='lisp'?'.lisp,.lbm,.json':'.qml,.json'} onChange={e=>void open(e)}/><Button disabled={disabled} onClick={()=>file.current?.click()}>Открыть файл или проект</Button>
|
||||
<TextAreaField label={`Исходный код ${label}`} value={project.source} rows={18} disabled={disabled} onChange={e=>{setProject(p=>({...p,source:e.target.value}));clear();}}/>
|
||||
{kind==='qml'&&<Checker label="Открывать QML на весь экран в VESC Tool" checked={project.fullscreen} onChange={fullscreen=>{setProject(p=>({...p,fullscreen}));clear();}} disabled={disabled}/>}
|
||||
{kind==='lisp'&&<><input ref={attachment} type="file" hidden multiple onChange={e=>void attach(e)}/><Button disabled={disabled} onClick={()=>attachment.current?.click()}>Добавить файлы import</Button><Description>В import укажите имя прикреплённого файла без пути к папке или ссылку pkg@ / pkg:: на библиотеку из сохранённого каталога расширений. Исходный код и вложения вместе — до 120 КБ.</Description>
|
||||
<ResourceList aria-label="Вложения Lisp">{Object.keys(project.imports).map(name=><li key={name}><ResourceRow title={name} actions={<Button disabled={disabled} onClick={()=>{setProject(p=>({...p,imports:Object.fromEntries(Object.entries(p.imports).filter(([key])=>key!==name))}));clear();}}>Убрать</Button>}/></li>)}</ResourceList></>}
|
||||
<Button disabled={disabled} onClick={()=>downloadText(`vesc-${kind}.${kind==='lisp'?'lisp':'qml'}`,project.source)}>Скачать исходный код</Button>
|
||||
<Button disabled={disabled} onClick={()=>{try{downloadText(`vesc-${kind}-project.json`,JSON.stringify(validateProject(project,kind),null,2),'application/json');}catch(e){props.failure(e);}}}>Скачать проект с вложениями</Button>
|
||||
<Button disabled={unavailable||pending||!project.source.trim()} onClick={()=>void prepare()}>Подготовить запись {label}</Button>
|
||||
<Button disabled={unavailable||pending} onClick={()=>void prepareAction('erase_prepare',{kind})}>Подготовить удаление {label}</Button>
|
||||
</SettingsCard>
|
||||
{kind==='qml'&&<VescQmlPreview {...props} source={project.source} active={props.active}/>}
|
||||
{pending&&<SettingsCard title="Проверка записи кода" description="Предыдущая запись не подтверждена. Автоматического повторения нет."><Button disabled={unavailable} onClick={()=>void reconcile()}>Проверить запись</Button><Button disabled={unavailable} onClick={()=>void prepareAction('restore',{kind})}>Подготовить восстановление копии</Button></SettingsCard>}
|
||||
{kind==='lisp'&&<SettingsCard title="LispBM · выполнение" description="Программа и REPL могут управлять выходами, включая мотор. Перед запуском отключите внешние входы и подготовьте безопасный стенд.">
|
||||
<Button disabled={unavailable||pending} onClick={()=>void prepareAction('control_prepare',{command:'start',text:''})}>Подготовить запуск Lisp</Button><Button disabled={unavailable} onClick={()=>void prepareAction('control_prepare',{command:'stop',text:''})}>Подготовить остановку Lisp</Button>
|
||||
<TextField label="Выражение REPL" value={repl} disabled={disabled} onChange={e=>{setRepl(e.target.value);clear();}}/>
|
||||
<Button disabled={unavailable||pending||!repl.trim()} onClick={()=>void prepareAction('control_prepare',{command:'repl',text:repl})}>Подготовить команду REPL</Button>
|
||||
<Button disabled={unavailable} onClick={()=>void run(async()=>{const v=await call<Record<string,unknown>>('stats');if(mounted.current)setStats(v);})}>Прочитать статистику Lisp</Button>
|
||||
{stats&&<ResourceList aria-label="Статистика Lisp">{[['cpu_use','CPU, %'],['heap_use','Куча, %'],['mem_use','Память, %'],['stack_use','Стек, %'],['done_ctx_r','Результат завершённого контекста']].map(([key,title])=><li key={key}><ResourceRow title={title} description={String(stats[key]??'—')}/></li>)}</ResourceList>}
|
||||
{output&&<TextAreaField label="Полученный вывод REPL" value={output} rows={8} readOnly/>}
|
||||
</SettingsCard>}
|
||||
{preview&&<SettingsCard title="Подтверждение операции" description="Подтверждение действует пять минут и привязано к этому контроллеру и сеансу.">
|
||||
<Description>{preview.command?(preview.command==='repl'?`REPL: ${preview.text}`:preview.command==='start'?'Запуск сохранённой программы Lisp.':'Остановка Lisp.'):(preview.erase?`Удаление ${label} из контроллера.`:`Запись ${label}: ${preview.bytes} байт. Исходная копия сохраняется автоматически. Lisp не запускается.`)}</Description>
|
||||
<Checker label="Подтверждаю операцию; внешние входы отключены, стенд подготовлен" checked={confirmed} onChange={setConfirmed} disabled={disabled}/><Button variant="primary" disabled={unavailable||!confirmed} onClick={()=>void apply()}>Выполнить подтверждённую операцию</Button>
|
||||
</SettingsCard>}
|
||||
{message&&<SettingsCard title="Результат"><Description role="status">{message}</Description></SettingsCard>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useMemo,useState,useRef,type ChangeEvent} from 'react';
|
||||
import {Button,ResourceList,ResourceRow,Select,SettingsCard,TextField} from '@nodedc/ui-react';
|
||||
import {VescChangeReview} from './VescChangeReview';
|
||||
import {useVescEditor} from './useVescEditor';
|
||||
import {VescParameterEditor,initialDraft,parseDraft,type Drafts} from './VescParameterEditor';
|
||||
import {vescStatus} from './model';
|
||||
import {useVescRead,type ReadProps} from './useVescRead';
|
||||
import {groupLabel,groupedParameters,parameterValue,type ConfigurationRead} from './configuration';
|
||||
|
||||
function plainDescription(value:string){
|
||||
const doc=new DOMParser().parseFromString(value,'text/html');
|
||||
doc.querySelectorAll('script,style,img,iframe').forEach(node=>node.remove());
|
||||
doc.querySelectorAll('br,p,li').forEach(node=>node.append(' '));
|
||||
return doc.body.textContent?.replace(/\s+/g,' ').trim()??'';
|
||||
}
|
||||
export function VescConfiguration(props:ReadProps&{active:boolean;kind:'motor'|'application'}){
|
||||
const {kind}=props,status=vescStatus(props.device);
|
||||
const editor=useVescEditor(props);
|
||||
const [drafts,setDrafts]=useState<Drafts>({}),[editing,setEditing]=useState<string|null>(null);
|
||||
const file=useRef<HTMLInputElement>(null);
|
||||
const {value,busy,available,read}=useVescRead<ConfigurationRead>(props,'vesc.configuration.read',status.configuration_read_supported===true);
|
||||
const [group,setGroup]=useState(''),[subgroup,setSubgroup]=useState(''),[query,setQuery]=useState(''),[description,setDescription]=useState<string|null>(null);
|
||||
useEffect(()=>{setDrafts({});setEditing(null);editor.clear();setGroup('');setSubgroup('');setQuery('');setDescription(null);},[kind]);
|
||||
const config=value?.configuration[kind];
|
||||
useEffect(()=>{setDrafts({});setEditing(null);editor.clear();},[value]);
|
||||
const changed=Object.entries(drafts).flatMap(([name,draft])=>{const p=config?.parameters.find(p=>p.name===name);return p?[{name,...parseDraft(p,draft)}]:[];});
|
||||
const working=busy||editor.busy;
|
||||
const baseline=value?{motor:value.configuration.motor.packet_sha256,application:value.configuration.application.packet_sha256}:null;
|
||||
async function importXml(event:ChangeEvent<HTMLInputElement>){
|
||||
const selected=event.target.files?.[0];event.target.value='';if(!selected||!baseline)return;
|
||||
try{if(selected.size>32768)throw new Error('XML превышает 32 КБ.');const xml=await selected.text();await editor.prepare({kind,baseline,xml});}
|
||||
catch(error){props.failure(error);}
|
||||
}
|
||||
|
||||
const currentGroup=config?.groups.find(item=>item.name===group)??config?.groups[0];
|
||||
const selectedGroup=group==='all'?'all':currentGroup?.name??'';
|
||||
const currentSubgroup=currentGroup?.subgroups.find(item=>item.name===subgroup)??currentGroup?.subgroups[0];
|
||||
const selectedSubgroup=subgroup==='all'?'all':currentSubgroup?.name??'';
|
||||
const parameters=useMemo(()=>config?groupedParameters(config,selectedGroup,query,selectedSubgroup):[],[config,selectedGroup,query,selectedSubgroup]);
|
||||
function download(){
|
||||
if(!config)return;
|
||||
const url=URL.createObjectURL(new Blob([config.xml],{type:'application/xml'}));
|
||||
const link=document.createElement('a');link.href=url;link.download=`vesc-${props.device.id}-${kind}.xml`;link.click();
|
||||
setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||||
}
|
||||
return <div className="sensor-content">
|
||||
<VescChangeReview editor={editor} pending={status.configuration_pending} blocked={props.blocked}/>
|
||||
<SettingsCard title={kind==='motor'?'Параметры мотора':'Входы и приложения'}
|
||||
description={value?`Прочитано ${new Date(value.observed_at).toLocaleString('ru-RU')}`:'Полная схема параметров VESC Tool для прошивки подключённого контроллера.'}
|
||||
actions={<Button disabled={!available||working||props.blocked} loading={busy} onClick={()=>void read()}>Прочитать параметры</Button>}>
|
||||
{!status.configuration_read_supported&&<Description>Для чтения полной конфигурации требуется обновление бортового приложения.</Description>}
|
||||
<div className="sensor-content">
|
||||
{!config&&<Description>Прочитайте конфигурацию, чтобы увидеть группы, значения, единицы и описания параметров.</Description>}
|
||||
{config&&<>
|
||||
<Select label="Группа параметров" value={selectedGroup} options={[{value:'all',label:'Все группы'},...config.groups.map(item=>({value:item.name,label:groupLabel(item.name)}))]} onChange={value=>{setGroup(value);setSubgroup('');setQuery('');}}/>
|
||||
{selectedGroup!=='all'&¤tGroup&&<Select label="Раздел параметров" value={selectedSubgroup} options={[{value:'all',label:'Все разделы группы'},...currentGroup.subgroups.map(item=>({value:item.name,label:groupLabel(item.name)}))]} onChange={value=>{setSubgroup(value);setQuery('');}}/>}
|
||||
<TextField label="Поиск по всем группам" placeholder="Название или имя параметра VESC" value={query} onChange={event=>setQuery(event.target.value)}/>
|
||||
<Description>{parameters.length} параметров. Значения относятся к указанному времени чтения.</Description>
|
||||
<ResourceList aria-label="Параметры VESC Tool">{parameters.map(parameter=><li key={parameter.name}>
|
||||
<ResourceRow title={<span className="vesc-parameter-title">{parameter.title||parameter.name}</span>}
|
||||
description={`${parameter.name} · ${parameterValue(parameter)}${parameter.transmittable?'':' · справочное значение схемы'}`}
|
||||
actions={<>{editor.available&¶meter.transmittable&¶meter.type!=='undefined'&&<Button disabled={working||props.blocked} onClick={()=>{editor.clear();setEditing(editing===parameter.name?null:parameter.name);}}>Изменить</Button>}{parameter.description?<Button variant="ghost" onClick={()=>setDescription(description===parameter.name?null:parameter.name)}>{description===parameter.name?'Скрыть описание':'Описание'}</Button>:null}</>}/>
|
||||
{editing===parameter.name&&<VescParameterEditor parameter={parameter} value={drafts[parameter.name]??initialDraft(parameter)} disabled={working||props.blocked} onChange={draft=>{editor.clear();setDrafts(old=>({...old,[parameter.name]:draft}));}}/>}
|
||||
{description===parameter.name&&<Description>{plainDescription(parameter.description)}</Description>}
|
||||
</li>)}</ResourceList>
|
||||
{!parameters.length&&<Description>Параметры не найдены.</Description>}
|
||||
<div className="sensor-actions"><Button onClick={download}>Скачать XML VESC Tool</Button>
|
||||
{editor.available&&<>
|
||||
<input ref={file} type="file" accept=".xml,application/xml,text/xml" hidden onChange={event=>void importXml(event)}/>
|
||||
<Button disabled={working||props.blocked} onClick={()=>file.current?.click()}>Импортировать XML</Button>
|
||||
</>}
|
||||
</div>
|
||||
{editor.available&&changed.length>0&&<><Description>Изменено параметров: {changed.length}. Сначала проверьте сравнение с контроллером.</Description>
|
||||
<div className="sensor-actions"><Button disabled={working||props.blocked||changed.some(c=>c.error!==null)} loading={editor.busy} onClick={()=>void editor.prepare({kind,baseline,changes:Object.fromEntries(changed.map(c=>[c.name,c.value]))})}>Сравнить изменения</Button>
|
||||
<Button disabled={working} variant="ghost" onClick={()=>{setDrafts({});editor.clear();}}>Сбросить черновик</Button></div>
|
||||
</>}
|
||||
|
||||
</>}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Description,InspectorSelectField,SettingsCard} from '@nodedc/ui-react';
|
||||
import {drivePositions,type DriveProfile} from './model';
|
||||
import {routeError,transportMode,type ControlAdapter,type ControlEndpoint,type ControlRoute,type ControlTransportProfile} from './controlTransport';
|
||||
|
||||
interface Props {
|
||||
drive:DriveProfile;profile:ControlTransportProfile;adapters:ControlAdapter[];endpoints:ControlEndpoint[];
|
||||
enabled:boolean;active:boolean;
|
||||
save:(parameters:{revision:number;drive_revision:number;routes:Record<string,ControlRoute>})=>Promise<ControlTransportProfile>;
|
||||
failure:(error:unknown)=>void;
|
||||
}
|
||||
const routeKey=(r:ControlRoute)=>r.kind==='usb'?'usb':JSON.stringify([r.adapter_id,r.channel,r.can_id,r.bitrate]);
|
||||
export function VescControlTransport({drive,profile,adapters,endpoints,enabled,active,save,failure}:Props){
|
||||
const [draft,setDraft]=useState(()=>structuredClone(profile.routes));
|
||||
const [base,setBase]=useState({revision:profile.revision,drive:drive.revision});
|
||||
const [dirty,setDirty]=useState(false),[busy,setBusy]=useState(false);
|
||||
const pending=useRef(false);
|
||||
const stale=base.revision!==profile.revision||base.drive!==drive.revision;
|
||||
const blocked=!enabled||active||busy||stale;
|
||||
const labels=drivePositions(drive.layout),bindings=Object.entries(drive.bindings);
|
||||
const available=(id:string)=>endpoints.filter(e=>e.device_id===id&&e.verified);
|
||||
const ready=(id:string,r:ControlRoute|undefined)=>!!r&&available(id).some(e=>routeKey(e.route)===routeKey(r));
|
||||
const allReady=bindings.length>0&&bindings.every(([,b])=>ready(b.device_id,draft[b.device_id]));
|
||||
const mode=Object.keys(draft).length?transportMode(draft):'none';
|
||||
const error=routeError(draft,drive);
|
||||
const profileKey=JSON.stringify(profile);
|
||||
useEffect(()=>{
|
||||
if(!dirty&&!pending.current&&profile.revision>=base.revision){setDraft(structuredClone(profile.routes));setBase({revision:profile.revision,drive:drive.revision});}
|
||||
},[profileKey,drive.revision,dirty]); // Availability can change without a saved-profile revision.
|
||||
function reload(){setDraft(structuredClone(profile.routes));setBase({revision:profile.revision,drive:drive.revision});setDirty(false);}
|
||||
async function apply(){
|
||||
if(blocked||error||!allReady||pending.current)return;
|
||||
pending.current=true;setBusy(true);failure(null);
|
||||
try{const ack=await save({revision:base.revision,drive_revision:base.drive,routes:draft});setDraft(structuredClone(ack.routes));setBase({revision:ack.revision,drive:base.drive});setDirty(false);}
|
||||
catch(e){failure(e);}finally{pending.current=false;setBusy(false);}
|
||||
}
|
||||
function title(r:ControlRoute){
|
||||
if(r.kind==='usb')return 'USB';
|
||||
const adapter=adapters.find(a=>a.id===r.adapter_id);
|
||||
return 'CAN'+(r.channel+1)+' · ID '+r.can_id+' · '+r.bitrate/1000+' кбит/с'+(adapters.length>1?' · '+(adapter?.label??'адаптер'):'');
|
||||
}
|
||||
return <SettingsCard title="Шина управления" description="Подключение моторов при управлении из центра наблюдения.">
|
||||
<div className="sensor-content">
|
||||
<InspectorSelectField label="Для всех моторов" value={mode} disabled={blocked} options={[
|
||||
{value:'none',label:'Недоступно',disabled:true},
|
||||
{value:'usb',label:'USB',disabled:!bindings.length||!bindings.every(([,b])=>available(b.device_id).some(e=>e.route.kind==='usb'))},
|
||||
{value:'can',label:'CAN',disabled:!bindings.length||!bindings.every(([,b])=>available(b.device_id).some(e=>e.route.kind==='can'))},
|
||||
{value:'mixed',label:'По моторам',disabled:true},
|
||||
]} onChange={value=>{
|
||||
if(value!=='usb'&&value!=='can')return;
|
||||
setDraft(Object.fromEntries(bindings.map(([,b])=>[b.device_id,available(b.device_id).find(e=>e.route.kind===value)!.route])));setDirty(true);
|
||||
}}/>
|
||||
{bindings.map(([slot,b])=>{
|
||||
const route=draft[b.device_id],choices=available(b.device_id);
|
||||
const current=route?routeKey(route):'';
|
||||
return <SettingsCard key={b.device_id} title={labels[slot]??slot} description={'VESC '+b.uuid.slice(0,6).toUpperCase()}>
|
||||
<InspectorSelectField label="Соединение" value={current} disabled={blocked} options={[
|
||||
{value:'',label:'Недоступно',disabled:true},
|
||||
...choices.map(e=>({value:routeKey(e.route),label:title(e.route)})),
|
||||
...(route&&!ready(b.device_id,route)?[{value:current,label:title(route)+' · недоступно',disabled:true}]:[]),
|
||||
]} onChange={value=>{
|
||||
const selected=choices.find(e=>routeKey(e.route)===value);if(!selected)return;
|
||||
setDraft(v=>({...v,[b.device_id]:selected.route}));setDirty(true);
|
||||
}}/>
|
||||
</SettingsCard>;
|
||||
})}
|
||||
<Description>Доступность CAN подтверждается ответом назначенного VESC. При обрыве выбранной связи текущий сеанс управления завершается. Смена шины применяется после сохранения.</Description>
|
||||
{active&&<Description>Завершите управление перед сменой шины.</Description>}
|
||||
{!allReady&&<Description>Один или несколько моторов недоступны по выбранному соединению.</Description>}
|
||||
{stale?<Button disabled={busy} onClick={reload}>Обновить профиль</Button>:<Button disabled={blocked||!!error||!allReady} loading={busy} onClick={()=>void apply()}>Сохранить выбор шины</Button>}
|
||||
</div>
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -1,13 +1,26 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,LoadingRegion,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {Button,LoadingRegion,ResourceList,ResourceRow,SettingsCard,StatusBadge,FeatureSettingsWindow} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import {vescLabel,vescStatus,type VescTelemetry} from './model';
|
||||
import {SensorGeneralSettings} from '../../../../packages/sensor-ui/src/SensorGeneralSettings';
|
||||
import {VescBackups} from './VescBackups';
|
||||
import {VescMotor} from './VescMotor';
|
||||
import {VescHall} from './VescHall';
|
||||
import {VescCalibration} from './VescCalibration';
|
||||
import {VescConfiguration} from './VescConfiguration';
|
||||
import {VescDiagnostics,VescConnections} from './VescDiagnostics';
|
||||
import './vesc.css';
|
||||
import {VescTools,VescTerminal} from './VescTools';
|
||||
import {VescFirmware} from './VescFirmware';
|
||||
import {VescLink} from './VescLink';
|
||||
import {VescPackages} from './VescPackages';
|
||||
import {VescSampleData} from './VescSampleData';
|
||||
import {VescCodeTools} from './VescCodeTools';
|
||||
import {VescBms} from './VescBms';
|
||||
import {VescTrends} from './VescTrends';
|
||||
import {VescLogAnalysis} from './VescLogAnalysis';
|
||||
|
||||
const fields=[['input_voltage_v','Напряжение питания','В'],['input_current_a','Ток питания','А'],
|
||||
['motor_current_a','Ток мотора','А'],['erpm','Электрические обороты','ERPM'],['duty','Заполнение PWM',''],
|
||||
@@ -21,11 +34,15 @@ export function VescDetail(props:SensorDetailProps){
|
||||
const [telemetry,setTelemetry]=useState<VescTelemetry|null>(status.telemetry);
|
||||
const [pending,setPending]=useState<string|null>(null);
|
||||
const [saved,setSaved]=useState<string|null>(null);
|
||||
const [section,setSection]=useState('general');
|
||||
const [motorBusy,setMotorBusy]=useState(false);
|
||||
const [hallBusy,setHallBusy]=useState(false);
|
||||
const [calibrationBusy,setCalibrationBusy]=useState(false);
|
||||
const [configBusy,setConfigBusy]=useState(false);
|
||||
const [diagnosticBusy,setDiagnosticBusy]=useState(false);
|
||||
const [linkBusy,setLinkBusy]=useState(false);
|
||||
const poweredBusy=motorBusy||hallBusy||calibrationBusy||linkBusy;
|
||||
const [generalBusy,setGeneralBusy]=useState(false);
|
||||
const poweredBusy=generalBusy||motorBusy||hallBusy||calibrationBusy||linkBusy||configBusy||diagnosticBusy;
|
||||
const running=useRef(false);const mounted=useRef(true);
|
||||
const available=enabled&&device.online&&device.verified&&status.readable;
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
@@ -44,37 +61,97 @@ export function VescDetail(props:SensorDetailProps){
|
||||
finally{running.current=false;if(mounted.current)setPending(null);}
|
||||
}
|
||||
const backupAt=saved??status.backup?.observed_at;
|
||||
return <div className="sensor-content">
|
||||
<div><Button onClick={back}>К устройствам</Button></div>
|
||||
<SettingsCard title={`${device.name} · Настройка VESC`} description={`${device.model} · ${device.connection_label??'USB'}`}
|
||||
actions={<StatusBadge tone={label.tone}>{label.label}</StatusBadge>}>
|
||||
{!enabled||!device.online?<p>Нет свежей связи с контроллером.</p>:status.message?<p>{status.message}</p>:null}
|
||||
{status.identity?<ResourceList aria-label="Контроллер VESC">
|
||||
<li><ResourceRow title="Прошивка" description={status.identity.version}/></li>
|
||||
<li><ResourceRow title="Аппаратная версия" description={status.identity.hardware}/></li>
|
||||
<li><ResourceRow title="UUID" description={status.identity.uuid.toUpperCase()}/></li>
|
||||
{status.identity.test_firmware!==null&&status.identity.test_firmware>0&&<li><ResourceRow title="Тестовая прошивка" description={String(status.identity.test_firmware)}/></li>}
|
||||
</ResourceList>:<p>Аппаратный идентификатор ещё не подтверждён.</p>}
|
||||
</SettingsCard>
|
||||
const busy=poweredBusy||pending!==null;
|
||||
const sections=[
|
||||
{id:'general',label:'Общие данные',group:'Устройство'},
|
||||
{id:'overview',label:'Контроллер и прошивка',group:'Устройство'},
|
||||
{id:'diagnostics',label:'Текущие показания',group:'Устройство'},
|
||||
{id:'trends',label:'Графики и CSV',group:'Устройство'},
|
||||
{id:'hardware',label:'USB и журнал ошибок',group:'Устройство'},
|
||||
{id:'connections',label:'CAN и приёмник',group:'Устройство'},
|
||||
{id:'samples',label:'Sample Data',group:'Диагностика'},
|
||||
{id:'motor-parameters',label:'Мотор',group:'Параметры VESC Tool'},
|
||||
{id:'application-parameters',label:'Входы и приложения',group:'Параметры VESC Tool'},
|
||||
{id:'calibration',label:'Калибровка FOC',group:'Настройка мотора'},
|
||||
{id:'hall',label:'Датчики Холла',group:'Настройка мотора'},
|
||||
{id:'rotation',label:'Проверка вращения',group:'Настройка мотора'},
|
||||
{id:'configuration',label:'Резервные копии',group:'Конфигурации'},
|
||||
{id:'firmware',label:'Прошивка и загрузчик',group:'Конфигурации'},
|
||||
{id:'bms',label:'Аккумулятор BMS',group:'Инструменты'},
|
||||
{id:'peripherals',label:'Входы и IMU',group:'Инструменты'},
|
||||
{id:'log-analysis',label:'Анализ журналов и FFT',group:'Инструменты'},
|
||||
{id:'terminal',label:'Терминал диагностики',group:'Инструменты'},
|
||||
{id:'packages',label:'Расширения',group:'Программирование'},
|
||||
{id:'lisp',label:'LispBM',group:'Программирование'},
|
||||
{id:'qml',label:'QML-интерфейс',group:'Программирование'},
|
||||
].map(item=>({...item,disabled:busy&&item.id!==section}));
|
||||
return <FeatureSettingsWindow open title="Настройка VESC" subtitle={device.connection_label??device.name}
|
||||
identity={{title:device.name,subtitle:device.model,avatarLabel:'VESC'}}
|
||||
sections={sections} activeSection={section} onSectionChange={value=>{if(!busy)setSection(value);}}
|
||||
onClose={()=>{if(!busy)back();}} headerActions={<StatusBadge tone={label.tone}>{label.label}</StatusBadge>}>
|
||||
<div className="sensor-content">
|
||||
{!enabled||!device.online?<Description role="status">Нет свежей связи с контроллером. Показаны последние полученные сведения.</Description>:status.message?<Description role="status">{status.message}</Description>:null}
|
||||
{section==='general'&&<SensorGeneralSettings {...props} blocked={motorBusy||hallBusy||calibrationBusy||configBusy||diagnosticBusy||linkBusy||pending!==null} onBusyChange={setGeneralBusy}/>}
|
||||
<div hidden={section!=='overview'}><div className="sensor-content">
|
||||
<SettingsCard title="О контроллере" description="Идентификация VESC и его прошивки. Эти сведения читаются по USB; разбирать корпус не требуется.">
|
||||
{status.identity?<ResourceList aria-label="Контроллер VESC">
|
||||
<li><ResourceRow title="Прошивка" description={status.identity.version}/></li>
|
||||
<li><ResourceRow title="Аппаратная конфигурация" description={status.identity.hardware}/></li>
|
||||
<li><ResourceRow title="UUID микроконтроллера" description={status.identity.uuid.toUpperCase()}/></li>
|
||||
{status.identity.test_firmware!==null&&status.identity.test_firmware>0&&<li><ResourceRow title="Тестовая прошивка" description={String(status.identity.test_firmware)}/></li>}
|
||||
</ResourceList>:<Description>Аппаратный идентификатор ещё не подтверждён.</Description>}
|
||||
<Description>Аппаратная конфигурация — название платформы в прошивке. Она не подтверждает производителя и точную модель платы. UUID позволяет узнавать этот контроллер после смены USB-порта; это идентификатор процессора, а не заводской серийный номер платы.</Description>
|
||||
</SettingsCard>
|
||||
{status.engine&&<SettingsCard title="Ядро VESC Tool">
|
||||
<ResourceList aria-label="Версия VESC Tool"><li><ResourceRow title="Версия" description={status.engine.version}/></li>
|
||||
<li><ResourceRow title="Ревизия исходного кода" description={status.engine.commit.slice(0,12)}/></li>
|
||||
{status.engine.contract&&<li><ResourceRow title="Проверенные версии прошивок" description={status.engine.contract.firmware_profiles.map(item=>`${item.major}.${String(item.minor).padStart(2,'0')}`).join(', ')}/></li>}
|
||||
</ResourceList>
|
||||
<Description>Ядро обновляется вместе с бортовым приложением. Его обновление не перепрошивает контроллеры.</Description>
|
||||
</SettingsCard>}
|
||||
<SettingsCard title="Работа с VESC">
|
||||
<Description>В разделе «Устройство» находятся показания, ошибки и связь. «Параметры VESC Tool» содержит настройки мотора и входов из схемы установленной прошивки. Калибровка и проверка вращения выделены отдельно: они подают ток на мотор. Резервные копии сохраняют конфигурацию перед изменениями.</Description>
|
||||
</SettingsCard>
|
||||
</div></div>
|
||||
<div hidden={section!=='diagnostics'}><div className="sensor-content">
|
||||
<SettingsCard title="Показания контроллера" description={telemetry?`Снимок: ${new Date(telemetry.observed_at).toLocaleString()}`:'Получите текущие значения и код ошибки.'}
|
||||
actions={<Button disabled={!available||pending!==null||poweredBusy} loading={pending==='vesc.telemetry.read'} onClick={()=>void read('vesc.telemetry.read')}>Обновить показания</Button>}>
|
||||
<LoadingRegion loading={pending==='vesc.telemetry.read'&&!telemetry} label="Чтение показаний VESC">
|
||||
{telemetry?<ResourceList aria-label="Показания VESC">{fields.map(([key,title,unit])=>{
|
||||
const value=telemetry.values[key];if(value===undefined)return null;
|
||||
return <li key={key}><ResourceRow title={title} description={typeof value==='boolean'?(value?'Активен':'Не активен'):`${Number(value).toLocaleString(undefined,{maximumFractionDigits:3})}${unit?' '+unit:''}`}/></li>;
|
||||
})}</ResourceList>:<p>Показания ещё не прочитаны.</p>}
|
||||
})}</ResourceList>:<Description>Показания ещё не прочитаны.</Description>}
|
||||
</LoadingRegion>
|
||||
<p>ERPM — электрические обороты. Обороты вала зависят от числа пар полюсов мотора.</p>
|
||||
<Description>ERPM — электрические обороты. Обороты вала зависят от числа пар полюсов мотора.</Description>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Резервная копия конфигурации" description="Сохраните текущие параметры мотора и входов новой версией."
|
||||
<VescLink {...props} blocked={motorBusy||hallBusy||calibrationBusy||configBusy||diagnosticBusy||pending!==null} onBusyChange={setLinkBusy}/>
|
||||
</div></div>
|
||||
<div hidden={section!=='configuration'}><div className="sensor-content">
|
||||
<SettingsCard title="Сохранить конфигурацию" description="Сохраните текущие параметры мотора и входов новой версией."
|
||||
actions={<Button disabled={!available||pending!==null||poweredBusy} loading={pending==='vesc.config.backup'} onClick={()=>void read('vesc.config.backup')}>Сохранить версию</Button>}>
|
||||
{backupAt&&<p>Последняя копия: {new Date(backupAt).toLocaleString()}</p>}
|
||||
<p>Копия привязана к UUID и прошивке. Версии до и после калибровки остаются в истории.</p>
|
||||
{backupAt&&<Description>Последняя копия: {new Date(backupAt).toLocaleString()}</Description>}
|
||||
<Description>Копия привязана к UUID и прошивке. Версии до и после калибровки остаются в истории.</Description>
|
||||
</SettingsCard>
|
||||
<VescLink {...props} blocked={motorBusy||hallBusy||calibrationBusy||pending!==null} onBusyChange={setLinkBusy}/>
|
||||
<VescCalibration {...props} blocked={linkBusy||motorBusy||hallBusy||pending!==null} onBusyChange={setCalibrationBusy}/>
|
||||
<VescHall {...props} blocked={linkBusy||motorBusy||calibrationBusy||pending!==null} onBusyChange={setHallBusy}/>
|
||||
<VescMotor {...props} blocked={linkBusy||hallBusy||calibrationBusy||pending!==null} onBusyChange={setMotorBusy}/>
|
||||
<VescBackups deviceId={device.id} archive={transport.configurationArchive} revision={backupAt??null}/>
|
||||
</div>;
|
||||
{section==='configuration'&&<VescBackups editorProps={{...props,blocked:motorBusy||hallBusy||calibrationBusy||linkBusy||diagnosticBusy||pending!==null,onBusyChange:setConfigBusy}} deviceId={device.id} archive={transport.configurationArchive} revision={backupAt??null}/>}
|
||||
</div></div>
|
||||
{section==='samples'&&<VescSampleData {...props} blocked={busy} onBusyChange={setConfigBusy}/>}
|
||||
<div hidden={section!=='trends'}><VescTrends {...props} active={section==='trends'}/></div>
|
||||
{section==='log-analysis'&&<VescLogAnalysis/>}
|
||||
{section==='packages'&&<VescPackages {...props} blocked={busy} onBusyChange={setConfigBusy}/>}
|
||||
<div hidden={section!=='lisp'}><VescCodeTools {...props} kind="lisp" blocked={busy} onBusyChange={setConfigBusy}/></div>
|
||||
<div hidden={section!=='qml'}><VescCodeTools {...props} kind="qml" active={section==='qml'} blocked={busy} onBusyChange={setConfigBusy}/></div>
|
||||
{section==='bms'&&<VescBms {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/>}
|
||||
{section==='peripherals'&&<VescTools {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/>}
|
||||
{section==='terminal'&&<VescTerminal {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/>}
|
||||
{section==='firmware'&&<VescFirmware {...props} blocked={busy} onBusyChange={setConfigBusy}/>}
|
||||
{section==='hardware'&&<VescDiagnostics {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/>}
|
||||
<div hidden={section!=='connections'}><VescConnections {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/></div>
|
||||
<div hidden={!section.endsWith('-parameters')}><VescConfiguration {...props}
|
||||
active={section.endsWith('-parameters')} kind={section==='application-parameters'?'application':'motor'}
|
||||
blocked={motorBusy||hallBusy||calibrationBusy||linkBusy||diagnosticBusy||pending!==null} onBusyChange={setConfigBusy}/></div>
|
||||
<div hidden={section!=='calibration'}><VescCalibration {...props} active={section==='calibration'} blocked={motorBusy||hallBusy||linkBusy||configBusy||diagnosticBusy||pending!==null} onBusyChange={setCalibrationBusy}/></div>
|
||||
<div hidden={section!=='hall'}><VescHall {...props} active={section==='hall'} blocked={motorBusy||calibrationBusy||linkBusy||configBusy||diagnosticBusy||pending!==null} onBusyChange={setHallBusy}/></div>
|
||||
<div hidden={section!=='rotation'}><VescMotor {...props} active={section==='rotation'} blocked={hallBusy||calibrationBusy||linkBusy||configBusy||diagnosticBusy||pending!==null} onBusyChange={setMotorBusy}/></div>
|
||||
</div>
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,ComparisonTable,Description,SettingsCard} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import {vescStatus} from './model';
|
||||
import {type ReadProps} from './useVescRead';
|
||||
import {compareDiagnostics,diagnosticExpired,diagnosticSnapshot,type DiagnosticRead,type DiagnosticSnapshot} from './diagnosticReview';
|
||||
|
||||
const number=(v:number|null)=>v===null?'Не сообщается':v.toLocaleString('ru-RU');
|
||||
const timestamp=(v:DiagnosticSnapshot)=>new Date(v.read.observed_at).toLocaleString('ru-RU');
|
||||
const faultFields:Record<string,string>={Motor:'Мотор',Current:'Ток, А','Current filtered':'Ток после фильтра, А',Voltage:'Напряжение, В','Gate drv voltage':'Питание драйвера, В',Duty:'Duty',RPM:'Обороты, ERPM',Tacho:'Тахометр','Cycles running':'Рабочие циклы','Comm step':'Шаг коммутации',Temperature:'Температура, °C'};
|
||||
const usbFields=[['port','USB-порт'],['tty','Последовательный порт'],['speed','Скорость USB'],['idVendor','USB VID'],['idProduct','USB PID'],['manufacturer','Производитель USB-интерфейса'],['product','USB-устройство'],['serial','Серийная строка USB']] as const;
|
||||
|
||||
export function VescDiagnosticReview(props:ReadProps){
|
||||
const {device,transport,enabled,failure,blocked,onBusyChange}=props;
|
||||
const status=vescStatus(device),supported=status.diagnostics_read_supported===true;
|
||||
const available=enabled&&device.online&&device.verified&&status.readable&&supported;
|
||||
const [current,setCurrent]=useState<DiagnosticSnapshot|null>(null),[baseline,setBaseline]=useState<DiagnosticSnapshot|null>(null);
|
||||
const [busy,setBusy]=useState(false),[raw,setRaw]=useState(false),[expired,setExpired]=useState(false);
|
||||
const mounted=useRef(true),running=useRef(false);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
useEffect(()=>{if(!current&&!baseline)return;const timer=setInterval(()=>{
|
||||
if(current&&diagnosticExpired(current)){setCurrent(null);setExpired(true);}
|
||||
if(baseline&&diagnosticExpired(baseline)){setBaseline(null);setExpired(true);}
|
||||
},1000);return()=>clearInterval(timer);},[current,baseline]);
|
||||
async function read(){
|
||||
if(running.current||blocked||!available)return;
|
||||
running.current=true;setBusy(true);onBusyChange(true);failure(null);
|
||||
try{
|
||||
const result=await perform<DiagnosticRead>(transport,device,'vesc.diagnostics.read',{},30000);
|
||||
if(result.device_id!==device.id||result.identity?.uuid.toLowerCase()!==status.identity?.uuid.toLowerCase())throw new Error('Ответ относится к другому контроллеру. Обновите подключение.');
|
||||
const next=diagnosticSnapshot(result,device.snapshot.context.session_id);
|
||||
if(mounted.current){setCurrent(next);setExpired(false);}
|
||||
}catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
const comparison=baseline&¤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 <div className="sensor-content">
|
||||
<SettingsCard title="Аппаратная диагностика" description="Состояние USB и ошибки, сохранённые прошивкой с момента её запуска. Чтение выполняется только по кнопке."
|
||||
actions={<Button disabled={!available||busy||blocked} loading={busy} onClick={()=>void read()}>Прочитать диагностику</Button>}>
|
||||
{!supported&&<Description>Для чтения аппаратной диагностики требуется обновление бортового приложения.</Description>}
|
||||
{!current&&<Description>{expired?'Снимки удалены из памяти по истечении срока.':'Диагностика ещё не прочитана.'} Команды hw_status и faults не запускают мотор.</Description>}
|
||||
{current&&<>
|
||||
<Description>Прочитано {timestamp(current)}. Ответ терминала завершается после паузы вывода: прошивка не передаёт признак полноты. Отсутствующие поля не считаются нулевыми.</Description>
|
||||
{!current.identityMatches&&<Description role="alert">UUID в тексте hw_status не совпал с идентификацией контроллера или отсутствует. Сравнение отключено.</Description>}
|
||||
<div className="sensor-actions"><Button disabled={busy||blocked||!current.identityMatches} onClick={()=>{if(!diagnosticExpired(current)){setBaseline(current);setExpired(false);}}}>Использовать как опорный</Button><Button disabled={busy||blocked} onClick={()=>{setCurrent(null);setBaseline(null);setRaw(false);setExpired(false);}}>Очистить снимки</Button><Button onClick={()=>setRaw(v=>!v)}>{raw?'Скрыть исходный ответ':'Показать исходный ответ'}</Button></div>
|
||||
<Description>В памяти окна остаются максимум два снимка на пять минут. Смена контроллера, USB-сеанса или закрытие раздела очищает их. Непрерывная запись не включается.</Description>
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{current&&<>
|
||||
<SettingsCard title="Состояние USB" description="Счётчики принадлежат текущему запуску микроконтроллера. USB configuration event сам по себе не означает неисправность кабеля.">
|
||||
<ComparisonTable density="compact" label="Счётчики диагностики" heading="Параметр" columns={columns} rows={[
|
||||
{id:'time',label:'Время чтения',cells:snapshots.map(timestamp)},
|
||||
{id:'config',label:'События USB',cells:snapshots.map(s=>number(s.configEvents))},
|
||||
{id:'timeouts',label:'Таймауты USB',cells:snapshots.map(s=>number(s.writeTimeouts))},
|
||||
{id:'offsets',label:'Смещения FOC',cells:snapshots.map(s=>s.offsets?.join(' · ')??'Не сообщается')},
|
||||
]}/>
|
||||
{!baseline?<Description>Для сравнения отметьте этот снимок как опорный, затем прочитайте диагностику ещё раз.</Description>:comparison?.reason?<Description role="status">{comparison.reason}</Description>:comparison&&<Description role="status">Изменение от опорного снимка: конфигурирования USB — {number(comparison.configEvents)}; таймауты записи — {number(comparison.writeTimeouts)}.</Description>}
|
||||
<Description>Рост счётчика подтверждает событие прошивки, но не определяет его физическую причину. Нулевая разность не исключает пропадание связи, перезапуск или подзаедание без ошибки.</Description>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Ошибки контроллера" description="Это сообщения faults с момента запуска прошивки; они могут относиться к уже завершившемуся событию.">
|
||||
<Description>{current.faults.state==='none'?'Прошивка сообщает: зарегистрированных ошибок с момента запуска нет.':current.faults.state==='unknown'?'Формат ответа не распознан. Откройте исходный ответ.':`В полученном ответе записей: ${current.faults.entries.length}.`}</Description>
|
||||
{current.faults.entries.map((entry,i)=><SettingsCard key={i} title={`${i+1} · ${entry.code}`}><ComparisonTable density="compact" label={`Запись ошибки ${i+1}`} heading="Параметр" columns={[{id:'value',label:'При ошибке'}]} rows={Object.entries(entry.fields).map(([key,value])=>({id:key,label:faultFields[key]??key,cells:[value]}))}/></SettingsCard>)}
|
||||
<Description>Отсутствие faults не подтверждает исправность двигателя, датчиков или проводки. Смещения токовых каналов без сопоставимого измерения не дают такого заключения.</Description>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="USB-подключение" description="Привязка к стороне ровера сохраняется по UUID микроконтроллера. Серийная строка USB может совпадать у разных VESC.">
|
||||
<ComparisonTable density="compact" label="Подключение VESC" heading="Параметр" columns={[{id:'value',label:'Последний снимок'}]} rows={[
|
||||
{id:'uuid',label:'UUID микроконтроллера',cells:[current.read.identity.uuid]},
|
||||
...usbFields.map(([key,label])=>({id:key,label,cells:[current.read.usb[key]??'Не сообщается']})),
|
||||
]}/>
|
||||
</SettingsCard>
|
||||
{raw&&Object.entries(current.read.reports).map(([name,report])=><SettingsCard key={name} title={name==='hw_status'?'Исходный hw_status':'Исходный faults'}><pre className="vesc-diagnostic-output">{report.text}</pre></SettingsCard>)}
|
||||
</>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {Button,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
|
||||
import {useVescRead,type ReadProps} from './useVescRead';
|
||||
|
||||
import {VescDiagnosticReview} from './VescDiagnosticReview';
|
||||
export function VescDiagnostics(props:ReadProps){
|
||||
const {device}=props;
|
||||
const binding=`${device.id}:${device.snapshot.context.session_id}:${device.online&&device.verified}`;
|
||||
return <VescDiagnosticReview key={binding} {...props}/>;
|
||||
}
|
||||
export function VescConnections(props:ReadProps){
|
||||
const input=useVescRead<{observed_at:string;input:{level:number;pulse_ms:number}}>(props,'vesc.input.read');
|
||||
const can=useVescRead<{observed_at:string;can_ids:number[];elapsed_s:number}>(props,'vesc.can.read');
|
||||
return <div className="sensor-content">
|
||||
<SettingsCard title="Вход приёмника PPM" description="Декодированный сигнал входа контроллера. Значение около нуля означает нейтраль; это снимок, а не проверка электрического подключения."
|
||||
actions={<Button disabled={!input.available||props.blocked||input.busy||can.busy} loading={input.busy} onClick={()=>void input.read()}>Прочитать PPM</Button>}>
|
||||
{input.value?<ResourceList aria-label="Приёмник VESC"><li><ResourceRow title="Уровень сигнала" description={input.value.input.level.toLocaleString('ru-RU')}/></li><li><ResourceRow title="Длительность импульса" description={`${input.value.input.pulse_ms.toLocaleString('ru-RU')} мс`}/></li><li><ResourceRow title="Время чтения" description={new Date(input.value.observed_at).toLocaleString('ru-RU')}/></li></ResourceList>:<Description>Сигнал ещё не прочитан.</Description>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Устройства на CAN" description="Поиск контроллеров, которые отвечают на CAN-запрос выбранного VESC. Отсутствие ответа само по себе не определяет причину неисправности шины."
|
||||
actions={<Button disabled={!can.available||props.blocked||input.busy||can.busy} loading={can.busy} onClick={()=>void can.read()}>Проверить CAN</Button>}>
|
||||
{can.value?<><Description role="status">{can.value.can_ids.length?`Ответили CAN ID: ${can.value.can_ids.join(', ')}`:'Другие контроллеры не ответили.'}</Description><Description>Проверено {new Date(can.value.observed_at).toLocaleString('ru-RU')}.</Description></>:<Description>Поиск ещё не выполнен.</Description>}
|
||||
</SettingsCard>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Checker,ProgressBar,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {vescStatus,type VescFirmwareState} from './model';
|
||||
|
||||
import {FirmwareDestination} from './FirmwareDestination';
|
||||
import type {CanFirmwareTarget,SwdTarget} from './firmwareFiles';
|
||||
import {firmwareFileError,firmwareVariant,type FirmwarePreview,type FirmwareCatalog} from './firmwareFiles';
|
||||
const labels:Record<string,string>={idle:'Загрузка не выполняется',not_started:'Запись не начиналась; исходные настройки подтверждены',uploading:'Запись контроллера',awaiting_identity:'Ожидается повторное определение контроллера',identified:'Контроллер определён после загрузки',unknown:'Итог записи не подтверждён'};
|
||||
const encode=(bytes:Uint8Array)=>btoa(Array.from(bytes,value=>String.fromCharCode(value)).join(''));
|
||||
export function VescFirmware(props:ReadProps){
|
||||
const {device,transport,enabled,failure}=props, status=vescStatus(device);
|
||||
const [mode,setMode]=useState('usb'),[canId,setCanId]=useState(''),[target,setTarget]=useState<CanFirmwareTarget|null>(null),[canOptions,setCanOptions]=useState<{value:string;label:string}[]>([]);
|
||||
const [swd,setSwd]=useState<SwdTarget>({target_code:1,pins:'default',address:0x08000000,flash_bytes:128*1024});
|
||||
const [source,setSource]=useState('file'),[catalog,setCatalog]=useState<FirmwareCatalog|null>(null),[imageId,setImageId]=useState('');
|
||||
const [withoutLimits,setWithoutLimits]=useState(false);
|
||||
const [kind,setKind]=useState('firmware'),[version,setVersion]=useState(status.identity?.version??'');
|
||||
const [preview,setPreview]=useState<FirmwarePreview|null>(null),[result,setResult]=useState<VescFirmwareState|null>(null);
|
||||
const [busy,setBusy]=useState(false),[uploading,setUploading]=useState(false),[progress,setProgress]=useState<number|null>(null);
|
||||
const [compatible,setCompatible]=useState(false),[isolated,setIsolated]=useState(false),[cancelling,setCancelling]=useState(false);
|
||||
const input=useRef<HTMLInputElement>(null),running=useRef(false),mounted=useRef(true);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
const remote=status.firmware_update??{state:'idle'};
|
||||
const state=uploading||remote.state==='uploading'?remote:result??remote;
|
||||
const active=uploading||remote.state==='uploading';
|
||||
const available=enabled&&device.online&&device.verified&&status.readable&&status.firmware_update_supported===true;
|
||||
const formats=status.engine?.contract?.firmware_formats??['bin'];
|
||||
const versions=status.engine?.contract?.firmware_profiles.map(p=>`${p.major}.${String(p.minor).padStart(2,'0')}`)??[];
|
||||
const disabled=!available||props.blocked||busy||active;
|
||||
const destinationReady=mode!=='can'||!!target;
|
||||
const hardware=mode==='can'?target?.hardware:status.identity?.hardware;
|
||||
const targetVersion=mode==='can'&&target?`${target.major}.${String(target.minor).padStart(2,'0')}`:status.identity?.version;
|
||||
const resetDestination=()=>{setPreview(null);setCompatible(false);setIsolated(false);setCatalog(null);setImageId('');};
|
||||
async function canRead(scan:boolean){if(disabled||running.current)return;running.current=true;setBusy(true);props.onBusyChange(true);failure(null);resetDestination();setTarget(null);
|
||||
try{if(scan){const v=await perform<{can_ids:number[]}>(transport,device,'vesc.can.read',{},30000);const options=v.can_ids.filter(id=>Number.isInteger(id)&&id>=0&&id<=253).map(id=>({value:String(id),label:`CAN ${id}`}));if(mounted.current){setCanOptions(options);setCanId(options[0]?.value??'');if(!options.length)failure(new Error('Устройства CAN не ответили.'));}}
|
||||
else{const v=await call<{target:CanFirmwareTarget}>('target',{can_id:Number(canId)});if(mounted.current)setTarget(v.target);}}
|
||||
catch(e){if(mounted.current)failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
const call=<T,>(name:string,p:Record<string,unknown>={},timeout=30000)=>perform<T>(transport,device,`vesc.firmware.${name}`,p,timeout);
|
||||
async function stage(file:File){
|
||||
if(running.current||disabled||!destinationReady)return;
|
||||
running.current=true;setBusy(true);props.onBusyChange(true);setPreview(null);setResult(null);setCompatible(false);setIsolated(false);setWithoutLimits(false);setProgress(0);failure(null);
|
||||
let transfer:string|null=null;
|
||||
try{
|
||||
const issue=firmwareFileError(file,kind,formats);if(issue)throw new Error(issue);
|
||||
const data=new Uint8Array(await file.arrayBuffer());
|
||||
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data)),v=>v.toString(16).padStart(2,'0')).join('');
|
||||
transfer=(await call<{transfer_id:string}>('begin',{name:file.name,bytes:data.length,sha256:digest,kind,
|
||||
hardware,target_version:mode==='swd'?status.identity?.version:kind==='bootloader'?targetVersion:version,...(mode==='can'?{can_id:Number(canId),target}:{}),...(mode==='swd'?{swd}:{})})).transfer_id;
|
||||
for(let offset=0;offset<data.length;offset+=32768){
|
||||
if(!mounted.current)throw new Error('Подготовка файла остановлена.');
|
||||
const chunk=data.subarray(offset,offset+32768);
|
||||
await call('chunk',{transfer_id:transfer,offset,data:encode(chunk)});
|
||||
if(mounted.current)setProgress((offset+chunk.length)/data.length);
|
||||
}
|
||||
const value=await call<FirmwarePreview>('seal',{transfer_id:transfer});
|
||||
if(mounted.current)setPreview(value);
|
||||
}catch(error){
|
||||
if(mounted.current)failure(error);
|
||||
if(transfer)try{await call('discard',{transfer_id:transfer});}catch{/* Expires without a write. */}
|
||||
}finally{running.current=false;props.onBusyChange(false);if(mounted.current){setBusy(false);setProgress(null);}}
|
||||
}
|
||||
async function readCatalog(){
|
||||
if(running.current||disabled)return;
|
||||
running.current=true;setBusy(true);props.onBusyChange(true);failure(null);
|
||||
try{const value=await call<FirmwareCatalog>('catalog',mode==='can'?{can_id:Number(canId)}:{});if(mounted.current){setCatalog(value);setImageId(value.items.find(i=>i.hardware_limits)?.id??value.items[0]?.id??'');}}
|
||||
catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
async function prepareCatalog(){
|
||||
if(running.current||disabled||!imageId)return;
|
||||
running.current=true;setBusy(true);props.onBusyChange(true);failure(null);setPreview(null);setCompatible(false);setIsolated(false);setWithoutLimits(false);
|
||||
try{const value=await call<FirmwarePreview>('catalog_prepare',{image_id:imageId,...(mode==='can'?{can_id:Number(canId)}:{})});if(mounted.current){setKind('firmware');setPreview(value);}}
|
||||
catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
async function discard(){
|
||||
if(!preview||running.current||disabled)return;
|
||||
running.current=true;setBusy(true);props.onBusyChange(true);failure(null);
|
||||
try{
|
||||
await call('discard',{transfer_id:preview.transfer_id});
|
||||
if(mounted.current){setPreview(null);setCompatible(false);setIsolated(false);}
|
||||
}catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
async function apply(){
|
||||
if(!preview||!compatible||!isolated||(preview.image.hardware_limits===false&&!withoutLimits)||running.current||disabled)return;
|
||||
running.current=true;setUploading(true);setResult(null);failure(null);
|
||||
const id=preview.transfer_id;setPreview(null);setCompatible(false);setIsolated(false);
|
||||
try{
|
||||
const value=await call<VescFirmwareState>('apply',{transfer_id:id,rig_clear:true,inputs_isolated:true,compatible_image_confirmed:true,...(preview.image.swd?{swd_target_confirmed:true}:{}),...(preview.image.hardware_limits===false?{hardware_limits_removed_confirmed:withoutLimits}:{})},300000);
|
||||
if(mounted.current)setResult(value);
|
||||
}catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;if(mounted.current){setUploading(false);await props.refresh();}}
|
||||
}
|
||||
async function downloadBackup(){
|
||||
if(!state.operation_id||busy||active)return;
|
||||
setBusy(true);failure(null);
|
||||
try{const value=await call<{backup:unknown}>('backup',{operation_id:state.operation_id});const url=URL.createObjectURL(new Blob([JSON.stringify(value.backup,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=`vesc-backup-${state.before_backup_id}.json`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
|
||||
catch(error){if(mounted.current)failure(error);}finally{if(mounted.current)setBusy(false);}
|
||||
}
|
||||
async function reconcile(){
|
||||
if(running.current||!enabled||!device.verified)return;
|
||||
running.current=true;setBusy(true);failure(null);
|
||||
try{const value=await call<VescFirmwareState>('reconcile');if(mounted.current){setResult(value);await props.refresh();}}
|
||||
catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;if(mounted.current)setBusy(false);}
|
||||
}
|
||||
async function cancel(){
|
||||
if(!state.operation_id||cancelling)return;
|
||||
setCancelling(true);failure(null);
|
||||
try{await call('cancel',{operation_id:state.operation_id});}
|
||||
catch(error){if(mounted.current)failure(error);}
|
||||
finally{if(mounted.current)setCancelling(false);}
|
||||
}
|
||||
return <div className="sensor-content">
|
||||
<FirmwareDestination mode={mode} onMode={v=>{setMode(v);setSource('file');setKind('firmware');setTarget(null);resetDestination();}} disabled={disabled} targets={status.engine?.contract?.firmware_targets??['usb']}
|
||||
options={canOptions} canId={canId} onCanId={v=>{setCanId(v);setTarget(null);resetDestination();}} scan={()=>void canRead(true)} read={()=>void canRead(false)} target={target} swd={swd} onSwd={v=>{setSwd(v);resetDestination();}}/>
|
||||
<SettingsCard title="Прошивка и загрузчик" description="Загрузка выбранного файла в указанное устройство. Конфигурация сохраняется перед записью; повторная запись после обрыва связи выполняется только по новой команде.">
|
||||
{!status.firmware_update_supported&&<Description>Для загрузки прошивки требуется обновление бортового приложения.</Description>}
|
||||
<Select label="Источник образа" value={source} options={[{value:'file',label:formats.includes('hex')?'Файл BIN / HEX':'Файл BIN'},...(formats.includes('hex')&&mode!=='swd'?[{value:'catalog',label:'Архив VESC'}]:[])]} disabled={disabled} onChange={value=>{setSource(value);setPreview(null);setCompatible(false);setIsolated(false);setWithoutLimits(false);}}/>
|
||||
{source==='catalog'?<>
|
||||
<Description>Официальный архив входит в бортовое приложение. Показаны образы для аппаратной конфигурации этого контроллера и версий, поддерживаемых установленным ядром. Архивные версии выбирают для восстановления или конкретной задачи.</Description>
|
||||
<Button disabled={disabled||!destinationReady} loading={busy} onClick={()=>void readCatalog()}>Открыть архив для контроллера</Button>
|
||||
{catalog&&<>
|
||||
{catalog.items.length?<><Select label="Образ из архива" value={imageId} options={catalog.items.map(i=>({value:i.id,label:firmwareVariant(i)}))} disabled={disabled} onChange={value=>{setImageId(value);setPreview(null);setCompatible(false);setWithoutLimits(false);}}/>
|
||||
<Button disabled={disabled||!imageId} loading={busy} onClick={()=>void prepareCatalog()}>Проверить выбранный образ</Button></>:<Description>В установленном архиве нет подходящего образа. Можно выбрать свой файл или обновить бортовое приложение.</Description>}
|
||||
<ResourceList aria-label="Источник архива"><li><ResourceRow title="Репозиторий" description={catalog.repository}/></li><li><ResourceRow title="Ревизия архива" description={catalog.commit.slice(0,12)}/></li></ResourceList>
|
||||
</>}
|
||||
</>:<>
|
||||
{mode!=='swd'&&<Select label="Тип образа" value={kind} options={[{value:'firmware',label:'Прошивка контроллера'},{value:'bootloader',label:'Загрузчик'}]} disabled={disabled}
|
||||
onChange={value=>{setKind(value);setPreview(null);setCompatible(false);setIsolated(false);}}/>}
|
||||
{mode!=='swd'&&kind==='firmware'&&<Select label="Версия в выбранном образе" value={version} options={Array.from(new Set(versions)).map(value=>({value,label:`Прошивка ${value}`}))} disabled={disabled}
|
||||
onChange={value=>{setVersion(value);setPreview(null);setCompatible(false);}}/>}
|
||||
<Description>BIN и HEX не подтверждают производителя платы. Выберите образ для {mode==='swd'?'выбранного процессора':hardware??'своего контроллера'} и указанной версии. Проверка структуры и SHA-256 не подтверждает происхождение файла. HEX проверяется оригинальным читателем VESC Tool; адреса и итоговый образ проверяются до записи. Сжатые BIN здесь не принимаются.</Description>
|
||||
<input ref={input} type="file" accept={formats.includes('hex')?'.bin,.hex':'.bin'} hidden onChange={event=>{const file=event.target.files?.[0];event.target.value='';if(file)void stage(file);}}/>
|
||||
<Button disabled={disabled||!version||!destinationReady} loading={busy} onClick={()=>input.current?.click()}>Выбрать и проверить файл</Button>
|
||||
</>}
|
||||
{progress!==null&&<ProgressBar label="Передача файла на борт" value={progress}/>}
|
||||
</SettingsCard>
|
||||
{preview&&<SettingsCard title="Образ готов к записи">
|
||||
<ResourceList aria-label="Проверенный файл прошивки">
|
||||
<li><ResourceRow title="Файл" description={preview.image.name}/></li>
|
||||
<li><ResourceRow title="Размер" description={`${preview.image.bytes.toLocaleString('ru-RU')} байт`}/></li>
|
||||
<li><ResourceRow title={preview.image.swd?"USB-программатор":"Контроллер"} description={`${preview.image.hardware} · ${preview.identity.uuid.toUpperCase()}`}/></li>
|
||||
{preview.image.can_id!==undefined&&<li><ResourceRow title="Адрес CAN" description={String(preview.image.can_id)}/></li>}
|
||||
{preview.image.swd&&<li><ResourceRow title="Цель SWD" description={`Семейство ${preview.image.swd.target_code} · ${preview.image.swd.pins} · адрес 0x${preview.image.swd.address.toString(16).toUpperCase()}`}/></li>}
|
||||
<li><ResourceRow title="SHA-256 образа для записи" description={preview.image.sha256}/></li>
|
||||
{preview.image.source_sha256&&preview.image.source_sha256!==preview.image.sha256&&<li><ResourceRow title="SHA-256 исходного файла" description={preview.image.source_sha256}/></li>}
|
||||
{preview.image.format==='hex'&&<li><ResourceRow title="Адрес HEX" description={`0x${preview.image.base_address?.toString(16).toUpperCase()} · пропуски заполнены 0xFF`}/></li>}
|
||||
</ResourceList>
|
||||
<Description>Подготовка действует до 10 минут и отменяется после переподключения. Запись изменяет постоянную память; не отключайте питание. Старые настройки после смены прошивки автоматически не восстанавливаются.</Description>
|
||||
{preview.image.hardware_limits===false&&<><Description>Этот вариант удаляет аппаратные пределы тока и напряжения из прошивки. Ошибочные настройки могут повредить контроллер или мотор.</Description><Checker label="Подтверждаю выбор образа без аппаратных пределов" checked={withoutLimits} onChange={setWithoutLimits} disabled={disabled}/></>}
|
||||
<Checker label={preview.image.swd?"Подтверждаю физическую цель SWD, распиновку, flash и совместимость полного образа":"Образ соответствует этой плате и версии"} checked={compatible} onChange={setCompatible} disabled={disabled}/>
|
||||
<Checker label="Входы отключены, приводы вывешены и остановлены" checked={isolated} onChange={setIsolated} disabled={disabled}/>
|
||||
<Button variant="primary" disabled={disabled||!compatible||!isolated||(preview.image.hardware_limits===false&&!withoutLimits)} onClick={()=>void apply()}>{kind==='bootloader'?'Записать загрузчик':'Записать прошивку'}</Button>
|
||||
<Button disabled={disabled} onClick={()=>void discard()}>Убрать подготовленный файл</Button>
|
||||
</SettingsCard>}
|
||||
{state.state!=='idle'&&<SettingsCard title="Результат загрузки">
|
||||
<Description role="status">{labels[state.state]??state.state}</Description>
|
||||
{active&&<><ProgressBar label="Запись контроллера" value={state.progress}/><Button disabled={!state.operation_id||cancelling} loading={cancelling} onClick={()=>void cancel()}>Запросить отмену</Button></>}
|
||||
{state.image&&<ResourceList aria-label="Последняя загрузка"><li><ResourceRow title="Файл" description={state.image.name}/></li><li><ResourceRow title="SHA-256" description={state.image.sha256}/></li></ResourceList>}
|
||||
{state.before_backup_id&&<><Description>Исходная конфигурация сохранена по UUID контроллера.</Description><Button disabled={busy||active||!available} onClick={()=>void downloadBackup()}>Скачать исходную конфигурацию</Button></>}
|
||||
{!active&&!['identified','not_started'].includes(state.state)&&<>
|
||||
<Description>Управление заблокировано до подтверждения результата. После обрыва или отмены версия контроллера сама по себе не доказывает завершение записи. Автоматического повторения нет.</Description>
|
||||
<Button disabled={!enabled||!device.verified||busy} loading={busy} onClick={()=>void reconcile()}>Проверить контроллер после загрузки</Button>
|
||||
</>}
|
||||
{state.state==='identified'&&state.image?.swd&&<Description>Записанные байты прочитаны обратно и совпали; команда перезапуска подтверждена. Запуск приложения целевой платы ещё необходимо проверить.</Description>}
|
||||
{state.state==='identified'&&!state.image?.swd&&<Description>Передача подтверждена, UUID и версия контроллера прочитаны заново. Обратное чтение бинарного образа этим протоколом не выполнено. Перед управлением проверьте настройки.</Description>}
|
||||
</SettingsCard>}
|
||||
</div>;
|
||||
}
|
||||
@@ -1,42 +1,21 @@
|
||||
import {useRef,useState} from 'react';
|
||||
import {Button,Checker,SettingsCard} from '@nodedc/ui-react';
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Button,Description,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import {vescStatus} from './model';
|
||||
import {VescHallInputs} from './VescHallInputs';
|
||||
import {VescHallMeasurement} from './VescHallMeasurement';
|
||||
|
||||
interface HallResult {
|
||||
completed:boolean;configuration_restored:boolean;release_confirmed:boolean;
|
||||
measurement:null|{valid_six_states:boolean;observed_states:number[];hall_table:number[]};
|
||||
}
|
||||
|
||||
export function VescHall({device,transport,enabled,refresh,failure,blocked,onBusyChange}:SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void}){
|
||||
const [confirmed,setConfirmed]=useState(false);
|
||||
const [busy,setBusy]=useState(false);
|
||||
const [result,setResult]=useState<HallResult|null>(null);
|
||||
const running=useRef(false);
|
||||
const available=enabled&&device.online&&device.verified&&device.vesc_status?.test_supported===true&&!!vescStatus(device).hall_measurement;
|
||||
async function measure(){
|
||||
if(running.current||blocked||!available||!confirmed)return;
|
||||
running.current=true;setBusy(true);onBusyChange(true);setResult(null);failure(null);
|
||||
try{
|
||||
const inventory=await transport.inventory();
|
||||
const controllers=inventory.items.filter(item=>item.kind==='vesc.controller'&&item.online);
|
||||
const target=controllers.find(item=>item.id===device.id);
|
||||
if(inventory.fresh===false||!target||controllers.some(item=>!item.verified))throw new Error('Нужна свежая связь со всеми VESC борта.');
|
||||
setResult(await perform<HallResult>(transport,target,'vesc.hall.measure',{
|
||||
rig_clear:true,native_cycle_confirmed:true,
|
||||
...(vescStatus(target).hall_measurement?.standstill_confirmation_required?{standstill_confirmed:true}:{}),
|
||||
sessions:Object.fromEntries(controllers.map(item=>[item.id,item.snapshot.context.session_id])),
|
||||
},60000));
|
||||
}catch(error){failure(error);}
|
||||
finally{running.current=false;setBusy(false);onBusyChange(false);setConfirmed(false);await refresh();}
|
||||
}
|
||||
return <SettingsCard title="Датчики Холла" description={`${device.name} · штатное измерение VESC Tool, 5 А.`}>
|
||||
<p>Мотор медленно смещается в обе стороны около 12 секунд. Измерение проверяет состояния датчиков и получает таблицу их положения; новая таблица автоматически не записывается.</p>
|
||||
<p>На прошивке 5.02 этот цикл нельзя прервать кнопкой или пультом. Для немедленной остановки нужно отключить силовое питание. Пульт должен оставаться выключенным, все приводы — вывешенными. Перед запуском убедитесь, что все моторы полностью остановились: в бессенсорном режиме показание оборотов на остановленном моторе может быть ненулевым.</p>
|
||||
<Checker checked={confirmed} onChange={setConfirmed} disabled={busy||blocked} label="Все моторы остановлены, наблюдаю"/>
|
||||
<Button disabled={!available||blocked||!confirmed||busy} loading={busy} onClick={()=>void measure()}>Измерить датчики Холла</Button>
|
||||
{busy&&<p role="status">Подготовка и штатное измерение датчиков. Дождитесь результата.</p>}
|
||||
{result&&<p role="status">{!result.completed?'Завершение измерения не подтверждено. Проверьте мотор и питание.':result.measurement?.valid_six_states?'Измерение получило шесть состояний Холла.':'Не удалось получить полную таблицу Холла. Возможны отсутствие движения или неисправность датчиков/соединения.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока не подтверждено.'} {result.configuration_restored?'Исходная конфигурация сохранена.':'Возврат исходной конфигурации не подтверждён.'}</p>}
|
||||
</SettingsCard>;
|
||||
export function VescHall(props:SensorDetailProps&{active?:boolean;blocked:boolean;onBusyChange:(busy:boolean)=>void}){
|
||||
const [expanded,setExpanded]=useState(false),[measuring,setMeasuring]=useState(false);
|
||||
const identity=`${props.device.id}:${props.device.snapshot.context.session_id}`;
|
||||
useEffect(()=>{if(props.active===false&&!measuring)setExpanded(false);},[props.active,measuring]);
|
||||
useEffect(()=>setExpanded(false),[identity]);
|
||||
const busy=(value:boolean)=>{setMeasuring(value);props.onBusyChange(value);};
|
||||
return <div className="sensor-content">
|
||||
<VescHallInputs {...props} key={identity} blocked={props.blocked||measuring}/>
|
||||
<SettingsCard title="Измерение с вращением" description="Отдельная процедура VESC Tool: подаёт ток и вращает мотор. Для проверки контакта запускать её не обязательно.">
|
||||
<Description>Пассивный просмотр выше не подаёт ток. Измерение ниже требует вывешенных приводов и выключенного пульта.</Description>
|
||||
<Button variant="ghost" disabled={measuring} aria-expanded={expanded} onClick={()=>setExpanded(v=>!v)}>{expanded?'Скрыть процедуру':'Открыть процедуру с вращением'}</Button>
|
||||
</SettingsCard>
|
||||
{expanded&&<VescHallMeasurement {...props} key={identity} onBusyChange={busy}/>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,ComparisonTable,Description,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import type {ConfigurationRead} from './configuration';
|
||||
import {vescStatus} from './model';
|
||||
import {hallConfiguration} from './hallInputs';
|
||||
|
||||
export function VescHallInputs(props:SensorDetailProps&{active?:boolean;blocked:boolean;onBusyChange:(busy:boolean)=>void}){
|
||||
const {device,transport,enabled,blocked,failure,onBusyChange}=props,status=vescStatus(device);
|
||||
const [value,setValue]=useState<ConfigurationRead|null>(null),[busy,setBusy]=useState(false);
|
||||
const mounted=useRef(true),running=useRef(false),epoch=useRef(0);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
useEffect(()=>{if(!device.online||!enabled){epoch.current++;setValue(null);}},[device.online,enabled]);
|
||||
const available=enabled&&device.online&&device.verified&&status.readable&&status.configuration_read_supported;
|
||||
async function read(){
|
||||
if(running.current||blocked||!available||props.active===false)return;
|
||||
const token=epoch.current;running.current=true;setBusy(true);setValue(null);onBusyChange(true);failure(null);
|
||||
try{const result=await perform<ConfigurationRead>(transport,device,'vesc.configuration.read',{},30000);if(mounted.current&&token===epoch.current)setValue(result);}
|
||||
catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
const config=hallConfiguration(value),fw=status.identity?.version;
|
||||
return <>
|
||||
<SettingsCard title="Входы Холла · без вращения" description="Три логических сигнала положения ротора. Это часть управления мотором, а не только телеметрия.">
|
||||
<StatusBadge tone="neutral">{!device.online||!enabled?'Нет связи':fw==='5.02'?'Пассивное чтение H1–H3 недоступно':'Пассивное чтение H1–H3 не подтверждено'}</StatusBadge>
|
||||
<ComparisonTable density="compact" label="Доступность входов Холла" heading="Сигнал" columns={[1,2,3].map(i=>({id:String(i),label:`H${i}`}))} rows={[
|
||||
{id:'level',label:'Уровень 0 / 1',cells:config.inputs.map(()=>'Нет данных')},
|
||||
{id:'changes',label:'Переключения',cells:config.transitions.map(()=>'Не измерены')},
|
||||
]}/>
|
||||
<Description>{fw==='5.02'?'Штатная прошивка 5.02 не предоставляет отдельное пассивное чтение этих входов. Код Hall в Sample Data — преобразованная фаза; он не подтверждает уровни H1–H3.':'Для этой прошивки достоверный способ пассивного чтения трёх входов пока не подтверждён.'}</Description>
|
||||
<Description>«Нет данных» не означает обрыв. Неподвижный вал не обязан давать переключения; одно состояние не доказывает исправность всех трёх датчиков. Установка пина обратно не меняет режим управления автоматически.</Description>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Использование датчиков в контроллере" description={value?`Настройки прочитаны ${new Date(value.observed_at).toLocaleString('ru-RU')}`:'Прочитайте сохранённые настройки. Чтение не подаёт ток и не меняет конфигурацию.'}
|
||||
actions={<Button disabled={!available||blocked||busy} loading={busy} onClick={()=>void read()}>Прочитать настройки датчиков</Button>}>
|
||||
<ResourceList aria-label="Настройки датчиков Холла">{[
|
||||
['Тип мотора',config.motor],['Режим порта датчиков',config.port],['Режим датчиков FOC',config.mode],['Участие Холлов в управлении',config.use],
|
||||
].map(([title,description])=><li key={title}><ResourceRow title={title} description={description}/></li>)}</ResourceList>
|
||||
<Description>Это выбранные настройки, а не результат обнаружения датчика. Ремонт контакта и правильность переключений ими не подтверждаются.</Description>
|
||||
</SettingsCard>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Checker,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import {vescStatus} from './model';
|
||||
|
||||
interface HallResult {
|
||||
completed:boolean;configuration_restored:boolean;release_confirmed:boolean;
|
||||
measurement:null|{valid_six_states:boolean;observed_states:number[];hall_table:number[]};
|
||||
}
|
||||
|
||||
export function VescHallMeasurement({device,transport,enabled,refresh,failure,blocked,onBusyChange,active=true}:SensorDetailProps&{active?:boolean;blocked:boolean;onBusyChange:(busy:boolean)=>void}){
|
||||
const [confirmed,setConfirmed]=useState(false);
|
||||
const [raised,setRaised]=useState(false),[remoteOff,setRemoteOff]=useState(false);
|
||||
const [busy,setBusy]=useState(false);
|
||||
const [result,setResult]=useState<HallResult|null>(null);
|
||||
useEffect(()=>{if(!active){setConfirmed(false);setRaised(false);setRemoteOff(false);}},[active]);
|
||||
const running=useRef(false);
|
||||
const available=enabled&&device.online&&device.verified&&device.vesc_status?.test_supported===true&&!!vescStatus(device).hall_measurement;
|
||||
async function measure(){
|
||||
if(!active||running.current||blocked||!available||!confirmed||!raised||!remoteOff)return;
|
||||
running.current=true;setBusy(true);onBusyChange(true);setResult(null);failure(null);
|
||||
try{
|
||||
const inventory=await transport.inventory();
|
||||
const controllers=inventory.items.filter(item=>item.kind==='vesc.controller'&&item.online);
|
||||
const target=controllers.find(item=>item.id===device.id);
|
||||
if(inventory.fresh===false||!target||controllers.some(item=>!item.verified))throw new Error('Нужна свежая связь со всеми VESC борта.');
|
||||
setResult(await perform<HallResult>(transport,target,'vesc.hall.measure',{
|
||||
rig_clear:true,native_cycle_confirmed:true,
|
||||
...(vescStatus(target).hall_measurement?.standstill_confirmation_required?{standstill_confirmed:true}:{}),
|
||||
sessions:Object.fromEntries(controllers.map(item=>[item.id,item.snapshot.context.session_id])),
|
||||
},60000));
|
||||
}catch(error){failure(error);}
|
||||
finally{running.current=false;setBusy(false);onBusyChange(false);setConfirmed(false);setRaised(false);setRemoteOff(false);await refresh();}
|
||||
}
|
||||
return <SettingsCard title="Измерение с вращением мотора" description={`${device.name} · штатное измерение VESC Tool, 5 А.`}>
|
||||
<Description>Мотор медленно смещается в обе стороны около 12 секунд. Измерение проверяет состояния датчиков и получает таблицу их положения; новая таблица автоматически не записывается.</Description>
|
||||
<Description>На прошивке 5.02 этот цикл нельзя прервать кнопкой или пультом. Для немедленной остановки нужно отключить силовое питание. Пульт должен оставаться выключенным, все приводы — вывешенными. Перед запуском убедитесь, что все моторы полностью остановились: в бессенсорном режиме показание оборотов на остановленном моторе может быть ненулевым.</Description>
|
||||
<Checker checked={raised} onChange={setRaised} disabled={busy||blocked} label="Все приводы вывешены"/>
|
||||
<Checker checked={remoteOff} onChange={setRemoteOff} disabled={busy||blocked} label="Пульт выключен"/>
|
||||
<Checker checked={confirmed} onChange={setConfirmed} disabled={busy||blocked} label="Все моторы остановлены, наблюдаю"/>
|
||||
<Button disabled={!active||!available||blocked||!confirmed||!raised||!remoteOff||busy} loading={busy} onClick={()=>void measure()}>Запустить вращение и измерение · 5 А</Button>
|
||||
{busy&&<Description role="status">Подготовка и штатное измерение датчиков. Дождитесь результата.</Description>}
|
||||
{result&&<Description role="status">{!result.completed?'Завершение измерения не подтверждено. Проверьте мотор и питание.':result.measurement?.valid_six_states?'Измерение получило шесть состояний Холла.':'Не удалось получить полную таблицу Холла. Возможны отсутствие движения или неисправность датчиков/соединения.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока не подтверждено.'} {result.configuration_restored?'Исходная конфигурация сохранена.':'Возврат исходной конфигурации не подтверждён.'}</Description>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useRef,useState} from 'react';
|
||||
import {Button,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
|
||||
import {perform,type Sensor,type SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
|
||||
@@ -16,7 +17,7 @@ export function VescLimits({controllers,transport,enabled,failure}:{controllers:
|
||||
catch(error){failure(error);}finally{running.current=false;setBusy(false);}
|
||||
}
|
||||
return <SettingsCard title="Ограничения контроллеров" description="Текущие настройки VESC. Чтение не запускает моторы и не меняет конфигурацию." actions={<Button disabled={!enabled||busy||!readable.length} loading={busy} onClick={()=>void read()}>Прочитать ограничения</Button>}>
|
||||
<p>Ток мотора задаёт тягу; ток батареи ограничивает потребление. Эти настройки действуют и при управлении с пульта. Паспортные пределы моторов, контроллеров и батареи проверяются отдельно.</p>
|
||||
<Description>Ток мотора задаёт тягу; ток батареи ограничивает потребление. Эти настройки действуют и при управлении с пульта. Паспортные пределы моторов, контроллеров и батареи проверяются отдельно.</Description>
|
||||
{controllers.map(device=>{
|
||||
const value=values[device.id];if(!value)return null;
|
||||
const p=value.parameters;
|
||||
@@ -30,6 +31,6 @@ export function VescLimits({controllers,transport,enabled,failure}:{controllers:
|
||||
];
|
||||
return <SettingsCard key={device.id} title={device.name} description={`Прочитано ${new Date(value.observed_at).toLocaleString('ru-RU')}`}><ResourceList aria-label={`Ограничения ${device.name}`}>{fields.map(([title,description])=><li key={title}><ResourceRow title={title} description={description}/></li>)}</ResourceList></SettingsCard>;
|
||||
})}
|
||||
{!Object.keys(values).length&&<p>Прочитайте значения для подключённых контроллеров.</p>}
|
||||
{!Object.keys(values).length&&<Description>Прочитайте значения для подключённых контроллеров.</Description>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
@@ -35,8 +36,8 @@ export function VescLink({device,transport,enabled,failure,refresh,blocked,onBus
|
||||
'Измерение не завершено.';
|
||||
return <SettingsCard title="Связь с контроллерами" description="Проверяет ответы всех VESC борта около 10 секунд. Моторы должны стоять; команды вращения и изменения настроек не отправляются."
|
||||
actions={<Button disabled={!available||blocked||busy} loading={busy} onClick={()=>void check()}>Проверить связь</Button>}>
|
||||
{busy&&<p role="status">Измеряется время ответа контроллеров.</p>}
|
||||
{result&&<><p role="status">{text}</p><ResourceList aria-label="Связь VESC">{Object.entries(result.devices).map(([id,item])=><li key={id}><ResourceRow title={item.name}
|
||||
{busy&&<Description role="status">Измеряется время ответа контроллеров.</Description>}
|
||||
{result&&<><Description role="status">{text}</Description><ResourceList aria-label="Связь VESC">{Object.entries(result.devices).map(([id,item])=><li key={id}><ResourceRow title={item.name}
|
||||
description={`${item.summary.replies} ответов${item.summary.max_ms===undefined?'':` · 95% не дольше ${Math.ceil(item.summary.p95_ms??0)} мс · максимум ${Math.ceil(item.summary.max_ms)} мс`}`}/></li>)}</ResourceList></>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import {useEffect,useMemo,useRef,useState} from 'react';
|
||||
import {Button,Description,RangeControl,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {LOG_MAX_BYTES,parseVescLog,spectrum,type VescLog} from './logAnalysis';
|
||||
import {SignalPlot} from './SignalPlot';
|
||||
export function VescLogAnalysis(){
|
||||
const [log,setLog]=useState<VescLog|null>(null),[name,setName]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false);
|
||||
const [keys,setKeys]=useState<string[]>([]),[from,setFrom]=useState(0),[to,setTo]=useState(0),[fftKey,setFftKey]=useState(''),[fftEnabled,setFftEnabled]=useState(false);
|
||||
const input=useRef<HTMLInputElement>(null),generation=useRef(0);
|
||||
useEffect(()=>()=>{generation.current++;},[]);
|
||||
async function open(file:File){const request=++generation.current;setBusy(true);setError('');
|
||||
try{if(file.size>LOG_MAX_BYTES)throw new Error('Максимальный размер CSV — 4 МиБ.');const parsed=parseVescLog(await file.text());if(request!==generation.current)return;
|
||||
setLog(parsed);setName(file.name);setKeys(parsed.columns.slice(0,2).map(c=>c.key));setFrom(0);setTo(parsed.duration);setFftKey(parsed.columns[0].key);setFftEnabled(false);
|
||||
}catch(e){if(request===generation.current)setError(e instanceof Error?e.message:'Не удалось прочитать журнал.');}
|
||||
finally{if(request===generation.current)setBusy(false);}
|
||||
}
|
||||
const fft=useMemo(()=>{if(!log||!fftEnabled)return null;try{return {value:spectrum(log.points,fftKey,from,to),error:''};}catch(e){return {value:null,error:e instanceof Error?e.message:'Спектр недоступен.'};}},[log,fftKey,from,to,fftEnabled]);
|
||||
const options=log?.columns.map(c=>({value:c.key,label:c.label+(c.unit?` · ${c.unit}`:'')}))??[];
|
||||
return <div className="sensor-content"><SettingsCard title="Анализ журнала" description="Откройте CSV Mission Core или оригинального VESC Tool. Файл обрабатывается в этом окне и не отправляется на борт." actions={<StatusBadge>Сохранённые данные</StatusBadge>}>
|
||||
<input ref={input} type="file" hidden accept=".csv,text/csv" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void open(file);}}/>
|
||||
<div className="sensor-actions"><Button loading={busy} onClick={()=>input.current?.click()}>Открыть CSV</Button>{log&&<Button disabled={busy} onClick={()=>{generation.current++;setLog(null);setName('');setError('');}}>Закрыть журнал</Button>}</div>
|
||||
{error&&<Description role="alert">{error}</Description>}
|
||||
<Description>До 4 МиБ и 20 000 строк. Поддерживаются Sample Data, RT CSV и Log Analysis CSV VESC Tool. Пустые ячейки остаются пропусками. При закрытии раздела журнал удаляется из памяти. Импорт не меняет живую телеметрию и настройки контроллера.</Description>
|
||||
{log&&<ResourceList aria-label="Открытый журнал"><li><ResourceRow title={name} description={`${log.format} · ${log.points.length} строк · ${(log.duration/1000).toLocaleString('ru-RU')} с`}/></li><li><ResourceRow title="Контроллер в журнале" description={log.uuid?`${log.uuid.toUpperCase()} · ${log.hardware??'аппаратура не указана'} · ${log.firmware??'прошивка не указана'}`:'UUID в этом формате не указан. Принадлежность открытому VESC не подтверждена.'}/></li></ResourceList>}
|
||||
</SettingsCard>{log&&<>
|
||||
<SettingsCard title="Сравнение сигналов" description="До четырёх графиков с общей осью времени. Каждый сигнал сохраняет собственные единицы и шкалу.">
|
||||
<RangeControl label="Начало интервала" min={0} max={log.duration} step={1} value={from} onChange={value=>setFrom(Math.min(value,to))} formatValue={v=>`${(v/1000).toFixed(3)} с`}/>
|
||||
<RangeControl label="Конец интервала" min={0} max={log.duration} step={1} value={to} onChange={value=>setTo(Math.max(from,value))} formatValue={v=>`${(v/1000).toFixed(3)} с`}/>
|
||||
{keys.map((key,i)=><div key={i} className="sensor-actions"><Select label={`Сигнал ${i+1}`} value={key} options={options.filter(o=>o.value===key||!keys.includes(o.value))} onChange={value=>setKeys(previous=>previous.map((v,j)=>i===j?value:v))}/><Button disabled={keys.length===1} onClick={()=>setKeys(previous=>previous.filter((_,j)=>j!==i))}>Убрать сигнал {i+1}</Button></div>)}
|
||||
<Button disabled={keys.length>=4||keys.length>=options.length} onClick={()=>{const next=options.find(o=>!keys.includes(o.value));if(next)setKeys(previous=>[...previous,next.value]);}}>Добавить сигнал</Button>
|
||||
</SettingsCard>
|
||||
{keys.map(key=>{const column=log.columns.find(c=>c.key===key)!;return <SignalPlot key={key} title={column.label} unit={column.unit} from={from} to={to} points={log.points.map(p=>({at:p.at,value:p.gap?null:p.values[key]??null}))}/>;})}
|
||||
<SettingsCard title="Частотный анализ FFT" description="Амплитудный спектр выбранного участка. Среднее удаляется, применяется окно Ханна; амплитуда указана в единицах сигнала.">
|
||||
<Select label="Сигнал для FFT" value={fftKey} options={options} onChange={setFftKey}/><Button onClick={()=>setFftEnabled(v=>!v)}>{fftEnabled?'Скрыть спектр':'Показать спектр'}</Button>
|
||||
<Description>Используются последние 32–4096 измерений участка, число округляется вниз до степени двойки. Пропуски и неравномерный шаг блокируют расчёт. Верхняя частота — половина частоты измерений; журнал с частотой 2 Гц не позволяет анализировать быстрые процессы мотора.</Description>
|
||||
{fft?.error&&<Description role="status">{fft.error}</Description>}
|
||||
{fft?.value&&<Description>{fft.value.n} измерений · частота {(fft.value.rate).toLocaleString('ru-RU',{maximumFractionDigits:3})} Гц · разрешение {(fft.value.rate/fft.value.n).toLocaleString('ru-RU',{maximumFractionDigits:5})} Гц · интервал {(fft.value.from/1000).toFixed(3)}–{(fft.value.to/1000).toFixed(3)} с · пик {fft.value.peak.hz.toLocaleString('ru-RU',{maximumFractionDigits:5})} Гц / {fft.value.peak.amplitude.toLocaleString('ru-RU',{maximumFractionDigits:5})} {log.columns.find(c=>c.key===fftKey)?.unit}</Description>}
|
||||
</SettingsCard>
|
||||
{fft?.value&&<SignalPlot title="Амплитудный спектр" unit={log.columns.find(c=>c.key===fftKey)?.unit??''} points={fft.value.bins.map(b=>({at:b.hz,value:b.amplitude}))} from={0} to={fft.value.rate/2} xUnit="Гц" xScale={1}/>}
|
||||
</>}</div>;
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Checker,Select,TextField,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import {testInput,speedInput,rotationResult,vescStatus,driveTestIds,drivePositions} from './model';
|
||||
|
||||
export function VescMotor({device,transport,enabled,refresh,failure,blocked=false,onBusyChange}:SensorDetailProps&{blocked?:boolean;onBusyChange?:(busy:boolean)=>void}){
|
||||
export function VescMotor({device,transport,enabled,refresh,failure,blocked=false,onBusyChange,active=true}:SensorDetailProps&{active?:boolean;blocked?:boolean;onBusyChange?:(busy:boolean)=>void}){
|
||||
const [duration,setDuration]=useState('30');
|
||||
const [current,setCurrent]=useState('30');
|
||||
const [speed,setSpeed]=useState('2000');
|
||||
@@ -17,6 +18,7 @@ export function VescMotor({device,transport,enabled,refresh,failure,blocked=fals
|
||||
const [clear,setClear]=useState(false);const [busy,setBusy]=useState(false);
|
||||
const [result,setResult]=useState<string|null>(null);const [stopping,setStopping]=useState(false);
|
||||
const [rc,setRc]=useState(device.vesc_status?.rc_latched===true);
|
||||
useEffect(()=>{if(!active)setClear(false);},[active]);
|
||||
const running=useRef(false);const mounted=useRef(true);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
const limits=vescStatus(device).test_limits;
|
||||
@@ -66,24 +68,24 @@ export function VescMotor({device,transport,enabled,refresh,failure,blocked=fals
|
||||
}
|
||||
useEffect(()=>setRc(device.vesc_status?.rc_latched===true),[device.vesc_status?.rc_latched]);
|
||||
return <SettingsCard title="Проверка вращения" description={`${device.name} · ${device.connection_label??'USB'}. Конфигурации подключённых контроллеров сохраняются автоматически.`}>
|
||||
<p>Для вывешенных колёс без нагрузки. При команде с приёмника проверка прекращается; повторный запуск требует явного возврата управления.</p>
|
||||
<Description>Для вывешенных колёс без нагрузки. При команде с приёмника проверка прекращается; повторный запуск требует явного возврата управления.</Description>
|
||||
<Select label="Проверяемые моторы" value={scope} disabled={busy||blocked} options={[{value:'single',label:`Только ${device.name}`},{value:'profile',label:'Все моторы профиля одновременно',disabled:!groupAvailable}]} onChange={setScope}/>
|
||||
{group&&profile&&<p>{Object.keys(drivePositions(profile.layout)).map(slot=>`${drivePositions(profile.layout)[slot]} · VESC ${profile.bindings[slot]?.uuid.slice(0,6).toUpperCase()??'не назначен'}`).join('; ')}. Общий отсчёт начинается, когда все моторы удерживают скорость. Остановка любого завершает всю проверку. Предел тока применяется к каждому мотору.</p>}
|
||||
{group&&profile&&<Description>{Object.keys(drivePositions(profile.layout)).map(slot=>`${drivePositions(profile.layout)[slot]} · VESC ${profile.bindings[slot]?.uuid.slice(0,6).toUpperCase()??'не назначен'}`).join('; ')}. Общий отсчёт начинается, когда все моторы удерживают скорость. Остановка любого завершает всю проверку. Предел тока применяется к каждому мотору.</Description>}
|
||||
<Select label="Направление вращения" value={direction} disabled={busy||blocked} options={[{value:'forward',label:'Прямое'},{value:'reverse',label:'Обратное',disabled:speedLimits?.reverse_supported!==true}]} onChange={value=>{setDirection(value);setClear(false);}}/>
|
||||
<p>Направление относительно настроек VESC. Перед обратным запуском дождитесь полной остановки всех моторов и подтвердите её.</p>
|
||||
<Description>Направление относительно настроек VESC. Перед обратным запуском дождитесь полной остановки всех моторов и подтвердите её.</Description>
|
||||
<TextField type="number" inputMode="decimal" label="Скорость, ERPM" value={speed} onChange={event=>setSpeed(event.target.value)} disabled={busy||!speedLimits} min={speedLimits?.min_erpm} max={speedLimits?.max_erpm} step="100" aria-invalid={!!speedValue.error} description={speedValue.error??'Электрические обороты в минуту. VESC плавно разгоняет мотор и удерживает заданную скорость.'}/>
|
||||
<TextField type="number" inputMode="decimal" label="Предел тока мотора, А" value={current} onChange={event=>setCurrent(event.target.value)} disabled={busy||!limits} min={limits?.min_current_a} max={limits?.max_current_a} step="0.1" aria-invalid={!!input.currentError} hint={limits?`${limits.min_current_a}–${limits.max_current_a} А`:undefined} description={input.currentError??'Максимальный ток разгона и удержания скорости. Прежние пределы сохраняются перед тестом и восстанавливаются после него.'}/>
|
||||
<TextField type="number" inputMode="decimal" label="Длительность вращения, с" value={duration} onChange={event=>setDuration(event.target.value)} disabled={busy||!limits} min={limits?.min_duration_s} max={limits?.max_duration_s} step="0.1" aria-invalid={!!input.durationError} hint={limits?`${limits.min_duration_s}–${limits.max_duration_s} с`:undefined} description={input.durationError??'Отсчёт начинается после разгона и стабилизации скорости. Подготовка, разгон и остановки не входят в это время.'}/>
|
||||
<p>Время считается по скорости и тахометру VESC. Если мотор не разгонится за 15 секунд, потеряет скорость или сработает ограничение, результат покажет фактическое время и причину остановки. Показания контроллера нужно сопоставить с видимым вращением.</p>
|
||||
{limits?.stall_timeout_s&&<p>При токе выше {limits.stall_current_a} А и отсутствии подтверждённого движения в течение {limits.stall_timeout_s} секунд проверка остановится.</p>}
|
||||
<p>Все приводы должны быть вывешены, вращение свободно. Подтверждение требуется перед каждым запуском.</p>
|
||||
<Description>Время считается по скорости и тахометру VESC. Если мотор не разгонится за 15 секунд, потеряет скорость или сработает ограничение, результат покажет фактическое время и причину остановки. Показания контроллера нужно сопоставить с видимым вращением.</Description>
|
||||
{limits?.stall_timeout_s&&<Description>При токе выше {limits.stall_current_a} А и отсутствии подтверждённого движения в течение {limits.stall_timeout_s} секунд проверка остановится.</Description>}
|
||||
<Description>Все приводы должны быть вывешены, вращение свободно. Подтверждение требуется перед каждым запуском.</Description>
|
||||
<Checker checked={clear} onChange={setClear} disabled={busy} label="Все моторы остановлены, наблюдаю"/>
|
||||
{blockedReason&&<p role="status">{blockedReason}</p>}
|
||||
{blockedReason&&<Description role="status">{blockedReason}</Description>}
|
||||
<div className="sensor-actions">
|
||||
{rc?<Button disabled={!available||!clear||busy||!valid} loading={busy} onClick={()=>void execute(true)}>Вернуть управление после нейтрали</Button>:
|
||||
<Button disabled={!available||!clear||busy||!valid} loading={busy} onClick={()=>void execute()}>Проверить вращение</Button>}
|
||||
<Button disabled={!enabled||!device.online||blocked} loading={stopping} onClick={()=>void stop()}>Остановить проверку</Button>
|
||||
</div>
|
||||
{result&&<p role="status">{result}</p>}
|
||||
{result&&<Description role="status">{result}</Description>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import {useEffect,useRef,useState,type ChangeEvent} from 'react';
|
||||
import {Button,Checker,Description,ResourceList,ResourceRow,Select,SettingsCard,TextAreaField,TextField} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {vescStatus} from './model';
|
||||
import {VescQmlPreview} from './VescQmlPreview';
|
||||
import {bytesBase64} from './editorFiles';
|
||||
interface Item {id:string;name:string;path:string;library:boolean;imported?:boolean;bytes:number;lisp_bytes:number;qml_bytes:number;description:string;qml_source?:string;compatible?:boolean|null;fits?:boolean}
|
||||
interface Catalog {sha256:string;items:Item[];source:string}
|
||||
interface Installed {pending:boolean;recognized:boolean;empty:boolean;installed:{id:string;name:string;path:string}|null}
|
||||
interface Preview {preview_id:string;package:{id:string;name:string}|null;before:Record<string,{bytes:number}>}
|
||||
const hash=async(data:Uint8Array)=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new Uint8Array(data)))).map(v=>v.toString(16).padStart(2,'0')).join('');
|
||||
export function VescPackages(props:ReadProps){
|
||||
const status=vescStatus(props.device),file=useRef<HTMLInputElement>(null),running=useRef(false),mounted=useRef(true);
|
||||
const [catalog,setCatalog]=useState<Catalog|null>(null),[selected,setSelected]=useState<Item|null>(null),[installed,setInstalled]=useState<Installed|null>(null);
|
||||
const [busy,setBusy]=useState(false),[query,setQuery]=useState(''),[category,setCategory]=useState('all'),[message,setMessage]=useState('');
|
||||
const [library,setLibrary]=useState(false),[compatible,setCompatible]=useState(false),[confirmed,setConfirmed]=useState(false),[preview,setPreview]=useState<Preview|null>(null);
|
||||
const available=props.enabled&&props.device.online&&props.device.verified,disabled=busy||props.blocked||!available;
|
||||
const supported=status.identity?.version==='6.00'&&status.identity.hardware_type===0&&status.identity.test_firmware===0;
|
||||
const pending=installed?.pending||status.package_pending;
|
||||
const call=<T,>(action:string,parameters:Record<string,unknown>={},timeout=60000)=>perform<T>(props.transport,props.device,'vesc.packages.'+action,parameters,timeout);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
function clear(){setPreview(null);setConfirmed(false);setMessage('');}
|
||||
async function run(work:()=>Promise<void>){if(running.current||disabled)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);try{await work();}catch(e){if(mounted.current)props.failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}}
|
||||
async function list(){const c=await call<Catalog>('catalog');if(mounted.current){setCatalog(c);setSelected(old=>old&&c.items.some(i=>i.id===old.id)?old:null);}}
|
||||
async function read(){const v=await call<Installed>('status',{},90000);if(mounted.current)setInstalled(v);}
|
||||
const load=()=>run(async()=>{clear();await list();});
|
||||
const inspect=(id:string)=>run(async()=>{clear();setCompatible(false);const v=await call<Item>('inspect',{id});if(mounted.current)setSelected(v);});
|
||||
async function importFile(event:ChangeEvent<HTMLInputElement>){const f=event.target.files?.[0];event.target.value='';if(!f)return;await run(async()=>{
|
||||
clear();const kind=f.name.toLowerCase().endsWith('.rcc')?'catalog':'package',limit=kind==='catalog'?8*1024*1024:1024*1024;
|
||||
if(f.size>limit)throw new Error('Файл превышает предел: пакет — 1 МБ, каталог — 8 МБ.');
|
||||
const data=new Uint8Array(await f.arrayBuffer()),sha256=await hash(data);
|
||||
const b=await call<{upload_id:string;chunk_bytes:number}>('begin',{kind,name:f.name.replace(/[^A-Za-z0-9_. -]/g,'_').slice(0,128),size:data.length,sha256,library,source:'import'});
|
||||
for(let at=0;at<data.length;at+=b.chunk_bytes){const chunk=data.slice(at,at+b.chunk_bytes),v=await call<{offset:number}>('chunk',{upload_id:b.upload_id,offset:at,data:bytesBase64(chunk)});if(v.offset!==at+chunk.length)throw new Error('Фрагмент файла не подтверждён.');}
|
||||
await call('load',{upload_id:b.upload_id});await list();if(mounted.current)setMessage('Импорт проверен и добавлен в каталог. Контроллер не изменён.');
|
||||
});}
|
||||
const download=()=>run(async()=>{if(!selected)return;const pieces:Uint8Array[]=[];let at=0;
|
||||
while(at<selected.bytes){const v=await call<{id:string;bytes:number;offset:number;data:string}>('download',{id:selected.id,offset:at});const part=Uint8Array.from(atob(v.data),c=>c.charCodeAt(0));if(v.id!==selected.id||v.offset!==at||v.bytes!==selected.bytes||!part.length||at+part.length>selected.bytes)throw new Error('Получен неполный пакет.');pieces.push(part);at+=part.length;}
|
||||
const data=new Uint8Array(at);at=0;for(const p of pieces){data.set(p,at);at+=p.length;}if(await hash(data)!==selected.id)throw new Error('Контрольная сумма пакета не совпала.');
|
||||
const url=URL.createObjectURL(new Blob([data],{type:'application/octet-stream'})),a=document.createElement('a');a.href=url;a.download=selected.path.split('/').at(-1)||'extension.vescpkg';a.click();setTimeout(()=>URL.revokeObjectURL(url),0);
|
||||
});
|
||||
const prepare=(action:string,p:Record<string,unknown>={})=>run(async()=>{clear();const v=await call<Preview>(action,p,90000);if(mounted.current)setPreview(v);});
|
||||
const apply=()=>run(async()=>{if(!preview||!confirmed)return;const id=preview.preview_id;clear();const v=await call<{verified:boolean;message?:string}>('apply',{preview_id:id,confirmed:true,inputs_isolated:true},350000);if(mounted.current){setMessage(v.message??(v.verified?'Расширение записано и проверено. Lisp не запускался.':'Итог записи неизвестен.'));setInstalled(old=>old?{...old,pending:!v.verified}:null);}await props.refresh();if(v.verified)await read();});
|
||||
const items=catalog?.items.filter(i=>(category==='all'||(category==='libraries')===i.library)&&`${i.name} ${i.path}`.toLowerCase().includes(query.toLowerCase()))??[];
|
||||
const updating=Boolean(installed?.installed&&selected&&installed.installed.path===selected.path&&installed.installed.id!==selected.id);
|
||||
return <div className="sensor-content">
|
||||
<SettingsCard title="Расширения VESC" description="Готовые приложения и библиотеки Lisp/QML из каталога VESC Tool. Загрузка пакета в каталог, запись на контроллер и запуск Lisp выполняются отдельно.">
|
||||
<Button loading={busy} disabled={disabled} onClick={()=>void load()}>Открыть сохранённый каталог</Button>
|
||||
<Button disabled={disabled} onClick={()=>void run(async()=>{clear();await call('refresh',{},180000);await list();if(mounted.current)setMessage('Каталог автора обновлён. Установленное расширение не изменено.');})}>Обновить каталог автора</Button>
|
||||
<Description>Автор распространяет каталог по HTTP. Перед установкой проверьте описание, совместимость и состав выбранного пакета.</Description>
|
||||
<input hidden type="file" ref={file} accept=".vescpkg,.rcc" onChange={e=>void importFile(e)}/>
|
||||
<Button disabled={disabled} onClick={()=>file.current?.click()}>Импорт пакета или каталога</Button>
|
||||
<Checker label="Импортировать отдельный пакет как библиотеку" checked={library} onChange={setLibrary} disabled={disabled}/>
|
||||
{!supported&&<Description role="status">Прошивка контроллера {status.identity?.version??'не определена'}. Каталог и импорт доступны; запись расширений поддерживается для VESC 6.00. Обновление каталога не меняет прошивку.</Description>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="На контроллере" description="Состояние определяется чтением обеих частей: Lisp и QML. После ручного изменения кода старое название пакета не считается подтверждённым.">
|
||||
<Button disabled={disabled||!supported} onClick={()=>void run(async()=>{clear();await read();})}>Прочитать установленное расширение</Button>
|
||||
{installed&&<Description>{installed.installed?`${installed.installed.name} · ${installed.installed.id.slice(0,12)}`:installed.empty?'Lisp и QML приложения отсутствуют.':'Есть пользовательский код. Его пакет не определён.'}</Description>}
|
||||
{pending&&<Description role="status">Предыдущее изменение не подтверждено. Проверьте содержимое или восстановите исходную копию.</Description>}
|
||||
{pending&&<Button disabled={disabled||!supported} onClick={()=>void run(async()=>{clear();const v=await call<{verified:boolean}>('reconcile',{},90000);await props.refresh();await read();if(mounted.current)setMessage(v.verified?'Содержимое подтверждено.':'Содержимое отличается от исходного и ожидаемого. Доступно восстановление.');})}>Проверить запись</Button>}
|
||||
<Button disabled={disabled||!supported} onClick={()=>void prepare('restore')}>Подготовить восстановление копии</Button>
|
||||
<Button disabled={disabled||!supported||pending} onClick={()=>void prepare('remove_prepare')}>Подготовить удаление расширения</Button>
|
||||
</SettingsCard>
|
||||
{selected&&<SettingsCard title={selected.name} description={`${selected.library?'Библиотека':'Приложение'} · ревизия ${selected.id.slice(0,12)}`}>
|
||||
<ResourceList aria-label="Состав расширения"><li><ResourceRow title="Lisp с вложениями" description={`${selected.lisp_bytes} байт`}/></li><li><ResourceRow title="QML-интерфейс" description={`${selected.qml_bytes} байт`}/></li><li><ResourceRow title="Совместимость по описанию автора" description={selected.compatible===true?'Тип контроллера разрешён автором':selected.compatible===false?'Этот контроллер исключён автором':'Условия не определены или не удалось проверить'}/></li></ResourceList>
|
||||
{selected.description&&<TextAreaField label="README автора" value={selected.description} readOnly rows={12}/>}
|
||||
{selected.library?<Description>Библиотеку используют через import в проекте Lisp. Она не заменяет приложение контроллера. Примеры pkg@ и pkg:: из README работают в редакторе Lisp: вложения берутся из сохранённого каталога.</Description>:<>
|
||||
{selected.compatible==null&&<Checker label="Совместимость проверена по документации автора" checked={compatible} onChange={setCompatible} disabled={disabled}/>}
|
||||
<Description>Запись заменит Lisp и QML приложения, включая пустые части пакета. Исходная копия сохраняется. Запуск здесь не выполняется; поведение после перезагрузки определяется прошивкой контроллера.</Description>
|
||||
<Button disabled={disabled||!supported||pending||selected.compatible===false||selected.fits===false||(selected.compatible==null&&!compatible)} onClick={()=>void prepare('prepare',{id:selected.id,compatibility_confirmed:compatible})}>{updating?'Подготовить обновление':'Подготовить установку'}</Button>
|
||||
{selected.fits===false&&<Description>Код не помещается во flash текущего профиля.</Description>}
|
||||
</>}
|
||||
<Button disabled={disabled} onClick={()=>void download()}>Скачать .vescpkg</Button>
|
||||
{selected.imported&&<Button disabled={disabled} onClick={()=>void run(async()=>{await call('forget',{id:selected.id});if(mounted.current)setSelected(null);await list();})}>Убрать импорт из каталога</Button>}
|
||||
</SettingsCard>}
|
||||
{selected?.qml_source&&<VescQmlPreview {...props} source={selected.qml_source}/>}
|
||||
{preview&&<SettingsCard title="Подтверждение записи" description="Операция привязана к UUID, прошивке, текущему коду и сеансу контроллера; подтверждение действует пять минут.">
|
||||
<Description>{preview.package?`Запись: ${preview.package.name}.`:'Удаление кода приложения или восстановление пользовательского кода.'} При потере связи автоматического повтора не будет. Проверка результата и восстановление доступны выше.</Description>
|
||||
<Checker label="Операция подтверждена, внешние входы отключены" checked={confirmed} onChange={setConfirmed} disabled={disabled}/>
|
||||
<Button variant="primary" disabled={disabled||!confirmed} onClick={()=>void apply()}>Выполнить запись без запуска</Button>
|
||||
</SettingsCard>}
|
||||
{message&&<SettingsCard title="Результат"><Description role="status">{message}</Description></SettingsCard>}
|
||||
{catalog&&<SettingsCard title="Каталог" description={`${catalog.items.length} пакетов · ревизия ${catalog.sha256.slice(0,12)}`}>
|
||||
<TextField label="Поиск расширения" value={query} onChange={e=>setQuery(e.target.value)}/><Select label="Тип пакета" value={category} onChange={setCategory} options={[{value:'all',label:'Все'},{value:'applications',label:'Приложения'},{value:'libraries',label:'Библиотеки'}]}/>
|
||||
<ResourceList aria-label="Расширения VESC">{items.map(item=><li key={item.path+item.id}><ResourceRow title={item.name} description={`${item.library?'Библиотека':'Приложение'} · ${item.id.slice(0,12)}`} actions={<Button disabled={disabled} onClick={()=>void inspect(item.id)}>Открыть</Button>}/></li>)}</ResourceList>
|
||||
{!items.length&&<Description>Подходящих пакетов нет.</Description>}
|
||||
</SettingsCard>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import {Checker,Select,TextField} from '@nodedc/ui-react';
|
||||
import type {VescParameter} from './configuration';
|
||||
export type Drafts=Record<string,string|boolean>;
|
||||
export function parseDraft(p:VescParameter,draft:string|boolean){
|
||||
if(p.type==='boolean')return {value:draft===true,error:null};
|
||||
if(p.type==='string')return {value:String(draft),error:String(draft).length>(p.max_length??0)?'Слишком длинное значение.':null};
|
||||
const scale=p.type==='number'?(p.editor_scale||1):1;
|
||||
const value=Number(String(draft).replace(',','.'))/scale;
|
||||
const error=String(draft).trim()===''||!Number.isFinite(value)?'Введите число.':
|
||||
p.type!=='number'&&!Number.isInteger(value)?'Введите целое число.':
|
||||
p.type==='enum'&&(value<0||value>=(p.options?.length??0))?'Выберите допустимое значение.':
|
||||
p.type==='bitfield'&&(value<0||value>255)?'Битовая маска должна быть от 0 до 255.':
|
||||
p.type!=='enum'&&p.type!=='bitfield'&&((p.min!==undefined&&value<p.min)||(p.max!==undefined&&value>p.max))?'Значение вне диапазона VESC Tool.':null;
|
||||
return {value,error};
|
||||
}
|
||||
export function initialDraft(p:VescParameter):string|boolean{return p.type==='boolean'?Boolean(p.value):typeof p.value==='number'?String(p.value*(p.type==='number'?(p.editor_scale||1):1)):String(p.value);}
|
||||
export function VescParameterEditor({parameter:p,value,onChange,disabled}:{parameter:VescParameter;value:string|boolean;onChange:(value:string|boolean)=>void;disabled:boolean}){
|
||||
const label=(p.title||p.name)+(p.suffix?' · '+p.suffix:'');
|
||||
if(p.type==='boolean')return <Checker label={label} checked={value===true} onChange={onChange} disabled={disabled}/>;
|
||||
if(p.type==='enum')return <Select label={label} value={String(value)} options={(p.options??[]).map((label,i)=>({label,value:String(i)}))} onChange={onChange} disabled={disabled}/>;
|
||||
const parsed=parseDraft(p,value),scale=p.type==='number'?(p.editor_scale||1):1;
|
||||
return <TextField label={label} value={String(value)} onChange={event=>onChange(event.target.value)} disabled={disabled}
|
||||
inputMode={p.type==='string'?'text':'decimal'} aria-invalid={!!parsed.error}
|
||||
description={parsed.error??(p.min!==undefined&&p.max!==undefined?`${p.min*scale}…${p.max*scale}${p.suffix?' '+p.suffix:''}`:p.name)}/>;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Checker,Description,SettingsCard,TextAreaField,TextField} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {vescStatus} from './model';
|
||||
import {bytesBase64} from './editorFiles';
|
||||
interface Frame {broker_status?:{mode:string;reads:number;pending:number;observed_at:string|null};blocked_codes?:number[];rendered:boolean;png?:string;width?:number;height?:number;observed_at:string;warnings?:string[];error?:string;discarded_commands?:number;qml_id?:string;standalone?:boolean}
|
||||
type Input=Record<string,unknown>;
|
||||
export function VescQmlPreview(props:ReadProps&{source:string;active?:boolean}){
|
||||
const [frame,setFrame]=useState<Frame|null>(null),[busy,setBusy]=useState(false),[inputBusy,setInputBusy]=useState(false),[snapshot,setSnapshot]=useState(false),[broker,setBroker]=useState(false),[text,setText]=useState('');
|
||||
const mounted=useRef(true),running=useRef(false),generation=useRef(0),session=useRef<string|null>(null),pointer=useRef<Input[]>([]);
|
||||
const call=<T,>(action:string,parameters:Record<string,unknown>)=>perform<T>(props.transport,props.device,'vesc.qml.'+action,parameters,30000);
|
||||
const canvas=useRef<HTMLImageElement>(null),queue=useRef<Input[]>([]);
|
||||
const closer=useRef((id:string)=>{void call('close',{qml_id:id}).catch(()=>{});});closer.current=id=>{void call('close',{qml_id:id}).catch(()=>{});};
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;generation.current++;if(session.current)closer.current(session.current);session.current=null;};},[]);
|
||||
useEffect(()=>{const old=session.current;session.current=null;if(old)closer.current(old);setFrame(null);generation.current++;pointer.current=[];queue.current=[];},[props.source,props.device.snapshot.context.session_id,props.active]);
|
||||
const available=props.enabled&&props.device.online&&props.device.verified&&vescStatus(props.device).qml_interactive_supported&&props.active!==false;
|
||||
const inputDisabled=busy||props.blocked||!available;
|
||||
const disabled=inputDisabled||inputBusy;
|
||||
async function run(work:()=>Promise<Frame|null>){
|
||||
if(running.current||disabled)return;
|
||||
const revision=generation.current;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);
|
||||
try{const value=await work();if(mounted.current&&revision===generation.current){setFrame(value);session.current=value?.qml_id??null;}else if(value?.qml_id)closer.current(value.qml_id);}
|
||||
catch(e){if(mounted.current&&revision===generation.current){props.failure(e);const old=session.current;session.current=null;setFrame(null);if(old)closer.current(old);}}
|
||||
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
async function open(){await run(async()=>{
|
||||
const data=new TextEncoder().encode(props.source);if(data.length>120*1024)throw new Error('QML принимает исходный код до 120 КБ.');
|
||||
const sha256=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data))).map(v=>v.toString(16).padStart(2,'0')).join('');
|
||||
const upload=await call<{upload_id:string;chunk_bytes:number}>('begin',{size:data.length,sha256});
|
||||
if(upload.chunk_bytes!==16384)throw new Error('Неподдерживаемый размер фрагмента QML.');
|
||||
for(let offset=0;offset<data.length;offset+=upload.chunk_bytes){if(!mounted.current)return null;await call('chunk',{upload_id:upload.upload_id,offset,data:bytesBase64(data.slice(offset,offset+upload.chunk_bytes))});}
|
||||
return call<Frame>('open',{upload_id:upload.upload_id,snapshot:snapshot||broker,broker});
|
||||
});}
|
||||
function input(events:Input[]){
|
||||
const id=session.current;if(!id||inputDisabled)return;
|
||||
if(queue.current.length+events.length>128){props.failure(new Error('Очередь ввода QML заполнена. Дождитесь ответа приложения.'));return;}
|
||||
queue.current.push(...events);if(running.current)return;
|
||||
const revision=generation.current;running.current=true;setInputBusy(true);
|
||||
void (async()=>{try{
|
||||
do {const batch=queue.current.splice(0,32);const value=await call<Frame>('frame',{qml_id:id,events:batch});
|
||||
if(!mounted.current||revision!==generation.current)return;setFrame(value);
|
||||
}while(queue.current.length&&session.current===id);
|
||||
}catch(e){if(mounted.current&&revision===generation.current){props.failure(e);session.current=null;queue.current=[];setFrame(null);closer.current(id);}}
|
||||
finally{running.current=false;if(mounted.current)setInputBusy(false);}})();
|
||||
}
|
||||
useEffect(()=>{
|
||||
const element=canvas.current;if(!element)return;
|
||||
const wheel=(e:WheelEvent)=>{e.preventDefault();e.stopPropagation();if(inputDisabled)return;input([{kind:'wheel',...coordinates(element,e.clientX,e.clientY),delta:Math.max(-1200,Math.min(1200,Math.round(-e.deltaY)))}]);};
|
||||
element.addEventListener('wheel',wheel,{passive:false});return()=>element.removeEventListener('wheel',wheel);
|
||||
});
|
||||
function coordinates(element:HTMLImageElement,x:number,y:number){const b=element.getBoundingClientRect();return {x:Math.max(0,Math.min(639,(x-b.left)/b.width*640)),y:Math.max(0,Math.min(479,(y-b.top)/b.height*480))};}
|
||||
return <SettingsCard title="QML-интерфейс" description="Откройте интерфейс расширения и выберите источник данных. Чтение с контроллера выполняется при взаимодействии или обновлении кадра.">
|
||||
<Checker label="Использовать снимок данных контроллера" checked={snapshot||broker} onChange={setSnapshot} disabled={disabled||!!session.current||broker}/>
|
||||
<Checker label="Читать данные контроллера через брокер" checked={broker} disabled={disabled||!!session.current||!vescStatus(props.device).qml_broker_supported} onChange={setBroker}/>
|
||||
<Description>{broker?'Доступны показания, параметры мотора и приложения, PPM, ADC, Nunchuk, IMU и BMS по USB. Не более двух чтений за кадр. Фонового опроса нет. Запись, CAN-переадресация, движение и запуск измерений заблокированы.':snapshot?'При открытии однократно читаются конфигурация и показания. Дальше приложение использует этот снимок.':'Интерфейс открывается без чтения данных контроллера. Показания и ответы оборудования отсутствуют.'} Сеанс завершается после минуты без взаимодействия или пяти минут работы.</Description>
|
||||
<div className="sensor-actions"><Button disabled={disabled||!props.source.trim()} loading={busy} onClick={()=>void open()}>{session.current?'Открыть заново':'Открыть QML'}</Button><Button disabled={disabled||!session.current} onClick={()=>input([])}>Обновить кадр</Button><Button disabled={disabled||!session.current} onClick={()=>void run(async()=>{await call('close',{qml_id:session.current});return null;})}>Закрыть QML</Button></div>
|
||||
{frame?.rendered&&frame.png&&<><img ref={canvas} src={`data:image/png;base64,${frame.png}`} width={frame.width} height={frame.height} style={{maxWidth:'100%',height:'auto',display:'block',touchAction:'none'}} tabIndex={0} draggable={false} aria-disabled={inputDisabled} aria-busy={inputBusy} alt="Интерактивный интерфейс QML. Нажатия и ввод работают внутри приложения."
|
||||
onPointerDown={e=>{if(inputDisabled||e.button!==0)return;e.preventDefault();e.currentTarget.focus();e.currentTarget.setPointerCapture(e.pointerId);pointer.current=[{kind:'down',...coordinates(e.currentTarget,e.clientX,e.clientY)}];}}
|
||||
onPointerMove={e=>{if(!pointer.current.length)return;const event={kind:'move',...coordinates(e.currentTarget,e.clientX,e.clientY)};if(pointer.current.length<30)pointer.current.push(event);else pointer.current[pointer.current.length-1]=event;}}
|
||||
onPointerUp={e=>{if(!pointer.current.length)return;const events=[...pointer.current,{kind:'up',...coordinates(e.currentTarget,e.clientX,e.clientY)}];pointer.current=[];input(events);}}
|
||||
onPointerCancel={()=>{pointer.current=[];}}
|
||||
onKeyDown={e=>{if(inputDisabled)return;const keys=['Enter','Tab','Backspace','Delete','ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Home','End','Escape'];if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='a'){e.preventDefault();e.stopPropagation();input([{kind:'key',key:'SelectAll'}]);}else if(keys.includes(e.key)){e.preventDefault();e.stopPropagation();input([{kind:'key',key:e.key}]);}else if(e.key.length===1&&!e.ctrlKey&&!e.metaKey){e.preventDefault();e.stopPropagation();input([{kind:'text',text:e.key}]);}}}/>
|
||||
{!frame.standalone&&!frame.broker_status&&<Description>Снимок данных: {new Date(frame.observed_at).toLocaleString('ru-RU')}.</Description>}
|
||||
{frame.broker_status&&<Description>Чтений: {frame.broker_status.reads} · В очереди: {frame.broker_status.pending}. {frame.broker_status.observed_at?`Последний ответ: ${new Date(frame.broker_status.observed_at).toLocaleString('ru-RU')}.`:'Приложение ещё не запросило данные.'}</Description>}
|
||||
<TextField label="Текст для активного поля QML" value={text} disabled={disabled} onChange={e=>setText(e.target.value)} maxLength={1024}/><Button disabled={disabled||!text} onClick={()=>{input([{kind:'text',text}]);setText('');}}>Ввести текст</Button>
|
||||
</>}
|
||||
{!!frame?.discarded_commands&&<Description>Заблокировано запросов: {frame.discarded_commands}. {frame.blocked_codes?.length?`Коды: ${frame.blocked_codes.join(", ")}. `:""}Они не отправлялись. Запись настроек, запуск программ и управление выполняются в соответствующих разделах VESC.</Description>}
|
||||
{!!frame?.warnings?.length&&<TextAreaField label="Сообщения Qt Quick" value={frame.warnings.join('\n')} rows={5} readOnly/>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import {useEffect,useMemo,useState} from 'react';
|
||||
import {Button,ComparisonTable,Description,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {SampleRecord} from './sampleReview';
|
||||
import {hallEventWindow,reviewRotorHall,type HallEvent} from './rotorHallReview';
|
||||
const number=(n:number|null)=>n===null?'—':n.toLocaleString('ru-RU',{maximumFractionDigits:3});
|
||||
export function VescRotorHallReview({records,from,to,onFocus}:{records:readonly (SampleRecord|null)[];from:number;to:number;onFocus:(window:{from:number;to:number;first:number;second:number})=>void}){
|
||||
const [slot,setSlot]=useState('0'),[page,setPage]=useState(0),[details,setDetails]=useState(false);
|
||||
const present=useMemo(()=>records.flatMap((record,i)=>record?[{record,slot:i,review:reviewRotorHall(record.points,from,to)}]:[]),[records,from,to]);
|
||||
const selected=present.find(p=>p.slot===Number(slot))??present[0];
|
||||
useEffect(()=>setPage(0),[records,from,to,slot]);
|
||||
if(!selected)return null;
|
||||
const {review,record}=selected,columns=present.map(p=>({id:String(p.slot),label:p.slot?'B':'A'}));
|
||||
const focus=(event:HallEvent)=>onFocus(hallEventWindow(record.points,event));
|
||||
const pages=Math.max(1,Math.ceil(review.events.length/10)),currentPage=Math.min(page,pages-1);
|
||||
return <SettingsCard title="Ротор и код Hall · разбор выборки" description="Наблюдения по исходным отсчётам выбранного интервала. Фильтр токов не меняет этот разбор.">
|
||||
<ComparisonTable density="compact" label="Ротор и Холлы" heading="Наблюдение" columns={columns} rows={[
|
||||
{id:'count',label:'Отсчётов',cells:present.map(p=>p.review.count)},
|
||||
{id:'states',label:'Коды 1–6',cells:present.map(p=>p.review.counts.slice(1,7).flatMap((n,i)=>n?[i+1]:[]).join(', ')||'Не наблюдались')},
|
||||
{id:'reserved',label:'Отсчёты 0 / 7',cells:present.map(p=>`${p.review.counts[0]} / ${p.review.counts[7]}`)},
|
||||
{id:'missing',label:'Нет кода Hall',cells:present.map(p=>p.review.missing)},
|
||||
{id:'changes',label:'Смены кода',cells:present.map(p=>p.review.transitions)},
|
||||
{id:'phase',label:'Отсчёты угла',cells:present.map(p=>p.review.phaseCount)},
|
||||
{id:'phase-step',label:'Макс. шаг угла, °',cells:present.map(p=>number(p.review.phaseStep))},
|
||||
{id:'current',label:'Макс. |ток|, А',cells:present.map(p=>number(p.review.peakCurrent))},
|
||||
]}/>
|
||||
<Description>На прошивке 5.02 это преобразованный код Hall, не уровни H1–H3. Разбор не определяет обрыв датчика или заклинивание. Пропуски и делитель частоты могут скрыть переходы; угол FOC не является измерением поворота вала.</Description>
|
||||
{present.some(p=>p.record.complete!==true)&&<Description>Полнота записи не подтверждена; положение пропусков неизвестно.</Description>}
|
||||
<Button variant="ghost" onClick={()=>setDetails(v=>!v)}>{details?'Скрыть подробности разбора':'Подробности разбора'}</Button>
|
||||
{details&&<>
|
||||
<Description>Это смены переданного кода между отсчётами. В штатной 5.02 он получен через таблицу коммутации BLDC; в FOC эта таблица может быть не инициализирована. Коды 0 и 7, изменение нескольких битов или постоянный код не доказывают неисправность. По этому полю нельзя посчитать переключения физических входов Холла.</Description>
|
||||
<Description>На FOC прошивки 5.02 угол — электрическая фаза управления, с шагом около 1,44°. Он не подтверждает поворот вала; для других режимов смысл нужно сверять с прошивкой. Шаг угла — кратчайшая разность соседних отсчётов через 0°; движение более чем на 180° между ними не восстанавливается. Остановка или заклинивание по этой таблице не устанавливаются.</Description>
|
||||
{present.some(p=>p.record.complete!==true)&&<Description>Полнота хотя бы одной записи не подтверждена. Положение потерь в буфере 5.02 неизвестно; время и соседство отсчётов нельзя считать непрерывной картиной события.</Description>}
|
||||
</>}
|
||||
{present.length>1&&<Select label="Подробности выборки" value={String(selected.slot)} onChange={setSlot} options={present.map(p=>({value:String(p.slot),label:p.slot?'B':'A'}))}/>}
|
||||
{details&&<>
|
||||
<ComparisonTable density="compact" label="Распределение кодов Hall" heading="Код" columns={[{id:'count',label:'Отсчётов'},{id:'span',label:'Макс. участок, мс'}]} rows={review.counts.map((n,i)=>({id:String(i),label:String(i),cells:[n,number(n?review.longest[i]:null)]}))}/>
|
||||
<Description>Длина участка измеряется от первого до последнего соседнего отсчёта одного кода. Один отсчёт даёт 0 мс. Это не полное время пребывания ротора в секторе.</Description>
|
||||
{!!review.halfTurns&&<Description>Найдено шагов ровно на 180°: {review.halfTurns}. Направление такого шага неоднозначно.</Description>}
|
||||
</>}
|
||||
<Description>{review.events.length?`Особенностей в интервале: ${review.events.length}. Выберите участок для графиков Холла, угла и тока.`:'В выбранном интервале перечисленные особенности не обнаружены. Это не проверка исправности датчиков или мотора.'}</Description>
|
||||
{!!review.events.length&&<ResourceList aria-label="Участки для просмотра">{review.events.slice(currentPage*10,currentPage*10+10).map((event,i)=><li key={`${currentPage}-${i}`}><ResourceRow title={event.label} description={`${number(event.at)}–${number(event.end)} мс · отсчёты ${event.first+1}–${event.last+1} · макс. |ток| ${number(event.current)} А`} actions={<Button onClick={()=>focus(event)}>Показать участок</Button>}/></li>)}</ResourceList>}
|
||||
{pages>1&&<div className="sensor-actions"><Button disabled={!currentPage} onClick={()=>setPage(currentPage-1)}>Предыдущие</Button><Description>{currentPage+1} / {pages}</Description><Button disabled={currentPage+1>=pages} onClick={()=>setPage(currentPage+1)}>Следующие</Button></div>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import {useEffect,useMemo,useRef,useState} from 'react';
|
||||
import {Button,ComparisonTable,Description,RangeControl,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {LOG_MAX_BYTES,spectrum} from './logAnalysis';
|
||||
import {VescRotorHallReview} from './VescRotorHallReview';
|
||||
import {sampleFields} from './samples';
|
||||
import {SignalPlot} from './SignalPlot';
|
||||
import {defaultSampleFilter,filterCoefficients,filteredSamplePoints,parseSampleRecord,sampleMeasurement,type SampleFilter,type SampleRecord} from './sampleReview';
|
||||
const number=(value:number|null|undefined)=>value==null?'—':value.toLocaleString('ru-RU',{maximumFractionDigits:5});
|
||||
const duration=(record:SampleRecord|null)=>record?.points.at(-1)?.at??0;
|
||||
export function VescSampleAnalysis({live}:{live:SampleRecord|null}){
|
||||
const [records,setRecords]=useState<[SampleRecord|null,SampleRecord|null]>([null,null]),[error,setError]=useState(''),[busy,setBusy]=useState(false);
|
||||
const [signals,setSignals]=useState(['i1','hall']),[from,setFrom]=useState(0),[to,setTo]=useState(0),[cursor1,setCursor1]=useState(0),[cursor2,setCursor2]=useState(0);
|
||||
const [filter,setFilter]=useState<SampleFilter>(defaultSampleFilter),[fft,setFft]=useState(false);
|
||||
const inputs=useRef<(HTMLInputElement|null)[]>([]),revision=useRef(0),expiry=useRef<number[]>([0,0]),day=useRef(new Date().toISOString().slice(0,10));
|
||||
const install=(record:SampleRecord,slot:number)=>{setRecords(old=>{const next:[SampleRecord|null,SampleRecord|null]=[...old];next[slot]=record;return next;});expiry.current[slot]=Date.now()+300000;setFrom(0);setFft(false);};
|
||||
useEffect(()=>{if(live)install(live,0);},[live]);
|
||||
useEffect(()=>{const timer=setInterval(()=>setRecords(old=>{const today=new Date().toISOString().slice(0,10),reset=today!==day.current;day.current=today;const next=old.map((r,i)=>r&&(reset||Date.now()>=expiry.current[i])?null:r) as typeof old;return next.some((r,i)=>r!==old[i])?next:old;}),1000);return()=>{clearInterval(timer);revision.current++;};},[]);
|
||||
const end=Math.max(...records.map(duration));
|
||||
useEffect(()=>{setFrom(0);setTo(end);setCursor1(0);setCursor2(end);},[end,records]);
|
||||
async function open(file:File,slot:number){const request=++revision.current;setBusy(true);setError('');try{
|
||||
if(file.size>LOG_MAX_BYTES)throw new Error('Максимальный размер файла — 4 МиБ.');
|
||||
const record=parseSampleRecord(await file.text(),file.name);if(request===revision.current)install(record,slot);
|
||||
}catch(e){if(request===revision.current)setError(e instanceof Error?e.message:'Не удалось прочитать выборку.');}finally{if(request===revision.current)setBusy(false);}}
|
||||
const present=records.flatMap((r,i)=>r?[{record:r,slot:i}]:[]),coefficients=useMemo(()=>filterCoefficients(filter),[filter]);
|
||||
const traces=useMemo(()=>records.map(r=>r?Object.fromEntries(signals.map(key=>[key,filteredSamplePoints(r.points,key,filter,coefficients)])):null),[records,signals,filter,coefficients]);
|
||||
const fftResult=useMemo(()=>records.map((r,i)=>{if(!r||!fft)return null;if(r.complete===false)return {data:null,error:'FFT отключён: паспорт не подтверждает полный буфер.'};try{
|
||||
const points=traces[i]![signals[0]].map(p=>({at:p.at,values:{[signals[0]]:p.value},gap:p.value===null}));
|
||||
return {data:spectrum(points,signals[0],from,to),error:''};
|
||||
}catch(e){return {data:null,error:e instanceof Error?e.message:'FFT недоступен.'};}}),[records,traces,signals,fft,from,to]);
|
||||
const options=sampleFields.map(([value,label,unit])=>({value,label:(value==='i3'?'Ток фазы 3':label)+(unit?` · ${unit}`:'')}));
|
||||
const setFilterValue=<K extends keyof SampleFilter>(key:K,value:SampleFilter[K])=>setFilter(old=>({...old,[key]:value}));
|
||||
return <><SettingsCard title="Разбор осциллограмм" description="Откройте сохранённые выборки Sample Data или прочитайте полученный буфер. До двух файлов, общая относительная ось времени и измерения выбранного участка." actions={<StatusBadge>Локальный анализ</StatusBadge>}>
|
||||
<div className="sensor-actions">{records.map((r,i)=><div key={i} className="sensor-actions"><input ref={el=>{inputs.current[i]=el;}} hidden type="file" accept=".json,.csv,application/json,text/csv" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void open(file,i);}}/><Button disabled={busy} onClick={()=>inputs.current[i]?.click()}>{r?'Заменить':'Открыть'} выборку {i?'B':'A'}</Button>{r&&<Button disabled={busy} onClick={()=>setRecords(old=>old.map((v,j)=>j===i?null:v) as typeof old)}>Закрыть {i?'B':'A'}</Button>}</div>)}</div>
|
||||
{error&&<Description role="alert">{error}</Description>}
|
||||
<Description>JSON с паспортом Mission Core или CSV Sample Data VESC Tool, до 4 МиБ и 2000 отсчётов на файл. Данные остаются в памяти этого окна не более пяти минут. Импорт ничего не запрашивает у контроллера.</Description>
|
||||
{!!present.length&&<ComparisonTable density="compact" label="Паспорта выборок" heading="Выборка" columns={present.map(({slot})=>({id:String(slot),label:slot?'B':'A'}))} rows={[
|
||||
{id:'file',label:'Источник',cells:present.map(({record:r})=>r.name)},
|
||||
{id:'uuid',label:'UUID из паспорта',cells:present.map(({record:r})=>r.uuid??'Не указан')},
|
||||
{id:'hardware',label:'Аппаратура / прошивка',cells:present.map(({record:r})=>`${r.hardware??'—'} / ${r.firmware??'—'}`)},
|
||||
{id:'capture',label:'Захват',cells:present.map(({record:r})=>r.capture??'Не указан')},
|
||||
{id:'session',label:'USB-сессия',cells:present.map(({record:r})=>r.session??'Не указана')},
|
||||
{id:'state',label:'Полнота',cells:present.map(({record:r})=>r.status)},
|
||||
{id:'size',label:'Отсчёты / длительность',cells:present.map(({record:r})=>`${r.points.length} / ${number(duration(r))} мс`)},
|
||||
{id:'third',label:'Третий фазный ток',cells:present.map(({record:r})=>r.thirdMeasured===null?'Способ получения не указан':r.thirdMeasured?'Измеренный':'Расчётный')},
|
||||
]}/>}
|
||||
{!!present.length&&<Description>Паспорт взят из файла и не удостоверяет текущий подключённый VESC. Время — от начала каждого буфера; две записи не синхронизированы. У неполного буфера 5.02 положение потери неизвестно, поэтому его временная ось приблизительна.</Description>}
|
||||
</SettingsCard>{!!present.length&&<>
|
||||
<SettingsCard title="Сигналы и интервал" description="Выберите до четырёх сигналов. Графики A и B используют одинаковый интервал времени; шкала значений у каждого своя.">
|
||||
{signals.map((key,i)=><Select key={i} label={`Сигнал ${i+1}`} value={key} options={options.filter(o=>o.value===key||!signals.includes(o.value))} onChange={value=>setSignals(old=>old.map((v,j)=>i===j?value:v))}/>)}
|
||||
<div className="sensor-actions"><Button disabled={signals.length>=4} onClick={()=>{const next=options.find(o=>!signals.includes(o.value));if(next)setSignals(old=>[...old,next.value]);}}>Добавить сигнал</Button><Button disabled={signals.length<=1} onClick={()=>setSignals(old=>old.slice(0,-1))}>Убрать последний сигнал</Button></div>
|
||||
<RangeControl label="Начало интервала, мс" min={0} max={end} step={.001} value={from} onChange={v=>{setFrom(Math.min(v,to));setCursor1(Math.max(cursor1,Math.min(v,to)));setCursor2(Math.max(cursor2,Math.min(v,to)));}}/>
|
||||
<RangeControl label="Конец интервала, мс" min={0} max={end} step={.001} value={to} onChange={v=>{setTo(Math.max(v,from));setCursor1(Math.min(cursor1,Math.max(v,from)));setCursor2(Math.min(cursor2,Math.max(v,from)));}}/>
|
||||
</SettingsCard>
|
||||
<VescRotorHallReview records={records} from={from} to={to} onFocus={window=>{setSignals(['hall','phase_deg','current']);setFrom(window.from);setTo(window.to);setCursor1(window.first);setCursor2(window.second);setFft(false);}}/>
|
||||
<SettingsCard title="Фильтр фазных токов" description="Фильтруются только I1, I2 и I3. Исходные отсчёты остаются неизменными; Холлы, угол и общий ток не сглаживаются.">
|
||||
<Select label="Фильтр" value={filter.kind} options={[{value:'none',label:'Без фильтра'},{value:'fir',label:'FIR · VESC Tool'},{value:'mean',label:'Скользящее среднее'}]} onChange={v=>setFilterValue('kind',v as SampleFilter['kind'])}/>
|
||||
{filter.kind!=='none'&&<><Select label="Количество коэффициентов" value={String(filter.bits)} options={Array.from({length:10},(_,i)=>({value:String(i+1),label:String(2**(i+1))}))} onChange={v=>setFilterValue('bits',+v)}/>
|
||||
{filter.kind==='fir'&&<><RangeControl label="Частота среза / частота отсчётов" min={0} max={.5} step={.001} value={filter.cutoff} onChange={v=>setFilterValue('cutoff',v)}/><Select label="Окно Хэмминга" value={String(filter.hamming)} options={[{value:'true',label:'Включено'},{value:'false',label:'Выключено'}]} onChange={v=>setFilterValue('hamming',v==='true')}/></>}
|
||||
<Select label="Компенсация задержки фильтра" value={String(filter.compensate)} options={[{value:'true',label:'Включена'},{value:'false',label:'Выключена'}]} onChange={v=>setFilterValue('compensate',v==='true')}/>
|
||||
<Description>Коэффициенты и смещение соответствуют VESC Tool 7.00. Края без полного окна и неравномерные участки остаются пропусками. Если отсчётов недостаточно для фильтра, уменьшите его длину.</Description>
|
||||
</>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Курсоры измерения" description="Курсоры выбирают ближайший отсчёт без интерполяции. В таблицах указаны фактическое время, разность значений и интервал; за пределами записи и на пропусках значения отсутствуют.">
|
||||
<RangeControl label="Курсор 1, мс" min={from} max={to} step={.001} value={cursor1} onChange={setCursor1}/><RangeControl label="Курсор 2, мс" min={from} max={to} step={.001} value={cursor2} onChange={setCursor2}/>
|
||||
</SettingsCard>
|
||||
{signals.map(key=>{const field=options.find(o=>o.value===key)!;const unit=sampleFields.find(f=>f[0]===key)![2];const measured=present.map(({slot})=>sampleMeasurement(traces[slot]![key],from,to,cursor1,cursor2));return <div className="sensor-content" key={key}>
|
||||
{present.map(({slot})=><SignalPlot key={slot} title={`${slot?'B':'A'} · ${field.label}`} unit={unit} points={traces[slot]![key]} from={from} to={to} xUnit="мс" xScale={1} cursors={[cursor1,cursor2]} step={key==='hall'||key==='commutation'}/>)}
|
||||
<SettingsCard title={`Измерения · ${field.label}`}><ComparisonTable density="compact" label={`Измерения ${field.label}`} heading="Параметр" columns={present.map(({slot})=>({id:String(slot),label:slot?'B':'A'}))} rows={[
|
||||
{id:'count',label:'Отсчётов в интервале',cells:measured.map(m=>m.count)},
|
||||
{id:'min',label:'Минимум',cells:measured.map(m=>number(m.min))},{id:'max',label:'Максимум',cells:measured.map(m=>number(m.max))},
|
||||
...(['hall','commutation','phase_deg'].includes(key)?[]:[{id:'rms',label:'RMS',cells:measured.map(m=>number(m.rms))}]),
|
||||
{id:'first',label:'Курсор 1 · мс / значение',cells:measured.map(m=>m.first?`${number(m.first.at)} / ${number(m.first.value)}`:'—')},
|
||||
{id:'second',label:'Курсор 2 · мс / значение',cells:measured.map(m=>m.second?`${number(m.second.at)} / ${number(m.second.value)}`:'—')},
|
||||
{id:'delta',label:'Δ значения (2 − 1)',cells:measured.map(m=>number(m.delta))},{id:'dt',label:'Δ времени, мс',cells:measured.map(m=>number(m.dt))},
|
||||
]}/></SettingsCard>
|
||||
</div>;})}
|
||||
<SettingsCard title="FFT первого сигнала" description="Окно Ханна, среднее удаляется. Используются последние 32–1024 отсчёта интервала (степень двойки). Для фильтрованных токов выберите участок без краевых пропусков.">
|
||||
<Button onClick={()=>setFft(v=>!v)}>{fft?'Скрыть FFT':'Показать FFT'}</Button>
|
||||
{present.some(({record:r})=>r.complete===null)&&<Description>CSV не содержит подтверждения полноты. Его спектр — анализ представленных строк, а не доказательство отсутствия потерянных пакетов.</Description>}
|
||||
{fft&&present.map(({slot})=>{const result=fftResult[slot];return <Description key={slot}>{slot?'B':'A'} · {result?.error||`${result?.data?.n} отсчётов · частота ${number(result?.data?.rate)} Гц · шаг ${number(result?.data?result.data.rate/result.data.n:null)} Гц · пик ${number(result?.data?.peak.hz)} Гц`}</Description>;})}
|
||||
</SettingsCard>
|
||||
{fftResult.map((r,i)=>r?.data?<SignalPlot key={i} title={`${i?'B':'A'} · Амплитудный спектр`} unit={sampleFields.find(f=>f[0]===signals[0])![2]} points={r.data.bins.map(p=>({at:p.hz,value:p.amplitude}))} from={0} to={r.data.rate/2} xUnit="Гц" xScale={1}/>:null)}
|
||||
</>}</>;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Description,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {vescStatus} from './model';
|
||||
import {downloadText} from './editorFiles';
|
||||
import {VescSampleAnalysis} from './VescSampleAnalysis';
|
||||
import {liveSampleRecord,type SampleRecord} from './sampleReview';
|
||||
import {samplePoints,sampleCsv,sampleStateLabel,type SampleState,type SampleRow} from './samples';
|
||||
export function VescSampleData(props:ReadProps){
|
||||
const [state,setState]=useState<SampleState|null>(null),[rows,setRows]=useState<SampleRow[]>([]),[busy,setBusy]=useState(false);
|
||||
const [mode,setMode]=useState('1'),[count,setCount]=useState('600'),[decimation,setDecimation]=useState('1'),[timeout,setTimeoutValue]=useState('30');
|
||||
const [live,setLive]=useState<SampleRecord|null>(null),[passport,setPassport]=useState('');
|
||||
const generation=useRef(0),running=useRef(false),mounted=useRef(true),expires=useRef(0);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;generation.current++;};},[]);
|
||||
useEffect(()=>{generation.current++;setState(null);setRows([]);setPassport('');setLive(null);},[props.device.snapshot.context.session_id]);
|
||||
useEffect(()=>{const timer=setInterval(()=>{if(expires.current&&Date.now()>=expires.current){setRows([]);setState(null);setPassport('');setLive(null);expires.current=0;}},1000);return()=>clearInterval(timer);},[]);
|
||||
const available=props.enabled&&props.device.online&&props.device.verified&&vescStatus(props.device).sample_data_supported;
|
||||
const disabled=busy||props.blocked||!available,active=state&&['armed','stored_wait','receiving'].includes(state.state);
|
||||
const call=(action:string,p:Record<string,unknown>={})=>perform<SampleState>(props.transport,props.device,'vesc.samples.'+action,p,30000);
|
||||
async function run(action:string,p:Record<string,unknown>={}){
|
||||
if(disabled||running.current)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);const revision=generation.current;
|
||||
try{
|
||||
const value=await call(action,p);if(!mounted.current||revision!==generation.current)return;
|
||||
setState(value);expires.current=Date.now()+Math.max(0,300000-(value.elapsed_ms??0));
|
||||
if(action==='start'||action==='fetch'){setRows([]);setLive(null);setPassport('');}
|
||||
if(action==='read'){
|
||||
const all=[...(value.rows??[])];while(all.length<value.received){
|
||||
if(!mounted.current||revision!==generation.current)return;
|
||||
const page=await call('read',{capture_id:value.capture_id,offset:all.length});
|
||||
if(page.capture_id!==value.capture_id||page.offset!==all.length||!page.rows?.length||page.received!==value.received)throw new Error('Буфер изменился. Прочитайте его заново.');
|
||||
all.push(...page.rows);if(all.length>2000)throw new Error('Размер буфера превышен.');
|
||||
}
|
||||
samplePoints(all);if(mounted.current&&revision===generation.current){setRows(all);setLive(liveSampleRecord('Буфер контроллера',all,value,vescStatus(props.device).identity,props.device.snapshot.context.session_id));setPassport(JSON.stringify({schema:'missioncore.vesc.sample-data/v1',identity:vescStatus(props.device).identity,session:props.device.snapshot.context.session_id,state:value,rows:all},null,2));}
|
||||
}
|
||||
}catch(e){if(mounted.current&&revision===generation.current)props.failure(e);}
|
||||
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
const valid=Number.isInteger(+count)&&+count>=1&&+count<=2000&&Number.isInteger(+decimation)&&+decimation>=1&&+decimation<=255&&Number.isInteger(+timeout)&&+timeout>=2&&+timeout<=120;
|
||||
return <div className="sensor-content"><SettingsCard title="Sample Data · осциллограмма" description="Штатная быстрая выборка фазных токов, напряжений, угла и состояний Холла. Захват не запускает мотор и не меняет его настройки." actions={<StatusBadge>{sampleStateLabel[state?.state??'idle']??state?.state}</StatusBadge>}>
|
||||
<Select label="Режим захвата" value={mode} disabled={disabled||!!active} onChange={setMode} options={[['1','Сейчас'],['2','При запуске мотора'],['3','Триггер: запуск мотора'],['4','Триггер: ошибка контроллера'],['5','Запуск: сохранить в контроллере'],['6','Ошибка: сохранить в контроллере'],['7','Последний буфер контроллера']].map(([value,label])=>({value,label}))}/>
|
||||
<div className="sensor-actions"><TextField label={+mode>=3&&+mode<=6?'Отсчётов до события':'Количество отсчётов'} type="number" min={1} max={2000} value={count} disabled={disabled||!!active||mode==='7'} onChange={e=>setCount(e.target.value)}/><TextField label="Делитель частоты" type="number" min={1} max={255} value={decimation} disabled={disabled||!!active} onChange={e=>setDecimation(e.target.value)}/><TextField label="Ожидание, с" type="number" min={2} max={120} value={timeout} disabled={disabled||!!active} onChange={e=>setTimeoutValue(e.target.value)}/></div>
|
||||
<Description>Прошивка 5.02: до 2000 отсчётов; триггер возвращает весь буфер. Третий фазный ток вычисляется из первых двух. Сырые ADC и повтор отдельных пакетов недоступны. Время рассчитано по частоте в пакетах и указанному делителю.</Description>
|
||||
{mode==='7'&&<Description>Укажите делитель, с которым был записан последний буфер. Контроллер не сообщает его возраст, UUID события и применённый делитель; принадлежность буфера новому событию не подтверждается.</Description>}
|
||||
<div className="sensor-actions"><Button disabled={disabled||!!active||!valid} loading={busy} onClick={()=>void run('start',{mode:+mode,count:+count,decimation:+decimation,timeout_s:+timeout,raw:false})}>{mode==='7'?'Запросить последний буфер':'Начать захват'}</Button><Button disabled={disabled} onClick={()=>void run('status')}>Обновить состояние</Button><Button disabled={disabled||!active} onClick={()=>void run('stop',{capture_id:state!.capture_id})}>Остановить захват</Button>{state?.state==='stored_wait'&&<Button disabled={disabled} onClick={()=>void run('fetch',{capture_id:state.capture_id})}>Запросить сохранённый буфер</Button>}</div>
|
||||
<Description>Захват включается только этой кнопкой. Максимальное ожидание — 120 секунд. Данные хранятся в памяти до пяти минут; экспорт выполняется отдельно. Триггер ошибки срабатывает на ошибку VESC: подзаедание без ошибки само по себе его не включает.</Description>
|
||||
{state&&<Description>{state.received} / {state.expected||'неизвестно'} отсчётов. {state.error??''}{state.state==='incomplete'?' Выборка неполная: разрыв нельзя точно расположить во времени, FFT отключён.':''}</Description>}
|
||||
<Button disabled={disabled||!!active||!state?.received||state.state==='expired'} onClick={()=>void run('read',{capture_id:state!.capture_id,offset:0})}>Показать полученную выборку</Button>
|
||||
</SettingsCard>{!!rows.length&&<SettingsCard title="Экспорт полученной выборки" description="CSV для VESC Tool или JSON с UUID, USB-сессией и состоянием буфера.">
|
||||
<div className="sensor-actions"><Button onClick={()=>downloadText('vesc-sample-data.csv',sampleCsv(rows),'text/csv')}>Скачать CSV</Button><Button onClick={()=>downloadText('vesc-sample-data.json',passport,'application/json')}>Скачать с паспортом выборки</Button></div>
|
||||
</SettingsCard>}<VescSampleAnalysis live={live}/></div>;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useState} from 'react';
|
||||
import {Button,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import {useVescRead,type ReadProps} from './useVescRead';
|
||||
import {vescStatus} from './model';
|
||||
|
||||
const tools=[{value:'adc',label:'Аналоговые входы ADC'},{value:'chuk',label:'Вход Nunchuk'},{value:'imu',label:'Инерциальный модуль IMU'}];
|
||||
const fieldLabels:Record<string,string>={level_1:'ADC 1 · уровень',voltage_1_v:'ADC 1 · напряжение, В',level_2:'ADC 2 · уровень',voltage_2_v:'ADC 2 · напряжение, В',level:'Уровень входа',roll:'Крен, рад',pitch:'Тангаж, рад',yaw:'Курс, рад',accX:'Ускорение X, g',accY:'Ускорение Y, g',accZ:'Ускорение Z, g',gyroX:'Гироскоп X, °/с',gyroY:'Гироскоп Y, °/с',gyroZ:'Гироскоп Z, °/с',magX:'Магнитометр X',magY:'Магнитометр Y',magZ:'Магнитометр Z',q0:'Кватернион W',q1:'Кватернион X',q2:'Кватернион Y',q3:'Кватернион Z',vesc_id:'CAN ID',v_tot:'Напряжение батареи, В',v_charge:'Напряжение зарядки, В',i_in:'Ток батареи, А',i_in_ic:'Ток измерителя, А',ah_cnt:'Счётчик заряда, А·ч',ah_cnt_chg_total:'Всего заряжено, А·ч',ah_cnt_dis_total:'Всего разряжено, А·ч',wh_cnt_chg_total:'Энергия заряда всего, Вт·ч',wh_cnt_dis_total:'Энергия разряда всего, Вт·ч',wh_cnt:'Счётчик энергии, Вт·ч',temp_ic:'Температура измерителя, °C',humidity:'Влажность, %',pressure:'Давление, Па',temp_hum_sensor:'Температура датчика влажности, °C',temp_cells_highest:'Максимальная температура ячеек, °C',soc:'Доля заряда',soh:'Доля остаточной ёмкости',can_id:'CAN ID',data_version:'Версия данных BMS',status:'Статус BMS',v_cells:'Напряжения ячеек, В',temps:'Температуры, °C',is_balancing:'Балансировка ячеек'};
|
||||
interface ToolRead {tool:string;state:'received'|'unsupported'|'no_response';observed_at:string;values:Record<string,unknown>}
|
||||
function display(value:unknown):string {
|
||||
if(Array.isArray(value))return value.length?value.map((v,i)=>`${i+1}: ${display(v)}`).join(' · '):'Не сообщается';
|
||||
if(typeof value==='number')return value.toLocaleString('ru-RU',{maximumFractionDigits:5});
|
||||
if(typeof value==='boolean')return value?'Да':'Нет';
|
||||
return value===null||value===''?'Не сообщается':String(value);
|
||||
}
|
||||
function ToolValues(props:ReadProps&{tool:string}){
|
||||
const read=useVescRead<ToolRead>(props,'vesc.tools.read',vescStatus(props.device).tools_read_supported===true);
|
||||
return <SettingsCard title={tools.find(v=>v.value===props.tool)?.label} description="Снимок данных, декодированный ядром VESC Tool. Поддержка команды прошивкой не означает, что соответствующий модуль физически установлен."
|
||||
actions={<Button disabled={!read.available||props.blocked||read.busy} loading={read.busy} onClick={()=>void read.read({tool:props.tool})}>Прочитать</Button>}>
|
||||
<div className="sensor-content">
|
||||
{!read.value?<Description>Данные ещё не прочитаны.</Description>:read.value.state==='unsupported'?<Description>Эта команда не поддерживается текущей прошивкой.</Description>:read.value.state==='no_response'?<Description>Ответ не получен. Проверьте наличие и подключение модуля.</Description>:<>
|
||||
<Description>Прочитано {new Date(read.value.observed_at).toLocaleString('ru-RU')}. Нулевые значения сами по себе не подтверждают наличие или исправность датчика.</Description>
|
||||
<ResourceList aria-label="Данные периферии VESC">{Object.entries(read.value.values).filter(([key])=>key!=='mask').map(([key,value])=><li key={key}><ResourceRow title={fieldLabels[key]??key} description={display(value)}/></li>)}</ResourceList>
|
||||
</>}
|
||||
</div>
|
||||
</SettingsCard>;
|
||||
}
|
||||
export function VescTools(props:ReadProps){
|
||||
const [tool,setTool]=useState('adc');
|
||||
return <div className="sensor-content"><Select label="Периферия" value={tool} options={tools} onChange={setTool} disabled={props.blocked}/><ToolValues key={tool} {...props} tool={tool}/></div>;
|
||||
}
|
||||
const commands=[['hw_status','Аппаратные сведения'],['faults','История ошибок'],['fault','Текущая ошибка'],['ping','Проверка ответа'],['mem','Память'],['threads','Потоки прошивки'],['rpm','Электрические обороты'],['tacho','Счётчик оборотов'],['volt','Напряжение'],['uptime','Время работы'],['help','Справка прошивки']].map(([value,label])=>({value,label:`${label} · ${value}`}));
|
||||
function TerminalResult(props:ReadProps&{command:string}){
|
||||
const read=useVescRead<{text:string;observed_at:string}>(props,'vesc.terminal.read',vescStatus(props.device).terminal_read_supported===true);
|
||||
return <SettingsCard title="Ответ терминала" description="Диагностические команды читают состояние прошивки. Команды, которые вращают мотор или изменяют устройство, здесь не выполняются."
|
||||
actions={<Button disabled={!read.available||props.blocked||read.busy} loading={read.busy} onClick={()=>void read.read({command:props.command})}>Выполнить чтение</Button>}>
|
||||
<div className="sensor-content">
|
||||
{read.value?<><Description>Прочитано {new Date(read.value.observed_at).toLocaleString('ru-RU')}.</Description><pre className="vesc-diagnostic-output">{read.value.text}</pre></>:<Description>Выберите команду и запросите ответ.</Description>}
|
||||
</div>
|
||||
</SettingsCard>;
|
||||
}
|
||||
export function VescTerminal(props:ReadProps){
|
||||
const [command,setCommand]=useState('hw_status');
|
||||
return <div className="sensor-content"><Select label="Команда диагностики" value={command} options={commands} onChange={setCommand} disabled={props.blocked}/><TerminalResult key={command} {...props} command={command}/></div>;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Icon,IconButton,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import {vescStatus} from './model';
|
||||
import {metrics,traceCsv,traceView,VescTrace,type Metric} from './trends';
|
||||
import {TraceObserver} from './traceObserver';
|
||||
|
||||
const number=(n:number|null)=>n===null?'Нет данных':n.toLocaleString(undefined,{maximumFractionDigits:3});
|
||||
export function VescTrends({device,transport,enabled,active}:SensorDetailProps&{active:boolean}){
|
||||
const identity=vescStatus(device).identity;
|
||||
const trace=useRef(new VescTrace());const [now,setNow]=useState(()=>performance.now());
|
||||
const [paused,setPaused]=useState(false),[expanded,setExpanded]=useState(false);
|
||||
const [metric,setMetric]=useState<Metric>('input_voltage_v'),[windowSeconds,setWindow]=useState('60');
|
||||
const uuid=identity?.uuid??'';
|
||||
useEffect(()=>{
|
||||
if(!active||paused||!enabled||!transport.liveTelemetry||!uuid){
|
||||
trace.current.gap(performance.now());
|
||||
const timer=setInterval(()=>{const at=performance.now();trace.current.prune(at);setNow(at);},1000);
|
||||
return()=>clearInterval(timer);
|
||||
}
|
||||
const observer=new TraceObserver(transport.liveTelemetry,(frame,at,rtt)=>{
|
||||
if(frame)trace.current.accept(frame,device.id,uuid,at,rtt);else trace.current.gap(at);setNow(at);
|
||||
},at=>{trace.current.prune(at);if(at>=trace.current.freshUntil)trace.current.gap(at);setNow(at);});
|
||||
return()=>observer.close();
|
||||
},[active,paused,enabled,transport,device.id,uuid]);
|
||||
// Paused/background views retain only bounded RAM and expire on their next view.
|
||||
useEffect(()=>{if(active){const at=performance.now();trace.current.prune(at);setNow(at);}},[active]);
|
||||
const point=trace.current.points.at(-1);
|
||||
const end=paused?(point?.at??now):now;
|
||||
const plotHeight=expanded?384:180;
|
||||
const view=traceView(trace.current.points,metric,end-Number(windowSeconds)*1000,end,plotHeight);
|
||||
const fresh=active&&!paused&&enabled&&now<trace.current.freshUntil;
|
||||
const selected=metrics.find(([key])=>key===metric)!;
|
||||
const state=!transport.liveTelemetry?'Просмотр недоступен':paused?'Сбор приостановлен':fresh?'Живые данные':'Нет свежих данных';
|
||||
function download(){
|
||||
if(!identity||!trace.current.points.some(p=>p.values))return;
|
||||
const url=URL.createObjectURL(new Blob([traceCsv(trace.current.points,identity)],{type:'text/csv;charset=utf-8'}));
|
||||
const a=document.createElement('a');a.href=url;a.download=`vesc-${uuid.replace(/[^a-fA-F0-9]/g,'').slice(0,24)}-${new Date().toISOString().replaceAll(':','-')}.csv`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||||
}
|
||||
return <div className="sensor-content"><SettingsCard title="Графики показаний" description="Показания приходят из живой телеметрии. Пауза останавливает только сбор графика."
|
||||
actions={<StatusBadge tone={fresh?'success':'neutral'}>{state}</StatusBadge>}>
|
||||
<div className="sensor-actions">
|
||||
<Select label="Величина VESC" value={metric} options={metrics.map(([value,label,unit])=>({value,label:label+(unit?` · ${unit}`:'')}))} onChange={setMetric}/>
|
||||
<Select label="Интервал графика" value={windowSeconds} options={['10','30','60','300'].map(value=>({value,label:value==='300'?'5 минут':`${value} секунд`}))} onChange={setWindow}/>
|
||||
<Button disabled={!transport.liveTelemetry} onClick={()=>{trace.current.gap(performance.now());setPaused(v=>!v);}}> {paused?'Продолжить сбор':'Пауза сбора'}</Button>
|
||||
</div>
|
||||
<div className="vesc-trend-toolbar nodedc-viewport-controls"><IconButton label={expanded?'Свернуть график':'Развернуть график'} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div>
|
||||
<svg className={`vesc-trend-plot${expanded?' vesc-trend-plot--expanded':''}`} viewBox={`0 0 800 ${plotHeight+56}`} role="img" aria-label={`${selected[1]}, ${selected[2]}. ${view.count} измерений. Минимум ${number(view.min)}, максимум ${number(view.max)}. Разрывы означают отсутствие данных.`}>
|
||||
{[0,.5,1].map(f=><g key={f}><line className="vesc-trend-grid" x1="64" x2="780" y1={20+f*plotHeight} y2={20+f*plotHeight}/><text x="56" y={24+f*plotHeight} textAnchor="end">{number(view.high-f*(view.high-view.low))}</text></g>)}
|
||||
{view.segments.map((line,i)=>line.length===1?<circle key={i} className="vesc-trend-point" cx={line[0].x} cy={line[0].y} r="2"/>:<polyline key={i} className="vesc-trend-line" points={line.map(p=>`${p.x},${p.y}`).join(' ')}/>)}
|
||||
<text x="64" y={plotHeight+47}>−{windowSeconds} с</text><text x="780" y={plotHeight+47} textAnchor="end">{paused?'Пауза':'Сейчас'}</text>
|
||||
</svg>
|
||||
{!view.count&&<Description role="status">В выбранном интервале нет измерений этой величины. Отсутствующие значения не заменяются нулями.</Description>}
|
||||
<ResourceList aria-label="Статистика графика"><li><ResourceRow title={selected[1]} description={`${fresh&&point?.values?.[metric]!==undefined?'Текущее':'Последнее в интервале'}: ${number(view.last)} ${selected[2]}`}/></li>
|
||||
<li><ResourceRow title="Выбранный интервал" description={`Минимум: ${number(view.min)} · максимум: ${number(view.max)} · среднее по измерениям: ${number(view.mean)} ${selected[2]} · ${view.count} измерений`}/></li></ResourceList>
|
||||
<Description>Пропуски связи и смена USB-сеанса разделяют линию. Показаны полученные значения контроллера; отключённый температурный датчик может возвращать недостоверную температуру. Мощность питания рассчитана как напряжение × ток, PWM показан в процентах.</Description>
|
||||
</SettingsCard><SettingsCard title="Выгрузка измерений" description="В памяти окна хранятся последние 5 минут, не более 1200 записей. После закрытия окна или переподключения контроллера сбор начинается заново. Данные автоматически истекают через 5 минут. CSV сохраняется только по вашей команде."
|
||||
actions={<><Button disabled={!trace.current.points.some(p=>p.values)} onClick={download}>Скачать CSV</Button><Button disabled={!trace.current.points.length} onClick={()=>{trace.current.clear();setNow(performance.now());}}>Очистить график</Button></>}>
|
||||
<Description>CSV содержит все доступные величины, UUID, время измерения на борту, USB-сеанс и отдельные строки разрывов. Частота отображения — до 2 Гц; короткие события между полученными измерениями могут не попасть в график.</Description>
|
||||
</SettingsCard></div>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export interface BmsTarget {can_id:number;uuid:string;hardware:string;major:number;minor:number;custom_configs?:number;hardware_type:number;test_firmware:number}
|
||||
export interface BmsReading {state:string;observed_at:string;target?:BmsTarget;commands_supported?:boolean;source?:string;values?:Record<string,unknown>}
|
||||
export interface BmsPreview {preview_id:string;expires_in_s:number;target:BmsTarget;command:string}
|
||||
export const bmsCommands=[{value:'charge_enable',label:'Разрешить зарядку'},{value:'charge_disable',label:'Запретить зарядку'},
|
||||
{value:'balance_enable',label:'Разрешить балансировку'},{value:'balance_disable',label:'Остановить балансировку'},
|
||||
{value:'reset_ah',label:'Сбросить счётчик А·ч'},{value:'reset_wh',label:'Сбросить счётчик Вт·ч'},{value:'zero_current',label:'Калибровать ноль тока'}];
|
||||
export function bmsNumber(v:unknown,digits=3,scale=1):string {
|
||||
return typeof v==='number'&&Number.isFinite(v)?(v*scale).toLocaleString('ru-RU',{maximumFractionDigits:digits}):'Не сообщается';
|
||||
}
|
||||
export function bmsCells(values:Record<string,unknown>){
|
||||
const cells=Array.isArray(values.v_cells)?values.v_cells.slice(0,96):[];
|
||||
const balancing=Array.isArray(values.is_balancing)?values.is_balancing:[];
|
||||
return cells.map((v,index)=>({index,voltage:typeof v==='number'&&Number.isFinite(v)?v:null,
|
||||
balancing:typeof balancing[index]==='boolean'?balancing[index]:null}));
|
||||
}
|
||||
export function bmsCellSummary(values:Record<string,unknown>){
|
||||
const cells=bmsCells(values),valid=cells.map(v=>v.voltage).filter((v):v is number=>v!==null);
|
||||
if(!cells.length||valid.length!==cells.length)return null;
|
||||
const min=Math.min(...valid),max=Math.max(...valid);return {min,max,spreadMv:(max-min)*1000};
|
||||
}
|
||||
export function bmsTemperature(v:unknown){return typeof v==='number'&&v>-280?bmsNumber(v,1)+' °C':'Не сообщается';}
|
||||
export function bmsCanOptions(ids:unknown){return Array.isArray(ids)?Array.from(new Set(ids.filter((n):n is number=>Number.isInteger(n)&&n>=0&&n<=253))).sort((a,b)=>a-b).map(n=>({value:String(n),label:`CAN ${n}`})):[];}
|
||||
@@ -0,0 +1,34 @@
|
||||
export interface VescParameter {
|
||||
name:string;title:string;description:string;suffix:string;transmittable:boolean;
|
||||
editor_scale:number;type:'number'|'integer'|'bitfield'|'enum'|'boolean'|'string'|'undefined';
|
||||
value:number|string|boolean;min?:number;max?:number;step?:number;decimals?:number;options?:string[];max_length?:number;
|
||||
}
|
||||
export interface VescConfig {
|
||||
parameters:VescParameter[];groups:{name:string;subgroups:{name:string;parameters:string[]}[]}[];
|
||||
xml:string;packet_sha256:string;signature:number;
|
||||
}
|
||||
export interface ConfigurationRead {observed_at:string;configuration:{motor:VescConfig;application:VescConfig}}
|
||||
const names:Record<string,string>={general:'Общие',bldc:'BLDC',dc:'DC',foc:'FOC',pid:'Регуляторы PID',
|
||||
'pid controllers':'Регуляторы PID','additional info':'Дополнительные сведения',current:'Ток',voltage:'Напряжение',rpm:'Обороты',wattage:'Мощность',temperature:'Температура',advanced:'Дополнительные',sensorless:'Без датчиков',sensors:'Датчики','hall sensors':'Датчики Холла',encoder:'Энкодер',hfi:'HFI',setup:'Установка',quality:'Качество',mapping:'Сопоставление входов','throttle curve':'Кривая газа','vesc remote':'VESC Remote',balance:'Балансировка',tune:'Регулировка',startup:'Запуск',tiltback:'Наклон',fault:'Ошибки','multi esc':'Несколько контроллеров',bms:'BMS',
|
||||
additional_info:'Дополнительные сведения',ppm:'PPM',adc:'ADC',uart:'UART',nunchuk:'VESC Remote',nrf:'NRF',
|
||||
pas:'PAS',imu:'IMU',gpd:'GPDrive',experiments:'Эксперименты'};
|
||||
export function groupLabel(name:string){return names[name.toLowerCase()]??name;}
|
||||
export function parameterValue(parameter:VescParameter):string{
|
||||
const value=parameter.value;
|
||||
if(parameter.type==='enum')return parameter.options?.[Number(value)]??String(value);
|
||||
if(typeof value==='boolean')return value?'Включено':'Выключено';
|
||||
if(typeof value==='number'){
|
||||
const scale=Number.isFinite(parameter.editor_scale)&¶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]:[];});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Configuration travels on the paced management lane. Its bounded request
|
||||
// budget includes delivery, native read/write and verified result delivery.
|
||||
// This does not renew a drive lease or retry an unconfirmed flash write.
|
||||
export const CONFIGURATION_OPERATION_TIMEOUT_MS=180000;
|
||||
@@ -0,0 +1,29 @@
|
||||
import type {DriveProfile} from './model';
|
||||
export type UsbRoute={kind:'usb';uuid:string};
|
||||
export type CanRoute={kind:'can';uuid:string;adapter_id:string;channel:number;can_id:number;bitrate:number};
|
||||
export type ControlRoute=UsbRoute|CanRoute;
|
||||
export interface ControlTransportProfile {schema:'missioncore.vesc.control-transport/v1';revision:number;routes:Record<string,ControlRoute>}
|
||||
export interface ControlEndpoint {device_id:string;uuid:string;route:ControlRoute;verified:boolean;session_id:string}
|
||||
export interface ControlAdapter {id:string;label:string;online:boolean}
|
||||
export const controlBitrates=[125000,250000,500000,1000000];
|
||||
export function transportMode(routes:Record<string,ControlRoute>):'usb'|'can'|'mixed'{
|
||||
const kinds=new Set(Object.values(routes).map(r=>r.kind));
|
||||
return kinds.size===1?(kinds.has('can')?'can':'usb'):'mixed';
|
||||
}
|
||||
export function routeError(routes:Record<string,ControlRoute>,drive:DriveProfile):string|null{
|
||||
const ids=Object.values(drive.bindings).map(b=>b.device_id);
|
||||
if(!ids.length||ids.length!==Object.keys(routes).length)return 'Назначьте все моторы привода.';
|
||||
const addresses=new Set<string>(),speeds=new Map<string,number>();
|
||||
for(const b of Object.values(drive.bindings)){
|
||||
const r=routes[b.device_id];
|
||||
if(!r||r.uuid!==b.uuid)return 'Назначение мотора изменилось. Обновите настройки.';
|
||||
if(r.kind==='can'){
|
||||
if(!/^usbcan_[a-f0-9]{32}$/.test(r.adapter_id)||![0,1].includes(r.channel)||!Number.isInteger(r.can_id)||r.can_id<0||r.can_id>254||!controlBitrates.includes(r.bitrate))return 'Укажите адаптер, канал, CAN ID от 0 до 254 и скорость.';
|
||||
const bus=`${r.adapter_id}:${r.channel}`,address=`${bus}:${r.can_id}`;
|
||||
if(addresses.has(address))return 'Один CAN-адрес назначен нескольким моторам.';
|
||||
if(speeds.has(bus)&&speeds.get(bus)!==r.bitrate)return 'На одном CAN-канале нужна одинаковая скорость.';
|
||||
addresses.add(address);speeds.set(bus,r.bitrate);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Projection of the original terminal reports. Never guesses missing fields. */
|
||||
export interface DiagnosticRead {
|
||||
device_id:string; identity:{uuid:string;version:string;hardware:string}; observed_at:string;
|
||||
usb:Record<string,string|null>; reports:Record<string,{command:string;text:string;completion:string}>;
|
||||
}
|
||||
export interface FaultEntry {code:string;fields:Record<string,string>}
|
||||
export interface DiagnosticSnapshot {
|
||||
read:DiagnosticRead; session:string; received:number; monotonic:number;
|
||||
configEvents:number|null; writeTimeouts:number|null; offsets:number[]|null;
|
||||
faults:{state:'none'|'reported'|'unknown';entries:FaultEntry[]}; identityMatches:boolean;
|
||||
}
|
||||
const LIMIT=64*1024;
|
||||
const MAX_AGE=300000;
|
||||
function unique(text:string,label:string):string|null {
|
||||
const values=text.split(/\r?\n/).map(line=>line.match(/^\s*([^:]+?)\s*:\s*(.*?)\s*$/)).filter(row=>row?.[1]===label);
|
||||
return values.length===1?values[0]![2]:null;
|
||||
}
|
||||
function counter(text:string,label:string):number|null {
|
||||
const v=unique(text,label);if(v===null||!/^\d{1,10}$/.test(v))return null;
|
||||
const n=Number(v);return n<=0xffffffff?n:null;
|
||||
}
|
||||
export function parseFaults(text:string):DiagnosticSnapshot['faults'] {
|
||||
if(text.length>LIMIT)return {state:'unknown',entries:[]};
|
||||
const entries:FaultEntry[]=[];let current:FaultEntry|null=null;
|
||||
for(const line of text.split(/\r?\n/)){
|
||||
const match=line.match(/^\s*([^:]+?)\s*:\s*(.*?)\s*$/);if(!match)continue;
|
||||
const [,key,value]=match;
|
||||
if(key==='Fault'){
|
||||
if(!/^FAULT_CODE_[A-Z0-9_]{1,80}$/.test(value)||entries.length>=64)return {state:'unknown',entries:[]};
|
||||
current={code:value,fields:Object.create(null) as Record<string,string>};entries.push(current);
|
||||
}else if(current&&key.length<=80&&value.length<=256){current.fields[key]=value;}
|
||||
}
|
||||
const none=text.trim()==='No faults registered since startup';
|
||||
return {state:entries.length?'reported':none?'none':'unknown',entries};
|
||||
}
|
||||
export function diagnosticSnapshot(read:DiagnosticRead,session:string,received=Date.now(),monotonic=performance.now()):DiagnosticSnapshot {
|
||||
if(!read||typeof read.observed_at!=='string'||!Number.isFinite(Date.parse(read.observed_at))||!read.identity||!read.device_id||!session||!read.usb||!read.reports)throw new Error('Неполный ответ диагностики.');
|
||||
for(const name of ['hw_status','faults']){
|
||||
const report=read.reports[name];if(!report||report.command!==name||typeof report.text!=='string'||report.text.length>LIMIT)throw new Error('Неполный или слишком большой ответ диагностики.');
|
||||
}
|
||||
const text=read.reports.hw_status.text,uuid=unique(text,'UUID')?.replace(/\s/g,'').toLowerCase();
|
||||
const identityMatches=!!uuid&&/^[0-9a-f]{24}$/.test(uuid)&&uuid===read.identity.uuid.toLowerCase();
|
||||
const rawOffsets=unique(text,'FOC Current Offsets');
|
||||
const offsets=rawOffsets&&/^\d{1,6}\s+\d{1,6}\s+\d{1,6}$/.test(rawOffsets)?rawOffsets.split(/\s+/).map(Number):null;
|
||||
return {read,session,received,monotonic,identityMatches,configEvents:counter(text,'USB config events'),writeTimeouts:counter(text,'USB write timeouts'),offsets,faults:parseFaults(read.reports.faults.text)};
|
||||
}
|
||||
export function diagnosticExpired(snapshot:DiagnosticSnapshot,wall=Date.now(),mono=performance.now()):boolean {
|
||||
return wall<snapshot.received||mono<snapshot.monotonic||mono-snapshot.monotonic>=MAX_AGE||wall-snapshot.received>=MAX_AGE||new Date(wall).toISOString().slice(0,10)!==new Date(snapshot.received).toISOString().slice(0,10);
|
||||
}
|
||||
export function compareDiagnostics(before:DiagnosticSnapshot,after:DiagnosticSnapshot):{reason:string|null;configEvents:number|null;writeTimeouts:number|null} {
|
||||
let reason:string|null=null;
|
||||
if(!before.identityMatches||!after.identityMatches)reason='UUID в ответе hw_status не подтверждён.';
|
||||
else if(before.read.device_id!==after.read.device_id||before.read.identity.uuid.toLowerCase()!==after.read.identity.uuid.toLowerCase())reason='Выбраны разные контроллеры.';
|
||||
else if(before.session!==after.session)reason='USB-сеанс изменился.';
|
||||
else if(before.read.identity.version!==after.read.identity.version||before.read.identity.hardware!==after.read.identity.hardware)reason='Изменилась прошивка или аппаратный профиль.';
|
||||
else if(after.monotonic<=before.monotonic||Date.parse(after.read.observed_at)<=Date.parse(before.read.observed_at))reason='Нужен более поздний снимок.';
|
||||
else if(diagnosticExpired(before,after.received,after.monotonic))reason='Срок сравнения истёк.';
|
||||
else if(([['configEvents'],['writeTimeouts']] as const).some(([key])=>before[key]!==null&&after[key]!==null&&after[key]!<before[key]!))reason='Счётчик уменьшился: возможен сброс или переполнение. Разность не вычисляется.';
|
||||
const delta=(key:'configEvents'|'writeTimeouts')=>reason||before[key]===null||after[key]===null?null:after[key]!-before[key]!;
|
||||
return {reason,configEvents:delta('configEvents'),writeTimeouts:delta('writeTimeouts')};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export function plainDescription(value:string){
|
||||
const doc=new DOMParser().parseFromString(value,'text/html');doc.querySelectorAll('script,style,img,iframe').forEach(n=>n.remove());doc.querySelectorAll('br,p,li').forEach(n=>n.append(' '));return doc.body.textContent?.replace(/\s+/g,' ').trim()??'';
|
||||
}
|
||||
export function downloadText(name:string,text:string,type='text/plain'){
|
||||
const url=URL.createObjectURL(new Blob([text],{type})),link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||||
}
|
||||
export interface CodeProject {kind:'lisp'|'qml';source:string;imports:Record<string,string>;fullscreen:boolean}
|
||||
export function validateProject(value:unknown,kind:'lisp'|'qml'):CodeProject{
|
||||
if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Не удалось прочитать проект.');
|
||||
const p=value as CodeProject;
|
||||
if(p.kind!==kind||typeof p.source!=='string'||typeof p.fullscreen!=='boolean'||!p.imports||typeof p.imports!=='object'||Array.isArray(p.imports))throw new Error('Тип или содержимое проекта не подходит.');
|
||||
if(new TextEncoder().encode(p.source).length>120*1024||p.source.includes('\0')||Object.keys(p.imports).length>32)throw new Error('Проект превышает ограничения VESC.');
|
||||
let total=new TextEncoder().encode(p.source).length;
|
||||
for(const [name,bytes] of Object.entries(p.imports)){
|
||||
if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$/.test(name)||typeof bytes!=='string'||bytes.length>164000)throw new Error('Недопустимое вложение проекта.');
|
||||
let raw:string;try{raw=atob(bytes);}catch{throw new Error('Повреждено вложение проекта.');}if(btoa(raw)!==bytes)throw new Error('Некорректное кодирование вложения.');total+=raw.length;
|
||||
}
|
||||
if(total>120*1024||(kind==='qml'&&Object.keys(p.imports).length))throw new Error('Вложения превышают ограничения выбранного формата.');
|
||||
return {kind,source:p.source,imports:{...p.imports},fullscreen:p.fullscreen};
|
||||
}
|
||||
export function bytesBase64(bytes:Uint8Array){let s='';for(const byte of bytes)s+=String.fromCharCode(byte);return btoa(s);}
|
||||
@@ -0,0 +1,18 @@
|
||||
export interface FirmwareImage {name:string;kind:string;bytes:number;sha256:string;hardware:string;target_version:string;source_bytes?:number;source_sha256?:string;format?:string;base_address?:number;hardware_limits?:boolean;swd?:SwdTarget;can_id?:number}
|
||||
export interface FirmwarePreview {transfer_id:string;expires_in_s:number;image:FirmwareImage;identity:{uuid:string}}
|
||||
export interface FirmwareCatalog {repository:string;commit:string;items:{id:string;name:string;version:string;hardware_limits:boolean;bytes:number}[]}
|
||||
export function firmwareFileError(file:{name:string;size:number},kind:string,formats:readonly string[]):string|null {
|
||||
const format=file.name.split('.').at(-1)?.toLowerCase();
|
||||
if(!format||!formats.includes(format))return 'Выберите поддерживаемый файл BIN или Intel HEX.';
|
||||
const limit=format==='hex'?8*1024*1024:kind==='bootloader'?65536:2*1024*1024;
|
||||
return file.size<(format==='hex'?32:256)||file.size>limit?'Размер файла выходит за допустимые пределы: BIN до 2 МиБ, загрузчик BIN до 64 КиБ, HEX до 8 МиБ.':null;
|
||||
}
|
||||
export const firmwareVariant=(image:FirmwareCatalog['items'][number])=>`${image.version} · ${image.hardware_limits?'Стандартные аппаратные пределы':'Без аппаратных пределов'} · ${image.name}`;
|
||||
|
||||
export interface CanFirmwareTarget {can_id:number;uuid:string;hardware:string;major:number;minor:number;hardware_type:number;test_firmware:number;custom_configs:number}
|
||||
export interface SwdTarget {target_code:number;pins:string;address:number;flash_bytes:number}
|
||||
export const swdTargets=[
|
||||
[1,'STM32F40x'],[2,'NRF51822 · 128K / 16K'],[3,'NRF51822 · 256K / 16K'],[4,'NRF51822 · 256K / 32K'],
|
||||
[5,'NRF52832 · 256K / 32K'],[6,'NRF52832 · 256K / 64K'],[7,'NRF52832 · 512K / 64K'],[8,'NRF52840 · 1M / 256K'],
|
||||
[9,'STM32F30x'],[10,'STM32L47x'],[11,'STM32G43'],[12,'STM32G47'],[13,'STM32G49']
|
||||
].map(([value,label])=>({value:String(value),label:String(label)}));
|
||||
@@ -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[]};
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/** Bounded, local-only CSV analysis. Formats follow pinned Tool 7.00
|
||||
* VescInterface::openRtLogFile and PageLogAnalysis::openLog/saveCsv. */
|
||||
export const LOG_MAX_BYTES=4*1024*1024,LOG_MAX_ROWS=20000,LOG_MAX_COLUMNS=96;
|
||||
export interface LogColumn {key:string;label:string;unit:string}
|
||||
export interface LogPoint {at:number;values:Record<string,number|null>;gap:boolean}
|
||||
export interface VescLog {format:string;columns:LogColumn[];points:LogPoint[];duration:number;uuid:string|null;hardware:string|null;firmware:string|null}
|
||||
const raw:Record<string,[string,string]>={input_voltage:['Напряжение питания','В'],temp_mos_max:['Температура контроллера','°C'],temp_motor:['Температура мотора','°C'],current_motor:['Ток мотора','А'],current_in:['Ток питания','А'],erpm:['Электрические обороты','ERPM'],duty_cycle:['Заполнение PWM','%'],d_axis_current:['Ток FOC d','А'],q_axis_current:['Ток FOC q','А'],d_axis_voltage:['Напряжение FOC d','В'],q_axis_voltage:['Напряжение FOC q','В'],amp_hours_used:['Расход заряда','А·ч'],amp_hours_charged:['Возвращённый заряд','А·ч'],watt_hours_used:['Расход энергии','Вт·ч'],watt_hours_charged:['Возвращённая энергия','Вт·ч'],encoder_position:['Положение ротора','°'],fault_code:['Код ошибки','']};
|
||||
const fail=(message:string):never=>{throw new Error(message);};
|
||||
export function csvRecords(text:string,delimiter:string):string[][] {
|
||||
const records:string[][]=[];let row:string[]=[],cell='',quoted=false,closed=false;
|
||||
function field(){row.push(cell);cell='';closed=false;if(row.length>LOG_MAX_COLUMNS)fail('Слишком много колонок журнала.');}
|
||||
function record(){field();if(row.some(v=>v!==''))records.push(row);row=[];if(records.length>LOG_MAX_ROWS+1)fail('Журнал превышает 20 000 строк.');}
|
||||
for(let i=0;i<text.length;i++){
|
||||
const ch=text[i];
|
||||
if(quoted){if(ch==='"'){if(text[i+1]==='"'){cell+='"';i++;}else{quoted=false;closed=true;}}else cell+=ch;}
|
||||
else if(ch===delimiter)field();
|
||||
else if(ch==='\n'||ch==='\r'){if(ch==='\r'&&text[i+1]==='\n')i++;record();}
|
||||
else if(ch==='"'&&!cell&&!closed)quoted=true;
|
||||
else if(closed)fail('Некорректные кавычки CSV.');
|
||||
else cell+=ch;
|
||||
if(cell.length>4096)fail('Поле журнала слишком длинное.');
|
||||
}
|
||||
if(quoted)fail('Незакрытые кавычки CSV.');
|
||||
if(cell||row.length||closed)record();return records;
|
||||
}
|
||||
const numeric=(text:string,line:number):number|null=>{
|
||||
if(text.trim()==='')return null;
|
||||
if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(text.trim()))return fail(`Нечисловое значение в строке ${line}.`);
|
||||
const n=Number(text);if(!Number.isFinite(n)||Math.abs(n)>1e15)fail(`Значение вне диапазона в строке ${line}.`);return n;
|
||||
};
|
||||
export function parseVescLog(source:string):VescLog {
|
||||
if(source.length>LOG_MAX_BYTES||new TextEncoder().encode(source).length>LOG_MAX_BYTES)fail('Максимальный размер CSV — 4 МиБ.');
|
||||
const text=source.replace(/^\uFEFF/,'');
|
||||
const first=text.split(/\r?\n/,1)[0];
|
||||
const delimiter=first.includes(';')?';':',';
|
||||
const records=csvRecords(text,delimiter);
|
||||
if(records.length<2)fail('В журнале нет измерений.');
|
||||
// Native Tool logs terminate every row with a semicolon.
|
||||
if(records.every(row=>row.at(-1)===''))records.forEach(row=>row.pop());
|
||||
const header=records[0];if(new Set(header).size!==header.length||header.some(h=>!h))fail('Пустые или повторяющиеся заголовки CSV.');
|
||||
if(header[0]==='T')return parseSampleCsv(records);
|
||||
const core=header[0]==='plot_elapsed_s',rt=header[0]==='ms_today',rich=!core&&!rt&&header[0].includes(':');
|
||||
if(!core&&!rt&&!rich)fail('Поддерживаются CSV Mission Core и журналы VESC Tool.');
|
||||
const meta=header.map(h=>h.split(':'));
|
||||
const time=core||rt?0:meta.findIndex(h=>h[0]==='t_day');
|
||||
const timeIndex=time>=0?time:meta.findIndex(h=>h[5]==='1');
|
||||
if(timeIndex<0)fail('В журнале не указана временная колонка.');
|
||||
if(rich&&!['s','ms','сек','с',''].includes(meta[timeIndex][2]??''))fail('Единица временной колонки должна быть s или ms.');
|
||||
const timeScale=rt||(rich&&meta[timeIndex][2]==='ms')?1:1000;
|
||||
const index=(key:string)=>header.indexOf(key);
|
||||
const stateIndex=index('state'),sessionIndex=index('usb_session'),sourceIndex=index('source_instance'),uuidIndex=index('uuid');
|
||||
if(core&&[stateIndex,sessionIndex,sourceIndex,uuidIndex,index('sample_utc')].some(v=>v<0))fail('В CSV Mission Core отсутствуют сведения об источнике.');
|
||||
const columns:LogColumn[]=[],indices:number[]=[];
|
||||
header.forEach((h,i)=>{
|
||||
if(i===timeIndex||core&&!h.includes(' ['))return;
|
||||
const parts=meta[i],key=rich?parts[0]:h;
|
||||
if(rich&&parts[5]==='1')return;
|
||||
const match=core?/^(.*) \[(.*)\]$/.exec(h):null;
|
||||
columns.push({key,label:rich?parts[1]||key:match?.[1]??raw[key]?.[0]??key,unit:rich?parts[2]??'':match?.[2]??raw[key]?.[1]??''});indices.push(i);
|
||||
});
|
||||
if(!columns.length||new Set(columns.map(c=>c.key)).size!==columns.length)fail('Журнал не содержит однозначных числовых колонок.');
|
||||
const identities=new Set<string>(),canIds=new Set<string>();let session='',previous=-Infinity,offset=0,start:number|undefined;
|
||||
const points:LogPoint[]=[];
|
||||
for(let i=1;i<records.length;i++){
|
||||
const row=records[i];if(row.length!==header.length)fail(`Число колонок изменилось в строке ${i+1}.`);
|
||||
const clock=numeric(row[timeIndex],i+1);if(clock===null||clock<0)fail(`Нет времени измерения в строке ${i+1}.`);
|
||||
if(rt&&clock!>=86400000)fail('Время ms_today выходит за пределы суток.');
|
||||
let at=clock!*timeScale+offset,rollover=false;
|
||||
if(at<previous){if(rt&&previous-offset>18*3600000&&clock!<6*3600000){offset+=86400000;at+=86400000;rollover=true;}else fail(`Время идёт назад в строке ${i+1}.`);}
|
||||
if(start===undefined)start=at;
|
||||
const identity=core?row[uuidIndex]:'';if(identity)identities.add(identity.toLowerCase());
|
||||
const canIndex=index('vesc_id');if(rt&&canIndex>=0)canIds.add(row[canIndex]);
|
||||
if(identities.size>1||canIds.size>1)fail('Журнал содержит разные контроллеры. Выберите журнал одного VESC.');
|
||||
const nextSession=core?row[sourceIndex]+'/'+row[sessionIndex]:'';
|
||||
if(core&&!['sample','gap'].includes(row[stateIndex]))fail(`Неизвестное состояние строки ${i+1}.`);
|
||||
const gap=core&&row[stateIndex]==='gap';
|
||||
if(rollover||(session&&session!==nextSession))points.push({at:at-start!,values:{},gap:true});
|
||||
const values:Record<string,number|null>={};
|
||||
columns.forEach((column,c)=>{let value=numeric(row[indices[c]],i+1);if(rt&&column.key==='duty_cycle'&&value!==null)value*=100;values[column.key]=gap?null:value;});
|
||||
points.push({at:at-start!,values,gap});session=nextSession;previous=at;
|
||||
}
|
||||
if(!points.some(p=>Object.values(p.values).some(v=>v!==null)))fail('В журнале нет числовых измерений.');
|
||||
const unique=(key:string)=>{const n=index(key);if(n<0)return null;const values=new Set(records.slice(1).map(row=>row[n]).filter(Boolean));return values.size===1?[...values][0]:null;};
|
||||
return {format:core?'Mission Core':rt?'VESC Tool · RT':'VESC Tool · Log Analysis',columns,points,duration:points.at(-1)!.at,uuid:unique('uuid'),hardware:unique('hardware'),firmware:unique('firmware')};
|
||||
}
|
||||
function parseSampleCsv(records:string[][]):VescLog {
|
||||
const expected=['T','I1','I2','I3','V1','V2','V3','I_tot','V_zero','Phase'];
|
||||
const header=records[0];if(expected.some((key,i)=>header[i]!==key)||header.slice(10).some(key=>!['Hall','Commutation','F_sw'].includes(key)))fail('Неизвестные колонки Sample Data.');
|
||||
if(records.length>2001)fail('Sample Data превышает 2000 отсчётов.');
|
||||
const labels:Record<string,[string,string]>={I1:['Ток фазы 1','А'],I2:['Ток фазы 2','А'],I3:['Ток фазы 3','А'],V1:['Напряжение фазы 1','В'],V2:['Напряжение фазы 2','В'],V3:['Напряжение фазы 3','В'],I_tot:['Ток мотора','А'],V_zero:['Нулевая точка','В'],Phase:['Угол фазы (электрический)','°'],Hall:['Состояние Холла',''],Commutation:['Шаг коммутации',''],F_sw:['Частота до делителя','Гц']};
|
||||
const columns=header.slice(1).map(key=>({key,label:labels[key][0],unit:labels[key][1]}));
|
||||
let previous=-1,start:number|undefined;
|
||||
const points=records.slice(1).map((row,i)=>{
|
||||
// Tool 7.00 adds a trailing delimiter to data rows, but not the header.
|
||||
if(row.length===header.length+1&&row.at(-1)==='')row=row.slice(0,-1);
|
||||
if(row.length!==header.length)fail(`Число колонок изменилось в строке ${i+2}.`);
|
||||
const seconds=numeric(row[0],i+2);if(seconds===null||seconds<0||seconds<=previous)return fail('Неверное время Sample Data.');
|
||||
start??=seconds;previous=seconds;
|
||||
return {at:(seconds-start)*1000,values:Object.fromEntries(columns.map((c,j)=>[c.key,numeric(row[j+1],i+2)])),gap:false};
|
||||
});
|
||||
return {format:'VESC Tool · Sample Data',columns,points,duration:points.at(-1)!.at,uuid:null,hardware:null,firmware:null};
|
||||
}
|
||||
export function spectrum(points:readonly LogPoint[],key:string,from:number,to:number){
|
||||
const selected=points.filter(p=>p.at>=from&&p.at<=to);
|
||||
if(selected.length<32)fail('Для спектра нужно не менее 32 измерений.');
|
||||
const n=2**Math.floor(Math.log2(Math.min(selected.length,4096))),data=selected.slice(-n);
|
||||
if(data.some(p=>p.gap||p.values[key]===null||p.values[key]===undefined))fail('В выбранном участке есть пропуски. Выберите непрерывный интервал.');
|
||||
const dt=(data.at(-1)!.at-data[0].at)/(n-1);
|
||||
if(!(dt>0)||data.some((p,i)=>i>0&&Math.abs(p.at-data[i-1].at-dt)>dt*.01))fail('Шаг времени неравномерен. Спектр требует равномерных измерений (допуск 1%).');
|
||||
const real=new Float64Array(n),imag=new Float64Array(n);
|
||||
const mean=data.reduce((sum,p)=>sum+p.values[key]!/n,0);let gain=0;
|
||||
for(let i=0;i<n;i++){const w=.5*(1-Math.cos(2*Math.PI*i/(n-1)));gain+=w;real[i]=(data[i].values[key]!-mean)*w;}
|
||||
for(let i=1,j=0;i<n;i++){let bit=n>>1;for(;j&bit;bit>>=1)j^=bit;j^=bit;if(i<j)[real[i],real[j]]=[real[j],real[i]];}
|
||||
for(let length=2;length<=n;length*=2){const angle=-2*Math.PI/length;
|
||||
for(let start=0;start<n;start+=length)for(let j=0;j<length/2;j++){
|
||||
const a=start+j,b=a+length/2,c=Math.cos(angle*j),s=Math.sin(angle*j),r=real[b]*c-imag[b]*s,im=real[b]*s+imag[b]*c;
|
||||
real[b]=real[a]-r;imag[b]=imag[a]-im;real[a]+=r;imag[a]+=im;
|
||||
}
|
||||
}
|
||||
const rate=1000/dt,bins=Array.from({length:n/2+1},(_,i)=>({hz:i*rate/n,amplitude:Math.hypot(real[i],imag[i])*(i===0||i===n/2?1:2)/gain}));
|
||||
const peak=bins.slice(1).reduce((best,v)=>v.amplitude>best.amplitude?v:best,bins[1]);
|
||||
return {bins,rate,n,from:data[0].at,to:data.at(-1)!.at,peak};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type {ControlAdapter,ControlEndpoint,ControlTransportProfile} from "./controlTransport";
|
||||
import type {Sensor} from '../../../../packages/sensor-ui/src/contracts';
|
||||
|
||||
export interface VescIdentity {uuid:string;hardware:string;version:string;test_firmware:number|null;hardware_type:number|null}
|
||||
@@ -8,13 +9,22 @@ export function drivePositions(layout:DriveProfile['layout']):Record<string,stri
|
||||
? {'left.1':'Левый передний','left.2':'Левый задний','right.1':'Правый передний','right.2':'Правый задний'}
|
||||
: {'left.1':'Левый','right.1':'Правый'};
|
||||
}
|
||||
export interface VescFirmwareState {state:string;progress?:number;operation_id?:string;before_backup_id?:string;image?:{name:string;sha256:string;swd?:{target_code:number;pins:string;address:number;flash_bytes:number};can_id?:number}}
|
||||
export interface VescStatus {
|
||||
board_settings_supported?:boolean;
|
||||
group_test_supported?:boolean;
|
||||
package_pending?:boolean; code_pending?:boolean; code_execution_pending?:boolean; bms_configuration_pending?:boolean;
|
||||
tools_read_supported?:boolean; terminal_read_supported?:boolean;
|
||||
firmware_update_supported?:boolean; firmware_update?:VescFirmwareState;
|
||||
connected?:boolean; telemetry_ready?:boolean;
|
||||
configuration_edit_supported?:boolean; configuration_pending?:boolean;
|
||||
configuration_read_supported?:boolean; diagnostics_read_supported?:boolean;
|
||||
engine?:{version:string;commit:string;contract?:{rpc_version:number;profile_sha256:string;firmware_targets?:string[];firmware_formats?:string[];firmware_profiles:{major:number;minor:number;hardware_type:number}[];methods:string[]}};
|
||||
sample_data_supported?:boolean; qml_preview_supported?:boolean; qml_interactive_supported?:boolean; qml_broker_supported?:boolean; board_settings_supported?:boolean;
|
||||
group_test_supported?:boolean; test_active?:boolean;
|
||||
link_check_supported?:boolean;
|
||||
foc_calibration?:{min_power_loss_w:number;max_power_loss_w:number;interruptible:boolean};
|
||||
speed_limits?:{min_erpm:number;max_erpm:number;duration_basis:string;reverse_supported?:boolean;standstill_confirmation_required?:boolean};
|
||||
hall_measurement?:{current_a:number;interruptible:boolean;standstill_confirmation_required?:boolean};
|
||||
control_transport?:ControlTransportProfile; control_endpoints?:ControlEndpoint[]; control_adapters?:ControlAdapter[];
|
||||
drive_profile?:DriveProfile;
|
||||
test_limits?:{min_current_a:number;max_current_a:number;min_duration_s:number;max_duration_s:number;current_ramp_a_per_s?:number;continuous_current?:boolean;max_erpm?:number;max_duty?:number;stall_current_a?:number;stall_timeout_s?:number};
|
||||
identity:VescIdentity|null; readable:boolean; message:string|null; telemetry:VescTelemetry|null;
|
||||
@@ -50,7 +60,11 @@ export function vescLabel(device:Sensor,fresh:boolean):{label:string;tone:'neutr
|
||||
if(!fresh||!device.online)return {label:'Нет связи',tone:'neutral'};
|
||||
if(!device.prepared)return {label:'Требуется подготовка',tone:'neutral'};
|
||||
if(!status.identity)return {label:'Не определён',tone:'warning'};
|
||||
if(status.firmware_update?.state==='uploading')return {label:'Загрузка прошивки',tone:'warning'};
|
||||
if(status.firmware_update&&['awaiting_identity','unknown'].includes(status.firmware_update.state))return {label:'Требуется проверка прошивки',tone:'warning'};
|
||||
if(status.connected===false)return {label:'Восстановление связи',tone:'warning'};
|
||||
if(!status.readable)return {label:'Прошивка не поддерживается',tone:'warning'};
|
||||
if(status.telemetry_ready===false)return {label:'Ожидание данных',tone:'neutral'};
|
||||
return {label:'Готов к чтению',tone:'success'};
|
||||
}
|
||||
|
||||
|
||||
@@ -5,5 +5,5 @@ import {vescLabel} from './model';
|
||||
|
||||
export const vescSensorUi:SensorUiContribution={
|
||||
kind:'vesc.controller',Detail:VescDetail,BoardSettings:VescBoardSettings,icon:'activity',retainOffline:true,
|
||||
supportsPreparation:true,supportsRenaming:true,detailLabel:'Настройка VESC',status:vescLabel,
|
||||
supportsPreparation:true,supportsRenaming:true,settingsInDetail:true,detailPresentation:'modal',detailLabel:'Настройка VESC',status:vescLabel,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/** Offline observations of original Sample Data. No motor/transport authority.
|
||||
* FW5.02 mc_interface.c: Phase is mcpwm_foc_get_phase(), Hall is mcpwm_read_hall_phase(), a transformed
|
||||
* commutation code, NOT the three raw GPIO inputs. Neither proves mechanical shaft movement.
|
||||
*/
|
||||
import type {LogPoint} from './logAnalysis';
|
||||
export interface HallEvent {kind:'code'|'missing'|'change';first:number;last:number;at:number;end:number;label:string;current:number|null}
|
||||
export interface HallReview {count:number;counts:number[];missing:number;transitions:number;longest:number[];phaseCount:number;phaseStep:number|null;halfTurns:number;peakCurrent:number|null;events:HallEvent[]}
|
||||
const finite=(v:unknown):v is number=>typeof v==='number'&&Number.isFinite(v);
|
||||
const hall=(p:LogPoint)=>!p.gap&&finite(p.values.hall)&&Number.isInteger(p.values.hall)&&p.values.hall>=0&&p.values.hall<=7?p.values.hall:null;
|
||||
const phase=(p:LogPoint)=>!p.gap&&finite(p.values.phase_deg)&&p.values.phase_deg>=0&&p.values.phase_deg<=360?p.values.phase_deg:null;
|
||||
export function wrappedPhaseStep(a:number,b:number){return ((b-a+540)%360)-180;}
|
||||
export function reviewRotorHall(points:readonly LogPoint[],from:number,to:number):HallReview {
|
||||
if(points.length>2000||!finite(from)||!finite(to)||from>to)throw new Error('Неверный интервал Sample Data.');
|
||||
let previous=-Infinity;
|
||||
for(const p of points){if(!finite(p.at)||p.at<=previous)throw new Error('Нарушен порядок времени Sample Data.');previous=p.at;}
|
||||
const out:HallReview={count:0,counts:Array(8).fill(0),missing:0,transitions:0,longest:Array(8).fill(0),phaseCount:0,phaseStep:null,halfTurns:0,peakCurrent:null,events:[]};
|
||||
let prior:{p:LogPoint;h:number|null;angle:number|null;index:number}|null=null,runStart=0;
|
||||
for(let index=0;index<points.length;index++){
|
||||
const p=points[index];if(p.at<from||p.at>to)continue;
|
||||
out.count++;const h=hall(p),angle=phase(p),current=!p.gap&&finite(p.values.current)?p.values.current:null;
|
||||
if(current!==null)out.peakCurrent=Math.max(out.peakCurrent??0,Math.abs(current));
|
||||
if(h===null)out.missing++;else out.counts[h]++;
|
||||
if(angle!==null){out.phaseCount++;if(prior&&prior.angle!==null){const step=Math.abs(wrappedPhaseStep(prior.angle,angle));out.phaseStep=Math.max(out.phaseStep??0,step);if(Math.abs(step-180)<1e-9)out.halfTurns++;}}
|
||||
if(h!==null){if(!prior||prior.h!==h)runStart=p.at;out.longest[h]=Math.max(out.longest[h],p.at-runStart);}
|
||||
if(h===null||h===0||h===7){
|
||||
const kind=h===null?'missing':'code',last=out.events.at(-1);
|
||||
const label=h===null?'Нет кода Hall в выборке':`Код Hall ${h}`;
|
||||
if(last&&last.kind===kind&&last.label===label&&last.last===index-1){last.last=index;last.end=p.at;if(current!==null)last.current=Math.max(last.current??0,Math.abs(current));}
|
||||
else out.events.push({kind,first:index,last:index,at:p.at,end:p.at,label,current:current===null?null:Math.abs(current)});
|
||||
}
|
||||
if(h!==null&&prior?.h!=null&&h!==prior.h){
|
||||
out.transitions++;
|
||||
out.events.push({kind:'change',first:prior.index,last:index,at:prior.p.at,end:p.at,label:`Код Hall: ${prior.h} → ${h}`,current:[prior.p.values.current,current].filter(finite).reduce<number|null>((peak,n)=>Math.max(peak??0,Math.abs(n)),null)});
|
||||
}
|
||||
prior={p,h,angle,index};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
export function hallEventWindow(points:readonly LogPoint[],event:HallEvent){
|
||||
return {from:points[Math.max(0,event.first-5)].at,to:points[Math.min(points.length-1,event.last+5)].at,first:event.at,second:event.end};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/** Offline Sample Data review; no transport, persistence or controller authority. */
|
||||
import {LOG_MAX_BYTES,parseVescLog,type LogPoint} from './logAnalysis';
|
||||
import {sampleFields,samplePoints,sampleStateLabel,type SampleRow,type SampleState} from './samples';
|
||||
import type {VescIdentity} from './model';
|
||||
export interface SampleRecord {
|
||||
name:string;points:LogPoint[];uuid:string|null;hardware:string|null;firmware:string|null;
|
||||
session:string|null;capture:string|null;status:string;complete:boolean|null;thirdMeasured:boolean|null;
|
||||
}
|
||||
function fail(message:string):never {throw new Error(message);}
|
||||
function object(v:unknown):Record<string,unknown>{return v!==null&&typeof v==='object'&&!Array.isArray(v)?v as Record<string,unknown>:fail('Повреждён паспорт выборки.');}
|
||||
function text(v:unknown,max=160):string|null {if(v===null||v===undefined||v==='')return null;if(typeof v!=='string'||v.length>max||/[\x00-\x1f]/.test(v))return fail('Некорректное поле паспорта.');return v;}
|
||||
function integer(v:unknown,min:number,max:number):number {return typeof v==='number'&&Number.isInteger(v)&&v>=min&&v<=max?v:fail('Некорректные счётчики выборки.');}
|
||||
const keys:Record<string,string>={I1:'i1',I2:'i2',I3:'i3',I_tot:'current',V1:'v1',V2:'v2',V3:'v3',V_zero:'v0',Phase:'phase_deg',Hall:'hall',Commutation:'commutation',F_sw:'switching_hz'};
|
||||
export function liveSampleRecord(name:string,rows:SampleRow[],state:SampleState,identity:VescIdentity|null|undefined,session:string|null|undefined):SampleRecord {
|
||||
return {name,points:samplePoints(rows),uuid:identity?.uuid??null,hardware:identity?.hardware??null,firmware:identity?.version??null,session:session??null,capture:state.capture_id,status:sampleStateLabel[state.state]??state.state,complete:state.state==='complete',thirdMeasured:rows.every(r=>r.third_current_measured)};
|
||||
}
|
||||
export function parseSampleRecord(source:string,name:string):SampleRecord {
|
||||
if(source.length>LOG_MAX_BYTES||new TextEncoder().encode(source).length>LOG_MAX_BYTES)fail('Максимальный размер файла — 4 МиБ.');
|
||||
source=source.replace(/^\uFEFF/,'').trim();
|
||||
if(!source.startsWith('{')){
|
||||
const log=parseVescLog(source);if(log.format!=='VESC Tool · Sample Data')fail('Здесь нужен CSV Sample Data. Обычные журналы открываются в разделе «Анализ журналов и FFT».');
|
||||
return {name,points:log.points.map(p=>({...p,values:Object.fromEntries(Object.entries(p.values).map(([k,v])=>[keys[k],v]))})),uuid:null,hardware:null,firmware:null,session:null,capture:null,status:'CSV: полнота и источник не подтверждены',complete:null,thirdMeasured:null};
|
||||
}
|
||||
const data=object(JSON.parse(source));if(data.schema!=='missioncore.vesc.sample-data/v1')fail('Неизвестная версия паспорта Sample Data.');
|
||||
const state=object(data.state),id=data.identity==null?{}:object(data.identity);
|
||||
if(!Array.isArray(data.rows)||!data.rows.length||data.rows.length>2000)fail('Выборка должна содержать 1–2000 отсчётов.');
|
||||
const rows=data.rows.map((value,i)=>{
|
||||
const r=object(value);if(r.index!==i||typeof r.dt_s!=='number'||!Number.isFinite(r.dt_s)||r.dt_s<=0||r.dt_s>1||typeof r.indexed!=='boolean'||typeof r.third_current_measured!=='boolean')fail('Повреждены порядок или шаг времени выборки.');
|
||||
for(const [key] of sampleFields)if(typeof r[key]!=='number'||!Number.isFinite(r[key])||Math.abs(r[key] as number)>1e15)fail('Повреждены числовые значения выборки.');
|
||||
integer(r.hall,0,7);integer(r.commutation,0,7);if((r.switching_hz as number)<=0)fail('Неверная частота выборки.');
|
||||
return Object.fromEntries(['index','dt_s','indexed','third_current_measured',...sampleFields.map(f=>f[0])].map(k=>[k,r[k]])) as unknown as SampleRow;
|
||||
});
|
||||
const received=integer(state.received,1,2000),expected=integer(state.expected,0,2000),malformed=integer(state.malformed,0,1e9);
|
||||
const label=text(state.state);if(!label||!Object.hasOwn(sampleStateLabel,label))fail('Неизвестное состояние выборки.');
|
||||
if(received!==rows.length||label==='complete'&&(received!==expected||malformed!==0))fail('Паспорт не соответствует полученным отсчётам.');
|
||||
integer(state.mode,1,7);integer(state.count,1,2000);integer(state.decimation,1,255);
|
||||
const uuid=text(id.uuid);if(uuid&&!/^[a-f\d]{24}$/i.test(uuid))fail('UUID должен содержать 24 шестнадцатеричных символа.');
|
||||
return {name,points:samplePoints(rows),uuid,hardware:text(id.hardware),firmware:text(id.version),session:text(data.session),capture:text(state.capture_id),status:sampleStateLabel[label],complete:label==='complete',thirdMeasured:rows.every(r=>r.third_current_measured)};
|
||||
}
|
||||
export interface SampleFilter {kind:'none'|'mean'|'fir';bits:number;cutoff:number;hamming:boolean;compensate:boolean}
|
||||
export const defaultSampleFilter:SampleFilter={kind:'none',bits:6,cutoff:.05,hamming:true,compensate:true};
|
||||
/** Tool 7.00 DigitalFiltering::generateFirFilter frequency bins, real inverse DFT,
|
||||
* fftshift and Hamming. This direct bounded DFT avoids a second FFT dependency. */
|
||||
export function filterCoefficients(filter:SampleFilter):number[]{
|
||||
if(filter.kind==='none')return [];
|
||||
if(!['mean','fir'].includes(filter.kind)||!Number.isInteger(filter.bits)||filter.bits<1||filter.bits>10||!Number.isFinite(filter.cutoff)||filter.cutoff<0||filter.cutoff>.5)fail('Недопустимые параметры фильтра.');
|
||||
const n=2**filter.bits;if(filter.kind==='mean')return Array(n).fill(1/n);
|
||||
const pass=Math.floor(n*filter.cutoff);
|
||||
return Array.from({length:n},(_,j)=>{const k=(j+n/2)%n;let sum=0;for(let i=0;i<pass;i++)sum+=Math.cos(2*Math.PI*k*i/n)+Math.cos(2*Math.PI*k*(n-i-1)/n);return sum/n*(filter.hamming ? 0.54-0.46*Math.cos(2*Math.PI*j/(n-1)):1);});
|
||||
}
|
||||
export function filteredSamplePoints(points:readonly LogPoint[],key:string,filter:SampleFilter,coefficients=filterCoefficients(filter)):{at:number;value:number|null}[]{
|
||||
const values=points.map(p=>({at:p.at,value:p.gap?null:p.values[key]??null}));
|
||||
if(filter.kind==='none'||!['i1','i2','i3'].includes(key))return values;
|
||||
const taps=coefficients.length,shift=filter.compensate?taps/2:taps;
|
||||
// Same valid convolution positions as Tool. Tool zero-pads unavailable edges;
|
||||
// Core retains them as gaps so a zero current is never invented.
|
||||
const result=values.map(p=>({...p,value:null as number|null}));
|
||||
for(let i=0;i<values.length-taps;i++){
|
||||
const dt=values[i+1].at-values[i].at;let value=0,valid=dt>0;
|
||||
for(let j=0;j<taps;j++){const p=values[i+j];if(p.value===null||j>0&&Math.abs(p.at-values[i+j-1].at-dt)>dt*.01){valid=false;break;}value+=p.value*coefficients[j];}
|
||||
if(valid)result[i+shift].value=value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function sampleMeasurement(points:readonly {at:number;value:number|null}[],from:number,to:number,cursor1:number,cursor2:number){
|
||||
const interval=points.filter(p=>p.at>=from&&p.at<=to),valid=interval.filter((p):p is {at:number;value:number}=>p.value!==null&&Number.isFinite(p.value));
|
||||
const nearest=(at:number)=>{if(!interval.length||at<interval[0].at||at>interval.at(-1)!.at)return null;const p=interval.reduce((a,b)=>Math.abs(a.at-at)<=Math.abs(b.at-at)?a:b);return p.value===null?null:p;};
|
||||
const first=nearest(cursor1),second=nearest(cursor2);
|
||||
return {count:valid.length,min:valid.length?Math.min(...valid.map(p=>p.value)):null,max:valid.length?Math.max(...valid.map(p=>p.value)):null,rms:valid.length?Math.sqrt(valid.reduce((sum,p)=>sum+p.value**2,0)/valid.length):null,first,second,delta:first&&second?second.value!-first.value!:null,dt:first&&second?second.at-first.at:null};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type {LogPoint} from './logAnalysis';
|
||||
export interface SampleRow {index:number;i1:number;i2:number;i3:number;v1:number;v2:number;v3:number;v0:number;current:number;switching_hz:number;commutation:number;hall:number;phase_deg:number;dt_s:number;indexed:boolean;third_current_measured:boolean}
|
||||
export interface SampleState {capture_id:string;state:string;received:number;expected:number;mode:number;count:number;decimation:number;malformed:number;error?:string;rows?:SampleRow[];offset?:number;elapsed_ms:number;provenance:string}
|
||||
export const sampleFields=[['i1','Ток фазы 1','А'],['i2','Ток фазы 2','А'],['i3','Ток фазы 3 (расчёт)','А'],['current','Ток мотора','А'],['v1','Напряжение фазы 1','В'],['v2','Напряжение фазы 2','В'],['v3','Напряжение фазы 3','В'],['v0','Нулевая точка','В'],['hall','Код Hall из выборки',''],['commutation','Шаг коммутации',''],['phase_deg','Угол фазы (электрический)','°'],['switching_hz','Частота выборки до делителя','Гц']] as const;
|
||||
export function samplePoints(rows:SampleRow[]):LogPoint[]{
|
||||
if(rows.length>2000)throw new Error('Буфер превышает 2000 отсчётов.');
|
||||
let at=0;return rows.map((r,i)=>{
|
||||
if(r.index!==i||!Number.isFinite(r.dt_s)||r.dt_s<=0||sampleFields.some(([key])=>!Number.isFinite(r[key])))throw new Error('Повреждён порядок или значения выборки.');
|
||||
const point={at,values:Object.fromEntries(sampleFields.map(([key])=>[key,r[key]])),gap:false};at+=r.dt_s*1000;return point;
|
||||
});
|
||||
}
|
||||
export function sampleCsv(rows:SampleRow[]){
|
||||
const points=samplePoints(rows);return 'T;I1;I2;I3;V1;V2;V3;I_tot;V_zero;Phase;Hall;Commutation;F_sw\n'+rows.map((r,i)=>[points[i].at/1000,r.i1,r.i2,r.i3,r.v1,r.v2,r.v3,r.current,r.v0,r.phase_deg,r.hall,r.commutation,r.switching_hz].join(';')).join('\n');
|
||||
}
|
||||
export const sampleStateLabel:Record<string,string>={idle:'Захват не запускался',armed:'Ожидание выборки',stored_wait:'Ожидание события; буфер на контроллере',receiving:'Получение выборки',complete:'Все ожидаемые отсчёты получены',incomplete:'Неполная выборка',timeout:'Срок ожидания истёк',cancelled:'Захват остановлен',unverified:'Последний буфер; событие не подтверждено',expired:'Буфер истёк'};
|
||||
@@ -0,0 +1,25 @@
|
||||
import type {SensorLiveFrame} from '../../../../packages/sensor-ui/src/contracts';
|
||||
|
||||
/** One abortable read at a time; no command path and no queued catch-up reads. */
|
||||
export class TraceObserver {
|
||||
private closed=false;private busy=false;private abort:AbortController|undefined;
|
||||
private timer:ReturnType<typeof setInterval>;
|
||||
constructor(private read:(signal:AbortSignal)=>Promise<SensorLiveFrame>,
|
||||
private receive:(frame:SensorLiveFrame|null,now:number,roundTripMs:number)=>void,
|
||||
private tick:(now:number)=>void,private visible:()=>boolean=()=>!document.hidden,
|
||||
private clock:()=>number=()=>performance.now()){
|
||||
this.timer=setInterval(()=>this.step(),500);this.step();
|
||||
}
|
||||
private step(){
|
||||
if(this.closed)return;this.tick(this.clock());
|
||||
if(!this.visible()){this.abort?.abort();this.receive(null,this.clock(),0);return;}
|
||||
if(this.busy)return;
|
||||
this.busy=true;const abort=new AbortController();this.abort=abort;const started=this.clock();
|
||||
const deadline=setTimeout(()=>abort.abort(),1200);
|
||||
Promise.resolve().then(()=>this.read(abort.signal)).then(frame=>{
|
||||
if(!this.closed&&!abort.signal.aborted&&this.visible())this.receive(frame,this.clock(),this.clock()-started);
|
||||
}).catch(()=>{if(!this.closed)this.receive(null,this.clock(),0);})
|
||||
.finally(()=>{clearTimeout(deadline);this.busy=false;if(this.abort===abort)this.abort=undefined;});
|
||||
}
|
||||
close(){this.closed=true;clearInterval(this.timer);this.abort?.abort();}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type {SensorLiveFrame} from '../../../../packages/sensor-ui/src/contracts';
|
||||
|
||||
export const TRACE_MS=300000,TRACE_LIMIT=1200,FRESH_MS=1500;
|
||||
export const metrics=[
|
||||
['input_voltage_v','Напряжение питания','В'],['input_current_a','Ток питания','А'],
|
||||
['motor_current_a','Ток мотора','А'],['input_power_w','Мощность питания','Вт'],
|
||||
['duty','Заполнение PWM','%'],['erpm','Электрические обороты','ERPM'],
|
||||
['mos_temperature_c','Температура контроллера','°C'],['motor_temperature_c','Температура мотора','°C'],
|
||||
['mos1_c','Датчик MOS 1','°C'],['mos2_c','Датчик MOS 2','°C'],['mos3_c','Датчик MOS 3','°C'],
|
||||
['id_current_a','Ток FOC по оси d','А'],['iq_current_a','Ток FOC по оси q','А'],
|
||||
['vd_v','Напряжение FOC по оси d','В'],['vq_v','Напряжение FOC по оси q','В'],
|
||||
['position_deg','Положение ротора','°'],['tachometer','Счётчик тахометра',''],
|
||||
['tachometer_abs','Абсолютный счётчик тахометра',''],['amp_hours','Расход заряда','А·ч'],
|
||||
['amp_hours_charged','Возвращённый заряд','А·ч'],['watt_hours','Расход энергии','Вт·ч'],
|
||||
['watt_hours_charged','Возвращённая энергия','Вт·ч'],['fault_code','Код ошибки',''],
|
||||
] as const;
|
||||
export type Metric=typeof metrics[number][0];
|
||||
export interface TracePoint {at:number;source:string;session:string;sample:number;utc:string;values:Partial<Record<Metric,number>>|null}
|
||||
export class VescTrace {
|
||||
points:TracePoint[]=[];
|
||||
private source='';private session='';private sample=-Infinity;private offset=0;
|
||||
private freshAt=-Infinity;private day='';
|
||||
get freshUntil(){return this.freshAt+FRESH_MS;}
|
||||
clear(){this.points=[];this.source='';this.session='';this.sample=-Infinity;this.freshAt=-Infinity;}
|
||||
prune(now:number,day=new Date().toISOString().slice(0,10)){
|
||||
if(this.day&&this.day!==day)this.clear();this.day=day;
|
||||
this.points=this.points.filter(p=>p.at>=now-TRACE_MS).slice(-TRACE_LIMIT);
|
||||
}
|
||||
gap(now:number){
|
||||
this.freshAt=-Infinity;
|
||||
if(this.points.at(-1)?.values)this.points.push({at:now,source:this.source,session:this.session,sample:this.sample,utc:'',values:null});
|
||||
this.prune(now);
|
||||
}
|
||||
accept(frame:SensorLiveFrame,id:string,uuid:string,now:number,roundTripMs:number):boolean{
|
||||
const matches=frame.devices?.filter(d=>d.id===id)??[];
|
||||
const p=matches.length===1?matches[0]:undefined;
|
||||
if(!frame.fresh||!frame.instance||!p||p.uuid?.toLowerCase()!==uuid.toLowerCase()||!p.session_id||
|
||||
!Number.isFinite(p.sample_time_ms)||p.sample_time_ms<0||!Number.isFinite(p.age_ms)||p.age_ms<0||
|
||||
!Number.isFinite(roundTripMs)||roundTripMs<0||p.age_ms+roundTripMs>=FRESH_MS||!Number.isFinite(Date.parse(p.observed_at))){this.gap(now);return false;}
|
||||
const changed=frame.instance!==this.source||p.session_id!==this.session;
|
||||
if(!changed&&p.sample_time_ms<=this.sample){if(now>=this.freshUntil)this.gap(now);return false;}
|
||||
if(changed){this.gap(now);this.offset=now-p.age_ms-roundTripMs-p.sample_time_ms;}
|
||||
let at=p.sample_time_ms+this.offset;
|
||||
// Monotonic source time owns spacing. Arrival delay cannot extend freshness
|
||||
// or turn a duplicate, reordered frame, reset or reconnect into continuity.
|
||||
if(at>(now+FRESH_MS)||at<now-TRACE_MS){this.gap(now);this.offset=now-p.age_ms-roundTripMs-p.sample_time_ms;at=p.sample_time_ms+this.offset;}
|
||||
if(this.points.at(-1)?.values&&at-this.points.at(-1)!.at>FRESH_MS)this.gap(at-FRESH_MS);
|
||||
at=Math.max(at,this.points.at(-1)?.at??at);
|
||||
const values:Partial<Record<Metric,number>>={};
|
||||
for(const [key] of metrics){const value=p.values?.[key];if(typeof value==='number'&&Number.isFinite(value))values[key]=key==='duty'?value*100:value;}
|
||||
if(values.input_current_a!==undefined&&values.input_voltage_v!==undefined){const watts=values.input_current_a*values.input_voltage_v;if(Number.isFinite(watts))values.input_power_w=watts;}
|
||||
if(!Object.keys(values).length){this.gap(now);return false;}
|
||||
this.source=frame.instance;this.session=p.session_id;this.sample=p.sample_time_ms;this.freshAt=now-p.age_ms-roundTripMs;
|
||||
this.points.push({at,source:this.source,session:this.session,sample:this.sample,utc:p.observed_at,values});this.prune(now);return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function traceView(points:readonly TracePoint[],metric:Metric,from:number,to:number,height=180){
|
||||
const visible=points.filter(p=>p.at>=from&&p.at<=to),values=visible.flatMap(p=>p.values?.[metric]===undefined?[]:[p.values[metric]!]);
|
||||
const min=values.length?Math.min(...values):null,max=values.length?Math.max(...values):null;
|
||||
const mean=values.length?values.reduce((sum,n)=>sum+n/values.length,0):null;
|
||||
const spread=min===null||max===null?1:Math.max((max-min)*.1,Math.abs(max)*.01,.001);
|
||||
const low=(min??0)-spread,high=(max??0)+spread;
|
||||
const segments:{x:number;y:number}[][]=[];let line:{x:number;y:number}[]=[];
|
||||
for(const point of visible){const v=point.values?.[metric];if(v===undefined){if(line.length)segments.push(line);line=[];continue;}
|
||||
line.push({x:64+((point.at-from)/Math.max(1,to-from))*716,y:20+(1-(v-low)/(high-low))*height});
|
||||
}
|
||||
if(line.length)segments.push(line);
|
||||
return {segments,min,max,mean,low,high,count:values.length,last:values.at(-1)??null};
|
||||
}
|
||||
|
||||
const csvCell=(v:string|number)=>typeof v==='number'?String(v):'"'+(/^[\s]*[=+@-]/.test(v)?"'"+v:v).replaceAll('"','""')+'"';
|
||||
export function traceCsv(points:readonly TracePoint[],identity:{uuid:string;hardware:string;version:string}){
|
||||
const header=['plot_elapsed_s','sample_utc','source_instance','usb_session','source_monotonic_ms','state','uuid','hardware','firmware',...metrics.map(([key,,unit])=>`${key} [${unit}]`)];
|
||||
const start=points[0]?.at??0;
|
||||
return '\uFEFF'+[header.map(csvCell).join(','),...points.map(p=>[
|
||||
(p.at-start)/1000,p.utc,p.source,p.session,p.sample,p.values?'sample':'gap',identity.uuid,identity.hardware,identity.version,
|
||||
...metrics.map(([key])=>p.values?.[key]??''),
|
||||
].map(csvCell).join(','))].join('\r\n')+'\r\n';
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {ReadProps} from './useVescRead';
|
||||
import {vescStatus} from './model';
|
||||
import {CONFIGURATION_OPERATION_TIMEOUT_MS} from './configurationOperation';
|
||||
|
||||
export interface ConfigChange {kind:'motor'|'application';name:string;title:string;before:number|string|boolean;after:number|string|boolean;suffix:string;editor_scale:number}
|
||||
export interface ConfigPreview {preview_id:string;expires_in_s:number;identity:{uuid:string};changes:ConfigChange[]}
|
||||
export interface ConfigResult {outcome:string;verified:boolean;message?:string;before_backup_id?:string;after_backup_id?:string}
|
||||
export function useVescEditor(props:ReadProps){
|
||||
const [preview,setPreview]=useState<ConfigPreview|null>(null),[result,setResult]=useState<ConfigResult|null>(null),[busy,setBusy]=useState(false);
|
||||
const running=useRef(false),mounted=useRef(true);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
const available=props.enabled&&props.device.online&&props.device.verified&&vescStatus(props.device).configuration_edit_supported===true;
|
||||
async function execute<T>(action:string,parameters:Record<string,unknown>,timeout=CONFIGURATION_OPERATION_TIMEOUT_MS):Promise<T|null>{
|
||||
if(running.current||props.blocked||!available)return null;
|
||||
running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);
|
||||
try{return await perform<T>(props.transport,props.device,action,parameters,timeout);}
|
||||
catch(error){if(mounted.current)props.failure(error);return null;}
|
||||
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
async function prepare(parameters:Record<string,unknown>){
|
||||
setPreview(null);setResult(null);
|
||||
const value=await execute<ConfigPreview>('vesc.configuration.preview',parameters);
|
||||
if(mounted.current)setPreview(value);
|
||||
}
|
||||
async function apply(){
|
||||
if(!preview)return;
|
||||
const id=preview.preview_id;setPreview(null);
|
||||
const value=await execute<ConfigResult>('vesc.configuration.apply',{preview_id:id,rig_clear:true,inputs_isolated:true});
|
||||
if(mounted.current){setResult(value);await props.refresh();}
|
||||
}
|
||||
async function reconcile(){
|
||||
const value=await execute<ConfigResult>('vesc.configuration.reconcile',{});
|
||||
if(mounted.current){setResult(value);await props.refresh();}
|
||||
}
|
||||
return {preview,result,busy,available,prepare,apply,reconcile,clear:()=>{setPreview(null);setResult(null);}};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {perform} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
|
||||
import {vescStatus} from './model';
|
||||
import {CONFIGURATION_OPERATION_TIMEOUT_MS} from './configurationOperation';
|
||||
|
||||
export type ReadProps=SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void};
|
||||
export function useVescRead<T>(props:ReadProps,action:string,supported=true){
|
||||
const {device,transport,enabled,failure,blocked,onBusyChange}=props;
|
||||
const [value,setValue]=useState<T|null>(null),[busy,setBusy]=useState(false);
|
||||
const running=useRef(false),mounted=useRef(true);
|
||||
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
|
||||
const available=enabled&&device.online&&device.verified&&vescStatus(device).readable&&supported;
|
||||
async function read(parameters:Record<string,unknown>={}){
|
||||
if(running.current||blocked||!available)return;
|
||||
running.current=true;setBusy(true);onBusyChange(true);failure(null);
|
||||
const timeout=action==='vesc.configuration.read'?CONFIGURATION_OPERATION_TIMEOUT_MS:30000;
|
||||
try{const result=await perform<T>(transport,device,action,parameters,timeout);if(mounted.current)setValue(result);}
|
||||
catch(error){if(mounted.current)failure(error);}
|
||||
finally{running.current=false;onBusyChange(false);if(mounted.current)setBusy(false);}
|
||||
}
|
||||
return {value,busy,available,read};
|
||||
}
|
||||
@@ -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}
|
||||
@@ -0,0 +1,53 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "tools_native.h"
|
||||
#include "engine_profile.h"
|
||||
|
||||
static QJsonObject canIdentity(const FW_RX_PARAMS &p, int id) {
|
||||
return {{"can_id",id},{"uuid",QString::fromLatin1(p.uuid.toHex())},{"hardware",p.hw},
|
||||
{"major",p.major},{"minor",p.minor},{"hardware_type",int(p.hwType)},{"test_firmware",p.isTestFw},{"custom_configs",p.customConfigNum}};
|
||||
}
|
||||
static bool bmsCommandsSupported(const FW_RX_PARAMS &p) {
|
||||
if(p.hwType!=HW_TYPE_VESC_BMS || p.isTestFw!=0)return false;
|
||||
for(const auto &v:engineProfile().value("bms_profiles").toArray()) {
|
||||
const auto profile=v.toObject();
|
||||
if(p.major==profile.value("major").toInt() && p.minor==profile.value("minor").toInt())return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// Use the original temporary route. Neither the local schema nor the local UUID
|
||||
// is replaced by the CAN reply; restore the route even when a check throws.
|
||||
class NativeCanTarget {
|
||||
VescInterface &vesc;
|
||||
bool &remote;
|
||||
public:
|
||||
NativeCanTarget(VescInterface &v, bool &flag, int id):vesc(v),remote(flag) {
|
||||
require(id>=0 && id<=253,"Invalid unicast CAN target");
|
||||
require(!remote && !v.commands()->getSendCan() && !v.isIgnoringCanChanges(),"CAN route already owned");
|
||||
remote=true;vesc.canTmpOverride(true,id);
|
||||
}
|
||||
~NativeCanTarget(){vesc.canTmpOverrideEnd();remote=false;}
|
||||
FW_RX_PARAMS identify() {
|
||||
FW_RX_PARAMS p;
|
||||
require(Utility::getFwVersionBlocking(&vesc,&p,1500),"CAN target did not identify");
|
||||
require(p.uuid.size()==12 && p.uuid!=QByteArray(12,'\0') && p.hw.size()>0 && p.hw.size()<=64,"CAN identity incomplete");
|
||||
return p;
|
||||
}
|
||||
};
|
||||
static void sendBmsCommand(Commands *cmd, const QString &action) {
|
||||
const QMap<QString,int> codes{{"charge_enable",COMM_BMS_SET_CHARGE_ALLOWED},
|
||||
{"charge_disable",COMM_BMS_SET_CHARGE_ALLOWED},{"balance_enable",COMM_BMS_FORCE_BALANCE},
|
||||
{"balance_disable",COMM_BMS_FORCE_BALANCE},{"reset_ah",COMM_BMS_RESET_COUNTERS},
|
||||
{"reset_wh",COMM_BMS_RESET_COUNTERS},{"zero_current",COMM_BMS_ZERO_CURRENT_OFFSET}};
|
||||
require(codes.contains(action),"Unknown BMS operation");
|
||||
require(cmd->getSendCan() && cmd->getCanSendId()>=0 && cmd->getCanSendId()<=253,"BMS needs an exact CAN route");
|
||||
require(cmd->getLimitedCompatibilityCommands().contains(codes.value(action)),"BMS command unsupported by transport firmware");
|
||||
if(action=="charge_enable" || action=="charge_disable")cmd->bmsSetChargeAllowed(action=="charge_enable");
|
||||
else if(action=="balance_enable" || action=="balance_disable")cmd->bmsForceBalance(action=="balance_enable");
|
||||
else if(action=="reset_ah" || action=="reset_wh")cmd->bmsResetCounters(action=="reset_ah",action=="reset_wh");
|
||||
else cmd->bmsZeroCurrentOffset();
|
||||
}
|
||||
static void requireSameCanIdentity(const FW_RX_PARAMS &a, const FW_RX_PARAMS &b) {
|
||||
require(a.uuid==b.uuid && a.hw==b.hw && a.major==b.major && a.minor==b.minor && a.hwType==b.hwType && a.isTestFw==b.isTestFw,
|
||||
"CAN target identity changed");
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include "custom_native.h"
|
||||
#include "codeloader.h"
|
||||
#include <QTemporaryDir>
|
||||
|
||||
// CodeLoader owns file formats. Only explicit uploaded attachments can be read;
|
||||
// no package-store lookup, host path fallback or automatic QML execution.
|
||||
class NativeCode {
|
||||
public:
|
||||
static bool supported(const FW_RX_PARAMS &p) {
|
||||
return p.major==6 && p.minor==0 && p.hwType==HW_TYPE_VESC && p.isTestFw==0;
|
||||
}
|
||||
static QList<QPair<QString,QString>> imports(const QString &source) {
|
||||
QList<QPair<QString,QString>> out; QSet<QString> tags;
|
||||
for(auto line:source.split('\n')) {
|
||||
while(line.startsWith(' '))line.remove(0,1);
|
||||
while(line.startsWith("( "))line.remove(1,1);
|
||||
if(!line.startsWith("(import ",Qt::CaseInsensitive))continue;
|
||||
auto match=QRegularExpression("^\\(import +\"([A-Za-z0-9][A-Za-z0-9_.-]{0,95})\" +'?([A-Za-z_][A-Za-z0-9_-]{0,63})\\) *\\r?(?:;.*)?$",QRegularExpression::CaseInsensitiveOption).match(line);
|
||||
require(match.hasMatch(),"Imports must name an attached flat file and a unique tag");
|
||||
require(!tags.contains(match.captured(2)) && out.size()<32,"Duplicate or excessive imports");
|
||||
tags.insert(match.captured(2));out.append(qMakePair(match.captured(1),match.captured(2)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
static QByteArray pack(const QJsonObject &project) {
|
||||
const auto kind=project.value("kind").toString(),source=project.value("source").toString();
|
||||
require((kind=="lisp"||kind=="qml") && project.value("source").isString(),"Code kind/source required");
|
||||
require(!source.contains(QChar(0)) && source.toUtf8().size()<=120*1024,"Code source exceeds bound");
|
||||
CodeLoader loader;VByteArray content;
|
||||
if(kind=="qml") {
|
||||
require(project.value("imports").toObject().isEmpty(),"QML attachments are not embedded by this firmware format");
|
||||
content.vbAppendUint16(project.value("fullscreen").toBool()?2:1);content.append(loader.qmlCompress(source));
|
||||
} else {
|
||||
QTemporaryDir directory;require(directory.isValid(),"Cannot allocate bounded import directory");
|
||||
const auto files=project.value("imports").toObject();require(files.size()<=32,"Too many imported files");
|
||||
QSet<QString> wanted;int total=source.toUtf8().size();
|
||||
for(const auto &item:imports(source))wanted.insert(item.first);
|
||||
require(wanted.size()==files.size(),"Import attachment inventory differs from source");
|
||||
for(const auto &name:wanted) {
|
||||
require(files.value(name).isString(),"Missing attached import");
|
||||
const auto encoded=files.value(name).toString().toLatin1();
|
||||
const auto bytes=QByteArray::fromBase64(encoded,QByteArray::AbortOnBase64DecodingErrors);
|
||||
require(bytes.toBase64()==encoded,"Invalid imported file encoding");
|
||||
total+=bytes.size();require(total<=120*1024,"Code and imports exceed flash bound");
|
||||
QFile file(directory.filePath(name));require(file.open(QIODevice::WriteOnly|QIODevice::NewOnly),"Cannot stage import");
|
||||
require(file.write(bytes)==bytes.size(),"Incomplete import staging");file.close();
|
||||
}
|
||||
content=loader.lispPackImports(source,directory.path(),false);
|
||||
require(content.size()>=5,"Upstream Lisp pack failed");
|
||||
}
|
||||
VByteArray data;data.vbAppendUint32(content.size()-2);
|
||||
data.vbAppendUint16(Packet::crc16(reinterpret_cast<const unsigned char*>(content.constData()),content.size()));data.append(content);
|
||||
require(data.size()<=120*1024,"Packed code exceeds flash bound");return data;
|
||||
}
|
||||
static QByteArray image(const QJsonObject &req) {
|
||||
const auto encoded=req.value("image").toString().toLatin1();
|
||||
const auto data=QByteArray::fromBase64(encoded,QByteArray::AbortOnBase64DecodingErrors);
|
||||
require(data.toBase64()==encoded && data.size()>=8 && data.size()<=120*1024,"Invalid code image encoding or size");
|
||||
VByteArray header(data.left(8));const auto length=header.vbPopFrontUint32();const auto crc=header.vbPopFrontUint16();const auto flags=header.vbPopFrontUint16();
|
||||
require(length==quint32(data.size()-8) && crc==Packet::crc16(reinterpret_cast<const unsigned char*>(data.constData()+6),data.size()-6),"Invalid code image header");
|
||||
const auto kind=req.value("kind").toString();require(kind=="lisp"?flags==0:kind=="qml"&&(flags==1||flags==2),"Code flags do not match kind");
|
||||
return data;
|
||||
}
|
||||
static QJsonObject decode(const QString &kind,const QByteArray &data) {
|
||||
QJsonObject result{{"kind",kind},{"sha256",sha256(data)},{"bytes",data.size()},{"payload",QString::fromLatin1(data.toBase64())}};
|
||||
if(data.isEmpty()){result.insert("source","");result.insert("imports",QJsonObject{});return result;}
|
||||
if(kind=="lisp") {
|
||||
const int end=data.indexOf('\0');require(end>0 && end+3<=data.size(),"Invalid Lisp source boundary");
|
||||
VByteArray table(data.mid(end+1));int count=table.vbPopFrontInt16();require(count>=0&&count<=32,"Invalid Lisp import count");
|
||||
int tableEnd=end+3;QList<QPair<int,int>> ranges;QSet<QString> names;
|
||||
for(int i=0;i<count;i++) {
|
||||
const int n=table.indexOf('\0');require(n>0&&n<=64&&n+9<=table.size(),"Invalid Lisp import table");
|
||||
const auto name=table.vbPopFrontString();int offset=table.vbPopFrontInt32(),length=table.vbPopFrontInt32();
|
||||
require(!names.contains(name)&&offset>=0&&length>0&&offset<=data.size()-length&&data[offset+length-1]=='\0',"Invalid Lisp import range");
|
||||
names.insert(name);ranges.append(qMakePair(offset,length));tableEnd+=n+9;
|
||||
}
|
||||
int previous=tableEnd;for(const auto &range:ranges){require(range.first>=previous,"Overlapping Lisp import range");previous=range.first+range.second;}
|
||||
CodeLoader loader;const auto unpacked=loader.lispUnpackImports(data);QJsonObject files;
|
||||
QStringList lines=unpacked.first.split('\n');
|
||||
for(auto &line:lines) {
|
||||
auto trimmed=line.trimmed();if(!trimmed.startsWith("(import ",Qt::CaseInsensitive))continue;
|
||||
auto match=QRegularExpression("^\\(import +\"([^\"]+)\" +'?([A-Za-z_][A-Za-z0-9_-]{0,63})\\) *\\r?(?:;.*)?$",QRegularExpression::CaseInsensitiveOption).match(trimmed);
|
||||
require(match.hasMatch(),"Lisp import cannot be reconstructed");const auto path=match.captured(1),tag=match.captured(2);
|
||||
const bool flat=QRegularExpression("^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$").match(path).hasMatch();const auto name=flat?path:"import_"+tag+".bin";
|
||||
bool found=false;for(const auto &file:unpacked.second)if(file.first==tag){const auto encoded=QString::fromLatin1(file.second.toBase64());require(!files.contains(name)||files.value(name).toString()==encoded,"Conflicting Lisp attachment");files.insert(name,encoded);found=true;break;}
|
||||
require(found,"Lisp attachment is missing");if(!flat)line.replace("\""+path+"\"","\""+name+"\"");
|
||||
}
|
||||
result.insert("source",lines.join('\n'));result.insert("imports",files);
|
||||
} else {
|
||||
require(data.size()>=5 && qFromBigEndian<quint32>(reinterpret_cast<const uchar*>(data.constData()))<=512*1024,"QML decompression bound exceeded");
|
||||
const auto xml=qUncompress(data);require(!xml.isEmpty(),"Invalid compressed QML");
|
||||
QString source=QString::fromUtf8(xml);const QString prefix="import Vedder.vesc.vescinterface 1.0;import \"qrc:/mobile\";";
|
||||
if(source.startsWith(prefix))source.remove(0,prefix.size());
|
||||
result.insert("source",source);result.insert("imports",QJsonObject{});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static QByteArray read(Commands *cmd,const QString &kind) {
|
||||
require(kind=="lisp"||kind=="qml"||kind=="qml_hw","Unknown code kind");
|
||||
QByteArray data;int total=-1;QElapsedTimer elapsed;elapsed.start();
|
||||
do {
|
||||
require(elapsed.elapsed()<25000,"Code read deadline exceeded");
|
||||
const int offset=data.size(),amount=total<0?0:qMin(400,total-offset);
|
||||
int receivedTotal=-1;QByteArray chunk;bool invalid=false;
|
||||
NativeCustom::wait([&](QObject *owner,std::function<void()> finish){
|
||||
auto reply=[&,finish](int length,int at,QByteArray bytes){if(at!=offset)return;invalid=length<0||length>128*1024||bytes.size()!=amount||(total>=0&&length!=total)||at+bytes.size()>length;receivedTotal=length;chunk=bytes;finish();};
|
||||
if(kind=="lisp")QObject::connect(cmd,&Commands::lispReadCodeRx,owner,reply);
|
||||
else if(kind=="qml")QObject::connect(cmd,&Commands::qmluiAppRx,owner,reply);
|
||||
else QObject::connect(cmd,&Commands::qmluiHwRx,owner,reply);
|
||||
},[&]{if(kind=="lisp")cmd->lispReadCode(amount,offset);else if(kind=="qml")cmd->qmlUiAppGet(amount,offset);else cmd->qmlUiHwGet(amount,offset);});
|
||||
require(!invalid,"Code fragment mismatch");total=receivedTotal;data.append(chunk);
|
||||
}while(data.size()<total);
|
||||
return data;
|
||||
}
|
||||
static void idle(Commands *cmd) {
|
||||
MC_VALUES v;unsigned int mask=0;
|
||||
NativeCustom::wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::valuesReceived,owner,[&,finish](MC_VALUES got,unsigned int m){v=got;mask=m;finish();});},[&]{cmd->getValues();});
|
||||
require((mask&0xFC)==0xFC && std::isfinite(v.current_motor)&&std::abs(v.current_motor)<=.5&&std::isfinite(v.current_in)&&std::abs(v.current_in)<=.5&&std::isfinite(v.duty_now)&&std::abs(v.duty_now)<=.001&&std::isfinite(v.rpm)&&std::abs(v.rpm)<1,"Code operation requires idle drive");
|
||||
}
|
||||
static void running(Commands *cmd,bool run) {
|
||||
bool ok=false;NativeCustom::wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::lispRunningResRx,owner,[&,finish](bool result){ok=result;finish();});},[&]{cmd->lispSetRunning(run);},3500);require(ok,"Lisp state change rejected");
|
||||
}
|
||||
static QJsonObject run(VescInterface &vesc,const FW_RX_PARAMS &identity,const QJsonObject &req) {
|
||||
const auto method=req.value("method").toString(),kind=req.value("kind").toString();auto cmd=vesc.commands();
|
||||
require(supported(identity),"Code tools are supported for the reviewed VESC firmware 6.00 profile");
|
||||
require(!cmd->getSendCan(),"Code tools require a direct USB target");
|
||||
if(method=="code_snapshot") {const auto data=read(cmd,kind);return {{"payload",QString::fromLatin1(data.toBase64())},{"sha256",sha256(data)},{"bytes",data.size()},{"fullscreen",kind=="qml"&&identity.qmlAppFullscreen}};}
|
||||
if(method=="code_read") {
|
||||
const auto data=(kind=="qml_hw"&&!identity.hasQmlHw)?QByteArray():read(cmd,kind);auto value=decode(kind,data);
|
||||
value.insert("project",QJsonObject{{"kind",kind=="qml_hw"?"qml":kind},{"source",value.value("source")},{"imports",value.value("imports")},{"fullscreen",kind=="qml"?identity.qmlAppFullscreen:kind=="qml_hw"?identity.qmlHwFullscreen:false}});return value;
|
||||
}
|
||||
if(method=="code_stats") {
|
||||
LISP_STATS value;NativeCustom::wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::lispStatsRx,owner,[&,finish](LISP_STATS v){value=v;finish();});},[&]{cmd->lispGetStats(true);});
|
||||
auto out=toolNumbers(value);QJsonObject bindings;for(const auto &v:value.number_bindings)bindings.insert(v.first,v.second);out.insert("bindings",bindings);return out;
|
||||
}
|
||||
if(method=="code_control") {
|
||||
const auto command=req.value("command").toString();require(command=="start"||command=="stop"||command=="repl","Unknown Lisp control");
|
||||
if(command!="stop")idle(cmd);
|
||||
if(command!="repl"){running(cmd,command=="start");return {{"acknowledged",true},{"command",command}};}
|
||||
const auto text=req.value("text").toString();require(!text.isEmpty()&&text.toUtf8().size()<=1024&&!text.contains(QChar(0)),"Invalid REPL request");
|
||||
QString output;QObject owner;QEventLoop loop;QTimer timeout;timeout.setSingleShot(true);
|
||||
QObject::connect(cmd,&Commands::lispPrintReceived,&owner,[&](QString line){if(output.toUtf8().size()<30000)output+=line.left(4096)+"\n";});
|
||||
QObject::connect(&timeout,&QTimer::timeout,&loop,&QEventLoop::quit);timeout.start(2000);cmd->lispSendReplCmd(text);loop.exec();
|
||||
return {{"sent",true},{"acknowledged",false},{"output",output},{"command",command}};
|
||||
}
|
||||
require(method=="code_write","Unknown code operation");
|
||||
const bool erase=req.value("erase").toBool();require(kind=="lisp"||kind=="qml","Hardware QML is read-only");
|
||||
const auto desired=erase?QByteArray():image(req);
|
||||
require(req.value("baseline").toString()==sha256(read(cmd,kind)),"Code changed after preview");
|
||||
if(kind=="qml")require(req.value("baseline_fullscreen").toBool()==identity.qmlAppFullscreen,"QML flags changed after preview");idle(cmd);
|
||||
bool ok=false;
|
||||
NativeCustom::wait([&](QObject *owner,std::function<void()> finish){auto reply=[&,finish](bool value){ok=value;finish();};if(kind=="lisp")QObject::connect(cmd,&Commands::lispEraseCodeRx,owner,reply);else QObject::connect(cmd,&Commands::eraseQmluiResReceived,owner,reply);},[&]{if(kind=="lisp")cmd->lispEraseCode(desired.size());else cmd->qmlUiErase(desired.size());},7000);
|
||||
require(ok,"Code erase rejected");QElapsedTimer elapsed;elapsed.start();
|
||||
for(int offset=0;offset<desired.size();offset+=384){
|
||||
require(elapsed.elapsed()<60000,"Code upload deadline exceeded");bool acknowledged=false;
|
||||
NativeCustom::wait([&](QObject *owner,std::function<void()> finish){auto reply=[&,finish](bool value,quint32 at){if(at!=quint32(offset))return;acknowledged=value;finish();};if(kind=="lisp")QObject::connect(cmd,&Commands::lispWriteCodeRx,owner,reply);else QObject::connect(cmd,&Commands::writeQmluiResReceived,owner,reply);},[&]{if(kind=="lisp")cmd->lispWriteCode(desired.mid(offset,384),offset);else cmd->qmlUiWrite(desired.mid(offset,384),offset);},2000);
|
||||
require(acknowledged,"Code write rejected");
|
||||
}
|
||||
require(read(cmd,kind)==(erase?QByteArray():desired.mid(8)),"Code readback mismatch");
|
||||
FW_RX_PARAMS after;require(Utility::getFwVersionBlocking(&vesc,&after,2000),"Code identity readback missing");requireSameCanIdentity(identity,after);
|
||||
if(kind=="qml")require(after.hasQmlApp==!erase && (erase || after.qmlAppFullscreen==(quint8(desired[7])==2)),"QML flags readback differs");
|
||||
// Upload never starts Lisp or creates a QML engine/view.
|
||||
return {{"verified",true},{"running_requested",false}};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "config_export.h"
|
||||
#include <cmath>
|
||||
#include <QSet>
|
||||
|
||||
static QJsonValue configValue(const ConfigParam &p) {
|
||||
switch (p.type) {
|
||||
case CFG_T_DOUBLE: return p.valDouble;
|
||||
case CFG_T_INT: case CFG_T_ENUM: case CFG_T_BITFIELD: return p.valInt;
|
||||
case CFG_T_BOOL: return bool(p.valInt);
|
||||
case CFG_T_QSTRING: return p.valString;
|
||||
default: return QJsonValue();
|
||||
}
|
||||
}
|
||||
|
||||
static void validateEdit(const ConfigParam &p, const QJsonValue &v) {
|
||||
if (p.type == CFG_T_BOOL) { require(v.isBool(), "Expected a boolean parameter"); return; }
|
||||
if (p.type == CFG_T_QSTRING) {
|
||||
require(v.isString() && v.toString().size() <= p.maxLen, "String parameter exceeds its native bound"); return;
|
||||
}
|
||||
require(v.isDouble() && std::isfinite(v.toDouble()), "Expected a finite number");
|
||||
const double n = v.toDouble();
|
||||
if (p.type == CFG_T_DOUBLE) require(n >= p.minDouble && n <= p.maxDouble, "Number outside native parameter bounds");
|
||||
else {
|
||||
require(std::trunc(n) == n && n >= -2147483648.0 && n <= 2147483647.0, "Expected a bounded integer");
|
||||
if (p.type == CFG_T_ENUM) require(n >= 0 && n < p.enumNames.size(), "Unknown native enum value");
|
||||
else if (p.type == CFG_T_BITFIELD) require(n >= 0 && n <= 255, "Invalid bitfield value");
|
||||
else { require(p.type == CFG_T_INT, "Unsupported parameter type"); require(n >= p.minInt && n <= p.maxInt, "Integer outside native parameter bounds"); }
|
||||
}
|
||||
}
|
||||
|
||||
static void updateEdit(ConfigParams *config, const QString &name, const QJsonValue &v) {
|
||||
require(config->hasParam(name), "Unknown parameter name");
|
||||
const auto p = config->getParamCopy(name);
|
||||
require(p.transmittable && config->getSerializeOrder().contains(name), "Parameter is not transmitted by this firmware");
|
||||
validateEdit(p, v);
|
||||
switch (p.type) {
|
||||
case CFG_T_DOUBLE: config->updateParamDouble(name, v.toDouble()); break;
|
||||
case CFG_T_INT: case CFG_T_BITFIELD: config->updateParamInt(name, v.toInt()); break;
|
||||
case CFG_T_ENUM: config->updateParamEnum(name, v.toInt()); break;
|
||||
case CFG_T_BOOL: config->updateParamBool(name, v.toBool()); break;
|
||||
case CFG_T_QSTRING: config->updateParamString(name, v.toString()); break;
|
||||
default: throw std::runtime_error("Unsupported parameter editor");
|
||||
}
|
||||
}
|
||||
|
||||
static QByteArray configPacket(ConfigParams *config, int code) {
|
||||
VByteArray raw; raw.vbAppendInt8(code); config->serialize(raw); return raw;
|
||||
}
|
||||
|
||||
static void loadExactConfig(ConfigParams *config, const QByteArray &packet, int code) {
|
||||
const auto shape = configPacket(config, code);
|
||||
require(packet.size() == shape.size() && packet.size() > 5 && quint8(packet[0]) == code,
|
||||
"Configuration packet shape mismatch");
|
||||
VByteArray raw(packet.mid(1));
|
||||
require(config->deSerialize(raw) && raw.isEmpty(), "Native configuration decoder rejected payload");
|
||||
require(configPacket(config, code) == packet, "Configuration packet is not byte-exact");
|
||||
}
|
||||
|
||||
// Validate the flat value document before handing it to upstream setXML. Never
|
||||
// import a parameter-definition/schema document or silently ignore unknown tags.
|
||||
static void validateConfigXml(ConfigParams *config, const QString &xml, const QString &root) {
|
||||
require(!xml.isEmpty() && xml.toUtf8().size() <= 32768, "XML exceeds import bound");
|
||||
QXmlStreamReader reader(xml);
|
||||
QSet<QString> seen;
|
||||
int depth = 0; bool rooted = false;
|
||||
while (!reader.atEnd()) {
|
||||
const auto token = reader.readNext();
|
||||
require(token != QXmlStreamReader::DTD && token != QXmlStreamReader::EntityReference,
|
||||
"XML entities and DTD are not accepted");
|
||||
if (token == QXmlStreamReader::StartElement) {
|
||||
++depth;
|
||||
if (depth == 1) { require(!rooted && reader.name() == root, "Wrong configuration XML root"); rooted = true; continue; }
|
||||
require(depth == 2, "Nested XML values are not accepted");
|
||||
const auto name = reader.name().toString();
|
||||
if(name=="ConfigVersion" && config->getStoreConfigVersion()) {
|
||||
require(!seen.contains(name),"Duplicate XML version");seen.insert(name);
|
||||
require(reader.readElementText(QXmlStreamReader::ErrorOnUnexpectedElement)==QString::number(VT_CONFIG_VERSION),"XML configuration version differs");--depth;continue;
|
||||
}
|
||||
require(config->hasParam(name) && !seen.contains(name), "Unknown or duplicate XML parameter");
|
||||
seen.insert(name);
|
||||
const auto p = config->getParamCopy(name);
|
||||
const auto text = reader.readElementText(QXmlStreamReader::ErrorOnUnexpectedElement);
|
||||
require(!reader.hasError(), "Malformed XML parameter");
|
||||
--depth;
|
||||
bool ok = true;
|
||||
if (p.type == CFG_T_QSTRING) {
|
||||
if (p.transmittable) require(text.size() <= p.maxLen, "XML string exceeds parameter bound");
|
||||
else require(text == p.valString, "XML changes non-transmitted metadata");
|
||||
}
|
||||
else if (p.type == CFG_T_BOOL) require(text == "0" || text == "1", "Invalid XML boolean");
|
||||
else {
|
||||
const auto n = text.toDouble(&ok);
|
||||
require(ok && std::isfinite(n), "Invalid XML number");
|
||||
if (p.type != CFG_T_DOUBLE) require(std::trunc(n) == n, "Invalid XML integer");
|
||||
}
|
||||
} else if (token == QXmlStreamReader::EndElement) --depth;
|
||||
}
|
||||
require(!reader.hasError() && rooted && depth == 0 && !seen.isEmpty(), "Incomplete configuration XML");
|
||||
}
|
||||
|
||||
static QJsonObject prepareConfig(ConfigParams *before, const QJsonObject &source, int code, const QString &root) {
|
||||
ConfigParams candidate; candidate = *before;
|
||||
require(source.size() == 1, "One configuration source is required");
|
||||
if (source.contains("changes")) {
|
||||
require(source.value("changes").isObject(), "Changes must be an object");
|
||||
const auto changes = source.value("changes").toObject();
|
||||
require(changes.size() <= 512, "Too many changed parameters");
|
||||
for (auto i = changes.begin(); i != changes.end(); ++i) updateEdit(&candidate, i.key(), i.value());
|
||||
} else if (source.contains("xml")) {
|
||||
require(source.value("xml").isString(), "XML must be a string");
|
||||
const auto xml = source.value("xml").toString();
|
||||
validateConfigXml(before, xml, root);
|
||||
QXmlStreamReader reader(xml);
|
||||
require(candidate.setXML(reader, root), "Upstream rejected XML configuration");
|
||||
} else if (source.contains("payload")) {
|
||||
const auto encoded = source.value("payload").toString().toLatin1();
|
||||
const auto bytes = QByteArray::fromBase64(encoded, QByteArray::AbortOnBase64DecodingErrors);
|
||||
require(bytes.toBase64() == encoded, "Invalid backup encoding");
|
||||
loadExactConfig(&candidate, bytes, code);
|
||||
} else throw std::runtime_error("Unsupported configuration source");
|
||||
for (const auto &name : candidate.getParamOrder()) {
|
||||
const auto p = candidate.getParamCopy(name);
|
||||
if (configValue(p) == configValue(before->getParamCopy(name))) continue;
|
||||
require(p.transmittable && candidate.getSerializeOrder().contains(name), "XML changes a non-transmitted value");
|
||||
validateEdit(p, configValue(p));
|
||||
}
|
||||
const auto packet = configPacket(&candidate, code);
|
||||
// Show actual representable values, including native wire quantization.
|
||||
loadExactConfig(&candidate, packet, code);
|
||||
QJsonArray changes;
|
||||
for (const auto &name : candidate.getSerializeOrder()) {
|
||||
const auto p = candidate.getParamCopy(name), old = before->getParamCopy(name);
|
||||
if (configValue(p) != configValue(old)) changes.append(QJsonObject{
|
||||
{"name", name}, {"title", p.longName}, {"before", configValue(old)}, {"after", configValue(p)},
|
||||
{"suffix", p.suffix}, {"editor_scale", p.editorScale}});
|
||||
}
|
||||
return {{"before_sha256", sha256(configPacket(before, code))}, {"after_sha256", sha256(packet)},
|
||||
{"payload", QString::fromLatin1(packet.toBase64())}, {"changes", changes}};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include "config_edit.h"
|
||||
#include "bms_native.h"
|
||||
#include <QElapsedTimer>
|
||||
#include <QTimer>
|
||||
#include <QtEndian>
|
||||
|
||||
// All protocol serialization/decoding remains in upstream Commands/ConfigParams.
|
||||
// Replies are correlated by configuration index and exact offset; no write retry.
|
||||
class NativeCustom {
|
||||
public:
|
||||
template<class Setup, class Send> static void wait(Setup setup, Send send, int ms=1800) {
|
||||
QEventLoop loop; QTimer timeout; QObject owner; bool done=false;
|
||||
timeout.setSingleShot(true);
|
||||
std::function<void()> finish=[&] {done=true;loop.quit();};
|
||||
setup(&owner,finish);
|
||||
QObject::connect(&timeout,&QTimer::timeout,&loop,&QEventLoop::quit);
|
||||
timeout.start(ms);send();if(!done)loop.exec();
|
||||
require(done,"Custom configuration reply timed out");
|
||||
}
|
||||
static void schema(ConfigParams &config,const QByteArray &compressed) {
|
||||
require(compressed.size()>=5 && compressed.size()<=65536,"Custom schema size invalid");
|
||||
const auto size=qFromBigEndian<quint32>(reinterpret_cast<const uchar*>(compressed.constData()));
|
||||
require(size>0 && size<=512*1024,"Custom schema decompression bound exceeded");
|
||||
const auto xml=qUncompress(compressed);
|
||||
require(xml.size()==int(size),"Custom schema compression invalid");
|
||||
QXmlStreamReader scan(xml);int elements=0;
|
||||
while(!scan.atEnd()){auto t=scan.readNext();require(t!=QXmlStreamReader::DTD && t!=QXmlStreamReader::EntityReference,"Custom schema entities forbidden");if(t==QXmlStreamReader::StartElement)require(++elements<=16000,"Custom schema too complex");}
|
||||
require(!scan.hasError(),"Malformed custom schema");
|
||||
require(config.loadCompressedParamsXml(compressed),"Upstream rejected custom schema");
|
||||
require(config.getParamOrder().size()>0 && config.getParamOrder().size()<=512 && config.getSerializeOrder().size()<=512,"Custom parameter count invalid");
|
||||
for(const auto &name:config.getSerializeOrder()) {
|
||||
auto p=config.getParamCopy(name);
|
||||
require(QRegularExpression("^[A-Za-z_][A-Za-z0-9_]{0,95}$").match(name).hasMatch(),"Custom parameter name invalid");
|
||||
if(p.type==CFG_T_QSTRING)require(p.maxLen>=0 && p.maxLen<=1024,"Custom string size invalid");
|
||||
require(p.enumNames.size()<=256,"Custom enum too large");
|
||||
}
|
||||
}
|
||||
static QByteArray getSchema(Commands *cmd,int index) {
|
||||
QByteArray data;int total=-1;QElapsedTimer elapsed;elapsed.start();
|
||||
do {
|
||||
require(elapsed.elapsed()<20000,"Custom schema read deadline");
|
||||
const int offset=data.size(),amount=total<0?10:qMin(400,total-offset);
|
||||
int receivedTotal=-1;QByteArray chunk;bool invalid=false;
|
||||
wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::customConfigChunkRx,owner,[&,finish](int id,int length,int at,QByteArray bytes){
|
||||
if(id!=index || at!=offset)return;
|
||||
invalid=length<1||length>65536||bytes.isEmpty()||bytes.size()>amount||at+bytes.size()>length||(total>=0&&length!=total);
|
||||
receivedTotal=length;chunk=bytes;finish();
|
||||
});},[&]{cmd->customConfigGetChunk(index,amount,offset);});
|
||||
require(!invalid,"Custom schema fragment mismatch");total=receivedTotal;data.append(chunk);
|
||||
}while(data.size()<total);
|
||||
return data;
|
||||
}
|
||||
static QByteArray read(Commands *cmd,ConfigParams *config,int index,bool defaults=false) {
|
||||
QByteArray bytes;
|
||||
wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::customConfigRx,owner,[&,finish](int id,QByteArray data){if(id==index){bytes=data;finish();}});},[&]{cmd->customConfigGet(index,defaults);});
|
||||
require(bytes.size()>4 && bytes.size()<=16384,"Custom configuration size invalid");
|
||||
// The adapter prefix is a local archive type tag; Commands owns the wire index.
|
||||
QByteArray packet(1,char(COMM_GET_CUSTOM_CONFIG));packet.append(bytes);
|
||||
loadExactConfig(config,packet,COMM_GET_CUSTOM_CONFIG);return packet;
|
||||
}
|
||||
static QJsonObject run(VescInterface &vesc,bool &remote,const QJsonObject &req) {
|
||||
const auto method=req.value("method").toString();
|
||||
const auto id=req.value("can_id"),ix=req.value("index");
|
||||
require(id.isDouble()&&id.toDouble()==id.toInt(-1)&&id.toInt()>=0&&id.toInt()<=253,"Exact CAN address required");
|
||||
require(ix.isDouble()&&ix.toDouble()==ix.toInt(-1)&&ix.toInt()>=0&&ix.toInt()<8,"Custom configuration index invalid");
|
||||
NativeCanTarget route(vesc,remote,id.toInt());const auto target=route.identify();
|
||||
require(bmsCommandsSupported(target) && ix.toInt()<target.customConfigNum,"BMS configuration profile unavailable");
|
||||
const auto identity=canIdentity(target,id.toInt());
|
||||
if(req.contains("target"))require(req.value("target").toObject()==identity,"BMS identity changed");
|
||||
auto cmd=vesc.commands();
|
||||
require(cmd->getLimitedCompatibilityCommands().contains(COMM_GET_CUSTOM_CONFIG_XML),"Transport does not support custom configuration");
|
||||
const auto compressed=getSchema(cmd,ix.toInt());ConfigParams config;schema(config,compressed);
|
||||
const auto before=read(cmd,&config,ix.toInt());
|
||||
QJsonObject result{{"target",identity},{"index",ix},{"schema_sha256",sha256(compressed)},
|
||||
{"schema",QString::fromLatin1(compressed.toBase64())},{"payload",QString::fromLatin1(before.toBase64())},
|
||||
{"configuration",exportConfig(&config,before,"CustomConfiguration")}};
|
||||
if(method=="custom_preview"||method=="custom_apply") {
|
||||
require(req.value("schema_sha256").toString()==sha256(compressed) && req.value("baseline").toString()==sha256(before),"BMS configuration changed since read");
|
||||
QJsonObject source=req.value("source").toObject();
|
||||
if(req.value("defaults").toBool()) {ConfigParams defaults;defaults=config;source={{"payload",QString::fromLatin1(read(cmd,&defaults,ix.toInt(),true).toBase64())}};}
|
||||
auto candidate=prepareConfig(&config,source,COMM_GET_CUSTOM_CONFIG,"CustomConfiguration");
|
||||
result.insert("candidate",candidate);
|
||||
if(method=="custom_apply") {
|
||||
require(req.value("after_sha256")==candidate.value("after_sha256"),"BMS preview changed");
|
||||
requireSameCanIdentity(target,route.identify());
|
||||
const auto desired=QByteArray::fromBase64(candidate.value("payload").toString().toLatin1());
|
||||
if(desired!=before) {
|
||||
loadExactConfig(&config,desired,COMM_GET_CUSTOM_CONFIG);
|
||||
wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::customConfigAckReceived,owner,[=](int index){if(index==ix.toInt())finish();});},[&]{cmd->customConfigSet(ix.toInt(),&config);},3500);
|
||||
require(read(cmd,&config,ix.toInt())==desired,"BMS configuration readback differs");
|
||||
}
|
||||
result.insert("verified",true);
|
||||
}
|
||||
}
|
||||
requireSameCanIdentity(target,route.identify());return result;
|
||||
}
|
||||
};
|
||||
@@ -1,10 +1,20 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Private per-device JSON process adapter. Every wire operation is upstream.
|
||||
#include "config_export.h"
|
||||
#include "config_edit.h"
|
||||
#include "firmware_native.h"
|
||||
#include "tools_native.h"
|
||||
#include "bms_native.h"
|
||||
#include "custom_native.h"
|
||||
#include "code_native.h"
|
||||
#include "package_native.h"
|
||||
#include "engine_profile.h"
|
||||
#include "sample_data.h"
|
||||
#include "qml_broker.h"
|
||||
#include <QEventLoop>
|
||||
#include <QElapsedTimer>
|
||||
#include <QSocketNotifier>
|
||||
#include <QSerialPort>
|
||||
#include <QTcpSocket>
|
||||
#include <QTimer>
|
||||
#include <QFileInfo>
|
||||
#include <cmath>
|
||||
@@ -27,6 +37,9 @@ public:
|
||||
class Engine {
|
||||
public:
|
||||
VescInterface vesc;
|
||||
FirmwareUpload firmwareUpload;
|
||||
NativeSamples samples;
|
||||
bool firmwareQualified = false;
|
||||
Packet *packet;
|
||||
FW_RX_PARAMS identity;
|
||||
bool procedureRunning = false;
|
||||
@@ -34,12 +47,34 @@ public:
|
||||
QJsonObject procedure;
|
||||
bool queryRunning = false;
|
||||
bool allowHardware = false;
|
||||
bool canBridge = false;
|
||||
bool remoteQuery = false;
|
||||
QByteArray lastMotor, lastApplication, lastHall;
|
||||
QTimer outputWatchdog;
|
||||
QElapsedTimer controlClock;
|
||||
qint64 lastLease = -1, lastOutput = -1;
|
||||
int watchdogTrips = 0, leaseCount = 0, outputCount = 0;
|
||||
QString outputKind = "none";
|
||||
QJsonObject controlDiagnostics() const {
|
||||
const auto now = controlClock.elapsed();
|
||||
return {{"watchdog_trips", watchdogTrips}, {"lease_count", leaseCount},
|
||||
{"output_count", outputCount}, {"output_kind", outputKind},
|
||||
{"lease_age_ms", lastLease < 0 ? -1 : now-lastLease},
|
||||
{"output_age_ms", lastOutput < 0 ? -1 : now-lastOutput},
|
||||
{"watchdog_active", outputWatchdog.isActive()}};
|
||||
}
|
||||
void recordOutput(const QString &kind) {
|
||||
outputKind=kind; lastOutput=controlClock.elapsed(); ++outputCount;
|
||||
}
|
||||
|
||||
Engine() {
|
||||
controlClock.start();
|
||||
samples.attach(vesc.commands());
|
||||
vesc.setLoadQmlUiOnConnect(false);
|
||||
vesc.setIgnoreCustomConfigs(true);
|
||||
outputWatchdog.setSingleShot(true);
|
||||
QObject::connect(&outputWatchdog, &QTimer::timeout, [&] {
|
||||
++watchdogTrips; recordOutput("watchdog_release");
|
||||
if (allowHardware && vesc.isPortConnected() && !procedureRunning) {
|
||||
vesc.commands()->setCurrent(0);
|
||||
try { flush(); } catch (...) {}
|
||||
@@ -49,7 +84,7 @@ public:
|
||||
packet = vesc.findChild<Packet *>();
|
||||
require(packet, "Upstream packet transport missing");
|
||||
QObject::connect(vesc.commands(), &Commands::fwVersionReceived,
|
||||
[&](FW_RX_PARAMS value) { identity = value; });
|
||||
[&](FW_RX_PARAMS value) { if(!remoteQuery) identity = value; });
|
||||
QObject::connect(packet, &Packet::packetReceived, [&](QByteArray &raw) {
|
||||
if (!raw.isEmpty() && quint8(raw[0]) == COMM_GET_MCCONF) lastMotor = raw;
|
||||
if (!raw.isEmpty() && quint8(raw[0]) == COMM_GET_APPCONF) lastApplication = raw;
|
||||
@@ -57,6 +92,19 @@ public:
|
||||
});
|
||||
}
|
||||
|
||||
void openCan(int port) {
|
||||
require(port > 0 && port <= 65535, "Invalid private bridge port");
|
||||
canBridge = true;
|
||||
vesc.connectTcp("127.0.0.1", port);
|
||||
QElapsedTimer timer; timer.start();
|
||||
while (!vesc.isPortConnected() && timer.elapsed() < 1500)
|
||||
QCoreApplication::processEvents(QEventLoop::AllEvents, 5);
|
||||
require(vesc.isPortConnected(), "Private CAN bridge did not connect");
|
||||
allowHardware = true;
|
||||
query(COMM_FW_VERSION, 3000);
|
||||
firmwareQualified = nativeFirmwareQualified(identity.major, identity.minor, identity.hwType, identity.isTestFw, identity.customConfigNum);
|
||||
}
|
||||
|
||||
void open(const QString &port) {
|
||||
require(QRegularExpression("^/dev/ttyACM[0-9]+$").match(port).hasMatch(), "Unsupported USB path");
|
||||
struct stat st;
|
||||
@@ -70,9 +118,7 @@ public:
|
||||
"Serial port is already owned");
|
||||
allowHardware = true;
|
||||
query(COMM_FW_VERSION, 3000);
|
||||
require(identity.major == 5 && identity.minor == 2 && identity.hwType == HW_TYPE_VESC
|
||||
&& identity.isTestFw == 0 && identity.customConfigNum == 0,
|
||||
"Native hardware acceptance currently admits stable FW 5.02 only");
|
||||
firmwareQualified = nativeFirmwareQualified(identity.major, identity.minor, identity.hwType, identity.isTestFw, identity.customConfigNum);
|
||||
}
|
||||
|
||||
QByteArray exchange(int command, int timeoutMs, const std::function<void()> &send) {
|
||||
@@ -155,6 +201,38 @@ public:
|
||||
return raw;
|
||||
}
|
||||
|
||||
QJsonObject diagnostic(const QString &command) {
|
||||
require(QStringList{"hw_status", "faults", "fault", "ping", "mem", "threads", "rpm", "tacho", "volt", "uptime", "help"}.contains(command), "Unsupported diagnostic command");
|
||||
require(allowHardware && vesc.isPortConnected() && !procedureRunning && !queryRunning,
|
||||
"Diagnostic unavailable during another operation");
|
||||
queryRunning = true;
|
||||
struct Reset { bool &flag; ~Reset() { flag = false; } } reset{queryRunning};
|
||||
QEventLoop loop;
|
||||
QTimer deadline, quiet;
|
||||
deadline.setSingleShot(true); quiet.setSingleShot(true);
|
||||
QObject observer;
|
||||
QStringList lines;
|
||||
int bytes = 0;
|
||||
bool overflow = false, timedOut = false;
|
||||
QObject::connect(vesc.commands(), &Commands::printReceived, &observer, [&](QString text) {
|
||||
bytes += text.toUtf8().size();
|
||||
if (bytes > 32768 || lines.size() >= 512) { overflow = true; loop.quit(); return; }
|
||||
lines.append(text);
|
||||
quiet.start(200);
|
||||
});
|
||||
QObject::connect(&deadline, &QTimer::timeout, &observer, [&] { timedOut = true; loop.quit(); });
|
||||
QObject::connect(&quiet, &QTimer::timeout, &observer, [&] { loop.quit(); });
|
||||
deadline.start(3000);
|
||||
// Match the upstream Terminal page. FW 5.02 routes print packets through
|
||||
// the blocking-command reply callback; SYNC does not establish it.
|
||||
vesc.commands()->sendTerminalCmd(command);
|
||||
flush();
|
||||
loop.exec();
|
||||
require(!overflow && !timedOut && !lines.isEmpty(), "Incomplete diagnostic response");
|
||||
return {{"command", command}, {"text", lines.join("\n")},
|
||||
{"completion", "200ms-print-quiescence"}};
|
||||
}
|
||||
|
||||
QByteArray configurationPacket(ConfigParams *config, int code) {
|
||||
VByteArray raw; raw.vbAppendInt8(code); config->serialize(raw); return raw;
|
||||
}
|
||||
@@ -241,6 +319,23 @@ public:
|
||||
}
|
||||
|
||||
void flush() {
|
||||
if (canBridge) {
|
||||
// A TCP write alone cannot confirm SDK acceptance. This private
|
||||
// FIFO marker is acknowledged only after preceding CAN sends.
|
||||
bool acknowledged = false;
|
||||
QEventLoop loop; QTimer timer; timer.setSingleShot(true);
|
||||
QObject observer;
|
||||
const QByteArray marker = QByteArray::fromHex("ff4d434252");
|
||||
QObject::connect(packet, &Packet::packetReceived, &observer, [&](QByteArray &data) {
|
||||
if (data == marker) { acknowledged = true; loop.quit(); }
|
||||
});
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
QByteArray request = marker; packet->sendPacket(request);
|
||||
timer.start(60);
|
||||
if (!acknowledged) loop.exec();
|
||||
require(acknowledged && vesc.isPortConnected(), "CAN write not confirmed");
|
||||
return;
|
||||
}
|
||||
auto serial = vesc.findChild<QSerialPort *>();
|
||||
require(serial && serial->isOpen(), "Serial transport closed");
|
||||
serial->flush();
|
||||
@@ -250,18 +345,65 @@ public:
|
||||
|
||||
QJsonObject dispatch(const QJsonObject &request) {
|
||||
const auto method = request.value("method").toString();
|
||||
if (method == "engine") return {{"version", "7.00"}, {"commit", "01d5f10901116c311e3fb84d5a1541f663d3ce20"},
|
||||
{"connected", vesc.isPortConnected()}, {"hardware_enabled", allowHardware},
|
||||
if (method == "engine") return {{"version", QString::number(VT_VERSION, 'f', 2)},
|
||||
{"commit", engineProfile().value("upstream").toObject().value("commit")},
|
||||
{"contract", engineProfile().value("contract")},
|
||||
{"connected", vesc.isPortConnected()}, {"hardware_enabled", allowHardware}, {"firmware_admitted", firmwareQualified},
|
||||
{"legacy_power_loss_correction", vesc.commands()->getMaxPowerLossBug()}};
|
||||
require(allowHardware && vesc.isPortConnected(), "Native device is not connected");
|
||||
if (method == "package_unpack") return NativePackage::inspect(request);
|
||||
if (method == "code_pack") {const auto data=NativeCode::pack(request.value("project").toObject());return {{"image",QString::fromLatin1(data.toBase64())},{"sha256",sha256(data)},{"bytes",data.size()}};}
|
||||
require(allowHardware, "Native hardware operations are disabled");
|
||||
if (method == "firmware_status") return firmwareUpload.state;
|
||||
if (method == "firmware_cancel") {
|
||||
require(firmwareUpload.running, "No active upload");
|
||||
firmwareUpload.cancel(vesc); return {{"cancel_requested", true}};
|
||||
}
|
||||
require(!firmwareUpload.running, "Firmware upload owns this controller");
|
||||
require(!remoteQuery, "CAN target operation owns this controller");
|
||||
require(vesc.isPortConnected(), "Native device is not connected");
|
||||
if (method == "sample_start" || method == "sample_status" || method == "sample_fetch" || method == "sample_stop" || method == "sample_read") {
|
||||
require(firmwareQualified && identity.major==5 && identity.minor==2,"Sample Data profile unsupported");
|
||||
if(method=="sample_start" && (procedureRunning || procedureUncertain))
|
||||
return {{"accepted",false},{"reason","Motor measurement is active"}};
|
||||
auto result=samples.run(method,request);
|
||||
if(method=="sample_start" || method=="sample_stop" || method=="sample_fetch")flush();
|
||||
return result;
|
||||
}
|
||||
if(samples.active() && QStringList{"firmware_start","firmware_target","firmware_snapshot","custom_read","custom_preview","custom_apply","bms_read","configuration_apply","foc_start","hall_start","code_write","code_control","bms_command"}.contains(method))
|
||||
throw std::runtime_error("Stop Sample Data before changing the controller");
|
||||
if (method == "code_snapshot" || method == "code_read" || method == "code_write" || method == "code_control" || method == "code_stats") {
|
||||
require(!queryRunning && !procedureRunning && !procedureUncertain && !outputWatchdog.isActive(), "Controller operation already active");
|
||||
query(COMM_FW_VERSION,2000);const auto before=identity;
|
||||
auto result=NativeCode::run(vesc,identity,request);
|
||||
query(COMM_FW_VERSION,2000);requireSameCanIdentity(before,identity);return result;
|
||||
}
|
||||
// Unknown firmware is identity-only, so a post-update UUID/version can
|
||||
// be observed without silently admitting an unqualified config schema.
|
||||
if (!firmwareQualified) {
|
||||
require(method == "query" && request.value("command").toInt(-1) == COMM_FW_VERSION,
|
||||
"Firmware supports identification only in this engine release");
|
||||
}
|
||||
if (method == "qml_read") {
|
||||
require(!procedureRunning&&!procedureUncertain&&!samples.active()&&!outputWatchdog.isActive(),"Controller is busy");
|
||||
auto intent=request.value("intent").toObject();validateQmlRead(intent);
|
||||
int code=intent.value("command").toInt();auto cmd=vesc.commands();
|
||||
require(qmlReadSupported(cmd,code),"QML read unsupported by firmware");
|
||||
QByteArray raw;
|
||||
if(code==32)raw=exchange(code,1000,[=]{cmd->getDecodedAdc();});
|
||||
else if(code==33)raw=exchange(code,1000,[=]{cmd->getDecodedChuk();});
|
||||
else if(code==65)raw=exchange(code,1000,[=]{cmd->getImuData(intent.value("mask").toInt());});
|
||||
else if(code==96)raw=exchange(code,1000,[=]{cmd->bmsGetValues();});
|
||||
else raw=query(code,1000);
|
||||
return {{"payload",QString::fromLatin1(raw.toBase64())}};
|
||||
}
|
||||
if (method == "query") return {{"payload", QString::fromLatin1(query(
|
||||
int(number(request, "command", 0, 255)), int(number(request, "timeout_ms", 20, 8000))).toBase64())}};
|
||||
if (method == "procedure_result") return {{"running", procedureRunning}, {"uncertain", procedureUncertain}, {"result", procedure}};
|
||||
if (method == "lease") {
|
||||
require(!procedureRunning && !procedureUncertain, "Native procedure owns this controller");
|
||||
vesc.commands()->disableAppOutput(250, false); flush(); outputWatchdog.start(200); return {};
|
||||
vesc.commands()->disableAppOutput(250, false); flush(); lastLease=controlClock.elapsed(); ++leaseCount; outputWatchdog.start(200); return {};
|
||||
}
|
||||
if (method == "release") { vesc.commands()->setCurrent(0); flush(); return {}; }
|
||||
if (method == "release") { vesc.commands()->setCurrent(0); flush(); recordOutput("release"); return {}; }
|
||||
require(!procedureRunning && !procedureUncertain, "Native procedure owns this controller");
|
||||
if (method == "current") {
|
||||
require(outputWatchdog.isActive(), "Output lease expired");
|
||||
@@ -270,6 +412,29 @@ public:
|
||||
vesc.commands()->setCurrent(current); flush(); return {};
|
||||
}
|
||||
if (method == "rpm") { require(outputWatchdog.isActive(), "Output lease expired"); vesc.commands()->setRpm(int(number(request, "erpm", -3000, 3000))); flush(); return {}; }
|
||||
if (method == "duty" || method == "duty_limited") {
|
||||
require(outputWatchdog.isActive(), "Output lease expired");
|
||||
require(!lastMotor.isEmpty() && !lastApplication.isEmpty(), "Read configurations before driving");
|
||||
auto mc = vesc.mcConfig();
|
||||
require(vesc.appConfig()->getParamEnum("app_ppm_conf.ctrl_type") == 4, "PPM Duty Cycle profile required");
|
||||
const auto limit = mc->getParamDouble("l_max_duty");
|
||||
require(std::isfinite(limit) && limit > 0 && limit <= 1, "Invalid configured duty limit");
|
||||
const auto current = mc->getParamDouble("l_current_max") * mc->getParamDouble("l_current_max_scale");
|
||||
const auto braking = -mc->getParamDouble("l_current_min") * mc->getParamDouble("l_current_min_scale");
|
||||
// Legacy duty RPC retains its original bounded contract. Remote
|
||||
// driving supplies the operator's request end to end, and may
|
||||
// only use scales within the controller's configured envelope.
|
||||
const auto requested = method == "duty" ? 30.0 : request.value("current_a").toDouble(-1);
|
||||
require(std::isfinite(requested) && requested >= .5, "Invalid requested current ceiling");
|
||||
for (const auto &key : {"l_current_max_scale", "l_current_min_scale"})
|
||||
require(mc->getParamDouble(key) > 0 && mc->getParamDouble(key) <= 1, "Invalid configured current scale");
|
||||
require(std::isfinite(current) && current > 0 && current <= requested + .001 &&
|
||||
std::isfinite(braking) && braking > 0 && braking <= requested + .001, "Apply the requested current ceiling first");
|
||||
auto duty = number(request, "duty", -limit, limit);
|
||||
if (method == "duty" && std::abs(duty) < 0.00001) vesc.commands()->setCurrent(0);
|
||||
else vesc.commands()->setDutyCycle(duty);
|
||||
flush(); recordOutput("duty"); return {};
|
||||
}
|
||||
if (method == "limits") {
|
||||
auto p = request.value("parameters").toObject();
|
||||
MCCONF_TEMP conf;
|
||||
@@ -289,12 +454,111 @@ public:
|
||||
});
|
||||
require(ack.size() == 1, "Invalid native limits ACK"); return {};
|
||||
}
|
||||
if (method == "firmware_start") {
|
||||
require(!outputWatchdog.isActive(), "Output lease is active");
|
||||
query(COMM_FW_VERSION, 2000);
|
||||
return firmwareUpload.start(vesc, request, identity, remoteQuery);
|
||||
}
|
||||
if (method == "firmware_target" || method == "firmware_snapshot" || (method == "firmware_begin" && request.contains("can_id"))) {
|
||||
require(!queryRunning && !outputWatchdog.isActive(), "Controller operation already active");
|
||||
const double id=number(request,"can_id",0,253);require(id==int(id),"Integral CAN address required");
|
||||
NativeCanTarget route(vesc,remoteQuery,int(id));const auto target=route.identify();
|
||||
const bool admitted=nativeFirmwareQualified(target.major,target.minor,target.hwType,target.isTestFw,target.customConfigNum);
|
||||
if(method=="firmware_target")return {{"target",canIdentity(target,int(id))},{"admitted",admitted}};
|
||||
require(admitted,"CAN firmware schema not qualified");
|
||||
if(method=="firmware_begin")return firmwareUpload.stage(method,request,target);
|
||||
require(request.value("target").toObject()==canIdentity(target,int(id)),"CAN target changed since selection");
|
||||
// Decode with the admitted schema, then restore local configuration
|
||||
// and packet baselines even on a failed remote read.
|
||||
ConfigParams mc,app;mc=*vesc.mcConfig();app=*vesc.appConfig();
|
||||
struct Restore { Engine &e;ConfigParams &mc,&app;QByteArray motor,application;
|
||||
~Restore(){*e.vesc.mcConfig()=mc;*e.vesc.appConfig()=app;e.lastMotor=motor;e.lastApplication=application;}
|
||||
} restore{*this,mc,app,lastMotor,lastApplication};
|
||||
QJsonObject packets;
|
||||
for(int code:{COMM_GET_MCCONF,COMM_GET_APPCONF,COMM_GET_VALUES,COMM_GET_DECODED_PPM})
|
||||
packets.insert(QString::number(code),QString::fromLatin1(query(code,2000).toBase64()));
|
||||
requireSameCanIdentity(target,route.identify());
|
||||
return {{"target",canIdentity(target,int(id))},{"packets",packets}};
|
||||
}
|
||||
if (method == "firmware_begin" || method == "firmware_chunk" || method == "firmware_seal")
|
||||
return firmwareUpload.stage(method, request, identity);
|
||||
if (method == "custom_read" || method == "custom_preview" || method == "custom_apply") {
|
||||
require(!queryRunning && !outputWatchdog.isActive(), "Controller operation already active");
|
||||
require(QStringList{"custom_read","custom_preview","custom_apply"}.contains(method), "Unknown custom operation");
|
||||
return NativeCustom::run(vesc,remoteQuery,request);
|
||||
}
|
||||
if (method == "bms_read" || method == "bms_command") {
|
||||
require(!queryRunning && !outputWatchdog.isActive(), "Controller operation already active");
|
||||
const double idNumber=number(request,"can_id",0,253);
|
||||
require(idNumber==int(idNumber),"Integral CAN address required");
|
||||
const int id=int(idNumber);
|
||||
NativeCanTarget route(vesc,remoteQuery,id);
|
||||
const auto target=route.identify();
|
||||
const auto targetJson=canIdentity(target,id);
|
||||
if(method == "bms_read") {
|
||||
if(target.hwType!=HW_TYPE_VESC_BMS)
|
||||
return {{"state","not_bms"},{"target",targetJson},{"commands_supported",false}};
|
||||
auto value=readNativeTool(vesc,"bms");
|
||||
requireSameCanIdentity(target,route.identify());
|
||||
if(bmsCommandsSupported(target) && value.value("state")=="received")
|
||||
require(value.value("values").toObject().value("can_id").toInt(-1)==id,"BMS reply CAN address differs");
|
||||
value.insert("target",targetJson);
|
||||
value.insert("source","direct_can");
|
||||
value.insert("commands_supported",bmsCommandsSupported(target));
|
||||
return value;
|
||||
}
|
||||
require(bmsCommandsSupported(target),"BMS firmware control profile unsupported");
|
||||
require(request.value("target").toObject()==targetJson,"BMS target changed after preview");
|
||||
bool emitted=false; QObject observer;
|
||||
QObject::connect(vesc.commands(),&Commands::dataToSend,&observer,[&](QByteArray &raw){
|
||||
if(raw.size()>=3 && quint8(raw[0])==COMM_FORWARD_CAN && quint8(raw[1])==id)emitted=true;
|
||||
});
|
||||
sendBmsCommand(vesc.commands(),request.value("command").toString());
|
||||
require(emitted,"BMS command not emitted");flush();
|
||||
return {{"sent",true},{"acknowledged",false},{"target",targetJson}};
|
||||
}
|
||||
if (method == "device_tool") return readNativeTool(vesc, request.value("tool").toString());
|
||||
if (method == "diagnostic") return diagnostic(request.value("command").toString());
|
||||
if (method == "configuration") {
|
||||
auto motor = query(COMM_GET_MCCONF, 2000);
|
||||
auto application = query(COMM_GET_APPCONF, 2000);
|
||||
return {{"motor", exportConfig(vesc.mcConfig(), motor, "MCConfiguration")},
|
||||
{"application", exportConfig(vesc.appConfig(), application, "APPConfiguration")}};
|
||||
}
|
||||
if (method == "configuration_preview") {
|
||||
query(COMM_GET_MCCONF, 2000); query(COMM_GET_APPCONF, 2000);
|
||||
const auto sources = request.value("sources").toObject();
|
||||
require(!sources.isEmpty() && sources.size() <= 2, "Configuration source is empty");
|
||||
QJsonObject result;
|
||||
for (auto i = sources.begin(); i != sources.end(); ++i) {
|
||||
require(i.key() == "motor" || i.key() == "application", "Invalid configuration kind");
|
||||
const bool motor = i.key() == "motor";
|
||||
result.insert(i.key(), prepareConfig(motor ? vesc.mcConfig() : vesc.appConfig(), i.value().toObject(),
|
||||
motor ? COMM_GET_MCCONF : COMM_GET_APPCONF, motor ? "MCConfiguration" : "APPConfiguration"));
|
||||
}
|
||||
return {{"configs", result}, {"baseline", QJsonObject{{"motor", sha256(lastMotor)}, {"application", sha256(lastApplication)}}}};
|
||||
}
|
||||
if (method == "configuration_apply") {
|
||||
const auto kind = request.value("kind").toString();
|
||||
require(kind == "motor" || kind == "application", "Invalid configuration kind");
|
||||
const bool motor = kind == "motor";
|
||||
const int get = motor ? COMM_GET_MCCONF : COMM_GET_APPCONF;
|
||||
const int set = motor ? COMM_SET_MCCONF : COMM_SET_APPCONF;
|
||||
const auto actual = query(get, 2000);
|
||||
require(sha256(actual) == request.value("before_sha256").toString(), "Configuration changed since preview");
|
||||
auto config = motor ? vesc.mcConfig() : vesc.appConfig();
|
||||
const auto candidate = prepareConfig(config, {{"payload", request.value("payload")}}, get,
|
||||
motor ? "MCConfiguration" : "APPConfiguration");
|
||||
const auto desired = QByteArray::fromBase64(candidate.value("payload").toString().toLatin1());
|
||||
require(candidate.value("after_sha256") == request.value("after_sha256"), "Preview content changed");
|
||||
if (actual == desired) return {{"verified", true}, {"changed", false}};
|
||||
loadExactConfig(config, desired, get);
|
||||
require(exchange(set, 3000, [&] {
|
||||
if (motor) vesc.commands()->setMcconf(false); else vesc.commands()->setAppConf();
|
||||
}).size() == 1, "Configuration write acknowledgement invalid");
|
||||
require(query(get, 3000) == desired, "Written configuration differs from preview");
|
||||
return {{"verified", true}, {"changed", true}};
|
||||
}
|
||||
if (method == "foc_start") {
|
||||
const auto loss = number(request, "max_power_loss_w", 10, 150);
|
||||
require(!lastMotor.isEmpty() && !lastApplication.isEmpty(), "Read configurations before calibration");
|
||||
@@ -335,7 +599,10 @@ int main(int argc, char **argv) {
|
||||
require(argc == 2, "One exact serial port or --offline argument is required");
|
||||
Engine engine;
|
||||
const QString port = QString::fromLocal8Bit(argv[1]);
|
||||
if (port != "--offline") engine.open(port);
|
||||
if (port.startsWith("--can-bridge=")) {
|
||||
bool valid = false; int number = port.mid(13).toInt(&valid);
|
||||
require(valid, "Invalid private CAN bridge argument"); engine.openCan(number);
|
||||
} else if (port != "--offline") engine.open(port);
|
||||
QFile output; output.open(stdout, QIODevice::WriteOnly);
|
||||
auto write = [&](const QJsonObject &value) {
|
||||
output.write(QJsonDocument(value).toJson(QJsonDocument::Compact) + '\n'); output.flush();
|
||||
@@ -349,7 +616,7 @@ int main(int argc, char **argv) {
|
||||
if (size == 0) { application.quit(); return; }
|
||||
if (size < 0) return;
|
||||
buffer.append(chunk, int(size));
|
||||
if (buffer.size() > 65536) { application.exit(2); return; }
|
||||
if (buffer.size() > 2*1024*1024) { application.exit(2); return; }
|
||||
int end;
|
||||
while ((end = buffer.indexOf('\n')) >= 0) {
|
||||
auto raw = buffer.left(end); buffer.remove(0, end + 1);
|
||||
@@ -364,6 +631,7 @@ int main(int argc, char **argv) {
|
||||
response.insert("ok", false); response.insert("error", e.what());
|
||||
response.insert("diagnostics", e.diagnostics);
|
||||
} catch (const std::exception &e) { response.insert("ok", false); response.insert("error", e.what()); }
|
||||
response.insert("control", engine.controlDiagnostics());
|
||||
write(response);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "config_export.h"
|
||||
#include <QtEndian>
|
||||
|
||||
// Transport/file bounds and STM32 vector sanity, not a signature or a board-ID
|
||||
// proof. Hardware and target version remain operator declarations for raw BIN.
|
||||
static QJsonObject inspectFirmwareImage(const QByteArray &raw, const QString &kind) {
|
||||
require(kind == "firmware" || kind == "bootloader", "Unknown image kind");
|
||||
const int bound = kind == "bootloader" ? 65536 : 2 * 1024 * 1024;
|
||||
require(raw.size() >= 256 && raw.size() <= bound, "Image size outside the supported bound");
|
||||
// This upload profile accepts raw STM32 BIN only. Encoded/compressed/Intel
|
||||
// HEX files must be deliberately converted by their owning Tool first.
|
||||
const auto sp = qFromLittleEndian<quint32>(raw.constData());
|
||||
const auto reset = qFromLittleEndian<quint32>(raw.constData() + 4);
|
||||
require(sp >= 0x20000000 && sp <= 0x20040000 && (sp & 3) == 0,
|
||||
"Raw STM32 image has an invalid initial stack pointer");
|
||||
require((reset & 1) && reset >= 0x08000001 && reset < 0x08200000,
|
||||
"Raw STM32 image has an invalid reset vector");
|
||||
// fwUpload owns normalization. Require that it leaves this raw image intact
|
||||
// so the reviewed hash describes exactly the bytes passed to the uploader.
|
||||
require(Packet::crc16(reinterpret_cast<const unsigned char *>(raw.constData()+6), raw.size()-6) != qFromBigEndian<quint16>(raw.constData()+4), "Wrapped firmware is not a raw BIN image");
|
||||
return {{"kind", kind}, {"bytes", raw.size()}, {"sha256", sha256(raw)},
|
||||
{"format", "raw-stm32-bin"}, {"board_identity_embedded", false}};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "firmware_source.h"
|
||||
#include "bms_native.h"
|
||||
#include "swd_native.h"
|
||||
#include <memory>
|
||||
#include <QElapsedTimer>
|
||||
#include <QTimer>
|
||||
|
||||
class FirmwareUpload {
|
||||
QByteArray image;
|
||||
QJsonObject manifest;
|
||||
QElapsedTimer age;
|
||||
bool sealed = false;
|
||||
public:
|
||||
bool running = false;
|
||||
bool consumed = false;
|
||||
bool cancelRequested = false;
|
||||
void cancel(VescInterface &v){cancelRequested=true;v.fwUploadCancel();v.swdCancel();}
|
||||
QJsonObject state{{"state", "empty"}, {"progress", 0}};
|
||||
QJsonObject stage(const QString &method, const QJsonObject &p, const FW_RX_PARAMS &identity) {
|
||||
require(!running, "Firmware upload owns the controller");
|
||||
if (method == "firmware_begin") {
|
||||
require(!p.contains("swd") || (!p.contains("can_id") && p.value("kind")=="firmware"), "SWD cannot share a CAN route or bootloader mode");
|
||||
require(p.value("hardware").toString() == identity.hw && identity.hwType == HW_TYPE_VESC,
|
||||
"Declared hardware does not match this controller");
|
||||
require(p.value("uuid").toString().toLower() == QString::fromLatin1(identity.uuid.toHex()),
|
||||
"Firmware target UUID changed");
|
||||
const int size = p.value("bytes").toInt(-1);
|
||||
const auto format = p.value("format").toString("bin");
|
||||
require(format == "bin" || format == "hex", "Unsupported image format");
|
||||
require(size >= (format == "hex" ? 32 : 256) && size <= (format == "hex" ? 8 : 2) * 1024 * 1024, "Image size outside bound");
|
||||
require(QRegularExpression("^[0-9a-f]{64}$").match(p.value("sha256").toString()).hasMatch(), "Invalid image digest");
|
||||
require(p.value("kind") == "firmware" || p.value("kind") == "bootloader", "Invalid image kind");
|
||||
image.clear(); manifest = p; sealed = consumed = false; age.start();
|
||||
state = {{"state", "staging"}, {"progress", 0}};
|
||||
return {{"offset", 0}};
|
||||
}
|
||||
require(age.isValid() && age.elapsed() < 600000 && !consumed, "Staged image expired or consumed");
|
||||
if (method == "firmware_chunk") {
|
||||
require(!sealed && p.value("offset").toInt(-1) == image.size(), "Image offset changed");
|
||||
const auto text = p.value("data").toString().toLatin1();
|
||||
const auto data = QByteArray::fromBase64(text);
|
||||
require(data.toBase64() == text && !data.isEmpty() && data.size() <= 32768,
|
||||
"Invalid image chunk");
|
||||
require(image.size() + data.size() <= manifest.value("bytes").toInt(), "Image exceeds declared size");
|
||||
image.append(data); return {{"offset", image.size()}};
|
||||
}
|
||||
require(method == "firmware_seal", "Unknown staging operation");
|
||||
require(image.size() == manifest.value("bytes").toInt() && sha256(image) == manifest.value("sha256").toString(),
|
||||
"Image size or digest changed");
|
||||
const auto range=manifest.contains("swd")?swdRange(manifest.value("swd").toObject()):QPair<quint32,int>{0,0};
|
||||
auto source = inspectFirmwareSource(image, manifest.value("kind").toString(), manifest.value("format").toString("bin"),range.first,range.second);
|
||||
image = source.image;
|
||||
auto info = source.info;
|
||||
manifest.insert("sha256", info.value("sha256"));
|
||||
manifest.insert("bytes", image.size());
|
||||
sealed = true; state = {{"state", "ready"}, {"progress", 0}};
|
||||
return info;
|
||||
}
|
||||
QJsonObject start(VescInterface &vesc, const QJsonObject &p, const FW_RX_PARAMS &identity, bool &remoteQuery) {
|
||||
require(!running && !consumed && sealed && age.elapsed() < 600000, "No fresh sealed image");
|
||||
std::shared_ptr<NativeCanTarget> route;
|
||||
FW_RX_PARAMS target=identity;
|
||||
if(manifest.contains("can_id")) {
|
||||
route=std::make_shared<NativeCanTarget>(vesc,remoteQuery,manifest.value("can_id").toInt(-1));
|
||||
target=route->identify();
|
||||
require(nativeFirmwareQualified(target.major,target.minor,target.hwType,target.isTestFw,target.customConfigNum),"CAN firmware schema not qualified");
|
||||
}
|
||||
require(p.value("sha256") == manifest.value("sha256") && manifest.value("hardware") == target.hw &&
|
||||
manifest.value("uuid") == QString::fromLatin1(target.uuid.toHex()), "Firmware target changed");
|
||||
cancelRequested=false;consumed = running = true; state = {{"state", "uploading"}, {"progress", 0}};
|
||||
// The original upload runs nested Qt event loops; the private input
|
||||
// notifier remains available for status/cancel only. No second owner.
|
||||
QTimer::singleShot(0, [&vesc, this, route] {
|
||||
QTimer bound; bound.setSingleShot(true);
|
||||
QObject::connect(&bound, &QTimer::timeout, [&] { cancel(vesc); });
|
||||
QObject observer;
|
||||
QObject::connect(&vesc, &VescInterface::fwUploadStatus, &observer,
|
||||
[&](const QString &message, double progress, bool) {
|
||||
state.insert("message", message.left(512));
|
||||
state.insert("progress", qBound(0.0, progress, 1.0));
|
||||
});
|
||||
bound.start(240000);
|
||||
bool ok = false;
|
||||
try {
|
||||
require(!cancelRequested,"Upload cancelled before start");
|
||||
if(manifest.contains("swd")) {
|
||||
const auto result=uploadSwd(vesc,manifest.value("swd").toObject(),image,cancelRequested);
|
||||
for(auto i=result.begin();i!=result.end();++i)state.insert(i.key(),i.value());ok=true;
|
||||
} else ok = vesc.fwUpload(image, manifest.value("kind") == "bootloader", false, true, false);
|
||||
}
|
||||
catch (...) { state.insert("message", "Upload exception; outcome unknown"); }
|
||||
image.clear(); sealed = false; running = false;
|
||||
state.insert("state", ok ? "uploaded" : "unknown");
|
||||
state.insert("upload_confirmed", ok);
|
||||
if (ok) state.insert("progress", 1);
|
||||
});
|
||||
return state;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "firmware_image.h"
|
||||
#include "hexfile.h"
|
||||
#include <QTemporaryFile>
|
||||
#include <QMap>
|
||||
#include <algorithm>
|
||||
|
||||
struct FirmwareSource { QByteArray image; QJsonObject info; };
|
||||
|
||||
// Validate the container strictly before passing it to the original HexFile
|
||||
// reader. In particular, upstream's permissive fromHex must not silently omit
|
||||
// junk, duplicate addresses, out-of-order overlapping records or sparse bombs.
|
||||
static FirmwareSource inspectFirmwareSource(const QByteArray &source, const QString &kind, const QString &format, quint32 swdBase=0, int swdLimit=0) {
|
||||
require(format == "bin" || format == "hex", "Use BIN or Intel HEX");
|
||||
require(source.size() >= (format == "hex" ? 32 : 256) && source.size() <= (format == "hex" ? 8 : 2) * 1024 * 1024,
|
||||
"Source file exceeds its bound");
|
||||
QByteArray image = source;
|
||||
quint32 base = swdLimit ? swdBase : kind == "bootloader" ? 0x080E0000 : 0x08000000;
|
||||
const int limit=swdLimit ? swdLimit : kind == "bootloader" ? 65536 : 2*1024*1024;
|
||||
require(limit>0 && limit<=2*1024*1024,"Invalid flash span");
|
||||
int segments = 1;
|
||||
if (format == "hex") {
|
||||
QMap<quint32,quint32> ranges;
|
||||
quint32 offset = 0; bool eof = false; int count = 0;
|
||||
for (auto line : source.split('\n')) {
|
||||
if (line.endsWith('\r')) line.chop(1);
|
||||
if (line.isEmpty()) continue;
|
||||
require(!eof && ++count <= 131074 && line.size() <= 521,
|
||||
"HEX has trailing records or too many records");
|
||||
require(QRegularExpression("^:[0-9A-Fa-f]+$").match(QString::fromLatin1(line)).hasMatch()
|
||||
&& line.size() % 2 == 1, "Invalid HEX characters");
|
||||
const auto record = QByteArray::fromHex(line.mid(1));
|
||||
require(record.size() >= 5 && record.size() == 5 + quint8(record[0]), "Invalid HEX record length");
|
||||
unsigned sum = 0; for (unsigned char c : record) sum += c;
|
||||
require((sum & 255) == 0, "Invalid HEX checksum");
|
||||
const int length = quint8(record[0]), type = quint8(record[3]);
|
||||
const quint32 address = (quint8(record[1]) << 8) | quint8(record[2]);
|
||||
if (type == 0) {
|
||||
require(length > 0 && address + length <= 65536, "HEX record crosses address window");
|
||||
// HexFile uses OR for these parts. Reject ambiguous segment
|
||||
// combinations rather than reinterpret the upstream output.
|
||||
require((offset & address) == 0, "Ambiguous HEX segment address");
|
||||
const quint64 start = quint64(offset) + address, end = start + length;
|
||||
require(start >= base && end <= quint64(base) + limit,
|
||||
"HEX address does not belong to the selected image kind");
|
||||
auto next = ranges.lowerBound(quint32(start));
|
||||
require(next == ranges.end() || next.key() >= end, "Overlapping HEX records");
|
||||
if (next != ranges.begin()) { auto prev = next; --prev; require(prev.value() <= start, "Overlapping HEX records"); }
|
||||
ranges.insert(quint32(start), quint32(end));
|
||||
} else if (type == 1) {
|
||||
require(length == 0 && address == 0, "Invalid HEX EOF"); eof = true;
|
||||
} else if (type == 2 || type == 4) {
|
||||
require(length == 2 && address == 0, "Invalid HEX address record");
|
||||
offset = quint32((quint8(record[4]) << 8) | quint8(record[5])) << (type == 2 ? 4 : 16);
|
||||
} else if (type == 3 || type == 5) {
|
||||
require(length == 4 && address == 0, "Invalid HEX entry point");
|
||||
} else require(false, "Unsupported HEX record type");
|
||||
}
|
||||
require(eof && !ranges.isEmpty() && ranges.firstKey() == base, "HEX is truncated or has the wrong base address");
|
||||
QTemporaryFile file;
|
||||
require(file.open() && file.write(source) == source.size() && file.flush(), "Cannot inspect HEX source");
|
||||
QMap<quint32,QByteArray> blocks;
|
||||
require(HexFile::parseFile(file.fileName(), blocks) && !blocks.isEmpty(), "Original VESC Tool rejected HEX");
|
||||
const auto size = quint64(ranges.last()) - base;
|
||||
require(size >= 256 && size <= limit, "HEX span exceeds bound");
|
||||
image = QByteArray(int(size), char(0xFF)); segments = blocks.size();
|
||||
quint64 sourceBytes = 0, parsedBytes = 0;
|
||||
for (auto it=ranges.begin();it!=ranges.end();++it) sourceBytes += it.value()-it.key();
|
||||
for (auto it=blocks.begin();it!=blocks.end();++it) {
|
||||
require(it.key() >= base && quint64(it.key())+it.value().size() <= quint64(base)+size,
|
||||
"Original HEX reader returned an invalid address");
|
||||
std::copy(it.value().begin(), it.value().end(), image.begin()+int(it.key()-base)); parsedBytes += it.value().size();
|
||||
}
|
||||
require(parsedBytes == sourceBytes, "Original HEX reader changed the data coverage");
|
||||
}
|
||||
require(image.size()<=limit,"Image exceeds selected flash span");
|
||||
auto info = swdLimit ? QJsonObject{{"sha256",sha256(image)},{"bytes",image.size()}} : inspectFirmwareImage(image, kind);
|
||||
info.insert("source_format", format); info.insert("source_bytes", source.size());
|
||||
info.insert("source_sha256", sha256(source)); info.insert("base_address", double(base));
|
||||
info.insert("segments", segments);
|
||||
return {image, info};
|
||||
}
|
||||
@@ -1,7 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Mission Core adapter to the unmodified VESC Tool engine. No hardware transport
|
||||
// is admitted by this executable. Input is one archived snapshot on stdin.
|
||||
#include "config_export.h"
|
||||
#include "config_edit.h"
|
||||
#include "firmware_source.h"
|
||||
#include "bms_native.h"
|
||||
#include "swd_native.h"
|
||||
#include "code_native.h"
|
||||
#include "package_native.h"
|
||||
#include "engine_profile.h"
|
||||
#include "sample_data.h"
|
||||
#include "qml_broker.h"
|
||||
#include <QEventLoop>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
// This application never calls connectSerial/connectTcp/connectBle or starts
|
||||
@@ -11,13 +20,14 @@ int main(int argc, char **argv) {
|
||||
QCoreApplication::setOrganizationName("MissionCore");
|
||||
QCoreApplication::setApplicationName("VescToolOfflineAdapter");
|
||||
QJsonObject result{{"schema", "missioncore.vesc.native-offline/v1"},
|
||||
{"upstream_commit", "01d5f10901116c311e3fb84d5a1541f663d3ce20"},
|
||||
{"upstream_commit", engineProfile().value("upstream").toObject().value("commit")},
|
||||
{"upstream_version", QString::number(VT_VERSION, 'f', 2)},
|
||||
{"hardware_access", false}};
|
||||
try {
|
||||
require(argc == 1, "No command-line transport or operation arguments are accepted");
|
||||
QFile input; require(input.open(stdin, QIODevice::ReadOnly), "Cannot read input");
|
||||
const auto raw = input.read(1024 * 1024 + 1);
|
||||
QByteArray raw;
|
||||
while(raw.size()<=1024*1024){const auto part=input.read(4096);if(part.isEmpty())break;raw.append(part);}
|
||||
require(!raw.isEmpty() && raw.size() <= 1024 * 1024, "Archive input is empty or too large");
|
||||
QJsonParseError parse;
|
||||
auto document = QJsonDocument::fromJson(raw, &parse);
|
||||
@@ -33,15 +43,21 @@ int main(int argc, char **argv) {
|
||||
const auto uuid = identity.value("uuid").toString();
|
||||
require(QRegularExpression("^[0-9a-fA-F]{24}$").match(uuid).hasMatch(), "Invalid archived UUID");
|
||||
fw.uuid = QByteArray::fromHex(uuid.toLatin1());
|
||||
require(fw.major == 5 && fw.minor == 2 && fw.isTestFw == 0 && fw.customConfigNum == 0
|
||||
&& identity.value("hardware_type").toInt(-1) == 0,
|
||||
"Offline acceptance currently admits stable firmware 5.02 only");
|
||||
require(nativeFirmwareQualified(fw.major, fw.minor, identity.value("hardware_type").toInt(-1), fw.isTestFw, fw.customConfigNum),
|
||||
"Firmware archive is not admitted by this engine release profile");
|
||||
VescInterface vesc;
|
||||
require(Utility::configLoadLatest(&vesc), "Bundled upstream configuration resources missing");
|
||||
auto *commands = vesc.commands();
|
||||
|
||||
// Replay the archived identity through the real firmware negotiation
|
||||
// signal. The real engine selects bundled schemas and compatibility.
|
||||
commands->fwVersionReceived(fw);
|
||||
for(int code=0;code<256;++code) {
|
||||
QByteArray raw(1,char(code));if(code==65)raw.append(QByteArray::fromHex("01ff"));
|
||||
auto intent=qmlReadIntent(raw);require(intent.isEmpty()!=qmlReadCode(code),"Read classifier failed");
|
||||
if(!intent.isEmpty()){validateQmlRead(intent);require(qmlReadSupported(commands,code),"Qualified firmware read rejected");}
|
||||
raw.append(char(0));require(qmlReadIntent(raw).isEmpty(),"Read classifier accepted trailing data");
|
||||
}
|
||||
require(!vesc.isPortConnected(), "Offline adapter unexpectedly connected");
|
||||
require(vesc.mcConfig()->getSerializeOrder().size() > 0, "Native schema not selected");
|
||||
bool failed = false;
|
||||
@@ -82,6 +98,81 @@ int main(int argc, char **argv) {
|
||||
commands->setRpm(-3000);
|
||||
require(rpmExamples.size() == 2 && !vesc.isPortConnected(), "Offline signed RPM serialization failed");
|
||||
result.insert("offline_signed_rpm_examples_base64", rpmExamples);
|
||||
if(archive.contains("sample_test")) {
|
||||
const auto test=archive.value("sample_test").toObject();
|
||||
if(test.contains("packet"))result.insert("sample",decodeSample(QByteArray::fromBase64(test.value("packet").toString().toLatin1()),0,test.value("decimation").toInt(1)));
|
||||
QJsonArray sent;QObject observer;
|
||||
QObject::connect(commands,&Commands::dataToSend,&observer,[&](QByteArray &p){sent.append(QString::fromLatin1(p.toBase64()));});
|
||||
NativeSamples samples;samples.attach(commands);
|
||||
auto state=samples.start({{"mode",test.value("mode").toInt(1)},{"count",2},{"decimation",3},{"timeout_s",2},{"raw",false}});
|
||||
for(const auto &p:test.value("packets").toArray())samples.receive(QByteArray::fromBase64(p.toString().toLatin1()));
|
||||
if(test.value("wait_timeout").toBool()) {QEventLoop wait;QTimer::singleShot(2200,&wait,&QEventLoop::quit);wait.exec();}
|
||||
result.insert("sample_state",samples.run("sample_read",{{"capture_id",state.value("capture_id")},{"offset",0}}));
|
||||
samples.run("sample_stop",{{"capture_id",state.value("capture_id")}});
|
||||
result.insert("sample_commands",sent);
|
||||
}
|
||||
if (archive.contains("edit")) {
|
||||
const auto edit = archive.value("edit").toObject();
|
||||
const auto kind = edit.value("kind").toString();
|
||||
require(kind == "motor" || kind == "application", "Unknown edit kind");
|
||||
const bool mc = kind == "motor";
|
||||
result.insert("edit", prepareConfig(mc ? vesc.mcConfig() : vesc.appConfig(), edit.value("source").toObject(),
|
||||
mc ? COMM_GET_MCCONF : COMM_GET_APPCONF, mc ? "MCConfiguration" : "APPConfiguration"));
|
||||
}
|
||||
if (archive.contains("firmware_image")) {
|
||||
const auto image = archive.value("firmware_image").toObject();
|
||||
result.insert("firmware_image", inspectFirmwareSource(QByteArray::fromBase64(image.value("data").toString().toLatin1()), image.value("kind").toString(), image.value("format").toString("bin")).info);
|
||||
}
|
||||
if(archive.contains("swd_image")) {
|
||||
const auto p=archive.value("swd_image").toObject();const auto range=swdRange(p.value("target").toObject());
|
||||
const auto data=QByteArray::fromBase64(p.value("data").toString().toLatin1());
|
||||
result.insert("swd_image",inspectFirmwareSource(data,"firmware",p.value("format").toString("bin"),range.first,range.second).info);
|
||||
}
|
||||
if(archive.contains("can_route")) {
|
||||
bool remote=false;QByteArray sent;QObject observer;
|
||||
QObject::connect(commands,&Commands::dataToSend,&observer,[&](QByteArray &data){sent=data;});
|
||||
try { NativeCanTarget route(vesc,remote,archive.value("can_route").toInt(-1));commands->getFwVersion();throw std::runtime_error("synthetic read failure"); }
|
||||
catch(const std::exception&){}
|
||||
require(!remote && !commands->getSendCan() && !vesc.isIgnoringCanChanges(),"CAN route leaked after failure");
|
||||
require(sent.size()==3 && quint8(sent[0])==COMM_FORWARD_CAN && quint8(sent[1])==7 && quint8(sent[2])==COMM_FW_VERSION,"CAN read was not unicast");
|
||||
result.insert("can_route",true);
|
||||
}
|
||||
if(archive.contains("bms_command")) {
|
||||
const auto p=archive.value("bms_command").toObject();
|
||||
const double id=p.value("can_id").toDouble(-1);require(id==int(id),"Integral CAN address required");
|
||||
bool remote=false; QByteArray sent;
|
||||
QObject observer;
|
||||
QObject::connect(commands,&Commands::dataToSend,&observer,[&](QByteArray &data){sent=data;});
|
||||
{
|
||||
NativeCanTarget route(vesc,remote,int(id));
|
||||
sendBmsCommand(commands,p.value("command").toString());
|
||||
}
|
||||
require(!remote && !commands->getSendCan() && !vesc.isIgnoringCanChanges(),"CAN route did not restore");
|
||||
FW_RX_PARAMS bms; bms.major=6;bms.minor=0;bms.hwType=HW_TYPE_VESC_BMS;bms.isTestFw=0;
|
||||
require(bmsCommandsSupported(bms),"Reviewed BMS protocol missing");
|
||||
bms.hwType=HW_TYPE_VESC;require(!bmsCommandsSupported(bms),"Motor must not become BMS");
|
||||
bms.hwType=HW_TYPE_VESC_BMS;bms.major=99;require(!bmsCommandsSupported(bms),"Unknown BMS firmware admitted");
|
||||
result.insert("bms_command",QJsonObject{{"packet_hex",QString::fromLatin1(sent.toHex())},{"route_restored",true}});
|
||||
}
|
||||
if(archive.contains("custom_schema")) {
|
||||
const auto xml=QByteArray::fromBase64(archive.value("custom_schema").toString().toLatin1());ConfigParams custom;
|
||||
NativeCustom::schema(custom,qCompress(xml));const auto packet=configPacket(&custom,COMM_GET_CUSTOM_CONFIG);
|
||||
loadExactConfig(&custom,packet,COMM_GET_CUSTOM_CONFIG);
|
||||
result.insert("custom_configuration",exportConfig(&custom,packet,"CustomConfiguration"));
|
||||
if(archive.contains("custom_edit"))result.insert("custom_edit",prepareConfig(&custom,archive.value("custom_edit").toObject(),COMM_GET_CUSTOM_CONFIG,"CustomConfiguration"));
|
||||
}
|
||||
if(archive.contains("package")) result.insert("package",NativePackage::inspect(archive.value("package").toObject()));
|
||||
if(archive.contains("code_project")) {
|
||||
const auto project=archive.value("code_project").toObject();const auto packed=NativeCode::pack(project);
|
||||
const auto checked=NativeCode::image({{"kind",project.value("kind")},{"image",QString::fromLatin1(packed.toBase64())}});
|
||||
require(checked==packed,"Code frame validation mismatch");auto decoded=NativeCode::decode(project.value("kind").toString(),packed.mid(8));
|
||||
require(decoded.value("source")==project.value("source") && decoded.value("imports").toObject()==project.value("imports").toObject(),"Code source/import roundtrip differs");result.insert("code",decoded);
|
||||
}
|
||||
if(archive.contains("code_image")) NativeCode::image(archive.value("code_image").toObject());
|
||||
if(archive.contains("code_decode")) {const auto value=archive.value("code_decode").toObject();NativeCode::decode(value.value("kind").toString(),QByteArray::fromBase64(value.value("payload").toString().toLatin1()));}
|
||||
FW_RX_PARAMS codeFw;codeFw.major=6;codeFw.minor=0;codeFw.hwType=HW_TYPE_VESC;codeFw.isTestFw=0;
|
||||
require(NativeCode::supported(codeFw),"Code firmware profile missing");codeFw.minor=1;require(!NativeCode::supported(codeFw),"Unknown code firmware admitted");
|
||||
codeFw.major=5;codeFw.minor=2;require(!NativeCode::supported(codeFw),"FW5.02 cannot run Lisp/QML");
|
||||
result.insert("archive_sha256", sha256(raw));
|
||||
result.insert("ok", true);
|
||||
} catch (const std::exception &error) {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "code_native.h"
|
||||
#include <QJSEngine>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <zlib.h>
|
||||
|
||||
class NativePackage {
|
||||
public:
|
||||
static QByteArray unpackBounded(const QByteArray &data) {
|
||||
require(data.size()>=5&&data.size()<=1024*1024,"Package size exceeds bound");
|
||||
auto size=qFromBigEndian<quint32>(reinterpret_cast<const uchar*>(data.constData()));
|
||||
require(size>0&&size<=4*1024*1024,"Expanded package exceeds bound");
|
||||
QByteArray raw(int(size),'\0');z_stream z{};require(inflateInit(&z)==Z_OK,"Cannot inspect package compression");
|
||||
z.next_in=reinterpret_cast<Bytef*>(const_cast<char*>(data.constData()+4));z.avail_in=data.size()-4;
|
||||
z.next_out=reinterpret_cast<Bytef*>(raw.data());z.avail_out=size;const auto code=inflate(&z,Z_FINISH);
|
||||
const bool valid=code==Z_STREAM_END&&z.total_out==size&&z.avail_in==0;inflateEnd(&z);require(valid,"Invalid package compression");
|
||||
require(raw.startsWith(QByteArray("VESC Packet\0",12)),"Invalid VESC package magic");
|
||||
int at=12;QSet<QByteArray> fields;
|
||||
while(at<raw.size()) {
|
||||
int end=raw.indexOf('\0',at);require(end>at&&end-at<=64&&end+5<=raw.size(),"Invalid package field");
|
||||
const auto name=raw.mid(at,end-at);const auto length=qFromBigEndian<qint32>(reinterpret_cast<const uchar*>(raw.constData()+end+1));at=end+5;
|
||||
require(!fields.contains(name)&&fields.size()<32&&length>=0&&length<=raw.size()-at,"Duplicate/truncated package field");fields.insert(name);
|
||||
if(name=="qmlIsFullscreen")require(length==1&&(raw[at]==0||raw[at]==1),"Invalid QML flag");
|
||||
at+=length;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
// Evaluate only the descriptor's pure compatibility function. A bare JS
|
||||
// engine has no Qt/QObject, USB, filesystem, network or application bridge.
|
||||
// QML object creation and Component.onCompleted are never evaluated.
|
||||
static QJsonValue compatible(const QString &descriptor,const QJsonObject &identity) {
|
||||
if(descriptor.isEmpty())return QJsonValue(QJsonValue::Null);
|
||||
if(descriptor.size()>16384)return QJsonValue(QJsonValue::Null);
|
||||
auto match=QRegularExpression("function\\s+isCompatible\\s*\\(\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\)\\s*\\{").match(descriptor);
|
||||
if(!match.hasMatch())return QJsonValue(QJsonValue::Null);
|
||||
int end=match.capturedEnd(),depth=1;QChar quote;bool line=false,block=false,escape=false;
|
||||
for(;end<descriptor.size()&&depth;end++) {
|
||||
auto c=descriptor[end],next=end+1<descriptor.size()?descriptor[end+1]:QChar();
|
||||
if(line){if(c=='\n')line=false;continue;}if(block){if(c=='*'&&next=='/'){block=false;end++;}continue;}
|
||||
if(!quote.isNull()){if(escape){escape=false;continue;}if(c=='\\'){escape=true;continue;}if(c==quote)quote=QChar();continue;}
|
||||
if(c=='`')return QJsonValue(QJsonValue::Null);
|
||||
if(c=='/'&&next=='/'){line=true;end++;continue;}if(c=='/'&&next=='*'){block=true;end++;continue;}
|
||||
if(c=='\''||c=='"'){quote=c;continue;}if(c=='{')depth++;if(c=='}')depth--;
|
||||
}
|
||||
if(depth)return QJsonValue(QJsonValue::Null);
|
||||
QJSEngine engine;auto fw=engine.newObject();
|
||||
for(auto it=identity.begin();it!=identity.end();++it)fw.setProperty(it.key(),engine.toScriptValue(it.value().toVariant()));
|
||||
fw.setProperty("hw",identity.value("hardware").toString());fw.setProperty("fwName",identity.value("firmware_name").toString());
|
||||
const int type=identity.value("hardware_type").toInt(-1);
|
||||
const auto typeName=type==0?"VESC":type==1?"VESC BMS":type==2?"Custom Module":"Unknown";
|
||||
auto name=engine.newObject();name.setProperty("name",typeName);engine.globalObject().setProperty("_hwType",name);
|
||||
fw.setProperty("hwTypeStr",engine.evaluate("(function(){return _hwType.name;})"));
|
||||
std::mutex mutex;std::condition_variable condition;bool done=false;
|
||||
std::thread timer([&]{std::unique_lock<std::mutex> lock(mutex);if(!condition.wait_for(lock,std::chrono::milliseconds(250),[&]{return done;}))engine.setInterrupted(true);});
|
||||
auto fn=engine.evaluate("("+descriptor.mid(match.capturedStart(),end-match.capturedStart())+")");
|
||||
auto result=fn.isCallable()?fn.call({fw}):QJSValue();
|
||||
{std::lock_guard<std::mutex> lock(mutex);done=true;}condition.notify_one();timer.join();
|
||||
if(engine.isInterrupted()||!result.isBool())return QJsonValue(QJsonValue::Null);
|
||||
return result.toBool();
|
||||
}
|
||||
static QByteArray image(const QByteArray &content) {
|
||||
if(content.isEmpty())return {};
|
||||
require(content.size()>=2,"Code flags missing");VByteArray out;out.vbAppendUint32(content.size()-2);
|
||||
out.vbAppendUint16(Packet::crc16(reinterpret_cast<const unsigned char*>(content.constData()),content.size()));out.append(content);return out;
|
||||
}
|
||||
static QJsonObject library(const QByteArray &content) {
|
||||
require(content.size()>=5&&content.size()<=512*1024&&content.startsWith(QByteArray(2,'\0')), "Invalid library Lisp content");
|
||||
const auto data=content.mid(2);const int end=data.indexOf('\0');require(end>0&&end+3<=data.size(),"Invalid library source");
|
||||
VByteArray table(data.mid(end+1));const auto count=table.vbPopFrontInt16();require(count>=0&&count<500,"Invalid library import count");
|
||||
int tableEnd=end+3;QList<QPair<int,int>> ranges;QSet<QString> names;
|
||||
for(int i=0;i<count;i++) {
|
||||
const int n=table.indexOf('\0');require(n>0&&n<=64&&n+9<=table.size(),"Invalid library tag");
|
||||
const auto tag=table.vbPopFrontString();int offset=table.vbPopFrontInt32(),length=table.vbPopFrontInt32();
|
||||
require(!names.contains(tag)&&offset>=0&&length>0&&offset<=data.size()-length&&data[offset+length-1]=='\0',"Invalid library range");
|
||||
names.insert(tag);ranges.append(qMakePair(offset,length));tableEnd+=n+9;
|
||||
}
|
||||
int previous=tableEnd;for(auto range:ranges){require(range.first>=previous,"Overlapping library range");previous=range.first+range.second;}
|
||||
CodeLoader loader;const auto parts=loader.lispUnpackImports(content);QJsonObject imports;
|
||||
for(auto part:parts.second)imports.insert(part.first,QString::fromLatin1(part.second.toBase64()));
|
||||
return {{"source",parts.first},{"imports",imports}};
|
||||
}
|
||||
static QJsonObject inspect(const QJsonObject &request) {
|
||||
const auto encoded=request.value("data").toString().toLatin1();const auto data=QByteArray::fromBase64(encoded,QByteArray::AbortOnBase64DecodingErrors);
|
||||
require(data.toBase64()==encoded,"Invalid package encoding");unpackBounded(data);
|
||||
CodeLoader loader;const auto pkg=loader.unpackVescPackage(data);require(pkg.loadOk&&!pkg.name.isEmpty()&&pkg.name.size()<=256,"Package metadata missing");
|
||||
auto lisp=image(pkg.lispData);VByteArray qml;
|
||||
if(!pkg.qmlFile.isEmpty()){qml.vbAppendUint16(pkg.qmlIsFullscreen?2:1);qml.append(loader.qmlCompress(pkg.qmlFile));}
|
||||
const auto qmlImage=image(qml);const bool fits=lisp.size()<=120*1024&&qmlImage.size()<=120*1024&&pkg.qmlFile.toUtf8().size()<=500*1024;
|
||||
if(!lisp.isEmpty())require(pkg.lispData.startsWith(QByteArray(2,'\0')),"Unknown Lisp flags");
|
||||
// Dependencies are already embedded by the upstream package builder.
|
||||
// Original bytes are retained, including native libraries and alignment.
|
||||
QJsonObject result{{"name",pkg.name},{"sha256",sha256(data)},{"description",pkg.description_md.left(65536)},
|
||||
{"compatible",compatible(pkg.pkgDescQml,request.value("identity").toObject())},{"fits",fits},
|
||||
{"lisp_bytes",lisp.size()},{"qml_bytes",qmlImage.size()},{"qml_source",pkg.qmlFile.toUtf8().size()<=120*1024?QJsonValue(pkg.qmlFile):QJsonValue()},
|
||||
{"images",QJsonObject{{"lisp",fits?QString::fromLatin1(lisp.toBase64()):QString()},{"qml",fits?QString::fromLatin1(qmlImage.toBase64()):QString()}}}};
|
||||
if(request.value("export_library").toBool())result.insert("library",library(pkg.lispData));
|
||||
return result;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "config_export.h"
|
||||
#include <QSet>
|
||||
#include <QMap>
|
||||
// Decode intent only. No raw QML payload is ever passed to a device transport.
|
||||
static bool qmlReadCode(int code) {
|
||||
return QList<int>{0,4,14,17,31,32,33,65,96}.contains(code);
|
||||
}
|
||||
// Identification is outside the upstream limited-mode list. Configuration
|
||||
// admission belongs to the exact schema already qualified by the engine.
|
||||
static bool qmlReadSupported(Commands *commands, int code) {
|
||||
return qmlReadCode(code) && (code==0||code==14||code==17||
|
||||
commands->getLimitedCompatibilityCommands().contains(code));
|
||||
}
|
||||
static QJsonObject qmlReadIntent(const QByteArray &raw) {
|
||||
if(raw.isEmpty())return {};
|
||||
const int code=quint8(raw[0]);
|
||||
if(!qmlReadCode(code)||raw.size()!=(code==65?3:1))return {};
|
||||
QJsonObject out{{"command",code}};
|
||||
if(code==65)out.insert("mask",(quint8(raw[1])<<8)|quint8(raw[2]));
|
||||
return out;
|
||||
}
|
||||
static void validateQmlRead(const QJsonObject &intent) {
|
||||
const auto value=intent.value("command");const int code=value.toInt(-1);
|
||||
require(value.isDouble()&&value.toDouble()==code&&qmlReadCode(code),"QML read is not admitted");
|
||||
require(intent.size()==(code==65?2:1),"Invalid QML read shape");
|
||||
if(code==65){const auto mask=intent.value("mask");require(mask.isDouble()&&mask.toDouble()==mask.toInt(-1)&&mask.toInt(-1)>=0&&mask.toInt(-1)<=65535,"Invalid IMU read mask");}
|
||||
}
|
||||
class QmlReadQueue {
|
||||
public:
|
||||
bool enabled;int blocked=0;QMap<int,QJsonObject> pending;QSet<int> blockedCodes;
|
||||
explicit QmlReadQueue(bool live):enabled(live){}
|
||||
void capture(const QByteArray &raw) {
|
||||
auto intent=qmlReadIntent(raw);
|
||||
if(!enabled||intent.isEmpty()) {
|
||||
if(blocked<1000000)++blocked;
|
||||
if(blockedCodes.size()<32&&!raw.isEmpty())blockedCodes.insert(quint8(raw[0]));
|
||||
return;
|
||||
}
|
||||
pending.insert(intent.value("command").toInt(),intent);
|
||||
}
|
||||
QJsonArray take() {QJsonArray out;for(const auto &intent:pending)out.append(intent);pending.clear();return out;}
|
||||
QJsonArray rejected() const {QJsonArray out;for(int code:blockedCodes)out.append(code);return out;}
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include <QMouseEvent>
|
||||
#include <QKeyEvent>
|
||||
#include <QWheelEvent>
|
||||
#include <QInputMethodEvent>
|
||||
#include <QSocketNotifier>
|
||||
|
||||
static void qmlInput(QQuickWindow &window,const QJsonArray &events) {
|
||||
require(events.size()<=32,"Too many input events");
|
||||
for(const auto &value:events){
|
||||
require(value.isObject(),"Invalid input event");auto e=value.toObject();auto kind=e.value("kind").toString();
|
||||
if(kind=="down" || kind=="up" || kind=="move" || kind=="wheel") {
|
||||
double x=e.value("x").toDouble(-1),y=e.value("y").toDouble(-1);
|
||||
require(std::isfinite(x)&&std::isfinite(y)&&x>=0&&x<640&&y>=0&&y<480,"Invalid input coordinates");
|
||||
QPointF p(x,y);
|
||||
if(kind=="wheel"){
|
||||
int delta=e.value("delta").toInt();require(std::abs(delta)<=1200,"Invalid wheel input");
|
||||
QWheelEvent ev(p,p,QPoint(),QPoint(0,delta),Qt::NoButton,Qt::NoModifier,Qt::NoScrollPhase,false);QCoreApplication::sendEvent(&window,&ev);
|
||||
}else{
|
||||
auto type=kind=="down"?QEvent::MouseButtonPress:kind=="up"?QEvent::MouseButtonRelease:QEvent::MouseMove;
|
||||
QMouseEvent ev(type,p,p,p,kind=="move"?Qt::NoButton:Qt::LeftButton,kind=="up"?Qt::NoButton:Qt::LeftButton,Qt::NoModifier);
|
||||
QCoreApplication::sendEvent(&window,&ev);
|
||||
}
|
||||
}else if(kind=="text"){
|
||||
auto text=e.value("text").toString();require(text.size()<=1024&&!text.contains(QChar(0)),"Invalid text input");
|
||||
QInputMethodEvent ev;ev.setCommitString(text);
|
||||
auto focus=window.activeFocusItem();if(focus)QCoreApplication::sendEvent(focus,&ev);
|
||||
}else if(kind=="key"){
|
||||
const QMap<QString,int> keys{{"Enter",Qt::Key_Return},{"Tab",Qt::Key_Tab},{"Backspace",Qt::Key_Backspace},{"Delete",Qt::Key_Delete},{"ArrowLeft",Qt::Key_Left},{"ArrowRight",Qt::Key_Right},{"ArrowUp",Qt::Key_Up},{"ArrowDown",Qt::Key_Down},{"Home",Qt::Key_Home},{"End",Qt::Key_End},{"Escape",Qt::Key_Escape},{"SelectAll",Qt::Key_A}};
|
||||
auto name=e.value("key").toString();require(keys.contains(name),"Unsupported QML key");
|
||||
auto modifiers=name=="SelectAll"?Qt::ControlModifier:Qt::NoModifier;
|
||||
QKeyEvent down(QEvent::KeyPress,keys[name],modifiers),up(QEvent::KeyRelease,keys[name],modifiers);
|
||||
QCoreApplication::sendEvent(&window,&down);QCoreApplication::sendEvent(&window,&up);
|
||||
}else throw std::runtime_error("Unknown QML input event");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Real Qt Quick preview using the pinned upstream Tool resources/objects.
|
||||
// This executable never receives a device path or a transport connection.
|
||||
#include "config_export.h"
|
||||
#include <sys/stat.h>
|
||||
#include "qml_sandbox.h"
|
||||
#include <QQmlEngine>
|
||||
#include <QQmlContext>
|
||||
#include <QQmlComponent>
|
||||
#include <QQmlError>
|
||||
#include <QQuickWindow>
|
||||
#include <QQuickRenderControl>
|
||||
#include <QQuickItem>
|
||||
#include <QBuffer>
|
||||
#include <QFontDatabase>
|
||||
#include <QTimer>
|
||||
#include <QEventLoop>
|
||||
#include <QElapsedTimer>
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QQuickStyle>
|
||||
#include <memory>
|
||||
#include <sys/socket.h>
|
||||
#include "qml_interactive.h"
|
||||
#include "qml_broker.h"
|
||||
#include "qml_vesc_interface.h"
|
||||
static QStringList messages;
|
||||
static void boundedMessage(QtMsgType, const QMessageLogContext&, const QString &message) {
|
||||
if(messages.size()<12) messages.append(message.left(320));
|
||||
}
|
||||
int main(int argc,char **argv) {
|
||||
QJsonObject result{{"schema","missioncore.vesc.qml-preview/v1"},{"hardware_access",false},{"snapshot_only",true}};
|
||||
try {
|
||||
require(argc==1,"QML preview accepts stdin only");
|
||||
QFile input; require(input.open(stdin,QIODevice::ReadOnly),"Cannot read preview");
|
||||
QByteArray raw; while(raw.size()<=512*1024){auto p=input.read(1);if(p.isEmpty()||p=="\n")break;raw+=p;}
|
||||
require(!raw.isEmpty()&&raw.size()<=512*1024,"Preview input exceeds limit");
|
||||
auto doc=QJsonDocument::fromJson(raw);require(doc.isObject(),"Invalid preview input");
|
||||
auto request=doc.object();const bool interactive=request.value("interactive").toBool();
|
||||
const bool standalone=request.value("standalone").toBool();
|
||||
const bool broker=request.value("broker").toBool();
|
||||
require(!broker||(interactive&&!standalone),"Broker requires an interactive controller context");
|
||||
result.insert("broker",broker);result.insert("snapshot_only",!broker);
|
||||
auto source=request.value("source").toString().toUtf8();
|
||||
require(!source.trimmed().isEmpty()&&source.size()<=120*1024&&!source.contains('\0'),"Invalid QML source size");
|
||||
int width=request.value("width").toInt(),height=request.value("height").toInt();
|
||||
require(width>=320&&width<=960&&height>=240&&height<=720,"Invalid preview dimensions");
|
||||
rlimit memory{512ULL*1024*1024,512ULL*1024*1024}, cpu{interactive?12UL:3UL,interactive?12UL:3UL}, files{64,64}, core{0,0};
|
||||
require(!setrlimit(RLIMIT_AS,&memory)&&!setrlimit(RLIMIT_CPU,&cpu)&&!setrlimit(RLIMIT_NOFILE,&files)&&!setrlimit(RLIMIT_CORE,&core),"Cannot bound QML process");
|
||||
const QString root=QFileInfo(QString::fromLocal8Bit(argv[0])).absoluteDir().absoluteFilePath("..");
|
||||
qputenv("QT_QPA_PLATFORM","offscreen");qputenv("QT_QUICK_BACKEND","software");
|
||||
qputenv("QT_QUICK_CONTROLS_STYLE","Material");qputenv("QT_QUICK_CONTROLS_MATERIAL_THEME","Dark");
|
||||
qputenv("QML_DISABLE_DISK_CACHE","1");qputenv("QV4_FORCE_INTERPRETER","1");
|
||||
qputenv("QT_QPA_FONTDIR",(root+"/fonts").toUtf8());
|
||||
qInstallMessageHandler(boundedMessage);
|
||||
// Confinement precedes QApplication, VescInterface and all user QML.
|
||||
confineQml(QDir(root).canonicalPath());
|
||||
int denied=open("/etc/passwd",O_RDONLY|O_CLOEXEC);if(denied>=0)close(denied);
|
||||
require(denied<0,"QML filesystem boundary failed");
|
||||
int sock=socket(AF_INET,SOCK_STREAM,0);if(sock>=0)close(sock);
|
||||
require(sock<0&&errno==EPERM,"QML network boundary failed");
|
||||
char *noArgs[]={nullptr};syscall(SYS_execve,"/mission-core-qml-no-executable",noArgs,noArgs);
|
||||
require(errno==EPERM,"QML execution boundary failed");
|
||||
result.insert("sandbox_verified",true);
|
||||
QApplication app(argc,argv);
|
||||
QFontDatabase::addApplicationFont(":/res/fonts/Roboto/Roboto-Regular.ttf");
|
||||
app.setFont(QFont("Roboto",12));
|
||||
QCoreApplication::setOrganizationName("MissionCore");
|
||||
QCoreApplication::setApplicationName("VescQmlPreview");
|
||||
qmlRegisterType<Commands>("Vedder.vesc.commands",1,0,"Commands");
|
||||
qmlRegisterType<ConfigParams>("Vedder.vesc.configparams",1,0,"ConfigParams");
|
||||
qmlRegisterSingletonType<Utility>("Vedder.vesc.utility",1,0,"Utility",[](QQmlEngine*,QJSEngine*)->QObject*{return new Utility;});
|
||||
qRegisterMetaType<MC_VALUES>();qRegisterMetaType<FW_RX_PARAMS>();qRegisterMetaType<BMS_VALUES>();
|
||||
QmlVescInterface vesc;vesc.brokerConnected=broker;vesc.setLoadQmlUiOnConnect(false);vesc.ignoreCanChange(broker);
|
||||
qmlRegisterSingletonInstance<QmlVescInterface>("Vedder.vesc.vescinterface",1,0,"VescIf",&vesc);
|
||||
Utility util;require(Utility::configLoadLatest(&vesc),"Upstream configuration resources missing");
|
||||
const auto identity=request.value("identity").toObject();FW_RX_PARAMS fw;
|
||||
fw.major=identity.value("major").toInt();fw.minor=identity.value("minor").toInt();
|
||||
fw.hw=identity.value("hardware").toString();fw.isTestFw=identity.value("test_firmware").toInt();
|
||||
fw.uuid=QByteArray::fromHex(identity.value("uuid").toString().toLatin1());
|
||||
vesc.brokerUuid=identity.value("uuid").toString();
|
||||
fw.customConfigNum=identity.value("custom_configs").toInt();
|
||||
fw.hwType=HW_TYPE(identity.value("hardware_type").toInt());
|
||||
if(!standalone)vesc.commands()->fwVersionReceived(fw);
|
||||
bool failed=false;QObject::connect(vesc.commands(),&Commands::deserializeConfigFailed,[&](bool,bool){failed=true;});
|
||||
if(!standalone)for(const auto &kind:QStringList{"motor","application"}) {
|
||||
auto packet=archivePacket(request,kind,kind=="motor"?COMM_GET_MCCONF:COMM_GET_APPCONF);
|
||||
vesc.commands()->processPacket(packet);
|
||||
}
|
||||
require(!failed,"Snapshot configuration rejected");
|
||||
const auto valuePacket=QByteArray::fromBase64(request.value("values").toString().toLatin1());
|
||||
require(standalone||(!valuePacket.isEmpty()&&quint8(valuePacket[0])==COMM_GET_VALUES),"Telemetry snapshot missing");
|
||||
QmlReadQueue reads(broker);QObject::connect(vesc.commands(),&Commands::dataToSend,[&](QByteArray &raw){reads.capture(raw);});
|
||||
QQmlEngine engine;engine.setImportPathList({root+"/qml","qrc:/"});
|
||||
engine.rootContext()->setContextProperty("VescIf",&vesc);
|
||||
engine.rootContext()->setContextProperty("Utility",&util);
|
||||
QQmlComponent component(&engine);component.setData(source,QUrl("qrc:/mobile/MissionCorePreview.qml"));
|
||||
QElapsedTimer loading;loading.start();
|
||||
while(component.isLoading()&&loading.elapsed()<1000)QCoreApplication::processEvents(QEventLoop::AllEvents,20);
|
||||
if(component.isError())for(const auto &e:component.errors())messages.append(e.toString().left(320));
|
||||
require(component.isReady(),"QML could not be loaded");
|
||||
QQuickRenderControl renderControl;
|
||||
QQuickWindow window(&renderControl);window.resize(width,height);window.setColor(QColor("#151515"));
|
||||
window.contentItem()->setWidth(width);window.contentItem()->setHeight(height);
|
||||
std::unique_ptr<QObject> object(component.create());require(bool(object),"QML could not be created");
|
||||
auto item=qobject_cast<QQuickItem*>(object.get());
|
||||
if(!item) {auto rootWindow=qobject_cast<QQuickWindow*>(object.get());require(rootWindow,"QML root must be Item or Window");rootWindow->hide();rootWindow->resize(width,height);item=rootWindow->contentItem();}
|
||||
item->setParentItem(window.contentItem());item->setWidth(width);item->setHeight(height);
|
||||
renderControl.initialize(nullptr);
|
||||
QEventLoop loop;QTimer feed;QObject::connect(&feed,&QTimer::timeout,[&]{auto packet=valuePacket;vesc.commands()->processPacket(packet);});if(!standalone&&!broker)feed.start(100);
|
||||
if(broker){auto packet=valuePacket;vesc.commands()->processPacket(packet);}
|
||||
QTimer::singleShot(500,&loop,&QEventLoop::quit);loop.exec();
|
||||
auto frame=[&]{
|
||||
auto image=renderControl.grab();require(!image.isNull(),"Qt Quick returned an empty frame");
|
||||
QByteArray png;QBuffer buffer(&png);buffer.open(QIODevice::WriteOnly);require(image.save(&buffer,"PNG"),"Cannot encode QML frame");
|
||||
require(png.size()<=512*1024,"QML frame exceeds limit");
|
||||
result.insert("png",QString::fromLatin1(png.toBase64()));result.insert("width",image.width());result.insert("height",image.height());
|
||||
result.insert("source_sha256",QString::fromLatin1(QCryptographicHash::hash(source,QCryptographicHash::Sha256).toHex()));
|
||||
result.insert("root_width",item->width());result.insert("root_height",item->height());
|
||||
result.insert("discarded_commands",reads.blocked);result.insert("blocked_codes",reads.rejected());result.insert("read_requests",reads.take());result.insert("ok",true);
|
||||
result.insert("interactive",interactive);result.insert("standalone",standalone);
|
||||
QJsonArray warnings;for(const auto &m:messages.mid(0,16))warnings.append(m);result.insert("warnings",warnings);
|
||||
};
|
||||
auto write=[&]{QFile output;output.open(stdout,QIODevice::WriteOnly);output.write(QJsonDocument(result).toJson(QJsonDocument::Compact)+"\n");output.flush();};
|
||||
frame();
|
||||
if(interactive){
|
||||
write();
|
||||
QTimer idle,maximum;idle.setSingleShot(true);maximum.setSingleShot(true);
|
||||
QObject::connect(&idle,&QTimer::timeout,&app,&QCoreApplication::quit);
|
||||
QObject::connect(&maximum,&QTimer::timeout,&app,&QCoreApplication::quit);
|
||||
idle.start(60000);maximum.start(300000);
|
||||
require(fcntl(STDIN_FILENO,F_SETFL,fcntl(STDIN_FILENO,F_GETFL)|O_NONBLOCK)==0,"Cannot bound input pipe");
|
||||
QSocketNotifier notifier(STDIN_FILENO,QSocketNotifier::Read);QByteArray pending;int requests=0;
|
||||
QObject::connect(¬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"
|
||||
@@ -0,0 +1,66 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Unprivileged Linux containment. A preview has no device, network, writable
|
||||
// filesystem or process-execution authority. Fail closed if the kernel lacks it.
|
||||
#pragma once
|
||||
#include <linux/landlock.h>
|
||||
#include <linux/filter.h>
|
||||
#include <linux/seccomp.h>
|
||||
#include <linux/audit.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/resource.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <sched.h>
|
||||
#include <cerrno>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
#include <QStringList>
|
||||
inline void confineQml(const QString &root) {
|
||||
if (syscall(SYS_landlock_create_ruleset, nullptr, 0, LANDLOCK_CREATE_RULESET_VERSION) < 3)
|
||||
throw std::runtime_error("QML preview needs Landlock ABI 3 or later");
|
||||
const __u64 read = LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR;
|
||||
landlock_ruleset_attr attr{};
|
||||
attr.handled_access_fs = (1ULL << 15) - 1; // ABI 3, including REFER/TRUNCATE
|
||||
int rules = syscall(SYS_landlock_create_ruleset, &attr, sizeof(attr), 0);
|
||||
if (rules < 0) throw std::runtime_error("Cannot create QML filesystem boundary");
|
||||
const QStringList paths{root, "/usr/share/fonts", "/etc/fonts", "/etc/localtime", "/dev/urandom"};
|
||||
for (const auto &path : paths) {
|
||||
int fd = open(path.toLocal8Bit().constData(), O_PATH | O_CLOEXEC);
|
||||
if (fd < 0) { if(path == root) {close(rules); throw std::runtime_error("QML runtime missing");} continue; }
|
||||
struct stat st{}; fstat(fd, &st);
|
||||
landlock_path_beneath_attr rule{}; rule.parent_fd=fd;
|
||||
rule.allowed_access = S_ISDIR(st.st_mode) ? read : LANDLOCK_ACCESS_FS_READ_FILE;
|
||||
int result=syscall(SYS_landlock_add_rule,rules,LANDLOCK_RULE_PATH_BENEATH,&rule,0);
|
||||
close(fd);
|
||||
if(result) {close(rules);throw std::runtime_error("Cannot admit QML runtime path");}
|
||||
}
|
||||
if(prctl(PR_SET_NO_NEW_PRIVS,1,0,0,0) || syscall(SYS_landlock_restrict_self,rules,0)) {
|
||||
close(rules);throw std::runtime_error("Cannot restrict QML filesystem");
|
||||
}
|
||||
close(rules);
|
||||
std::vector<sock_filter> filter{
|
||||
BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(seccomp_data,arch)),
|
||||
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,AUDIT_ARCH_X86_64,1,0),
|
||||
BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_KILL_PROCESS),
|
||||
BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(seccomp_data,nr)),
|
||||
BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K,0x40000000,0,1),
|
||||
BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_KILL_PROCESS)};
|
||||
for(int number : {SYS_socket,SYS_connect,SYS_bind,SYS_listen,SYS_accept,SYS_accept4,
|
||||
SYS_execve,SYS_execveat,SYS_fork,SYS_vfork,SYS_ptrace,
|
||||
SYS_process_vm_readv,SYS_process_vm_writev,SYS_mount,SYS_umount2,
|
||||
SYS_bpf,SYS_ioctl,SYS_io_uring_setup,SYS_unshare,SYS_setns}) {
|
||||
filter.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,number,0,1));
|
||||
filter.push_back(BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ERRNO|EPERM));
|
||||
}
|
||||
// glibc falls back from clone3 to clone; only thread creation is admitted.
|
||||
filter.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,SYS_clone3,0,1));
|
||||
filter.push_back(BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ERRNO|ENOSYS));
|
||||
filter.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,SYS_clone,0,3));
|
||||
filter.push_back(BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(seccomp_data,args[0])));
|
||||
filter.push_back(BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K,CLONE_THREAD,1,0));
|
||||
filter.push_back(BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ERRNO|EPERM));
|
||||
filter.push_back(BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW));
|
||||
sock_fprog program{static_cast<unsigned short>(filter.size()),filter.data()};
|
||||
if(prctl(PR_SET_SECCOMP,SECCOMP_MODE_FILTER,&program)) throw std::runtime_error("Cannot restrict QML system calls");
|
||||
}
|
||||
@@ -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(); }
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Bounded Sample Data receiver; Commands owns wire encoding and transport.
|
||||
#pragma once
|
||||
#include "config_export.h"
|
||||
#include <QTimer>
|
||||
#include <QElapsedTimer>
|
||||
#include <QUuid>
|
||||
#include <cmath>
|
||||
|
||||
static QJsonObject decodeSample(QByteArray raw, int sequence, int decimation) {
|
||||
require(raw.size()==34 || raw.size()==38 || raw.size()==44,"Unknown Sample Data packet length");
|
||||
const bool indexed=raw.size()==44, third=raw.size()!=34;
|
||||
VByteArray b(raw);
|
||||
int index=indexed?b.vbPopFrontInt16():sequence;
|
||||
require(index>=0 && index<2000,"Sample index outside buffer");
|
||||
QJsonObject row{{"index",index},{"indexed",indexed},{"third_current_measured",third}};
|
||||
auto take=[&](const QString &key){double v=b.vbPopFrontDouble32Auto();require(std::isfinite(v),"Non-finite sample");row.insert(key,v);return v;};
|
||||
double i1=take("i1"),i2=take("i2");
|
||||
if(third)take("i3");else row.insert("i3",-(i1+i2));
|
||||
for(const auto &key:{"v1","v2","v3","v0","current","switching_hz"})take(key);
|
||||
const double hz=row.value("switching_hz").toDouble();
|
||||
require(hz>0 && hz<=1000000,"Invalid sample frequency");
|
||||
const quint8 status=b.vbPopFrontInt8(),phase=b.vbPopFrontInt8();
|
||||
row.insert("commutation",status&7);row.insert("hall",(status>>3)&7);
|
||||
row.insert("phase_deg",phase/250.0*360.0);
|
||||
row.insert("dt_s",decimation/hz);
|
||||
if(indexed)require(b.vbPopFrontInt32()==index,"Sample index trailer mismatch");
|
||||
require(b.isEmpty(),"Unexpected sample trailer");
|
||||
return row;
|
||||
}
|
||||
|
||||
class NativeSamples {
|
||||
public:
|
||||
Commands *commands=nullptr;
|
||||
QTimer timer;
|
||||
QElapsedTimer lifetime,quiet;
|
||||
QString id,state="idle",error;
|
||||
QJsonArray rows;
|
||||
int mode=0,count=0,decimation=1,expected=0,timeout=30,malformed=0;
|
||||
bool active() const {return state=="armed" || state=="receiving" || state=="stored_wait";}
|
||||
void attach(Commands *c) {
|
||||
commands=c; timer.setInterval(100);
|
||||
QObject::connect(c,&Commands::samplesReceived,[this](QByteArray raw){receive(raw);});
|
||||
QObject::connect(&timer,&QTimer::timeout,[this]{
|
||||
if(lifetime.isValid() && lifetime.elapsed()>=300000){if(active())off();rows={};state="expired";timer.stop();return;}
|
||||
if(!active())return;
|
||||
if(mode==7 && !rows.isEmpty() && quiet.elapsed()>=1000){off();state="unverified";return;}
|
||||
if(lifetime.elapsed()>=timeout*1000){off();state=rows.isEmpty()?"timeout":"incomplete";}
|
||||
});
|
||||
}
|
||||
void off(){commands->samplePrint(DEBUG_SAMPLING_OFF,0,1,false);}
|
||||
QJsonObject status() const {
|
||||
return {{"capture_id",id},{"state",state},{"received",rows.size()},{"expected",expected},
|
||||
{"capacity",2000},{"mode",mode},{"count",count},{"decimation",decimation},
|
||||
{"malformed",malformed},{"error",error},{"indexed",false},{"raw_supported",false},
|
||||
{"third_current_measured",false},{"acknowledged",false},
|
||||
{"elapsed_ms",lifetime.isValid()?double(lifetime.elapsed()):0},
|
||||
{"provenance",mode==7?"controller_last_buffer":"requested_capture"}};
|
||||
}
|
||||
QJsonObject start(const QJsonObject &p) {
|
||||
if(active())return {{"accepted",false},{"reason","Sample Data capture is already active"}};
|
||||
if(quiet.isValid() && quiet.elapsed()<1000)return {{"accepted",false},{"reason","Previous Sample Data transfer is still draining"}};
|
||||
auto integer=[&](const char *k,int lo,int hi){auto v=p.value(k);double n=v.toDouble(-1);require(v.isDouble()&&n==int(n)&&n>=lo&&n<=hi,"Invalid Sample Data argument");return int(n);};
|
||||
mode=integer("mode",1,7);count=integer("count",1,2000);decimation=integer("decimation",1,255);timeout=integer("timeout_s",2,120);
|
||||
require(!p.value("raw").toBool(),"FW5.02 does not support raw ADC sampling");
|
||||
expected=mode==7?0:mode>=3?2000:count;
|
||||
id="sample_"+QUuid::createUuid().toString(QUuid::Id128);rows={};error.clear();malformed=0;
|
||||
state=(mode==5||mode==6)?"stored_wait":"armed";lifetime.start();quiet.invalidate();timer.start();
|
||||
commands->samplePrint(debug_sampling_mode(mode),count,decimation,false);
|
||||
auto result=status();result.insert("accepted",true);return result;
|
||||
}
|
||||
void receive(const QByteArray &raw) {
|
||||
quiet.restart();if(!active())return;
|
||||
try {
|
||||
// Only the reviewed FW5.02 live profile is admitted. New formats
|
||||
// are decoded in offline checks, never guessed from a live device.
|
||||
require(raw.size()==34,"FW5.02 Sample Data layout mismatch");
|
||||
require(rows.size()<2000,"Sample Data buffer exceeded");
|
||||
rows.append(decodeSample(raw,rows.size(),decimation));state="receiving";
|
||||
if(expected && rows.size()==expected)state="complete";
|
||||
}catch(const std::exception &e){++malformed;error=QString::fromUtf8(e.what());off();state="incomplete";}
|
||||
}
|
||||
QJsonObject run(const QString &method,const QJsonObject &p) {
|
||||
if(method=="sample_start")return start(p);
|
||||
if(method=="sample_status" && !p.contains("capture_id"))return status();
|
||||
if(p.value("capture_id").toString()!=id || id.isEmpty())return {{"state","expired"}};
|
||||
if(method=="sample_stop" && active()){off();state="cancelled";}
|
||||
if(method=="sample_fetch") {
|
||||
if(state!="stored_wait")return {{"accepted",false},{"reason","No pending stored capture"}};
|
||||
// No trigger-complete ACK exists; a returned older buffer must not
|
||||
// be represented as a confirmed capture of this trigger.
|
||||
mode=7;expected=0;state="armed";rows={};timeout=30;lifetime.restart();
|
||||
commands->samplePrint(DEBUG_SAMPLING_SEND_LAST_SAMPLES,0,1,false);
|
||||
}
|
||||
auto result=status();
|
||||
if(method=="sample_read"){
|
||||
double offset=p.value("offset").toDouble(-1);require(offset==int(offset)&&offset>=0&&offset<=2000,"Invalid sample offset");
|
||||
QJsonArray page;for(int i=int(offset);i<rows.size()&&page.size()<128;++i)page.append(rows[i]);
|
||||
result.insert("rows",page);result.insert("offset",int(offset));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "firmware_source.h"
|
||||
#include <QEventLoop>
|
||||
#include <QTimer>
|
||||
|
||||
// The original BM protocol identifies MCU families, not a board or its UUID.
|
||||
// Restrict writes to declared main flash; peripheral/option/UICR regions are
|
||||
// never accepted as an ordinary firmware image.
|
||||
static QPair<quint32,int> swdRange(const QJsonObject &p) {
|
||||
const int code=p.value("target_code").toInt(-1);
|
||||
require(code>=1 && code<=13,"Unsupported SWD target family");
|
||||
const bool nrf=code>=2 && code<=8;
|
||||
const quint32 origin=nrf?0:0x08000000;
|
||||
const int cap=code==2?128*1024:code==3||code==4||code==5||code==6?256*1024:code==7?512*1024:code==8?1024*1024:2*1024*1024;
|
||||
const auto base=p.value("address").toDouble(-1),size=p.value("flash_bytes").toDouble(-1);
|
||||
require(base>=origin && base<quint64(origin)+cap && base==quint32(base) && size>=256 && size<=cap && size==int(size) && base+size<=quint64(origin)+cap,"SWD range outside main flash");
|
||||
require(p.value("pins")=="default" || p.value("pins")=="nrf5x","Unknown SWD pin mapping");
|
||||
return {quint32(base),int(size)};
|
||||
}
|
||||
static int swdConnect(VescInterface &v,const QJsonObject &p) {
|
||||
auto cmd=v.commands();
|
||||
require(!cmd->isLimitedMode() || cmd->getLimitedCompatibilityCommands().contains(COMM_BM_MEM_READ),"SWD binary verification is unsupported by this programmer firmware");
|
||||
QEventLoop loop;QTimer timeout;timeout.setSingleShot(true);QObject observer;
|
||||
bool mapped=false;int target=-100;
|
||||
QObject::connect(&timeout,&QTimer::timeout,&loop,&QEventLoop::quit);
|
||||
const auto mappedResult=[&](bool ok){mapped=ok;loop.quit();};
|
||||
if(p.value("pins")=="nrf5x")QObject::connect(cmd,&Commands::bmMapPinsNrf5xRes,&observer,mappedResult);
|
||||
else QObject::connect(cmd,&Commands::bmMapPinsDefaultRes,&observer,mappedResult);
|
||||
timeout.start(3000);
|
||||
if(p.value("pins")=="nrf5x")cmd->bmMapPinsNrf5x();else cmd->bmMapPinsDefault();
|
||||
if(!mapped)loop.exec();require(mapped,"SWD pin mapping was not acknowledged");
|
||||
QObject::connect(cmd,&Commands::bmConnRes,&observer,[&](int code){target=code;loop.quit();});
|
||||
timeout.start(3000);cmd->bmConnect();if(target==-100)loop.exec();
|
||||
require(target==p.value("target_code").toInt(-1),"Connected SWD target differs from the selected MCU family");
|
||||
return target;
|
||||
}
|
||||
static QJsonObject uploadSwd(VescInterface &v,const QJsonObject &p,const QByteArray &image,bool &cancelled) {
|
||||
const auto range=swdRange(p);require(image.size()<=range.second,"SWD image exceeds selected range");
|
||||
require(!cancelled,"SWD cancelled before connect");
|
||||
const int code=swdConnect(v,p);
|
||||
require(v.commands()->bmReadMemWait(range.first,32).size()==32 && v.commands()->bmReadMemWait(range.first+quint32(image.size())-32,32).size()==32,"SWD image endpoints are not readable main flash");
|
||||
require(!cancelled,"SWD cancelled before erase");
|
||||
require(v.swdEraseFlash(),"SWD erase unconfirmed");
|
||||
require(!cancelled,"SWD cancelled after erase");
|
||||
require(v.swdUploadFw(image,range.first,true,true),"SWD write/readback failed");
|
||||
require(!cancelled,"SWD cancelled before reboot");
|
||||
require(v.swdReboot(),"SWD reboot unconfirmed");
|
||||
return {{"target_code",code},{"binary_readback_verified",true},{"reboot_confirmed",true},{"boot_verified",false}};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
bms-settings.xml: GPL-3.0-or-later; vedderb/vesc_bms_fw, commit 591d57dadb14d4392d4cf859a5187264a8aafed8, config/settings.xml. Offline schema/codec qualification only, not installed battery defaults.
|
||||
@@ -0,0 +1,817 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ConfigParams>
|
||||
<Params>
|
||||
<config_name>
|
||||
<longName>none</longName>
|
||||
<type>3</type>
|
||||
<transmittable>0</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine></cDefine>
|
||||
<valString>main_config_t</valString>
|
||||
<maxLen>0</maxLen>
|
||||
</config_name>
|
||||
<hw_name>
|
||||
<longName>VESC BMS</longName>
|
||||
<type>0</type>
|
||||
<transmittable>0</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine></cDefine>
|
||||
</hw_name>
|
||||
<controller_id>
|
||||
<longName>BMS ID</longName>
|
||||
<type>2</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_CONTROLLER_ID</cDefine>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxInt>255</maxInt>
|
||||
<minInt>-1</minInt>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepInt>1</stepInt>
|
||||
<valInt>104</valInt>
|
||||
<suffix></suffix>
|
||||
<vTx>1</vTx>
|
||||
</controller_id>
|
||||
<send_can_status_rate_hz>
|
||||
<longName>CAN Status Rate</longName>
|
||||
<type>2</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_SEND_CAN_STATUS_RATE_HZ</cDefine>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxInt>2000</maxInt>
|
||||
<minInt>0</minInt>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepInt>1</stepInt>
|
||||
<valInt>10</valInt>
|
||||
<suffix> Hz</suffix>
|
||||
<vTx>5</vTx>
|
||||
</send_can_status_rate_hz>
|
||||
<can_baud_rate>
|
||||
<longName>CAN Baud Rate</longName>
|
||||
<type>4</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_CAN_BAUD_RATE</cDefine>
|
||||
<valInt>2</valInt>
|
||||
<enumNames>CAN_BAUD_125K</enumNames>
|
||||
<enumNames>CAN_BAUD_250K</enumNames>
|
||||
<enumNames>CAN_BAUD_500K</enumNames>
|
||||
<enumNames>CAN_BAUD_1M</enumNames>
|
||||
<enumNames>CAN_BAUD_10K</enumNames>
|
||||
<enumNames>CAN_BAUD_20K</enumNames>
|
||||
<enumNames>CAN_BAUD_50K</enumNames>
|
||||
<enumNames>CAN_BAUD_75K</enumNames>
|
||||
</can_baud_rate>
|
||||
<balance_mode>
|
||||
<longName>Balancing Mode</longName>
|
||||
<type>4</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_BALANCE_MODE</cDefine>
|
||||
<valInt>2</valInt>
|
||||
<enumNames>BALANCE_MODE_DISABLED</enumNames>
|
||||
<enumNames>BALANCE_MODE_CHARGING_ONLY</enumNames>
|
||||
<enumNames>BALANCE_MODE_DURING_AND_AFTER_CHARGING</enumNames>
|
||||
<enumNames>BALANCE_MODE_ALWAYS</enumNames>
|
||||
</balance_mode>
|
||||
<cell_num>
|
||||
<longName>Number of Cells</longName>
|
||||
<type>2</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_CELL_NUM</cDefine>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxInt>1000</maxInt>
|
||||
<minInt>0</minInt>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepInt>1</stepInt>
|
||||
<valInt>12</valInt>
|
||||
<suffix></suffix>
|
||||
<vTx>4</vTx>
|
||||
</cell_num>
|
||||
<cell_first_index>
|
||||
<longName>First Cell Index</longName>
|
||||
<type>2</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_CELL_FIRST_INDEX</cDefine>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxInt>1000</maxInt>
|
||||
<minInt>0</minInt>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepInt>1</stepInt>
|
||||
<valInt>0</valInt>
|
||||
<suffix></suffix>
|
||||
<vTx>4</vTx>
|
||||
</cell_first_index>
|
||||
<max_bal_ch>
|
||||
<longName>Max Balance Channels</longName>
|
||||
<type>2</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_MAX_BAL_CH</cDefine>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxInt>1000</maxInt>
|
||||
<minInt>0</minInt>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepInt>1</stepInt>
|
||||
<valInt>11</valInt>
|
||||
<suffix></suffix>
|
||||
<vTx>4</vTx>
|
||||
</max_bal_ch>
|
||||
<dist_bal>
|
||||
<longName>Distributed Balancing</longName>
|
||||
<type>5</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_DIST_BAL</cDefine>
|
||||
<valInt>1</valInt>
|
||||
</dist_bal>
|
||||
<vc_balance_start>
|
||||
<longName>Balance Starting Voltage</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_BALANCE_START</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>99</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.001</stepDouble>
|
||||
<valDouble>0.015</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> V</suffix>
|
||||
<vTx>9</vTx>
|
||||
</vc_balance_start>
|
||||
<vc_balance_end>
|
||||
<longName>Balance End Voltage</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_BALANCE_END</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>99</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.001</stepDouble>
|
||||
<valDouble>0.008</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> V</suffix>
|
||||
<vTx>9</vTx>
|
||||
</vc_balance_end>
|
||||
<vc_charge_start>
|
||||
<longName>Charge Start Voltage</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_CHARGE_START</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>99</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.01</stepDouble>
|
||||
<valDouble>4.16</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> V</suffix>
|
||||
<vTx>9</vTx>
|
||||
</vc_charge_start>
|
||||
<vc_charge_end>
|
||||
<longName>Charge End Voltage</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_CHARGE_END</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>99</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.01</stepDouble>
|
||||
<valDouble>4.21</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> V</suffix>
|
||||
<vTx>9</vTx>
|
||||
</vc_charge_end>
|
||||
<vc_charge_min>
|
||||
<longName>Charge Minimum Voltage</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_CHARGE_MIN</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>99</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.01</stepDouble>
|
||||
<valDouble>2</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> V</suffix>
|
||||
<vTx>9</vTx>
|
||||
</vc_charge_min>
|
||||
<vc_balance_min>
|
||||
<longName>Balance Minimum Voltage</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_BALANCE_MIN</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>99</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.01</stepDouble>
|
||||
<valDouble>3.5</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> V</suffix>
|
||||
<vTx>9</vTx>
|
||||
</vc_balance_min>
|
||||
<balance_max_current>
|
||||
<longName>Balance Maximum Current</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_BALANCE_MAX_CURRENT</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>999</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.01</stepDouble>
|
||||
<valDouble>3</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> A</suffix>
|
||||
<vTx>9</vTx>
|
||||
</balance_max_current>
|
||||
<min_current_ah_wh_cnt>
|
||||
<longName>Minimum Counter Current</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_MIN_CURRENT_AH_WH_CNT</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>999</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.01</stepDouble>
|
||||
<valDouble>0.8</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> A</suffix>
|
||||
<vTx>9</vTx>
|
||||
</min_current_ah_wh_cnt>
|
||||
<min_current_sleep>
|
||||
<longName>Minimum Sleep Current</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_MIN_CURRENT_SLEEP</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>999</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.01</stepDouble>
|
||||
<valDouble>0.5</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> A</suffix>
|
||||
<vTx>9</vTx>
|
||||
</min_current_sleep>
|
||||
<v_charge_detect>
|
||||
<longName>Charger Detect Threshold Voltage</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_V_CHARGE_DETECT</cDefine>
|
||||
<editorDecimalsDouble>1</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>999</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>30</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> V</suffix>
|
||||
<vTx>9</vTx>
|
||||
</v_charge_detect>
|
||||
<t_charge_max>
|
||||
<longName>Charge Max Temp</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_T_CHARGE_MAX</cDefine>
|
||||
<editorDecimalsDouble>1</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>150</maxDouble>
|
||||
<minDouble>-15</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>45</valDouble>
|
||||
<vTxDoubleScale>10</vTxDoubleScale>
|
||||
<suffix> °C</suffix>
|
||||
<vTx>7</vTx>
|
||||
</t_charge_max>
|
||||
<i_measure_mode>
|
||||
<longName>Current Measurement Mode</longName>
|
||||
<type>4</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_I_MEASURE_MODE</cDefine>
|
||||
<valInt>0</valInt>
|
||||
<enumNames>BMS</enumNames>
|
||||
<enumNames>VESC CAN</enumNames>
|
||||
</i_measure_mode>
|
||||
<ext_shunt_res>
|
||||
<longName>Current Shunt Resistance</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_EXT_SHUNT_RES</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1000</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>100</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.1</stepDouble>
|
||||
<valDouble>0.0002</valDouble>
|
||||
<vTxDoubleScale>10</vTxDoubleScale>
|
||||
<suffix> mΩ</suffix>
|
||||
<vTx>9</vTx>
|
||||
</ext_shunt_res>
|
||||
<ext_shunt_gain>
|
||||
<longName>Current Shunt Amp Gain</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_EXT_SHUNT_GAIN</cDefine>
|
||||
<editorDecimalsDouble>3</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>10000</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>50</valDouble>
|
||||
<vTxDoubleScale>10</vTxDoubleScale>
|
||||
<suffix></suffix>
|
||||
<vTx>9</vTx>
|
||||
</ext_shunt_gain>
|
||||
<ext_pch_r_top>
|
||||
<longName>External Precharge R Div Top</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_EXT_PCH_R_TOP</cDefine>
|
||||
<editorDecimalsDouble>2</editorDecimalsDouble>
|
||||
<editorScale>0.001</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>1e+07</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>520000</valDouble>
|
||||
<vTxDoubleScale>10</vTxDoubleScale>
|
||||
<suffix> kΩ</suffix>
|
||||
<vTx>9</vTx>
|
||||
</ext_pch_r_top>
|
||||
<ext_pch_r_bot>
|
||||
<longName>External Precharge R Div Bottom</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_EXT_PCH_R_BOTTOM</cDefine>
|
||||
<editorDecimalsDouble>2</editorDecimalsDouble>
|
||||
<editorScale>0.001</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>1e+07</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>10000</valDouble>
|
||||
<vTxDoubleScale>10</vTxDoubleScale>
|
||||
<suffix> kΩ</suffix>
|
||||
<vTx>9</vTx>
|
||||
</ext_pch_r_bot>
|
||||
<min_charge_current>
|
||||
<longName>Min Charge Current</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_MIN_CHARGE_CURRENT</cDefine>
|
||||
<editorDecimalsDouble>2</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>999</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.01</stepDouble>
|
||||
<valDouble>0.5</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> A</suffix>
|
||||
<vTx>9</vTx>
|
||||
</min_charge_current>
|
||||
<max_charge_current>
|
||||
<longName>Max Charge Current</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_MAX_CHARGE_CURRENT</cDefine>
|
||||
<editorDecimalsDouble>2</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>999</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>0.1</stepDouble>
|
||||
<valDouble>16</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix> A</suffix>
|
||||
<vTx>9</vTx>
|
||||
</max_charge_current>
|
||||
<sleep_timeout_reset_ms>
|
||||
<longName>Sleep Timeout Reset Time</longName>
|
||||
<type>2</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_SLEEP_TIMEOUT_MS</cDefine>
|
||||
<editorScale>0.001</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxInt>9999999</maxInt>
|
||||
<minInt>0</minInt>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepInt>1</stepInt>
|
||||
<valInt>240000</valInt>
|
||||
<suffix> s</suffix>
|
||||
<vTx>6</vTx>
|
||||
</sleep_timeout_reset_ms>
|
||||
<soc_filter_const>
|
||||
<longName>SoC Filter Constant</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_SOC_FILTER_CONST</cDefine>
|
||||
<editorDecimalsDouble>1</editorDecimalsDouble>
|
||||
<editorScale>1e+06</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>1</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>1e-05</valDouble>
|
||||
<vTxDoubleScale>1</vTxDoubleScale>
|
||||
<suffix></suffix>
|
||||
<vTx>9</vTx>
|
||||
</soc_filter_const>
|
||||
<t_bal_lim_start>
|
||||
<longName>Temp Bal Lim Start</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_T_BAL_LIM_START</cDefine>
|
||||
<editorDecimalsDouble>1</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>200</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>60</valDouble>
|
||||
<vTxDoubleScale>10</vTxDoubleScale>
|
||||
<suffix> °C</suffix>
|
||||
<vTx>7</vTx>
|
||||
</t_bal_lim_start>
|
||||
<t_bal_lim_end>
|
||||
<longName>Temp Bal Lim End</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_T_BAL_LIM_END</cDefine>
|
||||
<editorDecimalsDouble>1</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>200</maxDouble>
|
||||
<minDouble>0</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>75</valDouble>
|
||||
<vTxDoubleScale>10</vTxDoubleScale>
|
||||
<suffix> °C</suffix>
|
||||
<vTx>7</vTx>
|
||||
</t_bal_lim_end>
|
||||
<t_charge_min>
|
||||
<longName>Charge Min Temp</longName>
|
||||
<type>1</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_T_CHARGE_MIN</cDefine>
|
||||
<editorDecimalsDouble>1</editorDecimalsDouble>
|
||||
<editorScale>1</editorScale>
|
||||
<editAsPercentage>0</editAsPercentage>
|
||||
<maxDouble>150</maxDouble>
|
||||
<minDouble>-45</minDouble>
|
||||
<showDisplay>0</showDisplay>
|
||||
<stepDouble>1</stepDouble>
|
||||
<valDouble>0</valDouble>
|
||||
<vTxDoubleScale>10</vTxDoubleScale>
|
||||
<suffix> °C</suffix>
|
||||
<vTx>7</vTx>
|
||||
</t_charge_min>
|
||||
<t_charge_mon_en>
|
||||
<longName>Charge Temp Mon</longName>
|
||||
<type>5</type>
|
||||
<transmittable>1</transmittable>
|
||||
<description><!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></description>
|
||||
<cDefine>CONF_T_CHARGE_MON_EN</cDefine>
|
||||
<valInt>1</valInt>
|
||||
</t_charge_mon_en>
|
||||
</Params>
|
||||
<SerOrder>
|
||||
<ser>controller_id</ser>
|
||||
<ser>send_can_status_rate_hz</ser>
|
||||
<ser>can_baud_rate</ser>
|
||||
<ser>max_bal_ch</ser>
|
||||
<ser>dist_bal</ser>
|
||||
<ser>balance_mode</ser>
|
||||
<ser>cell_num</ser>
|
||||
<ser>cell_first_index</ser>
|
||||
<ser>vc_balance_start</ser>
|
||||
<ser>vc_balance_end</ser>
|
||||
<ser>vc_charge_start</ser>
|
||||
<ser>vc_charge_end</ser>
|
||||
<ser>vc_charge_min</ser>
|
||||
<ser>vc_balance_min</ser>
|
||||
<ser>balance_max_current</ser>
|
||||
<ser>min_current_ah_wh_cnt</ser>
|
||||
<ser>min_current_sleep</ser>
|
||||
<ser>v_charge_detect</ser>
|
||||
<ser>t_charge_max</ser>
|
||||
<ser>i_measure_mode</ser>
|
||||
<ser>ext_shunt_res</ser>
|
||||
<ser>ext_shunt_gain</ser>
|
||||
<ser>ext_pch_r_top</ser>
|
||||
<ser>ext_pch_r_bot</ser>
|
||||
<ser>min_charge_current</ser>
|
||||
<ser>max_charge_current</ser>
|
||||
<ser>sleep_timeout_reset_ms</ser>
|
||||
<ser>soc_filter_const</ser>
|
||||
<ser>t_bal_lim_start</ser>
|
||||
<ser>t_bal_lim_end</ser>
|
||||
<ser>t_charge_min</ser>
|
||||
<ser>t_charge_mon_en</ser>
|
||||
</SerOrder>
|
||||
<Grouping>
|
||||
<group>
|
||||
<groupName>General</groupName>
|
||||
<subgroup>
|
||||
<subgroupName>General</subgroupName>
|
||||
<subgroupParams>
|
||||
<param>cell_num</param>
|
||||
<param>cell_first_index</param>
|
||||
<param>soc_filter_const</param>
|
||||
</subgroupParams>
|
||||
</subgroup>
|
||||
<subgroup>
|
||||
<subgroupName>Charging</subgroupName>
|
||||
<subgroupParams>
|
||||
<param>vc_charge_start</param>
|
||||
<param>vc_charge_end</param>
|
||||
<param>vc_charge_min</param>
|
||||
<param>v_charge_detect</param>
|
||||
<param>t_charge_min</param>
|
||||
<param>t_charge_max</param>
|
||||
<param>t_charge_mon_en</param>
|
||||
<param>min_charge_current</param>
|
||||
<param>max_charge_current</param>
|
||||
</subgroupParams>
|
||||
</subgroup>
|
||||
<subgroup>
|
||||
<subgroupName>Balancing</subgroupName>
|
||||
<subgroupParams>
|
||||
<param>balance_mode</param>
|
||||
<param>vc_balance_start</param>
|
||||
<param>vc_balance_end</param>
|
||||
<param>vc_balance_min</param>
|
||||
<param>balance_max_current</param>
|
||||
<param>max_bal_ch</param>
|
||||
<param>dist_bal</param>
|
||||
<param>t_bal_lim_start</param>
|
||||
<param>t_bal_lim_end</param>
|
||||
</subgroupParams>
|
||||
</subgroup>
|
||||
<subgroup>
|
||||
<subgroupName>Sleep</subgroupName>
|
||||
<subgroupParams>
|
||||
<param>min_current_sleep</param>
|
||||
<param>sleep_timeout_reset_ms</param>
|
||||
</subgroupParams>
|
||||
</subgroup>
|
||||
<subgroup>
|
||||
<subgroupName>Counters</subgroupName>
|
||||
<subgroupParams>
|
||||
<param>min_current_ah_wh_cnt</param>
|
||||
</subgroupParams>
|
||||
</subgroup>
|
||||
<subgroup>
|
||||
<subgroupName>Communication</subgroupName>
|
||||
<subgroupParams>
|
||||
<param>controller_id</param>
|
||||
<param>send_can_status_rate_hz</param>
|
||||
<param>can_baud_rate</param>
|
||||
</subgroupParams>
|
||||
</subgroup>
|
||||
<subgroup>
|
||||
<subgroupName>External</subgroupName>
|
||||
<subgroupParams>
|
||||
<param>i_measure_mode</param>
|
||||
<param>ext_shunt_res</param>
|
||||
<param>ext_shunt_gain</param>
|
||||
<param>ext_pch_r_top</param>
|
||||
<param>ext_pch_r_bot</param>
|
||||
</subgroupParams>
|
||||
</subgroup>
|
||||
</group>
|
||||
</Grouping>
|
||||
</ConfigParams>
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
#include "config_export.h"
|
||||
#include <QEventLoop>
|
||||
#include <QMetaProperty>
|
||||
#include <QTimer>
|
||||
|
||||
// Decoding and firmware compatibility belong to Commands. This adapter only
|
||||
// projects its typed result; it never builds or parses vendor packets.
|
||||
template<typename T> static QJsonObject toolNumbers(const T &value) {
|
||||
QJsonObject out;
|
||||
for (int i=0; i<T::staticMetaObject.propertyCount(); ++i) {
|
||||
const auto p=T::staticMetaObject.property(i);
|
||||
const auto v=p.readOnGadget(&value);
|
||||
if (v.type()==QVariant::Double || v.type()==QVariant::Int || v.type()==QVariant::String)
|
||||
out.insert(QString::fromLatin1(p.name()),QJsonValue::fromVariant(v));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
static QJsonObject readNativeTool(VescInterface &vesc, const QString &tool) {
|
||||
auto *cmd=vesc.commands();
|
||||
const QMap<QString,int> codes{{"adc",COMM_GET_DECODED_ADC},{"chuk",COMM_GET_DECODED_CHUK},
|
||||
{"imu",COMM_GET_IMU_DATA},{"bms",COMM_BMS_GET_VALUES}};
|
||||
require(codes.contains(tool),"Unknown peripheral tool");
|
||||
if (!cmd->getLimitedCompatibilityCommands().contains(codes.value(tool)))
|
||||
return {{"tool",tool},{"state","unsupported"}};
|
||||
QEventLoop loop; QTimer timeout; timeout.setSingleShot(true); QObject observer;
|
||||
QJsonObject values; bool received=false;
|
||||
auto finish=[&](const QJsonObject &v){values=v;received=true;loop.quit();};
|
||||
QObject::connect(cmd,&Commands::decodedAdcReceived,&observer,[&](double v,double volts,double v2,double volts2){
|
||||
if(tool=="adc")finish({{"level_1",v},{"voltage_1_v",volts},{"level_2",v2},{"voltage_2_v",volts2}});
|
||||
});
|
||||
QObject::connect(cmd,&Commands::decodedChukReceived,&observer,[&](double v){if(tool=="chuk")finish({{"level",v}});});
|
||||
QObject::connect(cmd,&Commands::valuesImuReceived,&observer,[&](IMU_VALUES v,unsigned int mask){
|
||||
if(tool=="imu"){auto out=toolNumbers(v);out.insert("mask",double(mask));finish(out);}
|
||||
});
|
||||
QObject::connect(cmd,&Commands::bmsValuesRx,&observer,[&](BMS_VALUES v){
|
||||
if(tool!="bms")return;
|
||||
auto out=toolNumbers(v);QJsonArray cells,temps,balancing;
|
||||
for(auto x:v.v_cells)cells.append(x);for(auto x:v.temps)temps.append(x);for(auto x:v.is_balancing)balancing.append(x);
|
||||
out.insert("v_cells",cells);out.insert("temps",temps);out.insert("is_balancing",balancing);finish(out);
|
||||
});
|
||||
QObject::connect(&timeout,&QTimer::timeout,&loop,&QEventLoop::quit);timeout.start(2000);
|
||||
if(tool=="adc")cmd->getDecodedAdc();
|
||||
if(tool=="chuk")cmd->getDecodedChuk();
|
||||
if(tool=="imu")cmd->getImuData(0xffff);
|
||||
if(tool=="bms")cmd->bmsGetValues();
|
||||
if(!received)loop.exec();
|
||||
require(vesc.isPortConnected(),"Peripheral read disconnected");
|
||||
return {{"tool",tool},{"state",received?"received":"no_response"},{"values",values}};
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import zipfile
|
||||
from engine_profile import load_profile, header
|
||||
|
||||
|
||||
def build(output):
|
||||
@@ -11,8 +12,33 @@ def build(output):
|
||||
files = {"__main__.py": (root / "packaging/native_probe.py").read_bytes(),
|
||||
"offline_main.cpp": (root / "native/offline_main.cpp").read_bytes(),
|
||||
"config_export.h": (root / "native/config_export.h").read_bytes(),
|
||||
"firmware_image.h": (root / "native/firmware_image.h").read_bytes(),
|
||||
"firmware_source.h": (root / "native/firmware_source.h").read_bytes(),
|
||||
"bms_native.h": (root / "native/bms_native.h").read_bytes(),
|
||||
"custom_native.h": (root / "native/custom_native.h").read_bytes(),
|
||||
"code_native.h": (root / "native/code_native.h").read_bytes(),
|
||||
"package_native.h": (root / "native/package_native.h").read_bytes(),
|
||||
"tools_native.h": (root / "native/tools_native.h").read_bytes(),
|
||||
"swd_native.h": (root / "native/swd_native.h").read_bytes(),
|
||||
"firmware_native.h": (root / "native/firmware_native.h").read_bytes(),
|
||||
"config_edit.h": (root / "native/config_edit.h").read_bytes(),
|
||||
"engine_main.cpp": (root / "native/engine_main.cpp").read_bytes(),
|
||||
"native_bundle.py": (root / "packaging/native_bundle.py").read_bytes()}
|
||||
files["bms-settings.xml"] = (root / "native/test-fixtures/bms-settings.xml").read_bytes()
|
||||
files["native_extensions_check.py"] = (root / "packaging/native_extensions_check.py").read_bytes()
|
||||
files["native_packages_check.py"] = (root / "packaging/native_packages_check.py").read_bytes()
|
||||
files["package_archive.py"] = (root / "runtime/package_archive.py").read_bytes()
|
||||
files["vesc_pkg_all.rcc"] = (root / "build/package-catalog/vesc_pkg_all.rcc").read_bytes()
|
||||
for name in ("qml_vesc_interface.h", "qml_broker.h", "qml_interactive.h", "sample_data.h", "qml_preview.cpp", "qml_sandbox.h"):
|
||||
files[name] = (root / "native" / name).read_bytes()
|
||||
files["native_broker_check.py"] = (root / "packaging/native_broker_check.py").read_bytes()
|
||||
files["native_samples_check.py"] = (root / "packaging/native_samples_check.py").read_bytes()
|
||||
files["qml_build.py"] = (root / "packaging/qml_build.py").read_bytes()
|
||||
files["native_can_check.py"] = (root / "packaging/native_can_check.py").read_bytes()
|
||||
profile = load_profile()
|
||||
files["engine-profile.json"] = json.dumps(profile, sort_keys=True).encode()
|
||||
files["engine_profile.py"] = (root / "packaging/engine_profile.py").read_bytes()
|
||||
files["engine_profile.h"] = header(profile)
|
||||
identity = hashlib.sha256(b"".join(k.encode() + v for k, v in sorted(files.items()))).hexdigest()[:24]
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
path = output / ("mission-core-vesc-native-probe-" + identity + ".pyz")
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"schema": "missioncore.vesc.engine-profile/v1",
|
||||
"rpc_version": 1,
|
||||
"upstream": {
|
||||
"repository": "https://github.com/vedderb/vesc_tool",
|
||||
"version": "7.00",
|
||||
"commit": "01d5f10901116c311e3fb84d5a1541f663d3ce20",
|
||||
"source_sha256": "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189"
|
||||
},
|
||||
"environment": "ubuntu-24.04-amd64",
|
||||
"firmware_profiles": [
|
||||
{
|
||||
"major": 5,
|
||||
"minor": 2,
|
||||
"hardware_type": 0,
|
||||
"test_firmware": 0,
|
||||
"custom_configs": 0
|
||||
}
|
||||
],
|
||||
"methods": [
|
||||
"engine",
|
||||
"query",
|
||||
"diagnostic",
|
||||
"configuration",
|
||||
"procedure_result",
|
||||
"lease",
|
||||
"release",
|
||||
"current",
|
||||
"rpm",
|
||||
"duty",
|
||||
"duty_limited",
|
||||
"limits",
|
||||
"foc_start",
|
||||
"hall_start",
|
||||
"configuration_preview",
|
||||
"configuration_apply",
|
||||
"firmware_begin",
|
||||
"firmware_chunk",
|
||||
"firmware_seal",
|
||||
"firmware_start",
|
||||
"firmware_status",
|
||||
"firmware_cancel",
|
||||
"device_tool",
|
||||
"bms_read",
|
||||
"bms_command",
|
||||
"firmware_target",
|
||||
"firmware_snapshot",
|
||||
"custom_read",
|
||||
"custom_preview",
|
||||
"custom_apply",
|
||||
"code_pack",
|
||||
"code_read",
|
||||
"code_write",
|
||||
"code_control",
|
||||
"code_stats",
|
||||
"package_unpack",
|
||||
"code_snapshot",
|
||||
"sample_start",
|
||||
"sample_status",
|
||||
"sample_fetch",
|
||||
"sample_stop",
|
||||
"sample_read",
|
||||
"qml_read"
|
||||
],
|
||||
"firmware_formats": [
|
||||
"bin",
|
||||
"hex"
|
||||
],
|
||||
"bms_profiles": [
|
||||
{
|
||||
"major": 6,
|
||||
"minor": 0
|
||||
}
|
||||
],
|
||||
"bms_protocol_source": {
|
||||
"repository": "https://github.com/vedderb/vesc_bms_fw",
|
||||
"commit": "591d57dadb14d4392d4cf859a5187264a8aafed8"
|
||||
},
|
||||
"firmware_targets": [
|
||||
"usb",
|
||||
"can",
|
||||
"swd"
|
||||
],
|
||||
"code_profiles": [
|
||||
{
|
||||
"major": 6,
|
||||
"minor": 0,
|
||||
"hardware_type": 0,
|
||||
"test_firmware": 0
|
||||
}
|
||||
],
|
||||
"control_transports": [
|
||||
"usb",
|
||||
"can"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Reviewed upstream pin and adapter contract; updates never imply hardware acceptance."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
def load_profile(raw=None):
|
||||
profile = json.loads(raw if raw is not None else Path(__file__).with_name("engine-profile.json").read_bytes())
|
||||
if (profile.get("schema") != "missioncore.vesc.engine-profile/v1"
|
||||
or profile.get("rpc_version") != 1 or type(profile["rpc_version"]) is not int
|
||||
or profile.get("environment") != "ubuntu-24.04-amd64"):
|
||||
raise ValueError("Unsupported native engine contract")
|
||||
source = profile.get("upstream", {})
|
||||
if (source.get("repository") != "https://github.com/vedderb/vesc_tool"
|
||||
or not re.fullmatch(r"[0-9]+\.[0-9]{2}", source.get("version", ""))
|
||||
or not re.fullmatch(r"[0-9a-f]{40}", source.get("commit", ""))
|
||||
or not re.fullmatch(r"[0-9a-f]{64}", source.get("source_sha256", ""))):
|
||||
raise ValueError("Upstream source must be pinned by commit and archive hash")
|
||||
profiles = profile.get("firmware_profiles")
|
||||
fields = {"major", "minor", "hardware_type", "test_firmware", "custom_configs"}
|
||||
if not isinstance(profiles, list) or not 1 <= len(profiles) <= 64:
|
||||
raise ValueError("Explicit bounded firmware profiles required")
|
||||
for item in profiles:
|
||||
if (not isinstance(item, dict) or set(item) != fields
|
||||
or any(type(v) is not int or not 0 <= v <= 255 for v in item.values())):
|
||||
raise ValueError("Invalid firmware acceptance profile")
|
||||
methods = profile.get("methods")
|
||||
if (not isinstance(methods, list) or not 1 <= len(methods) <= 128
|
||||
or len(set(methods)) != len(methods)
|
||||
or any(not isinstance(v, str) or not re.fullmatch(r"[a-z_]{1,48}", v) for v in methods)
|
||||
or not {"engine", "query", "configuration"}.issubset(methods)):
|
||||
raise ValueError("Invalid native operation inventory")
|
||||
if profile.get("firmware_formats", ["bin"]) not in (["bin"], ["bin", "hex"]):
|
||||
raise ValueError("Invalid firmware file formats")
|
||||
if profile.get("firmware_targets",["usb"]) not in (["usb"],["usb","can","swd"]):raise ValueError("Invalid firmware transports")
|
||||
if profile.get("control_transports", ["usb"]) not in (["usb"], ["usb", "can"]):
|
||||
raise ValueError("Invalid control transports")
|
||||
bms = profile.get("bms_profiles", [])
|
||||
if not isinstance(bms,list) or len(bms)>16 or any(not isinstance(v,dict) or set(v)!={"major","minor"} or any(type(n) is not int or not 0<=n<=255 for n in v.values()) for v in bms):
|
||||
raise ValueError("Explicit BMS command profiles required")
|
||||
if bms:
|
||||
source=profile.get("bms_protocol_source",{})
|
||||
if source.get("repository")!="https://github.com/vedderb/vesc_bms_fw" or not re.fullmatch(r"[0-9a-f]{40}",source.get("commit","")):
|
||||
raise ValueError("Pinned BMS protocol source required")
|
||||
code = profile.get("code_profiles", [])
|
||||
if code not in ([], [{"major":6,"minor":0,"hardware_type":0,"test_firmware":0}]): raise ValueError("Unreviewed code protocol profile")
|
||||
return profile
|
||||
|
||||
|
||||
def contract(profile):
|
||||
raw = json.dumps(profile, sort_keys=True, separators=(",", ":")).encode()
|
||||
return {"rpc_version": profile["rpc_version"], "profile_sha256": hashlib.sha256(raw).hexdigest(),
|
||||
"control_transports": profile.get("control_transports", ["usb"]), "code_profiles":profile.get("code_profiles",[]), "firmware_profiles": profile["firmware_profiles"], "methods": profile["methods"],
|
||||
"firmware_targets":profile.get("firmware_targets",["usb"]), "firmware_formats": profile.get("firmware_formats", ["bin"]), "bms_profiles": profile.get("bms_profiles", [])}
|
||||
|
||||
|
||||
def header(profile):
|
||||
data = {**profile, "contract": contract(profile)}
|
||||
literal = json.dumps(json.dumps(data, sort_keys=True, separators=(",", ":")))
|
||||
return ("// Generated from the reviewed engine profile; do not edit.\n#pragma once\n"
|
||||
"#include <QJsonDocument>\n#include <QJsonArray>\n#include <QJsonObject>\n"
|
||||
"static QJsonObject engineProfile() { return QJsonDocument::fromJson(QByteArray(" + literal + ")).object(); }\n"
|
||||
"static bool nativeFirmwareQualified(int major, int minor, int type, int test, int custom) {\n"
|
||||
" for (const auto &value : engineProfile().value(\"firmware_profiles\").toArray()) {\n"
|
||||
" auto p = value.toObject(); if (p.value(\"major\").toInt() == major && p.value(\"minor\").toInt() == minor &&\n"
|
||||
" p.value(\"hardware_type\").toInt() == type && p.value(\"test_firmware\").toInt() == test &&\n"
|
||||
" p.value(\"custom_configs\").toInt() == custom) return true;\n"
|
||||
" } return false;\n}\n").encode()
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Restore reviewed official firmware blobs; never selects a moving upstream ref."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import urllib.request
|
||||
|
||||
|
||||
def fetch(output):
|
||||
manifest=json.loads(Path(__file__).with_name('firmware-catalog.json').read_text())
|
||||
commit=manifest['commit']
|
||||
if not re.fullmatch(r'[0-9a-f]{40}',commit) or len(manifest['items'])>512:
|
||||
raise ValueError('Reviewed catalogue pin required')
|
||||
output.mkdir(parents=True,exist_ok=True)
|
||||
for item in manifest['items']:
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\.bin',item['path']):
|
||||
raise ValueError('Invalid upstream firmware path')
|
||||
sha=item['sha256']
|
||||
if not re.fullmatch(r'[0-9a-f]{64}',sha) or not 256<=item['bytes']<=2*1024**2:
|
||||
raise ValueError('Invalid firmware size/digest')
|
||||
path=output/(sha+'.bin')
|
||||
if path.exists():
|
||||
data=path.read_bytes()
|
||||
else:
|
||||
url='https://raw.githubusercontent.com/vedderb/vesc_fw_archive/'+commit+'/'+item['path']
|
||||
with urllib.request.urlopen(url,timeout=30) as response:data=response.read(item['bytes']+1)
|
||||
if len(data)!=item['bytes'] or hashlib.sha256(data).hexdigest()!=sha:
|
||||
raise ValueError('Pinned firmware bytes changed')
|
||||
if hashlib.sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest()!=item['git_blob']:
|
||||
raise ValueError('Upstream Git blob changed')
|
||||
if not path.exists():path.write_bytes(data)
|
||||
return {'commit':commit,'images':len(manifest['items'])}
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('--output',type=Path,required=True)
|
||||
print(json.dumps(fetch(p.parse_args().output)))
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Restore the reviewed catalogue bytes; never silently adopt new code."""
|
||||
from pathlib import Path
|
||||
import hashlib,json,urllib.request
|
||||
|
||||
def main():
|
||||
root=Path(__file__).resolve().parents[1];pin=json.loads((root/'packaging/package-catalog.json').read_text())
|
||||
target=root/'build/package-catalog/vesc_pkg_all.rcc'
|
||||
if target.exists() and hashlib.sha256(target.read_bytes()).hexdigest()==pin['sha256']:return
|
||||
with urllib.request.urlopen(pin['source'],timeout=30) as response:data=response.read(pin['bytes']+1)
|
||||
if len(data)!=pin['bytes'] or hashlib.sha256(data).hexdigest()!=pin['sha256']:raise ValueError('Upstream catalogue changed; review and repin explicitly or restore the qualified artifact')
|
||||
target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,13 @@
|
||||
Official archived VESC firmware images, unmodified.
|
||||
Repository: https://github.com/vedderb/vesc_fw_archive
|
||||
Archive revision: 0030cfa9d6250331436b31a01f006fe0546bf6a6
|
||||
Firmware version included: 5.02
|
||||
The catalog records each upstream path, Git blob ID, size and SHA-256.
|
||||
Upstream firmware source: https://github.com/vedderb/bldc/tree/5.02
|
||||
Firmware license: GNU GPL version 3 or later (see firmware LICENSE).
|
||||
No claim of locally reproduced binary/source equivalence is made. These are
|
||||
upstream archived binaries; the manifest is not manufacturer authentication.
|
||||
Archive selection does not flash a controller. Firmware updates require a
|
||||
separate explicit operator action for a compatible board.
|
||||
Rebuild the installer inputs with packaging/fetch_firmware_catalog.py using
|
||||
the committed catalog manifest. Runtime downloads are not used.
|
||||
@@ -0,0 +1,593 @@
|
||||
{
|
||||
"schema": "missioncore.vesc.firmware-catalog/v1",
|
||||
"repository": "https://github.com/vedderb/vesc_fw_archive",
|
||||
"commit": "0030cfa9d6250331436b31a01f006fe0546bf6a6",
|
||||
"admitted_versions": [
|
||||
"5.02"
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"id": "fwimg_75a855d02179b810b87e40b7a14002ee",
|
||||
"path": "5.02/100_250/VESC_default.bin",
|
||||
"git_blob": "c90ccf8657d3757c22a794e640f23423a08ae846",
|
||||
"sha256": "cf2eb45caaf6b6514adf392e833c54774c910879d3a82b7fdf9e87369c5533b6",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"100_250"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_4aefbbe67d1cfd47e6d5bede921b13e6",
|
||||
"path": "5.02/100_250/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "24bc5beaebd9193c7cd57703e65a4ed18f282998",
|
||||
"sha256": "229bc4d414864df07ce8cb066c52957fd9ef285225d3ce45007c04c2e752ed0a",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"100_250"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_3bf6f675f714c999b0acc2e511546958",
|
||||
"path": "5.02/410_o_411_o_412/VESC_0005ohm.bin",
|
||||
"git_blob": "893e8e9df2768b2c9a708f9565ede7c99b6b3f3b",
|
||||
"sha256": "c2bd00715419ae4a502c085a5ae9b605bfbe8b70e9c9af6cf14e4e20111365e9",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"410",
|
||||
"411",
|
||||
"412"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_0005ohm.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_80183324bdf6fb609c5a81a28771b31b",
|
||||
"path": "5.02/410_o_411_o_412/VESC_default.bin",
|
||||
"git_blob": "8d9a8672aee647bb79e0932e38e27f6bc7361040",
|
||||
"sha256": "70d491dd289569dd9d1d680a497a8aac66daaa09f9a0738fa8209ebc78b256cc",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"410",
|
||||
"411",
|
||||
"412"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_939bd113ef079cd9395fc0ea0f9b3186",
|
||||
"path": "5.02/410_o_411_o_412/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "80089b6b99015e0c8c5cebd51f3177dff855f89c",
|
||||
"sha256": "d412b6996539cd366ee7d128e84be2c62615c50794b3d37e98c4e74ee05e856d",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"410",
|
||||
"411",
|
||||
"412"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_681a14ef42afe71a902081629d74b2ef",
|
||||
"path": "5.02/46_o_47/VESC_0005ohm.bin",
|
||||
"git_blob": "346277633899b3e6521ae81080450f578647165f",
|
||||
"sha256": "8ca6965370105cd9ce19b75750c85c784d0978d2e8aa0435e853d03adbc4bd92",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"46",
|
||||
"47"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_0005ohm.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_57c7db707659d6a3c83ca1b43f60f3ea",
|
||||
"path": "5.02/46_o_47/VESC_33k.bin",
|
||||
"git_blob": "935687e5287cf161b23451f9640c1ee025af784b",
|
||||
"sha256": "b3c93169808237acbccd17f5edfaf7b3b7d5d804000d3452f226482fcca81807",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"46",
|
||||
"47"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_33k.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_3be270d4c425948c504cbd7fe5483855",
|
||||
"path": "5.02/46_o_47/VESC_default.bin",
|
||||
"git_blob": "1e95afa5ca6a56f3dd2204d0700ad14399f3cd20",
|
||||
"sha256": "8324b8f37666301aa35aa04aa9766b4a9d7b47ef675247c2d1621e40a45c1238",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"46",
|
||||
"47"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_f08494a202c43657f17f1b1b730aa945",
|
||||
"path": "5.02/48/VESC_default.bin",
|
||||
"git_blob": "3ad4d01d29deecbfe6f2526471ce3a4ca616135c",
|
||||
"sha256": "29cb80525dd88adeaa0bb0ca89fe31c47251df9a7d50607a95b2487cab2b4d78",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"48"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_248e82b3658efdc981674300f3da5461",
|
||||
"path": "5.02/60/VESC_default.bin",
|
||||
"git_blob": "5c2e98823998fee69c46c0a72b803d37442069f5",
|
||||
"sha256": "5f5c7c876d28e9454d8798b33bbb3844ece52e5ce3bbad2653a025f1c83e4f90",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"60"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_579fc598378b6ebc98133bfebd67f43f",
|
||||
"path": "5.02/60/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "5c5f692fa0622207dab86b525a0517677d96d45b",
|
||||
"sha256": "74ccc48aff7f95ec772d1dc8101b94f41f9f11e588c3afdb9a51d1f67d7cad2a",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"60"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_e2e670e40ec08022f880ae6b742d6d01",
|
||||
"path": "5.02/60_MK3/VESC_default.bin",
|
||||
"git_blob": "784ad4cfb5e650a7ba0ff7105a21f23f4aa1b4d2",
|
||||
"sha256": "055cd5d315d52225d5446e17c99c6c33d7e1e80c209d8b8b3832b533703f1a50",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"60_MK3"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_c33e1f3a783192f48410c1d920f10992",
|
||||
"path": "5.02/60_MK3/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "a532f14539ceab8b93f747523df8f5947236e4bb",
|
||||
"sha256": "55f761c5da50e69d84516f29d8a7d8374be63aad4e25404a89edbdc981129ebb",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"60_MK3"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_8279ca0cd0e0fd8c8ac7862759badf92",
|
||||
"path": "5.02/60_MK4/VESC_default.bin",
|
||||
"git_blob": "43d5946127e3adc87dffb16cf993334c74ac4fb7",
|
||||
"sha256": "5ddfa85461e5dfe203e183c1b0bfdc392e5d8e310a675e61a5a8da971bd8d413",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"60_MK4"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_ceff40c3cb92c34ab9735d7e960ef978",
|
||||
"path": "5.02/60_MK4/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "f2bdf292c1b2ed5f3a012532b4d2aa94757fa31c",
|
||||
"sha256": "24a93b4a0d3ab2ce5bc6e08129a4c81071f4e448e267b9f5629beed5272703bc",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"60_MK4"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_2b9bc59a8361eead3e11da0889404c73",
|
||||
"path": "5.02/60_MK5/VESC_default.bin",
|
||||
"git_blob": "0650e356c0304fccd5fcc4ad4d826e65c666b934",
|
||||
"sha256": "b7116ce5fbb739d2dfac6efdbd6b9e90fe5f9d552d482d65eebee4651dc6075e",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"60_MK5"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_c944ee5400afa5e02ef43a175d0603ab",
|
||||
"path": "5.02/60_MK5/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "22bc5b6fac1e188e1bfa93cd077f62833b8af38d",
|
||||
"sha256": "d75fd10faf81d841811f35d5a49a41eb1bba2e80adf1c9f70e1626bb0f7582e0",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"60_MK5"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_d2bd9fd4be5681db97f28095b7b69771",
|
||||
"path": "5.02/75_300/VESC_default.bin",
|
||||
"git_blob": "253d5be8030d0a7bb3805cf0acf88ae0c6b53ad1",
|
||||
"sha256": "b646c7e5c8b6014062833c8a1c96126c2b7b729672579723848bc8f0a3aa68d5",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"75_300"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_c6729c906442486769f56f5ff2b43b87",
|
||||
"path": "5.02/75_300/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "c2308f8c2ec9e28ea3af88ead47ae4982ed524c0",
|
||||
"sha256": "a19af872f4fc422da2bdc34d0ea330b787cc7c27392b4bededaf561db20ccb07",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"75_300"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_b9ca797afd58d737be17a2f73b721018",
|
||||
"path": "5.02/75_300_R2/VESC_default.bin",
|
||||
"git_blob": "5b79daf0d41008ff7ccad72b00ff8d0dc24f187d",
|
||||
"sha256": "52c3d9c8d1e7d5670d43d7976a0f02d68c356a666488bcb8d95228e321adf32a",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"75_300_R2"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_80c2913ec89ac6673d2be4b247a0aa69",
|
||||
"path": "5.02/75_300_R2/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "ce5d05d2b73f78df5f5a8209588699ff1db90d79",
|
||||
"sha256": "6d541051f2fcbf946e92db95a4cd573f2f94a3c5fb7cf4d638c9648038b143e9",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"75_300_R2"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_2f2d894c2758153f6cf7941b3c928846",
|
||||
"path": "5.02/75_300_R3/VESC_default.bin",
|
||||
"git_blob": "b8bdb09c31fc396ba40668e02f1489d533d34f24",
|
||||
"sha256": "9e1d3c2ccaa12067b604492ebfd1fea2c8768663e7b9b5c45711ad98ca347643",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"75_300_R3"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_2e065e7221d31da73cb36d210b9dcc09",
|
||||
"path": "5.02/75_300_R3/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "368d51117b0f92b018a0e5edc82b169ebf5e9c92",
|
||||
"sha256": "b317f748161d8667f6a36cbeb37e97b3ca959eaaa295aada4bffdc6b6a14946e",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"75_300_R3"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_f9fd23f542101759c6cd3d86b1373a4b",
|
||||
"path": "5.02/A200S_V21/VESC_default.bin",
|
||||
"git_blob": "ea3af455b80c648cba90de9308a23dc5f94edd6d",
|
||||
"sha256": "402af86fecd20118762f0d0bd39af63c4b94008deeb3a6500cd8456edd4766a0",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"A200S_V21"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_8ae9a0f15636d664557b0143933c7df1",
|
||||
"path": "5.02/A200S_V22/VESC_default.bin",
|
||||
"git_blob": "f0cc0d5bbd3c3dca813821c3d80438a183ccf48e",
|
||||
"sha256": "edab8fbe92aca9d99ac13ed786c690c859b4a74456362b55e566d7ac38547a65",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"A200S_V22"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_392b962f7e97e92575391f102b022f39",
|
||||
"path": "5.02/AXIOM/VESC_default.bin",
|
||||
"git_blob": "cff1a12ceb7650aa3aeed879e9e946d8058df374",
|
||||
"sha256": "9d365675f1edcf609efb5a17a80fa1cfd4f6bd2baa597512584e5a9f16587095",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"AXIOM"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_ed9bcf99fb6e822056f4aacc94586c3e",
|
||||
"path": "5.02/DAS_RS/VESC_default.bin",
|
||||
"git_blob": "8bab886fbbaf3b0fef51d1f55c62254df7b3833a",
|
||||
"sha256": "8797f475aea54dda11ccea40039fabb40f8faf69ec4cbc64c896d70b3b06bb42",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"DAS_RS"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_3c3d4fd4e1c0239a190fc561cef33ddf",
|
||||
"path": "5.02/HD60/VESC_default.bin",
|
||||
"git_blob": "6855adb297e6cefe443f7c656621bf9380dfb328",
|
||||
"sha256": "af3eae52ff6f906cdcecf581c1f66297c09095a63ca700b4c6aa9a648b0cf7e0",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"HD60"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_0b76cd76dc14492b1d0314b1b2599a0a",
|
||||
"path": "5.02/HD60/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "cce2905941e677ec21cfb5d37dcee54728f0a898",
|
||||
"sha256": "1231a6cc61917e773295082ca796515aa6aee9fe5bb12119f94cdb40745d9e49",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"HD60"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_25123e904a14be40712992047681f4b2",
|
||||
"path": "5.02/HD75/VESC_default.bin",
|
||||
"git_blob": "f2f46d242f0dfd7abf57dd4e7a19510f5b4bcc4a",
|
||||
"sha256": "d3ce9be5a85ca7a613c85899412ec0cbc4c025c3168baa161ca43d2204bec4e6",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"HD75"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_547e9963b050a1d412344d07bda659ed",
|
||||
"path": "5.02/HD75/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "50071916243efbaa6c67cc0bb26c0ae1cfae777a",
|
||||
"sha256": "e015ec6c4502a3ef2475d77d9f72fb5ec007f08f7a70716f3f9bb74a069d5d84",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"HD75"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_8445452db9e2c15e0edafc4232baf6a2",
|
||||
"path": "5.02/LUNA_BBSHD/VESC_default.bin",
|
||||
"git_blob": "8ddf65dca569be5b21466b2f1f450ce650a4fbac",
|
||||
"sha256": "92e938a56a164681731a89957c16d62e6b86e85203f0d0ddcb920dcb9406c8c7",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"LUNA_BBSHD"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_b037176c63f44af2d112be7c46b651ef",
|
||||
"path": "5.02/STORMCORE_100D/VESC_default.bin",
|
||||
"git_blob": "ca67541c042126b58c875fb6fb7b5d19bfa1ee23",
|
||||
"sha256": "633cbeb6fa11bfefdc98ac1b6b2765fe080ec56a5272c8219b6e9422b6ee4f22",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"STORMCORE_100D"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_510bc5346a26ab5abe00598b9e3a7a15",
|
||||
"path": "5.02/STORMCORE_100D/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "d2cb084eb6e2f10b4e33ab826b4d84ff2cb1bcb6",
|
||||
"sha256": "66c19f693ac1018de5818fa7856629133ad4d389cab3366d202495c6ee4f352b",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"STORMCORE_100D"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_3fb8cbee44e0ef14e11558f272d2a5ad",
|
||||
"path": "5.02/STORMCORE_100S/VESC_default.bin",
|
||||
"git_blob": "06adfb19ab9981c327aee4d6a71ae46c27778c65",
|
||||
"sha256": "4167f6c34fa3c2267cee15f593b0b93d14fd7ae032049fb944e3f464c90b4434",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"STORMCORE_100S"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_af09ed784286b4c5fa82baa72d43881e",
|
||||
"path": "5.02/STORMCORE_100S/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "12d545cb0afe8a282948cfd7288658e9d65f8a79",
|
||||
"sha256": "afeada4f382a354a709bb7a2849bbab7bde8b8144479d2dcffabd870e8ba33e3",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"STORMCORE_100S"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_c327a275325fe87b693611099625e451",
|
||||
"path": "5.02/STORMCORE_60D/VESC_default.bin",
|
||||
"git_blob": "25907b4cfcabf5277701d933ef837e7c991540bd",
|
||||
"sha256": "3867b3f60ca650d8dd742d532b46f4475b347d6e623d9555a140e386caf2f453",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"STORMCORE_60D"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_652b83aefe9aa2f1a2fb5246164c8414",
|
||||
"path": "5.02/STORMCORE_60D/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "b2a220c858eeb5b401fc18642d9f3ca938a691f9",
|
||||
"sha256": "89945b83a12f3f91eeff2c42d115830bc9f30817d05c513b1f6cd99f1a1c786a",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"STORMCORE_60D"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
},
|
||||
{
|
||||
"id": "fwimg_cb2a8e9dc5d125f6b89db1da8edc7e2e",
|
||||
"path": "5.02/UAVC_OMEGA/VESC_default.bin",
|
||||
"git_blob": "cf9c8f8c8f951a02195f8405ab1fb287dc2b0bce",
|
||||
"sha256": "d014be805e06237cca9057aae6e5ace96546905d6a0256633675e4a1fb9e3b77",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"UAVC_OMEGA"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_21e86da15b810624c5c542ae425badd6",
|
||||
"path": "5.02/UNITY/VESC_default.bin",
|
||||
"git_blob": "ffe19f1f13bc6137aca8b78a5825b58ac43507a1",
|
||||
"sha256": "17042fd9fb0f6455ff886eccb03ec2dced6d408d7895849eaa45f3b5420350ee",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"UNITY"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": true
|
||||
},
|
||||
{
|
||||
"id": "fwimg_ce34a332bbe40e7ada15fdb5bb4e6109",
|
||||
"path": "5.02/UNITY/VESC_default_no_hw_limits.bin",
|
||||
"git_blob": "d08e9d3892837078a251f8752ce4859ac496a51e",
|
||||
"sha256": "3f6efc4ce7483c65d7005a25e7e503539c29ffbd09749616654aa9d78d6971aa",
|
||||
"bytes": 393208,
|
||||
"hardware": [
|
||||
"UNITY"
|
||||
],
|
||||
"version": "5.02",
|
||||
"name": "VESC_default_no_hw_limits.bin",
|
||||
"kind": "firmware",
|
||||
"hardware_limits": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -27,11 +27,14 @@ ProtectKernelTunables=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectControlGroups=yes
|
||||
RestrictSUIDSGID=yes
|
||||
RestrictAddressFamilies=AF_UNIX
|
||||
# Native Tool and bridge communicate on loopback inside this private network.
|
||||
RestrictAddressFamilies=AF_UNIX AF_INET
|
||||
DevicePolicy=closed
|
||||
DeviceAllow=char-ttyACM rw
|
||||
MemoryMax=512M
|
||||
MemoryMax=1G
|
||||
TasksMax=64
|
||||
LogRateLimitIntervalSec=30s
|
||||
LogRateLimitBurst=60
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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()
|
||||
@@ -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)
|
||||
|
||||
@@ -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)<width+1:break
|
||||
size=int.from_bytes(buffer[1:width+1],"big")
|
||||
end=width+1+size
|
||||
if len(buffer)<end+3:break
|
||||
payload=buffer[width+1:end]
|
||||
if buffer[end+2]!=3 or binascii.crc_hqx(payload,0)!=int.from_bytes(buffer[end:end+2],"big"):
|
||||
raise ValueError("Invalid CRC")
|
||||
buffer=buffer[end+3:];frames.append(payload.hex())
|
||||
if payload[0]==0:
|
||||
conn.sendall(framed(b"\x00\x05\x02SYNTHETIC\x00"+bytes([1])*12+b"\x00\x00\x00\x00"))
|
||||
elif payload[0] in configs:conn.sendall(framed(configs[payload[0]]))
|
||||
elif payload==b"\xffMCBR":conn.sendall(framed(payload))
|
||||
except Exception as e:errors.append(str(e))
|
||||
thread=threading.Thread(target=peer,daemon=True);thread.start()
|
||||
process=subprocess.Popen([sys.argv[1],"--can-bridge="+str(listener.getsockname()[1])],
|
||||
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
def receive():
|
||||
if not select.select([process.stdout],[],[],5)[0]:raise ValueError("Native reply timeout")
|
||||
line=process.stdout.readline()
|
||||
if not line:raise ValueError(process.stderr.read().decode())
|
||||
return json.loads(line)
|
||||
try:
|
||||
hello=receive()
|
||||
assert hello["ready"] and hello["engine"]["connected"] and hello["engine"]["firmware_admitted"],hello
|
||||
requests=[{"id":1,"method":"query","command":0,"timeout_ms":1000},
|
||||
{"id":2,"method":"lease"},{"id":3,"method":"rpm","erpm":500},
|
||||
{"id":4,"method":"release"}]
|
||||
for request in requests:
|
||||
process.stdin.write(json.dumps(request).encode()+b"\n");process.stdin.flush()
|
||||
response=receive()
|
||||
assert response["id"]==request["id"] and response["ok"],response
|
||||
def rpc(method,**parameters):
|
||||
process.stdin.write(json.dumps({"id":20,"method":method,**parameters}).encode()+b"\n");process.stdin.flush()
|
||||
return receive()
|
||||
configuration=rpc("configuration")
|
||||
assert configuration["ok"],configuration
|
||||
motor={p["name"]:p["value"] for p in configuration["result"]["motor"]["parameters"]}
|
||||
ceiling=max(motor["l_current_max"]*motor["l_current_max_scale"],-motor["l_current_min"]*motor["l_current_min_scale"])
|
||||
assert ceiling>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()
|
||||
@@ -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}))
|
||||
|
||||
|
||||
@@ -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':'<!DOCTYPE x [<!ENTITY z SYSTEM "file:///etc/passwd">]><CustomConfiguration><max_bal_ch>&z;</max_bal_ch></CustomConfiguration>'},1)]:
|
||||
run('custom-'+name,{'custom_schema':b64(schema),'custom_edit':source},expected)
|
||||
run('custom-schema-dtd',{'custom_schema':b64(b'<!DOCTYPE x [<!ENTITY z SYSTEM "file:///etc/passwd">]><ConfigParams>&z;</ConfigParams>')},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)
|
||||
@@ -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':''}
|
||||
@@ -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": "<MCConfiguration><unknown>1</unknown></MCConfiguration>"}, 1),
|
||||
("xml-metadata", {"xml": "<MCConfiguration><motor_brand>Changed</motor_brand></MCConfiguration>"}, 1),
|
||||
("xml-nan", {"xml": "<MCConfiguration><l_current_max>NaN</l_current_max></MCConfiguration>"}, 1),
|
||||
("xml-duplicate", {"xml": "<MCConfiguration><l_current_max>20</l_current_max><l_current_max>30</l_current_max></MCConfiguration>"}, 1),
|
||||
("xml-entity", {"xml": '<!DOCTYPE MCConfiguration [<!ENTITY x "20">]><MCConfiguration><l_current_max>&x;</l_current_max></MCConfiguration>'}, 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())
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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 0<len(p['data'])<=22000:raise ValueError('Invalid code fragment')
|
||||
raw=base64.b64decode(p['data'],validate=True)
|
||||
if not raw or len(raw)>16384 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 offset<len(upload['data']) and upload['data'][offset:offset+len(data)]==data:return {'offset':len(upload['data'])}
|
||||
if offset!=len(upload['data']) or offset+len(data)>upload['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}
|
||||
@@ -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 'Итог подтверждён повторным чтением. Управление включается отдельно.'}
|
||||
@@ -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)
|
||||
|
||||
@@ -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("Подключение или профиль изменился. Начните новый сеанс управления.")
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user