334 lines
19 KiB
C++
334 lines
19 KiB
C++
// Real UI/backend objects, loopback-only gRPC, isolated settings, no hardware.
|
|
#include <QtTest>
|
|
#include <QApplication>
|
|
#include <QCheckBox>
|
|
#include <QComboBox>
|
|
#include <QDoubleSpinBox>
|
|
#include <QFile>
|
|
#include <QFileInfo>
|
|
#include <QLineEdit>
|
|
#include <QMainWindow>
|
|
#include <QPushButton>
|
|
#include <QSettings>
|
|
#include <QSpinBox>
|
|
#include <QTemporaryDir>
|
|
#include <QTabWidget>
|
|
#include <grpcpp/grpcpp.h>
|
|
#include "cmvr/api/arm_service.grpc.pb.h"
|
|
#include "cmvr/api/camera_service.grpc.pb.h"
|
|
#include <atomic>
|
|
#include <cmath>
|
|
#include <cstdio>
|
|
#include <functional>
|
|
#include <limits>
|
|
#include <mutex>
|
|
#include <stdexcept>
|
|
#define private public
|
|
#include "../src/mainwindow.h"
|
|
#undef private
|
|
#include "../src/robotclient.h"
|
|
#include "../src/handeyemotionwidget.h"
|
|
#include "../src/tcpcalibrationwidget.h"
|
|
#include "../src/urdfviewerwidget.h"
|
|
#include "../ui/handeyecalibrationwidget.h"
|
|
|
|
static void require(bool ok, const char *detail)
|
|
{
|
|
if (!ok) throw std::runtime_error(detail);
|
|
}
|
|
static bool until(const std::function<bool()> &predicate, int timeout=5000)
|
|
{
|
|
QElapsedTimer timer; timer.start();
|
|
while (!predicate() && timer.elapsed()<timeout) QTest::qWait(10);
|
|
return predicate();
|
|
}
|
|
class FakeCamera : public cmvr::api::CameraService::Service {
|
|
public:
|
|
std::atomic<int> mode{0}, reads{0};
|
|
grpc::Status GetRGBImage(grpc::ServerContext *, const cmvr::api::GetRGBImageCommand::Request *r,
|
|
cmvr::api::GetRGBImageCommand::Feedback *s) override
|
|
{
|
|
++reads;
|
|
if (r->header().device_id()!="camera-a") {
|
|
s->mutable_header()->set_success(false);
|
|
s->mutable_header()->set_error_message("unexpected camera identity");
|
|
return grpc::Status::OK;
|
|
}
|
|
s->mutable_header()->set_success(true);
|
|
auto *frame=s->mutable_color_frame();
|
|
frame->set_width(2); frame->set_height(1);
|
|
frame->set_type(cmvr::api::FrameData::U8C3); frame->set_codec("none");
|
|
const char pixels[]={10,20,30,40,50,60};
|
|
frame->set_data(pixels,mode.load()==2 ? 5 : sizeof(pixels));
|
|
auto *k=s->mutable_intrinsics();
|
|
k->set_fx(mode.load()==1 ? 0.f : 800.f); k->set_fy(810.f);
|
|
k->set_cx(.5f); k->set_cy(.25f);
|
|
for (int i=0;i<5;++i) k->add_coeffs(0.f);
|
|
if (mode.load()==3) k->set_fy(std::numeric_limits<float>::quiet_NaN());
|
|
// The audited unary server omits capture/source metadata.
|
|
return grpc::Status::OK;
|
|
}
|
|
};
|
|
class FakeArm : public cmvr::api::ArmService::Service {
|
|
public:
|
|
std::atomic<int> poses{0}, moves{0};
|
|
std::mutex mutex;
|
|
std::string lastPoseDevice;
|
|
grpc::Status GetArmInfo(grpc::ServerContext *,const cmvr::api::GetArmInfo::Request *r,
|
|
cmvr::api::GetArmInfo::Response *s) override
|
|
{
|
|
s->mutable_header()->set_success(true); s->set_device_id(r->header().device_id());
|
|
s->set_driver_type("AuboARM"); s->set_manufacturer("Aubo"); s->set_dof(6);
|
|
s->set_default_base_frame("base"); s->set_default_tcp_frame("tcp");
|
|
return grpc::Status::OK;
|
|
}
|
|
grpc::Status getRobotState(grpc::ServerContext *,const cmvr::api::GetRobotState::Request *r,
|
|
cmvr::api::GetRobotState::Response *s) override
|
|
{
|
|
++poses;
|
|
{ std::lock_guard<std::mutex> lock(mutex); lastPoseDevice=r->header().device_id(); }
|
|
s->mutable_header()->set_success(true);
|
|
auto *state=s->mutable_state(); state->set_connected(true); state->set_powered_on(true);
|
|
state->set_robot_mode(cmvr::api::ARM_ROBOT_MODE_IDLE);
|
|
state->set_safety_mode(cmvr::api::ARM_SAFETY_MODE_NORMAL);
|
|
state->set_timestamp(123.);
|
|
auto *pose=state->mutable_actual_tcp_pose();
|
|
pose->set_x(.4); pose->set_y(.2); pose->set_z(.5);
|
|
auto *j=state->mutable_actual_joint_state();
|
|
for (int i=0;i<6;++i) { j->add_position(.1); j->add_velocity(0.); }
|
|
return grpc::Status::OK;
|
|
}
|
|
grpc::Status moveL(grpc::ServerContext *,const cmvr::api::MoveL::Request *,
|
|
cmvr::api::MoveL::Response *s) override
|
|
{
|
|
++moves; s->mutable_header()->set_success(true); return grpc::Status::OK;
|
|
}
|
|
};
|
|
static HandEyeStore::Record record(const QString &name,const QString &mode)
|
|
{
|
|
HandEyeStore::Record r;
|
|
r.name=name; r.mode=mode; r.cameraId="camera-a"; r.method="PARK";
|
|
r.createdAt="2026-09-30T10:00:00Z"; r.sampleCount=12;
|
|
r.transform={{0,-1,0,.1, 1,0,0,.2, 0,0,1,.3, 0,0,0,1}};
|
|
r.metrics={{"accepted",true},{"translation_rms_mm",.2},{"rotation_rms_deg",.1}};
|
|
r.board={{"type","chessboard"},{"rows",6},{"square_size_m",.025}};
|
|
r.intrinsics={{"camera_matrix",QVariantList{800.,0.,320.,0.,800.,240.,0.,0.,1.}},
|
|
{"distortion",QVariantList{0.,0.,0.,0.,0.}}};
|
|
return r;
|
|
}
|
|
static QList<QVariant> imageReply(RobotClient &client,QSignalSpy &spy,quint64 token)
|
|
{
|
|
spy.clear(); client.requestHandEyeImage("camera-a",token);
|
|
require(until([&] { return !spy.isEmpty(); }),"image callback missing");
|
|
const auto reply=spy.takeFirst();
|
|
require(reply.at(0).toULongLong()==token && reply.at(1).toString()=="camera-a",
|
|
"image callback lost token/camera identity");
|
|
return reply;
|
|
}
|
|
static void assertPoint(QSignalSpy &spy,double x,double y,double z,const QString &profile)
|
|
{
|
|
require(!spy.isEmpty(),"coordinate result signal missing");
|
|
const auto response=spy.takeFirst();
|
|
require(response.at(0).toString()=="camera-a" && response.at(1).toString()==profile,
|
|
"coordinate result used wrong camera/profile");
|
|
const auto point=response.at(2).toList();
|
|
require(point.size()==3,"coordinate result is not XYZ");
|
|
const double expected[]={x,y,z};
|
|
for (int i=0;i<3;++i)
|
|
require(std::abs(point.at(i).toDouble()-expected[i])<1e-9,
|
|
"coordinate result transform, rotation, offset or units incorrect");
|
|
}
|
|
int main(int argc,char **argv)
|
|
{
|
|
QApplication app(argc,argv);
|
|
app.setStyle("Fusion");
|
|
QFile styleFile(":/styles.qss");
|
|
if (styleFile.open(QIODevice::ReadOnly))
|
|
app.setStyleSheet(QString::fromUtf8(styleFile.readAll()));
|
|
QTemporaryDir settingsDirectory;
|
|
app.setOrganizationName("CMVR-HandEye-Isolated-Test"); app.setApplicationName("Integration");
|
|
QSettings::setDefaultFormat(QSettings::IniFormat);
|
|
QSettings::setPath(QSettings::IniFormat,QSettings::UserScope,settingsDirectory.path());
|
|
FakeCamera camera; FakeArm arm;
|
|
grpc::ServerBuilder builder; int port=0;
|
|
builder.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);
|
|
builder.RegisterService(&camera); builder.RegisterService(&arm);
|
|
auto server=builder.BuildAndStart();
|
|
try {
|
|
require(settingsDirectory.isValid() && server && port>0,"isolated test startup failed");
|
|
{
|
|
RobotClient isolated;
|
|
QSignalSpy replies(&isolated,&RobotClient::handEyeImageReceived);
|
|
require(!imageReply(isolated,replies,1).at(5).toBool(),"disconnected image accepted");
|
|
QSignalSpy connected(&isolated,&RobotClient::connectionChanged);
|
|
isolated.connectToServer("127.0.0.1",port,true);
|
|
require(until([&] { return !connected.isEmpty(); }),"demo connection callback missing");
|
|
require(!imageReply(isolated,replies,2).at(5).toBool(),"demo image accepted");
|
|
require(camera.reads.load()==0,"demo/disconnected request reached camera RPC");
|
|
}
|
|
MainWindow window;
|
|
window.m_demoCheck->setChecked(false);
|
|
window.m_hostEdit->setText("127.0.0.1"); window.m_portSpin->setValue(port);
|
|
window.m_armIdEdit->setText("arm-a"); window.m_cameraIdEdit->setText("camera-a");
|
|
window.toggleConnection();
|
|
require(until([&] { return window.m_connected; }),"real loopback connection failed");
|
|
QSignalSpy images(window.m_client,&RobotClient::handEyeImageReceived);
|
|
const auto imageResult=imageReply(*window.m_client,images,10);
|
|
require(imageResult.at(5).toBool(),"valid unary image rejected");
|
|
const QImage image=qvariant_cast<QImage>(imageResult.at(2));
|
|
require(image.size()==QSize(2,1) && image.pixelColor(0,0)==QColor(30,20,10)
|
|
&& image.pixelColor(1,0)==QColor(60,50,40),"BGR image conversion or lifetime incorrect");
|
|
const auto intrinsics=imageResult.at(3).toMap(), metadata=imageResult.at(4).toMap();
|
|
require(intrinsics.value("fx").toDouble()==800. && intrinsics.value("fy").toDouble()==810.
|
|
&& intrinsics.value("width").toInt()==2 && intrinsics.value("coeffs").toList().size()==5,
|
|
"snapshot lost native intrinsics");
|
|
require(!metadata.value("captureTimestampAvailable").toBool()
|
|
&& metadata.value("captureUtcNs").toLongLong()==0,"missing capture timestamp fabricated");
|
|
camera.mode=1;
|
|
require(!imageReply(*window.m_client,images,11).at(5).toBool(),"zero focal length accepted");
|
|
camera.mode=2;
|
|
require(!imageReply(*window.m_client,images,12).at(5).toBool(),"malformed RGB byte count accepted");
|
|
camera.mode=3;
|
|
require(!imageReply(*window.m_client,images,13).at(5).toBool(),"NaN focal length accepted");
|
|
require(image.pixelColor(0,0)==QColor(30,20,10),"snapshot pixels changed after later RPCs");
|
|
camera.mode=0;
|
|
|
|
const QString endpoint=window.endpoint(); QSettings settings; QString error;
|
|
auto eth=record("fixed-camera","eye_to_hand"), eih=record("wrist-camera","eye_in_hand");
|
|
require(HandEyeStore::save(settings,endpoint,"arm-a",eth,false,error),"save ETH profile failed");
|
|
require(HandEyeStore::save(settings,endpoint,"arm-a",eih,false,error),"save EIH profile failed");
|
|
auto other=record("other-robot","eye_to_hand");
|
|
require(HandEyeStore::save(settings,endpoint,"arm-b",other,false,error),"save other robot failed");
|
|
other.name="other-server";
|
|
require(HandEyeStore::save(settings,"other:1234","arm-a",other,false,error),"save other server failed");
|
|
auto *panel=window.m_handEyeMotion;
|
|
auto *profiles=panel->findChild<QComboBox *>("handEyeMotionProfiles");
|
|
auto *convert=panel->findChild<QPushButton *>("handEyeConvert");
|
|
require(profiles && convert,"handeye motion UI missing");
|
|
window.m_handEye->calibrationsChanged(endpoint,"arm-a",eth.name);
|
|
require(profiles->count()==2 && profiles->currentData().toString()==eth.name,
|
|
"save notification did not immediately populate/select motion profile");
|
|
require(profiles->findData("other-robot")<0 && profiles->findData("other-server")<0,
|
|
"calibration leaked across robot/server identity");
|
|
window.m_armIdEdit->setText("arm-b");
|
|
require(profiles->count()==1 && profiles->findData("other-robot")>=0,"robot switch not isolated");
|
|
window.m_armIdEdit->setText("arm-a");
|
|
require(profiles->count()==2 && profiles->findData("other-robot")<0,"return robot retained wrong profiles");
|
|
profiles->setCurrentIndex(profiles->findData(eth.name));
|
|
const double inputs[]={100.,20.,300.};
|
|
for (int i=0;i<3;++i)
|
|
panel->findChild<QDoubleSpinBox *>(QString("handEyeCameraPoint%1").arg(i))->setValue(inputs[i]);
|
|
QSignalSpy points(panel,&HandEyeMotionWidget::basePointPrepared);
|
|
QSignalSpy captures(panel,&HandEyeMotionWidget::captureRequested);
|
|
QSignalSpy moveJ(window.m_client,&RobotClient::moveJRequested);
|
|
QSignalSpy moveL(window.m_client,&RobotClient::moveLPoseRequested);
|
|
QSignalSpy jog(window.m_client,&RobotClient::tcpJogMoveRequested);
|
|
QSignalSpy speedJ(window.m_client,&RobotClient::speedJRequested);
|
|
QSignalSpy speedL(window.m_client,&RobotClient::speedLRequested);
|
|
require(convert->isEnabled(),"fixed camera conversion disabled"); convert->click();
|
|
assertPoint(points,.08,.3,.6,eth.name);
|
|
require(captures.isEmpty(),"fixed camera unnecessarily requested robot pose");
|
|
profiles->setCurrentIndex(profiles->findData(eih.name));
|
|
require(!convert->isEnabled(),"wrist conversion enabled without verified active TCP offset");
|
|
window.m_tcpCalibration->findChild<QDoubleSpinBox *>("tcpSource2")->setValue(200.);
|
|
window.m_tcpCalibration->findChild<QDoubleSpinBox *>("tcpSource5")->setValue(90.);
|
|
window.m_tcpCalibration->findChild<QCheckBox *>("tcpSourceConfirmed")->setChecked(true);
|
|
require(convert->isEnabled(),"wrist conversion not enabled after real reference confirmation");
|
|
const int poseCount=arm.poses.load(); convert->click();
|
|
require(until([&] { return !points.isEmpty(); }),"wrist conversion failed to receive real pose");
|
|
require(captures.size()==1 && arm.poses.load()>poseCount,"wrist conversion bypassed real pose RPC");
|
|
{ std::lock_guard<std::mutex> lock(arm.mutex);
|
|
require(arm.lastPoseDevice=="arm-a","wrist pose RPC used wrong robot"); }
|
|
assertPoint(points,.7,.12,.9,eih.name);
|
|
require(moveJ.isEmpty() && moveL.isEmpty() && jog.isEmpty() && speedJ.isEmpty()
|
|
&& speedL.isEmpty() && arm.moves.load()==0,"coordinate conversion sent robot motion");
|
|
// Exercise export notification through the real MainWindow model loader.
|
|
const QString urdfSource=settingsDirectory.filePath("robot.urdf");
|
|
QFile urdf(urdfSource);
|
|
require(urdf.open(QIODevice::WriteOnly),"URDF fixture creation failed");
|
|
urdf.write("<robot name=\"fixture\"><link name=\"flange\"/></robot>"); urdf.close();
|
|
panel->setUrdfFile(urdfSource);
|
|
auto *reference=panel->findChild<QComboBox *>("handEyeUrdfReference");
|
|
reference->setCurrentIndex(reference->findData("flange"));
|
|
panel->findChild<QComboBox *>("handEyeUrdfCamera")->setEditText("camera_optical");
|
|
panel->findChild<QCheckBox *>("handEyeUrdfConfirmed")->setChecked(true);
|
|
const QString urdfOutput=settingsDirectory.filePath("robot_calibrated.urdf");
|
|
require(panel->exportUrdf(urdfOutput,error),qPrintable(error));
|
|
require(QFileInfo(window.m_urdfViewer->currentFile())==QFileInfo(urdfOutput),
|
|
"exported URDF was not loaded by MainWindow");
|
|
require(arm.moves.load()==0,"URDF update sent robot motion");
|
|
// Inspect UI request routing without starting even a loopback video
|
|
// worker. Other tests above exercise the real unary backend unchanged.
|
|
QObject::disconnect(window.m_client,&RobotClient::cameraStreamStartRequested,nullptr,nullptr);
|
|
QObject::disconnect(window.m_client,&RobotClient::cameraStreamStopRequested,nullptr,nullptr);
|
|
QSignalSpy starts(window.m_client,&RobotClient::cameraStreamStartRequested);
|
|
QSignalSpy stops(window.m_client,&RobotClient::cameraStreamStopRequested);
|
|
for (int codecIndex=0;codecIndex<2;++codecIndex) {
|
|
window.m_cameraCodecCombo->setCurrentIndex(codecIndex);
|
|
window.m_handEye->previewRequested("camera-a",true);
|
|
require(starts.size()==1,"handeye preview did not request one stream");
|
|
const auto start=starts.takeFirst();
|
|
require(start.at(0).toString()=="camera-a"
|
|
&& start.at(1).toString()==(codecIndex==0 ? "h264" : "h265")
|
|
&& start.at(2).toString()=="rgb","handeye preview sent display codec instead of canonical RGB codec");
|
|
window.m_handEye->previewRequested("camera-a",false);
|
|
require(stops.size()==1 && stops.takeFirst().at(0).toString()=="camera-a",
|
|
"handeye stop did not preserve per-camera ownership");
|
|
}
|
|
require(HandEyeStore::remove(settings,endpoint,"arm-a",eth.name,error),"remove fixed profile failed");
|
|
require(HandEyeStore::remove(settings,endpoint,"arm-a",eih.name,error),"remove wrist profile failed");
|
|
window.m_handEye->calibrationsChanged(endpoint,"arm-a",QString());
|
|
require(profiles->count()==0 && !convert->isEnabled(),"delete notification left selectable profile");
|
|
for (int i=0;i<3;++i)
|
|
require(panel->findChild<QLineEdit *>(QString("handEyeBasePoint%1").arg(i))->text().isEmpty(),
|
|
"deleted profile left stale converted coordinates");
|
|
window.toggleConnection();
|
|
require(until([&] { return !window.m_connected; }),"disconnect did not complete");
|
|
const int screenshotOption=app.arguments().indexOf("--screenshot");
|
|
if (screenshotOption>=0 && screenshotOption+1<app.arguments().size()) {
|
|
window.selectPage(14); window.resize(1440,1000); window.show();
|
|
QTest::qWait(250);
|
|
const QString screenshot=app.arguments().at(screenshotOption+1);
|
|
require(window.grab().save(screenshot),"screenshot save failed");
|
|
window.selectPage(1);
|
|
for (auto *tabs : window.findChildren<QTabWidget *>()) {
|
|
for (int i=0;i<tabs->count();++i) {
|
|
if (tabs->widget(i)==panel || tabs->widget(i)->isAncestorOf(panel))
|
|
tabs->setCurrentIndex(i);
|
|
}
|
|
}
|
|
QTest::qWait(250);
|
|
const QFileInfo screenshotInfo(screenshot);
|
|
require(window.grab().save(screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()+"-arm.png"),
|
|
"arm screenshot save failed");
|
|
window.m_jogModeTabs->setCurrentIndex(1);
|
|
QTest::qWait(100);
|
|
require(window.m_jogModeTabs->parentWidget()->grab().save(
|
|
screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()+"-jog.png"),
|
|
"Cartesian jog screenshot save failed");
|
|
window.selectPage(13);
|
|
window.m_tcpCalibration->findChild<QComboBox *>("tcpCalibrationMethod")->setCurrentIndex(1);
|
|
QTest::qWait(250);
|
|
require(window.grab().save(screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()+"-tcp.png"),
|
|
"TCP screenshot save failed");
|
|
window.selectPage(15);
|
|
QTest::qWait(250);
|
|
require(window.grab().save(screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()+"-touch.png"),
|
|
"Touch operation screenshot save failed");
|
|
// Layout verification at a smaller desktop size, without hardware.
|
|
window.resize(1280,800);
|
|
for(int page:{13,14,15}) {
|
|
window.selectPage(page); QTest::qWait(250);
|
|
require(window.grab().save(screenshotInfo.path()+"/"+screenshotInfo.completeBaseName()
|
|
+QStringLiteral("-compact-%1.png").arg(page)),"compact calibration screenshot failed");
|
|
}
|
|
}
|
|
std::puts("PASS: real unary BGR/K/lifetime validation, missing timestamps, rejection paths, isolated live dropdowns, ETH/EIH actual coordinate conversion and no motion, deletion invalidation");
|
|
} catch (const std::exception &error) {
|
|
std::fprintf(stderr,"FAIL: %s\n",error.what());
|
|
if (server) server->Shutdown();
|
|
return 1;
|
|
}
|
|
server->Shutdown(); return 0;
|
|
}
|