CmvrControlStation/tests/armcompatibility_test.cpp

379 lines
21 KiB
C++

#include "robotclient.h"
#include "mainwindow.h"
#include "applicationstyle.h"
#include <QApplication>
#include <QElapsedTimer>
#include <QEventLoop>
#include <QLabel>
#include <QLineEdit>
#include <QCheckBox>
#include <QComboBox>
#include <QPushButton>
#include <QSpinBox>
#include <QTabWidget>
#include <QTableWidget>
#include <QDebug>
#include <thread>
#include <atomic>
#include <cmath>
#include <cstdio>
#include <grpcpp/grpcpp.h>
#include "cmvr/api/arm_service.grpc.pb.h"
#include "cmvr/api/system_service.grpc.pb.h"
static bool waitFor(const std::function<bool()> &ready, int timeout = 7000)
{
QElapsedTimer timer; timer.start();
while (!ready() && timer.elapsed() < timeout) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 10);
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
return ready();
}
static void pumpEvents(int milliseconds)
{
QElapsedTimer timer; timer.start();
while (timer.elapsed() < milliseconds) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 10);
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
}
class System final : public cmvr::api::SystemService::Service {
grpc::Status GetSystemInfo(grpc::ServerContext*, const cmvr::api::GetSystemInfoCommand::Request*,
cmvr::api::GetSystemInfoCommand::Feedback *r) override {
r->mutable_header()->set_success(true); 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);
r->add_device_list()->set_device_id("tchl_arm"); // Legacy default enum zero is AGV.
r->add_device_list()->set_device_id("real_agv");
auto *motor = r->add_device_list(); motor->set_device_id("tchl_joint_motors");
motor->set_device_type(cmvr::api::MotorSystem);
return grpc::Status::OK;
}
};
class Arm final : public cmvr::api::ArmService::Service {
public:
bool modern = false;
std::atomic<int> stateCalls{0}, jointCalls{0}, controlCalls{0}, agvProbes{0}, frameCalls{0};
std::atomic<int> teachingCalls{0};
std::atomic<bool> rejectTeaching{false};
std::string recordedFile;
grpc::Status teaching(const cmvr::api::CommandHeader::Request *q,
cmvr::api::CommandHeader::Feedback *r) {
++teachingCalls;
if (q->device_id() != "tchl_arm") return {grpc::StatusCode::NOT_FOUND, "unknown arm"};
r->set_success(!rejectTeaching);
if (rejectTeaching) r->set_error_message("controller rejected teaching");
return grpc::Status::OK;
}
grpc::Status EnterTeachingMode(grpc::ServerContext*, const cmvr::api::CommandHeader::Request *q,
cmvr::api::CommandHeader::Feedback *r) override { return teaching(q, r); }
grpc::Status CompleteTeaching(grpc::ServerContext*, const cmvr::api::CommandHeader::Request *q,
cmvr::api::CommandHeader::Feedback *r) override { return teaching(q, r); }
grpc::Status StopTrajectoryRecording(grpc::ServerContext*, const cmvr::api::CommandHeader::Request *q,
cmvr::api::CommandHeader::Feedback *r) override { return teaching(q, r); }
grpc::Status ExitTeachingMode(grpc::ServerContext*, const cmvr::api::CommandHeader::Request *q,
cmvr::api::CommandHeader::Feedback *r) override { return teaching(q, r); }
grpc::Status StartTrajectoryRecording(grpc::ServerContext*, const cmvr::api::StartTrajectoryRecording::Request *q,
cmvr::api::StartTrajectoryRecording::Response *r) override {
recordedFile = q->file_name();
return teaching(&q->header(), r->mutable_header());
}
grpc::Status GetArmInfo(grpc::ServerContext*, const cmvr::api::GetArmInfo::Request *q,
cmvr::api::GetArmInfo::Response *r) override {
if (!modern) return {grpc::StatusCode::UNIMPLEMENTED, "legacy"};
r->mutable_header()->set_success(true); r->set_device_id(q->header().device_id());
r->set_manufacturer("test"); r->set_model("modern_arm"); r->set_dof(6);
r->set_default_base_frame("base"); r->set_default_tcp_frame("tool0");
for (int i = 1; i <= 6; ++i) r->add_joint_names("TCHL_AXIS_" + std::to_string(i));
return grpc::Status::OK;
}
grpc::Status getJointState(grpc::ServerContext*, const cmvr::api::JointRequest *q,
cmvr::api::JointResponse *r) override {
++jointCalls;
if (q->header().device_id() != "tchl_arm") {
++agvProbes; return {grpc::StatusCode::NOT_FOUND, "not an arm"};
}
r->mutable_header()->set_success(true);
for (int i = 1; i <= 6; ++i) {
r->mutable_state()->add_name("TCHL_AXIS_" + std::to_string(i));
r->mutable_state()->add_position(i * 0.1);
r->mutable_state()->add_velocity(i * -0.001);
r->mutable_state()->add_effort(0);
}
return grpc::Status::OK;
}
grpc::Status getRobotState(grpc::ServerContext*, const cmvr::api::GetRobotState::Request*,
cmvr::api::GetRobotState::Response *r) override {
++stateCalls;
if (!modern) return {grpc::StatusCode::UNIMPLEMENTED, "legacy"};
r->mutable_header()->set_success(true);
auto *state = r->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);
for (int i = 1; i <= 6; ++i) {
state->mutable_actual_joint_state()->add_name("TCHL_AXIS_" + std::to_string(i));
state->mutable_actual_joint_state()->add_position(i * 0.2);
state->mutable_actual_joint_state()->add_velocity(0);
}
return grpc::Status::OK;
}
grpc::Status moveJ(grpc::ServerContext*, const cmvr::api::MoveJ::Request*, cmvr::api::MoveJ::Response*) override {
++controlCalls; return {grpc::StatusCode::PERMISSION_DENIED, "test prohibits motion"};
}
grpc::Status ListBaseFrame(grpc::ServerContext*, const cmvr::api::ListFrame::Request*, cmvr::api::ListFrame::Response*) override {
++frameCalls; return {grpc::StatusCode::UNIMPLEMENTED, "frameGetChildren must not be invoked"};
}
grpc::Status ListTCPFrame(grpc::ServerContext*, const cmvr::api::ListFrame::Request*, cmvr::api::ListFrame::Response*) override {
++frameCalls; return {grpc::StatusCode::UNIMPLEMENTED, "frameGetChildren must not be invoked"};
}
};
struct JointPointTestAccess {
static bool verifyTeaching(const QString &host, int port, Arm &mock) {
MainWindow window;
window.m_demoCheck->setChecked(false);
window.selectPage(1);
QString command;
bool success = false;
int results = 0;
QObject::connect(window.m_client, &RobotClient::commandFinished, &window,
[&](const QString &name, bool ok, const QString&) { command = name; success = ok; ++results; });
window.m_client->connectToServer(host, port, false);
if (!waitFor([&] { return window.m_connected && window.m_armIdEdit->text() == "tchl_arm"; })) return false;
const auto click = [&](QPushButton *button, const char *expected, bool expectedSuccess) {
const int previous = results;
button->click();
return waitFor([&] { return results > previous; }) && command == expected && success == expectedSuccess;
};
// Empty file names must not reach the controller.
window.m_trajectoryFileNameEdit->clear();
if (!click(window.m_startTrajectoryRecordingButton, "Start Trajectory Recording", false)
|| mock.teachingCalls != 0) return false;
window.m_trajectoryFileNameEdit->setText(" test_teaching.traj ");
if (!click(window.m_enterTeachingButton, "Enter Teaching Mode", true)
|| !click(window.m_startTrajectoryRecordingButton, "Start Trajectory Recording", true)
|| mock.recordedFile != "test_teaching.traj"
|| !click(window.m_stopTrajectoryRecordingButton, "Stop Trajectory Recording", true)
|| !click(window.m_exitTeachingButton, "Exit Teaching Mode", true)
|| !click(window.m_completeTeachingButton, "Complete Teaching", true)
|| mock.teachingCalls != 5) return false;
mock.rejectTeaching = true;
if (!click(window.m_enterTeachingButton, "Enter Teaching Mode", false)
|| window.m_deviceTeachingStateLabel->text() != QStringLiteral("进入示教失败")) return false;
window.m_client->disconnectFromServer();
pumpEvents(100);
fprintf(stderr, "PASS five teaching buttons, filename validation and controller error feedback\n");
return true;
}
static bool verifyManualTelemetry(const QString &host, int port, const QString &deviceId,
Arm *mock = nullptr, bool allowPower = false) {
MainWindow window;
window.m_demoCheck->setChecked(false);
window.m_hostEdit->setText(host);
window.m_portSpin->setValue(port);
window.selectPage(1);
int samples = 0, powerResults = 0;
bool powerSuccess = false;
QVariantMap lastState;
QObject::connect(window.m_client, &RobotClient::telemetryReceived, &window,
[&](const QString &id, const QVariantList&, const QVariantMap&, const QVariantMap &state) {
if (id == deviceId) { ++samples; lastState = state; }
});
QObject::connect(window.m_client, &RobotClient::commandFinished, &window,
[&](const QString &command, bool ok, const QString &detail) {
if (command == "Torque On") { ++powerResults; powerSuccess = ok; }
if (!ok || command == "Torque On")
fprintf(stderr, "UI command %s ok=%d %s\n", command.toUtf8().constData(), ok, detail.toUtf8().constData());
});
window.m_client->connectToServer(host, port, false);
if (!waitFor([&] { return window.m_connected && window.m_armIdEdit->text() == deviceId
&& window.m_activeArmJointNames.size() == 6; }, 10000)) {
fprintf(stderr, "FAIL UI connection or arm metadata\n"); return false;
}
pumpEvents(1300);
if (window.m_armTelemetryButton->isChecked() || samples || (mock && mock->stateCalls)) {
fprintf(stderr, "FAIL automatic telemetry on connection\n"); return false;
}
window.selectPage(0); window.selectPage(1);
window.m_jogModeTabs->setCurrentIndex(1);
window.m_client->requestArmFrames(deviceId); // Compatibility API must be cache-only.
pumpEvents(1300);
if (window.m_armTelemetryButton->isChecked() || samples || (mock && mock->frameCalls)) {
fprintf(stderr, "FAIL automatic page telemetry or frame RPC\n"); return false;
}
fprintf(stderr, "PASS UI enters arm page without telemetry or frame enumeration\n");
if (allowPower) {
window.m_torqueOnButton->click();
if (!waitFor([&] { return powerResults > 0; }, 40000) || !powerSuccess) {
fprintf(stderr, "FAIL power-on/enable result; not retrying\n"); return false;
}
}
window.m_armTelemetryButton->click();
if (!waitFor([&] { return samples >= 4 && window.m_latestArmJointPositions.size() == 6; }, 10000)) {
fprintf(stderr, "FAIL manual telemetry samples=%d\n", samples); return false;
}
fprintf(stderr, "PASS UI manual telemetry received %d samples, robotMode=%d poweredOn=%d fault=%d\n",
samples, lastState.value("robotMode").toInt(), lastState.value("poweredOn").toBool(),
lastState.value("fault").toBool());
if (allowPower && (!lastState.value("poweredOn").toBool()
|| !lastState.value("brakeReleased").toBool() || lastState.value("fault").toBool())) {
fprintf(stderr, "FAIL controller did not confirm enabled state\n"); return false;
}
window.m_armTelemetryButton->click();
pumpEvents(500);
const int stoppedSamples = samples;
pumpEvents(1300);
if (samples != stoppedSamples || window.m_armTelemetryButton->isChecked()) {
fprintf(stderr, "FAIL telemetry restarted after manual stop\n"); return false;
}
if (mock && (mock->frameCalls || mock->controlCalls)) return false;
fprintf(stderr, "PASS UI manual stop stays stopped across device refresh\n");
window.m_client->disconnectFromServer();
pumpEvents(100);
return true;
}
static bool verifyUnknownState(const QVariantList &joints) {
MainWindow window;
window.m_armIdEdit->setText("tchl_arm");
QStringList names;
for (const auto &v : joints) names << v.toMap().value("name").toString();
window.updateArmInfo("tchl_arm", {{"source", "getJointState"}, {"jointNames", names}, {"dof", 6}});
QVariantMap controllerState{{"connected", true}, {"poweredOn", true},
{"brakeReleased", false}, {"robotMode", 3}};
window.updateTelemetry("tchl_arm", joints, {}, controllerState);
if (window.m_servoStatusValue->text() != QStringLiteral("已上电 · 未使能")) return false;
controllerState["brakeReleased"] = true;
window.updateTelemetry("tchl_arm", joints, {}, controllerState);
if (window.m_servoStatusValue->text() != QStringLiteral("已使能 · 空闲")) return false;
controllerState["poweredOn"] = false;
controllerState["brakeReleased"] = false;
window.updateTelemetry("tchl_arm", joints, {}, controllerState);
if (window.m_servoStatusValue->text() != QStringLiteral("未使能")) return false;
window.m_servoStatusValue->setText(QStringLiteral("已使能"));
window.m_faultStatusValue->setText(QStringLiteral("正常"));
window.updateTelemetry("tchl_arm", joints, {}, {{"robotStateAvailable", false}});
return window.m_jointTable->rowCount() == 6
&& window.m_motionTable->rowCount() == 6
&& window.m_jointTable->item(0, 0)->text() == "TCHL_AXIS_1"
&& window.m_servoStatusValue->text() == QStringLiteral("服务端未提供")
&& window.m_faultStatusValue->text() == QStringLiteral("服务端未提供")
&& window.m_armDeviceSummary->text().contains(QStringLiteral("6轴"))
&& window.m_latestArmPose.isEmpty();
}
};
static bool verifyClient(const QString &host, int port, bool legacy, bool live, Arm *mock)
{
RobotClient client;
bool connected = false, infoReady = false;
QVariantList devices, joints;
QVariantMap info, state, pose;
int telemetry = 0;
QObject::connect(&client, &RobotClient::connectionChanged, &client,
[&](bool value, int, const QString &detail) {
connected = value;
fprintf(stderr, "connection=%d %s\n", value, detail.toUtf8().constData());
});
QObject::connect(&client, &RobotClient::systemStatusReceived, &client,
[&](double, double, double, const QVariantList &value) { devices = value; });
QObject::connect(&client, &RobotClient::armInfoReceived, &client,
[&](const QString &id, const QVariantMap &value) { if (id == "tchl_arm") { info = value; infoReady = true; } });
QObject::connect(&client, &RobotClient::telemetryReceived, &client,
[&](const QString &id, const QVariantList &j, const QVariantMap &p, const QVariantMap &s) {
if (id == "tchl_arm") { ++telemetry; joints = j; pose = p; state = s; }
});
client.connectToServer(host, port, false);
if (!waitFor([&] { return connected; })) { fprintf(stderr, "FAIL connect\n"); return false; }
client.requestSystemRefresh();
if (!waitFor([&] { return !devices.isEmpty(); })) { fprintf(stderr, "FAIL system discovery\n"); return false; }
bool found = false;
for (const auto &value : devices) {
auto item = value.toMap();
if (item.value("deviceId") == "tchl_arm") found = item.value("type").toInt() == cmvr::api::Robot;
if (item.value("deviceId") == "real_agv" && item.value("type").toInt() != cmvr::api::AGV) return false;
}
if (!found) { fprintf(stderr, "FAIL arm not identified\n"); return false; }
client.requestArmInfo("tchl_arm");
client.setArmTelemetry("tchl_arm", true);
if (!waitFor([&] { return infoReady && telemetry >= 4; })) {
fprintf(stderr, "FAIL info=%d telemetry=%d\n", infoReady, telemetry); return false;
}
const QStringList names = info.value("jointNames").toStringList();
if (names.size() != 6 || names.front() != "TCHL_AXIS_1" || joints.size() != 6) return false;
if (legacy) {
if (info.value("source") != "getJointState" || !info.value("manufacturer").toString().isEmpty()
|| state.value("robotStateAvailable", true).toBool() || state.contains("poweredOn") || !pose.isEmpty()) return false;
if (!live && (mock->stateCalls != 1 || mock->agvProbes != 1)) return false;
if (!JointPointTestAccess::verifyUnknownState(joints)) return false;
} else if (info.value("model") != "modern_arm" || !state.value("poweredOn").toBool()) return false;
if (!live && mock->controlCalls != 0) return false;
client.setArmTelemetry("tchl_arm", false);
client.disconnectFromServer();
qInfo() << "PASS arm info, discovery, telemetry:" << (live ? host : legacy ? "legacy mock" : "modern mock")
<< names << "positions" << joints;
fprintf(stderr, "PASS %s: six real joint names, info, telemetry and UI\n",
live ? "live" : legacy ? "legacy mock" : "modern mock");
return true;
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
app.setOrganizationName("CMVR Tests"); app.setApplicationName("Arm Compatibility Test");
ApplicationStyle::install(app);
if (app.arguments().contains("--live-204-teaching-contract")) {
auto channel = grpc::CreateChannel("192.168.0.204:50052", grpc::InsecureChannelCredentials());
auto stub = cmvr::api::ArmService::NewStub(channel);
cmvr::api::CommandHeader::Request request;
request.set_device_id("__cmvr_teaching_probe_missing__");
const auto probe = [&](const char *name, auto call) {
grpc::ClientContext context;
context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3));
cmvr::api::CommandHeader::Feedback response;
const auto status = call(&context, request, &response);
if (status.error_code() != grpc::StatusCode::NOT_FOUND || response.success()) return false;
fprintf(stderr, "PASS deployed %s exists and rejects unknown device without hardware access\n", name);
return true;
};
if (!probe("EnterTeachingMode", [&](auto *c, const auto &q, auto *r) { return stub->EnterTeachingMode(c, q, r); })
|| !probe("CompleteTeaching", [&](auto *c, const auto &q, auto *r) { return stub->CompleteTeaching(c, q, r); })
|| !probe("StopTrajectoryRecording", [&](auto *c, const auto &q, auto *r) { return stub->StopTrajectoryRecording(c, q, r); })
|| !probe("ExitTeachingMode", [&](auto *c, const auto &q, auto *r) { return stub->ExitTeachingMode(c, q, r); })) return 6;
cmvr::api::StartTrajectoryRecording::Request recording;
*recording.mutable_header() = request;
recording.set_file_name("probe_not_created.traj");
cmvr::api::StartTrajectoryRecording::Response response;
grpc::ClientContext context;
context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3));
const auto status = stub->StartTrajectoryRecording(&context, recording, &response);
if (status.error_code() != grpc::StatusCode::NOT_FOUND || response.header().success()) return 6;
fprintf(stderr, "PASS deployed StartTrajectoryRecording exists and rejects unknown device without hardware access\n");
return 0;
}
if (app.arguments().contains("--live-204"))
return JointPointTestAccess::verifyManualTelemetry("192.168.0.204", 50052, "aubo_arm", nullptr,
app.arguments().contains("--allow-power")) ? 0 : 3;
if (app.arguments().contains("--live")) return verifyClient("192.168.0.234", 50052, true, true, nullptr) ? 0 : 1;
for (bool modern : {false, true}) {
System system; Arm arm; arm.modern = modern;
grpc::ServerBuilder builder; int port = 0;
builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&system); builder.RegisterService(&arm);
auto server = builder.BuildAndStart();
if (!server || !verifyClient("127.0.0.1", port, !modern, false, &arm)) return 2;
if (modern) {
arm.stateCalls = 0; arm.frameCalls = 0;
if (!JointPointTestAccess::verifyManualTelemetry("127.0.0.1", port, "tchl_arm", &arm)) return 4;
if (!JointPointTestAccess::verifyTeaching("127.0.0.1", port, arm)) return 5;
}
server->Shutdown();
}
return 0;
}