CmvrControlStation/tests/agvdemo_map_test.cpp

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

#include "agvmapdocument.h"
#include "robotclient.h"
#include <QElapsedTimer>
#include <QGuiApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QResource>
#include <QThread>
#include <QtMath>
#include <cmath>
#include <functional>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV Demo map test failed: %s", message);
}
void waitUntil(const std::function<bool()> &ready)
{
QElapsedTimer timer;
timer.start();
while (!ready() && timer.elapsed() < 5000) {
QCoreApplication::processEvents();
QThread::msleep(1);
}
require(ready(), "asynchronous Demo request completed");
}
bool close(double a, double b)
{
return std::abs(a - b) < 1e-9;
}
}
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Q_INIT_RESOURCE(resources);
RobotClient client;
const QString device = QStringLiteral("demo_map_test");
const QString map = QStringLiteral("demo_map");
bool connected = false;
QImage image;
QVariantMap metadata;
QVariantMap state;
QString content;
quint64 completedRead = 0;
quint64 completedSave = 0;
QVariantList stations;
int inventories = 0;
int contextualInventories = 0;
int stateUpdates = 0;
QObject::connect(&client, &RobotClient::connectionChanged,
[&](bool value, int, const QString &) { connected = value; });
QObject::connect(&client, &RobotClient::agvMapContentReceived,
[&](quint64 id, const QString &receivedDevice, const QString &receivedMap,
const QString &receivedContent, bool success, const QString &) {
require(success && receivedDevice == device && receivedMap == map,
"Demo read returns the requested device/map");
completedRead = id;
content = receivedContent;
});
QObject::connect(&client, &RobotClient::agvMapSaveFinished,
[&](quint64 id, const QString &, const QString &, bool success, const QString &) {
require(success, "Demo save succeeds");
completedSave = id;
});
QObject::connect(&client, &RobotClient::agvMapFrameReceived,
[&](const QImage &frame, const QVariantMap &values, const QString &detail) {
image = frame;
metadata = values;
require(detail.contains(QStringLiteral("演示")), "raster is explicitly labeled Demo");
});
QObject::connect(&client, &RobotClient::agvStateReceived,
[&](const QVariantMap &values, const QVariantMap &) { state = values; ++stateUpdates; });
QObject::connect(&client, &RobotClient::agvInventoryReceived,
[&](const QStringList &, const QVariantList &values) {
stations = values;
++inventories;
});
QObject::connect(&client, &RobotClient::agvInventoryReceivedForContext,
[&](const QVariantMap &context, const QStringList &, const QVariantList &) {
require(context.value(QStringLiteral("deviceId")).toString() == device
&& context.value(QStringLiteral("endpoint")).toString() == QStringLiteral("localhost:50052")
&& context.value(QStringLiteral("demo")).toBool()
&& context.value(QStringLiteral("available")).toBool(),
"typed inventory identifies the current Demo device/endpoint");
++contextualInventories;
});
client.connectToServer(QStringLiteral("localhost"), 50052, true);
waitUntil([&]() { return connected; });
client.requestAgvRefresh(device);
client.requestAgvMapContent(1, device, map);
client.startAgvMapStream(device, map, 2, true, false);
waitUntil([&]() { return completedRead == 1 && !image.isNull() && !state.isEmpty(); });
require(state.value(QStringLiteral("connected")).toBool()
&& state.value(QStringLiteral("mode")).toInt() == 2,
"connected Demo robot reports Idle mode rather than Disconnected");
require(state.value(QStringLiteral("deviceId")).toString() == device
&& state.value(QStringLiteral("endpoint")).toString() == QStringLiteral("localhost:50052")
&& state.value(QStringLiteral("demo")).toBool()
&& state.value(QStringLiteral("available")).toBool(),
"available state identifies its device, endpoint and Demo context");
require(metadata.value(QStringLiteral("deviceId")).toString() == device
&& metadata.value(QStringLiteral("mapId")).toString() == map,
"frame identifies the requested device and map for late-frame filtering");
const QJsonObject root = QJsonDocument::fromJson(content.toUtf8()).object();
const QJsonObject header = root.value(QStringLiteral("header")).toObject();
const QJsonObject minimum = header.value(QStringLiteral("min_pos")).toObject();
const QJsonObject maximum = header.value(QStringLiteral("max_pos")).toObject();
const double resolution = metadata.value(QStringLiteral("resolution")).toDouble();
const double renderScale = metadata.value(QStringLiteral("renderScale"), 1.0).toDouble();
const double originX = metadata.value(QStringLiteral("originX")).toDouble();
const double originY = metadata.value(QStringLiteral("originY")).toDouble();
require(header.value(QStringLiteral("source")).toString() == QStringLiteral("demo")
&& metadata.value(QStringLiteral("demo")).toBool(), "raw and frame identify Demo data");
require(resolution > 0.0 && renderScale > 0.0 && image.hasAlphaChannel(),
"scan raster has valid resolution/scale and transparent free space");
require(close(header.value(QStringLiteral("resolution")).toDouble(), resolution)
&& close(minimum.value(QStringLiteral("x")).toDouble(), originX)
&& close(minimum.value(QStringLiteral("y")).toDouble(), originY),
"raw origin and resolution match stream metadata");
require(close(maximum.value(QStringLiteral("x")).toDouble(), originX + image.width() * resolution / renderScale)
&& close(maximum.value(QStringLiteral("y")).toDouble(), originY + image.height() * resolution / renderScale),
"raw world bounds cover the complete stream image");
const auto projected = [&](double x, double y) {
return QPointF((x - originX) * renderScale / resolution,
image.height() - (y - originY) * renderScale / resolution);
};
const QPointF robot = projected(state.value(QStringLiteral("x")).toDouble(),
state.value(QStringLiteral("y")).toDouble());
const QPointF home = projected(0.0, 0.0);
const QRectF safeBounds(20, 20, image.width() - 40, image.height() - 40);
require(safeBounds.contains(robot) && safeBounds.contains(home), "robot and HOME have margin inside map");
const QJsonArray points = root.value(QStringLiteral("normal_pos_list")).toArray();
require(points.size() > 3000, "raw content contains actual occupancy scan samples");
int visibleOccupied = 0;
for (const QJsonValue &value : points) {
const QJsonObject point = value.toObject();
const QPointF position = projected(point.value(QStringLiteral("x")).toDouble(),
point.value(QStringLiteral("y")).toDouble());
require(QRectF(image.rect()).contains(position),
"all raw wall points project inside the frame");
const QPoint cell = QPoint(qFloor(position.x()), qFloor(position.y()));
if (image.rect().contains(cell) && image.pixelColor(cell).alpha() > 0)
++visibleOccupied;
}
require(image.pixelColor(robot.toPoint()).alpha() == 0
&& image.pixelColor(home.toPoint()).alpha() == 0,
"free cells under robot and HOME remain transparent for overlays");
require(visibleOccupied > points.size() / 2,
"occupied scan samples remain visible in raster");
AgvMapDocument document;
QString error;
require(document.load(content, &error) && document.hasStation(QStringLiteral("HOME")),
"complete Demo raw content remains editable and retains HOME");
const QStringList originalStationIds = document.stationIds();
const QVariantList originalRoutes = document.routes();
require(originalStationIds.size() == 11 && originalRoutes.size() == 20,
"Demo has named stations and both directions of its routes");
require(document.addStation(QStringLiteral("ADDED"), 1.8, -0.4, 0.0, &error)
&& document.addRoute(QStringLiteral("HOME-ADDED"), QStringLiteral("HOME"),
QStringLiteral("ADDED"), false, &error),
"can append a station and route to the Demo map");
const QString quotedName = QStringLiteral("\"工位1\"");
require(document.setStationName(QStringLiteral("LM1"), quotedName, &error),
"can save a station name containing literal quotation marks");
const QString saved = document.content();
client.saveAgvMapContent(2, device, map, saved);
waitUntil([&]() { return completedSave == 2; });
client.requestAgvMapContent(3, device, map);
client.requestAgvInventory(device);
waitUntil([&]() { return completedRead == 3 && inventories == 1 && contextualInventories == 1; });
require(content == saved, "reading does not regenerate or overwrite saved Demo content");
require(document.load(content, &error)
&& document.stationIds().size() == originalStationIds.size() + 1
&& document.routes().size() == originalRoutes.size() + 1,
"saved map retains original stations and routes alongside appended objects");
for (const QString &id : originalStationIds)
require(document.hasStation(id), "every original Demo station survives save/reload");
for (const QVariant &route : originalRoutes)
require(document.routes().contains(route), "every original Demo route survives save/reload");
require(QJsonDocument::fromJson(content.toUtf8()).object().value(QStringLiteral("normal_pos_list")).toArray() == points,
"scan samples are unchanged by station/route edits");
bool addedVisible = false;
bool homeNameVisible = false;
bool literalNameVisible = false;
for (const QVariant &value : stations) {
const QVariantMap station = value.toMap();
const QString id = station.value(QStringLiteral("id")).toString();
if (id == QStringLiteral("ADDED"))
addedVisible = station.value(QStringLiteral("name")).toString() == id;
if (id == QStringLiteral("HOME"))
homeNameVisible = station.value(QStringLiteral("name")).toString() == QStringLiteral("起点");
if (id == QStringLiteral("LM1"))
literalNameVisible = station.value(QStringLiteral("name")).toString() == quotedName;
}
require(addedVisible, "saved Demo station is available to navigation inventory");
require(homeNameVisible && literalNameVisible,
"inventory uses descriptions as names while preserving IDs and literal quotes");
if (argc > 1)
require(image.save(QString::fromLocal8Bit(argv[1])), "optional raster preview was saved");
client.disconnectFromServer();
waitUntil([&]() { return !connected; });
const int previousStates = stateUpdates;
client.requestAgvRefresh(device);
waitUntil([&]() { return stateUpdates > previousStates; });
require(!state.value(QStringLiteral("available")).toBool()
&& !state.value(QStringLiteral("error")).toString().isEmpty()
&& state.value(QStringLiteral("deviceId")).toString() == device,
"refresh failure explicitly reports unavailable state with context/error");
client.connectToServer(QStringLiteral("localhost"), 50052, true);
waitUntil([&]() { return connected; });
client.requestAgvRefresh(device);
waitUntil([&]() { return state.value(QStringLiteral("available")).toBool(); });
require(state.value(QStringLiteral("connected")).toBool()
&& state.value(QStringLiteral("mode")).toInt() == 2,
"successful Demo refresh restores available Idle state after a failure");
qInfo("PASS: Demo Idle/context/failure recovery, scan bounds, transparent free space, saved content and typed inventory");
return 0;
}