CmvrControlStation/tests/application_shell_test.cpp

776 lines
46 KiB
C++

#include "mainwindow.h"
#include "applicationstyle.h"
#include "urdfviewerwidget.h"
#include "taskorchestrationwidget.h"
#include "bioheadoperations.h"
#include "bioheadwidget.h"
#include "robotclient.h"
#include "motordebugwidget.h"
#include "motorplot.h"
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QAbstractItemView>
#include <QDialog>
#include <QMessageBox>
#include <QPushButton>
#include <QTimer>
#include <QDebug>
#include <QFile>
#include <QLabel>
#include <QTextStream>
#include <QTreeWidget>
#include <QListWidget>
#include <QEventLoop>
#include <QTabWidget>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QGraphicsView>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QScrollArea>
#include <QScrollBar>
#include <QTableWidget>
#include <QLineEdit>
#include <QJsonDocument>
#include <QElapsedTimer>
#include <QDoubleSpinBox>
#include <QSignalBlocker>
#include <QFileInfo>
#include <QDir>
#include <thread>
#include <atomic>
#include <cmath>
#include <QSpinBox>
#ifdef CMVR_WITH_GRPC
#include <grpcpp/grpcpp.h>
#include "cmvr/api/arm_service.grpc.pb.h"
#include "cmvr/api/motor_service.grpc.pb.h"
#endif
static bool waitFor(const std::function<bool()> &ready, int timeout=4000)
{
QElapsedTimer timer; timer.start();
while (!ready() && timer.elapsed()<timeout) {
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return ready();
}
struct MotorDebugTestAccess {
static bool verify(){
RobotClient c;QObject::disconnect(&c,&RobotClient::motorRpcRequested,nullptr,nullptr);
MotorDebugWidget w(&c);w.resize(1450,1060);w.show();
quint64 token=0;QString method;QVariantMap parameters;int requests=0;
QObject::connect(&c,&RobotClient::motorRpcRequested,&w,[&](const QString &m,const QString&,int node,const QVariantMap& p,quint64 t){
method=m;token=t;parameters=p;++requests;if(node!=0)qFatal("unexpected node");
});
c.connectionChanged(true,1,"mock");c.systemStatusReceived(0,0,0,{QVariantMap{{"deviceId","test_manager"},{"type",10}}});
if(method!="ListMotors")return false;
const QVariantMap motor{{"nodeId",0},{"jointName","test_J0"},{"driver","TchlMotor"},{"limitQLb",-1.0},{"limitQUb",1.0},{"limitQd",1.0},{"limitQdd",2.0}};
c.motorRpcFinished(token,"ListMotors",true,{{"motors",QVariantList{motor}}},"");
if(w.m_info->text().contains("test_J0")||w.m_info->text().contains("TchlMotor")||w.m_info->text().contains("ID"))return false;
for(const auto &caption:QStringList{QStringLiteral("位置下限"),QStringLiteral("位置上限"),QStringLiteral("速度上限"),QStringLiteral("加速度上限"),QStringLiteral("服务端缓存")})
if(!w.m_info->text().contains(caption))return false;
if(w.m_rpcButtons.size()!=17||w.findChild<QCheckBox*>("motorDebugUnlock"))return false;
if(w.m_rate->maximum()<=1000||w.m_timer->timerType()!=Qt::PreciseTimer)return false;
w.m_rate->setValue(200);if(w.m_timer->interval()!=5)return false;
w.m_rate->setValue(1000);if(w.m_timer->interval()!=1)return false;
w.m_rate->setValue(20);
for(auto *label:w.findChildren<QLabel*>())if(label->text()==QStringLiteral("运动指令"))return false;
const QStringList names={QStringLiteral("轮廓位置"),QStringLiteral("轮廓速度"),QStringLiteral("轮廓力矩"),QStringLiteral("周期位置"),QStringLiteral("周期速度"),QStringLiteral("周期力矩")};
const QList<int> modes={1,3,4,8,9,10};
const QStringList methods={"commandProfilePosition","commandProfileVelocity","commandProfileTorque","commandCyclicPosition","commandCyclicVelocity","commandCyclicTorque"};
const QList<QStringList> fields={QStringList{"q","qd","qdd"},QStringList{"qd","qdd"},QStringList{"tau"},
QStringList{"q","qd"},QStringList{"qd"},QStringList{"tau"}};
if(w.m_mode->count()!=6||w.m_limitParameters.size()!=5)return false;
w.m_parameters["q"]->setValue(2.5);w.m_parameters["qd"]->setValue(-0.2);w.m_parameters["qdd"]->setValue(0.4);
w.m_parameters["tau"]->setValue(12.5);w.m_slope->setValue(150);
for(int i=0;i<modes.size();++i){
const int before=requests;
if(w.m_mode->itemText(i)!=names[i]||w.m_mode->itemData(i).toInt()!=modes[i])return false;
w.m_mode->setCurrentIndex(i);
if(requests!=before)return false; // Choosing a mode must not issue control RPCs.
for(auto it=w.m_parameters.begin();it!=w.m_parameters.end();++it)
if(it.value()->isHidden()==fields[i].contains(it.key())||w.m_parameterLabels[it.key()]->isHidden()==fields[i].contains(it.key())||w.m_parameterRows[it.key()]->isHidden()==fields[i].contains(it.key()))return false;
if(w.m_slope->isHidden()!=(modes[i]!=4)||w.m_slopeLabel->isHidden()!=(modes[i]!=4))return false;
w.m_rpcButtons["setMode"]->click();
if(method!="setMode"||requests!=before+1||parameters!=QVariantMap{{"mode",modes[i]}})return false;
c.motorRpcFinished(token,method,true,{},"mode set");
w.m_sendMotion->click();
if(method!=methods[i]||requests!=before+2||QApplication::activeModalWidget())return false;
QVariantMap expected{{"mode",modes[i]}};
for(const auto &field:fields[i])expected.insert(field,w.m_parameters[field]->value());
if(modes[i]==4)expected.insert("torqueSlope",150);
if(parameters!=expected)return false;
c.motorRpcFinished(token,method,true,{},"mock result");
QApplication::processEvents();
if(i==0||i==2||i==3)w.grab().save(QString("motor-mode-%1.png").arg(modes[i]));
}
for(auto *input:w.findChildren<QAbstractSpinBox*>()){
if(input->buttonSymbols()!=QAbstractSpinBox::NoButtons)return false;
input->setFocus();const QString original=input->text();
QWheelEvent wheel(QPointF(5,5),QPointF(input->mapToGlobal(QPoint(5,5))),QPoint(),QPoint(0,120),Qt::NoButton,Qt::NoModifier,Qt::NoScrollPhase,false);
QApplication::sendEvent(input,&wheel);
if(input->text()!=original)return false;
}
w.m_parameters["q"]->findChild<QLineEdit*>()->setText("0.125");w.m_parameters["q"]->interpretText();
if(w.m_parameters["q"]->value()!=0.125)return false;
w.m_parameters["q"]->setValue(2.5);
w.m_limitParameters["qLower"]->setValue(-2);w.m_limitParameters["qUpper"]->setValue(3);
w.m_limitParameters["qd"]->setValue(4);w.m_limitParameters["qddLower"]->setValue(-5);w.m_limitParameters["qddUpper"]->setValue(6);
for(const QString &rpc:QStringList{"setLimitQ","setLimitQd","setLimitQdd"}){
w.m_rpcButtons[rpc]->click();
const QVariantMap expected=rpc=="setLimitQ"?QVariantMap{{"mode",10},{"lower",-2.0},{"upper",3.0}}:
rpc=="setLimitQd"?QVariantMap{{"mode",10},{"qd",4.0}}:QVariantMap{{"mode",10},{"lower",-5.0},{"upper",6.0}};
if(method!=rpc||parameters!=expected)return false;
c.motorRpcFinished(token,rpc,true,{},"mock result");
}
for(const QString &rpc:w.m_rpcButtons.keys()){
const int before=requests;w.m_rpcButtons[rpc]->click();
if(requests!=before+1||method!=rpc||QApplication::activeModalWidget()||parameters.contains("planMotion")||parameters.contains("confirmDebug"))return false;
if(rpc=="ListMotors")c.motorRpcFinished(token,rpc,true,{{"motors",QVariantList{motor}}},"");
else c.motorRpcFinished(token,rpc,true,{{"info",motor}},"mock result");
}
w.invoke("GetState");const quint64 oldRead=token;const int before=requests;
w.m_rpcButtons["torqueOn"]->click();if(method!="torqueOn"||requests!=before+1)return false;
c.motorRpcFinished(oldRead,"GetState",true,{},"stale");if(!w.m_inFlight)return false;
c.motorRpcFinished(token,"torqueOn",false,{},"server error");
if(!w.m_rpcButtons["setMode"]->isEnabled())return false;
struct Changes:QObject{int count=0;bool eventFilter(QObject*,QEvent*e)override{if(e->type()==QEvent::EnabledChange)++count;return false;}} changes;
const QList<QWidget*> controls={w.m_manager,w.m_motor,w.m_mode,w.m_parameters["q"],w.m_rpcButtons["torqueOn"],w.m_sendMotion};
for(auto *control:controls)control->installEventFilter(&changes);
w.clearSamples();
for(int i=0;i<120;++i){
w.invoke("GetState");const QVariantMap state{{"sampledAtS",1000.0+i*0.05},{"feedbackValid",true},{"torqueValid",true},
{"position",0.2*std::sin(i*0.1)},{"velocity",i*0.05},{"torque",20.0*std::sin(i*0.1)},{"mode",3},{"statusValid",true},{"enabled",false},{"statusWord",0x40}};
c.motorRpcFinished(token,"GetState",true,{{"state",state}},"");
if(i<2&&std::isfinite(w.accelerationEstimate()))return false;
}
if(changes.count||std::abs(w.accelerationEstimate()-1)>1e-6)return false;
for(auto *control:controls)control->removeEventFilter(&changes);
w.m_plot->setWindow(5);
QApplication::processEvents();
// Each plot zooms independently in both axes and restores with right click.
for(int channel=0;channel<4;++channel){
const auto old=w.m_plot->rangeFor(channel);const QPointF p=w.m_plot->plotRect(channel).center();
QWheelEvent wheel(p,QPointF(w.m_plot->mapToGlobal(p.toPoint())),QPoint(),QPoint(0,120),Qt::NoButton,Qt::NoModifier,Qt::NoScrollPhase,false);
QApplication::sendEvent(w.m_plot,&wheel);
const auto zoom=w.m_plot->rangeFor(channel);
if(!w.m_plot->m_views[channel].manual||zoom.right-zoom.left>=old.right-old.left||zoom.top-zoom.bottom>=old.top-old.bottom)return false;
for(int other=channel+1;other<4;++other)if(w.m_plot->m_views[other].manual)return false;
}
for(int channel=0;channel<4;++channel){
const auto p=w.m_plot->plotRect(channel).center();
QMouseEvent click(QEvent::MouseButtonPress,p,Qt::RightButton,Qt::RightButton,Qt::NoModifier);
QApplication::sendEvent(w.m_plot,&click);
if(w.m_plot->m_views[channel].manual)return false;
for(int other=channel+1;other<4;++other)if(!w.m_plot->m_views[other].manual)return false;
}
w.m_mode->setCurrentIndex(1);
for(int channel=0;channel<4;++channel){
const int expected=100;const auto range=w.m_plot->rangeFor(channel);const auto rect=w.m_plot->plotRect(channel);
const QPointF p(rect.left()+(w.m_plot->samples[expected].t-w.m_plot->samples.last().t-range.left)/(range.right-range.left)*rect.width(),rect.center().y());
QMouseEvent move(QEvent::MouseMove,p,Qt::NoButton,Qt::NoButton,Qt::NoModifier);
QApplication::sendEvent(w.m_plot,&move);
int index=-1;QPointF point;
if(!w.m_plot->hoverSample(index,point)||index!=expected||!std::isfinite(MotorPlot::value(w.m_plot->samples[index],channel)))return false;
}
QApplication::processEvents();w.grab().save("motor-debug-interactive.png");
auto *scroll=w.findChild<QScrollArea*>("motorControlScroll");
scroll->verticalScrollBar()->setValue(scroll->verticalScrollBar()->maximum());
QApplication::processEvents();w.grab().save("motor-limits-panel.png");
if(w.m_limitParameters["qLower"]->parentWidget()==w.m_parameters["q"]->parentWidget())return false;
// Window fitting reduces jitter without assuming the requested polling rate.
MotorPlot fit;
double time=0,oldVelocity=0,oldTime=0,fitError=0,rawError=0;
int compared=0;
for(int i=0;i<120;++i){
time+=0.035+0.005*(i%3);
const double velocity=2*time+(i%2?0.006:-0.006);
fit.append({{"sampledAtS",time},{"feedbackValid",true},{"position",time*time},{"velocity",velocity}});
if(i>10){
const double raw=(velocity-oldVelocity)/(time-oldTime);
fitError+=std::pow(fit.samples.last().qdd-2,2);rawError+=std::pow(raw-2,2);++compared;
}
oldTime=time;oldVelocity=velocity;
}
if(!compared||!std::isfinite(fitError)||fitError>=rawError*0.5)return false;
const int count=fit.samples.size();
fit.append({{"sampledAtS",time},{"feedbackValid",true},{"velocity",1e9}});
if(fit.samples.size()!=count)return false;
time+=0.04;fit.append({{"sampledAtS",time},{"feedbackValid",false}});
time+=0.04;fit.append({{"sampledAtS",time},{"feedbackValid",true},{"velocity",1.0}});
if(std::isfinite(fit.samples.last().qdd))return false;
time+=2;fit.append({{"sampledAtS",time},{"feedbackValid",true},{"velocity",100.0}});
if(std::isfinite(fit.samples.last().qdd))return false;
fit.append({{"sampledAtS",1.0},{"feedbackValid",true},{"velocity",0.0}});
if(fit.samples.size()!=1||std::isfinite(fit.samples.last().qdd))return false;
fit.clear();
for(int i=0;i<8;++i)fit.append({{"sampledAtS",100.0+i*1.01},{"feedbackValid",true},{"velocity",i*2.02}});
if(!std::isfinite(fit.samples.last().qdd)||std::abs(fit.samples.last().qdd-2)>1e-6)return false;
// Continuous valid high-rate feedback must not create artificial gaps.
for(double rate:{100.0,200.0,300.0,400.0,1000.0}){
fit.clear();double actualTime=1000;
for(int i=0;i<1000;++i){
actualTime+=1.0/rate;
fit.append({{"sampledAtS",actualTime},{"feedbackValid",true},{"velocity",2*(actualTime-1000)}});
if(actualTime-1000>0.05&&(!std::isfinite(fit.samples.last().qdd)||std::abs(fit.samples.last().qdd-2)>1e-6))return false;
}
}
fit.clear();double actualTime=1000;
const double burstIntervals[]={0.001,0.002,0.002,0.002,0.002,0.012,0.001,0.001,0.002,0.002};
for(int i=0;i<1000;++i){
actualTime+=burstIntervals[i%10];
fit.append({{"sampledAtS",actualTime},{"feedbackValid",true},{"velocity",2*(actualTime-1000)}});
if(actualTime-1000>0.05&&(!std::isfinite(fit.samples.last().qdd)||std::abs(fit.samples.last().qdd-2)>1e-6))return false;
}
const QString feedback=w.m_values->text();w.m_acquire->setChecked(true);w.invoke("setMode");
c.motorRpcFinished(token,"setMode",false,{},"driver rejected mode");
if(!w.m_acquire->isChecked()||w.m_values->text()!=feedback)return false;
w.invoke("GetState");c.motorRpcFinished(token,"GetState",true,{{"state",QVariantMap{{"sampledAtS",1010.0},{"feedbackValid",false}}}},"");
if(std::isfinite(w.accelerationEstimate()))return false;
const int beforeHide=requests;w.hide();if(w.m_acquire->isChecked()||requests!=beforeHide)return false;
QFile f("motor-debug-ui-test.txt");f.open(QIODevice::WriteOnly);
f.write("PASS: six modes and visible parameters, 23 direct APIs, independent limits, keyboard-only numeric inputs, stable sampling, hover values, independent zoom/reset, timestamp-based acceleration fitting and gap handling\n");
return true;
}
};
struct JointPointTestAccess {
static bool verify() {
int legacyCount=0;
const QDir testDir=QFileInfo(QString::fromUtf8(__FILE__)).absoluteDir();
for (const QString &relative : {QStringLiteral("../resources/joint_programs.json"),
QStringLiteral("../bin/release/joint_programs.json")}) {
QFile old(testDir.filePath(relative));
if (!old.exists()) continue;
if (!old.open(QIODevice::ReadOnly)) return false;
const auto root=QJsonDocument::fromJson(old.readAll()).object();
for (const auto &group : root.value("groups").toArray())
for (const auto &value : group.toObject().value("points").toArray()) {
const auto p=RecordedJointPoint::fromJson(value.toObject());
if (!p.valid() || p.toJson()!=value.toObject()) return false;
++legacyCount;
}
}
if (!legacyCount) return false;
RecordedJointPoint right;
right.name="saved right"; right.deviceId="right"; right.jointNames=QStringList{"right_J1"}; right.positions={-1.249};
RecordedJointPoint left;
left.name="left"; left.deviceId="left"; left.jointNames=QStringList{"left_J1"}; left.positions={0.3};
RecordedJointPoint both; both.name="both"; both.arms={right,left};
if (!both.valid() || RecordedJointPoint::fromJson(both.toJson()).toJson()!=both.toJson()) return false;
auto bad=both; bad.arms.append(right); if (bad.valid()) return false;
bad=both; bad.arms[0].positions[0]=qQNaN(); if (bad.valid()) return false;
MainWindow w;
QObject::disconnect(w.m_client,&RobotClient::jointPointMoveRequested,nullptr,nullptr);
QObject::disconnect(w.m_client,&RobotClient::armStopRequested,nullptr,nullptr);
w.m_jointProgramGroups.clear(); w.m_activeJointProgramGroup=0;
MainWindow::JointProgramGroup g; g.name="test"; w.m_jointProgramGroups.append(g);
w.m_recordedJointPoints={right,left}; w.refreshRecordedJointPoints();
w.m_jointPointNameEdit->setText("both");
w.m_jointPointTable->selectAll(); w.combineSelectedJointPoints();
if (w.m_recordedJointPoints.size()!=3 || w.m_recordedJointPoints[0].toJson()!=right.toJson()
|| w.m_recordedJointPoints[2].targets().size()!=2) return false;
int requests=0; quint64 token=0;
QObject::connect(w.m_client,&RobotClient::jointPointMoveRequested,&w,
[&](const QVariantList &targets,double,double,quint64 t) { ++requests; token=t;
if (targets.size()!=2) requests=-100; });
w.dispatchJointPoint(2);
if (requests!=1 || !w.m_jointPointMovePending) return false;
w.finishJointPoint(token-1,true,"stale"); if (!w.m_jointPointMovePending) return false;
QStringList stops;
QObject::connect(w.m_client,&RobotClient::armStopRequested,&w,[&](const QString &id) { stops.append(id); });
w.stopJointPointMotion(); w.stopJointPointLoop("test stop");
if (stops.size()!=2 || !stops.contains("right") || !stops.contains("left")) return false;
w.finishJointPoint(token,true,"late"); if (w.m_jointPointMovePending) return false;
QFile saved(QCoreApplication::applicationDirPath()+"/joint_programs.json");
if (!saved.open(QIODevice::ReadOnly)) return false;
const auto points=QJsonDocument::fromJson(saved.readAll()).object().value("groups").toArray()[0].toObject().value("points").toArray();
if (points.size()!=3 || points[0].toObject()!=right.toJson()) return false;
// Only the aggregate reply advances the flow; manual MoveJ cannot do so.
w.m_jointPointLoopRows={2,2}; w.m_jointPointExecutionWaits={0.02,0.0};
w.m_jointPointLoopCursor=0; w.m_jointPointLoopActive=true;
w.advanceJointPointLoop();
if (requests!=2) return false;
w.handleCommand("MoveJ",true,"unrelated reply");
QCoreApplication::processEvents();
if (requests!=2 || !w.m_jointPointMovePending) return false;
w.finishJointPoint(token,true,"both finished");
if (requests!=2 || !waitFor([&] { return requests==3; })) return false;
w.finishJointPoint(token,false,"failure");
if (w.m_jointPointLoopActive || w.m_jointPointMovePending) return false;
{
const QSignalBlocker block(w.m_armSideCombo), blockEdit(w.m_armIdEdit);
w.m_armSideCombo->clear(); w.m_armSideCombo->addItem("Right arm","right");
w.m_armSideCombo->addItem("Left arm","left"); w.m_armIdEdit->setText("right");
}
w.m_jointPointNameEdit->setText("capture selection");
bool dialogChecked=false;
QTimer::singleShot(0,&w,[&] {
auto *dialog=qobject_cast<QDialog *>(QApplication::activeModalWidget());
auto *list=dialog ? dialog->findChild<QListWidget *>() : nullptr;
dialogChecked=list && list->count()==2 && list->item(0)->checkState()==Qt::Checked
&& list->item(1)->checkState()==Qt::Unchecked && dialog->property("applicationChrome").toBool();
if (dialog) { dialog->grab().save("joint-point-capture-dialog.png"); dialog->reject(); }
});
w.recordCurrentJointPoint();
if (!dialogChecked) return false;
qInfo()<<"PASS legacy point round-trip, composite creation, stale replies and group stop";
return true;
}
};
#ifdef CMVR_WITH_GRPC
class MockDebugMotorService final : public cmvr::api::MotorService::Service {
public:
std::atomic<int> torqueWrites{0};
grpc::Status ListMotors(grpc::ServerContext*,const cmvr::api::MotorRequest* r,cmvr::api::MotorListResponse* s) override {
s->mutable_header()->set_success(true);auto *i=s->add_motors();i->set_manager_id(r->header().device_id());i->set_node_id(0);i->set_joint_name("test_J0");return grpc::Status::OK;
}
grpc::Status GetState(grpc::ServerContext*,const cmvr::api::MotorRequest*,cmvr::api::MotorResponse* s) override {
s->mutable_header()->set_success(true);s->mutable_state()->set_position(0.25);s->mutable_state()->set_velocity(-0.1);
s->mutable_state()->set_torque(35);s->mutable_state()->set_feedback_valid(true);s->mutable_state()->set_torque_valid(true);
s->mutable_state()->set_torque_unit("per_mille_rated");return grpc::Status::OK;
}
grpc::Status commandProfileTorque(grpc::ServerContext*,const cmvr::api::MotorRequest* r,cmvr::api::MotorResponse* s) override {
const bool ok=r->tau()==12.5&&r->torque_slope()==100;
s->mutable_header()->set_success(ok);if(ok)++torqueWrites;return grpc::Status::OK;
}
grpc::Status commandCyclicPosition(grpc::ServerContext*,const cmvr::api::MotorRequest* r,cmvr::api::MotorResponse* s) override {
s->mutable_header()->set_success(r->q()==0.3&&r->qd()==-0.2);return grpc::Status::OK;
}
};
class MockPointArm final : public cmvr::api::ArmService::Service {
public:
std::atomic<int> active{0}, peak{0}, moves{0}, stops{0};
std::atomic<bool> failRight{false};
grpc::Status GetArmInfo(grpc::ServerContext *,const cmvr::api::GetArmInfo::Request *r,
cmvr::api::GetArmInfo::Response *s) override {
s->mutable_header()->set_success(true);
s->add_joint_names(r->header().device_id()+"_J1"); return grpc::Status::OK;
}
grpc::Status getJointState(grpc::ServerContext *,const cmvr::api::JointRequest *r,
cmvr::api::JointResponse *s) override {
s->mutable_header()->set_success(true); s->mutable_state()->add_name(r->header().device_id()+"_J1");
s->mutable_state()->add_position(0.25); return grpc::Status::OK;
}
grpc::Status moveJ(grpc::ServerContext *c,const cmvr::api::MoveJ::Request *r,
cmvr::api::MoveJ::Response *s) override {
++moves; const int n=++active;
int old=peak.load(); while (old<n && !peak.compare_exchange_weak(old,n)) {}
const bool right=r->header().device_id()=="right";
const int delay=right && failRight ? 25 : (right?180:60);
for (int ms=0;ms<delay && !c->IsCancelled();ms+=5)
std::this_thread::sleep_for(std::chrono::milliseconds(5));
--active;
s->mutable_header()->set_success(!c->IsCancelled() && !(right && failRight));
s->mutable_header()->set_error_message("mock failure"); return grpc::Status::OK;
}
grpc::Status stopMotion(grpc::ServerContext *,const cmvr::api::CommandHeader::Request *,
cmvr::api::CommandHeader::Feedback *s) override {
++stops; s->set_success(true); return grpc::Status::OK;
}
};
static bool verifyPointRpc()
{
QFile report("joint-point-rpc-test.txt"); report.open(QIODevice::WriteOnly|QIODevice::Text);
QTextStream out(&report);
out.setCodec("UTF-8");
MockPointArm mock;
MockDebugMotorService motorMock;
grpc::ServerBuilder b; int port=0;
b.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);
b.RegisterService(&mock);b.RegisterService(&motorMock); auto server=b.BuildAndStart(); if (!server) return false;
bool result=true;
auto check=[&](bool ok,const QString &stage) { out<<(ok?"PASS ":"FAIL ")<<stage<<"\n"; out.flush(); result &= ok; };
{
RobotClient c; bool connected=false,done=false,success=false; quint64 last=0;
QObject::connect(&c,&RobotClient::connectionChanged,&c,[&](bool ok,int,const QString &) { connected=ok; });
QObject::connect(&c,&RobotClient::jointPointMoveFinished,&c,[&](quint64 t,bool ok,const QString &detail) {
done=true; success=ok; last=t;
out<<"reply "<<t<<" "<<ok<<" "<<detail<<"\n"; out.flush();
});
c.connectToServer("127.0.0.1",port,false);
const bool hasConnection=waitFor([&] { return connected; });
check(hasConnection,"connect");
if (hasConnection) {
RecordedJointPoint p; p.name="test";
JointPointTarget a; a.deviceId="left"; a.jointNames=QStringList{"left_J1"}; a.positions={0.1};
JointPointTarget d; d.deviceId="right"; d.jointNames=QStringList{"right_J1"}; d.positions={0.2};
p.arms={a,d};
int heartbeats=0; QTimer timer; timer.setInterval(10);
QObject::connect(&timer,&QTimer::timeout,&c,[&] { ++heartbeats; }); timer.start();
c.requestJointPointMove(p.commandTargets(),0.1,0.1,101);
check(waitFor([&] { return done; }) && success && last==101
&& mock.peak>=2 && mock.active==0 && heartbeats>=5,"concurrent move and responsive UI");
done=false; const int moves=mock.moves;
auto invalid=p; invalid.arms[1].jointNames=QStringList{"wrong"};
c.requestJointPointMove(invalid.commandTargets(),0.1,0.1,102);
check(waitFor([&] { return done; }) && !success && mock.moves==moves,"preflight blocks all motion");
done=false; mock.failRight=true;
c.requestJointPointMove(p.commandTargets(),0.1,0.1,103);
check(waitFor([&] { return done; }) && !success && last==103
&& waitFor([&] { return mock.active==0 && mock.stops>=2; }),"failure stops both arms");
done=false; mock.failRight=false; const int stops=mock.stops;
c.requestJointPointMove(p.commandTargets(),0.1,0.1,104);
check(waitFor([&] { return mock.active>=2; }),"cancel during concurrent moves");
c.requestArmStop("left");
check(waitFor([&] { return done; }) && !success && last==104
&& waitFor([&] { return mock.active==0 && mock.stops>=stops+2; }),"cancel stops both arms");
bool captured=false;
QObject::connect(&c,&RobotClient::jointPointCaptured,&c,
[&](quint64 t,const QVariantList &targets,bool ok,const QString &) {
captured=t==105 && ok && targets.size()==2;
});
c.requestJointPointCapture({"left","right"},105);
check(waitFor([&] { return captured; }),"capture two arms");
bool motorDone=false,motorOk=false;QVariantMap payload;
QObject::connect(&c,&RobotClient::motorRpcFinished,&c,[&](quint64,const QString& method,bool ok,const QVariantMap &p,const QString& detail) {
motorDone=true;motorOk=ok;payload=p;
out<<"motor reply "<<method<<" "<<ok<<" "<<detail<<" "<<QJsonDocument::fromVariant(p).toJson(QJsonDocument::Compact)<<"\n";out.flush();
});
c.requestMotorRpc("ListMotors","test_manager",0,{},201);
check(waitFor([&] {return motorDone;})&&motorOk&&payload.value("motors").toList().size()==1,"typed MotorService ListMotors");
motorDone=false;c.requestMotorRpc("GetState","test_manager",0,{},202);
check(waitFor([&] {return motorDone;})&&motorOk&&payload.value("state").toMap().value("torque").toDouble()==35,"position velocity torque feedback");
motorDone=false;c.requestMotorRpc("commandProfileTorque","test_manager",0,{{"tau",12.5},{"torqueSlope",100}},203);
check(waitFor([&] {return motorDone;})&&motorOk&&motorMock.torqueWrites==1,"per mille profile torque and slope");
motorDone=false;c.requestMotorRpc("commandCyclicPosition","test_manager",0,{{"q",0.3},{"qd",-0.2}},204);
check(waitFor([&] {return motorDone;})&&motorOk,"direct cyclic position parameters");
}
}
server->Shutdown();
if (result) qInfo()<<"PASS concurrent synchronous RPCs, responsive UI, preflight, error, cancel and capture";
return result;
}
#endif
struct TaskFlowTestAccess
{
static bool verify()
{
TaskOrchestrationWidget w;
w.m_tree->clear(); w.m_insertionParent = nullptr; w.m_insertionIndex = -1;
auto task = [&](const QString &name) {
return w.itemFromJson(QJsonObject{{"kind", "task"}, {"name", name},
{"deviceType", QStringLiteral("仿生头")}, {"deviceId", "bio_head"},
{"action", QStringLiteral("高兴")}, {"waitMs", 0}});
};
auto *a = task("A"); auto *b = task("B"); auto *d = task("D"); auto *c = task("C");
auto *loop = w.itemFromJson(QJsonObject{{"kind", "loop"}, {"name", "Outer"}, {"count", 2}});
auto *nested = w.itemFromJson(QJsonObject{{"kind", "loop"}, {"name", "Inner"}, {"count", 2}});
w.m_tree->addTopLevelItems({a, loop, c});
loop->addChildren({b, nested}); nested->addChild(d);
loop->setExpanded(true); nested->setExpanded(true);
w.rebuildFlowScene();
int edges = 0, memberships = 0;
QList<QRectF> cards;
for (auto *g : w.m_flowScene->items()) {
edges += g->data(0).toString() == "sequence";
memberships += g->data(0).toString() == "membership";
if (g->data(0).toString() == "taskNode") cards.append(g->sceneBoundingRect());
}
if (edges != 3 || memberships != 3) return false;
for (int i = 0; i < cards.size(); ++i) for (int j = i + 1; j < cards.size(); ++j)
if (cards[i].intersects(cards[j])) return false;
auto select = [&](const QString &name) {
w.m_flowScene->clearSelection();
for (auto *g : w.m_flowScene->items())
if (g->data(0).toString() == "taskNode" && g->data(1).toString() == name) {
g->setSelected(true); return true;
}
return false;
};
if (!select("Outer") || w.m_insertionParent || w.m_insertionIndex != 2) return false;
auto *x = task("X"); w.insertNode(x);
if (w.m_tree->topLevelItem(2) != x || loop->childCount() != 2) return false;
if (!select("B") || w.m_insertionParent != loop || w.m_insertionIndex != 1) return false;
if (!w.m_insertionHint->text().contains("Outer")) return false;
auto *y = task("Y"); w.insertNode(y);
if (loop->child(1) != y || nested->childCount() != 1) return false;
if (!select("Outer") || !w.useSelectedLoopAsInsertionParent()) return false;
if (w.m_insertionParent != loop || w.m_tree->currentItem()) return false;
auto *z = task("Z"); w.insertNode(z);
if (loop->child(3) != z) return false;
w.moveFlowItem(z, QPointF(-100000, 0));
if (z->parent() != loop || loop->child(0) != z) return false;
w.moveFlowItem(z, QPointF(100000, 0));
if (z->parent() != loop || loop->child(3) != z) return false;
w.setInsertionAtRoot();
if (w.m_insertionParent || w.m_tree->currentItem()
|| !w.m_insertionHint->text().contains(QStringLiteral("根流程(末尾)"))) return false;
// A click does not pass through the drag code; moving preserves nesting.
w.m_tree->setCurrentItem(loop); w.moveSelected(1);
if (!loop->isExpanded() || !nested->isExpanded() || d->parent() != nested) return false;
QList<TaskOrchestrationWidget::RunStep> steps; QString error;
if (!w.appendRunSteps(loop, steps, &error) || steps.size() != 10) return false;
const QStringList expected{"B", "Y", "D", "D", "Z", "B", "Y", "D", "D", "Z"};
for (int i = 0; i < steps.size(); ++i) if (steps[i].name != expected[i]) return false;
nested->setExpanded(false); w.save();
TaskOrchestrationWidget loaded;
QTreeWidgetItem *loadedLoop = nullptr;
for (int i = 0; i < loaded.m_tree->topLevelItemCount(); ++i)
if (loaded.m_tree->topLevelItem(i)->text(0) == "Outer") loadedLoop = loaded.m_tree->topLevelItem(i);
if (!loadedLoop || loadedLoop->child(2)->isExpanded()) return false;
auto *empty = w.itemFromJson(QJsonObject{{"kind", "loop"}, {"name", "Empty"}, {"count", 2}});
steps.clear(); bool rejected = !w.appendRunSteps(empty, steps, &error); delete empty;
if (!rejected || error.isEmpty()) return false;
w.resize(1500, 900); w.show(); qApp->processEvents();
QGraphicsItem *cardA = nullptr;
for (auto *g : w.m_flowScene->items())
if (g->data(0).toString() == "taskNode" && g->data(1).toString() == "A") cardA = g;
if (!cardA) return false;
w.m_flowView->ensureVisible(cardA);
const QPoint point = w.m_flowView->mapFromScene(cardA->sceneBoundingRect().center());
const QPoint global = w.m_flowView->viewport()->mapToGlobal(point);
const quint64 revision = w.m_sceneRevision;
QMouseEvent press(QEvent::MouseButtonPress, point, global, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QMouseEvent release(QEvent::MouseButtonRelease, point, global, Qt::LeftButton, Qt::NoButton, Qt::NoModifier);
QApplication::sendEvent(w.m_flowView->viewport(), &press);
QApplication::sendEvent(w.m_flowView->viewport(), &release);
qApp->processEvents();
if (w.m_sceneRevision != revision || w.m_tree->currentItem() != a
|| w.m_insertionParent || w.m_insertionIndex != 1) return false;
const QJsonObject beforeFold = w.itemToJson(loop);
QGraphicsItem *loopCard = nullptr;
for (auto *g : w.m_flowScene->items())
if (g->data(0).toString() == "taskNode" && g->data(1).toString() == "Outer") loopCard = g;
if (!loopCard) return false;
w.m_flowView->ensureVisible(loopCard);
const QPoint toggle = w.m_flowView->mapFromScene(loopCard->scenePos() + QPointF(246, 21));
const QPoint toggleGlobal = w.m_flowView->viewport()->mapToGlobal(toggle);
QMouseEvent foldPress(QEvent::MouseButtonPress, toggle, toggleGlobal, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QMouseEvent foldRelease(QEvent::MouseButtonRelease, toggle, toggleGlobal, Qt::LeftButton, Qt::NoButton, Qt::NoModifier);
QApplication::sendEvent(w.m_flowView->viewport(), &foldPress);
QApplication::sendEvent(w.m_flowView->viewport(), &foldRelease);
qApp->processEvents();
QJsonObject afterFold = w.itemToJson(loop);
afterFold.insert("collapsed", beforeFold.value("collapsed"));
if (loop->isExpanded() || afterFold != beforeFold) return false;
loop->setExpanded(true); w.rebuildFlowScene();
w.grab().save(QStringLiteral("task-flow-interactions.png"));
qInfo() << "Task flow: insertion contexts, nested order, edges, drag scope and persistence PASS";
return true;
}
};
static bool verifyBioheadPage()
{
RobotClient client;
// Prevent any dispatch to the real worker; inspect requests and inject replies.
QObject::disconnect(&client, &RobotClient::rpcRequested, nullptr, nullptr);
BioHeadWidget page(&client);
page.resize(1250, 850);
page.show();
auto *devices = page.findChild<QComboBox *>(QStringLiteral("bioheadDeviceCombo"));
auto *status = page.findChild<QLabel *>(QStringLiteral("bioheadStatus"));
auto *tabs = page.findChild<QTabWidget *>();
if (!devices || !status || !tabs || tabs->count() != 2) return false;
QPushButton *happy = nullptr;
int count = 0;
for (auto *button : page.findChildren<QPushButton *>()) {
if (button->property("bioheadAction").isValid()) {
++count;
if (button->isEnabled()) return false;
if (button->property("bioheadAction") == QStringLiteral("高兴")) happy = button;
}
}
if (count != 10 || !happy) return false;
const QVariantList list{QVariantMap{{"deviceId", "bio_head"}, {"type", 8}},
QVariantMap{{"deviceId", "usb_cam1"}, {"type", 2}}};
page.setAvailableDevices(list);
emit client.connectionChanged(true, 0, QString());
if (devices->count() != 1 || !happy->isEnabled()) return false;
bool dispatched = false;
QObject::connect(&client, &RobotClient::rpcRequested, &page,
[&](const QString &service, const QString &method, const QString &json, const QString &id) {
dispatched = service == QStringLiteral("cmvr.api.BioHeadService") && method == QStringLiteral("Happy")
&& id == QStringLiteral("bio_head") && QJsonDocument::fromJson(json.toUtf8()).object()
.value(QStringLiteral("header")).toObject().value(QStringLiteral("deviceId")).toString() == id;
});
happy->click();
if (!dispatched || happy->isEnabled()) return false;
emit client.rpcFinished(QStringLiteral("cmvr.api.BioHeadService"), QStringLiteral("Happy"), true,
QStringLiteral("{\"header\":{\"errorMessage\":\"device rejected\"}}"));
if (!happy->isEnabled() || !status->text().contains(QStringLiteral("device rejected"))) return false;
page.setAvailableDevices(list);
if (!status->text().contains(QStringLiteral("device rejected"))) return false;
page.grab().save(QStringLiteral("biohead-page.png"));
emit client.connectionChanged(false, 0, QString());
if (happy->isEnabled()) return false;
return true;
}
static bool verifyBioheadTaskRun()
{
// Isolated from MainWindow/RobotClient: no real connection or hardware calls.
TaskOrchestrationWidget tasks;
auto *tree = tasks.findChild<QTreeWidget *>();
if (!tree) return false;
tree->clear();
for (const QString &action : {QStringLiteral("开始说话"), QStringLiteral("停止说话"),
QStringLiteral("高兴")}) {
auto *item = new QTreeWidgetItem(tree);
item->setText(0, action);
item->setData(0, Qt::UserRole, QStringLiteral("task"));
item->setData(0, Qt::UserRole + 1, QStringLiteral("仿生头"));
item->setData(0, Qt::UserRole + 2, QStringLiteral("bio_head"));
item->setData(0, Qt::UserRole + 3, action);
item->setData(0, Qt::UserRole + 4, QStringLiteral("{}"));
item->setData(0, Qt::UserRole + 5, 40);
}
QPushButton *run = nullptr;
for (auto *button : tasks.findChildren<QPushButton *>())
if (button->text() == QStringLiteral("执行任务编排")) run = button;
if (!run) return false;
int requests = 0;
bool valid = true;
QEventLoop loop;
QObject::connect(&tasks, &TaskOrchestrationWidget::taskRequested, &tasks,
[&](const QString &type, const QString &id, const QString &action, const QJsonObject &) {
++requests;
valid = valid && type == QStringLiteral("仿生头") && id == QStringLiteral("bio_head");
const QString method = BioHeadOperations::method(action);
tasks.completeRpcTask(QStringLiteral("wrong.service"), method, true,
QStringLiteral("{\"header\":{\"success\":true}}"));
QTimer::singleShot(10, &tasks, [&, method]() {
const bool first = requests == 1;
tasks.completeRpcTask(QStringLiteral("cmvr.api.BioHeadService"), method, true,
first ? QStringLiteral("{\"header\":{\"success\":true}}")
: QStringLiteral("{\"header\":{\"errorMessage\":\"test rejection\"}}"));
});
});
run->click();
QTimer::singleShot(300, &loop, &QEventLoop::quit);
loop.exec();
auto *history = tasks.findChild<QListWidget *>();
bool failureShown = false;
if (history) for (int i = 0; i < history->count(); ++i)
failureShown |= history->item(i)->text().contains(QStringLiteral("test rejection"));
return valid && requests == 2 && run->isEnabled() && failureShown;
}
int main(int argc, char **argv)
{
QApplication application(argc, argv);
application.setApplicationName(QStringLiteral("CMVR Theme Verification"));
application.setOrganizationName(QStringLiteral("CMVR Tests"));
ApplicationStyle::install(application);
if (!MotorDebugTestAccess::verify()) return 14;
if (!JointPointTestAccess::verify()) return 12;
#ifdef CMVR_WITH_GRPC
if (!verifyPointRpc()) return 13;
#endif
if (!TaskFlowTestAccess::verify()) return 11;
if (!verifyBioheadPage()) return 10;
if (!verifyBioheadTaskRun()) return 9;
if (application.windowIcon().pixmap(32, 32).isNull()) return 1;
MainWindow window;
if (auto *demo = window.findChild<QCheckBox *>(QStringLiteral("demoCheck")))
demo->setChecked(false);
window.resize(1600, 1000);
window.show();
QTimer::singleShot(150, &window, [&]() {
int comboCount = 0;
QStringList audit;
for (QComboBox *combo : window.findChildren<QComboBox *>()) {
combo->ensurePolished();
if (!combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff"))) {
qCritical() << "Unthemed combo:" << combo->objectName(); application.exit(6); return;
}
++comboCount;
audit.append(QStringLiteral("PASS %1 / %2").arg(combo->metaObject()->className(), combo->objectName()));
}
QFile report(QStringLiteral("combo-audit.txt"));
if (report.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream stream(&report);
stream << "Main-window combos: " << comboCount << '\n' << audit.join('\n') << '\n';
}
report.close();
qInfo() << "Themed main-window combo count:" << comboCount;
window.grab().save(QStringLiteral("application-system.png"));
QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 1));
application.processEvents();
const auto viewers = window.findChildren<UrdfViewerWidget *>();
for (const auto *viewer : viewers) if (viewer->modelPreviewEnabled()) { application.exit(2); return; }
window.grab().save(QStringLiteral("application-arm.png"));
QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 16));
application.processEvents();
window.grab().save(QStringLiteral("application-tasks.png"));
if (auto *tasks = window.findChild<TaskOrchestrationWidget *>()) {
tasks->setAvailableDevices({QVariantMap{{"deviceId", "usb_cam1"}, {"type", 2}},
QVariantMap{{"deviceId", "mic1"}, {"type", 5}},
QVariantMap{{"deviceId", "bio_head"}, {"type", 8}}});
QPushButton *add = nullptr;
for (auto *button : tasks->findChildren<QPushButton *>())
if (button->text().contains(QStringLiteral("任务节点"))) { add = button; break; }
if (!add) { application.exit(7); return; }
bool taskInspected = false;
QTimer::singleShot(100, &window, [&]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (!dialog) return;
auto *title = dialog->findChild<QLabel *>(QStringLiteral("jointFlowDialogTitle"));
taskInspected = title && title->text() == QStringLiteral("任务节点参数");
int count = 0;
for (QComboBox *combo : dialog->findChildren<QComboBox *>()) {
combo->ensurePolished();
taskInspected = taskInspected && combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff"));
++count;
}
QComboBox *devices = nullptr;
for (auto *combo : dialog->findChildren<QComboBox *>())
for (int i = 0; i < combo->count(); ++i)
if (combo->itemData(i).toMap().value(QStringLiteral("deviceId"))
== QStringLiteral("bio_head")) {
devices = combo;
combo->setCurrentIndex(i);
break;
}
bool bioheadActions = false;
for (auto *combo : dialog->findChildren<QComboBox *>())
if (combo->findText(QStringLiteral("开始说话")) >= 0)
bioheadActions = combo->count() == BioHeadOperations::actions().size()
&& combo->findText(QStringLiteral("紧急停止")) >= 0;
taskInspected = taskInspected && devices && bioheadActions;
if (report.open(QIODevice::Append | QIODevice::Text)) {
QTextStream stream(&report);
stream << "Task-node dialog combos: " << count << " / " << (taskInspected ? "PASS" : "FAIL") << '\n';
report.close();
}
dialog->grab().save(QStringLiteral("task-node-dialog.png"));
dialog->reject();
});
add->click();
if (!taskInspected) { application.exit(8); return; }
}
QPushButton *settings = nullptr;
for (QPushButton *button : window.findChildren<QPushButton *>())
if (button->text() == QStringLiteral("软件设置")) settings = button;
if (!settings) { application.exit(3); return; }
bool inspected = false;
QTimer::singleShot(100, &window, [&]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (dialog && dialog->objectName() == QStringLiteral("applicationSettingsDialog")) {
inspected = dialog->property("applicationChrome").toBool()
&& !(dialog->windowFlags() & Qt::WindowStaysOnTopHint);
for (QComboBox *combo : dialog->findChildren<QComboBox *>()) {
combo->ensurePolished();
inspected = inspected && combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff"));
}
dialog->grab().save(QStringLiteral("application-settings.png"));
dialog->reject();
}
});
settings->click();
qInfo() << "Theme shell: navigation, disabled model default, icon and settings verified";
application.exit(inspected ? 0 : 4);
});
QTimer::singleShot(12000, &application, [&]() { application.exit(5); });
return application.exec();
}