CmvrControlStation/tests/seeragvmapclient_fake.h
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

267 lines
10 KiB
C++

#pragma once
#include "seeragvmapclient.h"
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QtEndian>
#include <atomic>
#include <chrono>
#include <functional>
#include <iostream>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
namespace {
void require(bool condition, const char *message)
{
if (!condition) {
std::cerr << "FAIL SEER map test: " << message << std::endl;
qFatal("SEER map TCP test failed: %s", message);
}
}
const QString mapName = QStringLiteral("WAREHOUSE");
const QString completeMap = QString::fromUtf8(u8" \n{\"header\":{\"mapName\":\"WAREHOUSE\",\"version\":\"1.0.6\","
"\"resolution\":0.02,\"mapType\":\"2D-Map\"},\"normalPosList\":[{\"x\":1.0123456789012345,\"y\":2.0}],"
"\"advancedPointList\":[{\"instanceName\":\"LM1\",\"description\":\"中文站点\"}],"
"\"advancedCurveList\":[],\"advancedLineList\":[],\"unknown\":18446744073709551614}\n");
enum class Fault {
None, ReadRejected, WrongType, WrongSequence, Moving, ActiveTask,
MissingSpeed, MissingTask, HeaderRejected, SilentUpload,
LoadRejected, WrongCurrentMap, WrongUploadType, WrongUploadSequence, MissingUploadAck,
AuthorityRejected
};
struct Fixture {
explicit Fixture(Fault selected = Fault::None) : fault(selected) {}
Fault fault;
std::atomic<int> reads{0};
std::atomic<int> uploads{0};
std::atomic<int> switches{0};
std::atomic<int> acquires{0};
std::atomic<int> speedReads{0};
std::atomic<int> taskReads{0};
std::atomic<int> loadReads{0};
std::atomic<int> currentMapReads{0};
std::atomic<bool> fragment{false};
std::atomic<int> readDelayMs{0};
std::mutex captureMutex;
QByteArray uploaded;
QString requestedReadName;
QString requestedSwitchName;
QString nickName;
std::vector<int> order;
QByteArray response(quint16 command, const QByteArray &body)
{
const QJsonObject json = QJsonDocument::fromJson(body).object();
{
std::lock_guard<std::mutex> lock(captureMutex);
order.push_back(command);
}
const auto encode = [](const QJsonObject &value) {
return QJsonDocument(value).toJson(QJsonDocument::Compact);
};
switch (command) {
case 4011:
++reads;
{
std::lock_guard<std::mutex> lock(captureMutex);
requestedReadName = json.value(QStringLiteral("map_name")).toString();
}
if (readDelayMs.load() > 0)
std::this_thread::sleep_for(std::chrono::milliseconds(readDelayMs.load()));
if (fault == Fault::ReadRejected)
return encode({{QStringLiteral("ret_code"), 40051}, {QStringLiteral("err_msg"), QStringLiteral("read denied")}});
return completeMap.toUtf8();
case 1005:
++speedReads;
if (fault == Fault::MissingSpeed)
return encode({{QStringLiteral("vx"), 0.0}, {QStringLiteral("vy"), 0.0}});
return encode({{QStringLiteral("vx"), fault == Fault::Moving ? 0.2 : 0.0},
{QStringLiteral("vy"), 0.0}, {QStringLiteral("w"), 0.0}});
case 1020:
++taskReads;
if (fault == Fault::MissingTask)
return encode({{QStringLiteral("task_status"), QStringLiteral("4")}});
return encode({{QStringLiteral("task_status"), fault == Fault::ActiveTask ? 2 : 4}});
case 4005:
++acquires;
{
std::lock_guard<std::mutex> lock(captureMutex);
nickName = json.value(QStringLiteral("nick_name")).toString();
}
if (fault == Fault::AuthorityRejected)
return encode({{QStringLiteral("ret_code"), 40001}, {QStringLiteral("err_msg"), QStringLiteral("control busy")}});
return encode({{QStringLiteral("ret_code"), 0}});
case 4010:
++uploads;
{
std::lock_guard<std::mutex> lock(captureMutex);
uploaded = body;
}
if (fault == Fault::HeaderRejected)
return encode({{QStringLiteral("ret_code"), 40050}, {QStringLiteral("err_msg"), QStringLiteral("need map header")}});
if (fault == Fault::MissingUploadAck)
return encode({{QStringLiteral("message"), QStringLiteral("not an acknowledgement")}});
return encode({{QStringLiteral("ret_code"), 0}});
case 2022:
++switches;
{
std::lock_guard<std::mutex> lock(captureMutex);
requestedSwitchName = json.value(QStringLiteral("map_name")).toString();
}
return encode({{QStringLiteral("ret_code"), 0}});
case 1022: {
const int query = ++loadReads;
return encode({{QStringLiteral("loadmap_status"), fault == Fault::LoadRejected ? 0 : (query == 1 ? 2 : 1)}});
}
case 1300:
++currentMapReads;
return encode({{QStringLiteral("current_map"), fault == Fault::WrongCurrentMap ? QStringLiteral("OTHER") : mapName}});
default:
return encode({{QStringLiteral("ret_code"), 49999}, {QStringLiteral("err_msg"), QStringLiteral("unexpected test command")}});
}
}
};
// Each listener is owned and used entirely by its own thread. All three bind
// only to loopback; no fixture can contact a configured real robot.
class FakePort final {
public:
explicit FakePort(Fixture &fixture) : m_fixture(fixture)
{
m_thread = std::thread([this] { serve(); });
QElapsedTimer elapsed;
elapsed.start();
while (m_port.load() == 0 && !m_failed.load() && elapsed.elapsed() < 3000)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
require(m_port.load() != 0 && !m_failed.load(), "fake loopback listener started");
}
~FakePort()
{
m_stop.store(true);
m_thread.join();
}
quint16 port() const { return static_cast<quint16>(m_port.load()); }
private:
struct Peer {
std::unique_ptr<QTcpSocket> socket;
QByteArray buffered;
};
void reply(Peer &peer, quint16 command, quint16 sequence, const QByteArray &body)
{
if (command == 4010 && m_fixture.fault == Fault::SilentUpload)
return;
QByteArray packet(16, '\0');
packet[0] = static_cast<char>(0x5a);
packet[1] = 1;
quint16 replyType = command + 10000;
quint16 replySequence = sequence;
if (command == 4011 && m_fixture.fault == Fault::WrongType)
++replyType;
if (command == 4011 && m_fixture.fault == Fault::WrongSequence)
++replySequence;
if (command == 4010 && m_fixture.fault == Fault::WrongUploadType)
++replyType;
if (command == 4010 && m_fixture.fault == Fault::WrongUploadSequence)
++replySequence;
qToBigEndian<quint16>(replySequence, reinterpret_cast<uchar *>(packet.data() + 2));
qToBigEndian<quint32>(static_cast<quint32>(body.size()), reinterpret_cast<uchar *>(packet.data() + 4));
qToBigEndian<quint16>(replyType, reinterpret_cast<uchar *>(packet.data() + 8));
packet += body;
if (m_fixture.fragment.load()) {
const int lengths[] = {1, 2, 5, 3, 7};
int offset = 0;
for (int length : lengths) {
const QByteArray part = packet.mid(offset, length);
peer.socket->write(part);
peer.socket->waitForBytesWritten(100);
offset += part.size();
std::this_thread::sleep_for(std::chrono::milliseconds(3));
}
peer.socket->write(packet.mid(offset));
} else {
peer.socket->write(packet);
}
peer.socket->waitForBytesWritten(100);
}
void serve()
{
QTcpServer listener;
if (!listener.listen(QHostAddress::LocalHost, 0)) {
m_failed.store(true);
return;
}
m_port.store(listener.serverPort());
std::vector<Peer> peers;
while (!m_stop.load()) {
listener.waitForNewConnection(2);
while (listener.hasPendingConnections())
peers.push_back({std::unique_ptr<QTcpSocket>(listener.nextPendingConnection()), {}});
for (Peer &peer : peers) {
if (peer.socket->state() != QAbstractSocket::ConnectedState)
continue;
if (!peer.socket->bytesAvailable())
peer.socket->waitForReadyRead(1);
peer.buffered += peer.socket->readAll();
while (peer.buffered.size() >= 16) {
const uchar *header = reinterpret_cast<const uchar *>(peer.buffered.constData());
require(header[0] == 0x5a && header[1] == 1, "request uses valid SEER frame header");
const quint32 length = qFromBigEndian<quint32>(header + 4);
require(length <= 64 * 1024 * 1024, "request payload bounded");
if (static_cast<quint64>(peer.buffered.size()) < 16ULL + length)
break;
const quint16 sequence = qFromBigEndian<quint16>(header + 2);
const quint16 command = qFromBigEndian<quint16>(header + 8);
require(sequence != 0, "requests have nonzero sequence");
const QByteArray body = peer.buffered.mid(16, static_cast<int>(length));
peer.buffered.remove(0, 16 + static_cast<int>(length));
reply(peer, command, sequence, m_fixture.response(command, body));
}
}
}
}
Fixture &m_fixture;
std::atomic<bool> m_stop{false};
std::atomic<bool> m_failed{false};
std::atomic<int> m_port{0};
std::thread m_thread;
};
class FakeRobot final {
public:
explicit FakeRobot(Fault fault = Fault::None)
: state(fault), status(state), control(state), config(state)
{
connection.host = QStringLiteral("127.0.0.1");
connection.statusPort = status.port();
connection.controlPort = control.port();
connection.configPort = config.port();
connection.nickName = QStringLiteral("CMVR-map-test");
}
Fixture state;
FakePort status;
FakePort control;
FakePort config;
SeerAgvMapConnection connection;
};
} // namespace