CmvrControlStation/tests/agvmanualmotion_test.cpp
Codex 22620db699 feat(agv): merge local map editing and manual controls
Bring local station and route editing/deletion, verified map saves, confirmed switches, direct map transport and manual velocity ramps onto latest main. Preserve upstream non-AGV implementations, interface definitions and startup behavior.

Validated with the existing qmake Release build, AGV map/UI/manual-motion tests, loopback upload/deletion/SEER transport tests and function-level retention audits.
2026-11-10 16:10:46 +08:00

422 lines
19 KiB
C++

#include "mainwindow.h"
#include "robotclient.h"
#include <QApplication>
#include <QCheckBox>
#include <QDoubleSpinBox>
#include <QElapsedTimer>
#include <QEvent>
#include <QFile>
#include <QKeyEvent>
#include <QLineEdit>
#include <QPushButton>
#include <QScrollArea>
#include <QSettings>
#include <QTabWidget>
#include <QThread>
#include <QTimer>
#include <cmath>
#include <cstdio>
#include <functional>
#include <vector>
namespace {
constexpr double epsilon = 1e-8;
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV manual motion test failed: %s", message);
}
void pump(int milliseconds)
{
QElapsedTimer clock;
clock.start();
do {
QApplication::processEvents();
QThread::msleep(2);
} while (clock.elapsed() < milliseconds);
}
void waitFor(const std::function<bool()> &condition, const char *message,
int milliseconds = 3500)
{
QElapsedTimer clock;
clock.start();
while (!condition() && clock.elapsed() < milliseconds)
pump(3);
require(condition(), message);
}
template<typename T>
T *child(QObject &parent, const char *name)
{
T *result = parent.findChild<T *>(QString::fromLatin1(name));
require(result != nullptr, name);
return result;
}
QPushButton *button(QObject &parent, const QString &text)
{
for (QPushButton *candidate : parent.findChildren<QPushButton *>())
if (candidate->text() == text)
return candidate;
qFatal("AGV manual motion test failed: missing button %s", qPrintable(text));
return nullptr;
}
void press(QPushButton *control)
{
require(control->isEnabled(), "test direction control is enabled");
require(QMetaObject::invokeMethod(control, "pressed", Qt::DirectConnection),
"direction pressed signal is invoked");
}
void release(QPushButton *control)
{
require(QMetaObject::invokeMethod(control, "released", Qt::DirectConnection),
"direction released signal is invoked");
}
void key(QWidget &target, QEvent::Type kind, int code)
{
QKeyEvent event(kind, code, Qt::NoModifier);
QApplication::sendEvent(&target, &event);
}
struct VelocityFrame {
quint64 id;
QString device;
double vx;
double vy;
double wz;
};
bool zero(const VelocityFrame &frame)
{
return std::abs(frame.vx) <= epsilon && std::abs(frame.vy) <= epsilon
&& std::abs(frame.wz) <= epsilon;
}
// This harness disconnects the ordinary Qt outbound dispatcher before any
// request is sent. Every acknowledgement is synthetic; no TCP/gRPC connection
// is opened and no vehicle command can leave the test process.
class Recorder : public QObject {
public:
explicit Recorder(RobotClient *source) : client(source)
{
QObject::disconnect(client, &RobotClient::agvManualVelocityRequested, client, nullptr);
QObject::disconnect(client, &RobotClient::agvActionRequested, nullptr, nullptr);
QObject::disconnect(client, &RobotClient::agvRefreshRequested, nullptr, nullptr);
QObject::disconnect(client, &RobotClient::agvInventoryRequested, nullptr, nullptr);
QObject::disconnect(client, &RobotClient::agvMapStreamStartRequested, nullptr, nullptr);
QObject::disconnect(client, &RobotClient::agvMapStreamStopRequested, nullptr, nullptr);
QObject::disconnect(client, &RobotClient::agvMapContentRequested, nullptr, nullptr);
QObject::disconnect(client, &RobotClient::connectRequested, nullptr, nullptr);
QObject::connect(client, &RobotClient::agvManualVelocityRequested, this,
[this](quint64 id, const QString &device, double vx, double vy, double wz) {
frames.push_back({id, device, vx, vy, wz});
if (automaticReplies)
QTimer::singleShot(0, this, [this, id]() {
client->agvManualVelocityFinished(id, true, QStringLiteral("synthetic ACK"));
});
});
QObject::connect(client, &RobotClient::agvActionRequested, this,
[this](const QString &device, const QString &action) {
actions.push_back({device, action});
});
}
void acknowledge(quint64 id, bool success = true)
{
client->agvManualVelocityFinished(id, success,
success ? QStringLiteral("synthetic ACK") : QStringLiteral("synthetic failure"));
}
int count(const QString &action) const
{
int result = 0;
for (const auto &entry : actions)
if (entry.second == action)
++result;
return result;
}
RobotClient *client;
bool automaticReplies = true;
std::vector<VelocityFrame> frames;
std::vector<std::pair<QString, QString>> actions;
};
void uiConnection(MainWindow &window, bool connected = true)
{
require(QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection,
Q_ARG(bool, connected), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("isolated manual UI fixture"))),
"synthetic UI connection is injected");
}
void page(MainWindow &window, int index)
{
require(QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection,
Q_ARG(int, index)), "page selection is invoked");
}
}
int main(int argc, char *argv[])
{
qInstallMessageHandler([](QtMsgType, const QMessageLogContext &, const QString &message) {
const QByteArray bytes = message.toUtf8();
std::fprintf(stderr, "%s\n", bytes.constData());
std::fflush(stderr);
});
QApplication app(argc, argv);
Q_INIT_RESOURCE(resources);
app.setOrganizationName(QStringLiteral("CMVR-Tests"));
app.setApplicationName(QStringLiteral("AGV Manual Motion"));
app.setStyle(QStringLiteral("Fusion"));
QFile styleFile(QStringLiteral(":/styles.qss"));
require(styleFile.open(QIODevice::ReadOnly), "production stylesheet is available in the test resources");
app.setStyleSheet(QString::fromUtf8(styleFile.readAll()));
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
app.applicationDirPath() + QStringLiteral("/agv-manual-test-settings"));
{
QSettings settings;
settings.clear();
settings.setValue(QStringLiteral("connection/demo"), false);
settings.setValue(QStringLiteral("connection/host"), QStringLiteral("127.0.0.1"));
settings.setValue(QStringLiteral("agv/device"), QStringLiteral("manual_fixture_A"));
settings.sync();
require(settings.status() == QSettings::NoError, "isolated fixture settings are written");
}
{
MainWindow initial;
const char *names[] = {"agvLinearAccelerationSpin", "agvLinearDecelerationSpin",
"agvAngularAccelerationSpin", "agvAngularDecelerationSpin"};
const double defaults[] = {0.2, 0.3, 0.5, 0.8};
const double persisted[] = {0.23, 0.37, 0.57, 0.91};
for (int i = 0; i < 4; ++i) {
auto *spin = child<QDoubleSpinBox>(initial, names[i]);
require(std::abs(spin->value() - defaults[i]) < epsilon,
"first launch has the four expected positive ramp limits");
require(spin->minimum() > 0.0, "ramp limits cannot be zero or negative");
spin->setValue(persisted[i]);
}
}
MainWindow window;
auto *client = window.findChild<RobotClient *>();
require(client != nullptr, "MainWindow has its RobotClient");
Recorder record(client);
auto *id = child<QLineEdit>(window, "agvIdEdit");
auto *host = child<QLineEdit>(window, "hostEdit");
auto *demo = child<QCheckBox>(window, "demoCheck");
auto *tools = child<QTabWidget>(window, "agvControlTools");
auto *tabs = child<QTabWidget>(window, "agvTabs");
auto *timer = child<QTimer>(window, "agvManualVelocityTimer");
auto *linearAcceleration = child<QDoubleSpinBox>(window, "agvLinearAccelerationSpin");
auto *linearDeceleration = child<QDoubleSpinBox>(window, "agvLinearDecelerationSpin");
auto *angularAcceleration = child<QDoubleSpinBox>(window, "agvAngularAccelerationSpin");
auto *angularDeceleration = child<QDoubleSpinBox>(window, "agvAngularDecelerationSpin");
require(std::abs(linearAcceleration->value() - 0.23) < epsilon
&& std::abs(linearDeceleration->value() - 0.37) < epsilon
&& std::abs(angularAcceleration->value() - 0.57) < epsilon
&& std::abs(angularDeceleration->value() - 0.91) < epsilon,
"all four ramp limits survive construction callbacks and relaunch");
linearAcceleration->setValue(0.2);
linearDeceleration->setValue(0.3);
angularAcceleration->setValue(0.5);
angularDeceleration->setValue(0.8);
child<QDoubleSpinBox>(window, "agvVxSpin")->setValue(0.2);
child<QDoubleSpinBox>(window, "agvVySpin")->setValue(0.2);
child<QDoubleSpinBox>(window, "agvWzSpin")->setValue(0.3);
require(!demo->isChecked(), "test never enables a background real or Demo connection");
window.resize(1500, 1000);
window.show();
uiConnection(window);
page(window, 3);
tools->setCurrentIndex(1);
window.setFocus();
pump(100);
auto *agvPage = child<QWidget>(window, "agvPage");
auto *forward = button(*agvPage, QStringLiteral("前进 (W)"));
auto *backward = button(*agvPage, QStringLiteral("后退 (S)"));
auto *stop = button(*agvPage, QStringLiteral("停止"));
auto *hardStop = button(*agvPage, QStringLiteral("停止速度"));
auto *emergency = button(*agvPage, QStringLiteral("AGV 急停"));
auto *clearFault = button(*agvPage, QStringLiteral("清除故障"));
qInfo("PASS manual UI: positive limits and isolated settings persist across relaunch");
const auto waitMoving = [&](size_t begin) {
waitFor([&] { return record.frames.size() >= begin + 4
&& record.frames.back().vx >= 0.06; },
"held direction accelerates over multiple acknowledged packets");
};
const auto checkQuiet = [&] {
const size_t before = record.frames.size();
pump(250);
require(record.frames.size() == before && !timer->isActive(),
"stopped manual session emits no later velocity packets");
};
const auto startForward = [&]() {
const size_t begin = record.frames.size();
press(forward);
waitMoving(begin);
require(record.frames[begin].vx > 0.0 && record.frames[begin].vx < 0.2,
"first forward packet ramps below the target speed");
return begin;
};
size_t begin = startForward();
for (size_t i = begin + 1; i < record.frames.size(); ++i)
require(record.frames[i].vx >= record.frames[i - 1].vx - epsilon
&& record.frames[i].vx - record.frames[i - 1].vx <= 0.030001,
"linear ramp is monotonic and bounded by its configured acceleration");
const size_t releaseAt = record.frames.size();
const int priorStops = record.count(QStringLiteral("StopVelocity"));
release(forward);
waitFor([&] { return record.count(QStringLiteral("StopVelocity")) > priorStops; },
"ordinary release completes braking and relinquishes velocity control");
require(record.frames.size() > releaseAt && record.frames[releaseAt].vx > 0.0
&& zero(record.frames.back()), "ordinary release sends braking steps before a final zero");
for (size_t i = releaseAt; i < record.frames.size(); ++i)
require(record.frames[i].vx >= -epsilon
&& record.frames[i].vx <= record.frames[i - 1].vx + epsilon
&& record.frames[i - 1].vx - record.frames[i].vx <= 0.045001,
"ordinary stop obeys the separate deceleration limit without reversing");
checkQuiet();
begin = startForward();
const size_t reverseAt = record.frames.size();
press(backward);
// Releasing the old control must not cancel the newer held direction.
release(forward);
waitFor([&] { return record.frames.back().vx < -0.02; }, "reverse direction eventually accelerates");
bool passedZero = false;
for (size_t i = reverseAt; i < record.frames.size(); ++i) {
passedZero = passedZero || zero(record.frames[i]);
require(record.frames[i].vx >= 0.0 || passedZero,
"reversal acknowledges a zero packet before producing the opposite direction");
}
stop->click();
waitFor([&] { return !timer->isActive(); }, "center stop softly completes a reversed motion");
require(zero(record.frames.back()), "center stop finishes with zero velocity");
qInfo("PASS manual UI: acceleration, release braking, center stop and zero-before-reversal");
window.setFocus();
begin = record.frames.size();
key(window, QEvent::KeyPress, Qt::Key_W);
waitMoving(begin);
linearAcceleration->setFocus();
key(*linearAcceleration, QEvent::KeyRelease, Qt::Key_W);
waitFor([&] { return !timer->isActive(); }, "held keyboard release is honored after input focus changes");
window.setFocus();
begin = record.frames.size();
key(window, QEvent::KeyPress, Qt::Key_E);
waitFor([&] { return record.frames.size() >= begin + 3; }, "held rotation key generates ramped packets");
require(record.frames[begin].wz < 0.0 && record.frames[begin].wz > -0.3,
"rotation uses a gradual first angular velocity");
key(window, QEvent::KeyRelease, Qt::Key_E);
waitFor([&] { return !timer->isActive(); }, "rotation release completes angular braking");
require(zero(record.frames.back()), "angular braking reaches zero");
qInfo("PASS manual UI: keyboard W/E and release after an editor gains focus");
record.automaticReplies = false;
begin = record.frames.size();
press(forward);
waitFor([&] { return record.frames.size() > begin; }, "delayed-ACK fixture sends its first packet");
const VelocityFrame delayed = record.frames.back();
pump(350);
require(record.frames.size() == begin + 1, "one in-flight packet prevents timer backlog while awaiting ACK");
record.acknowledge(delayed.id);
waitFor([&] { return record.frames.size() == begin + 2; }, "matching ACK admits one next ramp packet");
require(record.frames.back().vx - delayed.vx <= 0.030001,
"delayed acknowledgement cannot create a catch-up speed jump");
const quint64 failedId = record.frames.back().id;
record.acknowledge(failedId, false);
require(!timer->isActive(), "failed manual acknowledgement immediately ends the ramp");
record.acknowledge(delayed.id);
checkQuiet();
qInfo("PASS manual UI: delayed ACK has no backlog, elapsed-time cap and failure aborts without revival");
begin = record.frames.size();
press(forward);
waitFor([&] { return record.frames.size() == begin + 1; }, "timeout fixture sends one packet");
const quint64 timeoutId = record.frames.back().id;
waitFor([&] { return !timer->isActive(); }, "missing ACK times out and hard-stops", 1500);
record.acknowledge(timeoutId);
checkQuiet();
record.automaticReplies = true;
const auto assertHardStop = [&](const std::function<void()> &trigger, const char *description) {
startForward();
const size_t before = record.frames.size();
const int stopsBefore = record.count(QStringLiteral("StopVelocity"));
trigger();
require(!timer->isActive(), description);
require(record.count(QStringLiteral("StopVelocity")) > stopsBefore,
"hard safety transition requests immediate velocity stop");
pump(220);
require(record.frames.size() == before, "hard stop sends no deceleration or later nonzero packets");
};
const size_t beforeFaultActions = record.actions.size();
assertHardStop([&] { clearFault->click(); }, "another AGV action immediately ends manual control");
require(record.actions.size() >= beforeFaultActions + 2
&& record.actions[beforeFaultActions].second == QStringLiteral("StopVelocity")
&& record.actions[beforeFaultActions + 1].second == QStringLiteral("ClearFault"),
"manual stop is queued before the action that takes over control");
assertHardStop([&] { hardStop->click(); }, "explicit stop-velocity button immediately stops the timer");
startForward();
const size_t emergencyAt = record.frames.size();
const int emergencies = record.count(QStringLiteral("EmergencyStop"));
emergency->click();
require(!timer->isActive() && record.count(QStringLiteral("EmergencyStop")) == emergencies + 1,
"emergency bypasses the ramp and dispatches immediately");
pump(220);
require(record.frames.size() == emergencyAt, "emergency cannot be followed by a timer-generated nonzero packet");
assertHardStop([&] { QEvent event(QEvent::WindowDeactivate); QApplication::sendEvent(&window, &event); },
"window deactivation immediately stops the timer");
assertHardStop([&] { page(window, 0); }, "leaving AGV immediately stops the timer");
page(window, 3);
assertHardStop([&] { tools->setCurrentIndex(0); }, "hiding manual control sidebar tab immediately stops the timer");
const size_t hiddenManualAt = record.frames.size();
window.setFocus();
key(window, QEvent::KeyPress, Qt::Key_W);
pump(180);
key(window, QEvent::KeyRelease, Qt::Key_W);
require(record.frames.size() == hiddenManualAt && !timer->isActive(),
"keyboard cannot restart manual motion while its sidebar tab is hidden");
tools->setCurrentIndex(1);
assertHardStop([&] { tabs->setCurrentIndex(1); }, "hiding control workspace tab immediately stops the timer");
tabs->setCurrentIndex(0);
assertHardStop([&] { client->agvMapDirectBusyChanged(true); }, "map direct operation immediately stops the timer");
client->agvMapDirectBusyChanged(false);
const QString oldDevice = id->text();
assertHardStop([&] { id->setText(QStringLiteral("manual_fixture_B")); },
"changing the selected device immediately stops the timer");
require(!record.actions.empty() && record.actions.back().first == oldDevice,
"device change stops the device that actually owned the manual session");
uiConnection(window);
assertHardStop([&] { host->setText(QStringLiteral("127.0.0.2")); },
"changing connection source immediately stops the timer");
uiConnection(window);
startForward();
uiConnection(window, false);
require(!timer->isActive(), "connection loss immediately clears the ramp");
checkQuiet();
qInfo("PASS manual UI: timeout, explicit stop, emergency, lost focus, hidden tabs/page, map busy, device/source changes and disconnect");
qInfo("PASS AGV manual motion UI: all requests and ACKs remained inside this isolated process");
if (argc > 1) {
uiConnection(window);
auto *sidebar = child<QScrollArea>(window, "agvControlSidebar");
sidebar->ensureWidgetVisible(angularDeceleration);
pump(40);
require(window.grab().save(QString::fromLocal8Bit(argv[1])),
"optional manual settings screenshot is exported");
}
return 0;
}