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,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}};
|
||||
}
|
||||
Reference in New Issue
Block a user