Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
644 lines
39 KiB
C++
644 lines
39 KiB
C++
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
// Private per-device JSON process adapter. Every wire operation is upstream.
|
|
#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>
|
|
#include <functional>
|
|
#include <fcntl.h>
|
|
#include <sys/file.h>
|
|
#include <sys/ioctl.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/sysmacros.h>
|
|
#include <termios.h>
|
|
#include <unistd.h>
|
|
|
|
class ExchangeFailure : public std::runtime_error {
|
|
public:
|
|
QJsonObject diagnostics;
|
|
explicit ExchangeFailure(const QJsonObject &value)
|
|
: std::runtime_error("Native query timed out or disconnected"), diagnostics(value) {}
|
|
};
|
|
|
|
class Engine {
|
|
public:
|
|
VescInterface vesc;
|
|
FirmwareUpload firmwareUpload;
|
|
NativeSamples samples;
|
|
bool firmwareQualified = false;
|
|
Packet *packet;
|
|
FW_RX_PARAMS identity;
|
|
bool procedureRunning = false;
|
|
bool procedureUncertain = false;
|
|
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 (...) {}
|
|
}
|
|
});
|
|
require(Utility::configLoadLatest(&vesc), "Upstream resources missing");
|
|
packet = vesc.findChild<Packet *>();
|
|
require(packet, "Upstream packet transport missing");
|
|
QObject::connect(vesc.commands(), &Commands::fwVersionReceived,
|
|
[&](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;
|
|
if (!raw.isEmpty() && quint8(raw[0]) == COMM_DETECT_HALL_FOC) lastHall = raw;
|
|
});
|
|
}
|
|
|
|
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;
|
|
require(lstat(port.toLocal8Bit(), &st) == 0 && S_ISCHR(st.st_mode) && major(st.st_rdev) == 166,
|
|
"Not a CDC ACM device");
|
|
require(vesc.connectSerial(port, 115200), "Native serial connection failed");
|
|
auto serial = vesc.findChild<QSerialPort *>();
|
|
require(serial && serial->isOpen() && "/dev/" + serial->portName() == port,
|
|
"Native serial path mismatch");
|
|
require(flock(serial->handle(), LOCK_EX | LOCK_NB) == 0 && ioctl(serial->handle(), TIOCEXCL) == 0,
|
|
"Serial port is already owned");
|
|
allowHardware = true;
|
|
query(COMM_FW_VERSION, 3000);
|
|
firmwareQualified = nativeFirmwareQualified(identity.major, identity.minor, identity.hwType, identity.isTestFw, identity.customConfigNum);
|
|
}
|
|
|
|
QByteArray exchange(int command, int timeoutMs, const std::function<void()> &send) {
|
|
require(allowHardware && vesc.isPortConnected(), "Device disconnected");
|
|
require(!queryRunning, "A native query is already pending");
|
|
queryRunning = true;
|
|
struct PendingReset { bool &pending; ~PendingReset() { pending = false; } } reset{queryRunning};
|
|
QEventLoop loop;
|
|
QTimer timeout; timeout.setSingleShot(true);
|
|
QObject observer;
|
|
QElapsedTimer elapsed; elapsed.start();
|
|
QJsonArray events;
|
|
bool emitted = false;
|
|
int packetsSent = 0, packetsReceived = 0;
|
|
qint64 bytesWritten = 0;
|
|
auto serial = vesc.findChild<QSerialPort *>();
|
|
auto record = [&](const QString &kind, int code, qint64 bytes) {
|
|
if (events.size() == 24) events.removeFirst();
|
|
events.append(QJsonObject{{"event", kind}, {"command", code},
|
|
{"bytes", double(bytes)}, {"at_ms", elapsed.nsecsElapsed() / 1e6}});
|
|
};
|
|
QObject::connect(vesc.commands(), &Commands::dataToSend, &observer, [&](QByteArray &raw) {
|
|
const int code = raw.isEmpty() ? -1 : quint8(raw[0]);
|
|
if (code == command) emitted = true;
|
|
record("command_emitted", code, raw.size());
|
|
});
|
|
QObject::connect(packet, &Packet::dataToSend, &observer, [&](QByteArray &raw) {
|
|
++packetsSent; record("packet_sent", -1, raw.size());
|
|
});
|
|
if (serial) {
|
|
QObject::connect(serial, &QSerialPort::bytesWritten, &observer, [&](qint64 bytes) {
|
|
bytesWritten += bytes; record("serial_written", -1, bytes);
|
|
});
|
|
QObject::connect(serial, &QSerialPort::errorOccurred, &observer, [&](QSerialPort::SerialPortError error) {
|
|
if (error != QSerialPort::NoError) record("serial_error", int(error), 0);
|
|
});
|
|
}
|
|
QByteArray answer;
|
|
QObject::connect(packet, &Packet::packetReceived, &observer, [&](QByteArray &raw) {
|
|
++packetsReceived;
|
|
record("packet_received", raw.isEmpty() ? -1 : quint8(raw[0]), raw.size());
|
|
if (!raw.isEmpty() && quint8(raw[0]) == command) { answer = raw; loop.quit(); }
|
|
});
|
|
QObject::connect(&timeout, &QTimer::timeout, &loop, &QEventLoop::quit);
|
|
timeout.start(timeoutMs);
|
|
send();
|
|
if (answer.isEmpty()) loop.exec();
|
|
if (answer.isEmpty() || !vesc.isPortConnected()) {
|
|
throw ExchangeFailure({{"requested_command", command}, {"timeout_ms", timeoutMs},
|
|
{"elapsed_ms", elapsed.nsecsElapsed() / 1e6}, {"request_emitted", emitted},
|
|
{"packets_sent", packetsSent}, {"packets_received", packetsReceived},
|
|
{"serial_bytes_written", double(bytesWritten)}, {"port_connected", vesc.isPortConnected()},
|
|
{"serial_open", serial && serial->isOpen()}, {"serial_error", serial ? int(serial->error()) : -1},
|
|
{"serial_bytes_pending", serial ? double(serial->bytesToWrite()) : -1}, {"events", events}});
|
|
}
|
|
return answer;
|
|
}
|
|
|
|
QByteArray query(int code, int timeoutMs, bool internal = false) {
|
|
auto cmd = vesc.commands();
|
|
require(internal || !procedureRunning || code == COMM_GET_VALUES || code == COMM_GET_DECODED_PPM,
|
|
"Configuration reads are unavailable during native measurement");
|
|
std::function<void()> send;
|
|
switch (code) {
|
|
case COMM_FW_VERSION: send = [=] { cmd->getFwVersion(); }; break;
|
|
case COMM_GET_VALUES: send = [=] { cmd->getValues(); }; break;
|
|
case COMM_GET_MCCONF: send = [=] { cmd->getMcconf(); }; break;
|
|
case COMM_GET_APPCONF: send = [=] { cmd->getAppConf(); }; break;
|
|
case COMM_GET_DECODED_PPM: send = [=] { cmd->getDecodedPpm(); }; break;
|
|
case COMM_PING_CAN: send = [=] { cmd->pingCan(); }; break;
|
|
default: throw std::runtime_error("Native read command is not admitted");
|
|
}
|
|
auto raw = exchange(code, timeoutMs, send);
|
|
if (code == COMM_GET_MCCONF || code == COMM_GET_APPCONF) {
|
|
VByteArray serialized;
|
|
auto config = code == COMM_GET_MCCONF ? vesc.mcConfig() : vesc.appConfig();
|
|
config->serialize(serialized);
|
|
require(serialized == raw.mid(1), "Native configuration decode is not byte-exact");
|
|
}
|
|
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;
|
|
}
|
|
|
|
void calibrate(double loss) {
|
|
ConfigParams beforeMotor, beforeApp;
|
|
beforeMotor = *vesc.mcConfig(); beforeApp = *vesc.appConfig();
|
|
bool received = false, validated = false;
|
|
int code = -1000;
|
|
QString report, error;
|
|
QJsonArray changed;
|
|
auto connection = QObject::connect(vesc.commands(), &Commands::detectAllFocReceived,
|
|
[&](int result) { received = true; code = result; });
|
|
try {
|
|
// The actual upstream wizard motor procedure, including its FW 5.02
|
|
// power-loss correction. Do not infer a battery profile from Ah/voltage.
|
|
report = Utility::detectAllFoc(&vesc, false, loss,
|
|
beforeMotor.getParamDouble("l_in_current_min"), beforeMotor.getParamDouble("l_in_current_max"),
|
|
beforeMotor.getParamDouble("foc_openloop_rpm"), beforeMotor.getParamDouble("foc_sl_erpm"));
|
|
require(received, "Native calibration completion was not received");
|
|
query(COMM_GET_MCCONF, 3000, true);
|
|
query(COMM_GET_APPCONF, 3000, true);
|
|
auto mc = vesc.mcConfig(); auto app = vesc.appConfig();
|
|
const QStringList admitted = {"l_current_max", "l_current_min", "motor_type", "foc_motor_r",
|
|
"foc_motor_l", "foc_motor_flux_linkage", "foc_current_kp", "foc_current_ki", "foc_observer_gain",
|
|
"foc_sensor_mode", "m_sensor_port_mode", "foc_encoder_offset", "foc_encoder_ratio", "foc_encoder_inverted",
|
|
"foc_hall_table__0", "foc_hall_table__1", "foc_hall_table__2", "foc_hall_table__3",
|
|
"foc_hall_table__4", "foc_hall_table__5", "foc_hall_table__6", "foc_hall_table__7"};
|
|
for (const auto &key : beforeMotor.checkDifference(mc)) {
|
|
require(admitted.contains(key), "Calibration changed a protected motor parameter");
|
|
changed.append(key);
|
|
}
|
|
for (const auto &key : beforeApp.checkDifference(app))
|
|
require(key == "send_can_status", "Calibration changed a protected receiver parameter");
|
|
// Native FW 5.02 enables CAN status as a side effect. Restore the
|
|
// original application exactly; retain existing PPM and CAN identity.
|
|
if (!beforeApp.checkDifference(app).isEmpty()) {
|
|
*app = beforeApp;
|
|
const auto expected = configurationPacket(app, COMM_GET_APPCONF);
|
|
require(exchange(COMM_SET_APPCONF, 3000, [&] { vesc.commands()->setAppConf(); }).size() == 1,
|
|
"Application write ACK invalid");
|
|
require(query(COMM_GET_APPCONF, 3000, true) == expected, "Application restore not byte-exact");
|
|
}
|
|
if (code < 0) {
|
|
// A completed failed detection can leave partial RAM changes.
|
|
// Only the known calibration fields passed the guard above.
|
|
*mc = beforeMotor;
|
|
} else {
|
|
for (const auto &key : {"foc_motor_r", "foc_motor_l", "foc_motor_flux_linkage"})
|
|
require(std::isfinite(mc->getParamDouble(key)) && mc->getParamDouble(key) > 0,
|
|
"Invalid detected motor parameter");
|
|
require(mc->getParamDouble("l_current_max") > 0 && mc->getParamDouble("l_current_min") < 0,
|
|
"Invalid detected current limits");
|
|
// Calibration must not silently increase the owner's existing
|
|
// current limits. The separate spin test applies its own 30 A cap.
|
|
mc->updateParamDouble("l_current_max", qMin(mc->getParamDouble("l_current_max"), beforeMotor.getParamDouble("l_current_max")));
|
|
mc->updateParamDouble("l_current_min", qMax(mc->getParamDouble("l_current_min"), beforeMotor.getParamDouble("l_current_min")));
|
|
}
|
|
const auto expected = configurationPacket(mc, COMM_GET_MCCONF);
|
|
if (expected != lastMotor) {
|
|
require(exchange(COMM_SET_MCCONF, 3000, [&] { vesc.commands()->setMcconf(false); }).size() == 1,
|
|
"Motor write ACK invalid");
|
|
require(query(COMM_GET_MCCONF, 3000, true) == expected, "Motor write not byte-exact");
|
|
}
|
|
validated = true;
|
|
} catch (const std::exception &e) { error = e.what(); }
|
|
QObject::disconnect(connection);
|
|
QJsonObject parameters;
|
|
for (const auto &key : {"l_current_max", "l_current_min", "foc_motor_r", "foc_motor_l", "foc_motor_flux_linkage"})
|
|
parameters.insert(key, vesc.mcConfig()->getParamDouble(key));
|
|
procedure = {{"kind", "foc"}, {"completed", received}, {"success", received && code >= 0 && validated},
|
|
{"validated", validated}, {"code", code}, {"report", report}, {"error", error},
|
|
{"sensor_mode", vesc.mcConfig()->getParamEnum("foc_sensor_mode")}, {"parameters", parameters},
|
|
{"changed", changed}, {"upstream", "Utility::detectAllFoc"}};
|
|
procedureUncertain = !validated;
|
|
procedureRunning = false;
|
|
}
|
|
|
|
double number(const QJsonObject &request, const QString &name, double min, double max) {
|
|
auto v = request.value(name);
|
|
require(v.isDouble() && std::isfinite(v.toDouble()) && v.toDouble() >= min && v.toDouble() <= max,
|
|
"Numeric argument is outside operation bounds");
|
|
return v.toDouble();
|
|
}
|
|
|
|
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();
|
|
if (serial->bytesToWrite() > 0) require(serial->waitForBytesWritten(40), "Serial write not confirmed");
|
|
require(serial->bytesToWrite() == 0, "Serial write is incomplete");
|
|
}
|
|
|
|
QJsonObject dispatch(const QJsonObject &request) {
|
|
const auto method = request.value("method").toString();
|
|
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()}};
|
|
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(); lastLease=controlClock.elapsed(); ++leaseCount; outputWatchdog.start(200); 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");
|
|
auto current = number(request, "current_a", 0, 30);
|
|
require(current <= vesc.mcConfig()->getParamDouble("l_current_max"), "Configured current limit exceeded");
|
|
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;
|
|
conf.current_min_scale = number(p, "l_current_min_scale", 0, 1);
|
|
conf.current_max_scale = number(p, "l_current_max_scale", 0, 1);
|
|
// Restore/application may only change current scales. All other
|
|
// values must equal the last native read, including battery limits.
|
|
auto mc = vesc.mcConfig();
|
|
for (const auto &key : {"l_min_erpm", "l_max_erpm", "l_min_duty", "l_max_duty", "l_watt_min", "l_watt_max", "l_in_current_min", "l_in_current_max"})
|
|
require(p.value(key).isDouble() && p.value(key).toDouble() == mc->getParamDouble(key), "Only volatile current scales may change");
|
|
conf.erpm_or_speed_min = mc->getParamDouble("l_min_erpm");
|
|
conf.erpm_or_speed_max = mc->getParamDouble("l_max_erpm");
|
|
conf.duty_min = mc->getParamDouble("l_min_duty"); conf.duty_max = mc->getParamDouble("l_max_duty");
|
|
conf.watt_min = mc->getParamDouble("l_watt_min"); conf.watt_max = mc->getParamDouble("l_watt_max");
|
|
auto ack = exchange(COMM_SET_MCCONF_TEMP, 2000, [&] {
|
|
vesc.commands()->setMcconfTemp(conf, false, false, false, false, true);
|
|
});
|
|
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");
|
|
for (const auto &key : {"l_in_current_min", "l_in_current_max", "foc_openloop_rpm", "foc_sl_erpm"})
|
|
require(std::isfinite(vesc.mcConfig()->getParamDouble(key)) && std::abs(vesc.mcConfig()->getParamDouble(key)) > 0.001,
|
|
"Zero-valued detection inputs require an explicit equipment profile");
|
|
procedureRunning = true; procedure = {{"kind", "foc"}};
|
|
QTimer::singleShot(0, [this, loss] { calibrate(loss); });
|
|
return {{"started", true}, {"interruptible", false}};
|
|
}
|
|
if (method == "hall_start") {
|
|
require(request.value("current_a") == 5, "This Hall profile uses 5 A");
|
|
procedureRunning = true; procedure = {}; lastHall.clear();
|
|
QTimer::singleShot(0, [&] {
|
|
auto measured = Utility::measureHallFocBlocking(&vesc, 5.0);
|
|
QJsonArray table;
|
|
for (int i = 1; i < measured.size(); ++i) table.append(measured[i]);
|
|
const bool completed = measured.size() == 9 && measured.first() != -10;
|
|
procedure = {{"kind", "hall"}, {"completed", completed},
|
|
{"status", measured.isEmpty() ? -10 : measured.first()}, {"table", table},
|
|
{"payload", QString::fromLatin1(lastHall.toBase64())},
|
|
{"upstream", "Utility::measureHallFocBlocking"}};
|
|
procedureUncertain = !completed;
|
|
procedureRunning = false;
|
|
});
|
|
return {{"started", true}, {"interruptible", false}};
|
|
}
|
|
throw std::runtime_error("Native operation is not admitted");
|
|
}
|
|
};
|
|
|
|
int main(int argc, char **argv) {
|
|
qputenv("QT_QPA_PLATFORM", "offscreen");
|
|
QApplication application(argc, argv);
|
|
QCoreApplication::setOrganizationName("MissionCore");
|
|
QCoreApplication::setApplicationName("VescToolEngine");
|
|
try {
|
|
require(argc == 2, "One exact serial port or --offline argument is required");
|
|
Engine engine;
|
|
const QString port = QString::fromLocal8Bit(argv[1]);
|
|
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();
|
|
};
|
|
write({{"ready", true}, {"engine", engine.dispatch({{"method", "engine"}})}});
|
|
QByteArray buffer;
|
|
fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK);
|
|
QSocketNotifier input(STDIN_FILENO, QSocketNotifier::Read);
|
|
QObject::connect(&input, &QSocketNotifier::activated, [&] {
|
|
char chunk[4096]; const auto size = ::read(STDIN_FILENO, chunk, sizeof(chunk));
|
|
if (size == 0) { application.quit(); return; }
|
|
if (size < 0) return;
|
|
buffer.append(chunk, int(size));
|
|
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);
|
|
QJsonParseError error;
|
|
auto document = QJsonDocument::fromJson(raw, &error);
|
|
auto request = document.object();
|
|
QJsonObject response{{"id", request.value("id")}};
|
|
try {
|
|
require(error.error == QJsonParseError::NoError && document.isObject(), "Invalid JSON request");
|
|
response.insert("result", engine.dispatch(request)); response.insert("ok", true);
|
|
} catch (const ExchangeFailure &e) {
|
|
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);
|
|
}
|
|
});
|
|
return application.exec();
|
|
} catch (const std::exception &error) {
|
|
fprintf(stderr, "Native engine startup failed: %s\n", error.what());
|
|
return 1;
|
|
}
|
|
}
|