Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
171 lines
12 KiB
C++
171 lines
12 KiB
C++
// 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"
|