// 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_edit.h" #include "firmware_source.h" #include "bms_native.h" #include "swd_native.h" #include "code_native.h" #include "package_native.h" #include "engine_profile.h" #include "sample_data.h" #include "qml_broker.h" #include int main(int argc, char **argv) { // This application never calls connectSerial/connectTcp/connectBle or starts // a Qt event loop. Upstream timers therefore cannot reconnect or poll. qputenv("QT_QPA_PLATFORM", "offscreen"); QApplication app(argc, argv); QCoreApplication::setOrganizationName("MissionCore"); QCoreApplication::setApplicationName("VescToolOfflineAdapter"); QJsonObject result{{"schema", "missioncore.vesc.native-offline/v1"}, {"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"); 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); require(parse.error == QJsonParseError::NoError && document.isObject(), "Invalid archive JSON"); const auto archive = document.object(); const auto identity = archive.value("identity").toObject(); FW_RX_PARAMS fw; fw.major = identity.value("major").toInt(-1); fw.minor = identity.value("minor").toInt(-1); fw.hw = identity.value("hardware").toString(); fw.isTestFw = identity.value("test_firmware").toInt(-1); fw.customConfigNum = identity.value("custom_configs").toInt(-1); 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(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; QObject::connect(commands, &Commands::deserializeConfigFailed, [&](bool, bool) { failed = true; }); auto motor = archivePacket(archive, "motor", COMM_GET_MCCONF); auto application = archivePacket(archive, "application", COMM_GET_APPCONF); // FW 5.02 has fixed-size configurations. Obtain their size through the // public native serializer; do not reproduce the private schema walker. VByteArray motorShape, applicationShape; vesc.mcConfig()->serialize(motorShape); vesc.appConfig()->serialize(applicationShape); require(motor.size() == motorShape.size() + 1 && application.size() == applicationShape.size() + 1, "Archive length differs from the native firmware schema"); commands->processPacket(motor); commands->processPacket(application); require(!failed, "Upstream rejected archived configuration"); result.insert("motor", exportConfig(vesc.mcConfig(), motor, "MCConfiguration")); result.insert("application", exportConfig(vesc.appConfig(), application, "APPConfiguration")); // A disconnected serializer-only probe demonstrates that FW-specific // detect corrections execute upstream. This byte array goes nowhere. QByteArray encodedDetect; QObject::connect(commands, &Commands::dataToSend, [&](QByteArray &data) { if (!data.isEmpty() && quint8(data.at(0)) == COMM_DETECT_APPLY_ALL_FOC) encodedDetect = data; }); commands->detectAllFoc(false, 100.0, 0.0, 0.0, 0.0, 0.0); require(!encodedDetect.isEmpty() && !vesc.isPortConnected(), "Offline serialization failed"); result.insert("compatibility", QJsonObject{ {"legacy_power_loss_correction", commands->getMaxPowerLossBug()}, {"offline_detect_example_base64", QString::fromLatin1(encodedDetect.toBase64())}, {"example_requested_power_loss_w", 100.0}, {"transmitted_to_hardware", false}}); QJsonArray rpmExamples; QObject::connect(commands, &Commands::dataToSend, [&](QByteArray &data) { if (!data.isEmpty() && quint8(data.at(0)) == COMM_SET_RPM) rpmExamples.append(QString::fromLatin1(data.toBase64())); }); commands->setRpm(3000); 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) { result = QJsonObject{{"schema", "missioncore.vesc.native-offline/v1"}, {"ok", false}, {"hardware_access", false}, {"error", error.what()}}; } QFile output; output.open(stdout, QIODevice::WriteOnly); output.write(QJsonDocument(result).toJson(QJsonDocument::Compact) + '\n'); return result.value("ok").toBool() ? 0 : 1; }