CmvrControlStation/tests/agvmapstream_fallback_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

645 lines
33 KiB
C++

#include "robotclient.h"
#include "cmvr/api/agv_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QElapsedTimer>
#include <QDateTime>
#include <QGuiApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QThread>
#include <QtMath>
#include <atomic>
#include <chrono>
#include <cmath>
#include <functional>
#include <map>
#include <mutex>
#include <thread>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV map stream fallback test failed: %s", message);
}
void waitUntil(const std::function<bool()> &ready, const char *message)
{
QElapsedTimer timer;
timer.start();
while (!ready() && timer.elapsed() < 5000) {
QCoreApplication::processEvents();
QThread::msleep(1);
}
require(ready(), message);
}
bool close(double left, double right)
{
return std::abs(left - right) < 1e-9;
}
QJsonObject point(double x, double y)
{
return {{QStringLiteral("x"), x}, {QStringLiteral("y"), y}};
}
QString rawMap(const QString &id)
{
const bool second = id == QStringLiteral("B");
const double minX = second ? 20.0 : -2.0;
const double minY = second ? 10.0 : -1.0;
const double maxX = second ? 24.0 : 3.0;
const double maxY = second ? 12.0 : 2.0;
const QJsonObject station{
{QStringLiteral("className"), QStringLiteral("LandMark")},
{QStringLiteral("instanceName"), QStringLiteral("HOME_") + id},
{QStringLiteral("description"), QStringLiteral("Station ") + id},
{QStringLiteral("pos"), point(second ? 22.0 : 0.5, second ? 11.0 : 0.5)},
{QStringLiteral("dir"), second ? 0.5 : 0.0}};
const QJsonObject root{
{QStringLiteral("header"), QJsonObject{
{QStringLiteral("mapName"), id},
{QStringLiteral("mapType"), QStringLiteral("2D-Map")},
{QStringLiteral("resolution"), second ? 0.5 : 0.25},
{QStringLiteral("minPos"), point(minX, minY)},
{QStringLiteral("maxPos"), point(maxX, maxY)}}},
{QStringLiteral("normalPosList"), QJsonArray{
point(minX, minY), point(maxX, maxY),
point(second ? 21.0 : 0.0, second ? 11.0 : 1.0)}},
{QStringLiteral("advancedPointList"), QJsonArray{station}},
{QStringLiteral("advancedCurveList"), QJsonArray{}}};
return QString::fromUtf8(QJsonDocument(root).toJson(QJsonDocument::Compact));
}
class FakeAgvService final : public cmvr::api::AgvService::Service
{
public:
grpc::Status downloadMap(grpc::ServerContext *,
const cmvr::api::AgvMapCommand::Request *request,
cmvr::api::AgvMapCommand::Feedback *response) override
{
const std::string name = request->map_name();
{
std::lock_guard<std::mutex> guard(m_mutex);
++m_downloads[name];
m_downloadDevices[name] = request->header().device_id();
}
if (name == "REJECTED_CURRENT" || name == "DOWNLOAD_FAIL" || name == "GRID_ONLY"
|| name == "RAW_SILENT" || name == "PARTIAL_GRID" || name == "WRONG_GRID") {
response->mutable_header()->set_success(false);
response->mutable_header()->set_error_message("fake raw map download denied");
return grpc::Status::OK;
}
response->mutable_header()->set_success(true);
response->set_content(rawMap(QString::fromStdString(name == "MISMATCH" ? "A" : name)).toStdString());
return grpc::Status::OK;
}
grpc::Status streamMap(grpc::ServerContext *context,
const cmvr::api::AgvMapStreamCommand::Request *request,
grpc::ServerWriter<cmvr::api::AgvMapStreamCommand::Feedback> *writer) override
{
const std::string name = request->map_name();
{
std::lock_guard<std::mutex> guard(m_mutex);
m_lastIncremental[name] = request->incremental();
}
if (name == "HOLD_OPEN") {
++m_heldStreamsStarted;
// Much longer than the client test's stop budget. This stream
// never writes or closes on its own during a successful test.
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);
while (!context->IsCancelled() && std::chrono::steady_clock::now() < deadline)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (context->IsCancelled())
++m_heldStreamCancellations;
return grpc::Status::OK;
}
if (name == "PREVIEW_ONLY" || name == "RAW_SILENT") {
++m_previewStreamsStarted;
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(4);
// Keep the stream open without sending a unified frame. The
// selected raw map must be visible before this reader has data.
while (!context->IsCancelled() && std::chrono::steady_clock::now() < deadline)
std::this_thread::sleep_for(std::chrono::milliseconds(2));
if (context->IsCancelled())
++m_previewStreamCancellations;
return grpc::Status::OK;
}
if (name == "HEADER_FAIL") {
cmvr::api::AgvMapStreamCommand::Feedback failure;
failure.mutable_header()->set_success(false);
failure.mutable_header()->set_error_message("fake controller rejected stream map");
writer->Write(failure);
// A failure must terminate the reader rather than silently waiting
// for another frame. Bound the fixture so a regression also exits.
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
while (!context->IsCancelled() && std::chrono::steady_clock::now() < deadline)
std::this_thread::sleep_for(std::chrono::milliseconds(2));
if (context->IsCancelled())
++m_headerFailureCancellations;
return grpc::Status::OK;
}
// A controller may keep reporting its old current-map id while a
// named preview of B is requested. Raw fallback must still read B.
const std::string actualName = name.empty() ? "REJECTED_CURRENT"
: name == "B" || name == "WRONG_GRID" ? "A" : name;
for (quint64 sequence = 1; sequence <= 3; ++sequence) {
cmvr::api::AgvMapStreamCommand::Feedback frame;
frame.mutable_header()->set_success(true);
auto *update = frame.mutable_update();
update->set_map_id(actualName);
update->set_sequence(sequence);
update->set_timestamp(1720000000.0 + sequence);
update->set_dimension(cmvr::msgs::AGV_MAP_2D);
update->set_update_type(cmvr::msgs::AGV_MAP_UPDATE_SNAPSHOT);
// Reproduce the old adapter's successful but empty unified map.
update->mutable_map_2d()->set_width(0);
update->mutable_map_2d()->set_height(0);
if (name == "GRID_ONLY" || name == "SAVED_GRID" || name == "PARTIAL_GRID"
|| name == "WRONG_GRID") {
auto *grid = update->mutable_map_2d();
grid->set_width(2);
grid->set_height(2);
grid->set_resolution(0.5);
grid->mutable_origin()->set_x(4.0);
grid->mutable_origin()->set_y(5.0);
grid->add_data(100);
if (name != "PARTIAL_GRID") {
grid->add_data(0);
grid->add_data(0);
grid->add_data(100);
}
if ((name == "SAVED_GRID" || name == "PARTIAL_GRID") && sequence == 2)
update->set_update_type(cmvr::msgs::AGV_MAP_UPDATE_INCREMENTAL);
if ((name == "SAVED_GRID" || name == "PARTIAL_GRID") && sequence == 3) {
update->set_chunk_count(2);
update->set_chunk_index(1);
}
}
if (name == "B")
++m_staleMapUpdates;
if (!writer->Write(frame))
break;
}
{
std::lock_guard<std::mutex> guard(m_mutex);
++m_completedStreams[name];
}
return grpc::Status::OK;
}
int downloads(const std::string &name)
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_downloads[name];
}
std::string downloadedDevice(const std::string &name)
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_downloadDevices[name];
}
int headerFailureCancellations() const
{
return m_headerFailureCancellations.load();
}
int staleMapUpdates() const
{
return m_staleMapUpdates.load();
}
int previewStreamsStarted() const
{
return m_previewStreamsStarted.load();
}
int previewStreamCancellations() const
{
return m_previewStreamCancellations.load();
}
int heldStreamsStarted() const
{
return m_heldStreamsStarted.load();
}
int heldStreamCancellations() const
{
return m_heldStreamCancellations.load();
}
int completedStreams(const std::string &name)
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_completedStreams[name];
}
bool lastIncremental(const std::string &name)
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_lastIncremental[name];
}
private:
std::mutex m_mutex;
std::map<std::string, int> m_downloads;
std::map<std::string, std::string> m_downloadDevices;
std::map<std::string, int> m_completedStreams;
std::map<std::string, bool> m_lastIncremental;
std::atomic<int> m_headerFailureCancellations{0};
std::atomic<int> m_staleMapUpdates{0};
std::atomic<int> m_previewStreamsStarted{0};
std::atomic<int> m_previewStreamCancellations{0};
std::atomic<int> m_heldStreamsStarted{0};
std::atomic<int> m_heldStreamCancellations{0};
};
struct ReceivedFrame {
QImage image;
QVariantMap metadata;
};
void verifyFrame(const ReceivedFrame &frame, const QString &map, int sequence,
const QString &endpoint)
{
const bool second = map == QStringLiteral("B");
const QVariantMap &metadata = frame.metadata;
require(!frame.image.isNull()
&& frame.image.size() == (second ? QSize(9, 5) : QSize(21, 13)),
"empty unified map yields the complete nonempty raw scan raster");
require(frame.image.hasAlphaChannel()
&& frame.image.pixelColor(0, frame.image.height() - 1).alpha() > 0
&& frame.image.pixelColor(frame.image.width() - 1, 1).alpha() > 0,
"both measured scan extrema survive with correct image Y orientation");
require(frame.image.pixelColor(second ? 4 : 10, second ? 3 : 7).alpha() == 0,
"free station cell remains transparent instead of drawing invented walls");
require(metadata.value(QStringLiteral("mapId")).toString() == map
&& metadata.value(QStringLiteral("mapName")).toString() == map
&& metadata.value(QStringLiteral("source")).toString() == QStringLiteral("raw-smap")
&& metadata.value(QStringLiteral("scanPointCount")).toInt() == 3
&& !metadata.value(QStringLiteral("semanticOnly")).toBool(),
"metadata identifies the actual raw map and its measured scan samples");
require(close(metadata.value(QStringLiteral("originX")).toDouble(), second ? 20.0 : -2.0)
&& close(metadata.value(QStringLiteral("originY")).toDouble(), second ? 10.0 : -1.0)
&& close(metadata.value(QStringLiteral("originTheta")).toDouble(), 0.0)
&& close(metadata.value(QStringLiteral("resolution")).toDouble(), second ? 0.5 : 0.25)
&& close(metadata.value(QStringLiteral("renderScale")).toDouble(), 1.0),
"camel SMAP origin and resolution replace missing unified grid metadata");
require(metadata.value(QStringLiteral("deviceId")).toString() == QStringLiteral("fixture_device")
&& metadata.value(QStringLiteral("endpoint")).toString() == endpoint
&& metadata.contains(QStringLiteral("demo"))
&& !metadata.value(QStringLiteral("demo")).toBool()
&& metadata.value(QStringLiteral("available")).toBool()
&& metadata.value(QStringLiteral("dimension")).toInt() == 2,
"fallback frame retains the real connection and trimmed device context");
const double timestamp = metadata.value(QStringLiteral("timestamp")).toDouble();
const bool updateMatches = metadata.contains(QStringLiteral("sequence"))
&& metadata.value(QStringLiteral("sequence")).toULongLong() == quint64(sequence)
&& (sequence == 0
? std::isfinite(timestamp)
&& std::abs(timestamp - QDateTime::currentMSecsSinceEpoch() / 1000.0) < 30.0
: close(timestamp, 1720000000.0 + sequence))
&& metadata.value(QStringLiteral("updateType")).toInt() == cmvr::msgs::AGV_MAP_UPDATE_SNAPSHOT;
if (!updateMatches)
qWarning("map=%s expectedSeq=%d actualSeq=%llu timestamp=%.3f now=%.3f updateType=%d",
qPrintable(map), sequence, metadata.value(QStringLiteral("sequence")).toULongLong(),
timestamp, QDateTime::currentMSecsSinceEpoch() / 1000.0,
metadata.value(QStringLiteral("updateType")).toInt());
require(updateMatches,
"cached raw raster preserves each incoming update sequence and timestamp");
const QVariantList stations = metadata.value(QStringLiteral("stations")).toList();
require(stations.size() == 1
&& stations.first().toMap().value(QStringLiteral("id")).toString() == QStringLiteral("HOME_") + map
&& stations.first().toMap().value(QStringLiteral("name")).toString() == QStringLiteral("Station ") + map
&& close(stations.first().toMap().value(QStringLiteral("x")).toDouble(), second ? 22.0 : 0.5)
&& close(stations.first().toMap().value(QStringLiteral("y")).toDouble(), second ? 11.0 : 0.5),
"downloaded map retains its own named world-coordinate station overlay");
}
}
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
FakeAgvService service;
grpc::ServerBuilder builder;
int port = 0;
builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&service);
const std::unique_ptr<grpc::Server> server = builder.BuildAndStart();
require(server && port > 0, "local loopback fake AGV service starts");
const QString endpoint = QStringLiteral("127.0.0.1:%1").arg(port);
RobotClient client;
bool connected = false;
QVector<ReceivedFrame> frames;
QString stoppedDetail;
bool stopped = false;
QStringList stateDetails;
QVector<QVariantMap> stateContexts;
QObject::connect(&client, &RobotClient::connectionChanged,
[&](bool available, int, const QString &) { connected = available; });
QObject::connect(&client, &RobotClient::agvMapFrameReceived,
[&](const QImage &image, const QVariantMap &metadata, const QString &) {
require(metadata.value(QStringLiteral("streamGeneration")).toULongLong()
== client.agvMapStreamGeneration(),
"generic frame never forwards a queued older stream generation");
frames.append({image, metadata});
});
QObject::connect(&client, &RobotClient::agvMapStreamStateChangedForContext,
[&](const QVariantMap &context, bool, const QString &) {
require(context.value(QStringLiteral("streamGeneration")).toULongLong()
== client.agvMapStreamGeneration(),
"typed state never forwards a queued older stream generation");
stateContexts.append(context);
});
QObject::connect(&client, &RobotClient::agvMapStreamStateChanged,
[&](bool running, const QString &detail) {
stateDetails.append(detail);
stopped = !running;
if (!running)
stoppedDetail = detail;
});
client.connectToServer(QStringLiteral("127.0.0.1"), port, false);
waitUntil([&]() { return connected; }, "client connects only to the local fake service");
const QString paddedDevice = QStringLiteral(" fixture_device ");
client.startAgvMapPreview(paddedDevice, QStringLiteral("A"));
waitUntil([&]() { return frames.size() == 4 && stopped; }, "initial A preview and all three fallback updates arrive");
for (int i = 0; i < frames.size(); ++i)
verifyFrame(frames.at(i), QStringLiteral("A"), i, endpoint);
require(service.downloads("A") == 1 && service.downloadedDevice("A") == "fixture_device",
"three empty map updates download A exactly once for the requested device");
qInfo("PASS: initial seq0 preview and three empty updates share one camel SMAP download with exact geometry/context");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapPreview(paddedDevice, QStringLiteral("B"));
waitUntil([&]() { return frames.size() == 4 && stopped; }, "initial B preview and all three fallback updates arrive");
for (int i = 0; i < frames.size(); ++i)
verifyFrame(frames.at(i), QStringLiteral("B"), i, endpoint);
require(service.downloads("A") == 1 && service.downloads("B") == 1
&& service.staleMapUpdates() == 3,
"restarting for B reads B once and never reuses A's raster or semantics");
qInfo("PASS: named B preview reads B once despite three stale A map ids; raster and semantics are isolated");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapPreview(paddedDevice, QStringLiteral("HEADER_FAIL"));
waitUntil([&]() { return stopped; }, "unsuccessful stream feedback stops the reader");
require(frames.size() == 1 && stoppedDetail.contains(QStringLiteral("fake controller rejected stream map"))
&& service.downloads("HEADER_FAIL") == 1,
"stream header failure is exposed while retaining only the selected raw preview");
verifyFrame(frames.first(), QStringLiteral("HEADER_FAIL"), 0, endpoint);
waitUntil([&]() { return service.headerFailureCancellations() == 1; },
"stream header failure cancels the open fake server stream");
qInfo("PASS: header.success=false cancels, exposes the controller error, and preserves the selected seq0 preview");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapStream(paddedDevice, QString(), cmvr::msgs::AGV_MAP_2D, true, false);
waitUntil([&]() { return stopped; }, "rejected raw download stops the reader");
require(frames.isEmpty() && service.downloads("REJECTED_CURRENT") == 1
&& service.downloads("") == 0
&& stoppedDetail.contains(QStringLiteral("REJECTED_CURRENT"))
&& stoppedDetail.contains(QStringLiteral("fake raw map download denied")),
"raw download rejection reports the actual map from the update and exact backend error");
qInfo("PASS: rejected raw map download names the actual current map and backend reason");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapPreview(paddedDevice, QStringLiteral("PREVIEW_ONLY"));
waitUntil([&]() { return frames.size() == 1 && service.previewStreamsStarted() == 1; },
"selected raw preview appears although the unified stream sends no frames");
require(!stopped && service.downloads("PREVIEW_ONLY") == 1,
"the selected preview is visible with its silent unified stream still open");
verifyFrame(frames.first(), QStringLiteral("PREVIEW_ONLY"), 0, endpoint);
client.stopAgvMapStream();
waitUntil([&]() { return stopped && service.previewStreamCancellations() == 1; },
"silent selected-preview stream remains cancelable");
require(frames.size() == 1, "the silent fixture produced no additional map updates");
qInfo("PASS: named raw map is visible before a silent unified stream emits any frame, and stop cancels cleanly");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapPreview(paddedDevice, QStringLiteral("DOWNLOAD_FAIL"));
waitUntil([&]() { return stopped; }, "failed initial raw read plus empty unified grid stops with a reason");
require(frames.isEmpty() && service.downloads("DOWNLOAD_FAIL") == 1
&& stoppedDetail.contains(QStringLiteral("DOWNLOAD_FAIL"))
&& stoppedDetail.contains(QStringLiteral("fake raw map download denied")),
"failed initial download is not retried by an empty unified map or replaced by the previous preview");
qInfo("PASS: failed initial raw download is attempted once and empty grid reports the selected name/reason");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapPreview(paddedDevice, QStringLiteral("MISMATCH"));
waitUntil([&]() { return stopped; }, "raw content with a different map name is rejected");
require(frames.isEmpty() && service.downloads("MISMATCH") == 1
&& stoppedDetail.contains(QStringLiteral("MISMATCH"))
&& stoppedDetail.contains(QStringLiteral("车端却返回了 A")),
"wrong-map raw content is never relabeled as the selected map or downloaded repeatedly");
qInfo("PASS: raw content for the wrong map is rejected without relabeling the old map as the selected preview");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapPreview(paddedDevice, QStringLiteral("GRID_ONLY"));
waitUntil([&]() { return frames.size() == 3 && stopped; },
"valid unified grids remain usable when selected raw download is denied");
require(service.downloads("GRID_ONLY") == 1,
"valid unified grid fallback does not repeat the failed preview download");
for (int i = 0; i < frames.size(); ++i) {
const ReceivedFrame &frame = frames.at(i);
require(frame.image.size() == QSize(2, 2)
&& frame.image.pixelColor(0, 1).alpha() > 0
&& frame.image.pixelColor(1, 1).alpha() == 0
&& frame.image.pixelColor(1, 0).alpha() > 0
&& frame.metadata.value(QStringLiteral("mapId")).toString() == QStringLiteral("GRID_ONLY")
&& frame.metadata.value(QStringLiteral("sequence")).toULongLong() == quint64(i + 1)
&& close(frame.metadata.value(QStringLiteral("originX")).toDouble(), 4.0)
&& close(frame.metadata.value(QStringLiteral("originY")).toDouble(), 5.0)
&& close(frame.metadata.value(QStringLiteral("resolution")).toDouble(), 0.5)
&& frame.metadata.value(QStringLiteral("deviceId")).toString() == QStringLiteral("fixture_device")
&& frame.metadata.value(QStringLiteral("endpoint")).toString() == endpoint
&& !frame.metadata.value(QStringLiteral("demo")).toBool(),
"usable unified grid retains measured pixels, update ids, world origin and real context");
}
qInfo("PASS: valid unified grid still displays when raw preview download is denied");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapPreview(paddedDevice, QStringLiteral("WRONG_GRID"));
waitUntil([&]() { return stopped; }, "raw-failed selected preview ignores complete grids for another map");
require(frames.isEmpty() && service.downloads("WRONG_GRID") == 1
&& service.completedStreams("WRONG_GRID") == 1
&& stoppedDetail.contains(QStringLiteral("WRONG_GRID"))
&& stoppedDetail.contains(QStringLiteral("fake raw map download denied")),
"wrong-map complete grid neither replaces the selected map nor hides its actual download error");
qInfo("PASS: raw-failed named preview rejects another map's complete grids and retains the selected download error");
frames.clear();
stateDetails.clear();
stopped = false;
const int silentStarts = service.previewStreamsStarted();
const int silentStops = service.previewStreamCancellations();
client.startAgvMapPreview(paddedDevice, QStringLiteral("RAW_SILENT"));
waitUntil([&]() {
return service.previewStreamsStarted() == silentStarts + 1
&& stateDetails.join(QLatin1Char('\n')).contains(QStringLiteral("fake raw map download denied"));
}, "raw download failure is visible before the silent stream sends any response");
require(frames.isEmpty() && !stopped && service.downloads("RAW_SILENT") == 1
&& stateDetails.join(QLatin1Char('\n')).contains(QStringLiteral("RAW_SILENT")),
"map-specific raw error is immediately exposed while waiting for a compatible unified grid");
client.stopAgvMapStream();
waitUntil([&]() { return stopped && service.previewStreamCancellations() == silentStops + 1; },
"raw-failed silent stream can still be stopped");
qInfo("PASS: map-specific raw download error is exposed immediately even when unified stream is silent");
frames.clear();
stopped = false;
client.startAgvMapPreview(paddedDevice, QStringLiteral("SAVED_GRID"));
waitUntil([&]() { return frames.size() == 4 && stopped; },
"saved-map preview observes snapshot, delta and chunk updates");
verifyFrame(frames.first(), QStringLiteral("SAVED_GRID"), 0, endpoint);
require(!service.lastIncremental("SAVED_GRID"), "saved-map preview requests complete snapshots");
for (const ReceivedFrame &frame : frames)
require(frame.image == frames.first().image
&& frame.metadata.value(QStringLiteral("mapId")).toString() == QStringLiteral("SAVED_GRID")
&& frame.metadata.value(QStringLiteral("preview")).toBool()
&& frame.metadata.value(QStringLiteral("source")).toString() == QStringLiteral("raw-smap"),
"same-name native grid, delta and chunk never replace the complete selected raw raster");
require(frames.at(2).metadata.value(QStringLiteral("updateType")).toInt()
== cmvr::msgs::AGV_MAP_UPDATE_INCREMENTAL
&& frames.at(3).metadata.value(QStringLiteral("chunkCount")).toInt() == 2,
"fixture actually supplied a delta and a fragmented update");
qInfo("PASS: complete saved raw preview survives same-id different grid, delta and fragmented update");
frames.clear();
stopped = false;
client.startAgvMapStream(paddedDevice, QStringLiteral("SAVED_GRID"), cmvr::msgs::AGV_MAP_2D, true, true);
waitUntil([&]() { return frames.size() == 4 && stopped; },
"live stream still delivers changing unified grid data after its initial raw preview");
require(service.lastIncremental("SAVED_GRID") && frames.first().image.size() == QSize(21, 13),
"explicit live caller retains its requested incremental mode and initial raw scan");
for (int i = 1; i < frames.size(); ++i)
require(frames.at(i).image.size() == QSize(2, 2)
&& !frames.at(i).metadata.value(QStringLiteral("preview")).toBool()
&& close(frames.at(i).metadata.value(QStringLiteral("originX")).toDouble(), 4.0),
"live unified maps remain live instead of being frozen by saved-preview protection");
qInfo("PASS: explicit live stream remains compatible with unified updates rather than freezing to saved raw");
frames.clear();
stopped = false;
stoppedDetail.clear();
client.startAgvMapPreview(paddedDevice, QStringLiteral("PARTIAL_GRID"));
waitUntil([&]() { return stopped; }, "incomplete unified preview stream finishes");
require(frames.isEmpty() && service.downloads("PARTIAL_GRID") == 1
&& stoppedDetail.contains(QStringLiteral("fake raw map download denied")),
"failed raw preview never draws a partial grid, standalone delta or unassembled chunk");
qInfo("PASS: raw-failed preview rejects partial grid, standalone delta and chunk without inventing a complete image");
frames.clear();
stateContexts.clear();
stateDetails.clear();
stopped = false;
const int completedA = service.completedStreams("A");
client.startAgvMapPreview(paddedDevice, QStringLiteral("A"));
const quint64 oldGeneration = client.agvMapStreamGeneration();
QElapsedTimer queueTimer;
queueTimer.start();
// Deliberately withhold GUI event delivery so A frames and terminal state
// are queued when a new generation is requested on the same connection.
while (service.completedStreams("A") == completedA && queueTimer.elapsed() < 3000)
QThread::msleep(1);
require(service.completedStreams("A") > completedA, "old stream callbacks were queued without GUI delivery");
client.startAgvMapPreview(paddedDevice, QStringLiteral("B"));
const quint64 newGeneration = client.agvMapStreamGeneration();
require(newGeneration > oldGeneration, "each new stream has a distinct generation");
waitUntil([&]() { return frames.size() == 4 && stopped; },
"new B generation delivers frames and terminal state after queued A callbacks");
for (const ReceivedFrame &frame : frames)
require(frame.metadata.value(QStringLiteral("mapId")).toString() == QStringLiteral("B")
&& frame.metadata.value(QStringLiteral("streamGeneration")).toULongLong() == newGeneration,
"old queued A frame cannot leak through either same-device or same-endpoint context");
for (const QVariantMap &context : stateContexts)
require(context.value(QStringLiteral("mapId")).toString() == QStringLiteral("B")
&& context.value(QStringLiteral("streamGeneration")).toULongLong() == newGeneration,
"old queued A status cannot terminate or label the new B stream");
qInfo("PASS: queued previous-generation frames and state callbacks are discarded before generic and typed signals");
frames.clear();
stateContexts.clear();
stopped = false;
const int stoppedA = service.completedStreams("A");
client.startAgvMapPreview(paddedDevice, QStringLiteral("A"));
queueTimer.restart();
while (service.completedStreams("A") == stoppedA && queueTimer.elapsed() < 3000)
QThread::msleep(1);
require(service.completedStreams("A") > stoppedA, "stop fixture has queued old map frames");
client.stopAgvMapStream();
const quint64 stopGeneration = client.agvMapStreamGeneration();
waitUntil([&]() { return stopped; }, "current explicit stop is forwarded after invalidating old callbacks");
require(frames.isEmpty() && !stateContexts.isEmpty()
&& stateContexts.last().value(QStringLiteral("streamGeneration")).toULongLong() == stopGeneration,
"stop invalidates queued old frames while retaining its own current terminal state");
qInfo("PASS: explicit stop invalidates queued frames and still emits its own current generation state");
frames.clear();
stopped = false;
const int heldStarts = service.heldStreamsStarted();
const int heldStops = service.heldStreamCancellations();
client.startAgvMapStream(paddedDevice, QStringLiteral("HOLD_OPEN"), cmvr::msgs::AGV_MAP_3D,
false, false);
waitUntil([&]() { return service.heldStreamsStarted() == heldStarts + 1; },
"fake server holds a no-data map stream open without a client deadline");
require(!stopped && frames.isEmpty(), "held stream is active and has not completed by itself");
QElapsedTimer stopTimer;
stopTimer.start();
client.stopAgvMapStream();
waitUntil([&]() { return stopped && service.heldStreamCancellations() == heldStops + 1; },
"stopping a blocked reader cancels the server and joins promptly");
require(stopTimer.elapsed() < 1500, "stop does not wait for the long server stream to finish");
qInfo("PASS: an active no-data long-lived map stream cancels and joins within 1500 ms");
// Queue Stop immediately after each Start, without waiting for the stream
// thread to run or publish its context. Repetition exercises both the
// pre-publication and already-published cancellation interleavings.
frames.clear();
stateContexts.clear();
stopped = false;
stopTimer.restart();
for (int i = 0; i < 64; ++i) {
client.startAgvMapStream(paddedDevice, QStringLiteral("HOLD_OPEN"), cmvr::msgs::AGV_MAP_3D,
false, false);
client.stopAgvMapStream();
}
const quint64 immediateStopGeneration = client.agvMapStreamGeneration();
waitUntil([&]() { return stopped && !stateContexts.isEmpty()
&& stateContexts.last().value(QStringLiteral("streamGeneration")).toULongLong()
== immediateStopGeneration; }, "immediate Start/Stop burst joins every stream thread");
waitUntil([&]() { return service.heldStreamsStarted() == service.heldStreamCancellations(); },
"every held server stream reached by the burst observes cancellation");
require(stopTimer.elapsed() < 3000 && frames.isEmpty(),
"early stop cannot lose cancellation before context publication or deliver map frames");
qInfo("PASS: 64 immediate Start/Stop pairs finish within 3000 ms with all reached streams cancelled");
client.disconnectFromServer();
waitUntil([&]() { return !connected; }, "fixture client disconnects cleanly");
server->Shutdown();
qInfo("AGV map stream fallback integration checks passed (loopback only)");
return 0;
}