#include "../src/taskorchestrationwidget.cpp" #include "workflowrobotmanager.h" #include "cmvr/api/system_service.grpc.pb.h" #include "cmvr/api/arm_service.grpc.pb.h" #include #include #include #include #include #include #include static void check(bool ok,const char* reason){if(!ok)throw std::runtime_error(reason);} static void waitFor(std::function predicate,const char* reason,int limit=6000){QElapsedTimer t;t.start();while(!predicate()&&t.elapsed()mutable_header()->set_success(true);r->set_system_name("loopback robot");return grpc::Status::OK;} grpc::Status GetSystemStatus(grpc::ServerContext*,const cmvr::api::GetSystemStatusCommand::Request*,cmvr::api::GetSystemStatusCommand::Feedback* r)override{r->mutable_header()->set_success(true);auto* d=r->add_device_list();d->set_device_id("shared_arm");d->set_device_type(cmvr::api::Robot);d->set_device_kind(cmvr::api::DEVICE_KIND_ARM);auto* c=r->add_device_list();c->set_device_id("camera_only");c->set_device_type(cmvr::api::Camera);c->set_device_kind(cmvr::api::DEVICE_KIND_CAMERA);return grpc::Status::OK;} }; class FakeArm final:public cmvr::api::ArmService::Service{ public:std::atomic calls{0};int joints=6; grpc::Status torqueOn(grpc::ServerContext*,const cmvr::api::CommandHeader::Request* q,cmvr::api::CommandHeader::Feedback* r)override{if(q->device_id()!="shared_arm")return {grpc::StatusCode::INVALID_ARGUMENT,"wrong robot device"};++calls;r->set_success(true);return grpc::Status::OK;} grpc::Status GetArmInfo(grpc::ServerContext*,const cmvr::api::GetArmInfo::Request*,cmvr::api::GetArmInfo::Response* r)override{r->mutable_header()->set_success(true);r->set_dof(joints);for(int i=0;iadd_joint_names("joint_"+std::to_string(i));return grpc::Status::OK;} }; struct FakeRobot{ FakeSystem system;FakeArm arm;int port=0;std::unique_ptr server; explicit FakeRobot(int joints){arm.joints=joints;grpc::ServerBuilder b;b.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);b.RegisterService(&system);b.RegisterService(&arm);server=b.BuildAndStart();check(server&&port,"fake robot starts");} ~FakeRobot(){server->Shutdown();server->Wait();} }; struct StorageGuard{ QString path=QCoreApplication::applicationDirPath()+"/data/task_orchestration.json";QByteArray content;bool existed=false; StorageGuard(){QFile f(path);existed=f.exists();if(f.open(QIODevice::ReadOnly))content=f.readAll();f.close();QFile::remove(path);} ~StorageGuard(){if(existed){QFile f(path);if(f.open(QIODevice::WriteOnly))f.write(content);}else QFile::remove(path);} }; int main(int argc,char** argv){QApplication app(argc,argv);ApplicationStyle::install(app);StorageGuard storage;try{ QTemporaryDir files;FakeRobot first(6),second(7);TaskOrchestrationWidget target;RobotClient current;TaskRpcRunner currentRunner(¤t); const QString path=files.filePath("robots.json");QString a,b; { WorkflowRobotManager manager(¤t,¤tRunner,&target,nullptr,path); a=manager.addRobot("Robot A","127.0.0.1",first.port,false);b=manager.addRobot("Robot B","127.0.0.1",second.port,false); check(!a.isEmpty()&&!b.isEmpty()&&a!=b,"distinct persistent robot identities");manager.connectRobot(a);manager.connectRobot(b); waitFor([&]{return target.devicesForRobot(a).size()==2&&target.devicesForRobot(b).size()==2;},"each robot has its own discovered inventory"); const auto execution=[&](const QString& robot){auto e=TaskApi::execution(QStringLiteral("机械臂"),QStringLiteral("接口 · torqueOn"),"shared_arm",{});e.insert("robotId",robot);return e;}; const auto call=[&](QJsonObject e){bool done=false,success=false;manager.run(e,[&](bool ok,const QString& response){QString error;success=TaskApi::responseSucceeded(ok,response,error);done=true;});waitFor([&]{return done;},"routed call completed");return success;}; check(call(execution(a))&&first.arm.calls==1&&second.arm.calls==0,"same device ID routes only to robot A"); check(call(execution(b))&&first.arm.calls==1&&second.arm.calls==1,"same device ID routes only to robot B"); manager.requestInfo(a,"shared_arm",QStringLiteral("机械臂"));manager.requestInfo(b,"shared_arm",QStringLiteral("机械臂")); waitFor([&]{return target.robotDeviceInfo(a,"shared_arm").value("jointNames").toStringList().size()==6&&target.robotDeviceInfo(b,"shared_arm").value("jointNames").toStringList().size()==7;},"same-named devices keep distinct joint metadata"); QTreeWidget* tree=nullptr;for(auto* t:target.findChildren())if(t->columnCount()==6)tree=t;check(tree,"inspector tree found"); auto* node=new QTreeWidgetItem;node->setText(0,"isolated arm");node->setData(0,NodeIdRole,"isolated");node->setData(0,KindRole,"task");node->setData(0,RobotIdRole,a);node->setData(0,DeviceTypeRole,QStringLiteral("机械臂"));node->setData(0,DeviceIdRole,"shared_arm");node->setData(0,ActionRole,QStringLiteral("接口 · moveJ")); node->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(QJsonObject{{"service","cmvr.api.ArmService"},{"method","moveJ"},{"request",QJsonObject()}}).toJson()));tree->addTopLevelItem(node);tree->setCurrentItem(node); auto* robotChoice=target.findChild("workflowNodeRobot");auto* deviceChoice=target.findChild("workflowNodeDevice");check(robotChoice&&deviceChoice,"separate robot and device selectors exist");check(deviceChoice->count()==1&&deviceChoice->currentText()=="shared_arm","arm node excludes camera inventory"); auto jointRows=[&]{for(auto* w:target.findChildren())if(auto* e=dynamic_cast(w)){if(auto* t=e->findChild("taskJointTable"))return t->rowCount();}return -1;}; check(jointRows()==6,"robot A inspector shows six joints");robotChoice->setCurrentIndex(robotChoice->findData(b));QApplication::processEvents();check(jointRows()==7&&node->data(0,RobotIdRole)==b,"switching robot selects its seven-joint device"); target.resize(1500,900);target.show();for(auto* button:target.findChildren())if(button->text()==QStringLiteral("节点参数"))button->setChecked(true);QElapsedTimer settle;settle.start();while(settle.elapsed()<200){QApplication::processEvents();QThread::msleep(2);}QPushButton* saveButton=nullptr;for(auto* button:target.findChildren())if(button->text()==QStringLiteral("保存节点参数"))saveButton=button; check(saveButton&&target.rect().contains(QRect(saveButton->mapTo(&target,QPoint()),saveButton->size())),"parameter save stays visible in fixed inspector footer"); auto* parameterScroll=target.findChild("workflowParameterScroll");check(parameterScroll,"input parameters have their own scroll area");parameterScroll->verticalScrollBar()->setValue(parameterScroll->verticalScrollBar()->maximum());QApplication::processEvents(); check(robotChoice->isVisible()&&target.rect().contains(QRect(robotChoice->mapTo(&target,QPoint()),robotChoice->size())),"robot selection remains visible while parameters scroll"); parameterScroll->verticalScrollBar()->setValue(0);QApplication::processEvents();target.grab().save("build/tests/workflow-layout.png"); target.clearRobotDeviceInfo(a);robotChoice->setCurrentIndex(robotChoice->findData(a));waitFor([&]{return jointRows()==6;},"selecting a robot automatically reloads its joint metadata"); // Round-trip local robot binding into the same role/device-slot structure used by the web editor. QJsonArray nodes;for(const auto& robot:QStringList{a,b}){auto e=execution(robot);e.remove("robotId");nodes.append(QJsonObject{{"id",robot},{"kind","task"},{"name",robot},{"robotId",robot},{"robotName",robot==a?"Robot A":"Robot B"},{"deviceType",QStringLiteral("机械臂")},{"deviceId","shared_arm"},{"action",QStringLiteral("接口 · torqueOn")},{"parameters",QJsonObject{{"service","cmvr.api.ArmService"},{"method","torqueOn"},{"request",QJsonObject()}}},{"execution",e}});} QJsonObject graph,restored;QString error;check(FreeScanInterop::exportGraph({{"groups",QJsonArray{QJsonObject{{"name","two robots"},{"nodes",nodes}}}}},0,graph,error),qPrintable(error)); int roles=0;for(const auto& n:graph.value("nodes").toArray())if(n.toObject().value("type")=="start")roles=n.toObject().value("properties").toObject().value("resourceRoles").toArray().size();check(roles==2,"web export has two independent robot roles"); auto changed=graph;auto changedNodes=changed.value("nodes").toArray();QJsonObject destination; for(const auto& n:changedNodes)if(n.toObject().value("id")==b)destination=n.toObject().value("properties").toObject().value("executionTarget").toObject(); for(int i=0;i=8&&target.devicesForRobot(demoB).size()>=8;},"two independent demo inventories"); auto simA=manager.client(demoA)->simulator(),simB=manager.client(demoB)->simulator();check(simA!=simB,"demo robots have separate simulated worlds"); simA->call("cmvr.api.ArmService","moveJ",{{"header",QJsonObject{{"device_id","right_arm"}}},{"target",QJsonObject{{"position",QJsonArray{1.,0.,0.,0.,0.,0.,0.}}}}}); check(simA->sample("right_arm").value("moving").toBool()&&!simB->sample("right_arm").value("moving").toBool(),"demo movement does not leak into another robot with the same device ID"); } { WorkflowRobotManager restored(¤t,¤tRunner,&target,nullptr,path);check(restored.client(b)&&!restored.client(a),"robot registry persists add/remove");for(const auto& v:restored.robots())check(!v.toMap().value("connected").toBool(),"saved robots never auto-connect at startup"); } std::cout<<"PASS: two loopback cmvr-es servers, same device ID isolated RPC routes/metadata, separate selectors, 6/7 joint switch, web role round-trip, independent disconnect/remove, isolated demo motion and persistent registry; no real devices\n";return 0; }catch(const std::exception& e){std::cerr<<"FAIL: "<