CmvrControlStation/tests/workflow_robot_test.cpp

83 lines
12 KiB
C++
Raw Permalink Normal View History

#include "../src/taskorchestrationwidget.cpp"
#include "workflowrobotmanager.h"
#include "cmvr/api/system_service.grpc.pb.h"
#include "cmvr/api/arm_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QTemporaryDir>
#include <QElapsedTimer>
#include <QThread>
#include <atomic>
#include <iostream>
#include <stdexcept>
static void check(bool ok,const char* reason){if(!ok)throw std::runtime_error(reason);}
static void waitFor(std::function<bool()> predicate,const char* reason,int limit=6000){QElapsedTimer t;t.start();while(!predicate()&&t.elapsed()<limit){QApplication::processEvents();QThread::msleep(2);}check(predicate(),reason);}
class FakeSystem final:public cmvr::api::SystemService::Service{
public:
grpc::Status GetSystemInfo(grpc::ServerContext*,const cmvr::api::GetSystemInfoCommand::Request*,cmvr::api::GetSystemInfoCommand::Feedback* r)override{r->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<int> 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;i<joints;++i)r->add_joint_names("joint_"+std::to_string(i));return grpc::Status::OK;}
};
struct FakeRobot{
FakeSystem system;FakeArm arm;int port=0;std::unique_ptr<grpc::Server> 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(&current);
const QString path=files.filePath("robots.json");QString a,b;
{
WorkflowRobotManager manager(&current,&currentRunner,&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<QTreeWidget*>())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<QComboBox*>("workflowNodeRobot");auto* deviceChoice=target.findChild<QComboBox*>("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<QWidget*>())if(auto* e=dynamic_cast<TaskProtoEditor*>(w)){if(auto* t=e->findChild<QTableWidget*>("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<QPushButton*>())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<QPushButton*>())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<QScrollArea*>("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<changedNodes.size();++i){auto n=changedNodes[i].toObject();if(n.value("id")==a){auto p=n.value("properties").toObject();p.insert("cmvrRobotId",b);p.insert("executionTarget",destination);n.insert("properties",p);changedNodes[i]=n;}}
changed.insert("nodes",changedNodes);const auto merged=WorkflowGraph::merge(changed,graph);check(WorkflowGraph::node(merged,a).value("properties").toObject().value("executionTarget").toObject().value("roleKey")==destination.value("roleKey"),"changing robot also changes persisted web execution role");
check(FreeScanInterop::importGraph(graph,restored,error),qPrintable(error));auto roundTrip=restored.value("groups").toArray()[0].toObject().value("nodes").toArray();check(roundTrip[0].toObject().value("robotId")==a&&roundTrip[1].toObject().value("robotId")==b,"robot IDs survive export/import");
manager.disconnectRobot(a);waitFor([&]{return target.devicesForRobot(a).isEmpty();},"disconnect A clears only A devices");check(!call(execution(a))&&call(execution(b)),"disconnect A never redirects its request to connected B");
manager.connectRobot(a);waitFor([&]{return target.robotDeviceInfo(a,"shared_arm").value("jointNames").toStringList().size()==6;},"reconnecting an already selected robot automatically reloads metadata");
manager.removeRobot(a);check(!manager.client(a)&&manager.client(b),"removal does not affect another connection");
const auto demoA=manager.addRobot("Demo A","demo",50051,true),demoB=manager.addRobot("Demo B","demo",50051,true);manager.connectRobot(demoA);manager.connectRobot(demoB);
waitFor([&]{return target.devicesForRobot(demoA).size()>=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(&current,&currentRunner,&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: "<<e.what()<<"\n";return 1;}}