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.
This commit is contained in:
Codex 2026-11-10 16:10:46 +08:00
parent 58e5b7617b
commit 22620db699
40 changed files with 14699 additions and 296 deletions

View File

@ -30,7 +30,7 @@ set(PROTO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/protos")
set(GENERATED_ROOT "${CMAKE_CURRENT_BINARY_DIR}/generated_cpp") set(GENERATED_ROOT "${CMAKE_CURRENT_BINARY_DIR}/generated_cpp")
find_package(Qt5 5.12 REQUIRED COMPONENTS find_package(Qt5 5.12 REQUIRED COMPONENTS
Core Gui Widgets Multimedia 3DCore 3DRender 3DExtras 3DInput 3DAnimation) Core Gui Widgets Network Multimedia 3DCore 3DRender 3DExtras 3DInput 3DAnimation)
get_target_property(CMVR_QMAKE_EXECUTABLE Qt5::qmake IMPORTED_LOCATION) get_target_property(CMVR_QMAKE_EXECUTABLE Qt5::qmake IMPORTED_LOCATION)
if(CMVR_QMAKE_EXECUTABLE) if(CMVR_QMAKE_EXECUTABLE)
@ -152,6 +152,15 @@ if(CMVR_WITH_MSQUIC)
endif() endif()
set(CMVR_SOURCES set(CMVR_SOURCES
src/agvvelocityramp.h
src/seeragvmapclient.cpp
src/seeragvmapclient.h
src/agvmapdocument.cpp
src/agvmapdocument.h
src/agvmaprasterizer.cpp
src/agvmaprasterizer.h
src/agvmapeditorwidget.cpp
src/agvmapeditorwidget.h
src/agvmapviewwidget.cpp src/agvmapviewwidget.cpp
src/agvmapviewwidget.h src/agvmapviewwidget.h
src/audiostreammanager.cpp src/audiostreammanager.cpp
@ -259,7 +268,7 @@ if(CMVR_WITH_MSQUIC)
endif() endif()
target_link_libraries(CmvrControlStation PRIVATE target_link_libraries(CmvrControlStation PRIVATE
Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Multimedia Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Network Qt5::Multimedia
Qt5::3DCore Qt5::3DRender Qt5::3DExtras Qt5::3DInput Qt5::3DAnimation) Qt5::3DCore Qt5::3DRender Qt5::3DExtras Qt5::3DInput Qt5::3DAnimation)
# Generate every project-local CMVR message. This avoids source-tree generated # Generate every project-local CMVR message. This avoids source-tree generated

View File

@ -1,4 +1,4 @@
QT += core gui widgets multimedia 3dcore 3drender 3dextras 3dinput 3danimation QT += core gui widgets network multimedia 3dcore 3drender 3dextras 3dinput 3danimation
CONFIG += c++17 warn_on debug_and_release CONFIG += c++17 warn_on debug_and_release
TEMPLATE = app TEMPLATE = app
@ -239,6 +239,10 @@ CONFIG(debug, debug|release) {
!exists($$ASSIMP_SCENE_PARSER): error("Qt3D Assimp scene parser not found in the selected Qt Kit.") !exists($$ASSIMP_SCENE_PARSER): error("Qt3D Assimp scene parser not found in the selected Qt Kit.")
SOURCES += \ SOURCES += \
src/seeragvmapclient.cpp \
src/agvmapdocument.cpp \
src/agvmaprasterizer.cpp \
src/agvmapeditorwidget.cpp \
src/applicationsettings.cpp \ src/applicationsettings.cpp \
src/applicationstyle.cpp \ src/applicationstyle.cpp \
src/taskorchestrationwidget.cpp \ src/taskorchestrationwidget.cpp \
@ -272,6 +276,11 @@ SOURCES += \
ui/handeyecalibrationwidget.cpp ui/handeyecalibrationwidget.cpp
HEADERS += \ HEADERS += \
src/agvvelocityramp.h \
src/seeragvmapclient.h \
src/agvmapdocument.h \
src/agvmaprasterizer.h \
src/agvmapeditorwidget.h \
src/applicationsettings.h \ src/applicationsettings.h \
src/applicationstyle.h \ src/applicationstyle.h \
src/appmessagebox.h \ src/appmessagebox.h \

View File

@ -14,6 +14,22 @@ CMVR Control Station 是一个基于 Qt 5 的桌面控制站,用于连接 CMVR
## 设备管理 ## 设备管理
### AGV 手动加减速
AGV 页右侧“手动控制”可分别设置线加速度、线减速度(m/s²),以及角加速度、角减速度(rad/s²)。默认分别为 0.20、0.30、0.50、0.80,修改后自动保存到本机。X/Y/Z 速度输入仍表示目标速度,按住方向按钮或 Q/W/E/A/S/D 键时逐步接近目标;换向先减至零,再向新方向加速。
松开按键、点击手动区“停止”或“速度归零”会按设置减速,减速期间车辆仍有移动距离。右侧“停止速度”和“AGV 急停”沿用立即停止请求;失焦、离开手动页面、设备/连接变化及地图直连操作也会取消斜坡。手动速度最多保留一个在途请求,过期请求丢弃,失败或响应超时后停止继续发送速度,须重新按键才能启动。此功能只修改上位机,不修改控制器参数、服务端或接口定义。
### AGV 地图直连
AGV 的地图工作区可选择“通过服务”或“车辆直连”。该选项只改变地图读取、保存和切图的上位机通信路径,不修改服务端或 gRPC/proto 定义;Demo 模式继续使用演示数据。导航、状态、建图和其他设备仍使用原有服务。
车辆 IP 留空时,上位机通过当前服务地址的 ConfigurationService(默认 50053,可沿用配置服务端口设置)只读查找当前设备 ID 对应的 SEER 地址和端口。也可手填车辆 IP,此时使用标准端口 19204/19205/19207。配置查询和车辆 TCP 操作在独立线程执行,不占用原有控制请求线程。
直连保存发送包含顶层 `header` 的完整原始 SMAP,保留未知字段和数字文本。写入前读取最新地图供编辑器合并,并检查车辆速度和导航状态;静止且任务空闲才申请控制权、再次检查状态并发送一次地图请求。切图须同时读取到加载成功和当前地图名称匹配才显示完成。发送后超时、取消或回包异常会显示结果未知,不自动重发;原编辑内容仍保留。直连操作期间,本窗口的导航、运动和建图入口暂时禁用,急停与停止入口保持可用。
该路径要求本机能访问车辆网络,不会修复服务端持有的断开连接。服务状态与直连切图确认分别显示。实车操作前应确保没有其他控制端同时发起导航或修改地图;本机模拟 TCP 测试通过并不等同于实车保存成功。
左侧进入 `gRPC > 设备管理` 后,默认打开“设备总览”: 左侧进入 `gRPC > 设备管理` 后,默认打开“设备总览”:
- 主 gRPC 通道连接成功时自动调用 `GetSystemInfo` 和 `GetSystemStatus`。 - 主 gRPC 通道连接成功时自动调用 `GetSystemInfo` 和 `GetSystemStatus`。

202
assets/agv/LICENSE.txt Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

26
assets/agv/SOURCE.md Normal file
View File

@ -0,0 +1,26 @@
# AGV Demo scan map
`demo_scan.smap` is a Demo-only conversion of the official TurtleBot 4 depot
occupancy sample. It is never a connected robot's downloaded map.
Sources (TurtleBot 4 `jazzy` branch, Apache-2.0):
- [depot.pgm](https://github.com/turtlebot/turtlebot4/blob/jazzy/turtlebot4_navigation/maps/depot.pgm)
- [depot.yaml](https://github.com/turtlebot/turtlebot4/blob/jazzy/turtlebot4_navigation/maps/depot.yaml)
- [LICENSE](https://github.com/turtlebot/turtlebot4/blob/jazzy/LICENSE), copied unchanged to `LICENSE.txt`.
The original raster is 755 x 380 cells at 0.04 m/cell with origin
(-15.1, -7.74), giving bounds (-15.1, -7.74) to (15.1, 7.46).
For each 2 x 2 raster block containing an occupied cell (gray < 128), the
first occupied cell's center becomes one `normal_pos_list` point. World
coordinates use x = origin.x + (column + 0.5) * resolution and
y = origin.y + (height - row - 0.5) * resolution. This retains 3,217
real scan samples, including thin boundaries, without synthesizing walls.
Free and unknown cells do not become scan points.
The 11 named stations and 10 bidirectional connections are added solely for
Demonstration. Routes are serialized by `AgvMapDocument::addRoute`.
LM10 and LM4 use y = 0.2 m to avoid occupied samples on y = 0;
all station centers and route centerlines were checked against the original
PGM at 0.01 m intervals and lie in free cells. This is a visual Demo layout,
not a robot navigation or clearance certificate.

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,7 @@
<RCC> <RCC>
<qresource prefix="/"> <qresource prefix="/">
<file>styles.qss</file> <file>styles.qss</file>
<file>assets/agv/demo_scan.smap</file>
<file>icons/cmvr-app.ico</file> <file>icons/cmvr-app.ico</file>
<file>icons/cmvr-app.svg</file> <file>icons/cmvr-app.svg</file>
<file>icons/settings.svg</file> <file>icons/settings.svg</file>

1013
src/agvmapdocument.cpp Normal file

File diff suppressed because it is too large Load Diff

89
src/agvmapdocument.h Normal file
View File

@ -0,0 +1,89 @@
#pragma once
#include <QJsonArray>
#include <QJsonObject>
#include <QHash>
#include <QSet>
#include <QStringList>
#include <QVariantList>
#include <QVector>
// Edits the complete SEER 2D map returned by AgvService.downloadMap.
// Schema: https://github.com/seer-robotics/smap/blob/master/message_map.proto
// LandMark and BezierPath defaults follow the vendor's maps/1.smap example.
// Existing JSON is retained verbatim except explicitly edited name fields.
class AgvMapDocument
{
public:
bool load(const QString &content, QString *error = nullptr);
bool addStation(const QString &id, double x, double y, double theta,
QString *error = nullptr, const QString &name = QString());
bool setStationName(const QString &id, const QString &name,
QString *error = nullptr);
bool addRoute(const QString &id, const QString &source, const QString &target,
bool bidirectional, QString *error = nullptr);
bool removeRoute(const QString &id, QString *error = nullptr);
bool removeStation(const QString &id, bool removeConnectedRoutes,
QString *error = nullptr);
QStringList connectedRouteIds(const QString &stationId) const;
QStringList removedStationIds() const;
QStringList removedRouteIds() const;
bool mergeRemovalsInto(AgvMapDocument *latest, QString *error = nullptr) const;
bool verifyRemovals(const AgvMapDocument &readback, QString *error = nullptr) const;
QVariantList stations() const;
QVariantList routes() const;
QString content() const;
bool hasStation(const QString &id) const;
QStringList stationIds() const;
QString nextAvailableStationId() const;
bool validateStationIds(QString *error = nullptr) const;
bool isDirty() const { return m_dirty; }
void markSaved();
void clear();
private:
struct ObjectSource {
QString id;
int start = -1;
int end = -1;
};
struct StationSource {
QString originalName;
int descriptionStart = -1;
int descriptionLength = 0;
int objectEnd = -1;
bool hasDescription = false;
bool editableName = false;
};
QString key(const char *snake, const char *camel) const;
bool idInUse(const QString &id) const;
QJsonObject stationObject(const QString &id) const;
QJsonObject makeRoute(const QString &id, const QJsonObject &source,
const QJsonObject &target) const;
void updateDirty();
QString originalObject(const QString &id, bool station, int *matches = nullptr) const;
QJsonObject m_root;
QString m_source;
QString m_stationKey;
QString m_routeKey;
QJsonArray m_addedStations;
QJsonArray m_addedRoutes;
QSet<QString> m_draftStations;
QSet<QString> m_draftRoutes;
QSet<QString> m_removedStations;
QSet<QString> m_removedRoutes;
QVector<ObjectSource> m_stationElements;
QVector<ObjectSource> m_routeElements;
QHash<QString, StationSource> m_stationSources;
QHash<QString, QString> m_stationNameChanges;
int m_stationArrayEnd = -1;
int m_routeArrayEnd = -1;
int m_rootEnd = -1;
int m_originalStationCount = 0;
int m_originalRouteCount = 0;
bool m_camelCase = false;
bool m_loaded = false;
bool m_dirty = false;
};

1160
src/agvmapeditorwidget.cpp Normal file

File diff suppressed because it is too large Load Diff

103
src/agvmapeditorwidget.h Normal file
View File

@ -0,0 +1,103 @@
#pragma once
#include "agvmapdocument.h"
#include <QElapsedTimer>
#include <QSet>
#include <QHash>
#include <QVariantMap>
#include <QVector>
#include <QWidget>
#include <functional>
class AgvMapViewWidget;
class QLabel;
class QPushButton;
class RobotClient;
class AgvMapEditorWidget final : public QWidget
{
Q_OBJECT
public:
struct Context {
QString endpoint;
QString deviceId;
QString mapName;
QVariantMap pose;
bool connected = false;
bool demo = false;
QString key() const;
};
explicit AgvMapEditorWidget(RobotClient *client, AgvMapViewWidget *view,
QWidget *parent = nullptr);
void setContextProvider(std::function<Context()> provider);
void setAutoLoadEnabled(bool enabled);
void refreshContext();
void reloadCleanMap();
signals:
void mapSaved();
void busyChanged(bool busy);
private:
enum Action { NoAction, PickStation, PickRoute, CoordinateStation, Manage };
Context context() const;
bool prepareContext();
bool mapReady() const;
void begin(Action action);
void perform(Action action);
void showStationDialog(double x, double y);
void showRouteDialog(const QString &source = QString(),
const QString &target = QString());
void showManager();
void showStationNameDialog(const QString &id);
void save();
void undo();
void updateScene();
void updateButtons();
void setBusy(bool busy);
void setMessage(const QString &message, bool error = false);
void resetMode();
void requestSaveVerification();
void failSaveVerification(const QString &detail);
bool verifySavedEdits(const AgvMapDocument &readback, QString *error) const;
void receiveMap(quint64 requestId, const QString &deviceId, const QString &mapName,
const QString &content, bool success, const QString &detail);
void receiveSave(quint64 requestId, const QString &deviceId, const QString &mapName,
bool success, const QString &detail);
RobotClient *m_client;
AgvMapViewWidget *m_view;
std::function<Context()> m_contextProvider;
AgvMapDocument m_document;
AgvMapDocument m_saveCandidate;
QVector<AgvMapDocument> m_history;
struct Draft {
AgvMapDocument document;
QVector<AgvMapDocument> history;
};
QHash<QString, Draft> m_mapDrafts;
Context m_requestContext;
QString m_loadedKey;
QString m_sceneKey;
QString m_routeStart;
quint64 m_requestId = 0;
Action m_pendingAction = NoAction;
bool m_busy = false;
bool m_reloadingForSave = false;
bool m_verifyingSave = false;
int m_saveVerificationAttempts = 0;
quint64 m_saveVerificationGeneration = 0;
QElapsedTimer m_saveVerificationClock;
bool m_autoLoadEnabled = false;
QSet<QString> m_autoLoadAttemptedKeys;
QPushButton *m_browseButton;
QPushButton *m_stationButton;
QPushButton *m_routeButton;
QPushButton *m_coordinatesButton;
QPushButton *m_manageButton;
QPushButton *m_saveButton;
QPushButton *m_undoButton;
QLabel *m_status;
};

205
src/agvmaprasterizer.cpp Normal file
View File

@ -0,0 +1,205 @@
#include "agvmaprasterizer.h"
#include "agvmapdocument.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QPointF>
#include <algorithm>
#include <cmath>
#include <limits>
namespace {
QJsonValue field(const QJsonObject &object, const char *snake, const char *camel)
{
const QString key = QString::fromLatin1(snake);
return object.contains(key) ? object.value(key)
: object.value(QString::fromLatin1(camel));
}
bool number(const QJsonObject &object, const char *key, double &output)
{
const QJsonValue value = object.value(QString::fromLatin1(key));
// Protobuf JSON omits primitive values equal to zero.
if (value.isUndefined()) {
output = 0.0;
return true;
}
if (!value.isDouble() || !std::isfinite(value.toDouble()))
return false;
output = value.toDouble();
return true;
}
bool point(const QJsonValue &value, QPointF &output)
{
double x = 0.0;
double y = 0.0;
if (!value.isObject() || !number(value.toObject(), "x", x)
|| !number(value.toObject(), "y", y))
return false;
output = QPointF(x, y);
return true;
}
struct Bounds {
double minX = 0.0;
double minY = 0.0;
double maxX = 0.0;
double maxY = 0.0;
bool valid = false;
void include(double x, double y)
{
if (!valid) {
minX = maxX = x;
minY = maxY = y;
valid = true;
} else {
minX = std::min(minX, x);
minY = std::min(minY, y);
maxX = std::max(maxX, x);
maxY = std::max(maxY, y);
}
}
};
}
bool renderAgvSmap2d(const QString &content, QImage &image,
QVariantMap &metadata, QString &error)
{
image = QImage();
metadata.clear();
error.clear();
const auto fail = [&error](const QString &message) {
error = message;
return false;
};
QJsonParseError parseError;
const QJsonDocument json = QJsonDocument::fromJson(content.toUtf8(), &parseError);
if (parseError.error != QJsonParseError::NoError || !json.isObject())
return fail(QStringLiteral("地图不是有效的 SEER 2D JSON。"));
QJsonObject root = json.object();
if (!root.value(QStringLiteral("header")).isObject())
return fail(QStringLiteral("地图缺少有效的 header。"));
const QJsonObject header = root.value(QStringLiteral("header")).toObject();
double resolution = 0.0;
if (!number(header, "resolution", resolution) || resolution <= 0.0)
return fail(QStringLiteral("地图分辨率必须为有限正数。"));
// An empty semantic array can also be omitted by Protobuf JSON. Supply it
// only for the document reader; the caller's original content is untouched.
QString semanticContent = content;
if (!root.contains(QStringLiteral("advanced_point_list"))
&& !root.contains(QStringLiteral("advancedPointList"))) {
const bool camel = root.contains(QStringLiteral("normalPosList"))
|| root.contains(QStringLiteral("advancedCurveList"))
|| header.contains(QStringLiteral("mapType"));
root.insert(camel ? QStringLiteral("advancedPointList")
: QStringLiteral("advanced_point_list"), QJsonArray());
semanticContent = QString::fromUtf8(QJsonDocument(root).toJson(QJsonDocument::Compact));
}
AgvMapDocument document;
if (!document.load(semanticContent, &error))
return false;
const QVariantList stations = document.stations();
const QVariantList routes = document.routes();
Bounds bounds;
const QJsonValue minimum = field(header, "min_pos", "minPos");
const QJsonValue maximum = field(header, "max_pos", "maxPos");
if (!minimum.isUndefined() || !maximum.isUndefined()) {
QPointF minPoint;
QPointF maxPoint;
if (!point(minimum, minPoint) || !point(maximum, maxPoint)
|| minPoint.x() > maxPoint.x() || minPoint.y() > maxPoint.y())
return fail(QStringLiteral("地图 header 边界无效。"));
bounds.include(minPoint.x(), minPoint.y());
bounds.include(maxPoint.x(), maxPoint.y());
}
const QJsonValue scanValue = field(root, "normal_pos_list", "normalPosList");
if (!scanValue.isUndefined() && !scanValue.isArray())
return fail(QStringLiteral("地图扫描点列表无效。"));
const QJsonArray scan = scanValue.toArray();
for (const QJsonValue &value : scan) {
QPointF position;
if (!point(value, position))
return fail(QStringLiteral("地图含无效的扫描点坐标。"));
bounds.include(position.x(), position.y());
}
// Semantic-only maps still need a useful world extent. Include routes and
// stations as well so a stale header cannot crop those overlays.
for (const QVariant &value : stations) {
const QVariantMap station = value.toMap();
bounds.include(station.value(QStringLiteral("x")).toDouble(),
station.value(QStringLiteral("y")).toDouble());
}
for (const QVariant &value : routes) {
for (const QVariant &vertex : value.toMap().value(QStringLiteral("points")).toList()) {
const QVariantMap position = vertex.toMap();
const double x = position.value(QStringLiteral("x")).toDouble();
const double y = position.value(QStringLiteral("y")).toDouble();
if (std::isfinite(x) && std::isfinite(y))
bounds.include(x, y);
}
}
if (!bounds.valid)
bounds.include(0.0, 0.0);
// Both extrema are coordinates of samples, not exclusive pixel bounds.
// Include one cell beyond the maximum so even an exact edge point survives.
const double sourceWidthValue = std::ceil((bounds.maxX - bounds.minX) / resolution) + 1.0;
const double sourceHeightValue = std::ceil((bounds.maxY - bounds.minY) / resolution) + 1.0;
const double maximumDimension = std::numeric_limits<int>::max();
if (!std::isfinite(sourceWidthValue) || !std::isfinite(sourceHeightValue)
|| sourceWidthValue < 1.0 || sourceHeightValue < 1.0
|| sourceWidthValue > maximumDimension || sourceHeightValue > maximumDimension)
return fail(QStringLiteral("地图范围或分辨率超出支持的栅格尺寸。"));
const int sourceWidth = static_cast<int>(sourceWidthValue);
const int sourceHeight = static_cast<int>(sourceHeightValue);
const double scale = std::min(1.0, std::min(1600.0 / sourceWidth, 1000.0 / sourceHeight));
const int width = std::min(1600, std::max(1, static_cast<int>(std::ceil(sourceWidth * scale))));
const int height = std::min(1000, std::max(1, static_cast<int>(std::ceil(sourceHeight * scale))));
QImage rendered(width, height, QImage::Format_ARGB32_Premultiplied);
if (rendered.isNull())
return fail(QStringLiteral("无法分配地图图像。"));
rendered.fill(Qt::transparent);
const QRgb occupied = qPremultiply(qRgba(110, 120, 130, 220));
for (const QJsonValue &value : scan) {
QPointF position;
point(value, position); // Validated in the bounds pass.
const double gridX = (position.x() - bounds.minX) / resolution * scale;
const double gridY = (position.y() - bounds.minY) / resolution * scale;
const int x = std::max(0, std::min(width - 1, static_cast<int>(std::floor(gridX))));
const int y = std::max(0, std::min(height - 1, static_cast<int>(std::floor(height - gridY))));
reinterpret_cast<QRgb *>(rendered.scanLine(y))[x] = occupied;
}
metadata = {{QStringLiteral("dimension"), 2},
{QStringLiteral("resolution"), resolution},
{QStringLiteral("originX"), bounds.minX},
{QStringLiteral("originY"), bounds.minY},
// SMAP positions already use the world frame, unlike rotated
// occupancy-grid stream origins.
{QStringLiteral("originTheta"), 0.0},
{QStringLiteral("sourceWidth"), sourceWidth},
{QStringLiteral("sourceHeight"), sourceHeight},
{QStringLiteral("renderScale"), scale},
{QStringLiteral("source"), QStringLiteral("raw-smap")},
{QStringLiteral("scanPointCount"), scan.size()},
{QStringLiteral("semanticOnly"), scan.isEmpty()},
{QStringLiteral("stations"), stations},
{QStringLiteral("routes"), routes}};
const QString mapName = field(header, "map_name", "mapName").toString();
if (!mapName.isEmpty()) {
metadata.insert(QStringLiteral("mapId"), mapName);
metadata.insert(QStringLiteral("mapName"), mapName);
}
image = rendered;
return true;
}

11
src/agvmaprasterizer.h Normal file
View File

@ -0,0 +1,11 @@
#pragma once
#include <QImage>
#include <QString>
#include <QVariantMap>
// Convert world-coordinate SEER SMAP scan points to a bounded transparent
// raster. The caller supplies the device/connection context and final map ID.
// On failure the output image and metadata are cleared and error is populated.
bool renderAgvSmap2d(const QString &content, QImage &image,
QVariantMap &metadata, QString &error);

View File

@ -1,19 +1,49 @@
#include "agvmapviewwidget.h" #include "agvmapviewwidget.h"
#include <QApplication>
#include <QHelpEvent>
#include <QLineF> #include <QLineF>
#include <QMouseEvent> #include <QMouseEvent>
#include <QPainter> #include <QPainter>
#include <QPainterPath> #include <QPainterPath>
#include <QPaintEvent> #include <QPaintEvent>
#include <QPolygonF> #include <QPolygonF>
#include <QResizeEvent>
#include <QToolTip>
#include <QWheelEvent> #include <QWheelEvent>
#include <QtMath> #include <QtMath>
#include <cmath>
namespace { namespace {
constexpr double kMinimumZoom = 0.5; constexpr double kMinimumZoom = 0.5;
constexpr double kMaximumZoom = 8.0; constexpr double kMaximumZoom = 8.0;
constexpr int kMaximumTrajectoryPoints = 600; constexpr int kMaximumTrajectoryPoints = 600;
constexpr double kTrajectoryMinimumDistance = 0.03; constexpr double kTrajectoryMinimumDistance = 0.03;
constexpr double kStationSelectionRadius = 14.0;
constexpr double kMarkerFitMargin = 34.0;
const QColor kCanvasColor(QStringLiteral("#f7f9fc"));
const QColor kRouteColor(QStringLiteral("#2f6fed"));
const QColor kStationColor(QStringLiteral("#f5a033"));
const QColor kSelectedColor(QStringLiteral("#8b4de8"));
bool objectPosition(const QVariantMap &object, QPointF *point)
{
bool validX = false;
bool validY = false;
const double x = object.value(QStringLiteral("x")).toDouble(&validX);
const double y = object.value(QStringLiteral("y")).toDouble(&validY);
if (!validX || !validY || !qIsFinite(x) || !qIsFinite(y))
return false;
*point = QPointF(x, y);
return true;
}
QString stationDisplayName(const QVariantMap &station)
{
const QString name = station.value(QStringLiteral("name")).toString().trimmed();
return name.isEmpty() ? station.value(QStringLiteral("id")).toString() : name;
}
} }
AgvMapViewWidget::AgvMapViewWidget(QWidget *parent) AgvMapViewWidget::AgvMapViewWidget(QWidget *parent)
@ -30,13 +60,50 @@ void AgvMapViewWidget::setMapFrame(const QImage &image,
const QVariantMap &metadata) const QVariantMap &metadata)
{ {
const QString nextMapId = metadata.value(QStringLiteral("mapId")).toString(); const QString nextMapId = metadata.value(QStringLiteral("mapId")).toString();
if (!nextMapId.isEmpty() && nextMapId != m_mapId) { const bool mapChanged = !nextMapId.isEmpty() && nextMapId != m_mapId;
m_mapId = nextMapId;
clearTrajectory();
resetView();
}
m_image = image; m_image = image;
m_metadata = metadata; m_metadata = metadata;
m_mapStations = metadata.value(QStringLiteral("stations")).toList();
m_mapRoutes = metadata.value(QStringLiteral("routes")).toList();
if (mapChanged) {
m_mapId = nextMapId;
if (m_editorMapId != m_mapId)
m_hasEditorObjects = false;
clearTrajectory();
resetView();
} else {
refreshAutoFit();
}
update();
}
void AgvMapViewWidget::clearMapFrame(const QString &message)
{
m_image = QImage();
m_metadata.clear();
m_mapId.clear();
m_editorMapId.clear();
m_mapStations.clear();
m_mapRoutes.clear();
m_editorStations.clear();
m_editorRoutes.clear();
m_selectedStationId.clear();
m_hasEditorObjects = false;
m_hasPose = false;
m_localized = false;
m_trajectory.clear();
m_fitBounds = QRectF();
m_streamMessage = message;
setEditMode(BrowseMode);
resetView();
}
void AgvMapViewWidget::clearRobotPose()
{
m_hasPose = false;
m_localized = false;
m_trajectory.clear();
refreshAutoFit();
update(); update();
} }
@ -60,6 +127,7 @@ void AgvMapViewWidget::updateRobotPose(double x, double y, double theta,
- kMaximumTrajectoryPoints); - kMaximumTrajectoryPoints);
} }
} }
refreshAutoFit();
update(); update();
} }
@ -71,18 +139,20 @@ void AgvMapViewWidget::setStreamMessage(const QString &message)
void AgvMapViewWidget::zoomIn() void AgvMapViewWidget::zoomIn()
{ {
changeZoom(1.25, rect().center()); changeZoom(1.25, viewportCenter());
} }
void AgvMapViewWidget::zoomOut() void AgvMapViewWidget::zoomOut()
{ {
changeZoom(0.8, rect().center()); changeZoom(0.8, viewportCenter());
} }
void AgvMapViewWidget::resetView() void AgvMapViewWidget::resetView()
{ {
m_zoom = 1.0; m_zoom = 1.0;
m_pan = QPointF(); m_pan = QPointF();
m_autoFit = true;
refreshAutoFit();
update(); update();
} }
@ -92,12 +162,91 @@ void AgvMapViewWidget::clearTrajectory()
update(); update();
} }
void AgvMapViewWidget::setEditMode(EditMode mode)
{
m_editMode = mode;
m_dragging = false;
m_pressedButton = Qt::NoButton;
updateInteractionCursor();
setToolTip(mode == AddStationMode
? QStringLiteral("点击地图添加站点;拖动或按住右键平移")
: mode == AddRouteMode
? QStringLiteral("依次点击起点和终点站点添加路线;按住右键平移")
: QStringLiteral("拖动平移地图,滚轮缩放"));
}
void AgvMapViewWidget::setEditorObjects(const QVariantList &stations,
const QVariantList &routes, bool authoritative)
{
m_editorStations = stations;
m_editorRoutes = routes;
m_editorMapId = m_mapId;
m_hasEditorObjects = authoritative || !stations.isEmpty() || !routes.isEmpty();
refreshAutoFit();
update();
}
void AgvMapViewWidget::setSelectedStation(const QString &id)
{
m_selectedStationId = id;
update();
}
bool AgvMapViewWidget::canProjectPose() const bool AgvMapViewWidget::canProjectPose() const
{ {
bool validResolution = false;
bool validRenderScale = false;
bool validOriginX = false;
bool validOriginY = false;
bool validOriginTheta = false;
const double resolution = m_metadata.value(QStringLiteral("resolution"))
.toDouble(&validResolution);
const double renderScale = m_metadata.value(QStringLiteral("renderScale"), 1.0)
.toDouble(&validRenderScale);
const double originX = m_metadata.value(QStringLiteral("originX"))
.toDouble(&validOriginX);
const double originY = m_metadata.value(QStringLiteral("originY"))
.toDouble(&validOriginY);
const double originTheta = m_metadata.value(QStringLiteral("originTheta"))
.toDouble(&validOriginTheta);
return !m_image.isNull() return !m_image.isNull()
&& m_metadata.value(QStringLiteral("dimension")).toInt() == 2 && m_metadata.value(QStringLiteral("dimension")).toInt() == 2
&& m_metadata.value(QStringLiteral("resolution")).toDouble() > 0.0 && validResolution && qIsFinite(resolution) && resolution > 0.0
&& m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble() > 0.0; && validRenderScale && qIsFinite(renderScale) && renderScale > 0.0
&& validOriginX && qIsFinite(originX)
&& validOriginY && qIsFinite(originY)
&& validOriginTheta && qIsFinite(originTheta);
}
bool AgvMapViewWidget::widgetToWorld(const QPointF &point,
QPointF *worldPoint) const
{
if (!worldPoint || !canProjectPose()
|| !qIsFinite(point.x()) || !qIsFinite(point.y()))
return false;
const double scale = viewScale();
if (!qIsFinite(scale) || scale <= 0.0)
return false;
const QPointF imagePoint = (point - imageTopLeft()) / scale;
// The canvas includes the world around the received image; do not treat
// image bounds as the limit of the map coordinate system.
if (!QRectF(rect()).adjusted(8, 8, -8, -8).contains(point))
return false;
const double resolution = m_metadata.value(QStringLiteral("resolution")).toDouble();
const double renderScale = m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble();
const double originTheta = m_metadata.value(QStringLiteral("originTheta")).toDouble();
const double localX = imagePoint.x() / renderScale * resolution;
const double localY = (m_image.height() - imagePoint.y()) / renderScale * resolution;
const double cosine = qCos(originTheta);
const double sine = qSin(originTheta);
const QPointF result(
m_metadata.value(QStringLiteral("originX")).toDouble() + cosine * localX - sine * localY,
m_metadata.value(QStringLiteral("originY")).toDouble() + sine * localX + cosine * localY);
if (!qIsFinite(result.x()) || !qIsFinite(result.y()))
return false;
*worldPoint = result;
return true;
} }
QPointF AgvMapViewWidget::worldToImage(double x, double y) const QPointF AgvMapViewWidget::worldToImage(double x, double y) const
@ -118,24 +267,124 @@ QPointF AgvMapViewWidget::worldToImage(double x, double y) const
m_image.height() - gridY * renderScale); m_image.height() - gridY * renderScale);
} }
QRectF AgvMapViewWidget::sceneBounds() const
{
if (m_image.isNull())
return QRectF();
QRectF bounds(QPointF(), QSizeF(m_image.size()));
if (!canProjectPose())
return bounds;
QVector<QPointF> projectedPoints;
const auto includePoint = [this, &projectedPoints, &bounds](double x, double y) {
const QPointF point = worldToImage(x, y);
if (!qIsFinite(point.x()) || !qIsFinite(point.y()))
return;
const QRectF combined(QPointF(qMin(bounds.left(), point.x()),
qMin(bounds.top(), point.y())),
QPointF(qMax(bounds.right(), point.x()),
qMax(bounds.bottom(), point.y())));
if (qIsFinite(combined.width()) && qIsFinite(combined.height())) {
bounds = combined;
projectedPoints.append(point);
}
};
if (m_hasPose)
includePoint(m_robotX, m_robotY);
for (const QVariant &entry : editorStations()) {
QPointF point;
if (objectPosition(entry.toMap(), &point))
includePoint(point.x(), point.y());
}
for (const QVariant &entry : editorRoutes()) {
for (const QVariant &value : entry.toMap().value(QStringLiteral("points")).toList()) {
QPointF point;
if (objectPosition(value.toMap(), &point))
includePoint(point.x(), point.y());
}
}
const double rawScale = qMin(qMax(1, width() - 24) / bounds.width(),
qMax(1, height() - 52) / bounds.height());
if (qIsFinite(rawScale) && rawScale > 0.0) {
const double margin = kMarkerFitMargin / rawScale;
for (const QPointF &point : projectedPoints) {
const QRectF marker(point - QPointF(margin, margin),
QSizeF(margin * 2.0, margin * 2.0));
const QRectF combined = bounds.united(marker);
if (qIsFinite(combined.width()) && qIsFinite(combined.height()))
bounds = combined;
}
}
return bounds;
}
QRectF AgvMapViewWidget::fittedBounds() const
{
return m_fitBounds.isValid() ? m_fitBounds
: QRectF(QPointF(), QSizeF(m_image.size()));
}
void AgvMapViewWidget::refreshAutoFit()
{
if (m_autoFit)
m_fitBounds = sceneBounds();
}
const QVariantList &AgvMapViewWidget::editorStations() const
{
return m_hasEditorObjects && m_editorMapId == m_mapId ? m_editorStations : m_mapStations;
}
const QVariantList &AgvMapViewWidget::editorRoutes() const
{
return m_hasEditorObjects && m_editorMapId == m_mapId ? m_editorRoutes : m_mapRoutes;
}
QVariantMap AgvMapViewWidget::stationAt(const QPointF &point) const
{
if (!canProjectPose())
return {};
QVariantMap nearest;
double nearestDistance = kStationSelectionRadius;
for (const QVariant &entry : editorStations()) {
const QVariantMap station = entry.toMap();
QPointF world;
if (station.value(QStringLiteral("id")).toString().isEmpty()
|| !objectPosition(station, &world))
continue;
const QPointF position = imageToWidget(worldToImage(world.x(), world.y()));
const double distance = QLineF(point, position).length();
if (qIsFinite(distance) && distance <= kStationSelectionRadius + 1e-6
&& (nearest.isEmpty() || distance < nearestDistance)) {
nearestDistance = distance;
nearest = station;
}
}
return nearest;
}
double AgvMapViewWidget::viewScale() const double AgvMapViewWidget::viewScale() const
{ {
if (m_image.isNull()) if (m_image.isNull())
return 1.0; return 1.0;
const double horizontal = qMax(1, width() - 24) const QRectF bounds = fittedBounds();
/ static_cast<double>(m_image.width()); const double horizontal = qMax(1, width() - 24) / bounds.width();
const double vertical = qMax(1, height() - 24) const double vertical = qMax(1, height() - 52) / bounds.height();
/ static_cast<double>(m_image.height());
return qMin(horizontal, vertical) * m_zoom; return qMin(horizontal, vertical) * m_zoom;
} }
QPointF AgvMapViewWidget::viewportCenter() const
{
// Reserve the bottom ruler separately from the map's outer margin.
return QPointF(width() * 0.5, (height() - 28) * 0.5);
}
QPointF AgvMapViewWidget::imageTopLeft() const QPointF AgvMapViewWidget::imageTopLeft() const
{ {
if (m_image.isNull()) if (m_image.isNull())
return QPointF(); return QPointF();
const double scale = viewScale(); const double scale = viewScale();
return QPointF((width() - m_image.width() * scale) * 0.5, return viewportCenter()
(height() - m_image.height() * scale) * 0.5) + m_pan; - fittedBounds().center() * scale + m_pan;
} }
QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const
@ -143,59 +392,267 @@ QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const
return imageTopLeft() + point * viewScale(); return imageTopLeft() + point * viewScale();
} }
void AgvMapViewWidget::drawCoordinateAxes(QPainter &painter) const void AgvMapViewWidget::drawObjectLabel(QPainter &painter, const QString &text,
const QPointF &topLeft,
const QColor &color) const
{ {
constexpr double panelSize = 92.0; painter.save();
constexpr double panelMargin = 12.0; QFont labelFont = painter.font();
constexpr double arrowLength = 27.0; labelFont.setPointSize(9);
const QRectF panel(width() - panelMargin - panelSize, labelFont.setBold(true);
panelMargin, panelSize, panelSize); painter.setFont(labelFont);
const QFontMetrics metrics(labelFont);
const QString label = metrics.elidedText(text.simplified(), Qt::ElideRight,
qMin(270, qMax(80, width() - 48)));
QRectF labelRect(QPointF(), QSizeF(metrics.horizontalAdvance(label) + 2,
metrics.height() + 2));
labelRect.moveTopLeft(topLeft);
labelRect.moveLeft(qBound(16.0, labelRect.left(),
qMax(16.0, width() - 16.0 - labelRect.width())));
labelRect.moveTop(qBound(16.0, labelRect.top(),
qMax(16.0, height() - 42.0 - labelRect.height())));
QPainterPath lettering;
lettering.addText(labelRect.left() + 1, labelRect.top() + metrics.ascent() + 1,
labelFont, label);
painter.strokePath(lettering, QPen(kCanvasColor, 3, Qt::SolidLine,
Qt::RoundCap, Qt::RoundJoin));
painter.fillPath(lettering, color);
painter.restore();
}
void AgvMapViewWidget::drawEditorObjects(QPainter &painter) const
{
if (!canProjectPose())
return;
painter.save(); painter.save();
painter.setPen(QPen(QColor(QStringLiteral("#c9d4de")), 1)); for (const QVariant &entry : editorRoutes()) {
painter.setBrush(QColor(255, 255, 255, 232)); const QVariantMap route = entry.toMap();
painter.drawRoundedRect(panel, 8, 8); const QVariantList points = route.value(QStringLiteral("points")).toList();
QPolygonF geometry;
bool valid = true;
for (const QVariant &value : points) {
QPointF world;
if (!objectPosition(value.toMap(), &world)) {
valid = false;
break;
}
const QPointF projected = imageToWidget(worldToImage(world.x(), world.y()));
if (!qIsFinite(projected.x()) || !qIsFinite(projected.y())) {
valid = false;
break;
}
geometry.append(projected);
}
if (!valid || geometry.size() < 2)
continue;
const bool draft = route.value(QStringLiteral("draft")).toBool();
const QColor color = draft ? QColor(QStringLiteral("#789af0")) : kRouteColor;
painter.setPen(QPen(color, 2.0, draft ? Qt::DashLine : Qt::SolidLine,
Qt::RoundCap, Qt::RoundJoin));
painter.setBrush(Qt::NoBrush);
painter.drawPolyline(geometry);
const QPointF center = panel.center(); double routeLength = 0.0;
const double originTheta = m_metadata.value( for (int index = 1; index < geometry.size(); ++index)
QStringLiteral("originTheta")).toDouble(); routeLength += QLineF(geometry.at(index - 1), geometry.at(index)).length();
const QPointF xDirection(qCos(originTheta), qSin(originTheta)); if (!qIsFinite(routeLength) || routeLength < 20.0)
const QPointF yDirection(qSin(originTheta), -qCos(originTheta)); continue;
// SMAP curves are sampled into many short segments. Place directions
// by distance along the complete route, independently of sample density.
const auto drawArrow = [&painter, &geometry, routeLength, color](double fraction,
bool reverse) {
const double targetDistance = routeLength * fraction;
double distance = 0.0;
for (int index = 1; index < geometry.size(); ++index) {
const QLineF segment(geometry.at(index - 1), geometry.at(index));
const double length = segment.length();
if (length <= 0.0)
continue;
if (distance + length < targetDistance) {
distance += length;
continue;
}
QPointF direction = (segment.p2() - segment.p1()) / length;
if (reverse)
direction = -direction;
const QPointF normal(-direction.y(), direction.x());
const QPointF tip = segment.pointAt((targetDistance - distance) / length);
QPolygonF arrow;
arrow << tip << tip - direction * 8.0 + normal * 4.0
<< tip - direction * 8.0 - normal * 4.0;
painter.setPen(Qt::NoPen);
painter.setBrush(color);
painter.drawPolygon(arrow);
return;
}
};
drawArrow(0.65, false);
if (route.value(QStringLiteral("bidirectional")).toBool())
drawArrow(0.35, true);
}
const auto drawArrow = [&painter, center, arrowLength]( for (const QVariant &entry : editorStations()) {
const QPointF &direction, const QVariantMap station = entry.toMap();
const QColor &color, QPointF world;
const QString &label) { if (!objectPosition(station, &world))
const QPointF normal(-direction.y(), direction.x()); continue;
const QPointF tip = center + direction * arrowLength; const QPointF center = imageToWidget(worldToImage(world.x(), world.y()));
painter.setPen(QPen(color, 2.4, Qt::SolidLine, Qt::RoundCap)); if (!qIsFinite(center.x()) || !qIsFinite(center.y()))
continue;
const QString id = station.value(QStringLiteral("id")).toString();
const bool selected = !id.isEmpty() && id == m_selectedStationId;
const bool draft = station.value(QStringLiteral("draft")).toBool();
const QString kind = station.value(QStringLiteral("type")).toString()
+ QLatin1Char(' ') + station.value(QStringLiteral("class")).toString();
const bool charging = kind.contains(QStringLiteral("charge"), Qt::CaseInsensitive)
|| kind.contains(QStringLiteral("charging"), Qt::CaseInsensitive);
const QColor color = selected ? kSelectedColor
: charging ? QColor(QStringLiteral("#169f91"))
: draft ? QColor(QStringLiteral("#f7bc70")) : kStationColor;
if (selected) {
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(139, 77, 232, 40));
painter.drawEllipse(center, 14, 14);
}
painter.setPen(QPen(QColor(QStringLiteral("#ffffff")), 1.8));
painter.setBrush(color); painter.setBrush(color);
painter.drawLine(center, tip); if (charging) {
QPolygonF diamond;
diamond << center + QPointF(0, -7.5) << center + QPointF(7.5, 0)
<< center + QPointF(0, 7.5) << center + QPointF(-7.5, 0);
painter.drawPolygon(diamond);
} else {
painter.drawEllipse(center, 6, 6);
}
const QString name = stationDisplayName(station);
if (!name.isEmpty()) {
drawObjectLabel(painter, draft ? name + QStringLiteral(" · 草稿") : name,
center + QPointF(9, -24),
selected ? kSelectedColor
: QColor(QStringLiteral("#20334d")));
}
}
painter.restore();
}
QPolygonF arrowHead; double AgvMapViewWidget::gridStep() const
arrowHead << tip {
<< tip - direction * 8.0 + normal * 4.5 if (!canProjectPose())
<< tip - direction * 8.0 - normal * 4.5; return 1.0;
painter.setPen(Qt::NoPen); const double pixelsPerMeter = viewScale()
painter.drawPolygon(arrowHead); * m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble()
/ m_metadata.value(QStringLiteral("resolution")).toDouble();
const double desiredStep = 56.0 / pixelsPerMeter;
if (!qIsFinite(desiredStep) || desiredStep <= 0.0)
return 1.0;
const double magnitude = qPow(10.0, qFloor(qLn(desiredStep) / qLn(10.0)));
const double normalized = desiredStep / magnitude;
const double multiplier = normalized < 1.5 ? 1.0
: normalized < 3.5 ? 2.0 : normalized < 7.5 ? 5.0 : 10.0;
return magnitude * multiplier;
}
const QPointF labelCenter = tip + direction * 9.0; void AgvMapViewWidget::drawWorldGrid(QPainter &painter) const
const QRectF labelRect(labelCenter.x() - 9.0, {
labelCenter.y() - 9.0, 18.0, 18.0); if (!canProjectPose())
QFont labelFont = painter.font(); return;
labelFont.setBold(true); const QRectF visible = QRectF(rect()).adjusted(8, 8, -8, -8);
painter.setFont(labelFont); const QList<QPointF> corners = {visible.topLeft(), visible.topRight(),
painter.setPen(color); visible.bottomLeft(), visible.bottomRight()};
painter.drawText(labelRect, Qt::AlignCenter, label); QRectF worldBounds;
bool first = true;
for (const QPointF &corner : corners) {
QPointF world;
if (!widgetToWorld(corner, &world))
return;
if (first) {
worldBounds = QRectF(world, world);
first = false;
} else {
worldBounds = QRectF(QPointF(qMin(worldBounds.left(), world.x()),
qMin(worldBounds.top(), world.y())),
QPointF(qMax(worldBounds.right(), world.x()),
qMax(worldBounds.bottom(), world.y())));
}
}
const double step = gridStep();
if (!qIsFinite(step) || step <= 0.0)
return;
const auto project = [this](double x, double y) {
return imageToWidget(worldToImage(x, y));
}; };
painter.save();
painter.setPen(QPen(QColor(QStringLiteral("#d8e2f1")), 1.0));
const double firstX = std::floor(worldBounds.left() / step) * step;
const double firstY = std::floor(worldBounds.top() / step) * step;
for (int index = 0; index < 300; ++index) {
const double x = firstX + index * step;
if (!qIsFinite(x) || x > worldBounds.right() + step)
break;
painter.drawLine(project(x, worldBounds.top() - step),
project(x, worldBounds.bottom() + step));
}
for (int index = 0; index < 300; ++index) {
const double y = firstY + index * step;
if (!qIsFinite(y) || y > worldBounds.bottom() + step)
break;
painter.drawLine(project(worldBounds.left() - step, y),
project(worldBounds.right() + step, y));
}
painter.setPen(QPen(QColor(QStringLiteral("#c7d6ef")), 1));
painter.drawLine(project(0, worldBounds.top() - step),
project(0, worldBounds.bottom() + step));
painter.drawLine(project(worldBounds.left() - step, 0),
project(worldBounds.right() + step, 0));
painter.restore();
}
drawArrow(xDirection, QColor(QStringLiteral("#d94a4a")), void AgvMapViewWidget::drawCoordinateAxes(QPainter &painter) const
QStringLiteral("X")); {
drawArrow(yDirection, QColor(QStringLiteral("#2f9e69")), QPointF leftWorld;
QStringLiteral("Y")); QPointF rightWorld;
painter.setPen(Qt::NoPen); const double left = 12.0;
painter.setBrush(QColor(QStringLiteral("#374151"))); const double right = width() - 48.0;
painter.drawEllipse(center, 3.2, 3.2); const double baseline = height() - 14.0;
if (!widgetToWorld(QPointF(left, baseline), &leftWorld)
|| !widgetToWorld(QPointF(right, baseline), &rightWorld))
return;
const bool useX = qAbs(rightWorld.x() - leftWorld.x())
>= qAbs(rightWorld.y() - leftWorld.y());
const double start = useX ? leftWorld.x() : leftWorld.y();
const double end = useX ? rightWorld.x() : rightWorld.y();
const double derivative = (end - start) / (right - left);
const double step = gridStep();
if (!qIsFinite(derivative) || qAbs(derivative) < 1e-15
|| !qIsFinite(step) || step <= 0.0)
return;
painter.save();
QColor rulerBackground = kCanvasColor;
rulerBackground.setAlpha(240);
painter.fillRect(QRectF(0, height() - 26, width(), 26), rulerBackground);
QFont scaleFont = painter.font();
scaleFont.setPointSize(8);
scaleFont.setBold(false);
painter.setFont(scaleFont);
painter.setPen(QPen(QColor(QStringLiteral("#90a7cc")), 0.7));
const int decimals = qBound(0, -qFloor(qLn(step) / qLn(10.0)), 6);
const double firstValue = std::ceil(qMin(start, end) / step) * step;
for (int index = 0; index < 300; ++index) {
double value = firstValue + index * step;
if (!qIsFinite(value) || value > qMax(start, end))
break;
const double x = left + (value - start) / derivative;
painter.drawLine(QPointF(x, height() - 26), QPointF(x, height() - 22));
if (qAbs(value) < step * 1e-6)
value = 0.0;
painter.drawText(QRectF(x - 23, height() - 21, 46, 17), Qt::AlignCenter,
QString::number(value, 'f', decimals));
}
painter.drawText(QRectF(width() - 46, height() - 21, 38, 17),
Qt::AlignRight | Qt::AlignVCenter,
useX ? QStringLiteral("X / m") : QStringLiteral("Y / m"));
painter.restore(); painter.restore();
} }
@ -204,7 +661,12 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event)
Q_UNUSED(event) Q_UNUSED(event)
QPainter painter(this); QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::Antialiasing);
painter.fillRect(rect(), QColor(QStringLiteral("#eef2f6"))); painter.fillRect(rect(), kCanvasColor);
QPainterPath canvas;
canvas.addRoundedRect(QRectF(rect()).adjusted(1, 1, -1, -1), 10, 10);
painter.fillPath(canvas, kCanvasColor);
painter.save();
painter.setClipPath(canvas);
if (m_image.isNull()) { if (m_image.isNull()) {
painter.setPen(QColor(QStringLiteral("#71808e"))); painter.setPen(QColor(QStringLiteral("#71808e")));
@ -212,6 +674,7 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event)
m_streamMessage.isEmpty() m_streamMessage.isEmpty()
? QStringLiteral("等待 AGV 返回地图数据") ? QStringLiteral("等待 AGV 返回地图数据")
: m_streamMessage); : m_streamMessage);
painter.restore();
return; return;
} }
@ -220,12 +683,11 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event)
const QRectF target(topLeft, const QRectF target(topLeft,
QSizeF(m_image.width() * scale, QSizeF(m_image.width() * scale,
m_image.height() * scale)); m_image.height() * scale));
drawWorldGrid(painter);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawImage(target, m_image); painter.drawImage(target, m_image);
painter.setPen(QPen(QColor(QStringLiteral("#c9d4de")), 1));
painter.setBrush(Qt::NoBrush);
painter.drawRect(target);
painter.save();
if (canProjectPose() && m_trajectory.size() > 1) { if (canProjectPose() && m_trajectory.size() > 1) {
QPainterPath path; QPainterPath path;
path.moveTo(imageToWidget(worldToImage( path.moveTo(imageToWidget(worldToImage(
@ -234,11 +696,13 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event)
path.lineTo(imageToWidget(worldToImage( path.lineTo(imageToWidget(worldToImage(
m_trajectory.at(index).x(), m_trajectory.at(index).y()))); m_trajectory.at(index).x(), m_trajectory.at(index).y())));
} }
painter.setPen(QPen(QColor(QStringLiteral("#2f6fed")), 2, painter.setPen(QPen(QColor(QStringLiteral("#91b4e8")), 1.0,
Qt::DashLine, Qt::RoundCap, Qt::RoundJoin)); Qt::DashLine, Qt::RoundCap, Qt::RoundJoin));
painter.drawPath(path); painter.drawPath(path);
} }
drawEditorObjects(painter);
if (canProjectPose() && m_hasPose) { if (canProjectPose() && m_hasPose) {
const QPointF center = imageToWidget(worldToImage(m_robotX, m_robotY)); const QPointF center = imageToWidget(worldToImage(m_robotX, m_robotY));
const double originTheta = m_metadata.value( const double originTheta = m_metadata.value(
@ -246,46 +710,57 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event)
const double angle = m_robotTheta - originTheta; const double angle = m_robotTheta - originTheta;
const QPointF forward(qCos(angle), -qSin(angle)); const QPointF forward(qCos(angle), -qSin(angle));
const QPointF lateral(-forward.y(), forward.x()); const QPointF lateral(-forward.y(), forward.x());
const double size = 13.0; const double size = 10.0;
QPolygonF robot; QPolygonF robot;
robot << center + forward * size robot << center + forward * size
<< center - forward * size * 0.7 + lateral * size * 0.65 << center - forward * size * 0.7 + lateral * size * 0.65
<< center - forward * size * 0.7 - lateral * size * 0.65; << center - forward * size * 0.7 - lateral * size * 0.65;
painter.setPen(Qt::NoPen); painter.setPen(QPen(QColor(QStringLiteral("#ffffff")), 1.4));
painter.setBrush(QColor(47, 111, 237, m_localized ? 48 : 24)); QColor robotColor = kRouteColor;
painter.drawEllipse(center, 25, 25); robotColor.setAlpha(m_localized ? 255 : 150);
painter.setBrush(m_localized painter.setBrush(robotColor);
? QColor(QStringLiteral("#2f6fed"))
: QColor(QStringLiteral("#df8b24")));
painter.drawPolygon(robot); painter.drawPolygon(robot);
painter.setPen(QColor(QStringLiteral("#ffffff"))); painter.setPen(QColor(QStringLiteral("#ffffff")));
painter.drawLine(center - forward * 2, center + forward * 7); painter.drawLine(center - forward * 2, center + forward * 7);
const QString poseText = QStringLiteral("(%1, %2, %3°)") drawObjectLabel(painter, QStringLiteral("AGV"), center + QPointF(11, -22),
.arg(m_robotX, 0, 'f', 2) kRouteColor);
.arg(m_robotY, 0, 'f', 2)
.arg(qRadiansToDegrees(m_robotTheta), 0, 'f', 1);
const QFontMetrics metrics(painter.font());
QRectF labelRect = metrics.boundingRect(poseText);
labelRect.adjust(-7, -4, 7, 4);
labelRect.moveBottomLeft(center + QPointF(16, -14));
painter.setPen(QPen(QColor(QStringLiteral("#b9c9dc")), 1));
painter.setBrush(QColor(255, 255, 255, 238));
painter.drawRoundedRect(labelRect, 6, 6);
painter.setPen(QColor(QStringLiteral("#145da8")));
painter.drawText(labelRect, Qt::AlignCenter, poseText);
} }
painter.restore();
if (canProjectPose()) if (canProjectPose())
drawCoordinateAxes(painter); drawCoordinateAxes(painter);
if (!m_streamMessage.isEmpty()) { if (m_metadata.value(QStringLiteral("demo")).toBool()) {
const QRect messageRect(12, height() - 36, width() - 24, 24); QFont badgeFont = painter.font();
painter.setPen(QColor(QStringLiteral("#5c6975"))); badgeFont.setPointSize(9);
painter.drawText(messageRect, Qt::AlignLeft | Qt::AlignVCenter, painter.setFont(badgeFont);
m_streamMessage); painter.setPen(QColor(QStringLiteral("#7c8ba0")));
painter.drawText(QRectF(14, 10, 150, 20), Qt::AlignLeft | Qt::AlignVCenter,
QStringLiteral("DEMO · 扫描样例"));
} }
if (m_streamMessage.contains(QStringLiteral("失败"))
|| m_streamMessage.contains(QStringLiteral("断开"))
|| m_streamMessage.contains(QStringLiteral("错误"))
|| m_streamMessage.contains(QStringLiteral("等待"))) {
QFont messageFont = painter.font();
messageFont.setPointSize(9);
painter.setFont(messageFont);
const QFontMetrics metrics(messageFont);
const QString message = metrics.elidedText(m_streamMessage, Qt::ElideRight,
qMax(80, width() - 48));
const QRectF messageRect(12, 10,
metrics.horizontalAdvance(message) + 18, 22);
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(247, 249, 252, 238));
painter.drawRoundedRect(messageRect, 5, 5);
painter.setPen(QColor(QStringLiteral("#5c6975")));
painter.drawText(messageRect.adjusted(9, 0, -9, 0),
Qt::AlignLeft | Qt::AlignVCenter, message);
}
painter.restore();
} }
void AgvMapViewWidget::changeZoom(double factor, const QPointF &anchor) void AgvMapViewWidget::changeZoom(double factor, const QPointF &anchor)
@ -294,11 +769,11 @@ void AgvMapViewWidget::changeZoom(double factor, const QPointF &anchor)
return; return;
const double oldScale = viewScale(); const double oldScale = viewScale();
const QPointF imagePoint = (anchor - imageTopLeft()) / oldScale; const QPointF imagePoint = (anchor - imageTopLeft()) / oldScale;
m_autoFit = false;
m_zoom = qBound(kMinimumZoom, m_zoom * factor, kMaximumZoom); m_zoom = qBound(kMinimumZoom, m_zoom * factor, kMaximumZoom);
const double newScale = viewScale(); const double newScale = viewScale();
const QPointF centeredTopLeft( const QPointF centeredTopLeft = viewportCenter()
(width() - m_image.width() * newScale) * 0.5, - fittedBounds().center() * newScale;
(height() - m_image.height() * newScale) * 0.5);
m_pan = anchor - imagePoint * newScale - centeredTopLeft; m_pan = anchor - imagePoint * newScale - centeredTopLeft;
update(); update();
} }
@ -311,19 +786,53 @@ void AgvMapViewWidget::wheelEvent(QWheelEvent *event)
void AgvMapViewWidget::mousePressEvent(QMouseEvent *event) void AgvMapViewWidget::mousePressEvent(QMouseEvent *event)
{ {
if (event->button() == Qt::LeftButton) { if (event->button() == Qt::LeftButton || event->button() == Qt::RightButton) {
m_dragging = true; m_dragging = true;
m_mouseMoved = false;
m_pressedButton = event->button();
m_mousePressPosition = event->pos();
m_lastMousePosition = event->pos(); m_lastMousePosition = event->pos();
setCursor(Qt::ClosedHandCursor); if (m_editMode == BrowseMode || m_pressedButton == Qt::RightButton)
setCursor(Qt::ClosedHandCursor);
event->accept(); event->accept();
return; return;
} }
QWidget::mousePressEvent(event); QWidget::mousePressEvent(event);
} }
bool AgvMapViewWidget::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip && !m_dragging) {
auto *help = static_cast<QHelpEvent *>(event);
const QVariantMap station = stationAt(help->pos());
if (!station.isEmpty()) {
const QString id = station.value(QStringLiteral("id")).toString();
const QString name = stationDisplayName(station);
const QString text = name == id ? id : name + QStringLiteral("\nID: ") + id;
QToolTip::showText(help->globalPos(),
QStringLiteral("<qt>%1</qt>").arg(text.toHtmlEscaped().replace(
QLatin1Char('\n'), QStringLiteral("<br>"))), this);
event->accept();
return true;
}
}
return QWidget::event(event);
}
void AgvMapViewWidget::mouseMoveEvent(QMouseEvent *event) void AgvMapViewWidget::mouseMoveEvent(QMouseEvent *event)
{ {
if (m_dragging) { if (m_dragging) {
if (m_editMode != BrowseMode && m_pressedButton == Qt::LeftButton
&& !m_mouseMoved) {
if ((event->pos() - m_mousePressPosition).manhattanLength()
< QApplication::startDragDistance()) {
event->accept();
return;
}
m_mouseMoved = true;
setCursor(Qt::ClosedHandCursor);
}
m_autoFit = false;
m_pan += event->pos() - m_lastMousePosition; m_pan += event->pos() - m_lastMousePosition;
m_lastMousePosition = event->pos(); m_lastMousePosition = event->pos();
update(); update();
@ -335,11 +844,51 @@ void AgvMapViewWidget::mouseMoveEvent(QMouseEvent *event)
void AgvMapViewWidget::mouseReleaseEvent(QMouseEvent *event) void AgvMapViewWidget::mouseReleaseEvent(QMouseEvent *event)
{ {
if (event->button() == Qt::LeftButton && m_dragging) { if (event->button() == m_pressedButton && m_dragging) {
if (m_editMode != BrowseMode && m_pressedButton == Qt::LeftButton
&& !m_mouseMoved
&& (event->pos() - m_mousePressPosition).manhattanLength()
>= QApplication::startDragDistance()) {
m_autoFit = false;
m_pan += event->pos() - m_lastMousePosition;
m_mouseMoved = true;
update();
}
const bool editClick = m_editMode != BrowseMode
&& m_pressedButton == Qt::LeftButton && !m_mouseMoved
&& (event->pos() - m_mousePressPosition).manhattanLength()
< QApplication::startDragDistance();
m_dragging = false; m_dragging = false;
setCursor(Qt::OpenHandCursor); m_pressedButton = Qt::NoButton;
updateInteractionCursor();
if (editClick) {
QPointF world;
if (widgetToWorld(event->localPos(), &world)) {
if (m_editMode == AddStationMode) {
emit mapPointSelected(world.x(), world.y());
} else if (m_editMode == AddRouteMode) {
const QString nearestId = stationAt(event->localPos())
.value(QStringLiteral("id")).toString();
if (!nearestId.isEmpty()) {
setSelectedStation(nearestId);
emit stationSelected(nearestId);
}
}
}
}
event->accept(); event->accept();
return; return;
} }
QWidget::mouseReleaseEvent(event); QWidget::mouseReleaseEvent(event);
} }
void AgvMapViewWidget::updateInteractionCursor()
{
setCursor(m_editMode == BrowseMode ? Qt::OpenHandCursor : Qt::CrossCursor);
}
void AgvMapViewWidget::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
refreshAutoFit();
}

View File

@ -4,6 +4,7 @@
#include <QPoint> #include <QPoint>
#include <QPointF> #include <QPointF>
#include <QString> #include <QString>
#include <QVariantList>
#include <QVariantMap> #include <QVariantMap>
#include <QVector> #include <QVector>
#include <QWidget> #include <QWidget>
@ -11,44 +12,86 @@
class QMouseEvent; class QMouseEvent;
class QPainter; class QPainter;
class QPaintEvent; class QPaintEvent;
class QResizeEvent;
class QWheelEvent; class QWheelEvent;
class AgvMapViewWidget final : public QWidget class AgvMapViewWidget final : public QWidget
{ {
Q_OBJECT
public: public:
enum EditMode { BrowseMode, AddStationMode, AddRouteMode };
explicit AgvMapViewWidget(QWidget *parent = nullptr); explicit AgvMapViewWidget(QWidget *parent = nullptr);
void setMapFrame(const QImage &image, const QVariantMap &metadata); void setMapFrame(const QImage &image, const QVariantMap &metadata);
void clearMapFrame(const QString &message);
void updateRobotPose(double x, double y, double theta, bool localized); void updateRobotPose(double x, double y, double theta, bool localized);
void clearRobotPose();
void setStreamMessage(const QString &message); void setStreamMessage(const QString &message);
void zoomIn(); void zoomIn();
void zoomOut(); void zoomOut();
void resetView(); void resetView();
void clearTrajectory(); void clearTrajectory();
void setEditMode(EditMode mode);
void setEditorObjects(const QVariantList &stations, const QVariantList &routes,
bool authoritative = false);
void setSelectedStation(const QString &id);
QString mapId() const { return m_mapId; }
bool widgetToWorld(const QPointF &point, QPointF *worldPoint) const;
signals:
void mapPointSelected(double x, double y);
void stationSelected(const QString &id);
protected: protected:
bool event(QEvent *event) override;
void paintEvent(QPaintEvent *event) override; void paintEvent(QPaintEvent *event) override;
void wheelEvent(QWheelEvent *event) override; void wheelEvent(QWheelEvent *event) override;
void mousePressEvent(QMouseEvent *event) override; void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
private: private:
bool canProjectPose() const; bool canProjectPose() const;
QPointF worldToImage(double x, double y) const; QPointF worldToImage(double x, double y) const;
QPointF imageToWidget(const QPointF &point) const; QPointF imageToWidget(const QPointF &point) const;
QRectF sceneBounds() const;
QRectF fittedBounds() const;
void refreshAutoFit();
const QVariantList &editorStations() const;
const QVariantList &editorRoutes() const;
QVariantMap stationAt(const QPointF &point) const;
double viewScale() const; double viewScale() const;
QPointF viewportCenter() const;
QPointF imageTopLeft() const; QPointF imageTopLeft() const;
double gridStep() const;
void drawWorldGrid(QPainter &painter) const;
void drawCoordinateAxes(QPainter &painter) const; void drawCoordinateAxes(QPainter &painter) const;
void drawEditorObjects(QPainter &painter) const;
void drawObjectLabel(QPainter &painter, const QString &text,
const QPointF &topLeft, const QColor &color) const;
void changeZoom(double factor, const QPointF &anchor); void changeZoom(double factor, const QPointF &anchor);
void updateInteractionCursor();
QImage m_image; QImage m_image;
QVariantMap m_metadata; QVariantMap m_metadata;
QVector<QPointF> m_trajectory; QVector<QPointF> m_trajectory;
QVariantList m_editorStations;
QVariantList m_editorRoutes;
QVariantList m_mapStations;
QVariantList m_mapRoutes;
QString m_streamMessage; QString m_streamMessage;
QString m_mapId; QString m_mapId;
QString m_selectedStationId;
QString m_editorMapId;
QPointF m_pan; QPointF m_pan;
QRectF m_fitBounds;
QPoint m_mousePressPosition;
QPoint m_lastMousePosition; QPoint m_lastMousePosition;
EditMode m_editMode = BrowseMode;
Qt::MouseButton m_pressedButton = Qt::NoButton;
double m_zoom = 1.0; double m_zoom = 1.0;
double m_robotX = 0.0; double m_robotX = 0.0;
double m_robotY = 0.0; double m_robotY = 0.0;
@ -56,4 +99,7 @@ private:
bool m_localized = false; bool m_localized = false;
bool m_hasPose = false; bool m_hasPose = false;
bool m_dragging = false; bool m_dragging = false;
bool m_mouseMoved = false;
bool m_autoFit = true;
bool m_hasEditorObjects = false;
}; };

153
src/agvvelocityramp.h Normal file
View File

@ -0,0 +1,153 @@
#pragma once
#include <algorithm>
#include <cmath>
struct AgvManualVelocity
{
double vx = 0.0;
double vy = 0.0;
double wz = 0.0;
};
struct AgvRampLimits
{
double linearAcceleration = 0.2;
double linearDeceleration = 0.3;
double angularAcceleration = 0.5;
double angularDeceleration = 0.8;
};
// Stateless ramp for the velocities actually sent by the manual controller.
// A changed direction is reached in two phases: brake to zero, then accelerate.
// Callers must pass the last ramp output back as current on the next tick.
class AgvVelocityRamp
{
public:
static AgvManualVelocity step(const AgvManualVelocity &current,
const AgvManualVelocity &target,
const AgvRampLimits &limits,
double dt)
{
// An invalid current is unknown motion, so never extrapolate from it.
if (!isFinite(current))
return {};
AgvManualVelocity from = snapZero(current);
if (!std::isfinite(dt) || dt <= 0.0)
return from;
dt = std::min(dt, 0.15);
// An invalid target is treated as a request to stop safely.
AgvManualVelocity goal = isFinite(target) ? snapZero(target)
: AgvManualVelocity{};
const double fromLinear = linearMagnitude(from);
const double goalLinear = linearMagnitude(goal);
const bool fromHasLinear = fromLinear > 0.0;
const bool goalHasLinear = goalLinear > 0.0;
const bool fromHasAngular = from.wz != 0.0;
const bool goalHasAngular = goal.wz != 0.0;
const bool linearTurn = fromHasLinear && goalHasLinear
&& !sameLinearDirection(from, fromLinear, goal, goalLinear);
const bool angularReverse = fromHasAngular && goalHasAngular
&& (std::signbit(from.wz) != std::signbit(goal.wz));
// Also keeps braking when one component reaches zero before the other
// during a combined-motion reversal. A new component never starts
// while the previous movement is still braking.
const bool startOtherComponent =
(fromHasLinear && !fromHasAngular && goalHasAngular)
|| (fromHasAngular && !fromHasLinear && goalHasLinear);
if (linearTurn || angularReverse || startOtherComponent)
goal = {};
AgvManualVelocity result;
const double targetLinear = linearMagnitude(goal);
const double linearRate = targetLinear > fromLinear
? validRate(limits.linearAcceleration, 0.2)
: validRate(limits.linearDeceleration, 0.3);
const double nextLinear = approachMagnitude(fromLinear, targetLinear,
linearRate * dt);
if (nextLinear > 0.0) {
// Preserve the current direction during braking. When starting or
// accelerating, goal is collinear with current (or current is zero).
const AgvManualVelocity &direction = fromHasLinear ? from : goal;
const double magnitude = fromHasLinear ? fromLinear : targetLinear;
result.vx = (direction.vx / magnitude) * nextLinear;
result.vy = (direction.vy / magnitude) * nextLinear;
}
const double fromAngular = std::abs(from.wz);
const double targetAngular = std::abs(goal.wz);
const double angularRate = targetAngular > fromAngular
? validRate(limits.angularAcceleration, 0.5)
: validRate(limits.angularDeceleration, 0.8);
const double nextAngular = approachMagnitude(fromAngular, targetAngular,
angularRate * dt);
if (nextAngular > 0.0)
result.wz = std::copysign(nextAngular,
fromHasAngular ? from.wz : goal.wz);
return snapZero(result);
}
static bool isZero(const AgvManualVelocity &velocity, double epsilon = 1e-9)
{
if (!isFinite(velocity))
return false;
if (!std::isfinite(epsilon) || epsilon < 0.0)
epsilon = 1e-9;
return linearMagnitude(velocity) <= epsilon
&& std::abs(velocity.wz) <= epsilon;
}
private:
static double linearMagnitude(const AgvManualVelocity &velocity)
{
return std::hypot(velocity.vx, velocity.vy);
}
static bool isFinite(const AgvManualVelocity &velocity)
{
return std::isfinite(velocity.vx) && std::isfinite(velocity.vy)
&& std::isfinite(velocity.wz)
&& std::isfinite(linearMagnitude(velocity));
}
static AgvManualVelocity snapZero(AgvManualVelocity velocity)
{
// Absorb residue far below the manual controller's speed resolution.
if (linearMagnitude(velocity) <= 1e-12) {
velocity.vx = 0.0;
velocity.vy = 0.0;
}
if (std::abs(velocity.wz) <= 1e-12)
velocity.wz = 0.0;
return velocity;
}
static double validRate(double value, double fallback)
{
return std::isfinite(value) && value > 0.0 ? value : fallback;
}
static double approachMagnitude(double current, double target, double amount)
{
if (target > current)
return target - current <= amount ? target : current + amount;
return current - target <= amount ? target : current - amount;
}
static bool sameLinearDirection(const AgvManualVelocity &a, double aMagnitude,
const AgvManualVelocity &b, double bMagnitude)
{
const double ax = a.vx / aMagnitude;
const double ay = a.vy / aMagnitude;
const double bx = b.vx / bMagnitude;
const double by = b.vy / bMagnitude;
const double cross = ax * by - ay * bx;
const double dot = ax * bx + ay * by;
return dot > 0.0 && std::abs(cross) <= 1e-10;
}
};

View File

@ -10,6 +10,7 @@
#include "videorenderwidget.h" #include "videorenderwidget.h"
#include "agvmapviewwidget.h" #include "agvmapviewwidget.h"
#include "agvmapeditorwidget.h"
#include "audiostreammanager.h" #include "audiostreammanager.h"
#include "configeditorwidget.h" #include "configeditorwidget.h"
#include "robotclient.h" #include "robotclient.h"
@ -1035,10 +1036,30 @@ MainWindow::MainWindow(QWidget *parent)
} }
}); });
connect(m_client, &RobotClient::agvStateReceived, this, &MainWindow::updateAgvState); connect(m_client, &RobotClient::agvStateReceived, this, &MainWindow::updateAgvState);
connect(m_client, &RobotClient::agvInventoryReceived, this, &MainWindow::updateAgvInventory); connect(m_client, &RobotClient::agvInventoryReceivedForContext, this,
[this](const QVariantMap &context, const QStringList &maps,
const QVariantList &stations) {
if (m_connected && matchesAgvContext(context))
updateAgvInventory(maps, stations);
});
connect(m_client, &RobotClient::agvMapFrameReceived, this, connect(m_client, &RobotClient::agvMapFrameReceived, this,
[this](const QImage &image, const QVariantMap &metadata, [this](const QImage &image, const QVariantMap &metadata,
const QString &detail) { const QString &detail) {
if (!m_connected || !m_agvStreamRequested
|| !m_pages || m_pages->currentIndex() != 3
|| !matchesAgvContext(metadata)
|| m_agvStreamEndpoint != endpoint()
|| m_agvStreamDemo != m_demoCheck->isChecked()
|| metadata.value(QStringLiteral("streamGeneration")).toULongLong()
!= m_client->agvMapStreamGeneration())
return;
const QString mapId = metadata.value(QStringLiteral("mapId")).toString();
const QString deviceId = metadata.value(QStringLiteral("deviceId")).toString();
if ((!m_agvRequestedMap.isEmpty() && mapId != m_agvRequestedMap)
|| (!deviceId.isEmpty() && deviceId != m_agvStreamDeviceId))
return;
if (m_agvRequestedMap.isEmpty())
m_agvRequestedMap = mapId;
m_pendingAgvMapImage = image; m_pendingAgvMapImage = image;
m_pendingAgvMapMetadata = metadata; m_pendingAgvMapMetadata = metadata;
m_pendingAgvMapDetail = detail; m_pendingAgvMapDetail = detail;
@ -1054,9 +1075,18 @@ MainWindow::MainWindow(QWidget *parent)
m_agvMapRefreshTimer->start(); m_agvMapRefreshTimer->start();
} }
}); });
connect(m_client, &RobotClient::agvMapStreamStateChanged, this, connect(m_client, &RobotClient::agvMapStreamStateChangedForContext, this,
[this](bool running, const QString &detail) { [this](const QVariantMap &context, bool running, const QString &detail) {
if (!m_connected || !m_agvStreamRequested || !matchesAgvContext(context)
|| context.value(QStringLiteral("streamGeneration")).toULongLong()
!= m_client->agvMapStreamGeneration())
return;
const QString requestedMap = context.value(QStringLiteral("mapId")).toString();
if (!requestedMap.isEmpty() && requestedMap != m_agvRequestedMap)
return;
m_agvMapStreamActive = running; m_agvMapStreamActive = running;
if (!context.value(QStringLiteral("error")).toString().isEmpty())
m_agvMapReadError = context.value(QStringLiteral("error")).toString();
const int intervalMs = m_agvMapRefreshCombo const int intervalMs = m_agvMapRefreshCombo
? m_agvMapRefreshCombo->currentData().toInt() : 0; ? m_agvMapRefreshCombo->currentData().toInt() : 0;
if (m_agvMapRefreshTimer) { if (m_agvMapRefreshTimer) {
@ -1070,6 +1100,13 @@ MainWindow::MainWindow(QWidget *parent)
} }
if (m_agvMapView) if (m_agvMapView)
m_agvMapView->setStreamMessage(detail); m_agvMapView->setStreamMessage(detail);
if (!running) {
QPointF center;
const bool hasFrame = m_agvMapView && m_agvMapView->mapId() == m_agvRequestedMap
&& m_agvMapView->widgetToWorld(QPointF(m_agvMapView->rect().center()), &center);
m_agvMapRecoveryNeeded = !hasFrame && !m_agvMapRecoveryAttempted;
}
updateAgvMapSwitchStatus();
if (!m_agvMappingStateLabel) if (!m_agvMappingStateLabel)
return; return;
m_agvMappingStateLabel->setProperty("running", running); m_agvMappingStateLabel->setProperty("running", running);
@ -1219,7 +1256,7 @@ MainWindow::~MainWindow()
if (m_touchOperation) m_touchOperation->stop(); if (m_touchOperation) m_touchOperation->stop();
if (m_tcpJog) m_tcpJog->stop(); if (m_tcpJog) m_tcpJog->stop();
qApp->removeEventFilter(this); qApp->removeEventFilter(this);
stopAgvManualMotion(false); stopAgvManualMotion();
if (m_client) if (m_client)
m_client->stopAgvMapStream(); m_client->stopAgvMapStream();
m_audioManager->stopSource(); m_audioManager->stopSource();
@ -1307,9 +1344,19 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event)
stopAgvManualMotion(); stopAgvManualMotion();
} }
// A held key must be released even if focus has moved into an editor.
if (event && event->type() == QEvent::KeyRelease && m_agvManualKey != 0) {
auto *key = static_cast<QKeyEvent *>(event);
if (!key->isAutoRepeat() && key->key() == m_agvManualKey) {
m_agvManualKey = 0;
decelerateAgvManualMotion();
return true;
}
}
const bool agvControlVisible = m_connected && m_pages const bool agvControlVisible = m_connected && m_pages
&& m_pages->currentIndex() == 3 && m_agvControlWorkspace && m_pages->currentIndex() == 3 && m_agvControlWorkspace
&& m_agvControlWorkspace->isVisible(); && m_agvControlWorkspace->isVisible() && m_agvVxSpin && m_agvVxSpin->isVisible();
if (!event || !agvControlVisible if (!event || !agvControlVisible
|| (event->type() != QEvent::KeyPress || (event->type() != QEvent::KeyPress
&& event->type() != QEvent::KeyRelease)) { && event->type() != QEvent::KeyRelease)) {
@ -1361,10 +1408,11 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event)
if (!directionKey) if (!directionKey)
return QMainWindow::eventFilter(watched, event); return QMainWindow::eventFilter(watched, event);
if (event->type() == QEvent::KeyPress) if (event->type() == QEvent::KeyPress) {
startAgvManualMotion(vx, vy, wz); startAgvManualMotion(vx, vy, wz);
else m_agvManualButton.clear();
stopAgvManualMotion(); m_agvManualKey = m_agvManualMotionActive ? keyEvent->key() : 0;
}
return true; return true;
} }
@ -1553,11 +1601,15 @@ void MainWindow::selectPage(int index)
m_client->stopAgvMapStream(); m_client->stopAgvMapStream();
m_agvMapStreamActive = false; m_agvMapStreamActive = false;
} }
} else if (m_connected) { m_agvStreamRequested = false;
m_agvMapRecoveryNeeded = true;
} else if (m_connected && !m_agvIdEdit->text().trimmed().isEmpty()) {
m_agvDeviceRefreshPending = false;
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); m_client->requestAgvInventory(m_agvIdEdit->text().trimmed());
m_agvStatusRefreshTimer->start(); m_agvStatusRefreshTimer->start();
restartAgvMapStream(); if (m_agvStateAvailable && !m_agvMapStreamPaused)
restartAgvMapStream();
} }
if (index < m_navButtons.size()) if (index < m_navButtons.size())
m_navButtons.at(index)->setChecked(true); m_navButtons.at(index)->setChecked(true);
@ -1565,43 +1617,364 @@ void MainWindow::selectPage(int index)
void MainWindow::startAgvManualMotion(double vx, double vy, double wz) void MainWindow::startAgvManualMotion(double vx, double vy, double wz)
{ {
if (!m_connected || !m_client || !m_agvIdEdit if (m_agvDirectBusy || !m_connected || !m_client || !m_agvIdEdit
|| !m_agvVxSpin || !m_agvVxSpin->isVisible()
|| m_agvIdEdit->text().trimmed().isEmpty()) { || m_agvIdEdit->text().trimmed().isEmpty()) {
return; return;
} }
m_agvManualVx = vx; const AgvManualVelocity target{vx, vy, wz};
m_agvManualVy = vy; if (AgvVelocityRamp::isZero(target)) {
m_agvManualWz = wz; decelerateAgvManualMotion();
m_agvManualMotionActive = true; return;
m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), vx, vy, wz); }
if (!m_agvManualMotionActive) {
// Synchronize the client's device before creating the new session.
// Device binding may synchronously cancel the previous context.
m_client->beginAgvManualControl(m_agvIdEdit->text().trimmed());
m_agvManualDeviceId = m_agvIdEdit->text().trimmed();
m_agvManualVelocity = {};
m_agvManualVelocityInFlight = false;
m_agvManualMotionActive = true;
m_agvManualStepClock.start();
}
m_agvManualTarget = target;
if (m_agvManualVelocityTimer && !m_agvManualVelocityTimer->isActive()) if (m_agvManualVelocityTimer && !m_agvManualVelocityTimer->isActive())
m_agvManualVelocityTimer->start(); m_agvManualVelocityTimer->start();
} }
void MainWindow::decelerateAgvManualMotion()
{
m_agvManualKey = 0;
m_agvManualButton.clear();
if (!m_agvManualMotionActive)
return;
m_agvManualTarget = {};
// Retain the timer until the final zero has been acknowledged. A new
// direction can replace the target while decelerating, without a jump.
}
void MainWindow::advanceAgvManualMotion()
{
if (!m_agvManualMotionActive)
return;
if (!m_connected || m_agvDirectBusy || !m_pages || m_pages->currentIndex() != 3
|| !m_agvControlWorkspace || !m_agvControlWorkspace->isVisible()
|| !m_agvVxSpin->isVisible()
|| m_agvIdEdit->text().trimmed() != m_agvManualDeviceId) {
stopAgvManualMotion();
return;
}
if (m_agvManualVelocityInFlight) {
if (m_agvManualReplyClock.elapsed() > 600) {
stopAgvManualMotion();
appendLog(QStringLiteral("ERROR"), QStringLiteral("手动速度响应超时,已请求停止;请重新按方向键"));
}
return;
}
const double dt = qMin(0.15, m_agvManualStepClock.restart() / 1000.0);
AgvRampLimits limits;
limits.linearAcceleration = m_agvLinearAccelerationSpin->value();
limits.linearDeceleration = m_agvLinearDecelerationSpin->value();
limits.angularAcceleration = m_agvAngularAccelerationSpin->value();
limits.angularDeceleration = m_agvAngularDecelerationSpin->value();
m_agvManualVelocity = AgvVelocityRamp::step(m_agvManualVelocity, m_agvManualTarget, limits, dt);
m_agvManualVelocityInFlight = true;
m_agvManualReplyClock.start();
m_client->requestAgvManualVelocity(++m_agvManualVelocityRequestId, m_agvManualDeviceId,
m_agvManualVelocity.vx, m_agvManualVelocity.vy, m_agvManualVelocity.wz);
}
void MainWindow::stopAgvManualMotion(bool sendStop) void MainWindow::stopAgvManualMotion(bool sendStop)
{ {
const bool wasActive = m_agvManualMotionActive; const bool wasActive = m_agvManualMotionActive;
const QString deviceId = m_agvManualDeviceId;
m_agvManualMotionActive = false; m_agvManualMotionActive = false;
m_agvManualVelocityInFlight = false;
++m_agvManualVelocityRequestId;
m_agvManualTarget = {};
m_agvManualVelocity = {};
m_agvManualDeviceId.clear();
m_agvManualKey = 0;
m_agvManualButton.clear();
if (m_agvManualVelocityTimer) if (m_agvManualVelocityTimer)
m_agvManualVelocityTimer->stop(); m_agvManualVelocityTimer->stop();
if (sendStop && wasActive && m_connected && m_client && m_agvIdEdit if (m_client)
&& !m_agvIdEdit->text().trimmed().isEmpty()) { m_client->cancelAgvManualVelocity();
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), if (sendStop && wasActive && m_connected && m_client && !deviceId.isEmpty())
QStringLiteral("StopVelocity")); m_client->requestAgvAction(deviceId, QStringLiteral("StopVelocity"));
}
} }
void MainWindow::restartAgvMapStream(const QString &mapName) void MainWindow::restartAgvMapStream(const QString &mapName, bool recovering)
{ {
if (!m_connected || !m_client || !m_agvIdEdit if (!m_connected || !m_client || !m_agvIdEdit
|| m_agvIdEdit->text().trimmed().isEmpty()) { || m_agvIdEdit->text().trimmed().isEmpty()) {
return; return;
} }
const QString selectedMap = mapName.trimmed().isEmpty() && m_agvMapCombo // A transient status failure must not replace an explicitly selected map
? m_agvMapCombo->currentText().trimmed() : mapName.trimmed(); // with the vehicle's previous current map on recovery.
const QString selectedMap = !mapName.trimmed().isEmpty()
? mapName.trimmed()
: !m_agvSwitchMapTarget.isEmpty()
? m_agvSwitchMapTarget
: m_agvStateAvailable
? m_latestAgvState.value(QStringLiteral("map")).toString().trimmed()
: QString();
if (m_agvMapView && !selectedMap.isEmpty() && m_agvMapView->mapId() != selectedMap)
m_agvMapView->clearMapFrame(QStringLiteral("正在加载地图 %1…").arg(selectedMap));
m_agvRequestedMap = selectedMap;
m_agvStreamDeviceId = m_agvIdEdit->text().trimmed();
m_agvStreamEndpoint = endpoint();
m_agvStreamDemo = m_demoCheck->isChecked();
m_agvStreamRequested = true;
m_agvMapStreamPaused = false;
m_agvMapRecoveryNeeded = false;
if (!recovering)
m_agvMapRecoveryAttempted = false;
m_agvMapReadError.clear();
m_agvMapFramePending = false;
m_pendingAgvMapImage = QImage();
m_pendingAgvMapMetadata.clear();
m_pendingAgvMapDetail.clear();
m_client->stopAgvMapStream(); m_client->stopAgvMapStream();
m_client->startAgvMapStream(m_agvIdEdit->text().trimmed(), selectedMap, if (!selectedMap.isEmpty())
1, true, true); m_client->startAgvMapPreview(m_agvIdEdit->text().trimmed(), selectedMap);
else
m_client->startAgvMapStream(m_agvIdEdit->text().trimmed(), QString(), 1, true, true);
}
bool MainWindow::matchesAgvContext(const QVariantMap &context) const
{
return (!context.contains(QStringLiteral("deviceId"))
|| context.value(QStringLiteral("deviceId")).toString().trimmed()
== m_agvIdEdit->text().trimmed())
&& (!context.contains(QStringLiteral("endpoint"))
|| context.value(QStringLiteral("endpoint")).toString() == endpoint())
&& (!context.contains(QStringLiteral("demo"))
|| context.value(QStringLiteral("demo")).toBool() == m_demoCheck->isChecked());
}
void MainWindow::updateAgvMapRobotPose()
{
if (!m_agvMapView)
return;
const QString currentMap = m_latestAgvState.value(QStringLiteral("map")).toString();
if (!m_agvStateAvailable || !m_latestAgvState.value(QStringLiteral("connected")).toBool()
|| currentMap.isEmpty() || m_agvMapView->mapId() != currentMap) {
m_agvMapView->clearRobotPose();
return;
}
m_agvMapView->updateRobotPose(
m_latestAgvState.value(QStringLiteral("x")).toDouble(),
m_latestAgvState.value(QStringLiteral("y")).toDouble(),
m_latestAgvState.value(QStringLiteral("theta")).toDouble(),
m_latestAgvState.value(QStringLiteral("localized")).toBool());
}
void MainWindow::updateAgvMapSwitchStatus()
{
if (!m_agvMapSwitchStatus)
return;
if (m_agvSwitchMapTarget.isEmpty()) {
m_agvMapSwitchStatus->hide();
return;
}
const QString target = m_agvSwitchMapTarget;
const bool displayed = m_agvMapView && m_agvMapView->mapId() == target;
const QString preview = displayed ? QStringLiteral("已显示地图 %1").arg(target)
: QStringLiteral("正在加载地图 %1").arg(target);
const QString current = m_agvStateAvailable
? m_latestAgvState.value(QStringLiteral("map")).toString() : QString();
const bool controllerConnected = m_agvStateAvailable
&& m_latestAgvState.value(QStringLiteral("connected")).toBool();
QString text;
QString color = QStringLiteral("#66727d");
if (m_agvMapSwitchPending) {
text = preview + QStringLiteral(";正在请求车辆切换");
} else if (m_agvMapDirectMode && m_agvMapDirectMode->currentData().toBool()
&& m_agvDirectConfirmedMap == target && m_agvSwitchMapError.isEmpty()) {
text = preview + QStringLiteral(";车辆直连已确认本次切图完成");
color = QStringLiteral("#16835e");
} else if (m_agvMapDirectMode && m_agvMapDirectMode->currentData().toBool()
&& !m_demoCheck->isChecked() && m_agvSwitchMapAccepted
&& m_agvDirectConfirmedMap.isEmpty()) {
text = preview + QStringLiteral(";%1").arg(m_agvDirectSwitchDetail.isEmpty()
? QStringLiteral("切图请求已接受,尚未取得车辆直连确认") : m_agvDirectSwitchDetail);
color = QStringLiteral("#b57c0c");
} else if (controllerConnected && current == target
&& ((m_agvSwitchMapAccepted && m_agvSwitchMapRuntimeConfirmed)
|| !m_agvSwitchMapError.isEmpty())) {
if (m_agvSwitchMapError.isEmpty()) {
text = preview + QStringLiteral(";车端已确认使用该地图");
color = QStringLiteral("#16835e");
} else {
// A later state can show the target map without proving that the
// failed request succeeded. Keep both facts and the original error.
text = preview + QStringLiteral(";车端当前使用该地图;此前切图请求失败:%1")
.arg(m_agvSwitchMapError);
color = QStringLiteral("#b57c0c");
}
} else if (!m_agvSwitchMapError.isEmpty()) {
text = preview + QStringLiteral(";车辆切图失败:%1").arg(m_agvSwitchMapError);
color = QStringLiteral("#c63e3e");
} else if (m_agvSwitchMapAccepted && !controllerConnected) {
text = preview + QStringLiteral(";切图请求已接受,车辆离线,尚未确认当前地图");
color = QStringLiteral("#b57c0c");
} else if (m_agvSwitchMapAccepted) {
text = preview + (current.isEmpty()
? QStringLiteral(";切图请求已接受,等待车端状态恢复后确认")
: QStringLiteral(";车辆仍使用 %1,等待车端确认").arg(current));
} else {
text = preview;
}
if (!m_agvMapReadError.isEmpty()) {
text = QStringLiteral("地图读取失败:%1;").arg(m_agvMapReadError) + text;
color = QStringLiteral("#c63e3e");
}
m_agvMapSwitchStatus->setText(text);
m_agvMapSwitchStatus->setStyleSheet(QStringLiteral("font-size:11px; color:%1").arg(color));
m_agvMapSwitchStatus->show();
}
void MainWindow::refreshConfirmedAgvMap(quint64 switchToken)
{
if (!switchToken || switchToken != m_agvMapSwitchToken
|| m_agvMapSwitchRefreshToken != switchToken || m_agvMapSwitchPending
|| m_agvDirectBusy || m_agvMapEditorBusy
|| !m_agvSwitchMapAccepted || !m_agvSwitchMapError.isEmpty()
|| !m_connected || !m_agvStreamRequested || m_agvMapStreamPaused
|| !m_pages || m_pages->currentIndex() != 3
|| m_agvSwitchMapEndpoint != endpoint()
|| m_agvSwitchMapDevice != m_agvIdEdit->text().trimmed()
|| m_agvSwitchMapDemo != m_demoCheck->isChecked()
|| m_agvSwitchMapTarget.isEmpty() || m_agvRequestedMap != m_agvSwitchMapTarget)
return;
const bool confirmed = m_agvSwitchMapUsesDirect
? m_agvDirectConfirmedMap == m_agvSwitchMapTarget
: m_agvSwitchMapRuntimeConfirmed;
if (!confirmed)
return;
// A switch ACK only accepts the command. Its first preview may have read
// the old map before activation; refresh the snapshot once after proof.
// Consume the request token before emitting signals so repeated runtime
// updates and synchronous callbacks cannot create a restart loop.
m_agvMapSwitchRefreshToken = 0;
restartAgvMapStream(m_agvSwitchMapTarget);
if (m_agvMapEditor)
m_agvMapEditor->reloadCleanMap();
}
void MainWindow::configureAgvMapDirectConnection()
{
if (!m_client || !m_agvMapDirectMode || !m_agvMapDirectHost)
return;
const bool direct = m_agvMapDirectMode->currentData().toBool() && !m_demoCheck->isChecked();
QSettings settings;
const int storedPort = settings.value(QStringLiteral("configuration/port"), 50053).toInt();
const int configurationPort = storedPort == 50052 ? 50053 : storedPort;
m_client->configureAgvMapDirect(direct, m_agvMapDirectHost->text().trimmed(),
m_hostEdit->text().trimmed(), configurationPort);
m_agvDirectConfirmedMap.clear();
m_agvDirectSwitchDetail.clear();
m_agvMapSwitchRefreshToken = 0;
++m_agvMapSwitchToken;
updateAgvDirectControls();
updateAgvMapSwitchStatus();
}
void MainWindow::updateAgvDirectControls()
{
if (m_agvMapDirectMode)
m_agvMapDirectMode->setEnabled(!m_agvDirectBusy && !m_agvMapSwitchPending && !m_agvMapEditorBusy);
if (m_agvMapDirectHost)
m_agvMapDirectHost->setEnabled(m_agvMapDirectMode->currentData().toBool()
&& !m_demoCheck->isChecked() && !m_agvDirectBusy
&& !m_agvMapSwitchPending && !m_agvMapEditorBusy);
const bool enabled = m_connected && !m_agvDirectBusy
&& !m_agvMapSwitchPending && !m_agvMapEditorBusy;
for (QWidget *control : m_agvDirectBlockedControls)
control->setEnabled(enabled);
}
void MainWindow::clearAgvDisplay(const QString &message, bool preserveMapSelection)
{
stopAgvManualMotion();
if (!preserveMapSelection && m_agvMapRefreshTimer)
m_agvMapRefreshTimer->stop();
if (!preserveMapSelection && m_client && (m_agvStreamRequested || m_agvMapStreamActive))
m_client->stopAgvMapStream();
m_agvStateAvailable = false;
if (!preserveMapSelection) {
m_agvStreamRequested = false;
m_agvMapStreamActive = false;
m_agvMapRecoveryNeeded = true;
m_agvMapRecoveryAttempted = false;
m_agvMapReadError.clear();
m_agvMapSwitchPending = false;
m_agvMapSwitchRefreshToken = 0;
++m_agvMapSwitchToken;
m_agvSwitchMapRuntimeConfirmed = false;
m_agvSwitchMapAccepted = false;
m_agvSwitchMapTarget.clear();
m_agvSwitchMapError.clear();
m_agvDirectConfirmedMap.clear();
m_agvDirectSwitchDetail.clear();
m_agvRequestedMap.clear();
m_agvStreamDeviceId.clear();
m_agvStreamEndpoint.clear();
m_agvMapFramePending = false;
m_pendingAgvMapImage = QImage();
m_pendingAgvMapMetadata.clear();
m_pendingAgvMapDetail.clear();
}
m_latestAgvState.clear();
for (QLabel *label : {m_agvPoseValue, m_agvMotionValue, m_agvBatteryValue,
m_agvMapValue, m_agvNavigationValue, m_agvErrorValue,
m_agvModeValue, m_agvMotionStateValue, m_agvSafetyValue,
m_agvPowerValue, m_agvTimestampValue}) {
if (label)
label->setText(QStringLiteral("--"));
}
if (m_agvConnectionValue)
m_agvConnectionValue->setText(message);
if (m_agvProgress)
m_agvProgress->setValue(0);
if (!preserveMapSelection && m_agvMapCombo) {
const QSignalBlocker blocker(m_agvMapCombo);
m_agvMapCombo->clear();
}
if (m_agvStationCombo) {
const QSignalBlocker blocker(m_agvStationCombo);
m_agvStationCombo->clear();
}
if (m_agvStationTable)
m_agvStationTable->setRowCount(0);
if (!preserveMapSelection && m_agvMapListSummary)
m_agvMapListSummary->setText(QStringLiteral("等待当前设备地图列表"));
if (m_agvMapOverview)
m_agvMapOverview->clear();
if (m_agvMappingPreview)
m_agvMappingPreview->clear();
if (m_agvMapView) {
if (preserveMapSelection)
m_agvMapView->clearRobotPose();
else
m_agvMapView->clearMapFrame(message);
}
if (!preserveMapSelection && m_agvMappingStateLabel) {
m_agvMappingStateLabel->setProperty("running", false);
m_agvMappingStateLabel->setText(message);
}
if (m_agvMapEditor) {
// refreshContext retains dirty work and the editor's per-map drafts.
m_agvMapEditor->refreshContext();
}
for (QWidget *control : {static_cast<QWidget *>(m_agvIdEdit),
static_cast<QWidget *>(m_agvMapCombo),
static_cast<QWidget *>(m_agvSwitchMapButton)}) {
if (control)
control->setEnabled(m_connected && !m_agvMapEditorBusy && !m_agvMapSwitchPending);
}
updateAgvMapSwitchStatus();
} }
void MainWindow::presentPendingAgvMapFrame() void MainWindow::presentPendingAgvMapFrame()
@ -1613,6 +1986,12 @@ void MainWindow::presentPendingAgvMapFrame()
m_agvMapView->setMapFrame(m_pendingAgvMapImage, m_agvMapView->setMapFrame(m_pendingAgvMapImage,
m_pendingAgvMapMetadata); m_pendingAgvMapMetadata);
m_agvMapView->setStreamMessage(m_pendingAgvMapDetail); m_agvMapView->setStreamMessage(m_pendingAgvMapDetail);
m_agvMapReadError.clear();
m_agvMapRecoveryNeeded = false;
updateAgvMapRobotPose();
updateAgvMapSwitchStatus();
if (m_agvMapEditor)
QTimer::singleShot(0, m_agvMapEditor, &AgvMapEditorWidget::refreshContext);
} }
if (m_agvMappingStateLabel) if (m_agvMappingStateLabel)
m_agvMappingStateLabel->setText(m_pendingAgvMapDetail); m_agvMappingStateLabel->setText(m_pendingAgvMapDetail);
@ -1646,8 +2025,12 @@ void MainWindow::ensureArmModelLoaded()
void MainWindow::toggleConnection() void MainWindow::toggleConnection()
{ {
m_agvMapStreamPaused = false;
if (m_connected) { if (m_connected) {
if (m_tcpJog) m_tcpJog->stop(); if (m_tcpJog) m_tcpJog->stop();
clearAgvDisplay(QStringLiteral("正在断开连接"));
if (m_agvStatusRefreshTimer)
m_agvStatusRefreshTimer->stop();
m_connectButton->setEnabled(false); m_connectButton->setEnabled(false);
m_connectButton->setText(QStringLiteral("正在断开…")); m_connectButton->setText(QStringLiteral("正在断开…"));
m_client->disconnectFromServer(); m_client->disconnectFromServer();
@ -1659,6 +2042,7 @@ void MainWindow::toggleConnection()
return; return;
} }
saveSettings(); saveSettings();
clearAgvDisplay(QStringLiteral("等待当前设备状态"));
// Freeze the endpoint while the worker connects so TCP records retain // Freeze the endpoint while the worker connects so TCP records retain
// the identity of the server that actually owns the feedback. // the identity of the server that actually owns the feedback.
m_hostEdit->setEnabled(false); m_hostEdit->setEnabled(false);
@ -1684,6 +2068,9 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString &
if (!connected && m_taskOrchestration) if (!connected && m_taskOrchestration)
m_taskOrchestration->failActiveTask( m_taskOrchestration->failActiveTask(
detail.isEmpty() ? QStringLiteral("gRPC 连接已断开") : detail); detail.isEmpty() ? QStringLiteral("gRPC 连接已断开") : detail);
if (!connected) {
clearAgvDisplay(QStringLiteral("连接已断开"));
}
m_connectButton->setEnabled(true); m_connectButton->setEnabled(true);
m_connectButton->setText(connected ? QStringLiteral("断开连接") : QStringLiteral("连接")); m_connectButton->setText(connected ? QStringLiteral("断开连接") : QStringLiteral("连接"));
m_connectionText->setText(connected ? QStringLiteral("gRPC 已连接") m_connectionText->setText(connected ? QStringLiteral("gRPC 已连接")
@ -1702,12 +2089,18 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString &
state->style()->polish(state); state->style()->polish(state);
} }
setControlsEnabled(connected); setControlsEnabled(connected);
configureAgvMapDirectConnection();
if (m_agvStatusRefreshTimer) { if (m_agvStatusRefreshTimer) {
if (connected && m_pages && m_pages->currentIndex() == 3) { if (connected && m_demoCheck->isChecked()
&& m_agvIdEdit->text().trimmed().isEmpty()) {
m_agvIdEdit->setText(QStringLiteral("demo_agv_1"));
}
if (connected && m_pages && m_pages->currentIndex() == 3
&& !m_agvIdEdit->text().trimmed().isEmpty()) {
m_agvDeviceRefreshPending = false;
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); m_client->requestAgvInventory(m_agvIdEdit->text().trimmed());
m_agvStatusRefreshTimer->start(); m_agvStatusRefreshTimer->start();
restartAgvMapStream();
} else { } else {
m_agvStatusRefreshTimer->stop(); m_agvStatusRefreshTimer->stop();
} }
@ -2803,8 +3196,42 @@ void MainWindow::updateDexHandTactile(const QString &deviceId, int rows, int col
void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &navigation) void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &navigation)
{ {
const bool hasContext = state.contains(QStringLiteral("deviceId"))
|| state.contains(QStringLiteral("endpoint")) || state.contains(QStringLiteral("demo"));
if (hasContext && (!m_connected || !matchesAgvContext(state)))
return;
if (state.contains(QStringLiteral("available"))
&& !state.value(QStringLiteral("available")).toBool()) {
clearAgvDisplay(QStringLiteral("状态不可用"), !m_agvSwitchMapTarget.isEmpty());
m_latestAgvState = state;
m_agvErrorValue->setText(state.value(QStringLiteral("error"),
QStringLiteral("读取 AGV 状态失败")).toString());
return;
}
m_agvStateAvailable = true;
m_latestAgvState = state; m_latestAgvState = state;
const bool controllerConnected = state.value(QStringLiteral("connected")).toBool(); const bool controllerConnected = state.value(QStringLiteral("connected")).toBool();
// BackendWorker serializes switch and runtime RPCs, then queues their
// typed results in order. Only a state received after this request's ACK
// can prove activation; a cached pre-click timestamp cannot do so.
const bool freshSwitchState = !m_agvMapSwitchPending && m_agvSwitchMapAccepted
&& m_agvMapSwitchRefreshToken == m_agvMapSwitchToken
&& m_agvMapSwitchRefreshToken != 0 && !m_agvSwitchMapUsesDirect
&& m_agvSwitchMapError.isEmpty()
&& state.contains(QStringLiteral("deviceId"))
&& state.contains(QStringLiteral("endpoint")) && state.contains(QStringLiteral("demo"))
&& state.value(QStringLiteral("available")).toBool()
&& m_agvSwitchMapDevice == state.value(QStringLiteral("deviceId")).toString()
&& m_agvSwitchMapEndpoint == state.value(QStringLiteral("endpoint")).toString()
&& m_agvSwitchMapDemo == state.value(QStringLiteral("demo")).toBool()
&& (!state.contains(QStringLiteral("streamGeneration"))
|| state.value(QStringLiteral("streamGeneration")).toULongLong()
== m_client->agvMapStreamGeneration())
&& (!state.contains(QStringLiteral("timestamp"))
|| state.value(QStringLiteral("timestamp")).toDouble() > m_agvSwitchMapPreviousTimestamp);
if (freshSwitchState && controllerConnected
&& state.value(QStringLiteral("map")).toString() == m_agvSwitchMapTarget)
m_agvSwitchMapRuntimeConfirmed = true;
const bool localized = state.value(QStringLiteral("localized")).toBool(); const bool localized = state.value(QStringLiteral("localized")).toBool();
const bool fault = state.value(QStringLiteral("fault")).toBool(); const bool fault = state.value(QStringLiteral("fault")).toBool();
const bool emergency = state.value(QStringLiteral("emergency")).toBool(); const bool emergency = state.value(QStringLiteral("emergency")).toBool();
@ -2859,40 +3286,62 @@ void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &nav
.toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")) .toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))
: QStringLiteral("--")); : QStringLiteral("--"));
m_agvProgress->setValue(qBound(0, qRound(navigation.value(QStringLiteral("progress")).toDouble() * 100.0), 100)); m_agvProgress->setValue(qBound(0, qRound(navigation.value(QStringLiteral("progress")).toDouble() * 100.0), 100));
if (m_agvMapView) { updateAgvMapRobotPose();
m_agvMapView->updateRobotPose( updateAgvMapSwitchStatus();
state.value(QStringLiteral("x")).toDouble(), refreshConfirmedAgvMap(m_agvMapSwitchToken);
state.value(QStringLiteral("y")).toDouble(), if (m_agvMapRecoveryNeeded && !m_agvMapStreamPaused && m_connected && m_pages
state.value(QStringLiteral("theta")).toDouble(), localized); && m_pages->currentIndex() == 3 && !m_agvMapSwitchPending
&& !m_agvIdEdit->text().trimmed().isEmpty()) {
const bool recovering = m_agvStreamRequested;
if (!recovering || !m_agvMapRecoveryAttempted) {
if (recovering)
m_agvMapRecoveryAttempted = true;
restartAgvMapStream(QString(), recovering);
}
} }
if (m_agvMapEditor)
m_agvMapEditor->refreshContext();
} }
void MainWindow::updateAgvInventory(const QStringList &maps, const QVariantList &stations) void MainWindow::updateAgvInventory(const QStringList &maps, const QVariantList &stations)
{ {
const QSignalBlocker mapSignals(m_agvMapCombo);
QString selectedMap = m_agvMapCombo->currentText(); QString selectedMap = m_agvMapCombo->currentText();
if (selectedMap.trimmed().isEmpty()) if (selectedMap.trimmed().isEmpty())
selectedMap = m_latestAgvState.value(QStringLiteral("map")).toString(); selectedMap = m_latestAgvState.value(QStringLiteral("map")).toString();
m_agvMapCombo->clear(); m_agvMapCombo->clear();
m_agvMapCombo->addItems(maps); m_agvMapCombo->addItems(maps);
if (m_agvMapListSummary)
m_agvMapListSummary->setText(m_demoCheck->isChecked()
? QStringLiteral("演示 · %1 张地图").arg(maps.size())
: QStringLiteral("%1 张地图").arg(maps.size()));
const int mapIndex = m_agvMapCombo->findText(selectedMap); const int mapIndex = m_agvMapCombo->findText(selectedMap);
if (mapIndex >= 0) if (mapIndex >= 0)
m_agvMapCombo->setCurrentIndex(mapIndex); m_agvMapCombo->setCurrentIndex(mapIndex);
const QString selectedStation = m_agvStationCombo->currentText(); const QSignalBlocker stationSignals(m_agvStationCombo);
const QString selectedStation = m_agvStationCombo->currentData().toString();
m_agvStationCombo->clear(); m_agvStationCombo->clear();
m_agvStationTable->setRowCount(stations.size()); m_agvStationTable->setRowCount(stations.size());
for (int row = 0; row < stations.size(); ++row) { for (int row = 0; row < stations.size(); ++row) {
const QVariantMap station = stations.at(row).toMap(); const QVariantMap station = stations.at(row).toMap();
const QString stationId = station.value(QStringLiteral("id")).toString(); const QString stationId = station.value(QStringLiteral("id")).toString();
m_agvStationCombo->addItem(stationId); const QString stationName = station.value(QStringLiteral("name"),
m_agvStationTable->setItem(row, 0, new QTableWidgetItem(stationId)); station.value(QStringLiteral("description"), stationId)).toString().trimmed();
const QString displayName = stationName.isEmpty() ? stationId : stationName;
m_agvStationCombo->addItem(displayName == stationId ? stationId
: displayName + QStringLiteral(" (%1)").arg(stationId), stationId);
auto *stationItem = new QTableWidgetItem(displayName);
stationItem->setToolTip(QStringLiteral("ID: %1").arg(stationId));
stationItem->setData(Qt::UserRole, stationId);
m_agvStationTable->setItem(row, 0, stationItem);
m_agvStationTable->setItem(row, 1, new QTableWidgetItem(station.value(QStringLiteral("type")).toString())); m_agvStationTable->setItem(row, 1, new QTableWidgetItem(station.value(QStringLiteral("type")).toString()));
m_agvStationTable->setItem(row, 2, new QTableWidgetItem(QString::number( m_agvStationTable->setItem(row, 2, new QTableWidgetItem(QString::number(
station.value(QStringLiteral("x")).toDouble(), 'f', 3))); station.value(QStringLiteral("x")).toDouble(), 'f', 3)));
m_agvStationTable->setItem(row, 3, new QTableWidgetItem(QString::number( m_agvStationTable->setItem(row, 3, new QTableWidgetItem(QString::number(
station.value(QStringLiteral("y")).toDouble(), 'f', 3))); station.value(QStringLiteral("y")).toDouble(), 'f', 3)));
} }
const int stationIndex = m_agvStationCombo->findText(selectedStation); const int stationIndex = m_agvStationCombo->findData(selectedStation);
if (stationIndex >= 0) if (stationIndex >= 0)
m_agvStationCombo->setCurrentIndex(stationIndex); m_agvStationCombo->setCurrentIndex(stationIndex);
@ -3141,9 +3590,37 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri
|| command == QStringLiteral("Camera Stop Recording"))) { || command == QStringLiteral("Camera Stop Recording"))) {
updateCameraRecordingState(m_cameraRecording, detail); updateCameraRecordingState(m_cameraRecording, detail);
} }
if (success && command == QStringLiteral("AGV SwitchMap")) { if (command == QStringLiteral("AGV SwitchMap") && m_agvMapSwitchPending) {
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); const QString target = m_agvSwitchMapTarget;
restartAgvMapStream(m_agvMapCombo->currentText()); const QString device = m_agvSwitchMapDevice;
const bool matchingContext = m_connected && device == m_agvIdEdit->text().trimmed()
&& m_agvSwitchMapEndpoint == endpoint() && m_agvSwitchMapDemo == m_demoCheck->isChecked();
m_agvMapSwitchPending = false;
if (matchingContext) {
m_agvSwitchMapAccepted = success;
m_agvSwitchMapRuntimeConfirmed = false;
m_agvSwitchMapError = success ? QString() : detail;
if (!success)
m_agvMapSwitchRefreshToken = 0;
if (m_agvMapDirectMode && m_agvMapDirectMode->currentData().toBool()
&& !m_demoCheck->isChecked())
m_agvDirectSwitchDetail = detail;
}
for (QWidget *control : {static_cast<QWidget *>(m_agvMapCombo),
static_cast<QWidget *>(m_agvIdEdit),
static_cast<QWidget *>(m_agvSwitchMapButton)})
control->setEnabled(m_connected && !m_agvMapEditorBusy);
if (success && matchingContext) {
m_client->requestAgvRefresh(device);
m_client->requestAgvInventory(device);
// The selected map was requested on click. ACK only accepts the
// vehicle command; runtime state confirms the actual active map.
}
updateAgvMapSwitchStatus();
refreshConfirmedAgvMap(m_agvMapSwitchToken);
if (m_agvMapEditor)
m_agvMapEditor->refreshContext();
updateAgvDirectControls();
} }
if (command == QStringLiteral("AGV StopMapping")) { if (command == QStringLiteral("AGV StopMapping")) {
const bool asynchronousMappingFrame = const bool asynchronousMappingFrame =
@ -3176,14 +3653,18 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri
if (m_agvMappingStateLabel) if (m_agvMappingStateLabel)
m_agvMappingStateLabel->setText(QStringLiteral("建图已停止")); m_agvMappingStateLabel->setText(QStringLiteral("建图已停止"));
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); m_client->requestAgvInventory(m_agvIdEdit->text().trimmed());
restartAgvMapStream(); if (!m_agvMapStreamPaused && m_pages && m_pages->currentIndex() == 3)
restartAgvMapStream();
} else if (m_agvMappingStateLabel) { } else if (m_agvMappingStateLabel) {
m_agvMappingStateLabel->setText(QStringLiteral("停止建图失败")); m_agvMappingStateLabel->setText(QStringLiteral("停止建图失败"));
} }
} }
const QString commandDetail = command == QStringLiteral("AGV SwitchMap") && success
&& !(m_agvMapDirectMode && m_agvMapDirectMode->currentData().toBool() && !m_demoCheck->isChecked())
? QStringLiteral("切图请求已接受,等待车端确认当前地图") : detail;
appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"), appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"),
QStringLiteral("%1 · %2").arg(command, detail)); QStringLiteral("%1 · %2").arg(command, commandDetail));
if (!success) if (!success)
m_connectionText->setToolTip(detail); m_connectionText->setToolTip(detail);
} }
@ -3568,6 +4049,23 @@ void MainWindow::saveSnapshot()
void MainWindow::loadSettings() void MainWindow::loadSettings()
{ {
QSettings settings; QSettings settings;
// Other controls can save settings while their saved selection is restored.
// Read the AGV settings before those callbacks see an empty AGV field.
const QString agvDeviceId = settings.value(
QStringLiteral("agv/device"), QStringLiteral("agv")).toString();
const int agvMapRefreshInterval = settings.value(
QStringLiteral("agv/mapRefreshIntervalMs"), 0).toInt();
const bool agvMapDirect = settings.value(QStringLiteral("agv/mapDirect"), false).toBool();
const QString agvMapDirectHost = settings.value(QStringLiteral("agv/mapDirectHost")).toString();
const QStringList rampKeys = {QStringLiteral("agv/manualLinearAcceleration"),
QStringLiteral("agv/manualLinearDeceleration"), QStringLiteral("agv/manualAngularAcceleration"),
QStringLiteral("agv/manualAngularDeceleration")};
const double rampDefaults[] = {0.2, 0.3, 0.5, 0.8};
double rampValues[4];
for (int i = 0; i < 4; ++i) {
const double value = settings.value(rampKeys.at(i), rampDefaults[i]).toDouble();
rampValues[i] = qIsFinite(value) ? qBound(0.01, value, 5.0) : rampDefaults[i];
}
loadJointPrograms(settings); loadJointPrograms(settings);
m_hostEdit->setText(settings.value(QStringLiteral("connection/host"), QStringLiteral("192.168.0.28")).toString()); m_hostEdit->setText(settings.value(QStringLiteral("connection/host"), QStringLiteral("192.168.0.28")).toString());
m_hostEdit->setCursorPosition(0); m_hostEdit->setCursorPosition(0);
@ -3597,13 +4095,25 @@ void MainWindow::loadSettings()
if (modeIndex >= 0) if (modeIndex >= 0)
m_cameraStreamModeCombo->setCurrentIndex(modeIndex); m_cameraStreamModeCombo->setCurrentIndex(modeIndex);
} }
m_agvIdEdit->setText(settings.value(QStringLiteral("agv/device"), QStringLiteral("agv")).toString()); m_agvIdEdit->setText(agvDeviceId);
m_agvMapDirectMode->setCurrentIndex(agvMapDirect ? 1 : 0);
m_agvMapDirectHost->setText(agvMapDirectHost);
configureAgvMapDirectConnection();
if (m_agvMapRefreshCombo) { if (m_agvMapRefreshCombo) {
const int intervalMs = settings.value( const int index = m_agvMapRefreshCombo->findData(agvMapRefreshInterval);
QStringLiteral("agv/mapRefreshIntervalMs"), 0).toInt();
const int index = m_agvMapRefreshCombo->findData(intervalMs);
m_agvMapRefreshCombo->setCurrentIndex(index >= 0 ? index : 0); m_agvMapRefreshCombo->setCurrentIndex(index >= 0 ? index : 0);
} }
settings.setValue(QStringLiteral("agv/device"), agvDeviceId);
settings.setValue(QStringLiteral("agv/mapDirect"), agvMapDirect);
settings.setValue(QStringLiteral("agv/mapDirectHost"), agvMapDirectHost);
settings.setValue(QStringLiteral("agv/mapRefreshIntervalMs"), agvMapRefreshInterval);
const QList<QDoubleSpinBox *> rampSpins = {m_agvLinearAccelerationSpin,
m_agvLinearDecelerationSpin, m_agvAngularAccelerationSpin, m_agvAngularDecelerationSpin};
for (int i = 0; i < rampSpins.size(); ++i) {
const QSignalBlocker blocker(rampSpins.at(i));
rampSpins.at(i)->setValue(rampValues[i]);
settings.setValue(rampKeys.at(i), rampValues[i]);
}
m_velocitySpin->setValue(settings.value( m_velocitySpin->setValue(settings.value(
QStringLiteral("motion/speedJVelocity"), QStringLiteral("motion/speedJVelocity"),
settings.value(QStringLiteral("motion/velocity"), 1.0)).toDouble()); settings.value(QStringLiteral("motion/velocity"), 1.0)).toDouble());
@ -3671,9 +4181,21 @@ void MainWindow::saveSettings()
settings.setValue(QStringLiteral("camera/streamMode"), settings.setValue(QStringLiteral("camera/streamMode"),
m_cameraStreamModeCombo->currentData().toString()); m_cameraStreamModeCombo->currentData().toString());
settings.setValue(QStringLiteral("agv/device"), m_agvIdEdit->text().trimmed()); settings.setValue(QStringLiteral("agv/device"), m_agvIdEdit->text().trimmed());
if (m_agvMapDirectMode)
settings.setValue(QStringLiteral("agv/mapDirect"), m_agvMapDirectMode->currentData().toBool());
if (m_agvMapDirectHost)
settings.setValue(QStringLiteral("agv/mapDirectHost"), m_agvMapDirectHost->text().trimmed());
if (m_agvMapRefreshCombo) if (m_agvMapRefreshCombo)
settings.setValue(QStringLiteral("agv/mapRefreshIntervalMs"), settings.setValue(QStringLiteral("agv/mapRefreshIntervalMs"),
m_agvMapRefreshCombo->currentData().toInt()); m_agvMapRefreshCombo->currentData().toInt());
if (m_agvLinearAccelerationSpin)
settings.setValue(QStringLiteral("agv/manualLinearAcceleration"), m_agvLinearAccelerationSpin->value());
if (m_agvLinearDecelerationSpin)
settings.setValue(QStringLiteral("agv/manualLinearDeceleration"), m_agvLinearDecelerationSpin->value());
if (m_agvAngularAccelerationSpin)
settings.setValue(QStringLiteral("agv/manualAngularAcceleration"), m_agvAngularAccelerationSpin->value());
if (m_agvAngularDecelerationSpin)
settings.setValue(QStringLiteral("agv/manualAngularDeceleration"), m_agvAngularDecelerationSpin->value());
settings.setValue(QStringLiteral("motion/speedJVelocity"), m_velocitySpin->value()); settings.setValue(QStringLiteral("motion/speedJVelocity"), m_velocitySpin->value());
settings.setValue(QStringLiteral("motion/speedJAcceleration"), settings.setValue(QStringLiteral("motion/speedJAcceleration"),
m_accelerationSpin->value()); m_accelerationSpin->value());

View File

@ -3,9 +3,11 @@
#include <QImage> #include <QImage>
#include <QJsonArray> #include <QJsonArray>
#include <QJsonObject> #include <QJsonObject>
#include <QElapsedTimer>
#include <QHash> #include <QHash>
#include <QList> #include <QList>
#include <QMainWindow> #include <QMainWindow>
#include <QPointer>
#include <QSet> #include <QSet>
#include <QStyle> #include <QStyle>
#include <QStringList> #include <QStringList>
@ -15,6 +17,7 @@
#include "videoframe.h" #include "videoframe.h"
#include "jointpointdata.h" #include "jointpointdata.h"
#include "agvvelocityramp.h"
class QButtonGroup; class QButtonGroup;
class QCheckBox; class QCheckBox;
@ -50,6 +53,7 @@ class TcpJogController;
class HandEyeCalibrationWidget; class HandEyeCalibrationWidget;
class HandEyeMotionWidget; class HandEyeMotionWidget;
class AgvMapViewWidget; class AgvMapViewWidget;
class AgvMapEditorWidget;
class TactileHeatmapWidget; class TactileHeatmapWidget;
class JointFlowEditor; class JointFlowEditor;
class TaskOrchestrationWidget; class TaskOrchestrationWidget;
@ -158,9 +162,18 @@ private:
void setupTouchOperation(); void setupTouchOperation();
void syncHandEyeContext(); void syncHandEyeContext();
void startAgvManualMotion(double vx, double vy, double wz); void startAgvManualMotion(double vx, double vy, double wz);
void decelerateAgvManualMotion();
void advanceAgvManualMotion();
void stopAgvManualMotion(bool sendStop = true); void stopAgvManualMotion(bool sendStop = true);
void restartAgvMapStream(const QString &mapName = QString()); void restartAgvMapStream(const QString &mapName = QString(), bool recovering = false);
void presentPendingAgvMapFrame(); void presentPendingAgvMapFrame();
void clearAgvDisplay(const QString &message, bool preserveMapSelection = false);
void updateAgvMapSwitchStatus();
void refreshConfirmedAgvMap(quint64 switchToken);
void updateAgvMapRobotPose();
void configureAgvMapDirectConnection();
void updateAgvDirectControls();
bool matchesAgvContext(const QVariantMap &context) const;
void updateArmAlert(const QString &deviceId, const QString &alertKey, void updateArmAlert(const QString &deviceId, const QString &alertKey,
const QString &level, const QString &summary, const QString &level, const QString &summary,
const QString &detail = QString()); const QString &detail = QString());
@ -438,6 +451,7 @@ private:
QLabel *m_agvMappingPreview = nullptr; QLabel *m_agvMappingPreview = nullptr;
QLabel *m_agvMappingStateLabel = nullptr; QLabel *m_agvMappingStateLabel = nullptr;
AgvMapViewWidget *m_agvMapView = nullptr; AgvMapViewWidget *m_agvMapView = nullptr;
AgvMapEditorWidget *m_agvMapEditor = nullptr;
QWidget *m_agvControlWorkspace = nullptr; QWidget *m_agvControlWorkspace = nullptr;
QPushButton *m_agvDeleteMapButton = nullptr; QPushButton *m_agvDeleteMapButton = nullptr;
QPushButton *m_agvStopMappingButton = nullptr; QPushButton *m_agvStopMappingButton = nullptr;
@ -449,20 +463,64 @@ private:
QDoubleSpinBox *m_agvVxSpin = nullptr; QDoubleSpinBox *m_agvVxSpin = nullptr;
QDoubleSpinBox *m_agvVySpin = nullptr; QDoubleSpinBox *m_agvVySpin = nullptr;
QDoubleSpinBox *m_agvWzSpin = nullptr; QDoubleSpinBox *m_agvWzSpin = nullptr;
QDoubleSpinBox *m_agvLinearAccelerationSpin = nullptr;
QDoubleSpinBox *m_agvLinearDecelerationSpin = nullptr;
QDoubleSpinBox *m_agvAngularAccelerationSpin = nullptr;
QDoubleSpinBox *m_agvAngularDecelerationSpin = nullptr;
QComboBox *m_agvMapCombo = nullptr; QComboBox *m_agvMapCombo = nullptr;
QComboBox *m_agvMapDirectMode = nullptr;
QLineEdit *m_agvMapDirectHost = nullptr;
QList<QWidget *> m_agvDirectBlockedControls;
bool m_agvDirectBusy = false;
QString m_agvDirectConfirmedMap;
QString m_agvDirectSwitchDetail;
QLabel *m_agvMapListSummary = nullptr;
QLabel *m_agvMapSwitchStatus = nullptr;
QComboBox *m_agvMapRefreshCombo = nullptr; QComboBox *m_agvMapRefreshCombo = nullptr;
QComboBox *m_agvStationCombo = nullptr; QComboBox *m_agvStationCombo = nullptr;
QPushButton *m_agvSwitchMapButton = nullptr;
QTableWidget *m_agvStationTable = nullptr; QTableWidget *m_agvStationTable = nullptr;
QString m_agvDownloadPath; QString m_agvDownloadPath;
QVariantMap m_latestAgvState; QVariantMap m_latestAgvState;
QImage m_pendingAgvMapImage; QImage m_pendingAgvMapImage;
QVariantMap m_pendingAgvMapMetadata; QVariantMap m_pendingAgvMapMetadata;
QString m_pendingAgvMapDetail; QString m_pendingAgvMapDetail;
double m_agvManualVx = 0.0; QString m_agvRequestedMap;
double m_agvManualVy = 0.0; QString m_agvStreamDeviceId;
double m_agvManualWz = 0.0; QString m_agvStreamEndpoint;
QString m_agvContextDeviceId;
QString m_agvSwitchMapTarget;
QString m_agvSwitchMapDevice;
QString m_agvSwitchMapEndpoint;
bool m_agvSwitchMapDemo = false;
bool m_agvMapSwitchPending = false;
bool m_agvSwitchMapAccepted = false;
quint64 m_agvMapSwitchToken = 0;
quint64 m_agvMapSwitchRefreshToken = 0;
bool m_agvSwitchMapRuntimeConfirmed = false;
bool m_agvSwitchMapUsesDirect = false;
double m_agvSwitchMapPreviousTimestamp = 0.0;
QString m_agvSwitchMapError;
QString m_agvMapReadError;
bool m_agvMapEditorBusy = false;
AgvManualVelocity m_agvManualVelocity;
AgvManualVelocity m_agvManualTarget;
QElapsedTimer m_agvManualStepClock;
QElapsedTimer m_agvManualReplyClock;
QString m_agvManualDeviceId;
bool m_agvManualVelocityInFlight = false;
quint64 m_agvManualVelocityRequestId = 0;
QPointer<QPushButton> m_agvManualButton;
int m_agvManualKey = 0;
bool m_agvManualMotionActive = false; bool m_agvManualMotionActive = false;
bool m_agvMapStreamActive = false; bool m_agvMapStreamActive = false;
bool m_agvStreamRequested = false;
bool m_agvMapStreamPaused = false;
bool m_agvStreamDemo = false;
bool m_agvStateAvailable = false;
bool m_agvMapRecoveryNeeded = true;
bool m_agvMapRecoveryAttempted = false;
bool m_agvDeviceRefreshPending = false;
bool m_agvMapFramePending = false; bool m_agvMapFramePending = false;
bool m_agvStopMappingRetryPending = false; bool m_agvStopMappingRetryPending = false;
QList<QPushButton *> m_serviceButtons; QList<QPushButton *> m_serviceButtons;

View File

@ -1,6 +1,7 @@
#include "mainwindow.h" #include "mainwindow.h"
#include "agvmapviewwidget.h" #include "agvmapviewwidget.h"
#include "agvmapeditorwidget.h"
#include "audiostreammanager.h" #include "audiostreammanager.h"
#include "cameracapabilities.h" #include "cameracapabilities.h"
#include "robotclient.h" #include "robotclient.h"
@ -27,6 +28,7 @@
#include <QAbstractButton> #include <QAbstractButton>
#include <QCheckBox> #include <QCheckBox>
#include <QComboBox> #include <QComboBox>
#include <QCompleter>
#include <QCoreApplication> #include <QCoreApplication>
#include <QCursor> #include <QCursor>
#include <QDir> #include <QDir>
@ -53,6 +55,7 @@
#include <QPainter> #include <QPainter>
#include <QRegularExpression> #include <QRegularExpression>
#include <QSettings> #include <QSettings>
#include <QScrollArea>
#include <QSignalBlocker> #include <QSignalBlocker>
#include <QSettings> #include <QSettings>
#include <QSlider> #include <QSlider>
@ -1918,6 +1921,21 @@ QWidget *MainWindow::createAgvPage()
QWidget *page = new QWidget; QWidget *page = new QWidget;
Ui::AgvServicePage ui; Ui::AgvServicePage ui;
ui.setupUi(page); ui.setupUi(page);
page->setObjectName(QStringLiteral("agvPage"));
page->setStyleSheet(QStringLiteral(
"QFrame#panel { background:#ffffff; border:1px solid #dfe7ef; border-radius:12px; }"
"QLabel#sectionTitle { color:#21334a; font-size:14px; font-weight:600; }"
"QLabel#panelSubtitle, QLabel#eyebrow { color:#8190a3; font-size:11px; }"
"QLabel#agvStateValue { color:#30455c; font-size:12px; }"
"QScrollArea#agvControlSidebar { background:transparent; border:none; }"
"QScrollArea#agvControlSidebar > QWidget > QWidget { background:transparent; }"
"QTabWidget#agvControlTools::pane { border:none; background:transparent; top:0; }"
"QTabWidget#agvControlTools QTabBar { background:#e8eef5; border:none; }"
"QTabWidget#agvControlTools QTabBar::tab { padding:9px 18px; min-width:108px; "
"color:#76869a; border:none; font-weight:600; }"
"QTabWidget#agvControlTools QTabBar::tab:selected { color:#216fe2; background:#ffffff; }"
"QPushButton#agvMapToolButton { min-height:28px; padding:3px 10px; border-radius:6px; }"
"QPushButton#agvDirectionButton { min-height:36px; border-radius:7px; }"));
FramelessToolDialog *statusDialog = new FramelessToolDialog(this); FramelessToolDialog *statusDialog = new FramelessToolDialog(this);
m_agvStatusDialog = statusDialog; m_agvStatusDialog = statusDialog;
@ -1958,6 +1976,10 @@ QWidget *MainWindow::createAgvPage()
m_agvSafetyValue = statusUi.agvSafetyValue; m_agvSafetyValue = statusUi.agvSafetyValue;
m_agvPowerValue = statusUi.agvPowerValue; m_agvPowerValue = statusUi.agvPowerValue;
m_agvTimestampValue = statusUi.agvTimestampValue; m_agvTimestampValue = statusUi.agvTimestampValue;
m_agvConnectionValue->setObjectName(QStringLiteral("agvConnectionValue"));
m_agvModeValue->setObjectName(QStringLiteral("agvModeValue"));
m_agvMapValue->setObjectName(QStringLiteral("agvMapValue"));
m_agvErrorValue->setObjectName(QStringLiteral("agvErrorValue"));
m_agvMapOverview = ui.agvMapOverview; m_agvMapOverview = ui.agvMapOverview;
m_agvMappingPreview = ui.mappingPreview; m_agvMappingPreview = ui.mappingPreview;
m_agvMappingStateLabel = ui.mappingStateLabel; m_agvMappingStateLabel = ui.mappingStateLabel;
@ -1970,6 +1992,7 @@ QWidget *MainWindow::createAgvPage()
m_agvVySpin = ui.agvVySpin; m_agvVySpin = ui.agvVySpin;
m_agvWzSpin = ui.agvWzSpin; m_agvWzSpin = ui.agvWzSpin;
m_agvMapCombo = ui.agvMapCombo; m_agvMapCombo = ui.agvMapCombo;
m_agvSwitchMapButton = ui.switchMapButton;
m_agvStationCombo = ui.agvStationCombo; m_agvStationCombo = ui.agvStationCombo;
m_agvStationTable = ui.agvStationTable; m_agvStationTable = ui.agvStationTable;
ui.refreshButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/rotate-ccw.svg"), ui.refreshButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/rotate-ccw.svg"),
@ -1977,7 +2000,12 @@ QWidget *MainWindow::createAgvPage()
ui.emergencyButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/octagon-x.svg"), ui.emergencyButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/octagon-x.svg"),
QColor(QStringLiteral("#ffffff")))); QColor(QStringLiteral("#ffffff"))));
m_agvStationCombo->lineEdit()->setPlaceholderText(QStringLiteral("选择或输入站点 ID")); m_agvStationCombo->lineEdit()->setPlaceholderText(QStringLiteral("选择或输入站点 ID"));
m_agvMapCombo->lineEdit()->setPlaceholderText(QStringLiteral("地图名称")); m_agvMapCombo->lineEdit()->setPlaceholderText(QStringLiteral("选择或搜索已有地图"));
m_agvMapCombo->setInsertPolicy(QComboBox::NoInsert);
m_agvMapCombo->setMaxVisibleItems(12);
m_agvMapCombo->completer()->setCaseSensitivity(Qt::CaseInsensitive);
m_agvMapCombo->completer()->setFilterMode(Qt::MatchContains);
m_agvMapCombo->completer()->setCompletionMode(QCompleter::PopupCompletion);
m_agvStationTable->setHorizontalHeaderLabels({QStringLiteral("站点"), QStringLiteral("类型"), m_agvStationTable->setHorizontalHeaderLabels({QStringLiteral("站点"), QStringLiteral("类型"),
QStringLiteral("X"), QStringLiteral("Y")}); QStringLiteral("X"), QStringLiteral("Y")});
@ -1987,13 +2015,25 @@ QWidget *MainWindow::createAgvPage()
m_agvStationTable->horizontalHeader()->setStretchLastSection(true); m_agvStationTable->horizontalHeader()->setStretchLastSection(true);
m_agvStatusRefreshTimer->setInterval(500); m_agvStatusRefreshTimer->setInterval(500);
m_agvManualVelocityTimer = new QTimer(page); m_agvManualVelocityTimer = new QTimer(page);
m_agvManualVelocityTimer->setInterval(150); m_agvManualVelocityTimer->setObjectName(QStringLiteral("agvManualVelocityTimer"));
connect(m_agvManualVelocityTimer, &QTimer::timeout, this, [this]() { m_agvManualVelocityTimer->setTimerType(Qt::PreciseTimer);
if (!m_agvManualMotionActive || !m_connected) m_agvManualVelocityTimer->setInterval(100);
connect(m_agvManualVelocityTimer, &QTimer::timeout,
this, &MainWindow::advanceAgvManualMotion);
connect(m_client, &RobotClient::agvManualControlInterrupted, this,
[this](bool requestStop) { stopAgvManualMotion(requestStop); });
connect(m_client, &RobotClient::agvManualVelocityFinished, this,
[this](quint64 requestId, bool success, const QString &detail) {
if (!m_agvManualMotionActive || requestId != m_agvManualVelocityRequestId)
return; return;
m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), m_agvManualVelocityInFlight = false;
m_agvManualVx, m_agvManualVy, if (!success) {
m_agvManualWz); stopAgvManualMotion();
appendLog(QStringLiteral("ERROR"), QStringLiteral("手动速度下发失败,已请求停止:%1").arg(detail));
} else if (AgvVelocityRamp::isZero(m_agvManualTarget)
&& AgvVelocityRamp::isZero(m_agvManualVelocity)) {
stopAgvManualMotion();
}
}); });
m_agvControlWorkspace = new QWidget(ui.agvTabs); m_agvControlWorkspace = new QWidget(ui.agvTabs);
@ -2010,19 +2050,29 @@ QWidget *MainWindow::createAgvPage()
QVBoxLayout *rightLayout = new QVBoxLayout(rightColumn); QVBoxLayout *rightLayout = new QVBoxLayout(rightColumn);
rightLayout->setContentsMargins(0, 0, 0, 0); rightLayout->setContentsMargins(0, 0, 0, 0);
rightLayout->setSpacing(12); rightLayout->setSpacing(12);
workspaceLayout->addWidget(leftColumn, 7); auto *sidebar = new QScrollArea(m_agvControlWorkspace);
workspaceLayout->addWidget(rightColumn, 4); sidebar->setObjectName(QStringLiteral("agvControlSidebar"));
sidebar->setWidgetResizable(true);
sidebar->setFrameShape(QFrame::NoFrame);
sidebar->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
sidebar->setFixedWidth(480);
sidebar->setWidget(rightColumn);
workspaceLayout->addWidget(leftColumn, 1);
workspaceLayout->addWidget(sidebar);
ui.mappingPreviewPanel->setParent(leftColumn); ui.mappingPreviewPanel->setParent(leftColumn);
ui.mappingPreviewPanel->setMinimumSize(0, 0); ui.mappingPreviewPanel->setMinimumSize(0, 0);
ui.mappingPreviewTitle->setText(QStringLiteral("实时地图")); ui.mappingPreviewTitle->setText(QStringLiteral("地图工作区"));
ui.mappingPreviewLayout->setContentsMargins(16, 14, 16, 12);
ui.mappingPreviewLayout->setSpacing(10);
ui.mappingPreviewLayout->removeWidget(ui.mappingPreview); ui.mappingPreviewLayout->removeWidget(ui.mappingPreview);
ui.mappingPreview->hide(); ui.mappingPreview->hide();
ui.mappingStateLabel->hide();
m_agvMappingPreview = nullptr; m_agvMappingPreview = nullptr;
QHBoxLayout *mapToolbar = new QHBoxLayout; QHBoxLayout *mapToolbar = new QHBoxLayout;
QLabel *mapLegend = new QLabel( QLabel *mapLegend = new QLabel(
QStringLiteral("蓝色箭头:AGV 当前位姿 · 虚线:运动轨迹"), QStringLiteral("橙色站点 · 蓝色路线 · 箭头表示方向"),
ui.mappingPreviewPanel); ui.mappingPreviewPanel);
mapLegend->setObjectName(QStringLiteral("panelSubtitle")); mapLegend->setObjectName(QStringLiteral("panelSubtitle"));
QLabel *mapRefreshLabel = new QLabel(QStringLiteral("刷新率"), QLabel *mapRefreshLabel = new QLabel(QStringLiteral("刷新率"),
@ -2042,10 +2092,18 @@ QWidget *MainWindow::createAgvPage()
ui.mappingPreviewPanel); ui.mappingPreviewPanel);
QPushButton *zoomInButton = new QPushButton(QStringLiteral("+"), QPushButton *zoomInButton = new QPushButton(QStringLiteral("+"),
ui.mappingPreviewPanel); ui.mappingPreviewPanel);
QPushButton *resetViewButton = new QPushButton(QStringLiteral("适应窗口"), QPushButton *resetViewButton = new QPushButton(QStringLiteral("显示全图"),
ui.mappingPreviewPanel); ui.mappingPreviewPanel);
QPushButton *clearTrackButton = new QPushButton(QStringLiteral("清除轨迹"), QPushButton *clearTrackButton = new QPushButton(QStringLiteral("清除轨迹"),
ui.mappingPreviewPanel); ui.mappingPreviewPanel);
auto *expandMapButton = new QPushButton(QStringLiteral("展开地图"), ui.mappingPreviewPanel);
expandMapButton->setCheckable(true);
expandMapButton->setObjectName(QStringLiteral("agvExpandMapButton"));
expandMapButton->setMinimumHeight(30);
connect(expandMapButton, &QPushButton::toggled, page, [sidebar, expandMapButton](bool expanded) {
sidebar->setVisible(!expanded);
expandMapButton->setText(expanded ? QStringLiteral("显示侧栏") : QStringLiteral("展开地图"));
});
for (QPushButton *button : {zoomOutButton, zoomInButton, for (QPushButton *button : {zoomOutButton, zoomInButton,
resetViewButton, clearTrackButton}) { resetViewButton, clearTrackButton}) {
button->setObjectName(QStringLiteral("agvMapToolButton")); button->setObjectName(QStringLiteral("agvMapToolButton"));
@ -2053,6 +2111,9 @@ QWidget *MainWindow::createAgvPage()
} }
zoomOutButton->setMaximumWidth(42); zoomOutButton->setMaximumWidth(42);
zoomInButton->setMaximumWidth(42); zoomInButton->setMaximumWidth(42);
ui.mappingPreviewLayout->removeWidget(ui.mappingPreviewTitle);
mapToolbar->addWidget(ui.mappingPreviewTitle);
mapToolbar->addSpacing(8);
mapToolbar->addWidget(mapLegend); mapToolbar->addWidget(mapLegend);
mapToolbar->addStretch(); mapToolbar->addStretch();
mapToolbar->addWidget(mapRefreshLabel); mapToolbar->addWidget(mapRefreshLabel);
@ -2062,40 +2123,215 @@ QWidget *MainWindow::createAgvPage()
mapToolbar->addWidget(zoomInButton); mapToolbar->addWidget(zoomInButton);
mapToolbar->addWidget(resetViewButton); mapToolbar->addWidget(resetViewButton);
mapToolbar->addWidget(clearTrackButton); mapToolbar->addWidget(clearTrackButton);
ui.mappingPreviewLayout->insertLayout(1, mapToolbar); mapToolbar->addWidget(expandMapButton);
ui.mappingPreviewLayout->insertLayout(0, mapToolbar);
m_agvMapView = new AgvMapViewWidget(ui.mappingPreviewPanel); m_agvMapView = new AgvMapViewWidget(ui.mappingPreviewPanel);
m_agvMapView->setObjectName(QStringLiteral("agvLiveMap")); m_agvMapView->setObjectName(QStringLiteral("agvLiveMap"));
m_agvMapView->setMinimumHeight(320);
m_agvMapView->setStreamMessage(QStringLiteral("连接设备后自动加载实时地图")); m_agvMapView->setStreamMessage(QStringLiteral("连接设备后自动加载实时地图"));
ui.mappingPreviewLayout->insertWidget(2, m_agvMapView, 1); ui.mappingPreviewLayout->insertWidget(1, m_agvMapView, 1);
auto *mapEditor = new AgvMapEditorWidget(m_client, m_agvMapView,
ui.mappingPreviewPanel);
m_agvMapEditor = mapEditor;
mapEditor->setContextProvider([this]() {
AgvMapEditorWidget::Context context;
context.endpoint = endpoint();
context.deviceId = m_agvIdEdit->text().trimmed();
context.mapName = m_agvMapView->mapId();
if (context.mapName.isEmpty())
context.mapName = m_latestAgvState.value(QStringLiteral("map")).toString();
if (context.mapName == m_latestAgvState.value(QStringLiteral("map")).toString())
context.pose = m_latestAgvState;
context.connected = m_connected && m_agvStateAvailable && !m_agvMapSwitchPending
&& (m_agvRequestedMap.isEmpty() || m_agvRequestedMap == context.mapName)
&& (m_agvStreamDeviceId.isEmpty() || m_agvStreamDeviceId == context.deviceId);
context.demo = m_demoCheck->isChecked();
return context;
});
mapEditor->setAutoLoadEnabled(true);
ui.mappingPreviewLayout->insertWidget(1, mapEditor);
auto *mapSelectorBar = new QFrame(ui.mappingPreviewPanel);
mapSelectorBar->setObjectName(QStringLiteral("agvMapSelectorBar"));
mapSelectorBar->setStyleSheet(QStringLiteral(
"QFrame#agvMapSelectorBar { background:#f5f8fd; border:1px solid #e0e8f3; border-radius:8px; }"));
auto *mapSelectionLayout = new QVBoxLayout(mapSelectorBar);
mapSelectionLayout->setContentsMargins(12, 4, 12, 4);
mapSelectionLayout->setSpacing(4);
auto *mapSelectionRow = new QHBoxLayout();
mapSelectionRow->setContentsMargins(0, 0, 0, 0);
mapSelectionRow->setSpacing(10);
auto *mapSelectionLabel = new QLabel(QStringLiteral("地图"), mapSelectorBar);
mapSelectionLabel->setObjectName(QStringLiteral("sectionTitle"));
ui.agvMapCombo->setParent(mapSelectorBar);
ui.agvMapCombo->setMinimumWidth(220);
ui.agvMapCombo->setToolTip(QStringLiteral("列出 AGV 已有地图;可输入名称搜索,选中后点击“切换地图”"));
m_agvMapListSummary = new QLabel(QStringLiteral("连接后读取地图列表"), mapSelectorBar);
m_agvMapListSummary->setObjectName(QStringLiteral("agvMapListSummary"));
m_agvMapListSummary->setStyleSheet(QStringLiteral("color:#8593a6; font-size:11px"));
ui.inventoryButton->setParent(mapSelectorBar);
ui.switchMapButton->setParent(mapSelectorBar);
ui.inventoryButton->setText(QStringLiteral("刷新地图列表"));
ui.switchMapButton->setText(QStringLiteral("切换地图"));
ui.inventoryButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/rotate-ccw.svg"),
QColor(QStringLiteral("#66727d"))));
mapSelectionRow->addWidget(mapSelectionLabel);
mapSelectionRow->addWidget(ui.agvMapCombo, 1);
mapSelectionRow->addWidget(m_agvMapListSummary);
mapSelectionRow->addWidget(ui.inventoryButton);
mapSelectionRow->addWidget(ui.switchMapButton);
mapSelectionLayout->addLayout(mapSelectionRow);
auto *mapConnectionRow = new QHBoxLayout();
mapConnectionRow->setSpacing(10);
mapConnectionRow->addWidget(new QLabel(QStringLiteral("地图连接"), mapSelectorBar));
m_agvMapDirectMode = new QComboBox(mapSelectorBar);
m_agvMapDirectMode->setObjectName(QStringLiteral("agvMapDirectMode"));
m_agvMapDirectMode->addItem(QStringLiteral("通过服务"), false);
m_agvMapDirectMode->addItem(QStringLiteral("车辆直连"), true);
m_agvMapDirectMode->setToolTip(QStringLiteral(
"车辆直连用于读取、保存和切换地图;每次写入前检查车辆静止并申请控制权。"));
mapConnectionRow->addWidget(m_agvMapDirectMode);
m_agvMapDirectHost = new QLineEdit(mapSelectorBar);
m_agvMapDirectHost->setObjectName(QStringLiteral("agvMapDirectHost"));
m_agvMapDirectHost->setPlaceholderText(QStringLiteral("车辆 IP(留空时从设备配置读取)"));
m_agvMapDirectHost->setToolTip(QStringLiteral(
"填写车辆的 SEER 地址。留空时从配置服务读取当前设备的车辆地址和端口;手填时使用标准 SEER 端口。"));
m_agvMapDirectHost->setEnabled(false);
mapConnectionRow->addWidget(m_agvMapDirectHost, 1);
mapSelectionLayout->addLayout(mapConnectionRow);
m_agvMapSwitchStatus = new QLabel(mapSelectorBar);
m_agvMapSwitchStatus->setObjectName(QStringLiteral("agvMapSwitchStatus"));
m_agvMapSwitchStatus->setWordWrap(true);
m_agvMapSwitchStatus->hide();
mapSelectionLayout->addWidget(m_agvMapSwitchStatus);
ui.mappingPreviewLayout->insertWidget(1, mapSelectorBar);
const auto refreshEditorContext = [mapEditor]() {
QTimer::singleShot(0, mapEditor, &AgvMapEditorWidget::refreshContext);
};
connect(m_client, &RobotClient::connectionChanged, mapEditor, refreshEditorContext);
m_agvContextDeviceId = m_agvIdEdit->text().trimmed();
connect(m_agvIdEdit, &QLineEdit::textChanged, this, [this](const QString &text) {
const QString device = text.trimmed();
if (device == m_agvContextDeviceId)
return;
stopAgvManualMotion();
m_agvContextDeviceId = device;
m_client->cancelAgvMapDirectRequests();
if (m_agvMapDirectHost)
m_agvMapDirectHost->clear();
configureAgvMapDirectConnection();
m_agvMapStreamPaused = false;
m_agvDeviceRefreshPending = true;
m_agvStatusRefreshTimer->stop();
clearAgvDisplay(device.isEmpty() ? QStringLiteral("请填写 AGV 设备 ID")
: QStringLiteral("等待当前设备状态"));
});
connect(m_agvIdEdit, &QLineEdit::editingFinished, this, [this]() {
if (!m_agvDeviceRefreshPending || !m_connected || !m_pages
|| m_pages->currentIndex() != 3 || m_agvIdEdit->text().trimmed().isEmpty())
return;
m_agvDeviceRefreshPending = false;
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed());
m_agvStatusRefreshTimer->start();
});
const auto resetAgvSource = [this]() {
stopAgvManualMotion();
m_client->cancelAgvMapDirectRequests();
if (m_agvMapDirectHost)
m_agvMapDirectHost->clear();
configureAgvMapDirectConnection();
m_agvMapStreamPaused = false;
m_agvStatusRefreshTimer->stop();
clearAgvDisplay(QStringLiteral("等待重新连接 AGV"));
};
connect(m_hostEdit, &QLineEdit::textChanged, this, resetAgvSource);
connect(m_portSpin, qOverload<int>(&QSpinBox::valueChanged), this, resetAgvSource);
connect(m_demoCheck, &QCheckBox::toggled, this, resetAgvSource);
connect(m_agvMapDirectMode, qOverload<int>(&QComboBox::currentIndexChanged),
this, [this](int) {
configureAgvMapDirectConnection();
if (m_agvMapEditor)
m_agvMapEditor->refreshContext();
saveSettings();
});
connect(m_agvMapDirectHost, &QLineEdit::textChanged, this, [this]() {
configureAgvMapDirectConnection();
});
connect(m_agvMapDirectHost, &QLineEdit::editingFinished, this, [this]() {
if (m_agvMapEditor)
m_agvMapEditor->refreshContext();
saveSettings();
});
connect(m_client, &RobotClient::agvMapDirectBusyChanged, this, [this](bool busy) {
m_agvDirectBusy = busy;
if (busy)
stopAgvManualMotion();
updateAgvDirectControls();
if (!busy) {
const quint64 switchToken = m_agvMapSwitchToken;
QTimer::singleShot(0, this, [this, switchToken]() {
refreshConfirmedAgvMap(switchToken);
});
}
});
connect(m_client, &RobotClient::agvDirectMapSwitchConfirmed, this,
[this](const QString &deviceId, const QString &mapName, const QString &) {
if (!m_agvMapDirectMode->currentData().toBool() || m_demoCheck->isChecked()
|| !m_agvSwitchMapUsesDirect || m_agvMapSwitchPending || !m_agvSwitchMapAccepted
|| !m_agvSwitchMapError.isEmpty()
|| m_agvMapSwitchRefreshToken != m_agvMapSwitchToken
|| m_agvMapSwitchRefreshToken == 0
|| deviceId != m_agvIdEdit->text().trimmed()
|| mapName != m_agvSwitchMapTarget || m_agvSwitchMapEndpoint != endpoint())
return;
m_agvDirectConfirmedMap = mapName;
updateAgvMapSwitchStatus();
refreshConfirmedAgvMap(m_agvMapSwitchToken);
});
connect(m_agvMapCombo, &QComboBox::currentTextChanged, mapEditor, refreshEditorContext);
connect(mapEditor, &AgvMapEditorWidget::busyChanged, page, [this, ui](bool busy) {
m_agvMapEditorBusy = busy;
for (QWidget *control : {static_cast<QWidget *>(m_agvIdEdit),
static_cast<QWidget *>(m_agvMapCombo),
static_cast<QWidget *>(ui.switchMapButton),
static_cast<QWidget *>(ui.uploadMapButton),
static_cast<QWidget *>(ui.downloadMapButton),
static_cast<QWidget *>(ui.startMappingButton)})
control->setEnabled(!busy && !m_agvMapSwitchPending && m_connected);
updateAgvDirectControls();
if (!busy) {
const quint64 switchToken = m_agvMapSwitchToken;
QTimer::singleShot(0, this, [this, switchToken]() {
refreshConfirmedAgvMap(switchToken);
});
}
});
connect(mapEditor, &AgvMapEditorWidget::mapSaved, page, [this]() {
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed());
restartAgvMapStream(m_agvMapView->mapId());
});
leftLayout->addWidget(ui.mappingPreviewPanel, 1); leftLayout->addWidget(ui.mappingPreviewPanel, 1);
QFrame *mapActionsPanel = new QFrame(leftColumn); auto *controlTools = new QTabWidget(rightColumn);
controlTools->setObjectName(QStringLiteral("agvControlTools"));
controlTools->setDocumentMode(true);
QFrame *mapActionsPanel = new QFrame(controlTools);
mapActionsPanel->setObjectName(QStringLiteral("panel")); mapActionsPanel->setObjectName(QStringLiteral("panel"));
QVBoxLayout *mapActionsLayout = new QVBoxLayout(mapActionsPanel); QVBoxLayout *mapActionsLayout = new QVBoxLayout(mapActionsPanel);
mapActionsLayout->setContentsMargins(18, 14, 18, 14); mapActionsLayout->setContentsMargins(14, 14, 14, 14);
mapActionsLayout->setSpacing(9); mapActionsLayout->setSpacing(9);
QLabel *mapActionsTitle = new QLabel(QStringLiteral("地图与建图"), QLabel *mapActionsTitle = new QLabel(QStringLiteral("地图与建图"),
mapActionsPanel); mapActionsPanel);
mapActionsTitle->setObjectName(QStringLiteral("sectionTitle")); mapActionsTitle->setObjectName(QStringLiteral("sectionTitle"));
QLabel *mapActionsSubtitle = new QLabel( QLabel *mapActionsSubtitle = new QLabel(
QStringLiteral("加载已有地图、重新定位,或创建新的建图会话"), QStringLiteral("管理地图与建图会话"),
mapActionsPanel); mapActionsPanel);
mapActionsSubtitle->setObjectName(QStringLiteral("panelSubtitle")); mapActionsSubtitle->setObjectName(QStringLiteral("panelSubtitle"));
mapActionsLayout->addWidget(mapActionsTitle); mapActionsLayout->addWidget(mapActionsTitle);
mapActionsLayout->addWidget(mapActionsSubtitle); mapActionsLayout->addWidget(mapActionsSubtitle);
QHBoxLayout *mapSelectionRow = new QHBoxLayout;
ui.agvMapCombo->setParent(mapActionsPanel);
ui.inventoryButton->setParent(mapActionsPanel);
ui.switchMapButton->setParent(mapActionsPanel);
ui.inventoryButton->setText(QStringLiteral("刷新列表"));
ui.switchMapButton->setText(QStringLiteral("加载地图"));
mapSelectionRow->addWidget(ui.agvMapCombo, 1);
mapSelectionRow->addWidget(ui.inventoryButton);
mapSelectionRow->addWidget(ui.switchMapButton);
mapActionsLayout->addLayout(mapSelectionRow);
QPushButton *addMapButton = new QPushButton(QStringLiteral("新增地图"), QPushButton *addMapButton = new QPushButton(QStringLiteral("新增地图"),
mapActionsPanel); mapActionsPanel);
QPushButton *relocalizeButton = new QPushButton(QStringLiteral("重新定位"), QPushButton *relocalizeButton = new QPushButton(QStringLiteral("重新定位"),
@ -2113,13 +2349,14 @@ QWidget *MainWindow::createAgvPage()
mapActionsLayout->addLayout(mapOperationRow); mapActionsLayout->addLayout(mapOperationRow);
QGridLayout *mappingForm = new QGridLayout; QGridLayout *mappingForm = new QGridLayout;
QLabel *mappingNameLabel = new QLabel(QStringLiteral("新地图"), QLabel *mappingNameLabel = new QLabel(QStringLiteral("名称"),
mapActionsPanel); mapActionsPanel);
QLabel *mappingDimensionLabel = new QLabel(QStringLiteral("类型"), QLabel *mappingDimensionLabel = new QLabel(QStringLiteral("类型"),
mapActionsPanel); mapActionsPanel);
ui.mappingNameEdit->setParent(mapActionsPanel); ui.mappingNameEdit->setParent(mapActionsPanel);
ui.mappingDimensionCombo->setParent(mapActionsPanel); ui.mappingDimensionCombo->setParent(mapActionsPanel);
ui.mappingRealtimeCheck->setParent(mapActionsPanel); ui.mappingRealtimeCheck->setParent(mapActionsPanel);
ui.mappingDimensionCombo->setMaximumWidth(120);
mappingForm->addWidget(mappingNameLabel, 0, 0); mappingForm->addWidget(mappingNameLabel, 0, 0);
mappingForm->addWidget(ui.mappingNameEdit, 0, 1); mappingForm->addWidget(ui.mappingNameEdit, 0, 1);
mappingForm->addWidget(mappingDimensionLabel, 0, 2); mappingForm->addWidget(mappingDimensionLabel, 0, 2);
@ -2142,26 +2379,115 @@ QWidget *MainWindow::createAgvPage()
transferRow->addWidget(ui.uploadMapButton); transferRow->addWidget(ui.uploadMapButton);
transferRow->addWidget(ui.downloadMapButton); transferRow->addWidget(ui.downloadMapButton);
mapActionsLayout->addLayout(transferRow); mapActionsLayout->addLayout(transferRow);
leftLayout->addWidget(mapActionsPanel); mapActionsLayout->addStretch();
controlTools->addTab(mapActionsPanel, QStringLiteral("地图与建图"));
statusUi.agvDialogSurface->setGraphicsEffect(nullptr); statusUi.agvDialogSurface->setGraphicsEffect(nullptr);
statusUi.agvDialogSurface->setParent(rightColumn); statusUi.agvDialogSurface->setParent(rightColumn);
statusUi.agvDialogSurface->setMinimumSize(0, 0); statusUi.agvDialogSurface->setMinimumSize(0, 0);
statusUi.agvDialogTitleBar->hide(); statusUi.agvDialogTitleBar->hide();
statusUi.agvDialogContentLayout->setContentsMargins(0, 0, 0, 0); statusUi.agvDialogContentLayout->setContentsMargins(0, 0, 0, 0);
statusUi.navigationStatusPanel->setMaximumHeight(150); statusUi.runtimeLayout->setContentsMargins(14, 12, 14, 12);
rightLayout->addWidget(statusUi.agvDialogSurface, 3); statusUi.runtimeLayout->setSpacing(8);
statusUi.statusLayout->setVerticalSpacing(6);
statusUi.statusLayout->setHorizontalSpacing(14);
while (QLayoutItem *item = statusUi.statusLayout->takeAt(0))
delete item;
const QVector<QPair<QLabel *, QLabel *>> statusRows = {
{statusUi.connectionTitle, m_agvConnectionValue},
{statusUi.mapTitle, m_agvMapValue},
{statusUi.poseTitle, m_agvPoseValue},
{statusUi.batteryTitle, m_agvBatteryValue},
{statusUi.safetyTitle, m_agvSafetyValue},
{statusUi.errorTitle, m_agvErrorValue},
{statusUi.motionTitle, m_agvMotionValue},
{statusUi.modeTitle, m_agvModeValue},
{statusUi.motionStateTitle, m_agvMotionStateValue},
{statusUi.powerTitle, m_agvPowerValue},
{statusUi.timestampTitle, m_agvTimestampValue}
};
for (int row = 0; row < statusRows.size(); ++row) {
statusUi.statusLayout->addWidget(statusRows.at(row).first, row, 0);
statusUi.statusLayout->addWidget(statusRows.at(row).second, row, 1);
statusRows.at(row).second->setWordWrap(true);
statusRows.at(row).second->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
if (row >= 6) {
statusRows.at(row).first->hide();
statusRows.at(row).second->hide();
}
}
statusUi.statusLayout->setColumnStretch(0, 0);
statusUi.statusLayout->setColumnStretch(1, 1);
auto *runtimeHeader = new QHBoxLayout;
statusUi.runtimeLayout->removeWidget(statusUi.runtimeTitle);
auto *moreStateButton = new QPushButton(QStringLiteral("详细状态"), statusUi.runtimePanel);
moreStateButton->setCheckable(true);
moreStateButton->setObjectName(QStringLiteral("agvMapToolButton"));
runtimeHeader->addWidget(statusUi.runtimeTitle);
runtimeHeader->addStretch();
runtimeHeader->addWidget(moreStateButton);
statusUi.runtimeLayout->insertLayout(0, runtimeHeader);
connect(moreStateButton, &QPushButton::toggled, page, [statusRows, moreStateButton](bool expanded) {
for (int row = 6; row < statusRows.size(); ++row) {
statusRows.at(row).first->setVisible(expanded);
statusRows.at(row).second->setVisible(expanded);
}
moreStateButton->setText(expanded ? QStringLiteral("收起状态") : QStringLiteral("详细状态"));
});
statusUi.navigationStatusLayout->setContentsMargins(14, 12, 14, 12);
statusUi.navigationStatusLayout->setSpacing(6);
statusUi.agvNavigationValue->setMinimumHeight(30);
statusUi.navigationStatusPanel->setMaximumHeight(140);
rightLayout->addWidget(statusUi.agvDialogSurface);
ui.velocityPanel->setParent(rightColumn); ui.velocityPanel->setParent(controlTools);
ui.velocityPanel->setMinimumSize(0, 0); ui.velocityPanel->setMinimumSize(0, 0);
ui.velocityTitle->setText(QStringLiteral("手动速度控制")); ui.velocityTitle->setText(QStringLiteral("手动速度控制"));
ui.velocitySubtitle->setText( ui.velocitySubtitle->setText(
QStringLiteral("按住方向按钮或 Q/W/E/A/S/D 键运动,松开即停止")); QStringLiteral("按住方向按钮或 Q/W/E/A/S/D 键运动;松开或停止时按梯度减速,急停立即执行"));
ui.velocitySubtitle->setWordWrap(true);
ui.velocityLayout->setContentsMargins(14, 14, 14, 14);
ui.velocityLayout->setSpacing(8);
m_agvVxSpin->setMinimum(0.0); m_agvVxSpin->setMinimum(0.0);
m_agvVySpin->setMinimum(0.0); m_agvVySpin->setMinimum(0.0);
m_agvWzSpin->setMinimum(0.0); m_agvWzSpin->setMinimum(0.0);
if (qFuzzyIsNull(m_agvVySpin->value())) if (qFuzzyIsNull(m_agvVySpin->value()))
m_agvVySpin->setValue(0.2); m_agvVySpin->setValue(0.2);
auto *rampPanel = new QWidget(ui.velocityPanel);
rampPanel->setObjectName(QStringLiteral("agvManualRampPanel"));
auto *rampLayout = new QGridLayout(rampPanel);
rampLayout->setContentsMargins(0, 0, 0, 0);
rampLayout->setHorizontalSpacing(6);
rampLayout->setVerticalSpacing(6);
const auto addRampSetting = [this, rampPanel, rampLayout](const QString &name,
const QString &text, const QString &unit, double value, int row, int column) {
auto *label = new QLabel(text, rampPanel);
auto *spin = new QDoubleSpinBox(rampPanel);
spin->setObjectName(name);
spin->setRange(0.01, 5.0);
spin->setDecimals(2);
spin->setSingleStep(0.05);
spin->setSuffix(unit);
spin->setValue(value);
spin->setToolTip(QStringLiteral("数值越小,速度变化越缓;普通停止会有减速过程,急停不使用梯度。"));
label->setBuddy(spin);
rampLayout->addWidget(label, row, column);
rampLayout->addWidget(spin, row, column + 1);
connect(spin, qOverload<double>(&QDoubleSpinBox::valueChanged), this,
[this](double) { saveSettings(); });
return spin;
};
m_agvLinearAccelerationSpin = addRampSetting(QStringLiteral("agvLinearAccelerationSpin"),
QStringLiteral("线加速度"), QStringLiteral(" m/s²"), 0.2, 0, 0);
m_agvLinearDecelerationSpin = addRampSetting(QStringLiteral("agvLinearDecelerationSpin"),
QStringLiteral("线减速度"), QStringLiteral(" m/s²"), 0.3, 0, 2);
m_agvAngularAccelerationSpin = addRampSetting(QStringLiteral("agvAngularAccelerationSpin"),
QStringLiteral("角加速度"), QStringLiteral(" rad/s²"), 0.5, 1, 0);
m_agvAngularDecelerationSpin = addRampSetting(QStringLiteral("agvAngularDecelerationSpin"),
QStringLiteral("角减速度"), QStringLiteral(" rad/s²"), 0.8, 1, 2);
// Keep the direction pad above the settings so it remains easy to reach
// in the existing scrolling sidebar.
ui.velocityLayout->insertWidget(ui.velocityLayout->count() - 2, rampPanel);
ui.rotateLeftButton->setText(QStringLiteral("左旋 (Q)")); ui.rotateLeftButton->setText(QStringLiteral("左旋 (Q)"));
ui.forwardButton->setText(QStringLiteral("前进 (W)")); ui.forwardButton->setText(QStringLiteral("前进 (W)"));
ui.rotateRightButton->setText(QStringLiteral("右旋 (E)")); ui.rotateRightButton->setText(QStringLiteral("右旋 (E)"));
@ -2169,7 +2495,13 @@ QWidget *MainWindow::createAgvPage()
ui.rightButton->setText(QStringLiteral("右移 (D)")); ui.rightButton->setText(QStringLiteral("右移 (D)"));
ui.backwardButton->setText(QStringLiteral("后退 (S)")); ui.backwardButton->setText(QStringLiteral("后退 (S)"));
ui.velocityButton->hide(); ui.velocityButton->hide();
rightLayout->addWidget(ui.velocityPanel, 4); controlTools->addTab(ui.velocityPanel, QStringLiteral("手动控制"));
connect(controlTools, &QTabWidget::currentChanged, this,
[this](int) { stopAgvManualMotion(); });
connect(ui.agvTabs, &QTabWidget::currentChanged, this,
[this](int) { stopAgvManualMotion(); });
rightLayout->addWidget(controlTools);
rightLayout->addStretch();
const auto removeOriginalTab = [tabs = ui.agvTabs](QWidget *tab) { const auto removeOriginalTab = [tabs = ui.agvTabs](QWidget *tab) {
const int index = tabs->indexOf(tab); const int index = tabs->indexOf(tab);
@ -2253,10 +2585,18 @@ QWidget *MainWindow::createAgvPage()
connect(ui.refreshButton, &QPushButton::clicked, this, [this]() { connect(ui.refreshButton, &QPushButton::clicked, this, [this]() {
m_agvMapStreamPaused = false;
m_agvMapRecoveryNeeded = !m_agvMapStreamActive;
m_agvMapRecoveryAttempted = false;
if (m_connected && !m_agvIdEdit->text().trimmed().isEmpty()) {
m_agvDeviceRefreshPending = false;
m_agvStatusRefreshTimer->start();
}
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
}); });
connect(m_agvStatusRefreshTimer, &QTimer::timeout, this, [this]() { connect(m_agvStatusRefreshTimer, &QTimer::timeout, this, [this]() {
if (m_connected && m_pages && m_pages->currentIndex() == 3) if (m_connected && m_pages && m_pages->currentIndex() == 3
&& !m_agvIdEdit->text().trimmed().isEmpty() && !m_agvDeviceRefreshPending)
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
}); });
connect(ui.navigatePoseButton, &QPushButton::clicked, this, [this]() { connect(ui.navigatePoseButton, &QPushButton::clicked, this, [this]() {
@ -2265,8 +2605,11 @@ QWidget *MainWindow::createAgvPage()
m_agvMaxSpeedSpin->value()); m_agvMaxSpeedSpin->value());
}); });
connect(ui.navigateStationButton, &QPushButton::clicked, this, [this]() { connect(ui.navigateStationButton, &QPushButton::clicked, this, [this]() {
const int index = m_agvStationCombo->currentIndex();
const QString stationId = index >= 0 && m_agvStationCombo->currentText() == m_agvStationCombo->itemText(index)
? m_agvStationCombo->currentData().toString() : m_agvStationCombo->currentText().trimmed();
m_client->requestAgvNavigateStation(m_agvIdEdit->text().trimmed(), m_client->requestAgvNavigateStation(m_agvIdEdit->text().trimmed(),
m_agvStationCombo->currentText().trimmed(), stationId,
m_agvMaxSpeedSpin->value()); m_agvMaxSpeedSpin->value());
}); });
connect(ui.pauseButton, &QPushButton::clicked, this, [this]() { connect(ui.pauseButton, &QPushButton::clicked, this, [this]() {
@ -2280,37 +2623,53 @@ QWidget *MainWindow::createAgvPage()
}); });
connect(ui.forwardButton, &QPushButton::pressed, this, [this]() { connect(ui.forwardButton, &QPushButton::pressed, this, [this]() {
startAgvManualMotion(qAbs(m_agvVxSpin->value()), 0.0, 0.0); startAgvManualMotion(qAbs(m_agvVxSpin->value()), 0.0, 0.0);
m_agvManualKey = 0;
m_agvManualButton = m_agvManualMotionActive ? qobject_cast<QPushButton *>(sender()) : nullptr;
}); });
connect(ui.backwardButton, &QPushButton::pressed, this, [this]() { connect(ui.backwardButton, &QPushButton::pressed, this, [this]() {
startAgvManualMotion(-qAbs(m_agvVxSpin->value()), 0.0, 0.0); startAgvManualMotion(-qAbs(m_agvVxSpin->value()), 0.0, 0.0);
m_agvManualKey = 0;
m_agvManualButton = m_agvManualMotionActive ? qobject_cast<QPushButton *>(sender()) : nullptr;
}); });
connect(ui.leftButton, &QPushButton::pressed, this, [this]() { connect(ui.leftButton, &QPushButton::pressed, this, [this]() {
startAgvManualMotion(0.0, qAbs(m_agvVySpin->value()), 0.0); startAgvManualMotion(0.0, qAbs(m_agvVySpin->value()), 0.0);
m_agvManualKey = 0;
m_agvManualButton = m_agvManualMotionActive ? qobject_cast<QPushButton *>(sender()) : nullptr;
}); });
connect(ui.rightButton, &QPushButton::pressed, this, [this]() { connect(ui.rightButton, &QPushButton::pressed, this, [this]() {
startAgvManualMotion(0.0, -qAbs(m_agvVySpin->value()), 0.0); startAgvManualMotion(0.0, -qAbs(m_agvVySpin->value()), 0.0);
m_agvManualKey = 0;
m_agvManualButton = m_agvManualMotionActive ? qobject_cast<QPushButton *>(sender()) : nullptr;
}); });
connect(ui.rotateLeftButton, &QPushButton::pressed, this, [this]() { connect(ui.rotateLeftButton, &QPushButton::pressed, this, [this]() {
startAgvManualMotion(0.0, 0.0, qAbs(m_agvWzSpin->value())); startAgvManualMotion(0.0, 0.0, qAbs(m_agvWzSpin->value()));
m_agvManualKey = 0;
m_agvManualButton = m_agvManualMotionActive ? qobject_cast<QPushButton *>(sender()) : nullptr;
}); });
connect(ui.rotateRightButton, &QPushButton::pressed, this, [this]() { connect(ui.rotateRightButton, &QPushButton::pressed, this, [this]() {
startAgvManualMotion(0.0, 0.0, -qAbs(m_agvWzSpin->value())); startAgvManualMotion(0.0, 0.0, -qAbs(m_agvWzSpin->value()));
m_agvManualKey = 0;
m_agvManualButton = m_agvManualMotionActive ? qobject_cast<QPushButton *>(sender()) : nullptr;
}); });
for (QPushButton *button : { for (QPushButton *button : {
ui.forwardButton, ui.backwardButton, ui.leftButton, ui.forwardButton, ui.backwardButton, ui.leftButton,
ui.rightButton, ui.rotateLeftButton, ui.rotateRightButton}) { ui.rightButton, ui.rotateLeftButton, ui.rotateRightButton}) {
connect(button, &QPushButton::released, this, connect(button, &QPushButton::released, this,
[this]() { stopAgvManualMotion(); }); [this, button]() {
if (m_agvManualButton == button)
decelerateAgvManualMotion();
});
} }
connect(ui.manualStopButton, &QPushButton::clicked, this, connect(ui.manualStopButton, &QPushButton::clicked, this,
[this]() { stopAgvManualMotion(); }); [this]() { decelerateAgvManualMotion(); });
connect(ui.zeroVelocityButton, &QPushButton::clicked, this, [this]() { connect(ui.zeroVelocityButton, &QPushButton::clicked, this, [this]() {
stopAgvManualMotion(); decelerateAgvManualMotion();
m_agvVxSpin->setValue(0.0); m_agvVxSpin->setValue(0.0);
m_agvVySpin->setValue(0.0); m_agvVySpin->setValue(0.0);
m_agvWzSpin->setValue(0.0); m_agvWzSpin->setValue(0.0);
}); });
connect(statusUi.stopVelocityButton, &QPushButton::clicked, this, [this]() { connect(statusUi.stopVelocityButton, &QPushButton::clicked, this, [this]() {
stopAgvManualMotion(false);
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), m_client->requestAgvAction(m_agvIdEdit->text().trimmed(),
QStringLiteral("StopVelocity")); QStringLiteral("StopVelocity"));
}); });
@ -2318,6 +2677,7 @@ QWidget *MainWindow::createAgvPage()
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("ClearFault")); m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("ClearFault"));
}); });
connect(ui.emergencyButton, &QPushButton::clicked, this, [this]() { connect(ui.emergencyButton, &QPushButton::clicked, this, [this]() {
stopAgvManualMotion(false);
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), m_client->requestAgvAction(m_agvIdEdit->text().trimmed(),
QStringLiteral("EmergencyStop")); QStringLiteral("EmergencyStop"));
}); });
@ -2325,8 +2685,34 @@ QWidget *MainWindow::createAgvPage()
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); m_client->requestAgvInventory(m_agvIdEdit->text().trimmed());
}); });
connect(ui.switchMapButton, &QPushButton::clicked, this, [this]() { connect(ui.switchMapButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvSwitchMap(m_agvIdEdit->text().trimmed(), if (!m_connected || m_agvMapSwitchPending || m_agvMapEditorBusy || m_agvDirectBusy)
m_agvMapCombo->currentText().trimmed()); return;
m_agvDirectConfirmedMap.clear();
m_agvDirectSwitchDetail.clear();
const QString target = m_agvMapCombo->currentText().trimmed();
const QString device = m_agvIdEdit->text().trimmed();
if (target.isEmpty() || device.isEmpty())
return;
m_agvMapSwitchPending = true;
m_agvMapSwitchRefreshToken = ++m_agvMapSwitchToken;
m_agvSwitchMapRuntimeConfirmed = false;
m_agvSwitchMapUsesDirect = m_agvMapDirectMode->currentData().toBool()
&& !m_demoCheck->isChecked();
m_agvSwitchMapPreviousTimestamp =
m_latestAgvState.value(QStringLiteral("timestamp")).toDouble();
m_agvSwitchMapTarget = target;
m_agvSwitchMapDevice = device;
m_agvSwitchMapEndpoint = endpoint();
m_agvSwitchMapDemo = m_demoCheck->isChecked();
m_agvSwitchMapAccepted = false;
m_agvSwitchMapError.clear();
m_agvMapCombo->setEnabled(false);
m_agvIdEdit->setEnabled(false);
m_agvSwitchMapButton->setEnabled(false);
m_agvMapEditor->refreshContext();
restartAgvMapStream(target);
updateAgvMapSwitchStatus();
m_client->requestAgvSwitchMap(device, target);
}); });
connect(ui.uploadMapButton, &QPushButton::clicked, this, [this]() { connect(ui.uploadMapButton, &QPushButton::clicked, this, [this]() {
const QString path = QFileDialog::getOpenFileName( const QString path = QFileDialog::getOpenFileName(
@ -2448,6 +2834,30 @@ QWidget *MainWindow::createAgvPage()
ui.mappingStateLabel->setText(QStringLiteral("正在停止建图")); ui.mappingStateLabel->setText(QStringLiteral("正在停止建图"));
}); });
connect(ui.startMapStreamButton, &QPushButton::clicked, this, [this, ui]() { connect(ui.startMapStreamButton, &QPushButton::clicked, this, [this, ui]() {
if (!m_connected || m_agvIdEdit->text().trimmed().isEmpty() || m_agvMapSwitchPending)
return;
m_agvRequestedMap = ui.mappingNameEdit->text().trimmed();
m_agvStreamDeviceId = m_agvIdEdit->text().trimmed();
m_agvStreamEndpoint = endpoint();
m_agvStreamDemo = m_demoCheck->isChecked();
m_agvStreamRequested = true;
m_agvMapStreamPaused = false;
m_agvMapRecoveryNeeded = false;
// Live mapping sessions are restarted explicitly by their own controls.
m_agvMapRecoveryAttempted = true;
m_agvMapReadError.clear();
m_agvSwitchMapTarget.clear();
m_agvMapSwitchRefreshToken = 0;
++m_agvMapSwitchToken;
m_agvSwitchMapAccepted = false;
m_agvSwitchMapError.clear();
m_agvMapFramePending = false;
m_pendingAgvMapImage = QImage();
m_pendingAgvMapMetadata.clear();
m_pendingAgvMapDetail.clear();
if (!m_agvRequestedMap.isEmpty() && m_agvMapView->mapId() != m_agvRequestedMap)
m_agvMapView->clearMapFrame(QStringLiteral("正在接收建图地图…"));
updateAgvMapSwitchStatus();
m_client->startAgvMapStream( m_client->startAgvMapStream(
m_agvIdEdit->text().trimmed(), ui.mappingNameEdit->text().trimmed(), m_agvIdEdit->text().trimmed(), ui.mappingNameEdit->text().trimmed(),
ui.mappingDimensionCombo->currentIndex() + 1, ui.mappingDimensionCombo->currentIndex() + 1,
@ -2455,7 +2865,16 @@ QWidget *MainWindow::createAgvPage()
ui.streamIncrementalCheck->isChecked()); ui.streamIncrementalCheck->isChecked());
}); });
connect(ui.stopMapStreamButton, &QPushButton::clicked, this, [this]() { connect(ui.stopMapStreamButton, &QPushButton::clicked, this, [this]() {
m_agvMapStreamPaused = true;
m_agvStreamRequested = false;
m_agvMapStreamActive = false;
m_agvMapRecoveryNeeded = false;
m_agvMapRecoveryAttempted = true;
presentPendingAgvMapFrame();
m_agvMapRefreshTimer->stop();
m_client->stopAgvMapStream(); m_client->stopAgvMapStream();
m_agvMappingStateLabel->setText(QStringLiteral("地图流已停止"));
m_agvMapView->setStreamMessage(QStringLiteral("地图流已停止"));
}); });
ui.agvTabs->addTab(new RpcServiceWidget(QStringLiteral("cmvr.api.AgvService"), m_client), ui.agvTabs->addTab(new RpcServiceWidget(QStringLiteral("cmvr.api.AgvService"), m_client),
@ -2471,6 +2890,11 @@ QWidget *MainWindow::createAgvPage()
<< ui.followPathButton << ui.startMappingButton << ui.stopMappingButton << ui.followPathButton << ui.startMappingButton << ui.stopMappingButton
<< ui.startMapStreamButton << ui.stopMapStreamButton << ui.startMapStreamButton << ui.stopMapStreamButton
<< ui.uploadMapButton << ui.downloadMapButton; << ui.uploadMapButton << ui.downloadMapButton;
m_agvDirectBlockedControls << ui.navigatePoseButton << ui.navigateStationButton
<< ui.resumeButton << ui.velocityButton << relocalizeButton
<< ui.forwardButton << ui.backwardButton << ui.leftButton << ui.rightButton
<< ui.rotateLeftButton << ui.rotateRightButton << ui.followPathButton
<< ui.startMappingButton << ui.switchMapButton << ui.uploadMapButton;
return page; return page;
} }

File diff suppressed because it is too large Load Diff

View File

@ -11,6 +11,9 @@
#include <QVariantList> #include <QVariantList>
#include <QVariantMap> #include <QVariantMap>
#include <atomic>
#include <memory>
#include "videoframe.h" #include "videoframe.h"
class BackendWorker; class BackendWorker;
@ -24,6 +27,7 @@ public:
~RobotClient() override; ~RobotClient() override;
bool grpcAvailable() const; bool grpcAvailable() const;
quint64 agvMapStreamGeneration() const;
public slots: public slots:
void requestUserCoordinates(const QString &deviceId, const QVariantMap &parameters, quint64 token); void requestUserCoordinates(const QString &deviceId, const QVariantMap &parameters, quint64 token);
@ -95,11 +99,23 @@ public slots:
void requestAgvFollowPath(const QString &deviceId, const QVariantList &path, void requestAgvFollowPath(const QString &deviceId, const QVariantList &path,
double maxSpeed); double maxSpeed);
void requestAgvVelocity(const QString &deviceId, double vx, double vy, double wz); void requestAgvVelocity(const QString &deviceId, double vx, double vy, double wz);
void beginAgvManualControl(const QString &deviceId);
void requestAgvManualVelocity(quint64 requestId, const QString &deviceId,
double vx, double vy, double wz);
void cancelAgvManualVelocity();
void requestAgvAction(const QString &deviceId, const QString &action); void requestAgvAction(const QString &deviceId, const QString &action);
void requestAgvInventory(const QString &deviceId); void requestAgvInventory(const QString &deviceId);
void configureAgvMapDirect(bool enabled, const QString &vehicleHost,
const QString &configHost, int configPort);
void cancelAgvMapDirectRequests();
void requestAgvSwitchMap(const QString &deviceId, const QString &mapName); void requestAgvSwitchMap(const QString &deviceId, const QString &mapName);
void requestAgvMapContent(quint64 requestId, const QString &deviceId,
const QString &mapName);
void saveAgvMapContent(quint64 requestId, const QString &deviceId,
const QString &mapName, const QString &content);
void startAgvMapStream(const QString &deviceId, const QString &mapName, void startAgvMapStream(const QString &deviceId, const QString &mapName,
int dimension, bool snapshot, bool incremental); int dimension, bool snapshot, bool incremental);
void startAgvMapPreview(const QString &deviceId, const QString &mapName);
void stopAgvMapStream(); void stopAgvMapStream();
void requestRpc(const QString &serviceName, const QString &methodName, void requestRpc(const QString &serviceName, const QString &methodName,
const QString &requestJson, const QString &deviceId = QString()); const QString &requestJson, const QString &deviceId = QString());
@ -202,12 +218,21 @@ signals:
void agvFollowPathRequested(const QString &deviceId, const QVariantList &path, void agvFollowPathRequested(const QString &deviceId, const QVariantList &path,
double maxSpeed); double maxSpeed);
void agvVelocityRequested(const QString &deviceId, double vx, double vy, double wz); void agvVelocityRequested(const QString &deviceId, double vx, double vy, double wz);
void agvManualVelocityRequested(quint64 requestId, const QString &deviceId,
double vx, double vy, double wz);
void agvManualVelocityFinished(quint64 requestId, bool success, const QString &detail);
void agvManualControlInterrupted(bool requestStop);
void agvActionRequested(const QString &deviceId, const QString &action); void agvActionRequested(const QString &deviceId, const QString &action);
void agvInventoryRequested(const QString &deviceId); void agvInventoryRequested(const QString &deviceId);
void agvSwitchMapRequested(const QString &deviceId, const QString &mapName); void agvSwitchMapRequested(const QString &deviceId, const QString &mapName);
void agvMapContentRequested(quint64 requestId, const QString &deviceId,
const QString &mapName);
void agvMapSaveRequested(quint64 requestId, const QString &deviceId,
const QString &mapName, const QString &content);
void agvMapStreamStartRequested(const QString &deviceId, const QString &mapName, void agvMapStreamStartRequested(const QString &deviceId, const QString &mapName,
int dimension, bool snapshot, bool incremental); int dimension, bool snapshot, bool incremental,
void agvMapStreamStopRequested(); quint64 generation, bool preview);
void agvMapStreamStopRequested(quint64 generation);
void rpcRequested(const QString &serviceName, const QString &methodName, void rpcRequested(const QString &serviceName, const QString &methodName,
const QString &requestJson, const QString &deviceId); const QString &requestJson, const QString &deviceId);
void speakerAudioStreamStartRequested(const QString &deviceId); void speakerAudioStreamStartRequested(const QString &deviceId);
@ -265,9 +290,23 @@ signals:
void cameraRecordingStateChanged(bool recording, const QString &detail); void cameraRecordingStateChanged(bool recording, const QString &detail);
void agvStateReceived(const QVariantMap &state, const QVariantMap &navigation); void agvStateReceived(const QVariantMap &state, const QVariantMap &navigation);
void agvInventoryReceived(const QStringList &maps, const QVariantList &stations); void agvInventoryReceived(const QStringList &maps, const QVariantList &stations);
void agvInventoryReceivedForContext(const QVariantMap &context,
const QStringList &maps,
const QVariantList &stations);
void agvMapContentReceived(quint64 requestId, const QString &deviceId,
const QString &mapName, const QString &content,
bool success, const QString &detail);
void agvMapSaveFinished(quint64 requestId, const QString &deviceId,
const QString &mapName, bool success,
const QString &detail);
void agvDirectMapSwitchConfirmed(const QString &deviceId, const QString &mapName,
const QString &detail);
void agvMapDirectBusyChanged(bool busy);
void agvMapFrameReceived(const QImage &image, const QVariantMap &metadata, void agvMapFrameReceived(const QImage &image, const QVariantMap &metadata,
const QString &detail); const QString &detail);
void agvMapStreamStateChanged(bool running, const QString &detail); void agvMapStreamStateChanged(bool running, const QString &detail);
void agvMapStreamStateChangedForContext(const QVariantMap &context,
bool running, const QString &detail);
void rpcFinished(const QString &serviceName, const QString &methodName, void rpcFinished(const QString &serviceName, const QString &methodName,
bool success, const QString &responseJson); bool success, const QString &responseJson);
void audioStreamStateChanged(const QString &serviceName, bool running, void audioStreamStateChanged(const QString &serviceName, bool running,
@ -290,8 +329,35 @@ signals:
void logMessage(const QString &level, const QString &message); void logMessage(const QString &level, const QString &message);
private: private:
void interruptAgvManualVelocity(bool requestStop = true);
std::shared_ptr<std::atomic<quint64>> m_agvManualGeneration =
std::make_shared<std::atomic<quint64>>(0);
bool m_agvManualBusy = false;
enum class DirectMapOperation { Read, Save, Switch };
void observeAgvMapDirectDevice(const QString &deviceId);
void cancelAgvMapDirect(bool reportCancellation = true);
void requestAgvMapDirect(DirectMapOperation operation, quint64 requestId,
const QString &deviceId, const QString &mapName,
const QString &content = QString());
bool rejectAgvWhileMapDirectBusy(const QString &command);
QThread m_agvMapDirectThread;
QObject *m_agvMapDirectWorker = nullptr;
bool m_agvMapDirectEnabled = false;
bool m_agvMapDirectDemo = true;
bool m_agvMapDirectBusy = false;
QString m_agvMapDirectHost;
QString m_agvMapDirectConfigHost;
int m_agvMapDirectConfigPort = 50053;
QString m_agvMapDirectDevice;
quint64 m_agvMapDirectGeneration = 0;
std::shared_ptr<std::atomic<bool>> m_agvMapDirectCancel;
DirectMapOperation m_agvMapDirectOperation = DirectMapOperation::Read;
quint64 m_agvMapDirectRequestId = 0;
QString m_agvMapDirectRequestDevice;
QString m_agvMapDirectRequestMap;
QThread m_thread; QThread m_thread;
BackendWorker *m_worker = nullptr; BackendWorker *m_worker = nullptr;
std::atomic<quint64> m_agvMapStreamGeneration{0};
QMutex m_videoFrameMutex; QMutex m_videoFrameMutex;
struct PendingVideoFrame { struct PendingVideoFrame {
VideoFrame frame; VideoFrame frame;

559
src/seeragvmapclient.cpp Normal file
View File

@ -0,0 +1,559 @@
#include "seeragvmapclient.h"
#include <QElapsedTimer>
#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QThread>
#include <QTimer>
#include <QTcpSocket>
#include <algorithm>
#include <atomic>
#include <cmath>
namespace {
constexpr int kSliceMs = 50;
constexpr int kConnectMs = 2500;
constexpr int kExchangeMs = 3000;
constexpr int kMapExchangeMs = 10000;
constexpr int kLoadConfirmationMs = 12000;
constexpr int kPortIntervalMs = 200;
constexpr quint32 kMaximumPayloadBytes = 64U * 1024U * 1024U;
constexpr double kStationaryTolerance = 0.001;
bool canceled(const SeerAgvMapClient::CancelCheck &check)
{
return check && check();
}
quint16 get16(const QByteArray &bytes, int offset)
{
return (quint16(quint8(bytes.at(offset))) << 8) | quint8(bytes.at(offset + 1));
}
quint32 get32(const QByteArray &bytes, int offset)
{
return (quint32(get16(bytes, offset)) << 16) | get16(bytes, offset + 2);
}
void put16(QByteArray &bytes, int offset, quint16 value)
{
bytes[offset] = char(value >> 8);
bytes[offset + 1] = char(value & 0xff);
}
void put32(QByteArray &bytes, int offset, quint32 value)
{
put16(bytes, offset, quint16(value >> 16));
put16(bytes, offset + 2, quint16(value & 0xffff));
}
quint16 nextSequence()
{
static std::atomic<quint32> sequence{0};
return quint16(sequence.fetch_add(1, std::memory_order_relaxed) % 65535U + 1U);
}
bool parseObject(const QByteArray &raw, QJsonObject *object, QString *error)
{
QJsonParseError parseError;
const QJsonDocument document = QJsonDocument::fromJson(raw, &parseError);
if (parseError.error != QJsonParseError::NoError || !document.isObject()) {
*error = QStringLiteral("SEER 回包不是有效 JSON 对象:%1")
.arg(parseError.errorString());
return false;
}
*object = document.object();
return true;
}
bool integerMember(const QJsonObject &object, const QString &key, int *value)
{
const QJsonValue member = object.value(key);
if (!member.isDouble())
return false;
const double number = member.toDouble();
if (!std::isfinite(number) || std::floor(number) != number
|| number < -2147483648.0 || number > 2147483647.0)
return false;
*value = int(number);
return true;
}
// Status replies may omit ret_code according to the existing SEER protocol.
// A modifying reply must explicitly acknowledge success; an empty/malformed
// reply is not sufficient evidence that a map was saved or loaded.
bool controllerSucceeded(const QJsonObject &object, bool requireCode,
QString *error, bool *explicitRejection = nullptr)
{
if (explicitRejection)
*explicitRejection = false;
const QString key = QStringLiteral("ret_code");
if (!object.contains(key)) {
if (!requireCode)
return true;
*error = QStringLiteral("SEER 回包缺少明确的 ret_code,未确认操作结果");
return false;
}
int code = 0;
if (!integerMember(object, key, &code)) {
*error = QStringLiteral("SEER 回包 ret_code 类型无效,未确认操作结果");
return false;
}
if (code == 0)
return true;
if (explicitRejection)
*explicitRejection = true;
*error = QStringLiteral("SEER 命令失败:ret_code=%1,err_msg=%2")
.arg(code).arg(object.value(QStringLiteral("err_msg")).toString());
return false;
}
bool validateMap(const QByteArray &raw, const QString &mapName, QString *error)
{
if (raw.isEmpty() || quint64(raw.size()) > kMaximumPayloadBytes) {
*error = QStringLiteral("地图内容为空或超过 64 MiB 限制");
return false;
}
QJsonObject root;
if (!parseObject(raw, &root, error))
return false;
if (!root.value(QStringLiteral("header")).isObject()) {
*error = QStringLiteral("完整 SMAP 地图缺少顶层 header 对象");
return false;
}
const QJsonObject header = root.value(QStringLiteral("header")).toObject();
const QJsonValue camel = header.value(QStringLiteral("mapName"));
const QJsonValue snake = header.value(QStringLiteral("map_name"));
if ((!camel.isUndefined() && (!camel.isString() || camel.toString() != mapName))
|| (!snake.isUndefined() && (!snake.isString() || snake.toString() != mapName))
|| (camel.isUndefined() && snake.isUndefined())) {
*error = QStringLiteral("SMAP header 中的地图名称与请求地图不一致");
return false;
}
return true;
}
bool validateRequest(const SeerAgvMapConnection &connection, const QString &mapName,
bool writes, QString *error)
{
if (connection.host.trimmed().isEmpty() || mapName.isEmpty()
|| mapName != mapName.trimmed() || mapName.contains(QChar::Null)) {
*error = QStringLiteral("AGV 地址或地图名称无效");
return false;
}
if (connection.configPort == 0
|| (writes && (connection.statusPort == 0 || connection.controlPort == 0
|| connection.nickName.trimmed().isEmpty()))) {
*error = QStringLiteral("AGV TCP 端口或控制器昵称无效");
return false;
}
return true;
}
QByteArray mapRequest(const QString &name)
{
QJsonObject payload;
payload.insert(QStringLiteral("map_name"), name);
return QJsonDocument(payload).toJson(QJsonDocument::Compact);
}
class Channel
{
public:
Channel(const QString &host, quint16 port,
const SeerAgvMapClient::CancelCheck &cancelCheck)
: m_host(host.trimmed()), m_port(port), m_cancelCheck(cancelCheck)
{
m_socket.setReadBufferSize(65536);
}
bool open(QString *error)
{
return connect(error);
}
bool exchange(quint16 command, const QByteArray &payload, QByteArray *response,
QString *error, bool *possiblySent = nullptr,
int timeoutMs = kExchangeMs)
{
if (possiblySent)
*possiblySent = false;
if (quint64(payload.size()) > kMaximumPayloadBytes) {
*error = QStringLiteral("SEER 请求超过 64 MiB 限制");
return false;
}
if (!waitSpacing(error) || !connect(error))
return false;
QElapsedTimer timer;
timer.start();
const quint16 sequence = nextSequence();
QByteArray header(16, '\0');
header[0] = char(0x5a);
header[1] = char(0x01);
put16(header, 2, sequence);
put32(header, 4, quint32(payload.size()));
put16(header, 8, command);
m_lastRequest.start();
if (!writeBytes(header, timer, timeoutMs, error, possiblySent)
|| !writeBytes(payload, timer, timeoutMs, error, possiblySent)) {
m_socket.abort();
return false;
}
QByteArray replyHeader;
if (!readBytes(16, &replyHeader, timer, timeoutMs, error)) {
m_socket.abort();
return false;
}
if (quint8(replyHeader.at(0)) != 0x5a || quint8(replyHeader.at(1)) != 0x01
|| get16(replyHeader, 2) != sequence
|| get16(replyHeader, 8) != quint16(command + 10000U)) {
*error = QStringLiteral("SEER 回包帧头、序号或命令编号不匹配(请求 %1)")
.arg(command);
m_socket.abort();
return false;
}
const quint32 length = get32(replyHeader, 4);
if (length == 0 || length > kMaximumPayloadBytes) {
*error = QStringLiteral("SEER 回包长度无效或超过 64 MiB 限制");
m_socket.abort();
return false;
}
if (!readBytes(int(length), response, timer, timeoutMs, error)) {
m_socket.abort();
return false;
}
return true;
}
bool query(quint16 command, const QByteArray &payload, QJsonObject *object,
QString *error, bool requireCode = false,
bool *possiblySent = nullptr, bool *explicitRejection = nullptr,
int timeoutMs = kExchangeMs)
{
if (explicitRejection)
*explicitRejection = false;
QByteArray raw;
return exchange(command, payload, &raw, error, possiblySent, timeoutMs)
&& parseObject(raw, object, error)
&& controllerSucceeded(*object, requireCode, error, explicitRejection);
}
private:
bool checkDeadline(const QElapsedTimer &timer, int timeoutMs, QString *error)
{
if (canceled(m_cancelCheck)) {
*error = QStringLiteral("AGV 地图操作已取消");
return false;
}
if (timer.elapsed() >= timeoutMs) {
*error = QStringLiteral("AGV TCP %1:%2 等待超时").arg(m_host).arg(m_port);
return false;
}
return true;
}
bool waitSpacing(QString *error)
{
while (m_lastRequest.isValid() && m_lastRequest.elapsed() < kPortIntervalMs) {
if (canceled(m_cancelCheck)) {
*error = QStringLiteral("AGV 地图操作已取消,尚未发送请求");
return false;
}
QThread::msleep(kSliceMs);
}
if (canceled(m_cancelCheck)) {
*error = QStringLiteral("AGV 地图操作已取消,尚未发送请求");
return false;
}
return true;
}
bool connect(QString *error)
{
if (m_socket.state() == QAbstractSocket::ConnectedState)
return true;
if (canceled(m_cancelCheck)) {
*error = QStringLiteral("AGV 地图操作已取消,尚未连接车辆");
return false;
}
// A short waitForConnected() can end the connection attempt on some
// Qt/Windows versions. Keep one bounded attempt alive while polling
// cancellation in this worker's local event loop instead.
QEventLoop loop;
QTimer tick;
tick.setInterval(kSliceMs);
QElapsedTimer timer;
timer.start();
QObject::connect(&tick, &QTimer::timeout, &loop, [&]() {
if (!checkDeadline(timer, kConnectMs, error)) {
m_socket.abort();
loop.quit();
}
});
QObject::connect(&m_socket, &QTcpSocket::connected, &loop, &QEventLoop::quit);
QObject::connect(&m_socket,
QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
&loop, &QEventLoop::quit);
m_socket.connectToHost(m_host, m_port);
if (m_socket.state() != QAbstractSocket::ConnectedState
&& m_socket.state() != QAbstractSocket::UnconnectedState) {
tick.start();
loop.exec();
}
tick.stop();
if (m_socket.state() == QAbstractSocket::ConnectedState)
return checkDeadline(timer, kConnectMs, error);
if (error->isEmpty())
*error = QStringLiteral("无法连接 AGV TCP %1:%2:%3")
.arg(m_host).arg(m_port).arg(m_socket.errorString());
return false;
}
bool writeBytes(const QByteArray &bytes, const QElapsedTimer &timer,
int timeoutMs, QString *error, bool *possiblySent)
{
int offset = 0;
while (offset < bytes.size()) {
if (!checkDeadline(timer, timeoutMs, error))
return false;
const qint64 written = m_socket.write(bytes.constData() + offset,
std::min(65536, bytes.size() - offset));
if (written <= 0) {
*error = QStringLiteral("SEER TCP 写入失败:%1").arg(m_socket.errorString());
return false;
}
// Queuing any part of the frame can transmit it asynchronously.
// Conservatively mark the outcome unknown on any later failure.
if (possiblySent)
*possiblySent = true;
offset += int(written);
while (m_socket.bytesToWrite() > 0) {
if (!checkDeadline(timer, timeoutMs, error))
return false;
m_socket.waitForBytesWritten(kSliceMs);
if (m_socket.state() != QAbstractSocket::ConnectedState) {
*error = QStringLiteral("SEER TCP 写入时断开:%1").arg(m_socket.errorString());
return false;
}
}
}
return true;
}
bool readBytes(int size, QByteArray *bytes, const QElapsedTimer &timer,
int timeoutMs, QString *error)
{
bytes->clear();
bytes->reserve(size);
while (bytes->size() < size) {
if (!checkDeadline(timer, timeoutMs, error))
return false;
if (m_socket.bytesAvailable() > 0) {
const QByteArray next = m_socket.read(std::min(65536, size - bytes->size()));
if (!next.isEmpty()) {
bytes->append(next);
continue;
}
}
if (m_socket.state() != QAbstractSocket::ConnectedState) {
*error = QStringLiteral("SEER TCP 回包未收全,连接已断开:%1")
.arg(m_socket.errorString());
return false;
}
m_socket.waitForReadyRead(kSliceMs);
}
return true;
}
QString m_host;
quint16 m_port;
const SeerAgvMapClient::CancelCheck &m_cancelCheck;
QTcpSocket m_socket;
QElapsedTimer m_lastRequest;
};
bool stationaryAndIdle(Channel &status, QString *error)
{
QJsonObject speed;
if (!status.query(1005, QByteArray(), &speed, error))
return false;
for (const QString &field : {QStringLiteral("vx"), QStringLiteral("vy"), QStringLiteral("w")}) {
const QJsonValue value = speed.value(field);
if (!value.isDouble() || !std::isfinite(value.toDouble())) {
*error = QStringLiteral("无法确认车辆静止:速度字段 %1 缺失或无效").arg(field);
return false;
}
if (std::abs(value.toDouble()) > kStationaryTolerance) {
*error = QStringLiteral("车辆正在运动,未发送地图修改请求");
return false;
}
}
QJsonObject task;
if (!status.query(1020, QByteArray(), &task, error))
return false;
int taskStatus = -1;
if (!integerMember(task, QStringLiteral("task_status"), &taskStatus)
|| (taskStatus != 0 && taskStatus != 4 && taskStatus != 5 && taskStatus != 6)) {
*error = QStringLiteral("车辆存在等待、运行、暂停任务或任务状态未知,未发送地图修改请求");
return false;
}
return true;
}
bool acquire(Channel &config, const QString &nickName, QString *error)
{
QJsonObject payload;
payload.insert(QStringLiteral("nick_name"), nickName);
QJsonObject response;
return config.query(4005, QJsonDocument(payload).toJson(QJsonDocument::Compact),
&response, error, true);
}
void uncertainDetail(SeerAgvMapResult *result)
{
if (result->uncertain)
result->detail += QStringLiteral(";请求可能已送达,结果未确认,请先读取车端状态后再操作,不会自动重发");
}
} // namespace
SeerAgvMapResult SeerAgvMapClient::readMap(const SeerAgvMapConnection &connection,
const QString &mapName,
const CancelCheck &cancelCheck)
{
SeerAgvMapResult result;
if (!validateRequest(connection, mapName, false, &result.detail))
return result;
Channel config(connection.host, connection.configPort, cancelCheck);
QByteArray raw;
if (!config.exchange(4011, mapRequest(mapName), &raw, &result.detail,
nullptr, kMapExchangeMs))
return result;
QJsonObject object;
if (!parseObject(raw, &object, &result.detail)
|| !controllerSucceeded(object, false, &result.detail)
|| !validateMap(raw, mapName, &result.detail))
return result;
result.success = true;
result.content = QString::fromUtf8(raw);
result.detail = QStringLiteral("已从车辆读取完整地图 %1").arg(mapName);
return result;
}
SeerAgvMapResult SeerAgvMapClient::saveMap(const SeerAgvMapConnection &connection,
const QString &mapName,
const QString &rawContent,
const CancelCheck &cancelCheck)
{
SeerAgvMapResult result;
const QByteArray raw = rawContent.toUtf8();
if (!validateRequest(connection, mapName, true, &result.detail)
|| !validateMap(raw, mapName, &result.detail))
return result;
Channel status(connection.host, connection.statusPort, cancelCheck);
Channel config(connection.host, connection.configPort, cancelCheck);
if (!stationaryAndIdle(status, &result.detail)
|| !acquire(config, connection.nickName, &result.detail)
|| !stationaryAndIdle(status, &result.detail))
return result;
QJsonObject response;
bool possiblySent = false;
bool rejected = false;
// Transmit the original UTF-8 document, including its top-level header.
// The parsing above only validates it; it never reserializes map numbers,
// scan points, unknown fields, whitespace, or station/route content.
if (!config.query(4010, raw, &response, &result.detail, true,
&possiblySent, &rejected, kMapExchangeMs)) {
result.uncertain = possiblySent && !rejected;
uncertainDetail(&result);
return result;
}
result.accepted = true;
result.success = true;
result.detail = QStringLiteral("车辆已确认保存地图 %1").arg(mapName);
return result;
}
SeerAgvMapResult SeerAgvMapClient::switchMap(const SeerAgvMapConnection &connection,
const QString &mapName,
const CancelCheck &cancelCheck)
{
SeerAgvMapResult result;
if (!validateRequest(connection, mapName, true, &result.detail))
return result;
Channel status(connection.host, connection.statusPort, cancelCheck);
Channel config(connection.host, connection.configPort, cancelCheck);
Channel control(connection.host, connection.controlPort, cancelCheck);
// Establish the control channel before the final status check, so a slow
// connection cannot age the stationary/idle preflight before the write.
if (!control.open(&result.detail)
|| !stationaryAndIdle(status, &result.detail)
|| !acquire(config, connection.nickName, &result.detail)
|| !stationaryAndIdle(status, &result.detail))
return result;
QJsonObject response;
bool possiblySent = false;
bool rejected = false;
if (!control.query(2022, mapRequest(mapName), &response, &result.detail, true,
&possiblySent, &rejected)) {
result.uncertain = possiblySent && !rejected;
uncertainDetail(&result);
return result;
}
result.accepted = true;
QElapsedTimer confirmation;
confirmation.start();
while (confirmation.elapsed() < kLoadConfirmationMs) {
if (canceled(cancelCheck)) {
result.detail = QStringLiteral("切图请求已接受,确认过程已取消");
result.uncertain = true;
uncertainDetail(&result);
return result;
}
QJsonObject loading;
if (!status.query(1022, QByteArray(), &loading, &result.detail)) {
result.uncertain = true;
uncertainDetail(&result);
return result;
}
int loadStatus = -1;
if (!integerMember(loading, QStringLiteral("loadmap_status"), &loadStatus)
|| loadStatus < 0 || loadStatus > 2) {
result.detail = QStringLiteral("切图请求已接受,但车辆地图加载状态缺失或未知");
result.uncertain = true;
uncertainDetail(&result);
return result;
}
// The existing SEER protocol: 0=failed, 1=success, 2=loading.
// 1004 reports pose; 1300 is the authoritative current_map query.
QJsonObject maps;
if (!status.query(1300, QByteArray(), &maps, &result.detail)) {
result.uncertain = true;
uncertainDetail(&result);
return result;
}
if (!maps.value(QStringLiteral("current_map")).isString()) {
result.detail = QStringLiteral("切图请求已接受,但车辆未返回有效 current_map");
result.uncertain = true;
uncertainDetail(&result);
return result;
}
result.currentMap = maps.value(QStringLiteral("current_map")).toString();
if (loadStatus == 0) {
result.detail = QStringLiteral("车辆报告地图加载失败,当前地图:%1").arg(result.currentMap);
return result;
}
if (loadStatus == 1 && result.currentMap == mapName) {
result.success = true;
result.detail = QStringLiteral("车辆已确认切换到地图 %1").arg(mapName);
return result;
}
}
result.uncertain = true;
result.detail = QStringLiteral("切图请求已接受,等待车辆确认超时,当前地图:%1").arg(result.currentMap);
uncertainDetail(&result);
return result;
}

51
src/seeragvmapclient.h Normal file
View File

@ -0,0 +1,51 @@
#ifndef SEERAGVMAPCLIENT_H
#define SEERAGVMAPCLIENT_H
#include <QString>
#include <QtGlobal>
#include <functional>
struct SeerAgvMapConnection
{
QString host;
quint16 statusPort = 19204;
quint16 controlPort = 19205;
quint16 configPort = 19207;
QString nickName = QStringLiteral("CMVR地图编辑");
};
struct SeerAgvMapResult
{
bool success = false;
// A map write/load acknowledgement was received. Acquiring authority does
// not set this flag, and a load acknowledgement is not load completion.
bool accepted = false;
// The map request may have reached the controller, but its outcome could
// not be established. The caller must not automatically repeat it.
bool uncertain = false;
QString detail;
QString content;
QString currentMap;
};
// Synchronous, map-only client. Call from a worker thread. Each operation owns
// fresh sockets and sends each modifying command at most once. Cancellation
// closes these sockets; it never sends motion, stop, or navigation commands.
class SeerAgvMapClient
{
public:
using CancelCheck = std::function<bool()>;
static SeerAgvMapResult readMap(const SeerAgvMapConnection &connection,
const QString &mapName,
const CancelCheck &cancelCheck = CancelCheck());
static SeerAgvMapResult saveMap(const SeerAgvMapConnection &connection,
const QString &mapName,
const QString &rawContent,
const CancelCheck &cancelCheck = CancelCheck());
static SeerAgvMapResult switchMap(const SeerAgvMapConnection &connection,
const QString &mapName,
const CancelCheck &cancelCheck = CancelCheck());
};
#endif // SEERAGVMAPCLIENT_H

226
tests/agvdemo_map_test.cpp Normal file
View File

@ -0,0 +1,226 @@
#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;
}

View File

@ -0,0 +1,421 @@
#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;
}

View File

@ -0,0 +1,665 @@
#include "agvmapdocument.h"
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <cmath>
#include <limits>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV map test failed: %s", message);
}
const QString camelMap = QString::fromUtf8(R"JSON({
"header": {"mapType":"2D-Map","mapName":"warehouse","resolution":0.05},
"normalPosList": [{"x":1.2,"y":3.4}],
"unknown": {"largeInteger":9007199254740993,"quoted":"[ ] } \\\""},
"advancedPointList": [
{"className":"LandMark","instanceName":"A","pos":{"x":0,"y":0},"custom":9007199254740993},
{"className":"LandMark","instanceName":"B","pos":{"x":3,"y":6}}
],
"advancedCurveList": []
})JSON");
void testPreservationAndBidirectionalRoutes()
{
AgvMapDocument document;
QString error;
require(document.load(camelMap, &error), "load confirmed camelCase format");
require(document.content() == camelMap && !document.isDirty(), "unmodified text is exact");
require(document.addStation("C", 4.0, 7.0, 0.7, &error), "append station");
require(document.addRoute("A-B", "A", "B", true, &error), "append two directed edges");
require(document.isDirty() && document.stationIds().size() == 3, "draft state and station IDs");
const QString saved = document.content();
require(saved.contains("\"largeInteger\":9007199254740993"), "preserve unknown integer precision");
require(saved.contains("\"custom\":9007199254740993"), "preserve existing station fields exactly");
const QJsonObject root = QJsonDocument::fromJson(saved.toUtf8()).object();
require(root.value("normalPosList").toArray().size() == 1, "preserve original map data");
const QJsonArray curves = root.value("advancedCurveList").toArray();
require(curves.size() == 2, "bidirectional creates two edges");
const QJsonObject forward = curves.at(0).toObject();
const QJsonObject reverse = curves.at(1).toObject();
require(forward.value("className") == QStringLiteral("BezierPath"), "use documented route class");
require(forward.value("startPos").toObject().value("instanceName") == QStringLiteral("A"), "forward source");
require(reverse.value("startPos").toObject().value("instanceName") == QStringLiteral("B"), "reverse source");
require(reverse.value("endPos").toObject().value("instanceName") == QStringLiteral("A"), "reverse target");
require(forward.value("controlPos1") == reverse.value("controlPos2"), "reverse control points");
const QVariantList overlays = document.routes();
require(overlays.size() == 2 && overlays.first().toMap().value("draft").toBool(), "draft route overlay");
const QVariantList geometry = overlays.first().toMap().value("points").toList();
require(geometry.size() == 33, "Bezier overlay is sampled");
require(std::abs(geometry.at(16).toMap().value("x").toDouble() - 1.5) < 1e-9,
"straight Bezier midpoint");
document.markSaved();
require(!document.isDirty() && document.content() == saved, "markSaved retains serialized text");
require(!document.routes().first().toMap().value("draft").toBool(), "saved overlay loses draft flag");
require(document.addStation("D", 8, 9, 0, &error), "append after markSaved");
require(QJsonDocument::fromJson(document.content().toUtf8()).isObject(), "second save remains valid JSON");
}
void testRejectionsAreAtomic()
{
AgvMapDocument document;
QString error;
require(!document.addStation("A", 0, 0, 0, &error), "cannot edit unloaded map");
require(document.load(camelMap, &error), "load map for validation");
require(!document.addStation("A", 1, 2, 0, &error), "duplicate station rejected");
require(!document.addStation(" ", 1, 2, 0, &error), "empty station rejected");
require(!document.addStation("C", std::numeric_limits<double>::infinity(), 2, 0, &error), "infinite x rejected");
require(!document.addStation("C", 1, 2, std::numeric_limits<double>::quiet_NaN(), &error), "NaN heading rejected");
require(!document.addRoute("r", "A", "missing", false, &error), "unknown endpoint rejected");
require(!document.addRoute("r", "A", "A", false, &error), "same endpoint rejected");
require(!document.isDirty() && document.content() == camelMap, "failed edits leave map unchanged");
require(document.addStation("r_reverse", 7, 8, 0, &error), "prepare reverse ID collision");
const QString beforeRoute = document.content();
require(!document.addRoute("r", "A", "B", true, &error), "reverse ID collision rejected");
require(document.routes().isEmpty() && document.content() == beforeRoute, "reverse collision is atomic");
require(document.addStation("C", 0, 0, 0, &error), "coincident station is allowed");
require(!document.addRoute("same-position", "A", "C", false, &error), "zero-length route rejected");
}
void testSnakeCaseAndMissingRouteArray()
{
AgvMapDocument document;
QString error;
const QString snakeMap = QStringLiteral(
"{\"header\":{\"map_type\":\"2D-Map\",\"resolution\":0.1},"
"\"advanced_point_list\":[],\"normal_pos_list\":[],\"keep\":\"unchanged\"}");
require(document.load(snakeMap, &error), "load snake_case format");
require(document.addStation("LM1", 1, 2, 0, &error), "first station in empty array");
require(document.addStation("LM2", 3, 4, 0, &error), "second station in empty array");
require(document.addRoute("LM1-LM2", "LM1", "LM2", false, &error), "create previously absent route array");
const QJsonObject root = QJsonDocument::fromJson(document.content().toUtf8()).object();
require(root.value("advanced_point_list").toArray().size() == 2, "snake_case stations serialized");
require(root.value("advanced_curve_list").toArray().size() == 1, "snake_case routes serialized");
require(!root.contains("advancedCurveList"), "original naming convention preserved");
require(root.value("advanced_curve_list").toArray().first().toObject().contains("start_pos"), "snake_case endpoint");
AgvMapDocument reread;
require(reread.load(document.content(), &error), "reload appended map");
require(reread.hasStation("LM1") && reread.routes().size() == 1, "reload overlays");
document.clear();
require(document.content().isEmpty() && document.stationIds().isEmpty() && !document.isDirty(), "clear all state");
}
void testUnsupportedFormats()
{
AgvMapDocument document;
QString error;
require(!document.load("{}", &error), "unknown JSON rejected");
require(!document.load("PK\\x03\\x04", &error), "binary archive rejected");
require(!document.load("{\"header\":{\"mapType\":\"3D-Map\",\"resolution\":0.1},\"advancedPointList\":[]}", &error), "3D map rejected");
require(!document.load("{\"header\":{\"resolution\":0.1},\"advancedPointList\":[],\"advanced_point_list\":[]}", &error), "mixed field names rejected");
require(!document.load("{\"header\":{\"resolution\":0.1},\"advancedPointList\":[],\"advancedPointList\":[]}", &error), "duplicate top-level array rejected");
}
void testIdentifierCompatibility()
{
AgvMapDocument document;
QString error;
require(document.load(camelMap, &error), "load identifier test map");
require(document.addStation(QStringLiteral("充电站"), 1, 2, 0, &error), "Chinese station ID is valid");
require(document.addRoute(QStringLiteral("回家路线"), QStringLiteral("充电站"), "A", false, &error),
"Chinese route and endpoint IDs are valid");
const QString before = document.content();
require(!document.addStation("A,B", 3, 4, 0, &error), "comma station ID rejected");
require(!document.addStation("new\nstation", 3, 4, 0, &error), "newline station ID rejected");
require(!document.addStation("new\tstation", 3, 4, 0, &error), "control character station ID rejected");
require(!document.addRoute("route,1", "A", "B", false, &error), "comma route ID rejected");
require(document.content() == before, "invalid IDs do not change content");
QString legacyMap = camelMap;
legacyMap.replace(QStringLiteral("\"instanceName\":\"A\""),
QStringLiteral("\"instanceName\":\"A,legacy\""));
require(document.load(legacyMap, &error), "legacy delimiter ID is preserved when loading");
require(!document.addRoute("legacy", "A,legacy", "B", false, &error),
"cannot create a new path using an unrepresentable endpoint ID");
}
void testStationNumericIdentifiers()
{
AgvMapDocument document;
QString error;
require(document.nextAvailableStationId().isEmpty(), "unloaded document has no station suggestion");
QString source = camelMap;
source.replace(QStringLiteral("\"instanceName\":\"A\""), QStringLiteral("\"instanceName\":\"LM1\""));
source.replace(QStringLiteral("\"instanceName\":\"B\""), QStringLiteral("\"instanceName\":\"CP0002\""));
require(document.load(source, &error) && document.validateStationIds(&error),
"different numeric station IDs are valid");
require(document.nextAvailableStationId() == QStringLiteral("LM3"),
"default ID skips occupied numbers across all prefixes and leading zeroes");
for (const QString &id : {QStringLiteral("STATION_1"), QStringLiteral("LM01"),
QStringLiteral("0001"), QStringLiteral("LM2")}) {
require(!document.addStation(id, 4, 5, 0, &error), "numeric collision rejected before mutation");
require(error.contains(id) && error.contains(QStringLiteral("数字编号")),
"numeric rejection identifies the new ID and explains the conflict");
require(!document.isDirty() && document.content() == source,
"rejected numeric collision preserves clean content exactly");
}
require(document.addStation(document.nextAvailableStationId(), 4, 5, 0, &error,
QStringLiteral("装卸站一")), "suggested station ID is available");
const QString dirtySource = document.content();
require(!document.addStation("CUSTOM_0003", 5, 6, 0, &error)
&& document.isDirty() && document.content() == dirtySource,
"numeric collision also preserves an existing dirty draft");
require(document.addStation("zone1a", 5, 6, 0, &error),
"legacy nonnumeric IDs remain supported");
require(document.addRoute("CUSTOM_4", "LM1", "LM3", false, &error)
&& document.addStation("LM4", 6, 7, 0, &error),
"route numeric suffixes do not reserve station numbers");
require(document.addRoute("LM5", "LM1", "LM3", false, &error)
&& document.nextAvailableStationId() == QStringLiteral("LM6"),
"default station still avoids an exact route identifier collision");
require(document.validateStationIds(&error), "valid additions keep station numeric IDs unique");
AgvMapDocument latest;
require(latest.load(document.content(), &error)
&& !latest.addStation("STATION_3", 7, 8, 0, &error)
&& !latest.isDirty(),
"save merge rechecks a newly occupied numeric ID in the latest downloaded map");
QString badSource = source;
badSource.replace(QStringLiteral("CP0002"), QStringLiteral("STATION_1"));
require(document.load(badSource, &error), "existing numeric collision remains readable for diagnosis");
require(!document.validateStationIds(&error) && error.contains(QStringLiteral("LM1"))
&& error.contains(QStringLiteral("STATION_1"))
&& document.content() == badSource && !document.isDirty(),
"validation reports both existing colliding IDs without renaming or dirtying the map");
require(document.nextAvailableStationId() == QStringLiteral("LM2"),
"default allocation skips the shared number even in an existing bad map");
require(document.load(camelMap, &error), "load numeric overflow test map");
const QString huge = QStringLiteral("18446744073709551616000000000000000001");
require(document.addStation(QStringLiteral("LM") + huge, 1, 2, 0, &error),
"large numeric suffix is preserved without integer conversion");
const QString hugeSource = document.content();
require(!document.addStation(QStringLiteral("STATION_000") + huge, 2, 3, 0, &error)
&& document.content() == hugeSource,
"large numeric collision with leading zeroes is detected without overflow");
require(document.addStation(QStringLiteral("CP18446744073709551616000000000000000002"), 2, 3, 0, &error)
&& document.validateStationIds(&error), "different huge numbers are not conflated");
require(document.addStation("LM0", 3, 4, 0, &error), "zero numeric station ID remains compatible");
require(!document.addStation("CP000", 4, 5, 0, &error), "all-zero suffixes normalize to the same zero");
require(document.nextAvailableStationId() == QStringLiteral("LM1"),
"huge numeric IDs and zero do not overflow or block small available numbers");
require(document.load(camelMap, &error), "load reported map ID allocation reproduction");
for (int number = 1; number <= 11; ++number) {
const QString id = (number == 5 ? QStringLiteral("CP") : QStringLiteral("LM"))
+ QString::number(number);
require(document.addStation(id, number, 1, 0, &error), "prepare existing LM1-11 with CP5");
}
require(document.nextAvailableStationId() == QStringLiteral("LM12"),
"reported map reserves CP5 and offers LM12 rather than conflicting STATION_1");
require(!document.addStation("STATION_01", 12, 1, 0, &error),
"reported leading-zero alternative cannot reuse LM1's numeric ID");
}
QVariantMap stationOverlay(const AgvMapDocument &document, const QString &id)
{
for (const QVariant &value : document.stations()) {
if (value.toMap().value("id").toString() == id)
return value.toMap();
}
return {};
}
void testStationNames()
{
AgvMapDocument document;
QString error;
require(!document.setStationName("A", "name", &error), "unloaded rename rejected");
require(document.load(camelMap, &error), "load station names map");
const QVariantMap initial = stationOverlay(document, "A");
require(initial.value("name") == QStringLiteral("A")
&& initial.value("description").toString().isEmpty()
&& initial.value("originalName").toString().isEmpty()
&& !initial.value("nameChanged").toBool(), "missing description falls back only for display");
require(document.setStationName("A", QStringLiteral("装卸站一"), &error), "name existing station without description");
require(document.isDirty(), "rename alone is dirty");
require(stationOverlay(document, "A").value("nameChanged").toBool()
&& stationOverlay(document, "A").value("originalName").toString().isEmpty(),
"rename tracks empty original description");
QString expected = camelMap;
expected.replace(QStringLiteral("\"custom\":9007199254740993}"),
QStringLiteral("\"custom\":9007199254740993,\"description\":\"装卸站一\"}"));
require(document.content() == expected, "rename appends only description preserving complete original text");
require(document.setStationName("A", QStringLiteral("装卸站二"), &error), "repeat rename");
require(stationOverlay(document, "A").value("originalName").toString().isEmpty(),
"repeat rename retains first original name");
require(document.setStationName("A", QString(), &error), "restore absent description");
require(!document.isDirty() && document.content() == camelMap
&& !stationOverlay(document, "A").value("nameChanged").toBool(),
"rename back removes pending change and restores absent field exactly");
require(document.addStation("C", 4, 5, 0, &error, QStringLiteral("充电站, 一号")), "new Chinese display name with comma");
require(stationOverlay(document, "C").value("name") == QStringLiteral("充电站, 一号")
&& stationOverlay(document, "C").value("draft").toBool()
&& !stationOverlay(document, "C").value("nameChanged").toBool(),
"draft station name stays separate from identifier");
require(document.setStationName("C", QStringLiteral("充电站二"), &error), "rename draft station");
require(document.setStationName("A", QStringLiteral("装卸站一"), &error), "rename while additions pending");
require(document.addRoute("A-C", "A", "C", false, &error), "route endpoints continue using IDs");
const QString saved = document.content();
const QJsonObject savedRoot = QJsonDocument::fromJson(saved.toUtf8()).object();
const QJsonArray stations = savedRoot.value("advancedPointList").toArray();
require(stations.at(2).toObject().value("description") == QStringLiteral("充电站二"),
"draft rename persists final description");
require(savedRoot.value("advancedCurveList").toArray().first().toObject()
.value("startPos").toObject().value("instanceName") == QStringLiteral("A"),
"display name does not alter route identity");
require(saved.contains("\"custom\":9007199254740993")
&& saved.contains("\"largeInteger\":9007199254740993"),
"combined rename/additions preserve raw integers");
document.markSaved();
const QVariantMap savedA = stationOverlay(document, "A");
require(!document.isDirty() && document.content() == saved
&& savedA.value("originalName") == QStringLiteral("装卸站一")
&& !savedA.value("nameChanged").toBool()
&& !stationOverlay(document, "C").value("draft").toBool(),
"markSaved updates name base and clears draft flags");
require(document.setStationName("A", QStringLiteral("装卸站三"), &error), "rename after save");
require(stationOverlay(document, "A").value("originalName") == QStringLiteral("装卸站一"),
"subsequent rename compares saved base");
require(document.setStationName("A", QStringLiteral("装卸站一"), &error), "restore saved name");
require(!document.isDirty() && document.content() == saved, "restore saved name restores exact text");
require(!document.setStationName("missing", "name", &error) && !document.isDirty(),
"missing station rename is atomic");
document.clear();
require(document.stations().isEmpty() && !document.isDirty(), "clear removes names and changes");
}
void testStationNameTokenPreservation()
{
const QString source = QString::fromUtf8(R"JSON({
"header":{"resolution":0.05}, "advanced_point_list":[
{"instance_name":"A", "pos":{"x":1,"y":2}, "opaque":{"description":"nested","big":18446744073709551615}, "descr\u0069ption" : "旧名称", "tail":["} ]",9007199254740993]},
{"instance_name":"B", "description":"", "pos":{"x":3,"y":4}}
], "unknown":9007199254740993
})JSON");
AgvMapDocument document;
QString error;
require(document.load(source, &error), "load escaped description key and snake_case stations");
const QString name = QStringLiteral("新\"名称\\仓库\n二楼");
require(document.setStationName("A", name, &error), "rename escaped description field");
require(stationOverlay(document, "A").value("originalName") == QStringLiteral("旧名称"),
"existing string is rename comparison base");
const QByteArray encoded = QJsonDocument(QJsonArray{name}).toJson(QJsonDocument::Compact);
const QString encodedString = QString::fromUtf8(encoded.mid(1, encoded.size() - 2));
QString expected = source;
expected.replace(QStringLiteral("\"旧名称\""), encodedString);
require(document.content() == expected, "replace exactly one JSON value preserving key spelling whitespace and uint64");
AgvMapDocument reread;
require(reread.load(document.content(), &error)
&& stationOverlay(reread, "A").value("name") == name,
"escaped quotes slash newline and Chinese persist");
require(document.setStationName("A", QStringLiteral("再修改"), &error)
&& stationOverlay(document, "A").value("originalName") == QStringLiteral("旧名称"),
"existing name comparison base survives multiple changes");
require(document.setStationName("A", QStringLiteral("旧名称"), &error)
&& !document.isDirty() && document.content() == source,
"restore original string preserves original escape spelling");
require(document.setStationName("B", QStringLiteral("库房B"), &error), "rename explicit empty description");
require(document.setStationName("B", QString(), &error)
&& !document.isDirty() && document.content() == source,
"restore empty description keeps original field");
QString unsupported = source;
unsupported.replace(QStringLiteral("\"description\":\"\""), QStringLiteral("\"description\":{\"unknown\":9007199254740993}"));
require(document.load(unsupported, &error), "preserve station with unknown description type");
require(!document.setStationName("B", "new", &error)
&& !document.isDirty() && document.content() == unsupported,
"unknown description type cannot be silently replaced");
QString duplicate = source;
duplicate.replace(QStringLiteral("\"description\":\"\""), QStringLiteral("\"description\":\"first\",\"description\":\"last\""));
require(document.load(duplicate, &error), "preserve duplicate description map");
require(!document.setStationName("B", "new", &error)
&& !document.isDirty() && document.content() == duplicate,
"ambiguous duplicate descriptions reject rename without altering map");
}
void testDeleteArrayTokenPreservation()
{
const QStringList ids{QStringLiteral("A"), QStringLiteral("B"), QStringLiteral("C"), QStringLiteral("D")};
QStringList stationTokens;
QStringList routeTokens;
for (int index = 0; index < ids.size(); ++index) {
stationTokens.append(QStringLiteral("{\"instanceName\":\"%1\", \"pos\":{\"x\":%2,\"y\":2}, \"opaque\":18446744073709551615}")
.arg(ids.at(index)).arg(index));
routeTokens.append(QStringLiteral("{\"instanceName\":\"R%1\",\"unknown\":[9007199254740993,\"} ] \\\"\"]}")
.arg(index));
}
const QString source = QStringLiteral("{\n \"header\":{\"resolution\":0.05,\"opaque\":18446744073709551615},\n"
" \"advancedPointList\":[\n %1\n ],\n \"advancedCurveList\":[\n %2\n ],\n"
" \"normalPosList\":[{\"x\":9007199254740993}],\"unknown\":\"keep\\\\raw\"\n}")
.arg(stationTokens.join(QStringLiteral(",\n ")), routeTokens.join(QStringLiteral(",\n ")));
QString error;
for (int mask = 1; mask < 16; ++mask) {
AgvMapDocument document;
require(document.load(source, &error), "load raw array deletion fixture");
int survivors = 4;
for (int index = 0; index < 4; ++index) {
if (mask & (1 << index)) {
require(document.removeStation(ids.at(index), false, &error), "remove original station subset");
require(document.removeRoute(QStringLiteral("R%1").arg(index), &error), "remove original route subset");
--survivors;
}
}
const QString saved = document.content();
const QJsonDocument parsed = QJsonDocument::fromJson(saved.toUtf8());
require(parsed.isObject() && parsed.object().value("advancedPointList").toArray().size() == survivors
&& parsed.object().value("advancedCurveList").toArray().size() == survivors,
"first middle last contiguous disjoint and all deletions keep valid JSON");
require(saved.contains("\"header\":{\"resolution\":0.05,\"opaque\":18446744073709551615}")
&& saved.contains("\"normalPosList\":[{\"x\":9007199254740993}]")
&& saved.contains("\"unknown\":\"keep\\\\raw\""), "deletions preserve header scan and unknown raw tokens");
for (int index = 0; index < 4; ++index) {
require(saved.contains(stationTokens.at(index)) == !(mask & (1 << index))
&& saved.contains(routeTokens.at(index)) == !(mask & (1 << index)),
"every untouched object remains byte-for-byte and only deleted objects disappear");
}
require(document.addStation("NEW", 8, 9, 0, &error)
&& document.addRoute("NEW-R", "NEW", mask == 15 ? "missing" : document.stationIds().first(), false, &error) == (mask != 15),
"append after removals uses remaining station topology");
AgvMapDocument reread;
require(reread.load(document.content(), &error) && reread.hasStation("NEW"),
"append commas account for all original elements deleted");
}
}
void testDeleteDraftsAndIdentifierReservations()
{
QString error;
AgvMapDocument document;
require(document.load(camelMap, &error) && document.addStation("LM1", 8, 9, 0, &error)
&& document.addRoute("A-LM1", "A", "LM1", true, &error), "prepare draft station and bidirectional routes");
const AgvMapDocument undo = document;
const QString before = document.content();
require(!document.removeStation("LM1", false, &error) && document.content() == before,
"connected station rejection is atomic");
require(document.connectedRouteIds("LM1").size() == 2
&& document.removeStation("LM1", true, &error), "explicit cascade removes both directed draft routes");
require(!document.isDirty() && document.content() == camelMap
&& document.removedStationIds().isEmpty() && document.removedRouteIds().isEmpty(),
"new station then delete cancels additions and returns clean original text");
document = undo;
require(document.isDirty() && document.content() == before && document.hasStation("LM1")
&& document.routes().size() == 2, "document copy restores cascade in one undo step");
document.markSaved();
require(document.removeRoute("A-LM1", &error) && document.routes().size() == 1
&& document.removedRouteIds() == QStringList{QStringLiteral("A-LM1")},
"delete selected directed route leaves its reverse intact");
require(!document.addRoute("A-LM1", "A", "LM1", false, &error), "pending removed route ID cannot be reused");
require(document.removeStation("LM1", true, &error)
&& document.removedStationIds() == QStringList{QStringLiteral("LM1")}
&& !document.addStation("LM1", 1, 2, 0, &error)
&& !document.addStation("STATION_01", 1, 2, 0, &error)
&& document.nextAvailableStationId() == QStringLiteral("LM2"),
"pending removed station reserves textual ID and numeric suffix");
document.markSaved();
require(!document.isDirty() && document.removedStationIds().isEmpty() && document.removedRouteIds().isEmpty()
&& document.nextAvailableStationId() == QStringLiteral("LM1"), "confirmed save resets tombstones and ID reservation");
require(!document.removeRoute("missing", &error) && !document.removeStation("missing", true, &error)
&& !document.isDirty(), "missing delete leaves document clean");
require(document.load(camelMap, &error) && document.setStationName("A", "keep this rename", &error)
&& document.removeStation("B", false, &error), "combine surviving rename with trailing station deletion");
AgvMapDocument combined;
require(combined.load(document.content(), &error) && combined.stationIds().size() == 1
&& stationOverlay(combined, "A").value("description") == QStringLiteral("keep this rename")
&& document.content().contains("\"custom\":9007199254740993"),
"name insertion on preceding retained object does not overlap trailing deletion range");
require(document.removeStation("A", false, &error)
&& QJsonDocument::fromJson(document.content().toUtf8()).object().value("advancedPointList").toArray().isEmpty(),
"deleting locally renamed object removes its name edit and leaves valid empty array");
}
void testDeleteMergeConflictsAndConfirmation()
{
QString error;
AgvMapDocument base;
require(base.load(camelMap, &error) && base.addRoute("A-B", "A", "B", true, &error), "prepare persisted map with directed routes");
base.markSaved();
const QString original = base.content();
AgvMapDocument local = base;
require(local.setStationName("A", "local rename before delete", &error)
&& local.removeStation("A", true, &error), "rename then delete existing station");
AgvMapDocument latest;
require(latest.load(original, &error) && local.mergeRemovalsInto(&latest, &error)
&& !latest.hasStation("A") && latest.routes().isEmpty(),
"delete conflict comparison uses original station before local rename");
AgvMapDocument readback;
require(readback.load(latest.content(), &error) && local.verifyRemovals(readback, &error),
"readback confirms station routes and references absent");
require(local.mergeRemovalsInto(&readback, &error), "already absent objects allow idempotent retry");
require(!local.verifyRemovals(base, &error), "upload acknowledgement cannot confirm absent delete in stale map");
QString externallyChanged = original;
externallyChanged.replace("\"custom\":9007199254740993", "\"custom\":9007199254740992");
require(latest.load(externallyChanged, &error), "load externally changed uint64-like token");
const QString untouched = latest.content();
require(!local.mergeRemovalsInto(&latest, &error) && latest.content() == untouched && !latest.isDirty(),
"external change lost by double conversion blocks delete atomically");
require(latest.load(original, &error) && latest.addStation("C", 8, 9, 0, &error)
&& latest.addRoute("A-C", "A", "C", false, &error), "prepare external new reference");
latest.markSaved();
const QString withExternalRoute = latest.content();
require(!local.mergeRemovalsInto(&latest, &error) && latest.content() == withExternalRoute,
"new external connected route blocks cascade rather than being silently removed");
require(latest.load(original, &error) && latest.setStationName("B", "external unrelated edit", &error),
"prepare unrelated concurrent station rename");
latest.markSaved();
require(local.mergeRemovalsInto(&latest, &error)
&& stationOverlay(latest, "B").value("description") == QStringLiteral("external unrelated edit"),
"delete merge preserves unrelated concurrent changes");
QString reordered = original;
reordered.replace("{\"className\":\"LandMark\",\"instanceName\":\"A\",\"pos\":{\"x\":0,\"y\":0},\"custom\":9007199254740993}",
"{ \"custom\":9007199254740993,\"pos\":{\"y\":0,\"x\":0},\"instanceName\":\"A\",\"className\":\"LandMark\" }");
require(reordered != original && latest.load(reordered, &error) && local.mergeRemovalsInto(&latest, &error),
"complete original-object comparison accepts whitespace and object key reordering");
QString dangling = readback.content();
dangling.replace("\"advancedCurveList\":", "\"advancedCurveList\":");
QJsonObject danglingRoot = QJsonDocument::fromJson(dangling.toUtf8()).object();
danglingRoot.insert("advancedCurveList", QJsonArray{QJsonObject{{"instanceName", "new-dangling"},
{"startPos", QJsonObject{{"instanceName", "A"}}}, {"endPos", QJsonObject{{"instanceName", "B"}}}}});
require(latest.load(QString::fromUtf8(QJsonDocument(danglingRoot).toJson()), &error)
&& !local.verifyRemovals(latest, &error), "confirmation rejects new dangling reference to deleted station");
AgvMapDocument routeOnly = base;
require(routeOnly.removeRoute("A-B", &error), "prepare route-only deletion");
QString changedRoute = original;
changedRoute.replace("\"instanceName\":\"A-B\"", "\"changedExternal\":true,\"instanceName\":\"A-B\"");
require(latest.load(changedRoute, &error) && !routeOnly.mergeRemovalsInto(&latest, &error),
"external unknown route property change blocks deletion");
QString duplicateRoute = original;
const QJsonArray originalRoutes = QJsonDocument::fromJson(original.toUtf8()).object().value("advancedCurveList").toArray();
const QString duplicateToken = QString::fromUtf8(QJsonDocument(originalRoutes.first().toObject()).toJson(QJsonDocument::Compact));
const int curveClose = duplicateRoute.lastIndexOf(QLatin1Char(']'));
duplicateRoute.insert(curveClose, QLatin1Char(',') + duplicateToken);
require(latest.load(duplicateRoute, &error), "ambiguous legacy route identifiers remain readable");
const QString duplicateBefore = latest.content();
require(!latest.removeRoute("A-B", &error) && !latest.removeStation("A", true, &error)
&& latest.content() == duplicateBefore && !latest.isDirty(),
"ambiguous route deletion and cascades reject atomically");
AgvMapDocument empty;
require(empty.mergeRemovalsInto(nullptr, &error) && empty.verifyRemovals(empty, &error),
"no tombstones have zero-cost no-op merge and verify");
}
QString valueToken(const QString &source, const QString &key)
{
const QString encodedKey = QString::fromUtf8(QJsonDocument(QJsonArray{key})
.toJson(QJsonDocument::Compact));
const QString keyToken = encodedKey.mid(1, encodedKey.size() - 2);
int start = source.indexOf(keyToken + QLatin1Char(':'));
require(start >= 0, "native fixture contains requested root field token");
start += keyToken.size() + 1;
while (start < source.size() && source.at(start).isSpace())
++start;
require(source.at(start) == QLatin1Char('{') || source.at(start) == QLatin1Char('['),
"native root token is an object or array");
int depth = 0;
bool quoted = false;
for (int index = start; index < source.size(); ++index) {
const QChar character = source.at(index);
if (quoted) {
if (character == QLatin1Char('\\'))
++index;
else if (character == QLatin1Char('"'))
quoted = false;
} else if (character == QLatin1Char('"')) {
quoted = true;
} else if (character == QLatin1Char('{') || character == QLatin1Char('[')) {
++depth;
} else if (character == QLatin1Char('}') || character == QLatin1Char(']')) {
if (--depth == 0)
return source.mid(start, index - start + 1);
}
}
qFatal("AGV map test failed: native root token is not balanced");
return QString();
}
QString testNativeFullMapUploadContent(const QString &original)
{
// Add an unknown uint64 token to this LOCAL fixture to catch lossy full-root
// reserialization; no network client or vehicle write is used by this test.
QString source = original;
source.insert(source.lastIndexOf(QLatin1Char('}')),
QStringLiteral(",\"uploadUnknown\":{\"uint64\":18446744073709551615,\"opaque\":\"keep\\\\raw\\\"text\"}"));
const QJsonObject originalRoot = QJsonDocument::fromJson(source.toUtf8()).object();
require(originalRoot.value("header").isObject()
&& originalRoot.value("normalPosList").isArray()
&& !originalRoot.value("advancedPointList").toArray().isEmpty(),
"real-format fixture has root header, camel scan and stations");
const QString headerToken = valueToken(source, "header");
const QString scanToken = valueToken(source, "normalPosList");
const QString unknownToken = valueToken(source, "uploadUnknown");
const QString lineToken = valueToken(source, "advancedLineList");
const QString originalCurveToken = valueToken(source, "advancedCurveList");
const QJsonArray oldStations = originalRoot.value("advancedPointList").toArray();
const QJsonArray oldRoutes = originalRoot.value("advancedCurveList").toArray();
const QString originalId = oldStations.first().toObject().value("instanceName").toString();
const QString literalName = QStringLiteral("\"离线保存测试\"\\路径\n二楼");
AgvMapDocument document;
QString error;
require(document.load(source, &error) && document.content() == source,
"downloaded native map starts as exact original text");
require(document.setStationName(originalId, literalName, &error)
&& document.addStation("LOCAL_UPLOAD_TEST", 1.25, 0.5, 0.3, &error,
QStringLiteral("本地测试站"))
&& document.addRoute("LOCAL_UPLOAD_ROUTE", originalId, "LOCAL_UPLOAD_TEST", true, &error),
"native map supports combined existing-name edits, new station and bidirectional routes");
const QString content = document.content();
const QByteArray bytes = content.toUtf8();
const QJsonDocument upload = QJsonDocument::fromJson(bytes);
require(bytes.trimmed().startsWith('{') && bytes.trimmed().endsWith('}') && upload.isObject(),
"upload is one JSON object, never a quoted JSON string or wrapper");
const QJsonObject root = upload.object();
require(root.value("header") == originalRoot.value("header")
&& content.contains(headerToken),
"complete native header remains at root and is preserved byte-for-byte");
require(root.value("normalPosList") == originalRoot.value("normalPosList")
&& content.contains(scanToken), "all native scan samples and zero-value omissions retain exact text");
require(root.value("advancedLineList") == originalRoot.value("advancedLineList")
&& content.contains(lineToken) && content.contains(unknownToken)
&& content.contains("18446744073709551615"),
"advanced lines and unknown fields retain exact tokens including uint64 precision");
require(!root.contains("advanced_point_list") && !root.contains("advanced_curve_list")
&& !root.contains("content") && !root.contains("map")
&& root.value("advancedPointList").toArray().size() == oldStations.size() + 1
&& root.value("advancedCurveList").toArray().size() == oldRoutes.size() + 2,
"native camel arrays are extended without extra envelopes or snake fields");
const QJsonArray savedStations = root.value("advancedPointList").toArray();
for (int index = 0; index < oldStations.size(); ++index) {
QJsonObject expected = oldStations.at(index).toObject();
if (index == 0)
expected.insert("description", literalName);
require(savedStations.at(index).toObject() == expected,
"existing native station fields change only the explicitly edited description");
}
const QJsonObject added = savedStations.last().toObject();
require(added.value("className") == QStringLiteral("LandMark")
&& added.value("instanceName") == QStringLiteral("LOCAL_UPLOAD_TEST")
&& added.value("property").toArray().first().toObject().contains("boolValue"),
"new station follows the documented camel SMAP form");
const QJsonArray savedRoutes = root.value("advancedCurveList").toArray();
for (int index = 0; index < oldRoutes.size(); ++index)
require(savedRoutes.at(index) == oldRoutes.at(index), "all existing native routes remain unchanged");
require(valueToken(content, "advancedCurveList").startsWith(
originalCurveToken.left(originalCurveToken.size() - 1)),
"existing route tokens are retained verbatim before appended routes");
const QJsonObject newRoute = savedRoutes.at(oldRoutes.size()).toObject();
require(newRoute.value("className") == QStringLiteral("BezierPath")
&& newRoute.value("startPos").toObject().value("instanceName") == originalId
&& newRoute.value("endPos").toObject().value("instanceName") == QStringLiteral("LOCAL_UPLOAD_TEST")
&& newRoute.value("property").toArray().first().toObject().contains("int32Value"),
"new route uses documented camel references and property values");
AgvMapDocument reread;
require(reread.load(content, &error) && reread.hasStation("LOCAL_UPLOAD_TEST")
&& stationOverlay(reread, originalId).value("name") == literalName,
"complete upload text reloads with literal escaped name and additions");
document.markSaved();
require(!document.isDirty() && document.content() == content, "markSaved keeps exact complete native upload payload");
qInfo() << "PASS native SMAP local payload:" << bytes.size() << "bytes; root header and"
<< originalRoot.value("normalPosList").toArray().size() << "scan samples preserved";
return content;
}
void testNativeMapSerialization()
{
const QString source = QStringLiteral(R"JSON({"advancedCurveList":[{"className":"DegenerateBezier","instanceName":"LM1-LM2","startPos":{"instanceName":"LM1","pos":{"x":0.294,"y":-0.17}},"endPos":{"instanceName":"LM2","pos":{"x":5.201,"y":-0.054}},"controlPos1":{"x":1.93,"y":-0.131},"controlPos2":{"x":3.565,"y":-0.093}}],"advancedLineList":[{"className":"AdvancedLine","instanceName":"L1","startPos":{"x":1,"y":2},"endPos":{"x":3,"y":4}}],"advancedPointList":[{"className":"LocationMark","ignoreDir":true,"instanceName":"LM1","pos":{"x":0.294,"y":-0.17},"property":[{"boolValue":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"className":"LocationMark","ignoreDir":true,"instanceName":"LM2","pos":{"x":5.201,"y":-0.054}}],"header":{"mapName":"20260918102324025","mapType":"2D-Map","maxPos":{"x":8.206,"y":13.428},"minPos":{"x":-2.32,"y":-2.757},"resolution":0.02,"version":"1.0.6"},"normalPosList":[{"x":-2.32,"y":-2.757},{"y":0.5},{"x":8.206,"y":13.428}]})JSON");
testNativeFullMapUploadContent(source);
}
} // namespace
int main(int argc, char *argv[])
{
QCoreApplication application(argc, argv);
testPreservationAndBidirectionalRoutes();
testRejectionsAreAtomic();
testSnakeCaseAndMissingRouteArray();
testUnsupportedFormats();
testIdentifierCompatibility();
testStationNumericIdentifiers();
testStationNames();
testStationNameTokenPreservation();
testDeleteArrayTokenPreservation();
testDeleteDraftsAndIdentifierReservations();
testDeleteMergeConflictsAndConfirmation();
testNativeMapSerialization();
if (argc > 1) {
QFile fixture(QString::fromLocal8Bit(argv[1]));
require(fixture.open(QIODevice::ReadOnly), "local downloaded real SMAP fixture opens");
const QString content = testNativeFullMapUploadContent(QString::fromUtf8(fixture.readAll()));
if (argc > 2) {
QFile output(QString::fromLocal8Bit(argv[2]));
require(output.open(QIODevice::WriteOnly) && output.write(content.toUtf8()) == content.toUtf8().size(),
"optional local upload payload dump is written without network access");
}
}
qInfo() << "PASS: AGV map document offline tests";
return 0;
}

View File

@ -0,0 +1,503 @@
#include "agvmapdocument.h"
#include "agvmapeditorwidget.h"
#include "agvmapviewwidget.h"
#include "robotclient.h"
#include "cmvr/api/agv_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QApplication>
#include <QDialog>
#include <QElapsedTimer>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QMessageBox>
#include <QPointer>
#include <QPushButton>
#include <QTableWidget>
#include <QTabWidget>
#include <QThread>
#include <QTimer>
#include <QVBoxLayout>
#include <functional>
#include <iostream>
#include <mutex>
#include <vector>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV delete integration failed: %s", message);
}
void waitFor(const std::function<bool()> &ready, const char *message)
{
QElapsedTimer timer;
timer.start();
while (!ready() && timer.elapsed() < 7000) {
QApplication::processEvents();
QThread::msleep(2);
}
require(ready(), message);
}
void nextModal(const QString &kind, const std::function<void(QDialog *)> &action)
{
auto *timer = new QTimer(qApp);
timer->setInterval(5);
QObject::connect(timer, &QTimer::timeout, timer, [=]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (!dialog || dialog->objectName() != kind)
return;
// Stop before an action can enter a nested confirmation event loop.
timer->stop();
timer->deleteLater();
action(dialog);
});
timer->start();
QTimer::singleShot(7000, qApp, [guard = QPointer<QTimer>(timer)]() {
require(!guard || !guard->isActive(), "expected local editor modal opened");
});
}
int rowFor(QTableWidget *table, const QString &id)
{
for (int row = 0; row < table->rowCount(); ++row) {
if (table->item(row, 0)->text() == id)
return row;
}
return -1;
}
bool hasRoute(const AgvMapDocument &document, const QString &id)
{
for (const QVariant &value : document.routes()) {
if (value.toMap().value("id").toString() == id)
return true;
}
return false;
}
QString fixture(const QString &mapName)
{
const QString seed = QStringLiteral(R"JSON({
"header":{"mapType":"2D-Map","mapName":"%1","resolution":0.05,"vendorHeader":"unchanged"},
"normalPosList":[{"x":1.23456789012345,"y":2},{"x":3,"y":4}],
"advancedLineList":[{"instanceName":"do not touch line","customLine":9007199254740993}],
"advancedPointList":[
{"className":"LandMark","instanceName":"LM1","description":"first","pos":{"x":0,"y":0},"vendorPoint":9007199254740993},
{"className":"LandMark","instanceName":"LM2","description":"second","pos":{"x":2,"y":0}},
{"className":"LandMark","instanceName":"LM3","description":"third","pos":{"x":2,"y":2}},
{"className":"LandMark","instanceName":"LM4","description":"fourth","pos":{"x":4,"y":2}}
],
"advancedCurveList":[],
"rootUnknown":{"largeInteger":18446744073709551615,"quoted":"keep [ ] } \\\" exactly"}
})JSON").arg(mapName);
AgvMapDocument document;
QString error;
require(document.load(seed, &error)
&& document.addRoute("LM1_LM2", "LM1", "LM2", true, &error)
&& document.addRoute("LM2_LM3", "LM2", "LM3", true, &error)
&& document.addRoute("LM3_LM4", "LM3", "LM4", true, &error),
"local native map fixture has four points and six directed routes");
QString result = document.content();
result.replace(QStringLiteral("\"instanceName\":\"LM1_LM2\""),
QStringLiteral("\"instanceName\":\"LM1_LM2\",\"vendorRoute\":9007199254740993"));
return result;
}
// The test only starts this service on 127.0.0.1:0. It cannot reach a vehicle.
class FakeAgvService final : public cmvr::api::AgvService::Service
{
public:
enum Result { Persist, AckOnly };
FakeAgvService()
{
m_maps.insert("delete_map", fixture("delete_map"));
m_maps.insert("other_map", fixture("other_map"));
}
grpc::Status downloadMap(grpc::ServerContext *,
const cmvr::api::AgvMapCommand::Request *request,
cmvr::api::AgvMapCommand::Feedback *response) override
{
std::lock_guard<std::mutex> lock(m_mutex);
++m_reads;
const QString map = QString::fromStdString(request->map_name());
response->mutable_header()->set_success(m_maps.contains(map));
response->set_content(m_maps.value(map).toUtf8().toStdString());
return grpc::Status::OK;
}
grpc::Status uploadMap(grpc::ServerContext *,
const cmvr::api::AgvMapCommand::Request *request,
cmvr::api::AgvMapCommand::Feedback *response) override
{
std::lock_guard<std::mutex> lock(m_mutex);
m_uploads.push_back(*request);
if (m_result == Persist)
m_maps[QString::fromStdString(request->map_name())] = QString::fromUtf8(
request->content().data(), static_cast<int>(request->content().size()));
m_result = Persist;
response->mutable_header()->set_success(true);
return grpc::Status::OK;
}
void replace(const QString &content)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_maps["delete_map"] = content;
}
void next(Result result)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_result = result;
}
int reads()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_reads;
}
int uploads()
{
std::lock_guard<std::mutex> lock(m_mutex);
return static_cast<int>(m_uploads.size());
}
QString stored()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_maps.value("delete_map");
}
QString uploaded()
{
std::lock_guard<std::mutex> lock(m_mutex);
require(!m_uploads.empty(), "at least one explicit upload exists");
const auto &request = m_uploads.back();
require(request.map_name() == "delete_map" && request.header().device_id() == "fixture_delete_device",
"actual protobuf deletion upload retains target map and device");
return QString::fromUtf8(request.content().data(), static_cast<int>(request.content().size()));
}
private:
std::mutex m_mutex;
QHash<QString, QString> m_maps;
std::vector<cmvr::api::AgvMapCommand::Request> m_uploads;
Result m_result = Persist;
int m_reads = 0;
};
class Harness
{
public:
Harness()
{
grpc::ServerBuilder builder;
builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&service);
server = builder.BuildAndStart();
require(server && port > 0, "ephemeral loopback mock is the only connected server");
QObject::connect(&client, &RobotClient::connectionChanged,
[&](bool value, int, const QString &) { connected = value; });
client.connectToServer("127.0.0.1", port, false);
waitFor([&]() { return connected; }, "actual RobotClient connects to loopback mock");
auto *layout = new QVBoxLayout(&window);
view = new AgvMapViewWidget(&window);
editor = new AgvMapEditorWidget(&client, view, &window);
layout->addWidget(editor);
layout->addWidget(view);
editor->setContextProvider([&]() {
AgvMapEditorWidget::Context context;
context.endpoint = QStringLiteral("127.0.0.1:%1").arg(port);
context.deviceId = "fixture_delete_device";
context.mapName = selected;
context.connected = connected;
return context;
});
QObject::connect(editor, &AgvMapEditorWidget::mapSaved, [&]() { ++saved; });
QObject::connect(editor, &AgvMapEditorWidget::busyChanged, [&](bool value) { busy = value; });
QObject::connect(&client, &RobotClient::agvMapSaveFinished,
[&](quint64, const QString &, const QString &, bool success, const QString &) {
if (success)
++acks;
});
window.resize(1000, 700);
window.show();
setFrame();
manage = editor->findChild<QPushButton *>("agvManageMapObjectsButton");
save = editor->findChild<QPushButton *>("agvSaveMapObjectsButton");
undo = editor->findChild<QPushButton *>("agvUndoMapObjectsButton");
status = editor->findChild<QLabel *>("agvMapEditorStatus");
require(manage && save && undo && status, "public editor save, manager and undo controls exist");
editor->setAutoLoadEnabled(true);
waitFor([&]() { return service.reads() == 1 && !busy && manage->isEnabled()
&& status->text().contains(QStringLiteral("地图已读取")); },
"editor loads complete native fixture through real gRPC client");
}
~Harness()
{
client.disconnectFromServer();
waitFor([&]() { return !connected; }, "mock client disconnected");
server->Shutdown();
server->Wait();
}
void setFrame()
{
QImage image(400, 300, QImage::Format_RGB32);
image.fill(Qt::white);
view->setMapFrame(image, {{"mapId", selected}, {"dimension", 2},
{"resolution", 0.05}, {"renderScale", 1.0},
{"originX", 0.0}, {"originY", 0.0}, {"originTheta", 0.0}});
editor->refreshContext();
}
void changeMap(const QString &name)
{
selected = name;
setFrame();
waitFor([&]() { return !busy && manage->isEnabled(); }, "one selected-map change settles");
}
void inspect(const std::function<void(QTableWidget *, QTableWidget *)> &action)
{
nextModal("agvMapObjectsDialog", [=](QDialog *dialog) {
auto *stations = dialog->findChild<QTableWidget *>("agvMapStationsTable");
auto *routes = dialog->findChild<QTableWidget *>("agvMapRoutesTable");
require(stations && routes, "manager exposes point and route tables");
action(stations, routes);
dialog->accept();
});
manage->click();
}
void remove(const QString &id, bool station)
{
nextModal("agvMapObjectsDialog", [=](QDialog *dialog) {
auto *tabs = dialog->findChild<QTabWidget *>("agvMapObjectsTabs");
auto *table = dialog->findChild<QTableWidget *>(station ? "agvMapStationsTable" : "agvMapRoutesTable");
auto *button = dialog->findChild<QPushButton *>(station ? "agvDeleteStationButton" : "agvDeleteRouteButton");
require(tabs && table && button, "dedicated delete UI exists in correct manager tab");
tabs->setCurrentIndex(station ? 0 : 1);
const int row = rowFor(table, id);
require(row >= 0, "existing native object can be selected for deletion");
table->setCurrentCell(row, 0);
require(button->isEnabled(), "deletion requires a selected object");
nextModal(station ? "agvDeleteStationConfirmDialog" : "agvDeleteRouteConfirmDialog",
[=](QDialog *confirm) {
auto *yes = confirm->findChild<QPushButton *>(station
? "agvDeleteStationConfirmButton" : "agvDeleteRouteConfirmButton");
require(yes, "deletion has an explicit confirmation button");
yes->click();
});
button->click();
require(rowFor(table, id) < 0, "confirmed deletion immediately removes the local manager row");
dialog->accept();
});
manage->click();
require(save->isEnabled() && undo->isEnabled(), "deletion remains an explicit unsaved undoable draft");
require(service.uploads() == 0, "deleting in the manager sends no immediate vehicle upload");
}
FakeAgvService service;
std::unique_ptr<grpc::Server> server;
RobotClient client;
QWidget window;
AgvMapViewWidget *view = nullptr;
AgvMapEditorWidget *editor = nullptr;
QPushButton *manage = nullptr;
QPushButton *save = nullptr;
QPushButton *undo = nullptr;
QLabel *status = nullptr;
QString selected = "delete_map";
int port = 0;
int saved = 0;
int acks = 0;
bool connected = false;
bool busy = false;
};
void requireUntouchedNativeFields(const QString &content)
{
const QString source = fixture("delete_map");
const auto root = QJsonDocument::fromJson(source.toUtf8()).object();
const auto result = QJsonDocument::fromJson(content.toUtf8()).object();
const auto unchangedLine = [&](const QString &key) {
const int start = source.indexOf(QLatin1Char('"') + key + QLatin1Char('"'));
const int end = source.indexOf(QLatin1Char('\n'), start);
return start >= 0 && end > start && content.contains(source.mid(start, end - start));
};
require(result.value("header") == root.value("header")
&& result.value("normalPosList") == root.value("normalPosList")
&& result.value("advancedLineList") == root.value("advancedLineList")
&& content.contains("\"largeInteger\":18446744073709551615")
&& content.contains("\"vendorPoint\":9007199254740993")
&& content.contains("\"customLine\":9007199254740993")
&& unchangedLine("header") && unchangedLine("normalPosList")
&& unchangedLine("advancedLineList") && unchangedLine("rootUnknown"),
"deletion payload preserves complete native header, scan, lines and unknown integer/string tokens");
}
void testOneRouteAndRevisit()
{
Harness h;
h.remove("LM1_LM2", false);
AgvMapDocument concurrent;
QString error;
require(concurrent.load(h.service.stored(), &error)
&& concurrent.addStation("REMOTE", 6, 4, 0, &error),
"unrelated concurrent server change prepared");
h.service.replace(concurrent.content());
h.save->click();
waitFor([&]() { return h.saved == 1 && !h.busy; }, "route deletion must be read back before mapSaved");
require(h.service.uploads() == 1 && h.service.reads() == 3
&& !h.save->isEnabled() && !h.undo->isEnabled(),
"one explicit deletion save has one latest read, one upload and one confirming read");
AgvMapDocument stored;
require(stored.load(h.service.uploaded(), &error) && !hasRoute(stored, "LM1_LM2")
&& hasRoute(stored, "LM1_LM2_reverse") && stored.hasStation("LM2")
&& stored.hasStation("REMOTE") && stored.routes().size() == 5,
"selected route alone is removed while reverse route, points and concurrent additions survive");
requireUntouchedNativeFields(h.service.uploaded());
h.changeMap("other_map");
h.changeMap("delete_map");
h.inspect([](QTableWidget *stations, QTableWidget *routes) {
require(rowFor(routes, "LM1_LM2") < 0 && rowFor(routes, "LM1_LM2_reverse") >= 0
&& rowFor(stations, "REMOTE") >= 0,
"one away/back revisit reads the confirmed map without resurrecting deleted route");
});
require(h.service.uploads() == 1, "revisiting a saved map performs no hidden upload");
qInfo("PASS: single directed route deletion, native preservation, concurrent addition and single map revisit");
}
void testStationCascade()
{
Harness h;
h.remove("LM2", true);
h.inspect([](QTableWidget *stations, QTableWidget *routes) {
require(rowFor(stations, "LM2") < 0 && routes->rowCount() == 2
&& rowFor(routes, "LM3_LM4") >= 0 && rowFor(routes, "LM3_LM4_reverse") >= 0,
"station deletion stages every linked forward/reverse route and preserves unrelated pair");
});
h.save->click();
waitFor([&]() { return h.saved == 1 && !h.busy; }, "cascade deletion is persisted and verified");
QString error;
AgvMapDocument stored;
require(stored.load(h.service.stored(), &error) && !stored.hasStation("LM2")
&& stored.stations().size() == 3 && stored.routes().size() == 2
&& !hasRoute(stored, "LM1_LM2") && !hasRoute(stored, "LM1_LM2_reverse")
&& !hasRoute(stored, "LM2_LM3") && !hasRoute(stored, "LM2_LM3_reverse")
&& h.service.uploads() == 1,
"persisted deletion contains no dangling routes to the removed station");
requireUntouchedNativeFields(h.service.uploaded());
qInfo("PASS: station deletion cascades only associated directed routes and preserves native data");
}
void testUnconfirmedDeletion(bool station)
{
Harness h;
const QString id = station ? "LM2" : "LM1_LM2";
h.remove(id, station);
const int readsBefore = h.service.reads();
h.service.next(FakeAgvService::AckOnly);
h.save->click();
waitFor([&]() { return h.acks == 1 && h.service.reads() >= readsBefore + 2; },
"ACK-only deletion begins readback verification");
require(h.saved == 0 && h.busy && !h.save->isEnabled() && !h.undo->isEnabled(),
"upload ACK cannot clear pending deletion or report saved");
waitFor([&]() { return !h.busy && h.save->isEnabled(); },
"unchanged remote deletion result ends boundedly with retained draft");
require(h.saved == 0 && h.undo->isEnabled() && h.service.uploads() == 1
&& h.service.reads() > readsBefore + 1 && h.service.reads() <= readsBefore + 7,
"failed deletion readback keeps draft after at most six checks and one upload");
const QString desired = h.service.uploaded();
AgvMapDocument stillOld;
QString error;
require(stillOld.load(h.service.stored(), &error) && stillOld.hasStation("LM2")
&& hasRoute(stillOld, "LM1_LM2"),
"ACK-only mock independently proves deleted native objects remain remote");
h.changeMap("other_map");
h.changeMap("delete_map");
h.inspect([=](QTableWidget *stations, QTableWidget *routes) {
require(rowFor(station ? stations : routes, id) < 0,
"unconfirmed deletion draft survives switching away and back");
});
h.client.disconnectFromServer();
waitFor([&]() { return !h.connected; }, "loopback disconnected to test draft lifetime");
h.editor->refreshContext();
require(!h.save->isEnabled(), "disconnected deletion cannot be sent");
h.client.connectToServer("127.0.0.1", h.port, false);
waitFor([&]() { return h.connected; }, "loopback reconnected");
h.editor->refreshContext();
require(h.save->isEnabled() && h.undo->isEnabled() && h.saved == 0,
"reconnection restores the deletion draft without implicit save");
for (int index = 0; index < 10; ++index)
h.editor->refreshContext();
require(h.service.uploads() == 1, "context polling and reconnection never re-upload deletion");
// Simulate that a previously accepted upload becomes visible after the
// bounded check ended. The operator's next explicit retry is idempotent.
h.service.replace(desired);
h.save->click();
waitFor([&]() { return h.saved == 1 && !h.busy; },
"explicit retry succeeds even when the target objects are already missing");
require(h.service.uploads() == 2 && !h.save->isEnabled() && !h.undo->isEnabled(),
"already-missing target retry performs one upload then confirms and clears the draft");
qInfo("PASS: %s ACK without deletion retains draft across map revisit/disconnect; explicit retry is idempotent",
station ? "station cascade" : "route");
}
void testConflict(int kind)
{
Harness h;
h.remove(kind == 0 ? "LM1_LM2" : "LM2", kind != 0);
QString changed = h.service.stored();
if (kind == 0) {
require(changed.contains("\"vendorRoute\":9007199254740993"), "route conflict fixture custom field present");
changed.replace("\"vendorRoute\":9007199254740993", "\"vendorRoute\":9007199254740995");
} else if (kind == 1) {
changed.replace("\"description\":\"second\"", "\"description\":\"external rename\"");
} else {
AgvMapDocument latest;
QString error;
require(latest.load(changed, &error) && latest.addRoute("NEW_ASSOCIATION", "LM4", "LM2", false, &error),
"new external route to locally deleted station prepared");
changed = latest.content();
}
h.service.replace(changed);
const int reads = h.service.reads();
h.save->click();
waitFor([&]() { return h.service.reads() == reads + 1 && !h.busy && h.save->isEnabled(); },
"fresh latest-map deletion conflict returns an editable local draft");
require(h.service.uploads() == 0 && h.saved == 0 && h.undo->isEnabled()
&& h.service.stored() == changed,
"changed deleted object or new station association prevents upload and preserves external map");
h.inspect([=](QTableWidget *stations, QTableWidget *routes) {
require(rowFor(kind == 0 ? routes : stations, kind == 0 ? "LM1_LM2" : "LM2") < 0,
"conflict leaves the original local deletion available for undo or operator review");
});
qInfo("PASS: fresh-map conflict blocks deletion upload (%s)",
kind == 0 ? "route unknown-field change" : kind == 1 ? "station name change" : "new associated route");
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Q_INIT_RESOURCE(resources);
testOneRouteAndRevisit();
testStationCascade();
testUnconfirmedDeletion(false);
testUnconfirmedDeletion(true);
testConflict(0);
testConflict(1);
testConflict(2);
std::cout << "PASS AGV delete integration: route and station/cascade persistence, readback, native preservation,"
" single revisit, disconnect/draft retention, idempotent explicit retry and external conflicts;"
" loopback only, no vehicle writes" << std::endl;
return 0;
}

View File

@ -0,0 +1,313 @@
#include "agvmapdocument.h"
#include "agvmapeditorwidget.h"
#include "agvmapviewwidget.h"
#include "robotclient.h"
#include <QApplication>
#include <QDialog>
#include <QDir>
#include <QFile>
#include <QLabel>
#include <QMessageBox>
#include <QPointer>
#include <QPushButton>
#include <QTableWidget>
#include <QTabWidget>
#include <QTimer>
#include <QVBoxLayout>
#include <QVector>
#include <functional>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV editor deletion test failed: %s", message);
}
struct Request {
quint64 id;
QString device;
QString map;
QString content;
};
QString mapContent(const QString &name)
{
return QStringLiteral(R"JSON({
"header":{"mapType":"2D-Map","mapName":"%1","resolution":0.05},
"unknownInteger":9007199254740993,
"normalPosList":[{"x":1,"y":2}],
"advancedPointList":[
{"className":"LandMark","instanceName":"LM1","desc":"一号","pos":{"x":0,"y":0}},
{"className":"LandMark","instanceName":"LM2","pos":{"x":2,"y":0}},
{"className":"LandMark","instanceName":"LM3","pos":{"x":4,"y":0}}
],
"advancedCurveList":[
{"className":"BezierPath","instanceName":"R12","startPos":{"instanceName":"LM1","pos":{"x":0,"y":0}},"endPos":{"instanceName":"LM2","pos":{"x":2,"y":0}}},
{"className":"BezierPath","instanceName":"R21","startPos":{"instanceName":"LM2","pos":{"x":2,"y":0}},"endPos":{"instanceName":"LM1","pos":{"x":0,"y":0}}},
{"className":"BezierPath","instanceName":"R23","startPos":{"instanceName":"LM2","pos":{"x":2,"y":0}},"endPos":{"instanceName":"LM3","pos":{"x":4,"y":0}}}
]
})JSON").arg(name);
}
void nextModal(const std::function<bool(QDialog *)> &action)
{
auto *timer = new QTimer(qApp);
timer->setInterval(10);
QObject::connect(timer, &QTimer::timeout, timer, [timer, action]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (!dialog || !action(dialog))
return;
timer->stop();
timer->deleteLater();
});
timer->start();
QTimer::singleShot(7000, qApp, [guard = QPointer<QTimer>(timer)]() {
if (guard && guard->isActive())
qFatal("AGV editor deletion test failed: modal did not open");
});
}
int rowFor(QTableWidget *table, const QString &id)
{
for (int row = 0; row < table->rowCount(); ++row) {
if (table->item(row, 0) && table->item(row, 0)->text() == id)
return row;
}
return -1;
}
void confirmNext(bool station, bool accept,
const std::function<void(QMessageBox *)> &extra = {})
{
nextModal([=](QDialog *dialog) {
const QString expected = station ? QStringLiteral("agvDeleteStationConfirmDialog")
: QStringLiteral("agvDeleteRouteConfirmDialog");
if (dialog->objectName() != expected)
return false;
auto *box = qobject_cast<QMessageBox *>(dialog);
require(box, "delete confirmation is a message box");
if (extra) {
extra(box);
} else {
box->button(accept ? QMessageBox::Yes : QMessageBox::Cancel)->click();
}
return true;
});
}
void deleteInManager(QDialog *dialog, bool station, const QString &id, bool accept,
const std::function<void(QMessageBox *)> &extra = {})
{
auto *tabs = dialog->findChild<QTabWidget *>("agvMapObjectsTabs");
auto *table = dialog->findChild<QTableWidget *>(station ? "agvMapStationsTable" : "agvMapRoutesTable");
auto *remove = dialog->findChild<QPushButton *>(station ? "agvDeleteStationButton" : "agvDeleteRouteButton");
require(tabs && table && remove, "manager delete controls exist");
tabs->setCurrentIndex(station ? 0 : 1);
const int row = rowFor(table, id);
require(row >= 0, "object to delete exists");
table->setCurrentCell(row, 0);
require(remove->isEnabled(), "selecting a row enables deletion");
confirmNext(station, accept, extra);
remove->click();
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
const QString screenshotDir = qEnvironmentVariable("AGV_DELETE_SCREENSHOT_DIR");
if (!screenshotDir.isEmpty())
require(QDir().mkpath(screenshotDir), "screenshot directory is available");
QTimer::singleShot(30000, &app, []() { qFatal("AGV deletion test timed out"); });
RobotClient client;
QObject::disconnect(&client, nullptr, nullptr, nullptr);
QVector<Request> reads, writes;
QObject::connect(&client, &RobotClient::agvMapContentRequested,
[&](quint64 id, const QString &device, const QString &map) {
reads.append({id, device, map, {}});
});
QObject::connect(&client, &RobotClient::agvMapSaveRequested,
[&](quint64 id, const QString &device, const QString &map, const QString &content) {
writes.append({id, device, map, content});
});
QWidget window;
auto *layout = new QVBoxLayout(&window);
auto *view = new AgvMapViewWidget(&window);
auto *editor = new AgvMapEditorWidget(&client, view, &window);
layout->addWidget(editor);
layout->addWidget(view);
window.resize(1050, 700);
bool connected = true;
QString selectedMap = QStringLiteral("delete_map");
editor->setContextProvider([&]() {
AgvMapEditorWidget::Context context;
context.connected = connected;
context.demo = true;
context.endpoint = QStringLiteral("offline:50052");
context.deviceId = QStringLiteral("agv_delete_test");
context.mapName = selectedMap;
return context;
});
const auto setViewMap = [&]() {
QImage image(1280, 720, QImage::Format_RGB32);
image.fill(Qt::white);
view->setMapFrame(image, {{"mapId", selectedMap}, {"dimension", 2},
{"resolution", 0.05}, {"renderScale", 1.0},
{"originX", 0.0}, {"originY", 0.0}, {"originTheta", 0.0}});
};
setViewMap();
window.show();
app.processEvents();
editor->refreshContext();
auto *manage = editor->findChild<QPushButton *>("agvManageMapObjectsButton");
auto *save = editor->findChild<QPushButton *>("agvSaveMapObjectsButton");
auto *undo = editor->findChild<QPushButton *>("agvUndoMapObjectsButton");
require(manage && save && undo, "editor buttons exist");
const auto replyRead = [&](Request request, const QString &content) {
emit client.agvMapContentReceived(request.id, request.device, request.map,
content, true, {});
};
const auto manager = [&](const std::function<void(QDialog *)> &action) {
nextModal([=](QDialog *dialog) {
if (dialog->objectName() != QStringLiteral("agvMapObjectsDialog"))
return false;
QTimer::singleShot(0, dialog, [=]() {
action(dialog);
dialog->accept();
});
return true;
});
const int oldReads = reads.size();
manage->click();
if (reads.size() > oldReads)
replyRead(reads.last(), mapContent(selectedMap));
};
manager([&](QDialog *dialog) {
auto *removeStation = dialog->findChild<QPushButton *>("agvDeleteStationButton");
auto *removeRoute = dialog->findChild<QPushButton *>("agvDeleteRouteButton");
require(!removeStation->isEnabled() && !removeRoute->isEnabled(),
"deletion is disabled without a selection");
if (!screenshotDir.isEmpty()) {
auto *stations = dialog->findChild<QTableWidget *>("agvMapStationsTable");
auto *routes = dialog->findChild<QTableWidget *>("agvMapRoutesTable");
auto *tabs = dialog->findChild<QTabWidget *>("agvMapObjectsTabs");
stations->setCurrentCell(rowFor(stations, "LM1"), 0);
require(dialog->grab().save(screenshotDir + "/stations.png"), "station screenshot saved");
tabs->setCurrentIndex(1);
routes->setCurrentCell(rowFor(routes, "R12"), 0);
require(dialog->grab().save(screenshotDir + "/routes.png"), "route screenshot saved");
}
deleteInManager(dialog, false, QStringLiteral("R12"), false);
require(rowFor(dialog->findChild<QTableWidget *>("agvMapRoutesTable"), "R12") >= 0,
"cancel keeps selected route");
require(!save->isEnabled() && !undo->isEnabled(), "cancel creates no draft or history");
deleteInManager(dialog, false, QStringLiteral("R12"), true);
auto *routes = dialog->findChild<QTableWidget *>("agvMapRoutesTable");
require(rowFor(routes, "R12") < 0 && rowFor(routes, "R21") >= 0
&& rowFor(routes, "R23") >= 0,
"deleting one direction keeps reverse and unrelated route");
auto *localUndo = dialog->findChild<QPushButton *>("agvManagerUndoButton");
require(localUndo && localUndo->isEnabled(), "route removal is undoable");
localUndo->click();
require(rowFor(routes, "R12") >= 0 && !localUndo->isEnabled(),
"one undo restores route without extra history");
deleteInManager(dialog, true, QStringLiteral("LM1"), false,
[&](QMessageBox *box) {
require(box->text().contains("R12") && box->text().contains("R21")
&& box->text().contains(QStringLiteral("2 条")),
"station confirmation lists connected route IDs and count");
if (!screenshotDir.isEmpty())
require(box->grab().save(screenshotDir + "/station-confirm.png"), "confirmation screenshot saved");
box->button(QMessageBox::Cancel)->click();
});
require(rowFor(dialog->findChild<QTableWidget *>("agvMapStationsTable"), "LM1") >= 0,
"station cancellation preserves station");
deleteInManager(dialog, true, QStringLiteral("LM1"), true);
require(rowFor(dialog->findChild<QTableWidget *>("agvMapStationsTable"), "LM1") < 0
&& rowFor(routes, "R12") < 0 && rowFor(routes, "R21") < 0
&& rowFor(routes, "R23") >= 0,
"station removal removes only connected routes");
require(writes.isEmpty() && save->isEnabled() && undo->isEnabled(),
"deletion remains local until explicit save");
localUndo->click();
require(rowFor(routes, "R12") >= 0 && rowFor(routes, "R21") >= 0
&& !save->isEnabled() && !undo->isEnabled(),
"single undo restores station and both connected routes atomically");
});
qInfo("PASS: route direction, station cascade, cancellation and atomic undo");
manager([&](QDialog *dialog) {
deleteInManager(dialog, false, QStringLiteral("R12"), true,
[&](QMessageBox *box) {
connected = false;
editor->refreshContext();
// A queued acceptance can arrive before the context polling timer.
box->done(QMessageBox::Yes);
});
auto *remove = dialog->findChild<QPushButton *>("agvDeleteRouteButton");
require(!remove->isEnabled(), "connection change disables manager actions immediately");
});
require(writes.isEmpty() && !save->isEnabled(), "disconnect during confirmation cannot delete or upload");
connected = true;
editor->refreshContext();
manager([&](QDialog *dialog) {
require(rowFor(dialog->findChild<QTableWidget *>("agvMapRoutesTable"), "R12") >= 0,
"disconnected acceptance did not delete route");
deleteInManager(dialog, false, QStringLiteral("R12"), true,
[&](QMessageBox *box) {
selectedMap = QStringLiteral("other_map");
setViewMap();
editor->refreshContext();
box->done(QMessageBox::Yes);
});
require(!dialog->findChild<QPushButton *>("agvDeleteRouteButton")->isEnabled(),
"map change disables stale manager actions");
});
selectedMap = QStringLiteral("delete_map");
setViewMap();
editor->refreshContext();
manager([&](QDialog *dialog) {
require(rowFor(dialog->findChild<QTableWidget *>("agvMapRoutesTable"), "R12") >= 0,
"map-change acceptance did not delete original route");
deleteInManager(dialog, true, QStringLiteral("LM1"), true);
});
qInfo("PASS: stale nested confirmation guards connection and map identity");
int saved = 0;
QObject::connect(editor, &AgvMapEditorWidget::mapSaved, [&]() { ++saved; });
save->click();
replyRead(reads.last(), mapContent(selectedMap));
require(writes.size() == 1, "one explicit save issues one upload");
AgvMapDocument uploaded;
QString error;
require(uploaded.load(writes.last().content, &error), "uploaded full map parses");
require(!uploaded.hasStation("LM1") && uploaded.hasStation("LM2") && uploaded.hasStation("LM3")
&& uploaded.routes().size() == 1,
"upload contains confirmed station and cascade deletions");
require(writes.last().content.contains(QStringLiteral("9007199254740993")),
"deletion preserves unrelated large integer source text");
const Request upload = writes.last();
emit client.agvMapSaveFinished(upload.id, upload.device, upload.map, true, {});
require(saved == 0 && !save->isEnabled() && !undo->isEnabled(),
"upload ACK alone cannot commit deletion draft");
replyRead(reads.last(), upload.content);
require(saved == 1 && !save->isEnabled() && !undo->isEnabled(),
"readback absence confirms deletion and clears undo history");
qInfo("PASS: deletion save upload and readback confirmation");
if (argc > 1) {
QFile report(QString::fromLocal8Bit(argv[1]));
require(report.open(QIODevice::WriteOnly | QIODevice::Truncate), "test report path is writable");
report.write("PASS: cancel preserves content and creates no history\n"
"PASS: selected directed route deletion preserves reverse route\n"
"PASS: station confirmation lists related routes and cascades atomically\n"
"PASS: one undo restores station and related routes\n"
"PASS: nested confirmation guards disconnect and map change\n"
"PASS: edits stay local until one explicit upload\n"
"PASS: ACK alone cannot commit; readback absence confirms deletion\n"
"PASS: unrelated large integer source text preserved\n");
}
return 0;
}

View File

@ -0,0 +1,686 @@
#include "agvmapdocument.h"
#include "agvmapeditorwidget.h"
#include "agvmapviewwidget.h"
#include "robotclient.h"
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDoubleSpinBox>
#include <QFile>
#include <QLabel>
#include <QLineEdit>
#include <QPointer>
#include <QPushButton>
#include <QTableWidget>
#include <QTimer>
#include <QVBoxLayout>
#include <QVector>
#include <functional>
namespace {
void require(bool condition, const char *message)
{
if (!condition) {
QFile failure(QStringLiteral("agvmapeditor_failure_assertion.txt"));
if (failure.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
failure.write(message);
failure.write("\n");
failure.close();
}
qFatal("AGV editor failure test failed: %s", message);
}
}
struct Request {
quint64 id;
QString device;
QString map;
QString content;
};
QString mapContent(const QString &name)
{
return QStringLiteral(R"JSON({
"header":{"mapType":"2D-Map","mapName":"%1","resolution":0.05},
"unknownInteger":9007199254740993,
"normalPosList":[{"x":1,"y":2}],
"advancedPointList":[
{"className":"LandMark","instanceName":"HOME","pos":{"x":0,"y":0}},
{"className":"LandMark","instanceName":"B","pos":{"x":2,"y":0}}
],
"advancedCurveList":[]
})JSON").arg(name);
}
void fillNextModal(const std::function<bool(QDialog *)> &fill)
{
auto *timer = new QTimer(qApp);
timer->setInterval(10);
QObject::connect(timer, &QTimer::timeout, timer, [timer, fill]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (!dialog || !fill(dialog))
return;
timer->stop();
timer->deleteLater();
});
timer->start();
QTimer::singleShot(7000, qApp, [guard = QPointer<QTimer>(timer)]() {
if (guard && guard->isActive())
qFatal("AGV editor failure test failed: expected dialog did not open");
});
}
void fillNextStation(const QString &id, double x, double y, const QString &displayName = QString())
{
fillNextModal([=](QDialog *dialog) {
if (dialog->objectName() != QStringLiteral("agvStationDialog"))
return false;
auto *name = dialog->findChild<QLineEdit *>("agvNewStationId");
auto *label = dialog->findChild<QLineEdit *>("agvNewStationName");
auto *xSpin = dialog->findChild<QDoubleSpinBox *>("agvNewStationX");
auto *ySpin = dialog->findChild<QDoubleSpinBox *>("agvNewStationY");
auto *box = dialog->findChild<QDialogButtonBox *>();
require(name && label && xSpin && ySpin && box, "station dialog controls exist");
name->setText(id);
label->setText(displayName);
xSpin->setValue(x);
ySpin->setValue(y);
box->button(QDialogButtonBox::Ok)->click();
return true;
});
}
void fillNextRoute(const QString &id)
{
fillNextModal([=](QDialog *dialog) {
if (dialog->objectName() != QStringLiteral("agvRouteDialog"))
return false;
auto *name = dialog->findChild<QLineEdit *>("agvNewRouteId");
auto *both = dialog->findChild<QCheckBox *>("agvNewRouteBidirectional");
auto *box = dialog->findChild<QDialogButtonBox *>();
require(name && both && box, "route dialog controls exist");
name->setText(id);
both->setChecked(false);
box->button(QDialogButtonBox::Ok)->click();
return true;
});
}
void inspectNextManager(const std::function<void(QTableWidget *)> &inspect)
{
fillNextModal([=](QDialog *dialog) {
if (dialog->objectName() != QStringLiteral("agvMapObjectsDialog"))
return false;
auto *stations = dialog->findChild<QTableWidget *>("agvMapStationsTable");
require(stations, "manager stations table exists");
inspect(stations);
dialog->accept();
return true;
});
}
QString managerStationName(QTableWidget *stations, const QString &id)
{
for (int row = 0; row < stations->rowCount(); ++row) {
if (stations->item(row, 0)->text() == id)
return stations->item(row, 1)->text();
}
return QString();
}
void renameNextStation(const QString &id, const QString &displayName)
{
fillNextModal([=](QDialog *dialog) {
if (dialog->objectName() != QStringLiteral("agvMapObjectsDialog"))
return false;
auto *stations = dialog->findChild<QTableWidget *>("agvMapStationsTable");
auto *rename = dialog->findChild<QPushButton *>("agvRenameStationButton");
require(stations && rename, "manager rename controls exist");
int selected = -1;
for (int row = 0; row < stations->rowCount(); ++row) {
if (stations->item(row, 0)->text() == id)
selected = row;
}
require(selected >= 0, "existing station can be selected for rename");
stations->setCurrentCell(selected, 0);
fillNextModal([=](QDialog *nameDialog) {
if (nameDialog->objectName() != QStringLiteral("agvStationNameDialog"))
return false;
auto *name = nameDialog->findChild<QLineEdit *>("agvStationName");
auto *box = nameDialog->findChild<QDialogButtonBox *>();
require(name && box, "station name dialog controls exist");
name->setText(displayName);
box->button(QDialogButtonBox::Ok)->click();
return true;
});
// Start the nested dialog after this modal observer stops its timer.
QTimer::singleShot(0, dialog, [dialog, rename]() {
rename->click();
dialog->accept();
});
return true;
});
}
QString documentStationName(const AgvMapDocument &document, const QString &id)
{
for (const QVariant &value : document.stations()) {
if (value.toMap().value("id").toString() == id)
return value.toMap().value("description").toString();
}
return QString();
}
void requireSavedStation(const Request &request, const QString &id)
{
AgvMapDocument document;
QString error;
require(document.load(request.content, &error), "upload contains a valid full map");
require(document.hasStation(id), "upload retains the station draft");
require(request.content.contains(QStringLiteral("9007199254740993")),
"upload preserves unknown integer text");
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTimer::singleShot(30000, &app, []() {
qFatal("AGV editor failure test failed: test timed out");
});
RobotClient client;
// Detach outbound worker requests before attaching the editor and observers.
// Every response below is injected in-process; no server is connected.
QObject::disconnect(&client, nullptr, nullptr, nullptr);
QVector<Request> reads;
QVector<Request> writes;
QObject::connect(&client, &RobotClient::agvMapContentRequested,
[&](quint64 id, const QString &device, const QString &map) {
reads.append({id, device, map, QString()});
});
QObject::connect(&client, &RobotClient::agvMapSaveRequested,
[&](quint64 id, const QString &device, const QString &map, const QString &content) {
writes.append({id, device, map, content});
});
QWidget window;
auto *layout = new QVBoxLayout(&window);
auto *view = new AgvMapViewWidget(&window);
auto *editor = new AgvMapEditorWidget(&client, view, &window);
layout->addWidget(editor);
layout->addWidget(view);
window.resize(1050, 700);
bool connected = true;
bool demo = true;
QString selectedMap = QStringLiteral("map_A");
editor->setContextProvider([&]() {
AgvMapEditorWidget::Context context;
context.connected = connected;
context.demo = demo;
context.endpoint = QStringLiteral("offline:50052");
context.deviceId = QStringLiteral("agv_failure_test");
context.mapName = selectedMap;
return context;
});
const auto setViewMap = [&]() {
QImage image(1280, 720, QImage::Format_RGB32);
image.fill(Qt::white);
view->setMapFrame(image, {{"mapId", selectedMap}, {"dimension", 2},
{"resolution", 0.05}, {"renderScale", 1.0},
{"originX", 0.0}, {"originY", 0.0}, {"originTheta", 0.0}});
};
setViewMap();
window.show();
app.processEvents();
editor->refreshContext();
auto *coordinates = editor->findChild<QPushButton *>("agvCoordinateStationButton");
auto *save = editor->findChild<QPushButton *>("agvSaveMapObjectsButton");
auto *undo = editor->findChild<QPushButton *>("agvUndoMapObjectsButton");
auto *manage = editor->findChild<QPushButton *>("agvManageMapObjectsButton");
auto *addStation = editor->findChild<QPushButton *>("agvAddStationButton");
auto *addRoute = editor->findChild<QPushButton *>("agvAddRouteButton");
auto *status = editor->findChild<QLabel *>("agvMapEditorStatus");
require(coordinates && save && undo && manage && addStation && addRoute && status,
"editor controls exist");
int saved = 0;
QObject::connect(editor, &AgvMapEditorWidget::mapSaved, [&]() { ++saved; });
const auto replyRead = [&](const Request &request, bool success,
const QString &content, const QString &detail) {
// A read reply may synchronously open a dialog or append another request.
const Request copy = request;
emit client.agvMapContentReceived(copy.id, copy.device, copy.map,
content, success, detail);
};
const auto replyWrite = [&](const Request &request, bool success, const QString &detail) {
const Request copy = request;
emit client.agvMapSaveFinished(copy.id, copy.device, copy.map, success, detail);
};
coordinates->click();
require(reads.size() == 1 && !coordinates->isEnabled(), "initial map read is pending");
replyRead(reads.last(), false, QString(), QStringLiteral("initial read failed"));
require(coordinates->isEnabled() && !save->isEnabled() && !undo->isEnabled(),
"failed initial read releases busy state without drafts");
require(status->text().contains(QStringLiteral("initial read failed")),
"initial read error is visible");
coordinates->click();
require(reads.size() == 2, "initial read can be retried");
fillNextStation(QStringLiteral("P1"), 3.0, 4.0);
replyRead(reads.last(), true, mapContent(selectedMap), QString());
require(save->isEnabled() && undo->isEnabled(), "retry creates a station draft");
qInfo("PASS: initial map read failure and retry");
save->click();
require(reads.size() == 3 && !save->isEnabled(), "save first requests the latest map");
replyRead(reads.last(), false, QString(), QStringLiteral("save read failed"));
require(save->isEnabled() && undo->isEnabled() && coordinates->isEnabled(),
"failed pre-save read retains draft and releases busy state");
require(writes.isEmpty() && saved == 0, "failed pre-save read never uploads or marks saved");
require(status->text().contains(QStringLiteral("save read failed")),
"pre-save read error is visible");
qInfo("PASS: pre-save read failure preserves drafts");
save->click();
require(reads.size() == 4, "save retries the latest-map read");
replyRead(reads.last(), true, mapContent(selectedMap), QString());
require(writes.size() == 1 && !save->isEnabled() && !coordinates->isEnabled(),
"successful re-read starts upload and remains busy");
requireSavedStation(writes.last(), QStringLiteral("P1"));
replyWrite(writes.last(), false, QStringLiteral("upload failed"));
require(save->isEnabled() && undo->isEnabled() && coordinates->isEnabled() && saved == 0,
"failed upload retains draft and does not emit mapSaved");
require(status->text().contains(QStringLiteral("upload failed")), "upload error is visible");
save->click();
require(reads.size() == 5, "upload retry re-reads latest full map");
replyRead(reads.last(), true, mapContent(selectedMap), QString());
require(writes.size() == 2, "upload can be retried");
requireSavedStation(writes.last(), QStringLiteral("P1"));
const Request acceptedPreSaveRead = reads.last();
replyWrite(writes.last(), true, QString());
require(saved == 0 && reads.size() == 6 && !save->isEnabled() && !undo->isEnabled()
&& !coordinates->isEnabled() && !manage->isEnabled(),
"upload ACK starts readback verification and keeps all edit controls busy");
const Request acceptedVerificationRead = reads.last();
require(acceptedVerificationRead.id != acceptedPreSaveRead.id,
"readback verification uses a fresh request token");
replyRead(acceptedPreSaveRead, true, writes.last().content, QString());
require(saved == 0 && !save->isEnabled() && !coordinates->isEnabled(),
"old pre-save read cannot commit an accepted upload");
replyRead(acceptedVerificationRead, true, writes.last().content, QString());
require(saved == 1 && !save->isEnabled() && !undo->isEnabled() && coordinates->isEnabled(),
"verified successful retry clears drafts and emits mapSaved once");
qInfo("PASS: upload failure preserves drafts and successful retry commits them");
fillNextStation(QStringLiteral("P2"), 5.0, 6.0);
coordinates->click();
require(save->isEnabled(), "second station is a draft");
save->click();
require(reads.size() == 7, "save re-read is pending before disconnect");
const Request disconnectedRead = reads.last();
connected = false;
editor->refreshContext();
require(!save->isEnabled() && !coordinates->isEnabled(), "disconnect disables editing");
replyRead(disconnectedRead, true, mapContent(QStringLiteral("map_A")), QString());
require(writes.size() == 2 && saved == 1, "old read after disconnect cannot upload");
connected = true;
editor->refreshContext();
require(save->isEnabled() && undo->isEnabled(), "returning to original context retains draft");
replyRead(disconnectedRead, true, mapContent(QStringLiteral("map_A")), QString());
require(writes.size() == 2, "old read remains invalid after reconnect");
save->click();
require(reads.size() == 8, "save re-read is pending before map change");
const Request previousMapRead = reads.last();
selectedMap = QStringLiteral("map_B");
setViewMap();
editor->refreshContext();
require(coordinates->isEnabled() && !save->isEnabled(), "new map releases busy state");
replyRead(previousMapRead, true, mapContent(QStringLiteral("map_A")), QString());
require(writes.size() == 2 && saved == 1, "old map read cannot upload after map change");
coordinates->click();
require(reads.size() == 9 && reads.last().map == selectedMap, "new map is read normally");
fillNextStation(QStringLiteral("P3"), 7.0, 8.0, QStringLiteral("地图B站点"));
replyRead(reads.last(), true, mapContent(selectedMap), QString());
require(writes.size() == 2 && save->isEnabled() && undo->isEnabled(),
"ordinary new-map read creates a draft without a stale save flag uploading it");
require(status->text().contains(QStringLiteral("地图B站点")), "new-map named station dialog completed");
// A late map_A frame must disable every action while map_B is selected.
selectedMap = QStringLiteral("map_A");
setViewMap();
selectedMap = QStringLiteral("map_B");
editor->refreshContext();
require(!coordinates->isEnabled() && !manage->isEnabled() && !addStation->isEnabled()
&& !addRoute->isEnabled() && !save->isEnabled() && !undo->isEnabled(),
"late frame for another map disables editing save and undo");
const int readsBeforeWrongFrame = reads.size();
undo->click();
save->click();
coordinates->click();
require(reads.size() == readsBeforeWrongFrame && writes.size() == 2,
"wrong-map frame actions cannot consume drafts or request a save");
setViewMap();
editor->refreshContext();
inspectNextManager([](QTableWidget *stations) {
require(managerStationName(stations, "P3") == QStringLiteral("地图B站点")
&& managerStationName(stations, "P2").isEmpty(),
"wrong-map undo cannot remove B draft or expose A draft");
});
manage->click();
selectedMap = QStringLiteral("map_A");
setViewMap();
editor->refreshContext();
require(save->isEnabled() && undo->isEnabled() && reads.size() == 9,
"returning to A restores its draft and history without downloading");
inspectNextManager([](QTableWidget *stations) {
require(managerStationName(stations, "P2") == QStringLiteral("P2")
&& managerStationName(stations, "P3").isEmpty(),
"returning to A restores only A unsaved station");
});
manage->click();
fillNextStation(QStringLiteral("A_TEMP"), 8.0, 9.0);
coordinates->click();
undo->click();
require(save->isEnabled() && undo->isEnabled(), "A undo removes only its latest edit");
save->click();
require(reads.size() == 10 && reads.last().map == selectedMap,
"restored A draft saves against A latest map");
replyRead(reads.last(), true, mapContent(selectedMap), QString());
require(writes.size() == 3 && writes.last().map == selectedMap,
"restored A draft uploads to A rather than B");
AgvMapDocument restoredA;
QString error;
require(restoredA.load(writes.last().content, &error) && restoredA.hasStation("P2")
&& !restoredA.hasStation("A_TEMP") && !restoredA.hasStation("P3"),
"restored A upload contains its retained draft after undo");
replyWrite(writes.last(), true, QString());
require(saved == 1 && reads.size() == 11 && !save->isEnabled() && !undo->isEnabled(),
"restored A ACK retains its draft until verification returns");
replyRead(reads.last(), true, writes.last().content, QString());
require(saved == 2 && !save->isEnabled() && !undo->isEnabled(),
"restored A successful save clears only its draft");
selectedMap = QStringLiteral("map_B");
setViewMap();
editor->refreshContext();
require(save->isEnabled() && undo->isEnabled() && reads.size() == 11,
"B unsaved work survives saving A");
qInfo("PASS: disconnect/map switch discard stale reads and reset pre-save state");
editor->setAutoLoadEnabled(true);
const int automaticStart = reads.size();
selectedMap = QStringLiteral("map_C");
editor->refreshContext();
require(reads.size() == automaticStart && !save->isEnabled() && !undo->isEnabled(),
"automatic load waits for selected map frame and disables old draft actions");
QImage threeDimensionalPreview(1280, 720, QImage::Format_RGB32);
threeDimensionalPreview.fill(Qt::white);
view->setMapFrame(threeDimensionalPreview, {{"mapId", selectedMap}, {"dimension", 3}});
editor->refreshContext();
require(reads.size() == automaticStart && !coordinates->isEnabled(),
"automatic load and editing require valid 2D coordinate projection");
setViewMap();
editor->refreshContext();
require(reads.size() == automaticStart + 1 && reads.last().map == selectedMap,
"ready new map loads automatically while previous map draft stays preserved");
for (int i = 0; i < 20; ++i)
editor->refreshContext();
require(reads.size() == automaticStart + 1, "polling never duplicates an in-flight automatic load");
const Request failedAutomaticRead = reads.last();
replyRead(failedAutomaticRead, false, QString(), QStringLiteral("automatic read failed"));
for (int i = 0; i < 20; ++i)
editor->refreshContext();
require(reads.size() == automaticStart + 1 && coordinates->isEnabled() && !save->isEnabled(),
"failed automatic load releases busy state and is not retried by polling");
require(status->text().contains(QStringLiteral("automatic read failed")),
"automatic read failure stays visible");
coordinates->click();
require(reads.size() == automaticStart + 2, "explicit editor action retries a failed automatic load");
replyRead(reads.last(), false, QString(), QStringLiteral("explicit retry failed"));
editor->refreshContext();
require(reads.size() == automaticStart + 2, "failed explicit retry does not re-enable automatic polling");
selectedMap = QStringLiteral("map_B");
setViewMap();
editor->refreshContext();
require(reads.size() == automaticStart + 2 && save->isEnabled() && undo->isEnabled(),
"failed load of C leaves B draft available when returning");
undo->click();
require(!save->isEnabled() && !undo->isEnabled(), "B undo remains usable after another map's failure");
selectedMap = QStringLiteral("map_D");
setViewMap();
editor->refreshContext();
require(reads.size() == automaticStart + 3, "another map receives its own automatic attempt");
replyRead(reads.last(), true, mapContent(selectedMap), QString());
require(coordinates->isEnabled() && !save->isEnabled() && !undo->isEnabled(),
"automatic load shows existing objects without creating a draft");
require(status->text().contains(QStringLiteral("2 个站点")),
"automatic load includes all existing stations");
for (int i = 0; i < 20; ++i)
editor->refreshContext();
require(reads.size() == automaticStart + 3, "successful automatic load is not repeated");
selectedMap = QStringLiteral("map_C");
setViewMap();
editor->refreshContext();
selectedMap = QStringLiteral("map_D");
setViewMap();
editor->refreshContext();
require(reads.size() == automaticStart + 4,
"clean map revisit downloads current content rather than retaining a cache");
replyRead(reads.last(), true, mapContent(selectedMap), QString());
selectedMap = QStringLiteral("map_C");
setViewMap();
editor->refreshContext();
require(reads.size() == automaticStart + 4, "temporary map changes never retry a failed map automatically");
connected = false;
editor->refreshContext();
connected = true;
editor->refreshContext();
require(reads.size() == automaticStart + 5 && !coordinates->isEnabled(),
"a new connection permits a new automatic attempt");
replyRead(failedAutomaticRead, true, mapContent(selectedMap), QString());
require(!coordinates->isEnabled() && writes.size() == 3 && saved == 2,
"old automatic reply cannot replace a newer same-map request");
replyRead(reads.last(), true, mapContent(selectedMap), QString());
require(coordinates->isEnabled() && !save->isEnabled() && writes.size() == 3 && saved == 2,
"fresh automatic reply loads without uploading or marking a save");
selectedMap = QStringLiteral("map_D");
setViewMap();
editor->refreshContext();
require(reads.size() == automaticStart + 6, "returning to a successfully loaded map downloads fresh content");
AgvMapDocument freshMap;
require(freshMap.load(mapContent(selectedMap), &error), "prepare updated map content");
require(freshMap.addStation(QStringLiteral("REMOTE_D"), 9.0, 10.0, 0.0, &error),
"independent station was added since the last visit");
require(freshMap.addRoute(QStringLiteral("HOME_REMOTE_D"), QStringLiteral("HOME"),
QStringLiteral("REMOTE_D"), false, &error),
"independent route was added since the last visit");
replyRead(reads.last(), true, freshMap.content(), QString());
require(status->text().contains(QStringLiteral("3 个站点")) && !save->isEnabled(),
"returning to a map displays new remote objects");
require(status->text().contains(QStringLiteral("1 条路线")),
"automatic load includes existing routes as well as stations");
for (int i = 0; i < 20; ++i)
editor->refreshContext();
require(reads.size() == automaticStart + 6, "loaded context suppresses polling after a successful revisit");
connected = false;
editor->refreshContext();
connected = true;
editor->refreshContext();
require(reads.size() == automaticStart + 7, "reconnect invalidates the clean loaded document");
replyRead(reads.last(), true, freshMap.content(), QString());
fillNextStation(QStringLiteral("P4"), 12.0, 13.0);
coordinates->click();
require(save->isEnabled(), "station draft exists before automatic-mode reconnect");
connected = false;
editor->refreshContext();
connected = true;
editor->refreshContext();
require(reads.size() == automaticStart + 7 && save->isEnabled() && undo->isEnabled(),
"reconnect preserves dirty document context and does not auto-replace drafts");
qInfo("PASS: automatic map load readiness, one attempt, explicit retry and stale replies");
undo->click();
require(!save->isEnabled(), "remove new-station draft before testing an existing name edit");
renameNextStation(QStringLiteral("HOME"), QStringLiteral("本地上料站"));
manage->click();
require(save->isEnabled() && undo->isEnabled(), "existing station rename creates an editable draft");
save->click();
require(reads.size() == automaticStart + 8 && !save->isEnabled(),
"name save first re-reads complete latest map");
AgvMapDocument external;
require(external.load(freshMap.content(), &error)
&& external.setStationName("HOME", QStringLiteral("外部修改的站点"), &error),
"prepare concurrent station name update");
replyRead(reads.last(), true, external.content(), QString());
require(writes.size() == 3 && saved == 2 && save->isEnabled() && undo->isEnabled(),
"concurrent name conflict refuses upload and retains local editable draft");
require(status->text().contains(QStringLiteral("名称已被其他操作修改")),
"name conflict is visible to the operator");
inspectNextManager([](QTableWidget *stations) {
require(managerStationName(stations, "HOME") == QStringLiteral("本地上料站"),
"conflict does not replace user's name with remote name");
});
manage->click();
require(external.setStationName("HOME", QString(), &error)
&& external.setStationName("B", QStringLiteral("远端等待站"), &error),
"prepare latest map without conflicting name but with unrelated remote name edit");
save->click();
require(reads.size() == automaticStart + 9, "conflicted name draft can retry latest-map read");
replyRead(reads.last(), true, external.content(), QString());
require(writes.size() == 4 && writes.last().map == selectedMap && !save->isEnabled(),
"nonconflicting name merge starts a save for the active map");
AgvMapDocument merged;
require(merged.load(writes.last().content, &error)
&& documentStationName(merged, "HOME") == QStringLiteral("本地上料站")
&& documentStationName(merged, "B") == QStringLiteral("远端等待站")
&& merged.hasStation("REMOTE_D") && !merged.hasStation("P4"),
"name rebase combines local rename with latest unrelated remote changes");
replyWrite(writes.last(), true, QString());
require(saved == 2 && !save->isEnabled() && !undo->isEnabled(),
"name upload ACK does not clear the pending name edit");
replyRead(reads.last(), true, writes.last().content, QString());
require(saved == 3 && !save->isEnabled() && !undo->isEnabled() && manage->isEnabled(),
"successful name upload clears dirty name and history exactly once");
inspectNextManager([](QTableWidget *stations) {
require(managerStationName(stations, "HOME") == QStringLiteral("本地上料站")
&& managerStationName(stations, "B") == QStringLiteral("远端等待站"),
"saved manager shows local and latest remote names");
});
manage->click();
qInfo("PASS: station name conflict preserves draft and nonconflicting latest-map merge saves");
// ACK success is provisional: a lost verification read must leave the
// original local additions available, even if the write reached the robot.
editor->setAutoLoadEnabled(false);
const QString beforeVerificationDisconnect = writes.last().content;
fillNextStation(QStringLiteral("VERIFY12"), 14.0, 15.0, QStringLiteral("验证中断站点"));
coordinates->click();
fillNextRoute(QStringLiteral("VERIFY_ROUTE"));
addRoute->click();
emit view->stationSelected(QStringLiteral("HOME"));
emit view->stationSelected(QStringLiteral("B"));
const int writesBeforeVerificationDisconnect = writes.size();
const int readsBeforeVerificationDisconnect = reads.size();
save->click();
require(reads.size() == readsBeforeVerificationDisconnect + 1,
"verification-disconnect save starts by downloading latest map");
replyRead(reads.last(), true, beforeVerificationDisconnect, QString());
require(writes.size() == writesBeforeVerificationDisconnect + 1,
"verification-disconnect save uploads one merged map");
const Request uploadedBeforeDisconnect = writes.last();
requireSavedStation(uploadedBeforeDisconnect, QStringLiteral("VERIFY12"));
require(uploadedBeforeDisconnect.content.contains(QStringLiteral("VERIFY_ROUTE")),
"verification candidate includes station and route drafts");
replyWrite(uploadedBeforeDisconnect, true, QString());
require(saved == 3 && reads.size() == readsBeforeVerificationDisconnect + 2
&& !save->isEnabled() && !undo->isEnabled() && !coordinates->isEnabled(),
"accepted upload remains pending while its fresh readback is outstanding");
const Request verificationBeforeDisconnect = reads.last();
connected = false;
editor->refreshContext();
replyRead(verificationBeforeDisconnect, true, uploadedBeforeDisconnect.content, QString());
require(saved == 3 && !save->isEnabled(),
"late verification after disconnect cannot commit or mark drafts saved");
connected = true;
editor->refreshContext();
require(save->isEnabled() && undo->isEnabled() && coordinates->isEnabled(),
"reconnecting restores station and route drafts after interrupted verification");
const int writesBeforeConfirmedRetry = writes.size();
save->click();
const Request retryPreSaveRead = reads.last();
// This simulates an ACKed write that really reached the vehicle before
// its readback was interrupted. Explicit retry must not reject its own IDs.
replyRead(retryPreSaveRead, true, uploadedBeforeDisconnect.content, QString());
require(writes.size() == writesBeforeConfirmedRetry + 1,
"explicit retry merges already persisted station and route idempotently and uploads once");
replyWrite(writes.last(), true, QString());
const Request retryVerificationRead = reads.last();
replyRead(verificationBeforeDisconnect, true, uploadedBeforeDisconnect.content, QString());
require(saved == 3 && !save->isEnabled(),
"old verification token remains invalid after reconnect and a newer save");
replyRead(retryVerificationRead, true, writes.last().content, QString());
require(saved == 4 && !save->isEnabled() && !undo->isEnabled() && coordinates->isEnabled(),
"matching retry readback commits the retained draft exactly once");
const QString beforeVerificationMapChange = writes.last().content;
fillNextStation(QStringLiteral("VERIFY13"), 16.0, 17.0);
coordinates->click();
save->click();
replyRead(reads.last(), true, beforeVerificationMapChange, QString());
const Request uploadedBeforeMapChange = writes.last();
replyWrite(uploadedBeforeMapChange, true, QString());
const Request verificationBeforeMapChange = reads.last();
require(saved == 4 && !save->isEnabled() && !undo->isEnabled(),
"map-change verification starts without clearing its local draft");
const QString verificationMap = selectedMap;
selectedMap = QStringLiteral("map_E");
setViewMap();
editor->refreshContext();
replyRead(verificationBeforeMapChange, true, uploadedBeforeMapChange.content, QString());
require(saved == 4 && !save->isEnabled() && coordinates->isEnabled(),
"verification reply for the previous map cannot commit in a different context");
selectedMap = verificationMap;
setViewMap();
editor->refreshContext();
require(save->isEnabled() && undo->isEnabled(),
"returning to the interrupted verification map restores its unsaved station");
const int writesBeforeMapRetry = writes.size();
save->click();
replyRead(reads.last(), true, uploadedBeforeMapChange.content, QString());
require(writes.size() == writesBeforeMapRetry + 1,
"map-context retry accepts its already persisted station without duplicating it");
replyWrite(writes.last(), true, QString());
replyRead(reads.last(), true, writes.last().content, QString());
require(saved == 5 && !save->isEnabled() && !undo->isEnabled(),
"new verification after returning to the map commits once");
qInfo("PASS: upload ACK readback, stale verification, disconnect/context retention and idempotent explicit retry");
fillNextStation(QStringLiteral("VERIFY14"), 18.0, 19.0);
coordinates->click();
const int writesBeforeWrongHeader = writes.size();
save->click();
const Request expectedMapRead = reads.last();
require(expectedMapRead.map == selectedMap, "pre-save request envelope identifies the selected map");
replyRead(expectedMapRead, true, mapContent(QStringLiteral("wrong_map")), QString());
require(writes.size() == writesBeforeWrongHeader && saved == 5
&& save->isEnabled() && undo->isEnabled() && coordinates->isEnabled(),
"correct envelope with a different header map name rejects upload and preserves the dirty draft");
qInfo("PASS: pre-save payload header identity protects against a wrong-map response");
qInfo("PASS: AGV editor offline failure handling tests");
return 0;
}

View File

@ -0,0 +1,203 @@
#include "agvmapdocument.h"
#include "agvmapeditorwidget.h"
#include "agvmapviewwidget.h"
#include "robotclient.h"
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QColor>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDoubleSpinBox>
#include <QElapsedTimer>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QPointer>
#include <QResource>
#include <QThread>
#include <QTimer>
#include <QVBoxLayout>
#include <functional>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV editor smoke failed: %s", message);
}
void waitFor(const std::function<bool()> &condition, const char *message)
{
QElapsedTimer timer;
timer.start();
while (!condition() && timer.elapsed() < 7000) {
QApplication::processEvents();
QThread::msleep(10);
}
require(condition(), message);
}
void fillNextDialog(const QString &kind, const std::function<void(QDialog *)> &fill)
{
auto *timer = new QTimer(qApp);
timer->setInterval(10);
QObject::connect(timer, &QTimer::timeout, timer, [timer, kind, fill]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (!dialog || dialog->objectName() != kind)
return;
timer->stop();
fill(dialog);
auto *box = dialog->findChild<QDialogButtonBox *>();
require(box != nullptr, "dialog has action buttons");
box->button(QDialogButtonBox::Ok)->click();
timer->deleteLater();
});
timer->start();
QTimer::singleShot(7000, qApp, [guard = QPointer<QTimer>(timer)]() {
if (guard && guard->isActive())
qFatal("AGV editor smoke failed: expected dialog did not open");
});
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Q_INIT_RESOURCE(resources);
RobotClient client;
QWidget window;
auto *layout = new QVBoxLayout(&window);
auto *view = new AgvMapViewWidget(&window);
auto *editor = new AgvMapEditorWidget(&client, view, &window);
layout->addWidget(editor);
layout->addWidget(view, 1);
window.resize(1050, 700);
QImage image(1280, 720, QImage::Format_RGB32);
image.fill(QColor("#eef2f6"));
view->setMapFrame(image, {{"mapId", "demo_map"}, {"dimension", 2},
{"resolution", 0.01}, {"renderScale", 1.0},
{"originX", 0.0}, {"originY", 0.0}, {"originTheta", 0.0}});
bool connected = false;
editor->setContextProvider([&]() {
AgvMapEditorWidget::Context context;
context.connected = connected;
context.demo = true;
context.endpoint = "demo:50052";
context.deviceId = "agv_smoke";
context.mapName = "demo_map";
context.pose = {{"map", "demo_map"}, {"localized", true},
{"x", 1.0}, {"y", 1.0}, {"theta", 0.0}};
return context;
});
QObject::connect(&client, &RobotClient::connectionChanged,
[&connected, editor](bool value, int, const QString &) {
connected = value;
editor->refreshContext();
});
window.show();
client.connectToServer("127.0.0.1", 50052, true);
waitFor([&]() { return connected; }, "Demo connected");
int originalRouteCount = -1;
QObject::connect(&client, &RobotClient::agvMapContentReceived,
[&](quint64 token, const QString &, const QString &, const QString &content,
bool ok, const QString &) {
if (token != 10000)
return;
AgvMapDocument original;
QString error;
require(ok && original.load(content, &error), "original Demo map is valid");
originalRouteCount = original.routes().size();
});
client.requestAgvMapContent(10000, "agv_smoke", "demo_map");
waitFor([&]() { return originalRouteCount >= 0; }, "original route count loaded");
auto *coordinates = editor->findChild<QPushButton *>("agvCoordinateStationButton");
auto *route = editor->findChild<QPushButton *>("agvAddRouteButton");
auto *save = editor->findChild<QPushButton *>("agvSaveMapObjectsButton");
auto *status = editor->findChild<QLabel *>("agvMapEditorStatus");
require(coordinates && route && save && status, "editor controls exist");
const auto addStation = [&](const QString &id, double x, double y) {
fillNextDialog("agvStationDialog", [=](QDialog *dialog) {
dialog->findChild<QLineEdit *>("agvNewStationId")->setText(id);
dialog->findChild<QDoubleSpinBox *>("agvNewStationX")->setValue(x);
dialog->findChild<QDoubleSpinBox *>("agvNewStationY")->setValue(y);
});
coordinates->click();
waitFor([&]() { return status->text().contains(id) && save->isEnabled(); },
"station draft created");
};
addStation("P1", 2.0, 3.0);
fillNextDialog("agvRouteDialog", [](QDialog *dialog) {
dialog->findChild<QLineEdit *>("agvNewRouteId")->setText("HOME_P1");
dialog->findChild<QCheckBox *>("agvNewRouteBidirectional")->setChecked(true);
});
route->click();
view->stationSelected("HOME");
view->stationSelected("P1");
require(save->isEnabled(), "route draft remains unsaved");
int saves = 0;
QObject::connect(editor, &AgvMapEditorWidget::mapSaved, [&]() { ++saves; });
save->click();
waitFor([&]() { return saves == 1; }, "station and two directions saved");
require(!save->isEnabled(), "successful save clears dirty state");
QString downloaded;
bool received = false;
bool uploaded = false;
bool inventoryUpdated = false;
QObject::connect(&client, &RobotClient::agvMapContentReceived,
[&](quint64 token, const QString &, const QString &, const QString &content,
bool ok, const QString &) {
if (token == 10001 || token == 10003) {
require(ok, "verification read succeeded");
downloaded = content;
received = true;
}
});
QObject::connect(&client, &RobotClient::agvMapSaveFinished,
[&](quint64 token, const QString &, const QString &, bool ok, const QString &) {
if (token == 10002) {
require(ok, "simulated independent map edit saved");
uploaded = true;
}
});
QObject::connect(&client, &RobotClient::agvInventoryReceived,
[&](const QStringList &, const QVariantList &stations) {
for (const QVariant &value : stations)
inventoryUpdated |= value.toMap().value("id").toString() == "P1";
});
client.requestAgvMapContent(10001, "agv_smoke", "demo_map");
waitFor([&]() { return received; }, "read saved map back from Demo service");
AgvMapDocument result;
QString error;
require(result.load(downloaded, &error), "saved map is valid SMAP");
require(result.hasStation("P1") && result.routes().size() == originalRouteCount + 2,
"saved station and forward/reverse routes persisted");
client.requestAgvInventory("agv_smoke");
waitFor([&]() { return inventoryUpdated; }, "saved station appears in navigation inventory");
addStation("P2", 4.0, 3.0);
require(result.addStation("REMOTE", 5.0, 6.0, 0.0, &error), "independent station addition");
QString changedMap = result.content();
changedMap.insert(changedMap.indexOf(QLatin1Char('{')) + 1,
QStringLiteral("\"external64\":9007199254740993,"));
client.saveAgvMapContent(10002, "agv_smoke", "demo_map", changedMap);
waitFor([&]() { return uploaded; }, "independent update stored before editor save");
save->click();
waitFor([&]() { return saves == 2; }, "editor rebases additions onto latest map");
received = false;
client.requestAgvMapContent(10003, "agv_smoke", "demo_map");
waitFor([&]() { return received; }, "read merged map");
require(result.load(downloaded, &error), "merged map remains valid");
require(result.hasStation("P1") && result.hasStation("P2") && result.hasStation("REMOTE"),
"both local and independent additions preserved");
require(result.routes().size() == originalRouteCount + 2 && downloaded.contains("9007199254740993"),
"previous routes and unknown integer are preserved");
if (argc > 1)
require(window.grab().save(QString::fromLocal8Bit(argv[1])), "editor screenshot saved");
client.disconnectFromServer();
waitFor([&]() { return !connected; }, "Demo disconnected cleanly");
qInfo("PASS: AGV editor add station, bidirectional route, save, reload and rebase");
return 0;
}

View File

@ -0,0 +1,645 @@
#include "agvmapdocument.h"
#include "agvmapeditorwidget.h"
#include "agvmaprasterizer.h"
#include "agvmapviewwidget.h"
#include "robotclient.h"
#include "cmvr/api/agv_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QApplication>
#include <QCheckBox>
#include <QDateTime>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDoubleSpinBox>
#include <QElapsedTimer>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QPointer>
#include <QPushButton>
#include <QThread>
#include <QTimer>
#include <QVBoxLayout>
#include <chrono>
#include <cmath>
#include <functional>
#include <iostream>
#include <mutex>
#include <vector>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV editor upload integration failed: %s", message);
}
void waitFor(const std::function<bool()> &ready, const char *message)
{
QElapsedTimer timer;
timer.start();
while (!ready() && timer.elapsed() < 7000) {
QApplication::processEvents();
QThread::msleep(2);
}
require(ready(), message);
}
void fillDialog(const QString &kind, const std::function<void(QDialog *)> &fill)
{
auto *timer = new QTimer(qApp);
timer->setInterval(5);
QObject::connect(timer, &QTimer::timeout, timer, [timer, kind, fill]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (!dialog || dialog->objectName() != kind)
return;
timer->stop();
fill(dialog);
dialog->findChild<QDialogButtonBox *>()->button(QDialogButtonBox::Ok)->click();
timer->deleteLater();
});
timer->start();
QTimer::singleShot(7000, qApp, [guard = QPointer<QTimer>(timer)]() {
if (guard && guard->isActive())
qFatal("AGV editor upload integration failed: expected modal did not open");
});
}
QString rootToken(const QString &content, const QString &key)
{
int start = content.indexOf(QLatin1Char('"') + key + QStringLiteral("\":"));
require(start >= 0, "native map contains a requested root token");
start += key.size() + 3;
while (content.at(start).isSpace())
++start;
int depth = 0;
bool quoted = false;
for (int index = start; index < content.size(); ++index) {
const QChar character = content.at(index);
if (quoted) {
if (character == QLatin1Char('\\'))
++index;
else if (character == QLatin1Char('"'))
quoted = false;
} else if (character == QLatin1Char('"')) {
quoted = true;
} else if (character == QLatin1Char('{') || character == QLatin1Char('[')) {
++depth;
} else if (character == QLatin1Char('}') || character == QLatin1Char(']')) {
if (--depth == 0)
return content.mid(start, index - start + 1);
}
}
qFatal("AGV editor upload integration failed: unbalanced root token");
return QString();
}
struct Upload {
cmvr::api::AgvMapCommand::Request request;
qint64 deadlineMs;
};
// This is the ONLY server used by the test. It binds an ephemeral loopback
// port and never forwards map commands to a controller or external service.
class FakeAgvService final : public cmvr::api::AgvService::Service
{
public:
enum Result { Success, ControllerRejected, TransportFailed, AckBeforePersistence,
AckWithoutPersistence, ReformattedPersistence, PersistenceMissingLastRoute,
PersistenceWrongStationName };
FakeAgvService(QString name, QString content)
: m_name(std::move(name)), m_content(std::move(content)) {}
grpc::Status downloadMap(grpc::ServerContext *,
const cmvr::api::AgvMapCommand::Request *request,
cmvr::api::AgvMapCommand::Feedback *response) override
{
std::lock_guard<std::mutex> guard(m_mutex);
m_events.append(QStringLiteral("download:") + QString::fromStdString(request->map_name()));
m_downloads.push_back(*request);
if (!m_pendingContent.isEmpty() && m_pendingOldReads >= 0) {
if (m_pendingOldReads == 0) {
m_content = m_pendingContent;
m_pendingContent.clear();
} else {
--m_pendingOldReads;
}
}
if (m_failRead || QString::fromStdString(request->map_name()) != m_name) {
m_failRead = false;
response->mutable_header()->set_success(false);
response->mutable_header()->set_error_message("fixture latest map read denied");
} else {
response->mutable_header()->set_success(true);
response->set_content(m_content.toUtf8().toStdString());
}
return grpc::Status::OK;
}
grpc::Status uploadMap(grpc::ServerContext *context,
const cmvr::api::AgvMapCommand::Request *request,
cmvr::api::AgvMapCommand::Feedback *response) override
{
std::lock_guard<std::mutex> guard(m_mutex);
const qint64 deadlineMs = std::chrono::duration_cast<std::chrono::milliseconds>(
context->deadline() - std::chrono::system_clock::now()).count();
m_uploads.push_back({*request, deadlineMs});
m_events.append(QStringLiteral("upload:") + QString::fromStdString(request->map_name()));
const Result result = m_nextResult;
m_nextResult = Success;
if (result == TransportFailed)
return grpc::Status(grpc::StatusCode::UNAVAILABLE, "fixture upload transport failed");
if (result == ControllerRejected) {
response->mutable_header()->set_success(false);
response->mutable_header()->set_error_message("SEER ret_code=40050 err_msg=need map header");
} else {
const QString uploaded = QString::fromUtf8(request->content().data(),
static_cast<int>(request->content().size()));
m_pendingContent.clear();
if (result == AckBeforePersistence || result == AckWithoutPersistence) {
m_pendingContent = uploaded;
m_pendingOldReads = result == AckBeforePersistence ? 2 : -1;
} else if (result == ReformattedPersistence) {
m_content = QString::fromUtf8(QJsonDocument::fromJson(uploaded.toUtf8())
.toJson(QJsonDocument::Indented));
} else if (result == PersistenceMissingLastRoute) {
QJsonObject partial = QJsonDocument::fromJson(uploaded.toUtf8()).object();
QJsonArray curves = partial.value("advancedCurveList").toArray();
require(!curves.isEmpty(), "partial-persistence fixture has a route to omit");
curves.removeLast();
partial.insert("advancedCurveList", curves);
m_content = QString::fromUtf8(QJsonDocument(partial).toJson(QJsonDocument::Compact));
} else if (result == PersistenceWrongStationName) {
QJsonObject partial = QJsonDocument::fromJson(uploaded.toUtf8()).object();
QJsonArray points = partial.value("advancedPointList").toArray();
require(!points.isEmpty(), "wrong-name fixture has a station to alter");
QJsonObject point = points.last().toObject();
point.insert("description", "wrong persisted station name");
points.replace(points.size() - 1, point);
partial.insert("advancedPointList", points);
m_content = QString::fromUtf8(QJsonDocument(partial).toJson(QJsonDocument::Compact));
} else {
m_content = uploaded;
}
response->mutable_header()->set_success(true);
}
return grpc::Status::OK;
}
void replaceLatest(const QString &content)
{
std::lock_guard<std::mutex> guard(m_mutex);
m_content = content;
}
void nextResult(Result result)
{
std::lock_guard<std::mutex> guard(m_mutex);
m_nextResult = result;
}
void denyNextRead()
{
std::lock_guard<std::mutex> guard(m_mutex);
m_failRead = true;
}
int downloads()
{
std::lock_guard<std::mutex> guard(m_mutex);
return static_cast<int>(m_downloads.size());
}
int uploads()
{
std::lock_guard<std::mutex> guard(m_mutex);
return static_cast<int>(m_uploads.size());
}
Upload upload(int index)
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_uploads.at(index);
}
QString stored()
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_content;
}
QStringList events()
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_events;
}
private:
std::mutex m_mutex;
QString m_name;
QString m_content;
QString m_pendingContent;
std::vector<cmvr::api::AgvMapCommand::Request> m_downloads;
std::vector<Upload> m_uploads;
QStringList m_events;
Result m_nextResult = Success;
bool m_failRead = false;
int m_pendingOldReads = -1;
};
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Q_INIT_RESOURCE(resources);
require(argc > 1, "pass an already-downloaded native SMAP path; the test never downloads from a vehicle");
QFile source(QString::fromLocal8Bit(argv[1]));
require(source.open(QIODevice::ReadOnly), "local selected native map opens");
const QString native = QString::fromUtf8(source.readAll());
const QJsonObject original = QJsonDocument::fromJson(native.toUtf8()).object();
const QString mapName = original.value("header").toObject().value("mapName").toString();
const QString originalId = original.value("advancedPointList").toArray().first()
.toObject().value("instanceName").toString();
require(!mapName.isEmpty() && !originalId.isEmpty(), "selected map identifies its native header and stations");
const QString headerToken = rootToken(native, "header");
const QString scanToken = rootToken(native, "normalPosList");
const QString lineToken = original.contains("advancedLineList")
? rootToken(native, "advancedLineList") : QString();
FakeAgvService service(mapName, native);
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, "only an ephemeral loopback fake server is started");
RobotClient client;
bool connected = false;
bool editorBusy = false;
int saved = 0;
int failed = 0;
int uploadAcks = 0;
bool injectStaleReadback = false;
bool staleReadbackInjected = false;
int staleAckBaseline = 0;
int staleSavedBaseline = 0;
QString failure;
QString lastDispatchedContent;
QString lastDispatchedMap;
QObject::connect(&client, &RobotClient::connectionChanged,
[&](bool available, int, const QString &) { connected = available; });
QObject::connect(&client, &RobotClient::agvMapSaveRequested,
[&](quint64, const QString &, const QString &name, const QString &content) {
lastDispatchedMap = name;
lastDispatchedContent = content;
});
QObject::connect(&client, &RobotClient::agvMapSaveFinished,
[&](quint64, const QString &, const QString &, bool success, const QString &detail) {
if (!success) {
++failed;
failure = detail;
} else
++uploadAcks;
});
QObject::connect(&client, &RobotClient::agvMapContentRequested,
[&](quint64 token, const QString &requestDevice, const QString &requestMap) {
if (!injectStaleReadback || uploadAcks <= staleAckBaseline)
return;
injectStaleReadback = false;
staleReadbackInjected = true;
// All three responses carry the exact desired new map so accepting
// any stale identity would falsely commit the still-old fixture.
client.agvMapContentReceived(token - 1, requestDevice, requestMap,
lastDispatchedContent, true, "late prior token");
client.agvMapContentReceived(token, requestDevice + "_old", requestMap,
lastDispatchedContent, true, "wrong device");
client.agvMapContentReceived(token, requestDevice, requestMap + "_old",
lastDispatchedContent, true, "wrong map");
require(saved == staleSavedBaseline && editorBusy,
"stale token/device/map verification replies cannot commit the saved draft or unlock editing");
});
client.connectToServer("127.0.0.1", port, false);
waitFor([&]() { return connected; }, "real RobotClient connects only to this loopback fake service");
QWidget window;
auto *layout = new QVBoxLayout(&window);
auto *view = new AgvMapViewWidget(&window);
auto *editor = new AgvMapEditorWidget(&client, view, &window);
layout->addWidget(editor);
layout->addWidget(view);
window.resize(1050, 750);
QImage image;
QVariantMap metadata;
QString error;
require(renderAgvSmap2d(native, image, metadata, error), "actual downloaded scan builds the editor view");
view->setMapFrame(image, metadata);
const QString device = "fixture_upload_device";
QString selectedMap = mapName;
editor->setContextProvider([&]() {
AgvMapEditorWidget::Context context;
context.endpoint = QStringLiteral("127.0.0.1:%1").arg(port);
context.deviceId = device;
context.mapName = selectedMap;
context.connected = connected;
context.demo = false;
return context;
});
QObject::connect(editor, &AgvMapEditorWidget::mapSaved, [&]() { ++saved; });
QObject::connect(editor, &AgvMapEditorWidget::busyChanged, [&](bool value) { editorBusy = value; });
window.show();
editor->setAutoLoadEnabled(true);
auto *coordinate = editor->findChild<QPushButton *>("agvCoordinateStationButton");
auto *route = editor->findChild<QPushButton *>("agvAddRouteButton");
auto *save = editor->findChild<QPushButton *>("agvSaveMapObjectsButton");
auto *undo = editor->findChild<QPushButton *>("agvUndoMapObjectsButton");
auto *status = editor->findChild<QLabel *>("agvMapEditorStatus");
require(coordinate && route && save && undo && status, "actual editor controls are present");
waitFor([&]() { return service.downloads() == 1 && coordinate->isEnabled()
&& status->text().contains(QStringLiteral("地图已读取")); },
"editor initially reads the complete native selected map through RobotClient/gRPC");
const auto addStation = [&](const QString &id) {
fillDialog("agvStationDialog", [=](QDialog *dialog) {
dialog->findChild<QLineEdit *>("agvNewStationId")->setText(id);
dialog->findChild<QLineEdit *>("agvNewStationName")->setText(QStringLiteral("\"本地工位\""));
dialog->findChild<QDoubleSpinBox *>("agvNewStationX")->setValue(1.25);
dialog->findChild<QDoubleSpinBox *>("agvNewStationY")->setValue(0.5);
});
coordinate->click();
require(save->isEnabled() && undo->isEnabled(), "new station is an unsaved editor draft");
};
addStation("LM9001");
fillDialog("agvRouteDialog", [](QDialog *dialog) {
dialog->findChild<QLineEdit *>("agvNewRouteId")->setText("LOCAL_ROUTE");
dialog->findChild<QCheckBox *>("agvNewRouteBidirectional")->setChecked(true);
});
route->click();
view->stationSelected(originalId);
view->stationSelected("LM9001");
AgvMapDocument concurrent;
require(concurrent.load(native, &error)
&& concurrent.addStation("REMOTE_FROM_LATEST", -1.0, 0.75, 0, &error),
"prepare a concurrent server-side station update after the editor's first read");
QString latest = concurrent.content();
latest.insert(latest.lastIndexOf(QLatin1Char('}')),
QStringLiteral(",\"serverUnknown\":{\"uint64\":18446744073709551615,\"flag\":\"preserve latest\"}"));
service.replaceLatest(latest);
save->click();
waitFor([&]() { return saved == 1 && service.uploads() == 1 && !save->isEnabled(); },
"editor reads latest, merges local additions and receives successful real-client fake-gRPC upload response");
const auto verifyUpload = [&](int index) {
const Upload upload = service.upload(index);
const auto &request = upload.request;
const QString content = QString::fromUtf8(request.content().data(), static_cast<int>(request.content().size()));
const QJsonDocument json = QJsonDocument::fromJson(content.toUtf8());
require(request.map_name() == mapName.toStdString() && request.header().device_id() == device.toStdString()
&& request.header().valid_for_ms() == 10000 && !request.header().command_id().empty()
&& request.header().timestamp().seconds() > 0
&& std::abs(request.header().timestamp().seconds() - QDateTime::currentSecsSinceEpoch()) < 30,
"actual protobuf request retains target map/device and valid upload command header");
// gRPC encodes a rounded relative wire timeout; this bundled Windows
// runtime reports roughly 100 ms beyond the exact client deadline.
// valid_for_ms above remains exactly 10000, and this check excludes
// an unbounded or materially longer transport timeout.
if (!(upload.deadlineMs > 0 && upload.deadlineMs <= 10200))
qWarning("captured upload deadline remaining=%lld ms", static_cast<long long>(upload.deadlineMs));
require(upload.deadlineMs > 0 && upload.deadlineMs <= 10200,
"actual gRPC upload carries the bounded ten-second deadline");
require(json.isObject() && content.trimmed().startsWith('{')
&& json.object().value("header") == original.value("header")
&& content.contains(headerToken) && content.contains(scanToken) && content.contains(lineToken),
"actual request.content has root native header, all scan and advanced-line tokens unchanged");
require(!json.object().contains("map_content") && !json.object().contains("content")
&& !json.object().contains("advanced_point_list")
&& content.contains("18446744073709551615"),
"actual request.content is the complete native camel SMAP, never an escaped wrapper or lossy root reserialization");
AgvMapDocument parsed;
require(parsed.load(content, &error) && parsed.hasStation("REMOTE_FROM_LATEST")
&& parsed.hasStation("LM9001"), "fresh server objects survive alongside local additions");
return content;
};
const QString acceptedContent = verifyUpload(0);
require(acceptedContent == lastDispatchedContent && lastDispatchedMap == mapName,
"editor-dispatched text equals captured protobuf content byte-for-byte");
const QJsonObject accepted = QJsonDocument::fromJson(acceptedContent.toUtf8()).object();
require(accepted.value("normalPosList").toArray().size() == original.value("normalPosList").toArray().size()
&& accepted.value("advancedPointList").toArray().size() == original.value("advancedPointList").toArray().size() + 2
&& accepted.value("advancedCurveList").toArray().size() == original.value("advancedCurveList").toArray().size() + 2,
"native map retains its complete scan and merges the concurrent station plus local station/bidirectional routes");
require(service.events() == QStringList{QStringLiteral("download:") + mapName,
QStringLiteral("download:") + mapName, QStringLiteral("upload:") + mapName,
QStringLiteral("download:") + mapName},
"real save sequence is initial read, read-latest, upload and persistence readback of the same map");
if (argc > 2) {
QFile dump(QString::fromLocal8Bit(argv[2]));
require(dump.open(QIODevice::WriteOnly) && dump.write(acceptedContent.toUtf8()) == acceptedContent.toUtf8().size(),
"captured actual protobuf upload payload is optionally dumped locally");
}
qInfo("PASS: editor -> RobotClient -> loopback AgvService captures complete native selected map and read-latest merge");
addStation("LM9002");
service.nextResult(FakeAgvService::ControllerRejected);
save->click();
waitFor([&]() { return failed == 1 && save->isEnabled() && service.uploads() == 2; },
"business response failure returns to the editor with its draft available for retry");
verifyUpload(1);
require(saved == 1 && undo->isEnabled() && failure.contains("ret_code=40050")
&& status->text().contains("need map header"), "controller rejection is not falsely marked as saved");
AgvMapDocument persisted;
require(persisted.load(service.stored(), &error) && !persisted.hasStation("LM9002"),
"rejected local fake upload has no server-side persistence");
save->click();
waitFor([&]() { return saved == 2 && service.uploads() == 3 && !save->isEnabled(); },
"retry after business rejection re-reads, merges and saves through the actual client");
verifyUpload(2);
require(persisted.load(service.stored(), &error) && persisted.hasStation("LM9002"),
"successful retry persists the originally rejected draft in the fake service");
addStation("LM9003");
service.nextResult(FakeAgvService::TransportFailed);
save->click();
waitFor([&]() { return failed == 2 && service.uploads() == 4 && save->isEnabled(); },
"transport response failure preserves local editing and completes the real client callback");
verifyUpload(3);
require(saved == 2 && failure.contains("fixture upload transport failed") && undo->isEnabled(),
"transport failure never emits editor mapSaved or discards the draft");
addStation("LM9004");
service.denyNextRead();
const int oldUploads = service.uploads();
save->click();
waitFor([&]() { return save->isEnabled() && status->text().contains("fixture latest map read denied"); },
"read-latest failure returns an actionable save failure to the editor");
require(service.uploads() == oldUploads && saved == 2 && undo->isEnabled(),
"failed latest-map read prevents upload and preserves the unsaved local changes");
const int beforeDelayedSaves = saved;
const int beforeDelayedAcks = uploadAcks;
const int beforeDelayedReads = service.downloads();
const int beforeDelayedUploads = service.uploads();
staleAckBaseline = uploadAcks;
staleSavedBaseline = saved;
injectStaleReadback = true;
service.nextResult(FakeAgvService::AckBeforePersistence);
save->click();
waitFor([&]() { return uploadAcks == beforeDelayedAcks + 1
&& service.downloads() >= beforeDelayedReads + 2; },
"upload ACK is delivered before the fake service exposes the saved objects");
require(saved == beforeDelayedSaves && editorBusy && !save->isEnabled()
&& !undo->isEnabled() && !coordinate->isEnabled() && staleReadbackInjected,
"accepted upload with an old readback retains the dirty draft and busy lock rather than reporting saved");
const int uploadsAfterAck = service.uploads();
save->click();
require(service.uploads() == uploadsAfterAck, "repeated save click while verifying does not send another upload");
waitFor([&]() { return saved == beforeDelayedSaves + 1 && !editorBusy; },
"two stale readbacks are retried read-only until the actual updated map is downloadable");
require(service.uploads() == beforeDelayedUploads + 1
&& service.downloads() == beforeDelayedReads + 4
&& !save->isEnabled() && !undo->isEnabled(),
"delayed persistence uses one upload, one fresh pre-save read and exactly three verification reads");
require(persisted.load(service.stored(), &error) && persisted.hasStation("LM9003")
&& persisted.hasStation("LM9004"),
"all retained station drafts were actually persisted before editor mapSaved");
qInfo("PASS: upload ACK precedes persistence; old maps trigger bounded reads, never duplicate uploads or premature saved state");
addStation("LM9005");
const int beforeFormattedSaves = saved;
const int beforeFormattedUploads = service.uploads();
service.nextResult(FakeAgvService::ReformattedPersistence);
save->click();
waitFor([&]() { return saved == beforeFormattedSaves + 1 && !editorBusy; },
"semantically identical persisted objects confirm despite harmless JSON reformatting");
require(service.uploads() == beforeFormattedUploads + 1
&& service.stored() != lastDispatchedContent
&& persisted.load(service.stored(), &error) && persisted.hasStation("LM9005")
&& !save->isEnabled() && !undo->isEnabled(),
"verification compares edited station semantics rather than byte-for-byte full JSON text");
qInfo("PASS: JSON formatting changes do not cause false persistence mismatch");
addStation("LM9006");
const int beforeUnpersistedSaves = saved;
const int beforeUnpersistedAcks = uploadAcks;
const int beforeUnpersistedReads = service.downloads();
const int beforeUnpersistedUploads = service.uploads();
service.nextResult(FakeAgvService::AckWithoutPersistence);
save->click();
waitFor([&]() { return uploadAcks == beforeUnpersistedAcks + 1
&& service.downloads() >= beforeUnpersistedReads + 2; },
"ACK-only fixture starts persistence verification");
require(saved == beforeUnpersistedSaves && editorBusy && !save->isEnabled(),
"ACK-only save has no early mapSaved notification");
waitFor([&]() { return !editorBusy && save->isEnabled(); },
"bounded unchanged readbacks finish with an editable retained draft");
require(saved == beforeUnpersistedSaves && undo->isEnabled()
&& service.uploads() == beforeUnpersistedUploads + 1
&& service.downloads() > beforeUnpersistedReads + 1
&& service.downloads() <= beforeUnpersistedReads + 7,
"unchanged persistence has at most six readbacks, one upload and no draft commit");
require(persisted.load(service.stored(), &error) && !persisted.hasStation("LM9006"),
"fixture proves accepted upload and persisted map are independent");
const int readsAfterVerificationFailure = service.downloads();
const int uploadsAfterVerificationFailure = service.uploads();
for (int i = 0; i < 20; ++i)
editor->refreshContext();
require(service.downloads() == readsAfterVerificationFailure
&& service.uploads() == uploadsAfterVerificationFailure,
"context polling after unconfirmed persistence never starts a hidden upload or another verification loop");
const auto draftFrame = [&]() {
QVariantMap currentMetadata = metadata;
currentMetadata.insert("mapId", selectedMap);
view->setMapFrame(image, currentMetadata);
editor->refreshContext();
};
editor->setAutoLoadEnabled(false);
selectedMap = QStringLiteral("unloaded_other_map");
draftFrame();
selectedMap = mapName;
draftFrame();
require(save->isEnabled() && undo->isEnabled() && saved == beforeUnpersistedSaves
&& service.uploads() == uploadsAfterVerificationFailure,
"switching away and back once retains the unconfirmed draft without implicit persistence");
qInfo("PASS: ACK without persistence times out boundedly and retains draft across one map revisit without re-upload");
const int beforeRetrySaves = saved;
service.nextResult(FakeAgvService::Success);
save->click();
waitFor([&]() { return saved == beforeRetrySaves + 1 && !editorBusy; },
"operator can explicitly retry the retained unconfirmed draft and verify its persistence");
require(service.uploads() == uploadsAfterVerificationFailure + 1
&& persisted.load(service.stored(), &error) && persisted.hasStation("LM9006")
&& !save->isEnabled() && !undo->isEnabled(),
"one explicit retry persists once and only then clears the draft");
addStation("LM9007");
fillDialog("agvRouteDialog", [](QDialog *dialog) {
dialog->findChild<QLineEdit *>("agvNewRouteId")->setText("VERIFY_BOTH_DIRECTIONS");
dialog->findChild<QCheckBox *>("agvNewRouteBidirectional")->setChecked(true);
});
route->click();
view->stationSelected(originalId);
view->stationSelected("LM9007");
const int beforePartialSaves = saved;
const int beforePartialUploads = service.uploads();
service.nextResult(FakeAgvService::PersistenceMissingLastRoute);
save->click();
waitFor([&]() { return service.uploads() == beforePartialUploads + 1
&& !editorBusy && save->isEnabled(); },
"persisted station and forward route cannot confirm a missing requested reverse route");
require(saved == beforePartialSaves && undo->isEnabled()
&& persisted.load(service.stored(), &error) && persisted.hasStation("LM9007"),
"partial persistence retains the station and route draft instead of reporting a complete save");
const auto hasRoute = [](const AgvMapDocument &document, const QString &id) {
for (const QVariant &value : document.routes()) {
if (value.toMap().value("id").toString() == id)
return true;
}
return false;
};
require(hasRoute(persisted, "VERIFY_BOTH_DIRECTIONS")
&& !hasRoute(persisted, "VERIFY_BOTH_DIRECTIONS_reverse"),
"fake persistence independently proves exactly one requested direction is missing");
service.nextResult(FakeAgvService::Success);
save->click();
waitFor([&]() { return saved == beforePartialSaves + 1 && !editorBusy; },
"explicit retry idempotently merges already-persisted matching station and forward route");
require(service.uploads() == beforePartialUploads + 2
&& persisted.load(service.stored(), &error)
&& hasRoute(persisted, "VERIFY_BOTH_DIRECTIONS")
&& hasRoute(persisted, "VERIFY_BOTH_DIRECTIONS_reverse")
&& !save->isEnabled() && !undo->isEnabled(),
"retry adds the missing direction exactly once and confirms the complete map before commit");
qInfo("PASS: partial route persistence cannot masquerade as saved; explicit retry safely reuses matching persisted draft objects");
addStation("LM9008");
const int beforeWrongNameSaves = saved;
const int beforeWrongNameUploads = service.uploads();
service.nextResult(FakeAgvService::PersistenceWrongStationName);
save->click();
waitFor([&]() { return service.uploads() == beforeWrongNameUploads + 1
&& !editorBusy && save->isEnabled(); },
"matching station identity and position cannot confirm a wrong persisted display name");
require(saved == beforeWrongNameSaves && undo->isEnabled()
&& persisted.load(service.stored(), &error) && persisted.hasStation("LM9008"),
"wrong persisted station name retains the requested local name as an unsaved draft");
bool wrongNameActuallyStored = false;
for (const QVariant &value : persisted.stations()) {
const QVariantMap point = value.toMap();
if (point.value("id").toString() == "LM9008")
wrongNameActuallyStored = point.value("description").toString()
== "wrong persisted station name";
}
require(wrongNameActuallyStored && service.uploads() == beforeWrongNameUploads + 1,
"fixture proves mismatched display name is diagnosed without another automatic write");
qInfo("PASS: wrong persisted station display name never clears requested local name or reports saved");
client.disconnectFromServer();
waitFor([&]() { return !connected; }, "test client disconnects from its local fake service");
server->Shutdown();
server->Wait();
qInfo("PASS: real-client upload controller rejection/retry, transport failure and read-latest failure; no vehicle writes");
std::cout << "PASS AGV save readback integration: saved=" << saved
<< " uploads=" << service.uploads() << " downloads=" << service.downloads()
<< "; delayed/absent/partial persistence, stale identities, JSON formatting,"
" route directions, display names and explicit idempotent retry checked;"
" loopback only, no vehicle writes" << std::endl;
return 0;
}

View File

@ -0,0 +1,260 @@
#include "agvmapdocument.h"
#include "agvmaprasterizer.h"
#include <QCoreApplication>
#include <QColor>
#include <QDebug>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QPoint>
#include <algorithm>
#include <cmath>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV map rasterizer test failed: %s", message);
}
QString text(const QJsonObject &root)
{
return QString::fromUtf8(QJsonDocument(root).toJson(QJsonDocument::Compact));
}
QJsonObject position(double x, double y)
{
return {{"x", x}, {"y", y}};
}
QJsonObject fixture(bool camel)
{
const auto key = [camel](const char *snake, const char *mixed) {
return QString::fromLatin1(camel ? mixed : snake);
};
const QJsonObject home{{key("class_name", "className"), "LandMark"},
{key("instance_name", "instanceName"), "HOME"},
{"description", QStringLiteral("\"起点1\"")}, {"pos", position(0, 0)}};
const QJsonObject end{{key("class_name", "className"), "ChargePoint"},
{key("instance_name", "instanceName"), "END"},
{"description", QStringLiteral("充电点")}, {"pos", position(4, 0)}, {"dir", 0.3}};
const QJsonObject curve{{key("class_name", "className"), "BezierPath"},
{key("instance_name", "instanceName"), "HOME-END"},
{key("start_pos", "startPos"), home},
{key("end_pos", "endPos"), end},
{key("control_pos1", "controlPos1"), position(1, 2)},
{key("control_pos2", "controlPos2"), position(3, 2)}};
return {{"header", QJsonObject{{key("map_type", "mapType"), "2D-Map"},
{key("map_name", "mapName"), "raster-test"}, {"resolution", 0.5},
{key("min_pos", "minPos"), position(-1, -2)},
{key("max_pos", "maxPos"), position(4, 5)}}},
{key("normal_pos_list", "normalPosList"),
QJsonArray{position(-3, -4), position(6, 7), QJsonObject{{"y", 1}}, QJsonObject()}},
{key("advanced_point_list", "advancedPointList"), QJsonArray{home, end}},
{key("advanced_curve_list", "advancedCurveList"), QJsonArray{curve}}};
}
void requireScanVisible(const QJsonArray &scan, const QImage &image, const QVariantMap &metadata)
{
const double resolution = metadata.value("resolution").toDouble();
const double scale = metadata.value("renderScale").toDouble();
const double originX = metadata.value("originX").toDouble();
const double originY = metadata.value("originY").toDouble();
for (const QJsonValue &value : scan) {
const QJsonObject point = value.toObject();
const double x = (point.value("x").toDouble() - originX) / resolution * scale;
const double y = (point.value("y").toDouble() - originY) / resolution * scale;
require(x >= 0.0 && x < image.width() && y >= 0.0 && y < image.height(),
"every scan sample, including both extrema, falls inside the raster extent");
const QPoint pixel(std::max(0, std::min(image.width() - 1, static_cast<int>(std::floor(x)))),
std::max(0, std::min(image.height() - 1,
static_cast<int>(std::floor(image.height() - y)))));
require(image.pixelColor(pixel).alpha() > 0, "every occupied sample remains visible after aggregation");
}
}
int occupiedCount(const QImage &image)
{
int count = 0;
for (int y = 0; y < image.height(); ++y) {
const QRgb *line = reinterpret_cast<const QRgb *>(image.constScanLine(y));
for (int x = 0; x < image.width(); ++x)
count += qAlpha(line[x]) > 0;
}
return count;
}
void testNamingAndCompleteBounds(bool camel)
{
const QJsonObject root = fixture(camel);
const QString content = text(root);
QImage image;
QVariantMap metadata;
QString error;
require(renderAgvSmap2d(content, image, metadata, error), "snake/camel SMAP renders successfully");
require(error.isEmpty() && image.format() == QImage::Format_ARGB32_Premultiplied,
"successful output has transparent ARGB format and no stale error");
require(metadata.value("originX").toDouble() == -3.0
&& metadata.value("originY").toDouble() == -4.0
&& metadata.value("originTheta").toDouble() == 0.0,
"world AABB includes scan outliers outside the header");
require(metadata.value("sourceWidth").toInt() == 19 && metadata.value("sourceHeight").toInt() == 23
&& metadata.value("renderScale").toDouble() == 1.0 && image.size() == QSize(19, 23),
"inclusive extrema occupy cells without changing small-map resolution");
require(metadata.value("mapId").toString() == "raster-test"
&& metadata.value("dimension").toInt() == 2 && metadata.value("source").toString() == "raw-smap",
"metadata identifies the SMAP map and coordinate system");
requireScanVisible(root.value(camel ? "normalPosList" : "normal_pos_list").toArray(), image, metadata);
require(occupiedCount(image) < image.width() * image.height() / 10,
"unobserved/free cells remain transparent rather than being invented as occupancy");
AgvMapDocument document;
require(document.load(content, &error), "fixture is an editable map");
require(metadata.value("stations").toList() == document.stations()
&& metadata.value("routes").toList() == document.routes(),
"names, types, route endpoint IDs and sampled Bezier geometry use the existing document reader");
const QVariantList stations = metadata.value("stations").toList();
require(stations.first().toMap().value("name").toString() == QStringLiteral("\"起点1\"")
&& stations.last().toMap().value("type").toString() == "ChargePoint",
"literal station names and charging-point type survive rendering");
const QVariantList routePoints = metadata.value("routes").toList().first().toMap().value("points").toList();
require(routePoints.size() == 33 && routePoints.at(16).toMap().value("y").toDouble() > 1.0,
"curved route geometry is preserved instead of replacing it with a straight line");
}
void testLargeMapAndHeaderCoverage()
{
QJsonObject root = fixture(false);
QJsonObject header = root.value("header").toObject();
header.insert("resolution", 0.001);
header.insert("min_pos", position(-10000, -5000));
header.insert("max_pos", position(10000, 5000));
root.insert("header", header);
const QJsonArray scan{position(-10000, -5000), position(10000, 5000),
position(-10000, 5000), position(10000, -5000), position(0, 0)};
root.insert("normal_pos_list", scan);
QImage image;
QVariantMap metadata;
QString error;
require(renderAgvSmap2d(text(root), image, metadata, error), "large virtual grid renders without allocating the source grid");
require(image.width() == 1600 && image.height() <= 1000 && image.sizeInBytes() <= 1600 * 1000 * 4,
"image allocation is bounded to 1600 by 1000 ARGB pixels");
require(metadata.value("sourceWidth").toInt() == 20000001
&& metadata.value("sourceHeight").toInt() == 10000001
&& metadata.value("renderScale").toDouble() < 1.0,
"original dimensions and uniform render scale are retained");
requireScanVisible(scan, image, metadata);
require(occupiedCount(image) == 5, "large-map aggregation keeps all separated corner and center samples");
// A larger header must remain covered even when all points are near HOME.
root.insert("normal_pos_list", QJsonArray{position(0, 0)});
require(renderAgvSmap2d(text(root), image, metadata, error), "header-only margins render successfully");
require(metadata.value("originX").toDouble() == -10000.0
&& metadata.value("originY").toDouble() == -5000.0
&& metadata.value("sourceWidth").toInt() == 20000001,
"scan bounds never crop larger header extents");
}
void testSemanticOnlyAndOmittedArrays()
{
QJsonObject root = fixture(true);
root.remove("normalPosList");
QJsonObject header = root.value("header").toObject();
header.remove("minPos");
header.remove("maxPos");
root.insert("header", header);
QImage image;
QVariantMap metadata;
QString error;
require(renderAgvSmap2d(text(root), image, metadata, error), "semantic-only map can render without scan/bounds");
require(metadata.value("semanticOnly").toBool() && occupiedCount(image) == 0
&& metadata.value("stations").toList().size() == 2 && metadata.value("routes").toList().size() == 1,
"semantic-only output stays transparent and retains navigation objects");
require(image.width() > 1 && image.height() > 1, "semantic positions provide useful map extents");
root.remove("advancedPointList");
root.remove("advancedCurveList");
require(renderAgvSmap2d(text(root), image, metadata, error), "empty protobuf semantic arrays may be omitted");
require(image.size() == QSize(1, 1) && occupiedCount(image) == 0
&& metadata.value("stations").toList().isEmpty(), "empty valid map has a minimal transparent frame");
}
void reject(const QString &content)
{
QImage image(2, 2, QImage::Format_ARGB32);
image.fill(Qt::white);
QVariantMap metadata{{"oldMap", "stale"}};
QString error;
require(!renderAgvSmap2d(content, image, metadata, error), "invalid SMAP is rejected");
require(image.isNull() && metadata.isEmpty() && !error.isEmpty(), "failure clears old image/metadata and explains the error");
}
void testInvalidInputs()
{
reject("not JSON");
QJsonObject root = fixture(false);
QJsonObject header = root.value("header").toObject();
header.insert("resolution", 0);
root.insert("header", header);
reject(text(root));
header.insert("resolution", "0.5");
root.insert("header", header);
reject(text(root));
root = fixture(false);
root.insert("normal_pos_list", QJsonObject());
reject(text(root));
root.insert("normal_pos_list", QJsonArray{QJsonObject{{"x", QJsonValue(QJsonValue::Null)}, {"y", 0}}});
reject(text(root));
root = fixture(false);
header = root.value("header").toObject();
header.insert("min_pos", position(5, 6));
root.insert("header", header);
reject(text(root));
header.remove("max_pos");
root.insert("header", header);
reject(text(root));
header.insert("min_pos", position(-1e308, -1e308));
header.insert("max_pos", position(1e308, 1e308));
header.insert("resolution", 1e-300);
root.insert("header", header);
reject(text(root));
}
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
testNamingAndCompleteBounds(false);
testNamingAndCompleteBounds(true);
testLargeMapAndHeaderCoverage();
testSemanticOnlyAndOmittedArrays();
testInvalidInputs();
if (argc > 1) {
QFile source(QString::fromLocal8Bit(argv[1]));
require(source.open(QIODevice::ReadOnly), "optional real SMAP fixture opens locally");
const QString content = QString::fromUtf8(source.readAll());
QImage image;
QVariantMap metadata;
QString error;
require(renderAgvSmap2d(content, image, metadata, error), "real downloaded camelCase SMAP renders");
const QJsonObject root = QJsonDocument::fromJson(content.toUtf8()).object();
const QJsonArray scan = root.value(root.contains("normalPosList") ? "normalPosList" : "normal_pos_list").toArray();
requireScanVisible(scan, image, metadata);
require(image.width() <= 1600 && image.height() <= 1000 && occupiedCount(image) > 0,
"real scan produces a bounded non-empty occupancy image");
AgvMapDocument document;
require(document.load(content, &error)
&& metadata.value("stations").toList() == document.stations()
&& metadata.value("routes").toList() == document.routes(),
"real SMAP station and route metadata matches the editor exactly");
if (argc > 2)
require(image.save(QString::fromLocal8Bit(argv[2])), "real SMAP raster preview saved");
qInfo().nospace() << "PASS real SMAP: image=" << image.width() << "x" << image.height()
<< " resolution=" << metadata.value("resolution").toDouble()
<< " scan=" << scan.size() << " stations=" << document.stations().size()
<< " routes=" << document.routes().size();
}
qInfo("PASS: SMAP snake/camel raster, complete/extreme bounds, memory limit, semantic-only maps, invalid-input cleanup and document metadata");
return 0;
}

View File

@ -0,0 +1,644 @@
#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;
}

View File

@ -0,0 +1,683 @@
#include "agvmapviewwidget.h"
#include <QApplication>
#include <QHelpEvent>
#include <QLineF>
#include <QMouseEvent>
#include <QPainter>
#include <QPolygonF>
#include <QSignalSpy>
#include <QToolTip>
#include <QtTest>
#include <QtMath>
#include <limits>
namespace {
QVariantMap mapMetadata()
{
return {{QStringLiteral("mapId"), QStringLiteral("rotated-map")},
{QStringLiteral("dimension"), 2},
{QStringLiteral("originX"), 5.0},
{QStringLiteral("originY"), -3.0},
{QStringLiteral("originTheta"), qDegreesToRadians(90.0)},
{QStringLiteral("resolution"), 0.2},
{QStringLiteral("renderScale"), 0.5}};
}
void prepareView(AgvMapViewWidget &view)
{
// The map viewport is 800x600 after reserving margins and the bottom ruler.
view.resize(824, 652);
QImage image(400, 300, QImage::Format_RGB32);
image.fill(QColor(QStringLiteral("#f8fafc")));
view.setMapFrame(image, mapMetadata());
view.show();
QApplication::processEvents();
}
void mouseEvent(AgvMapViewWidget &view, QEvent::Type type,
const QPoint &position, Qt::MouseButton button,
Qt::MouseButtons buttons)
{
QMouseEvent event(type, QPointF(position), button, buttons, Qt::NoModifier);
QApplication::sendEvent(&view, &event);
}
void click(AgvMapViewWidget &view, const QPoint &position)
{
mouseEvent(view, QEvent::MouseButtonPress, position,
Qt::LeftButton, Qt::LeftButton);
mouseEvent(view, QEvent::MouseButtonRelease, position,
Qt::LeftButton, Qt::NoButton);
}
bool nearPoint(const QPointF &actual, const QPointF &expected)
{
return QLineF(actual, expected).length() < 1e-8;
}
QPointF widgetPointForWorld(const AgvMapViewWidget &view, const QPointF &world)
{
QPointF origin;
QPointF horizontal;
QPointF vertical;
if (!view.widgetToWorld(QPointF(100, 100), &origin)
|| !view.widgetToWorld(QPointF(200, 100), &horizontal)
|| !view.widgetToWorld(QPointF(100, 200), &vertical))
return QPointF(-1000, -1000);
horizontal = (horizontal - origin) / 100.0;
vertical = (vertical - origin) / 100.0;
const QPointF delta = world - origin;
const double determinant = horizontal.x() * vertical.y()
- vertical.x() * horizontal.y();
return QPointF(100 + (delta.x() * vertical.y() - vertical.x() * delta.y()) / determinant,
100 + (horizontal.x() * delta.y() - delta.x() * horizontal.y()) / determinant);
}
}
class AgvMapViewWidgetTest : public QObject
{
Q_OBJECT
private slots:
void projectsRotatedAndDownsampledMap();
void keepsCoordinatesDuringZoomAndPan();
void rejectsInvalidAndThreeDimensionalMaps();
void distinguishesClickFromDrag();
void selectsStationsWithinScreenRadius();
void acceptsCanvasPointsOutsideReceivedImage();
void fitsMapAndObjectsOutsideImage();
void keepsBottomWallAboveRulerOnShortCanvas();
void keepsManualViewDuringTelemetryUpdates();
void paintsReferenceStationRouteAndGridStyle();
void paintsDirectionsOnSampledRoutes_data();
void paintsDirectionsOnSampledRoutes();
void usesMetadataObjectsUntilDocumentOverridesThem();
void displaysStationNamesWithoutChangingIds();
void elidesLongStationNames();
void paintsEditorOverlays();
};
void AgvMapViewWidgetTest::projectsRotatedAndDownsampledMap()
{
AgvMapViewWidget view;
prepareView(view);
QCOMPARE(view.mapId(), QStringLiteral("rotated-map"));
QPointF world;
// The fitted image starts at (12,12), with 2 screen pixels per image pixel.
// Image (100,150) is grid-local (40,60) metres; a 90 degree origin rotates
// it to world (-55,37) after adding the translated origin (5,-3).
QVERIFY(view.widgetToWorld(QPointF(212, 312), &world));
QVERIFY(nearPoint(world, QPointF(-55, 37)));
QVERIFY(view.widgetToWorld(QPointF(12, 612), &world));
QVERIFY(nearPoint(world, QPointF(5, -3)));
}
void AgvMapViewWidgetTest::keepsCoordinatesDuringZoomAndPan()
{
AgvMapViewWidget view;
prepareView(view);
const QPointF anchor(view.width() * 0.5, (view.height() - 28) * 0.5);
QPointF worldBefore;
QVERIFY(view.widgetToWorld(anchor, &worldBefore));
view.zoomIn();
QPointF worldAfter;
QVERIFY(view.widgetToWorld(anchor, &worldAfter));
QVERIFY(nearPoint(worldAfter, worldBefore));
const QPointF zoomedPoint = anchor + (QPointF(212, 312) - anchor) * 1.25;
QVERIFY(view.widgetToWorld(zoomedPoint, &worldAfter));
QVERIFY(nearPoint(worldAfter, QPointF(-55, 37)));
view.setEditMode(AgvMapViewWidget::AddStationMode);
const QPoint dragStart(300, 250);
const QPoint delta(80, -40);
mouseEvent(view, QEvent::MouseButtonPress, dragStart,
Qt::RightButton, Qt::RightButton);
mouseEvent(view, QEvent::MouseMove, dragStart + delta,
Qt::NoButton, Qt::RightButton);
mouseEvent(view, QEvent::MouseButtonRelease, dragStart + delta,
Qt::RightButton, Qt::NoButton);
QVERIFY(view.widgetToWorld(zoomedPoint + delta, &worldAfter));
QVERIFY(nearPoint(worldAfter, QPointF(-55, 37)));
view.resetView();
QVERIFY(view.widgetToWorld(QPointF(212, 312), &worldAfter));
QVERIFY(nearPoint(worldAfter, QPointF(-55, 37)));
}
void AgvMapViewWidgetTest::rejectsInvalidAndThreeDimensionalMaps()
{
AgvMapViewWidget view;
prepareView(view);
QPointF world(42, 42);
QVERIFY(!view.widgetToWorld(QPointF(-100, -100), &world));
QCOMPARE(world, QPointF(42, 42));
QVERIFY(!view.widgetToWorld(QPointF(212, 312), nullptr));
QVERIFY(!view.widgetToWorld(
QPointF(std::numeric_limits<double>::quiet_NaN(), 312), &world));
QImage image(400, 300, QImage::Format_RGB32);
const QList<QString> fields = {QStringLiteral("originX"), QStringLiteral("originY"),
QStringLiteral("originTheta"), QStringLiteral("resolution"),
QStringLiteral("renderScale")};
for (const QString &field : fields) {
QVariantMap metadata = mapMetadata();
metadata.insert(field, std::numeric_limits<double>::infinity());
view.setMapFrame(image, metadata);
QVERIFY2(!view.widgetToWorld(QPointF(212, 312), &world), qPrintable(field));
}
QVariantMap metadata = mapMetadata();
metadata.insert(QStringLiteral("resolution"), 0.0);
view.setMapFrame(image, metadata);
QVERIFY(!view.widgetToWorld(QPointF(212, 312), &world));
metadata = mapMetadata();
metadata.insert(QStringLiteral("dimension"), 3);
view.setMapFrame(image, metadata);
QVERIFY(!view.widgetToWorld(QPointF(212, 312), &world));
view.setEditMode(AgvMapViewWidget::AddStationMode);
QSignalSpy selected(&view, &AgvMapViewWidget::mapPointSelected);
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 0);
}
void AgvMapViewWidgetTest::distinguishesClickFromDrag()
{
AgvMapViewWidget view;
prepareView(view);
QSignalSpy selected(&view, &AgvMapViewWidget::mapPointSelected);
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 0);
view.setEditMode(AgvMapViewWidget::AddStationMode);
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 1);
QVERIFY(qAbs(selected.at(0).at(0).toDouble() + 55.0) < 1e-8);
QVERIFY(qAbs(selected.at(0).at(1).toDouble() - 37.0) < 1e-8);
const QPoint press(212, 312);
const QPoint jitter(qMax(0, QApplication::startDragDistance() - 1), 0);
mouseEvent(view, QEvent::MouseButtonPress, press,
Qt::LeftButton, Qt::LeftButton);
mouseEvent(view, QEvent::MouseMove, press + jitter,
Qt::NoButton, Qt::LeftButton);
mouseEvent(view, QEvent::MouseButtonRelease, press + jitter,
Qt::LeftButton, Qt::NoButton);
QCOMPARE(selected.count(), 2);
QPointF world;
QVERIFY(view.widgetToWorld(press, &world));
QVERIFY(nearPoint(world, QPointF(-55, 37)));
const QPoint delta(QApplication::startDragDistance() + 30, 0);
mouseEvent(view, QEvent::MouseButtonPress, press,
Qt::LeftButton, Qt::LeftButton);
mouseEvent(view, QEvent::MouseMove, press + delta,
Qt::NoButton, Qt::LeftButton);
mouseEvent(view, QEvent::MouseButtonRelease, press + delta,
Qt::LeftButton, Qt::NoButton);
QCOMPARE(selected.count(), 2);
QVERIFY(view.widgetToWorld(press + delta, &world));
QVERIFY(nearPoint(world, QPointF(-55, 37)));
}
void AgvMapViewWidgetTest::selectsStationsWithinScreenRadius()
{
AgvMapViewWidget view;
prepareView(view);
view.setEditorObjects(
{QVariantMap{{QStringLiteral("id"), QStringLiteral("A")},
{QStringLiteral("x"), -55.0}, {QStringLiteral("y"), 37.0}},
QVariantMap{{QStringLiteral("id"), QStringLiteral("B")},
{QStringLiteral("x"), -55.0}, {QStringLiteral("y"), 47.0}}}, {});
view.setEditMode(AgvMapViewWidget::AddRouteMode);
QSignalSpy selected(&view, &AgvMapViewWidget::stationSelected);
QSignalSpy points(&view, &AgvMapViewWidget::mapPointSelected);
click(view, QPoint(225, 312));
QCOMPARE(selected.count(), 1);
QCOMPARE(selected.at(0).at(0).toString(), QStringLiteral("A"));
click(view, QPoint(226, 312));
QCOMPARE(selected.count(), 2);
click(view, QPoint(227, 312));
QCOMPARE(selected.count(), 2);
click(view, QPoint(252, 312));
QCOMPARE(selected.count(), 3);
QCOMPARE(selected.at(2).at(0).toString(), QStringLiteral("B"));
click(view, QPoint(400, 400));
QCOMPARE(points.count(), 0);
const QPointF anchor(view.width() * 0.5, (view.height() - 28) * 0.5);
view.zoomIn();
const QPointF zoomedCenter = anchor + (QPointF(212, 312) - anchor) * 1.25;
click(view, (zoomedCenter + QPointF(13, 0)).toPoint());
QCOMPARE(selected.count(), 4);
click(view, (zoomedCenter + QPointF(15, 0)).toPoint());
QCOMPARE(selected.count(), 4);
}
void AgvMapViewWidgetTest::paintsEditorOverlays()
{
AgvMapViewWidget view;
prepareView(view);
const QVariantMap first{{QStringLiteral("id"), QStringLiteral("A")},
{QStringLiteral("x"), -55.0}, {QStringLiteral("y"), 37.0},
{QStringLiteral("theta"), 0.0}, {QStringLiteral("draft"), false}};
const QVariantMap second{{QStringLiteral("id"), QStringLiteral("B")},
{QStringLiteral("x"), -45.0}, {QStringLiteral("y"), 65.0},
{QStringLiteral("theta"), 1.2}, {QStringLiteral("draft"), true}};
const QVariantMap route{{QStringLiteral("id"), QStringLiteral("A_TO_B")},
{QStringLiteral("points"), QVariantList{first, second}},
{QStringLiteral("draft"), true}};
view.setEditorObjects({first, second}, {route});
view.setSelectedStation(QStringLiteral("A"));
view.updateRobotPose(-65, 50, 0.7, true);
QApplication::processEvents();
QVERIFY(view.grab().save(QStringLiteral("agvmapviewwidget-test-preview.png")));
}
void AgvMapViewWidgetTest::acceptsCanvasPointsOutsideReceivedImage()
{
AgvMapViewWidget view;
prepareView(view);
QPointF world;
// Image begins at x=12. x=9 lies in the canvas around the received image.
QVERIFY(view.widgetToWorld(QPointF(9, 312), &world));
QVERIFY(nearPoint(world, QPointF(-55, -3.6)));
QVERIFY(!view.widgetToWorld(QPointF(2, 312), &world));
view.setEditMode(AgvMapViewWidget::AddStationMode);
QSignalSpy selected(&view, &AgvMapViewWidget::mapPointSelected);
click(view, QPoint(9, 312));
QCOMPARE(selected.count(), 1);
QVERIFY(qAbs(selected.at(0).at(1).toDouble() + 3.6) < 1e-8);
}
void AgvMapViewWidgetTest::fitsMapAndObjectsOutsideImage()
{
AgvMapViewWidget view;
prepareView(view);
const QPointF robotWorld(15, -30);
const QPointF stationWorld(-55, 200);
const QVariantMap station{{QStringLiteral("id"), QStringLiteral("OUTSIDE")},
{QStringLiteral("x"), stationWorld.x()},
{QStringLiteral("y"), stationWorld.y()},
{QStringLiteral("theta"), 0.0}};
view.setEditorObjects({station}, {});
view.updateRobotPose(robotWorld.x(), robotWorld.y(), 0.2, true);
view.resetView();
QApplication::processEvents();
const QPointF robotPosition = widgetPointForWorld(view, robotWorld);
const QPointF stationPosition = widgetPointForWorld(view, stationWorld);
const QRectF safeMarkerArea = QRectF(view.rect()).adjusted(25, 25, -25, -25);
QVERIFY(safeMarkerArea.contains(robotPosition));
QVERIFY(safeMarkerArea.contains(stationPosition));
const QList<QPointF> mapCorners = {QPointF(5, -3), QPointF(5, 157),
QPointF(-115, -3), QPointF(-115, 157)};
for (const QPointF &corner : mapCorners)
QVERIFY(QRectF(view.rect()).adjusted(8, 8, -8, -8)
.contains(widgetPointForWorld(view, corner)));
const QImage rendered = view.grab().toImage();
int blueRobotPixels = 0;
const QPoint center = robotPosition.toPoint();
for (int y = center.y() - 12; y <= center.y() + 12; ++y) {
for (int x = center.x() - 12; x <= center.x() + 12; ++x) {
const QColor color = rendered.pixelColor(x, y);
if (color.blue() > 180 && color.red() < 100 && color.green() < 170)
++blueRobotPixels;
}
}
QVERIFY(blueRobotPixels > 30);
QVERIFY(rendered.save(QStringLiteral("agvmapviewwidget-full-fit-preview.png")));
view.setEditMode(AgvMapViewWidget::AddRouteMode);
QSignalSpy selected(&view, &AgvMapViewWidget::stationSelected);
click(view, stationPosition.toPoint());
QCOMPARE(selected.count(), 1);
QCOMPARE(selected.at(0).at(0).toString(), QStringLiteral("OUTSIDE"));
}
void AgvMapViewWidgetTest::keepsBottomWallAboveRulerOnShortCanvas()
{
AgvMapViewWidget view;
view.resize(824, 340);
QImage map(1600, 800, QImage::Format_ARGB32_Premultiplied);
map.fill(Qt::transparent);
const QColor wallColor(83, 98, 112);
QPainter raster(&map);
raster.fillRect(QRect(0, 0, map.width(), 12), wallColor);
raster.fillRect(QRect(0, map.height() - 12, map.width(), 12), wallColor);
raster.fillRect(QRect(0, 0, 12, map.height()), wallColor);
raster.fillRect(QRect(map.width() - 12, 0, 12, map.height()), wallColor);
raster.end();
QVariantMap metadata = mapMetadata();
metadata.insert(QStringLiteral("originX"), 0.0);
metadata.insert(QStringLiteral("originY"), 0.0);
metadata.insert(QStringLiteral("originTheta"), 0.0);
metadata.insert(QStringLiteral("resolution"), 0.1);
metadata.insert(QStringLiteral("renderScale"), 1.0);
view.setMapFrame(map, metadata);
view.show();
QApplication::processEvents();
// Height limits this wide image to scale .36, in the 288px-tall viewport.
// All four map edges must remain in view, with the bottom above the ruler.
const QPointF topLeft = widgetPointForWorld(view, QPointF(0, 80));
const QPointF bottomRight = widgetPointForWorld(view, QPointF(160, 0));
QVERIFY(nearPoint(topLeft, QPointF(124, 12)));
QVERIFY(nearPoint(bottomRight, QPointF(700, 300)));
const int rulerTop = view.height() - 26;
QVERIFY(bottomRight.y() <= rulerTop - 12);
const QImage rendered = view.grab().toImage();
QCOMPARE(rendered.pixelColor(412, 14), wallColor);
QCOMPARE(rendered.pixelColor(126, 156), wallColor);
QCOMPARE(rendered.pixelColor(698, 156), wallColor);
// This is the last occupied screen row, not a marker or a geometry bound.
QCOMPARE(rendered.pixelColor(412, 299), wallColor);
QVERIFY(rendered.pixelColor(412, rulerTop + 2) != wallColor);
QVERIFY(rendered.save(QStringLiteral("agvmapviewwidget-short-canvas-wall-preview.png")));
const QPointF anchor(412, 156);
QPointF before;
QPointF after;
QVERIFY(view.widgetToWorld(anchor, &before));
view.zoomIn();
QVERIFY(view.widgetToWorld(anchor, &after));
QVERIFY(nearPoint(before, after));
view.zoomOut();
QVERIFY(view.widgetToWorld(anchor, &after));
QVERIFY(nearPoint(before, after));
QVERIFY(nearPoint(widgetPointForWorld(view, QPointF(160, 0)), bottomRight));
}
void AgvMapViewWidgetTest::keepsManualViewDuringTelemetryUpdates()
{
AgvMapViewWidget view;
prepareView(view);
view.zoomIn();
const QPointF center = view.rect().center();
QPointF before;
QPointF after;
QVERIFY(view.widgetToWorld(center, &before));
view.updateRobotPose(15, -30, 0.3, true);
view.setEditorObjects(
{QVariantMap{{QStringLiteral("id"), QStringLiteral("OUTSIDE")},
{QStringLiteral("x"), -55.0}, {QStringLiteral("y"), 200.0}}}, {});
QVERIFY(view.widgetToWorld(center, &after));
QVERIFY(nearPoint(before, after));
view.resetView();
QVERIFY(view.widgetToWorld(center, &after));
QVERIFY(!nearPoint(before, after));
QVERIFY(QRectF(view.rect()).adjusted(25, 25, -25, -25)
.contains(widgetPointForWorld(view, QPointF(15, -30))));
}
void AgvMapViewWidgetTest::paintsReferenceStationRouteAndGridStyle()
{
AgvMapViewWidget view;
view.resize(824, 652);
QImage transparentMap(400, 300, QImage::Format_ARGB32_Premultiplied);
transparentMap.fill(Qt::transparent);
QVariantMap metadata = mapMetadata();
metadata.insert(QStringLiteral("mapId"), QStringLiteral("reference-style"));
metadata.insert(QStringLiteral("originX"), 0.0);
metadata.insert(QStringLiteral("originY"), 0.0);
metadata.insert(QStringLiteral("originTheta"), 0.0);
metadata.insert(QStringLiteral("resolution"), 0.1);
metadata.insert(QStringLiteral("renderScale"), 1.0);
view.setMapFrame(transparentMap, metadata);
const QVariantMap first{{QStringLiteral("id"), QStringLiteral("LM1")},
{QStringLiteral("x"), 5.0}, {QStringLiteral("y"), 10.0}};
const QVariantMap second{{QStringLiteral("id"), QStringLiteral("LM2")},
{QStringLiteral("x"), 15.0}, {QStringLiteral("y"), 10.0}};
const QVariantMap selected{{QStringLiteral("id"), QStringLiteral("LM8")},
{QStringLiteral("x"), 15.0}, {QStringLiteral("y"), 20.0}};
const QVariantMap charging{{QStringLiteral("id"), QStringLiteral("CP5")},
{QStringLiteral("x"), 25.0}, {QStringLiteral("y"), 20.0},
{QStringLiteral("type"), QStringLiteral("ChargingPoint")}};
const QVariantMap forward{{QStringLiteral("id"), QStringLiteral("LM1_TO_LM2")},
{QStringLiteral("points"), QVariantList{first, second}}};
const QVariantMap reverse{{QStringLiteral("id"), QStringLiteral("LM2_TO_LM1")},
{QStringLiteral("points"), QVariantList{second, first}}};
view.setEditorObjects({first, second, selected, charging}, {forward, reverse});
view.setSelectedStation(QStringLiteral("LM8"));
view.show();
QApplication::processEvents();
QImage rendered = view.grab().toImage();
QVERIFY(rendered.save(QStringLiteral("agvmapviewwidget-reference-style-preview.png")));
const QColor orange = rendered.pixelColor(112, 412);
QVERIFY(orange.red() > 220 && orange.green() > 120
&& orange.green() < 190 && orange.blue() < 90);
const QColor purple = rendered.pixelColor(312, 212);
QVERIFY(purple.blue() > 190 && purple.red() > 100
&& purple.red() < 170 && purple.green() < 120);
const QColor halo = rendered.pixelColor(322, 220);
QVERIFY(halo.red() > 200 && halo.blue() > halo.red() + 10);
const QColor teal = rendered.pixelColor(512, 212);
QVERIFY(teal.red() < 80 && teal.green() > 120 && teal.blue() > 100);
QVERIFY(rendered.pixelColor(516, 216).red() > 120);
const auto countBlue = [&rendered](const QRect &area) {
int count = 0;
for (int y = area.top(); y <= area.bottom(); ++y) {
for (int x = area.left(); x <= area.right(); ++x) {
const QColor color = rendered.pixelColor(x, y);
if (color.blue() > 200 && color.red() < 100 && color.green() < 160)
++count;
}
}
return count;
};
// Arrow heads protrude above the thin line at two distinct positions.
QVERIFY(countBlue(QRect(234, 408, 8, 3)) > 2);
QVERIFY(countBlue(QRect(182, 408, 8, 3)) > 2);
const QColor outsideGrid = rendered.pixelColor(9, 412);
QVERIFY2(outsideGrid.blue() > outsideGrid.red() + 12, qPrintable(outsideGrid.name()));
mouseEvent(view, QEvent::MouseButtonPress, QPoint(300, 300),
Qt::RightButton, Qt::RightButton);
mouseEvent(view, QEvent::MouseMove, QPoint(320, 290),
Qt::NoButton, Qt::RightButton);
mouseEvent(view, QEvent::MouseButtonRelease, QPoint(320, 290),
Qt::RightButton, Qt::NoButton);
rendered = view.grab().toImage();
const QColor movedGrid = rendered.pixelColor(9, 402);
QVERIFY2(movedGrid.blue() > movedGrid.red() + 12, qPrintable(movedGrid.name()));
}
void AgvMapViewWidgetTest::paintsDirectionsOnSampledRoutes_data()
{
QTest::addColumn<bool>("curved");
QTest::addColumn<bool>("bidirectional");
QTest::newRow("33-point-straight") << false << false;
QTest::newRow("33-point-bezier") << true << false;
QTest::newRow("33-point-bidirectional-bezier") << true << true;
}
void AgvMapViewWidgetTest::paintsDirectionsOnSampledRoutes()
{
QFETCH(bool, curved);
QFETCH(bool, bidirectional);
AgvMapViewWidget view;
view.resize(824, 652);
QImage transparentMap(400, 300, QImage::Format_ARGB32_Premultiplied);
transparentMap.fill(Qt::transparent);
QVariantMap metadata = mapMetadata();
metadata.insert(QStringLiteral("originX"), 0.0);
metadata.insert(QStringLiteral("originY"), 0.0);
metadata.insert(QStringLiteral("originTheta"), 0.0);
metadata.insert(QStringLiteral("resolution"), 0.1);
metadata.insert(QStringLiteral("renderScale"), 1.0);
view.setMapFrame(transparentMap, metadata);
// These are the 33 samples returned by the SMAP document renderer for a
// straight route or cubic Bezier with controls (5,20) and (15,20).
QVariantList points;
QList<QPointF> worldPoints;
for (int step = 0; step <= 32; ++step) {
const double t = step / 32.0;
const QPointF world(curved ? 5.0 + 10.0 * (3.0 * t * t - 2.0 * t * t * t)
: 5.0 + 10.0 * t,
curved ? 10.0 + 30.0 * t * (1.0 - t) : 10.0);
worldPoints.append(world);
points.append(QVariantMap{{QStringLiteral("x"), world.x()},
{QStringLiteral("y"), world.y()}});
}
view.setEditorObjects({}, {QVariantMap{{QStringLiteral("id"), QStringLiteral("SAMPLED")},
{QStringLiteral("points"), points},
{QStringLiteral("bidirectional"), bidirectional}}});
view.show();
QApplication::processEvents();
QPolygonF geometry;
for (const QPointF &world : worldPoints)
geometry.append(widgetPointForWorld(view, world));
for (int index = 1; index < geometry.size(); ++index)
QVERIFY(QLineF(geometry.at(index - 1), geometry.at(index)).length() < 20.0);
// A three-pixel stroke masks the thin route itself. Filled arrow heads must
// leave blue pixels beyond it, including when every sample segment is short.
QImage centerlineMask(view.size(), QImage::Format_ARGB32_Premultiplied);
centerlineMask.fill(Qt::transparent);
QPainter maskPainter(&centerlineMask);
maskPainter.setRenderHint(QPainter::Antialiasing);
maskPainter.setPen(QPen(Qt::black, 3.0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
maskPainter.drawPolyline(geometry);
maskPainter.end();
const QImage rendered = view.grab().toImage();
int arrowPixels = 0;
for (int y = 0; y < rendered.height(); ++y) {
for (int x = 0; x < rendered.width(); ++x) {
const QColor color = rendered.pixelColor(x, y);
if (centerlineMask.pixelColor(x, y).alpha() == 0
&& color.blue() > 200 && color.red() < 100 && color.green() < 160)
++arrowPixels;
}
}
QVERIFY2(arrowPixels >= (bidirectional ? 8 : 4),
qPrintable(QStringLiteral("Only %1 pixels protrude beyond the route").arg(arrowPixels)));
if (!curved) {
// The straight route spans x112..312: its forward tip is at 65%, and
// its head extends above the stroke immediately behind that tip.
const QColor arrowWing = rendered.pixelColor(235, 409);
QVERIFY(arrowWing.blue() > 200 && arrowWing.red() < 100 && arrowWing.green() < 160);
}
QVERIFY(rendered.save(QStringLiteral("agvmapviewwidget-%1-preview.png")
.arg(QString::fromLatin1(QTest::currentDataTag()))));
}
void AgvMapViewWidgetTest::usesMetadataObjectsUntilDocumentOverridesThem()
{
AgvMapViewWidget view;
prepareView(view);
const QVariantMap rawStation{{QStringLiteral("id"), QStringLiteral("STREAM")},
{QStringLiteral("x"), -55.0}, {QStringLiteral("y"), 37.0}};
QVariantMap metadata = mapMetadata();
metadata.insert(QStringLiteral("stations"), QVariantList{rawStation});
QImage image(400, 300, QImage::Format_ARGB32_Premultiplied);
image.fill(Qt::transparent);
view.setMapFrame(image, metadata);
view.setEditMode(AgvMapViewWidget::AddRouteMode);
QSignalSpy selected(&view, &AgvMapViewWidget::stationSelected);
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 1);
QCOMPARE(selected.at(0).at(0).toString(), QStringLiteral("STREAM"));
QVariantMap documentStation = rawStation;
documentStation.insert(QStringLiteral("id"), QStringLiteral("DOCUMENT"));
view.setEditorObjects({documentStation}, {});
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 2);
QCOMPARE(selected.at(1).at(0).toString(), QStringLiteral("DOCUMENT"));
view.setEditorObjects({}, {});
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 3);
QCOMPARE(selected.at(2).at(0).toString(), QStringLiteral("STREAM"));
// Deleting the final station leaves an authoritative empty document;
// stale preview metadata must not bring the deleted station back.
const QImage beforeDeletion = view.grab().toImage();
view.setEditorObjects({}, {}, true);
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 3);
QVERIFY(view.grab().toImage() != beforeDeletion);
view.setMapFrame(image, metadata);
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 3);
view.setEditorObjects({documentStation}, {});
metadata.insert(QStringLiteral("mapId"), QStringLiteral("different-map"));
metadata.remove(QStringLiteral("stations"));
view.setMapFrame(image, metadata);
click(view, QPoint(212, 312));
QCOMPARE(selected.count(), 3);
}
void AgvMapViewWidgetTest::displaysStationNamesWithoutChangingIds()
{
AgvMapViewWidget view;
prepareView(view);
const QString sharedName = QStringLiteral("同名站点");
QVariantMap first{{QStringLiteral("id"), QStringLiteral("A")},
{QStringLiteral("name"), sharedName},
{QStringLiteral("x"), -55.0}, {QStringLiteral("y"), 37.0}};
const QVariantMap second{{QStringLiteral("id"), QStringLiteral("B")},
{QStringLiteral("name"), sharedName},
{QStringLiteral("x"), -55.0}, {QStringLiteral("y"), 77.0}};
view.setEditorObjects({first, second}, {});
view.setEditMode(AgvMapViewWidget::AddRouteMode);
QSignalSpy selected(&view, &AgvMapViewWidget::stationSelected);
click(view, QPoint(212, 312));
click(view, QPoint(412, 312));
QCOMPARE(selected.count(), 2);
QCOMPARE(selected.at(0).at(0).toString(), QStringLiteral("A"));
QCOMPARE(selected.at(1).at(0).toString(), QStringLiteral("B"));
for (const auto &station : {QPair<QPoint, QString>{QPoint(212, 312), QStringLiteral("A")},
QPair<QPoint, QString>{QPoint(412, 312), QStringLiteral("B")}}) {
QHelpEvent help(QEvent::ToolTip, station.first, view.mapToGlobal(station.first));
QApplication::sendEvent(&view, &help);
QVERIFY(QToolTip::text().contains(sharedName));
QVERIFY(QToolTip::text().contains(QStringLiteral("ID: ") + station.second));
QToolTip::hideText();
}
view.setSelectedStation(QString());
view.setEditorObjects({first}, {});
const QImage named = view.grab().toImage();
first.remove(QStringLiteral("name"));
view.setEditorObjects({first}, {});
const QImage fallback = view.grab().toImage();
QVERIFY(named != fallback);
first.insert(QStringLiteral("name"), QStringLiteral(" A "));
view.setEditorObjects({first}, {});
QCOMPARE(view.grab().toImage(), fallback);
first.insert(QStringLiteral("name"), QStringLiteral(" \t "));
view.setEditorObjects({first}, {});
QCOMPARE(view.grab().toImage(), fallback);
}
void AgvMapViewWidgetTest::elidesLongStationNames()
{
AgvMapViewWidget view;
prepareView(view);
QVariantMap station{{QStringLiteral("id"), QStringLiteral("A")},
{QStringLiteral("x"), -55.0}, {QStringLiteral("y"), 37.0}};
view.setEditorObjects({station}, {});
const QImage fallback = view.grab().toImage();
const QString name = QStringLiteral("装配工位名称非常长 ").repeated(20);
station.insert(QStringLiteral("name"), name);
view.setEditorObjects({station}, {});
const QImage rendered = view.grab().toImage();
QRect changed;
for (int y = 0; y < rendered.height(); ++y) {
for (int x = 0; x < rendered.width(); ++x) {
if (rendered.pixel(x, y) != fallback.pixel(x, y))
changed = changed.united(QRect(x, y, 1, 1));
}
}
QVERIFY(changed.width() > 100);
QVERIFY(changed.width() <= 278);
QVERIFY(changed.height() <= 28);
QHelpEvent help(QEvent::ToolTip, QPoint(212, 312), view.mapToGlobal(QPoint(212, 312)));
QApplication::sendEvent(&view, &help);
QVERIFY(QToolTip::text().contains(name.trimmed()));
QVERIFY(QToolTip::text().contains(QStringLiteral("ID: A")));
QToolTip::hideText();
QVERIFY(rendered.save(QStringLiteral("agvmapviewwidget-station-name-preview.png")));
}
QTEST_MAIN(AgvMapViewWidgetTest)
#include "agvmapviewwidget_test.moc"

1458
tests/agvpage_smoke.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,239 @@
#include "../src/agvvelocityramp.h"
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
namespace {
int checks = 0;
void expect(bool condition, const char *message)
{
++checks;
if (!condition) {
std::cerr << "FAIL: " << message << '\n';
std::exit(1);
}
}
bool near(double actual, double expected, double tolerance = 1e-10)
{
return std::abs(actual - expected) <= tolerance;
}
bool finite(const AgvManualVelocity &value)
{
return std::isfinite(value.vx) && std::isfinite(value.vy)
&& std::isfinite(value.wz);
}
double length(const AgvManualVelocity &value)
{
return std::hypot(value.vx, value.vy);
}
void positiveAndNegativeAcceleration()
{
const AgvRampLimits limits;
AgvManualVelocity value;
const AgvManualVelocity target{0.2, 0.0, 0.0};
for (int tick = 0; tick != 10; ++tick) {
const auto next = AgvVelocityRamp::step(value, target, limits, 0.1);
expect(near(next.vx - value.vx, 0.02), "positive acceleration bound");
expect(next.vx <= target.vx && next.vx >= value.vx, "positive no overshoot");
value = next;
}
expect(near(value.vx, target.vx), "positive target reached");
expect(near(AgvVelocityRamp::step(value, target, limits, 0.1).vx, 0.2),
"target stable");
value = {};
for (int tick = 0; tick != 20; ++tick) {
const auto next = AgvVelocityRamp::step(value, {-0.37, 0.0, 0.0}, limits, 0.1);
expect(next.vx <= value.vx && next.vx >= -0.37, "negative no overshoot");
expect(std::abs(next.vx - value.vx) <= 0.02 + 1e-10, "negative slope bound");
value = next;
}
expect(near(value.vx, -0.37), "negative target reached exactly");
}
void stoppingAndMagnitudeDecrease()
{
const AgvRampLimits limits;
auto value = AgvVelocityRamp::step({0.5, 0.0, 0.0}, {0.2, 0.0, 0.0}, limits, 0.1);
expect(near(value.vx, 0.47), "same direction lowering uses deceleration");
value = {-0.2, 0.0, -0.3};
int tick = 0;
while (!AgvVelocityRamp::isZero(value) && tick++ < 10) {
const auto next = AgvVelocityRamp::step(value, {}, limits, 0.1);
expect(next.vx >= value.vx && next.vx <= 0.0, "stop never flips negative linear sign");
expect(next.wz >= value.wz && next.wz <= 0.0, "stop never flips negative angular sign");
value = next;
}
expect(tick == 7, "stop reaches zero in finite expected time");
expect(value.vx == 0.0 && value.vy == 0.0 && value.wz == 0.0, "stop exact zero");
}
void reversalsAndTurns()
{
const AgvRampLimits limits;
auto value = AgvManualVelocity{0.2, 0.0, 0.0};
bool seenZero = false;
for (int tick = 0; tick != 20; ++tick) {
const auto next = AgvVelocityRamp::step(value, {-0.2, 0.0, 0.0}, limits, 0.1);
if (next.vx < 0.0)
expect(seenZero, "linear reversal has an explicit zero sample");
if (value.vx > 0.0)
expect(near(value.vx - next.vx, std::min(0.03, value.vx)), "reverse brakes first");
seenZero = seenZero || AgvVelocityRamp::isZero(next);
value = next;
}
expect(near(value.vx, -0.2), "linear reversal reaches target");
value = {0.12, 0.0, 0.0};
seenZero = false;
for (int tick = 0; tick != 12; ++tick) {
const auto next = AgvVelocityRamp::step(value, {0.0, 0.12, 0.0}, limits, 0.1);
if (next.vy > 0.0)
expect(seenZero && next.vx == 0.0, "ninety degree turn stops before new axis");
seenZero = seenZero || AgvVelocityRamp::isZero(next);
value = next;
}
expect(near(value.vy, 0.12), "ninety degree turn reaches target");
value = {0.08, 0.0, 0.0};
seenZero = false;
for (int tick = 0; tick != 12; ++tick) {
const auto next = AgvVelocityRamp::step(value, {0.0, 0.0, 0.25}, limits, 0.1);
if (next.wz > 0.0)
expect(seenZero && next.vx == 0.0, "linear to angular stops before rotation");
seenZero = seenZero || AgvVelocityRamp::isZero(next);
value = next;
}
expect(near(value.wz, 0.25), "linear to angular reaches target");
value = {0.0, 0.0, -0.17};
seenZero = false;
for (int tick = 0; tick != 12; ++tick) {
const auto next = AgvVelocityRamp::step(value, {0.14, 0.0, 0.0}, limits, 0.1);
if (next.vx > 0.0)
expect(seenZero && next.wz == 0.0, "angular to linear stops first");
seenZero = seenZero || AgvVelocityRamp::isZero(next);
value = next;
}
expect(near(value.vx, 0.14), "angular to linear reaches target");
}
void vectorAndAngularLimits()
{
const AgvRampLimits limits;
auto value = AgvManualVelocity{};
const AgvManualVelocity target{0.3, 0.4, 0.0};
for (int tick = 0; tick != 25; ++tick) {
const auto next = AgvVelocityRamp::step(value, target, limits, 0.1);
expect(near(length(next) - length(value), 0.02), "XY acceleration uses vector magnitude");
expect(near(next.vx / next.vy, 0.75), "XY vector direction preserved");
value = next;
}
expect(near(value.vx, 0.3) && near(value.vy, 0.4), "diagonal target reached");
value = AgvVelocityRamp::step(value, {0.06, 0.08, 0.0}, limits, 0.1);
expect(near(length(value), 0.47), "diagonal deceleration magnitude bound");
value = AgvVelocityRamp::step(value, {}, limits, 0.1);
expect(near(length(value), 0.44), "diagonal stop magnitude bound");
value = AgvVelocityRamp::step({}, {0.0, 0.0, 0.3}, limits, 0.1);
expect(near(value.wz, 0.05), "angular acceleration separate limit");
value = AgvVelocityRamp::step({0.0, 0.0, 0.3}, {0.0, 0.0, -0.3}, limits, 0.1);
expect(near(value.wz, 0.22), "angular reversal brakes at deceleration rate");
bool seenZero = false;
for (int tick = 0; tick != 12; ++tick) {
const auto next = AgvVelocityRamp::step(value, {0.0, 0.0, -0.3}, limits, 0.1);
if (next.wz < 0.0)
expect(seenZero, "angular reversal has zero sample");
seenZero = seenZero || AgvVelocityRamp::isZero(next);
value = next;
}
expect(near(value.wz, -0.3), "angular reverse target reached");
// In a combined reversal the faster component must wait for the slower
// component to finish braking before any new component starts.
value = {0.3, 0.0, 0.05};
seenZero = false;
for (int tick = 0; tick != 30; ++tick) {
const auto next = AgvVelocityRamp::step(value, {-0.2, 0.0, -0.3}, limits, 0.1);
if (next.vx < 0.0 || next.wz < 0.0)
expect(seenZero, "combined reversal waits for all motion to stop");
seenZero = seenZero || AgvVelocityRamp::isZero(next);
value = next;
}
expect(near(value.vx, -0.2) && near(value.wz, -0.3), "combined reverse target reached");
}
void elapsedTimeAndInvalidInputs()
{
const AgvRampLimits limits;
expect(near(AgvVelocityRamp::step({}, {1.0, 0.0, 0.0}, limits, 1.0).vx, 0.03),
"long GUI delay capped at 150 ms");
expect(near(AgvVelocityRamp::step({}, {1.0, 0.0, 0.0}, limits, 0.025).vx, 0.005),
"fractional elapsed time respected");
const AgvManualVelocity current{0.2, 0.0, 0.1};
const auto nan = std::numeric_limits<double>::quiet_NaN();
const auto infinity = std::numeric_limits<double>::infinity();
for (double dt : {0.0, -1.0, nan, infinity}) {
const auto value = AgvVelocityRamp::step(current, {}, limits, dt);
expect(near(value.vx, current.vx) && near(value.wz, current.wz),
"invalid elapsed time does not move ramp");
}
AgvManualVelocity a, b;
for (int tick = 0; tick != 10; ++tick)
a = AgvVelocityRamp::step(a, {0.5, 0.0, 0.0}, limits, 0.1);
for (int tick = 0; tick != 40; ++tick)
b = AgvVelocityRamp::step(b, {0.5, 0.0, 0.0}, limits, 0.025);
expect(near(a.vx, b.vx), "same elapsed time at different tick rates");
const auto invalidTarget = AgvVelocityRamp::step({0.2, 0.0, 0.0},
{nan, infinity, nan}, limits, 0.1);
expect(near(invalidTarget.vx, 0.17) && finite(invalidTarget), "invalid target brakes safely");
expect(AgvVelocityRamp::isZero(AgvVelocityRamp::step({nan, 0.0, 0.0},
{0.2, 0.0, 0.0}, limits, 0.1)),
"invalid current never extrapolates");
expect(!AgvVelocityRamp::isZero({nan, 0.0, 0.0}), "invalid velocity is not reported stationary");
AgvRampLimits bad;
bad.linearAcceleration = nan;
bad.linearDeceleration = -1.0;
bad.angularAcceleration = infinity;
bad.angularDeceleration = 0.0;
const auto start = AgvVelocityRamp::step({}, {0.2, 0.0, 0.3}, bad, 0.1);
expect(near(start.vx, 0.02) && near(start.wz, 0.05), "invalid acceleration uses bounded defaults");
const auto stop = AgvVelocityRamp::step({0.2, 0.0, 0.3}, {}, bad, 0.1);
expect(near(stop.vx, 0.17) && near(stop.wz, 0.22), "invalid deceleration uses bounded defaults");
const auto huge = AgvVelocityRamp::step({1e308, 1e308, 0.0}, {}, limits, 0.1);
expect(finite(huge), "extreme finite velocities never overflow output");
expect(finite(AgvVelocityRamp::step({}, {infinity, 0.0, 0.0}, limits, 0.1)),
"infinite target never becomes output");
AgvManualVelocity value{0.3, 0.4, -0.3};
const double ticks[] = {0.03, 0.1, 0.05, 0.14, 0.01};
for (int tick = 0; tick != 60; ++tick) {
const auto next = AgvVelocityRamp::step(value, {}, limits, ticks[tick % 5]);
expect(length(next) <= length(value) + 1e-10 && finite(next), "irregular ticks stop monotonically");
value = next;
}
expect(AgvVelocityRamp::isZero(value), "irregular ticks reach exact zero");
}
} // namespace
int main()
{
positiveAndNegativeAcceleration();
stoppingAndMagnitudeDecrease();
reversalsAndTurns();
vectorAndAngularLimits();
elapsedTimeAndInvalidInputs();
std::cout << "PASS AGV velocity ramp: " << checks
<< " checks (vector limits, start/stop/reversal, elapsed time, invalid inputs)\n";
return 0;
}

View File

@ -0,0 +1,264 @@
#include "robotclient.h"
#include "cmvr/api/agv_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QThread>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <map>
#include <mutex>
#include <thread>
#include <vector>
namespace {
void require(bool condition, const char *message)
{
if (!condition) {
std::cerr << "FAIL " << message << std::endl;
std::exit(1);
}
}
void pump(int milliseconds)
{
QElapsedTimer elapsed;
elapsed.start();
while (elapsed.elapsed() < milliseconds) {
QCoreApplication::processEvents();
QThread::msleep(1);
}
}
void waitFor(const std::function<bool()> &predicate, const char *message, int timeout = 5000)
{
QElapsedTimer elapsed;
elapsed.start();
while (!predicate() && elapsed.elapsed() < timeout)
pump(1);
require(predicate(), message);
}
class FakeAgv final : public cmvr::api::AgvService::Service {
public:
grpc::Status setVelocity(grpc::ServerContext *context,
const cmvr::api::AgvSetVelocityCommand::Request *request,
cmvr::api::AgvSetVelocityCommand::Feedback *response) override
{
{
std::lock_guard<std::mutex> lock(mutex);
receivedIds.push_back(request->header().device_id());
receivedVx.push_back(request->velocity().vx());
}
++velocities;
while (hold.load() && !context->IsCancelled())
std::this_thread::sleep_for(std::chrono::milliseconds(1));
response->mutable_header()->set_success(!reject.load());
if (reject.load())
response->mutable_header()->set_error_message("fixture velocity rejection");
if (rpcFail.load())
return grpc::Status(grpc::StatusCode::UNAVAILABLE, "fixture RPC unavailable");
return grpc::Status::OK;
}
grpc::Status stopVelocityControl(grpc::ServerContext *,
const cmvr::api::CommandHeader::Request *,
cmvr::api::CommandHeader::Feedback *response) override
{
++stops;
response->set_success(true);
return grpc::Status::OK;
}
std::atomic<int> velocities{0};
std::atomic<int> stops{0};
std::atomic<bool> hold{false};
std::atomic<bool> reject{false};
std::atomic<bool> rpcFail{false};
std::mutex mutex;
std::vector<std::string> receivedIds;
std::vector<double> receivedVx;
};
struct Ack {
bool success;
QString detail;
};
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
FakeAgv service;
int port = 0;
grpc::ServerBuilder builder;
builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&service);
auto server = builder.BuildAndStart();
require(bool(server) && port != 0, "loopback server starts");
{
RobotClient client;
const QString device = QStringLiteral("manual_fixture");
bool connected = false;
bool directBusy = false;
bool mapDone = false;
int interruptions = 0;
bool lastInterruptionRequestsStop = true;
std::map<quint64, std::vector<Ack>> acks;
QObject::connect(&client, &RobotClient::connectionChanged,
[&](bool value, int, const QString &) { connected = value; });
QObject::connect(&client, &RobotClient::agvManualVelocityFinished,
[&](quint64 id, bool success, const QString &detail) {
acks[id].push_back({success, detail});
});
QObject::connect(&client, &RobotClient::agvManualControlInterrupted,
[&](bool requestStop) {
++interruptions;
lastInterruptionRequestsStop = requestStop;
});
QObject::connect(&client, &RobotClient::agvMapDirectBusyChanged,
[&](bool value) { directBusy = value; });
QObject::connect(&client, &RobotClient::agvMapContentReceived,
[&](quint64 id, const QString &, const QString &, const QString &, bool, const QString &) {
if (id == 900)
mapDone = true;
});
const auto waitAck = [&](quint64 id) {
waitFor([&]() { return !acks[id].empty(); }, "typed manual ACK arrives");
require(acks[id].size() == 1, "one typed ACK per request");
};
const auto blockWorker = [&]() {
service.hold.store(true);
const int before = service.velocities.load();
client.requestAgvVelocity(device, 0.01, 0.0, 0.0);
waitFor([&]() { return service.velocities > before; }, "legacy RPC blocks original worker");
return service.velocities.load();
};
client.connectToServer(QStringLiteral("127.0.0.1"), port, false);
waitFor([&]() { return connected; }, "client connects to fake service");
client.requestAgvManualVelocity(1, device, 0.1, 0.0, 0.0);
waitAck(1);
require(acks[1][0].success && service.velocities == 1, "manual RPC receives its own success ACK");
service.hold.store(true);
client.requestAgvManualVelocity(2, device, 0.2, 0.0, 0.0);
waitFor([&]() { return service.velocities == 2; }, "manual RPC enters server");
client.requestAgvManualVelocity(3, device, 0.3, 0.0, 0.0);
waitAck(3);
require(!acks[3][0].success && service.velocities == 2, "concurrent manual request is rejected without queue");
const int cancelInterruptionsBefore = interruptions;
client.cancelAgvManualVelocity();
require(interruptions == cancelInterruptionsBefore, "explicit cancel cannot recursively interrupt the UI");
client.requestAgvManualVelocity(4, device, 0.4, 0.0, 0.0);
waitAck(4);
require(!acks[4][0].success, "cancel does not release physical in-flight admission");
service.hold.store(false);
waitAck(2);
require(!acks[2][0].success, "canceled executing RPC cannot yield a current successful ACK");
int before = blockWorker();
client.requestAgvManualVelocity(10, device, 0.5, 0.0, 0.0);
const int interruptionsBefore = interruptions;
client.requestAgvAction(device, QStringLiteral("StopVelocity"));
require(interruptions > interruptionsBefore && !lastInterruptionRequestsStop,
"stop clears UI immediately without requesting an extra stop ahead of itself");
service.hold.store(false);
waitAck(10);
waitFor([&]() { return service.stops == 1; }, "stop RPC follows blocked older worker call");
require(!acks[10][0].success && service.velocities == before, "canceled queued packet never reaches vehicle service");
before = blockWorker();
client.requestAgvManualVelocity(11, device, 0.6, 0.0, 0.0);
pump(360);
service.hold.store(false);
waitAck(11);
require(!acks[11][0].success && acks[11][0].detail.contains(QStringLiteral("300 ms"))
&& service.velocities == before, "queued packet expires after 300 ms without transmission");
service.reject.store(true);
client.requestAgvManualVelocity(12, device, 0.7, 0.0, 0.0);
waitAck(12);
require(!acks[12][0].success && acks[12][0].detail.contains(QStringLiteral("fixture velocity rejection")),
"typed ACK retains exact application rejection");
service.reject.store(false);
service.rpcFail.store(true);
client.requestAgvManualVelocity(13, device, 0.8, 0.0, 0.0);
waitAck(13);
require(!acks[13][0].success && acks[13][0].detail.contains(QStringLiteral("fixture RPC unavailable")),
"typed ACK reports RPC failure");
service.rpcFail.store(false);
before = service.velocities.load();
const QString newDevice = QStringLiteral("fresh_manual_fixture");
client.requestAgvManualVelocity(14, newDevice, 0.1, 0.0, 0.0);
waitAck(14);
require(!acks[14][0].success && service.velocities == before,
"synchronous device interruption cannot admit the rest of a canceled manual call");
client.beginAgvManualControl(device);
require(service.velocities == before, "begin manual control only synchronizes local context");
client.requestAgvManualVelocity(15, device, 0.1, 0.0, 0.0);
waitAck(15);
require(acks[15][0].success && service.velocities == before + 1,
"prepared fresh manual session accepts its first packet");
before = blockWorker();
client.requestAgvManualVelocity(20, device, 0.9, 0.0, 0.0);
client.requestAgvRefresh(QStringLiteral("different_fixture"));
service.hold.store(false);
waitAck(20);
require(!acks[20][0].success && service.velocities == before, "device change invalidates queued packet");
before = blockWorker();
client.requestAgvManualVelocity(21, device, 1.0, 0.0, 0.0);
client.connectToServer(QStringLiteral("127.0.0.1"), port, false);
service.hold.store(false);
waitAck(21);
require(!acks[21][0].success && service.velocities == before, "source reconnect invalidates queued packet");
pump(30);
before = blockWorker();
client.requestAgvManualVelocity(22, device, 1.1, 0.0, 0.0);
client.configureAgvMapDirect(true, QString(), QStringLiteral("127.0.0.1"), port);
client.requestAgvMapContent(900, device, QStringLiteral("fixture_map"));
require(directBusy, "direct map is busy before old worker barrier drains");
client.requestAgvManualVelocity(23, device, 1.2, 0.0, 0.0);
waitAck(23);
require(!acks[23][0].success, "direct map busy refuses new manual packets");
service.hold.store(false);
waitAck(22);
require(!acks[22][0].success && service.velocities == before, "direct map busy invalidates queued manual packet");
waitFor([&]() { return mapDone && !directBusy; }, "fake config discovery rejects without vehicle sockets");
client.configureAgvMapDirect(false, QString(), QStringLiteral("127.0.0.1"), port);
before = blockWorker();
client.requestAgvManualVelocity(24, device, 1.3, 0.0, 0.0);
client.requestRpc(QStringLiteral("cmvr.api.AgvService"), QStringLiteral("clearFault"),
QStringLiteral("{}"), device);
require(lastInterruptionRequestsStop, "generic non-stop write requests a hard manual stop");
service.hold.store(false);
waitAck(24);
require(!acks[24][0].success && service.velocities == before, "generic AGV write invalidates manual packet");
before = blockWorker();
client.requestAgvManualVelocity(25, device, 1.4, 0.0, 0.0);
client.disconnectFromServer();
service.hold.store(false);
waitAck(25);
waitFor([&]() { return !connected; }, "disconnect completes");
require(!acks[25][0].success && service.velocities == before, "disconnect invalidates queued packet");
client.requestAgvManualVelocity(26, device, 0.1, 0.0, 0.0);
waitAck(26);
require(!acks[26][0].success && service.velocities == before, "disconnected worker never sends velocity");
}
server->Shutdown();
std::cout << "PASS manual velocity loopback: typed ACK, single-flight admission, canceled executing ACK, "
"stop-before-queued-packet, 300 ms expiry, RPC/application failures, source/device/direct-map/generic/disconnect invalidation"
<< std::endl;
return 0;
}

View File

@ -0,0 +1,428 @@
#include "seeragvmapclient_fake.h"
#include "robotclient.h"
#include "cmvr/api/agv_service.grpc.pb.h"
#include "cmvr/api/configuration_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QApplication>
#include <QThread>
#include <map>
namespace {
const QString deviceId = QStringLiteral("fixture_seer");
void waitFor(const std::function<bool()> &predicate, const char *message, int timeoutMs = 15000)
{
QElapsedTimer elapsed;
elapsed.start();
while (!predicate() && elapsed.elapsed() < timeoutMs) {
QCoreApplication::processEvents();
QThread::msleep(2);
}
require(predicate(), message);
}
void pumpFor(int milliseconds)
{
QElapsedTimer elapsed;
elapsed.start();
while (elapsed.elapsed() < milliseconds) {
QCoreApplication::processEvents();
QThread::msleep(2);
}
}
// The existing configuration API is used only to discover three random
// loopback ports. It never serves or changes a real configuration file.
class FakeConfiguration final : public cmvr::api::ConfigurationService::Service {
public:
explicit FakeConfiguration(const FakeRobot &robot)
{
m_content = QStringLiteral("agv { agvs { id: \"fixture_seer\" seer_robokit_agv { "
"id: \"fixture_seer\" ip: \"127.0.0.1\" enable: true "
"port_status: %1 port_control: %2 port_config: %3 } } }")
.arg(robot.connection.statusPort).arg(robot.connection.controlPort)
.arg(robot.connection.configPort).toStdString();
}
grpc::Status ListConfigFiles(grpc::ServerContext *,
const cmvr::api::ListConfigFilesCommand::Request *,
cmvr::api::ListConfigFilesCommand::Feedback *response) override
{
++lists;
response->mutable_header()->set_success(true);
auto *file = response->add_files();
file->set_relative_path("test/agv.pbtxt");
file->set_message_type("cmvr.config.AGVRootConfig");
return grpc::Status::OK;
}
grpc::Status ReadConfigFile(grpc::ServerContext *,
const cmvr::api::ReadConfigFileCommand::Request *request,
cmvr::api::ReadConfigFileCommand::Feedback *response) override
{
++reads;
require(request->relative_path() == "test/agv.pbtxt", "bridge reads only discovered fake config path");
response->mutable_header()->set_success(true);
response->set_content(m_content);
return grpc::Status::OK;
}
std::atomic<int> lists{0};
std::atomic<int> reads{0};
private:
std::string m_content;
};
// Record legacy map calls so tests prove the enabled bridge bypasses their
// body packaging, while disabled direct mode still uses this existing API.
class FakeLegacyAgv final : public cmvr::api::AgvService::Service {
public:
grpc::Status setVelocity(grpc::ServerContext *context,
const cmvr::api::AgvSetVelocityCommand::Request *,
cmvr::api::AgvSetVelocityCommand::Feedback *response) override
{
++velocities;
while (holdVelocity.load() && !context->IsCancelled())
std::this_thread::sleep_for(std::chrono::milliseconds(1));
++velocitiesFinished;
response->mutable_header()->set_success(true);
return grpc::Status::OK;
}
grpc::Status downloadMap(grpc::ServerContext *,
const cmvr::api::AgvMapCommand::Request *,
cmvr::api::AgvMapCommand::Feedback *response) override
{
++reads;
response->mutable_header()->set_success(true);
response->set_content(completeMap.toStdString());
return grpc::Status::OK;
}
grpc::Status uploadMap(grpc::ServerContext *,
const cmvr::api::AgvMapCommand::Request *request,
cmvr::api::AgvMapCommand::Feedback *response) override
{
++uploads;
{
std::lock_guard<std::mutex> lock(mutex);
uploaded = request->content();
}
response->mutable_header()->set_success(true);
return grpc::Status::OK;
}
grpc::Status switchMap(grpc::ServerContext *,
const cmvr::api::AgvMapCommand::Request *,
cmvr::api::AgvMapCommand::Feedback *response) override
{
++switches;
response->mutable_header()->set_success(true);
return grpc::Status::OK;
}
std::atomic<int> reads{0};
std::atomic<int> uploads{0};
std::atomic<int> switches{0};
std::atomic<int> velocities{0};
std::atomic<int> velocitiesFinished{0};
std::atomic<bool> holdVelocity{false};
std::mutex mutex;
std::string uploaded;
};
class FakeServices final {
public:
explicit FakeServices(const FakeRobot &robot) : configuration(robot)
{
grpc::ServerBuilder builder;
builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&configuration);
builder.RegisterService(&legacy);
server = builder.BuildAndStart();
require(server && port > 0, "fake configuration and legacy services bind loopback ephemeral port");
}
~FakeServices()
{
server->Shutdown();
server->Wait();
}
FakeConfiguration configuration;
FakeLegacyAgv legacy;
int port = 0;
std::unique_ptr<grpc::Server> server;
};
struct ReadEvent {
bool success;
QString device;
QString map;
QString content;
QString detail;
};
struct SaveEvent {
bool success;
QString detail;
};
struct Capture {
explicit Capture(RobotClient &client)
{
QObject::connect(&client, &RobotClient::connectionChanged, &context,
[&] (bool value, int, const QString &) { connected = value; });
QObject::connect(&client, &RobotClient::agvMapDirectBusyChanged, &context,
[&] (bool value) { busy = value; busyEvents.push_back(value); });
QObject::connect(&client, &RobotClient::agvMapContentReceived, &context,
[&] (quint64 id, const QString &device, const QString &map, const QString &content,
bool success, const QString &detail) {
readEvents[id].push_back({success, device, map, content, detail});
});
QObject::connect(&client, &RobotClient::agvMapSaveFinished, &context,
[&] (quint64 id, const QString &, const QString &, bool success, const QString &detail) {
saveEvents[id].push_back({success, detail});
});
QObject::connect(&client, &RobotClient::commandFinished, &context,
[&] (const QString &command, bool success, const QString &detail) {
if (command == QStringLiteral("AGV SwitchMap"))
switchEvents.push_back({success, detail});
if (command == QStringLiteral("AGV SetVelocity") && !success)
++rejectedVelocities;
});
QObject::connect(&client, &RobotClient::agvDirectMapSwitchConfirmed, &context,
[&] (const QString &device, const QString &map, const QString &) {
confirmations.push_back({device, map});
});
}
bool connected = false;
bool busy = false;
int rejectedVelocities = 0;
std::vector<bool> busyEvents;
std::map<quint64, std::vector<ReadEvent>> readEvents;
std::map<quint64, std::vector<SaveEvent>> saveEvents;
std::vector<SaveEvent> switchEvents;
std::vector<std::pair<QString, QString>> confirmations;
QObject context;
};
void configure(RobotClient &client, Capture &capture, FakeServices &services, bool enabled = true, bool demo = false)
{
client.configureAgvMapDirect(enabled, QString(), QStringLiteral("127.0.0.1"), services.port);
client.connectToServer(QStringLiteral("127.0.0.1"), services.port, demo);
waitFor([&] { return capture.connected; }, "RobotClient connects to loopback or local Demo source");
}
void successfulChain()
{
FakeRobot robot;
robot.state.fragment.store(true);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
configure(client, capture, services);
// Mimic the editor's read-latest -> upload callback and the page's
// switch-confirmed -> reload callback. Both must see busy already cleared.
QObject::connect(&client, &RobotClient::agvMapContentReceived,
[&] (quint64 id, const QString &, const QString &, const QString &content,
bool success, const QString &) {
if (id == 1 && success)
client.saveAgvMapContent(2, deviceId, mapName, content);
});
QObject::connect(&client, &RobotClient::agvMapSaveFinished,
[&] (quint64 id, const QString &, const QString &, bool success, const QString &) {
if (id == 2 && success)
client.requestAgvSwitchMap(deviceId, mapName);
});
QObject::connect(&client, &RobotClient::agvDirectMapSwitchConfirmed,
[&] (const QString &, const QString &, const QString &) {
client.requestAgvMapContent(3, deviceId, mapName);
});
client.requestAgvMapContent(1, deviceId, mapName);
waitFor([&] { return !capture.readEvents[3].empty(); }, "real bridge callback chain completes read/save/switch/reload");
require(capture.readEvents[1].size() == 1 && capture.readEvents[1][0].success,
"bridge reports initial complete map read once");
require(capture.saveEvents[2].size() == 1 && capture.saveEvents[2][0].success,
"read callback can start save without spurious busy rejection");
require(capture.readEvents[3].size() == 1 && capture.readEvents[3][0].success
&& capture.readEvents[3][0].content == completeMap, "confirmed switch callback reloads exact target map");
require(capture.switchEvents.size() == 1 && capture.switchEvents[0].success
&& capture.confirmations.size() == 1 && capture.confirmations[0].second == mapName,
"bridge reports confirmed switch exactly once");
require(!capture.busy && capture.busyEvents.size() == 8, "four operations each open and close busy state");
require(robot.state.uploads == 1 && robot.state.switches == 1 && robot.state.reads == 2,
"callback chain sends exactly one mutation per operation");
require(services.configuration.reads == 4 && services.configuration.lists == 4,
"bridge uses existing read-only config API to resolve selected device");
require(services.legacy.uploads == 0 && services.legacy.switches == 0 && services.legacy.reads == 0,
"enabled map bridge bypasses old map gRPC wrapper");
std::lock_guard<std::mutex> lock(robot.state.captureMutex);
require(robot.state.uploaded == completeMap.toUtf8(), "actual RobotClient bridge preserves complete raw 4010 payload");
std::cout << "PASS bridge read-latest/save/switch-confirmed/reload callback chain\n";
}
void definiteErrors()
{
{
FakeRobot robot(Fault::HeaderRejected);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
configure(client, capture, services);
client.saveAgvMapContent(10, deviceId, mapName, completeMap);
waitFor([&] { return !capture.saveEvents[10].empty(); }, "bridge returns controller save rejection");
require(capture.saveEvents[10].size() == 1 && !capture.saveEvents[10][0].success
&& capture.saveEvents[10][0].detail.contains(QStringLiteral("40050")),
"save rejection never becomes success in queued signal delivery");
require(robot.state.uploads == 1 && services.legacy.uploads == 0, "save rejection has no hidden legacy fallback or resend");
}
{
FakeRobot robot(Fault::LoadRejected);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
configure(client, capture, services);
client.requestAgvSwitchMap(deviceId, mapName);
waitFor([&] { return !capture.switchEvents.empty(); }, "bridge returns explicit failed map load after accepted ACK");
require(capture.switchEvents.size() == 1 && !capture.switchEvents[0].success
&& capture.confirmations.empty(), "accepted ACK plus explicit load failure never reports successful switch");
require(robot.state.switches == 1, "load failure is not resent by bridge");
}
std::cout << "PASS bridge preserves save rejection and explicit load failure\n";
}
void busyAndContextCancellation()
{
FakeRobot robot;
robot.state.readDelayMs.store(500);
FakeServices services(robot);
RobotClient client;
Capture capture(client);
configure(client, capture, services);
client.requestAgvMapContent(20, deviceId, mapName);
require(capture.busy, "starting async map read immediately marks bridge busy");
client.saveAgvMapContent(21, deviceId, mapName, completeMap);
require(capture.saveEvents[21].size() == 1 && !capture.saveEvents[21][0].success,
"second mutation while busy is immediately rejected");
waitFor([&] { return robot.state.reads == 1; }, "fake first read reached TCP channel");
client.requestAgvMapContent(22, QStringLiteral("different_device"), mapName);
waitFor([&] { return !capture.busy; }, "device context change cancels old direct worker promptly");
pumpFor(650);
require(capture.readEvents[20].size() == 1 && !capture.readEvents[20][0].success,
"old context receives cancellation failure but no late success");
require(capture.readEvents[22].size() == 1 && !capture.readEvents[22][0].success,
"new context does not queue another operation while prior worker drains");
require(robot.state.uploads == 0 && robot.state.reads == 1,
"busy rejection and context cancellation send no queued mutation or duplicate read");
robot.state.readDelayMs.store(0);
client.requestAgvMapContent(23, deviceId, mapName);
waitFor([&] { return !capture.readEvents[23].empty(); }, "bridge becomes usable again after cancelled context drains");
require(capture.readEvents[23].size() == 1 && capture.readEvents[23][0].success,
"fresh context returns requested complete map without old result leakage");
std::cout << "PASS bridge busy deduplication and stale context cancellation\n";
}
void legacyAndDemoPaths()
{
{
FakeRobot robot;
FakeServices services(robot);
RobotClient client;
Capture capture(client);
configure(client, capture, services, false);
client.requestAgvMapContent(30, deviceId, mapName);
waitFor([&] { return !capture.readEvents[30].empty(); }, "disabled direct mode uses legacy read");
client.saveAgvMapContent(31, deviceId, mapName, completeMap);
waitFor([&] { return !capture.saveEvents[31].empty(); }, "disabled direct mode uses legacy upload");
require(capture.readEvents[30][0].success && capture.saveEvents[31][0].success
&& services.legacy.reads == 1 && services.legacy.uploads == 1,
"existing gRPC map interface still works when direct mode disabled");
require(robot.state.reads == 0 && robot.state.uploads == 0 && services.configuration.lists == 0,
"disabled direct mode opens no TCP or config discovery requests");
}
{
FakeRobot robot;
FakeServices services(robot);
RobotClient client;
Capture capture(client);
configure(client, capture, services, true, true);
const QString demoDevice = QStringLiteral("demo_agv_1");
client.saveAgvMapContent(40, demoDevice, mapName, completeMap);
waitFor([&] { return !capture.saveEvents[40].empty(); }, "Demo map save remains on local worker");
client.requestAgvMapContent(41, demoDevice, mapName);
waitFor([&] { return !capture.readEvents[41].empty(); }, "Demo reload remains on local worker");
client.requestAgvSwitchMap(demoDevice, mapName);
waitFor([&] { return !capture.switchEvents.empty(); }, "Demo switch remains on local worker");
require(capture.saveEvents[40][0].success && capture.readEvents[41][0].success
&& capture.readEvents[41][0].content == completeMap && capture.switchEvents[0].success,
"Demo save/read/switch still completes with direct option enabled");
require(capture.busyEvents.empty() && capture.confirmations.empty()
&& robot.state.reads == 0 && robot.state.uploads == 0 && robot.state.switches == 0
&& services.configuration.lists == 0 && services.legacy.uploads == 0,
"Demo uses neither real map TCP nor config lookup nor legacy network writes");
}
std::cout << "PASS unchanged legacy gRPC and local Demo map paths\n";
}
void backendQueueBarrier()
{
{
FakeRobot robot;
FakeServices services(robot);
RobotClient client;
Capture capture(client);
configure(client, capture, services);
services.legacy.holdVelocity.store(true);
client.requestAgvVelocity(deviceId, 0.1, 0.0, 0.0);
waitFor([&] { return services.legacy.velocities == 1; }, "old motion RPC is blocked in original worker");
client.requestAgvVelocity(deviceId, 0.2, 0.0, 0.0);
client.saveAgvMapContent(50, deviceId, mapName, completeMap);
client.requestAgvVelocity(deviceId, 0.3, 0.0, 0.0);
pumpFor(300);
require(capture.busy && capture.rejectedVelocities == 1, "busy map operation blocks newly requested motion");
require(services.configuration.lists == 0 && robot.state.acquires == 0 && robot.state.uploads == 0,
"direct lookup, authority and map upload all wait for prior backend worker commands");
services.legacy.holdVelocity.store(false);
waitFor([&] { return !capture.saveEvents[50].empty(); }, "queued old motions drain before direct map operation");
require(capture.saveEvents[50].size() == 1 && capture.saveEvents[50][0].success,
"direct operation succeeds once backend barrier is passed");
require(services.legacy.velocities == 2 && services.legacy.velocitiesFinished == 2 && robot.state.uploads == 1,
"only preexisting motions and exactly one map mutation were dispatched");
}
{
FakeRobot robot;
FakeServices services(robot);
RobotClient client;
Capture capture(client);
configure(client, capture, services);
services.legacy.holdVelocity.store(true);
client.requestAgvVelocity(deviceId, 0.1, 0.0, 0.0);
waitFor([&] { return services.legacy.velocities == 1; }, "cancellation case has old worker RPC in flight");
client.saveAgvMapContent(51, deviceId, mapName, completeMap);
client.cancelAgvMapDirectRequests();
require(capture.saveEvents[51].size() == 1 && !capture.saveEvents[51][0].success,
"cancelling barrier-waiting operation immediately reports cancelled save");
services.legacy.holdVelocity.store(false);
waitFor([&] { return !capture.busy; }, "cancelled backend barrier drains boundedly");
pumpFor(100);
require(capture.saveEvents[51].size() == 1 && services.configuration.lists == 0
&& robot.state.acquires == 0 && robot.state.uploads == 0,
"cancelled barrier never runs direct lookup or mutation and produces no late result");
}
std::cout << "PASS backend queue barrier, new motion rejection and cancellation before barrier\n";
}
} // namespace
int main(int argc, char **argv)
{
QApplication application(argc, argv);
successfulChain();
definiteErrors();
busyAndContextCancellation();
legacyAndDemoPaths();
backendQueueBarrier();
std::cout << "PASS RobotClient SEER map bridge integration: only ephemeral loopback services used\n";
return 0;
}

View File

@ -0,0 +1,266 @@
#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

View File

@ -0,0 +1,136 @@
#include "seeragvmapclient_fake.h"
namespace {
void readChecks()
{
{
FakeRobot robot;
robot.state.fragment.store(true);
const auto result = SeerAgvMapClient::readMap(robot.connection, mapName, {});
require(result.success && result.content == completeMap, "fragmented map read preserves all original text");
std::lock_guard<std::mutex> lock(robot.state.captureMutex);
require(robot.state.reads == 1 && robot.state.requestedReadName == mapName, "read uses map_name without file suffix");
require(robot.state.uploads == 0 && robot.state.switches == 0 && robot.state.acquires == 0, "read never changes robot");
}
for (Fault fault : {Fault::ReadRejected, Fault::WrongType, Fault::WrongSequence}) {
FakeRobot robot(fault);
const auto result = SeerAgvMapClient::readMap(robot.connection, mapName, {});
require(!result.success && !result.accepted, "failed read or mismatched response must not succeed");
require(robot.state.reads == 1 && robot.state.uploads == 0 && robot.state.switches == 0,
"failed read sends no writes and no duplicate read");
}
}
void saveChecks()
{
{
FakeRobot robot;
robot.state.fragment.store(true);
const auto result = SeerAgvMapClient::saveMap(robot.connection, mapName, completeMap, {});
require(result.success && result.accepted && !result.uncertain, "save requires explicit success ACK");
require(robot.state.uploads == 1 && robot.state.acquires == 1, "save obtains authority and uploads once");
require(robot.state.speedReads >= 2 && robot.state.taskReads >= 2, "save rechecks motion and task after obtaining authority");
std::lock_guard<std::mutex> lock(robot.state.captureMutex);
require(robot.state.nickName == robot.connection.nickName, "authority nickname is passed intact");
require(robot.state.uploaded == completeMap.toUtf8(), "4010 body is exact full SMAP, preserving header, Unicode, decimals and uint64");
require(!robot.state.uploaded.contains("map_content"), "save does not add old service wrapper");
}
for (Fault fault : {Fault::Moving, Fault::ActiveTask, Fault::MissingSpeed, Fault::MissingTask}) {
FakeRobot robot(fault);
const auto result = SeerAgvMapClient::saveMap(robot.connection, mapName, completeMap, {});
require(!result.success && !result.accepted, "unsafe or unverifiable robot state blocks save");
require(robot.state.uploads == 0 && robot.state.acquires == 0, "unsafe state never obtains authority or writes map");
}
{
FakeRobot robot;
const auto result = SeerAgvMapClient::saveMap(robot.connection, QStringLiteral("OTHER"), completeMap, {});
require(!result.success && robot.state.uploads == 0 && robot.state.acquires == 0,
"map name mismatch blocks write before obtaining authority");
}
{
FakeRobot robot(Fault::HeaderRejected);
const auto result = SeerAgvMapClient::saveMap(robot.connection, mapName, completeMap, {});
require(!result.success && !result.accepted && !result.uncertain, "ret_code 40050 is a definite save rejection");
require(result.detail.contains(QStringLiteral("40050")) && result.detail.contains(QStringLiteral("need map header")),
"controller header error remains visible");
require(robot.state.uploads == 1, "rejected map upload is never retried automatically");
}
{
FakeRobot robot(Fault::SilentUpload);
const auto result = SeerAgvMapClient::saveMap(robot.connection, mapName, completeMap, {});
require(!result.success && result.uncertain, "upload ACK timeout reports uncertain outcome");
require(robot.state.uploads == 1, "timeout never resends map mutation");
}
for (Fault fault : {Fault::WrongUploadType, Fault::WrongUploadSequence, Fault::MissingUploadAck}) {
FakeRobot robot(fault);
const auto result = SeerAgvMapClient::saveMap(robot.connection, mapName, completeMap, {});
require(!result.success && !result.accepted && result.uncertain,
"missing or mismatched upload acknowledgement remains uncertain");
require(robot.state.uploads == 1, "invalid upload response never resends map");
}
{
FakeRobot robot(Fault::AuthorityRejected);
const auto result = SeerAgvMapClient::saveMap(robot.connection, mapName, completeMap, {});
require(!result.success && !result.accepted && !result.uncertain && robot.state.acquires == 1,
"authority rejection is definite and does not imply map acceptance");
require(robot.state.uploads == 0, "no map upload follows failed control acquisition");
}
}
void switchChecks()
{
{
FakeRobot robot;
const auto result = SeerAgvMapClient::switchMap(robot.connection, mapName, {});
require(result.success && result.accepted && !result.uncertain && result.currentMap == mapName,
"switch succeeds only after load state and current map agree");
require(robot.state.switches == 1 && robot.state.loadReads >= 2 && robot.state.currentMapReads >= 1,
"switch ACK is followed by loading and actual map confirmation");
std::lock_guard<std::mutex> lock(robot.state.captureMutex);
require(robot.state.requestedSwitchName == mapName, "switch sends bare map name");
}
{
FakeRobot robot(Fault::LoadRejected);
const auto result = SeerAgvMapClient::switchMap(robot.connection, mapName, {});
require(!result.success && result.accepted, "accepted switch with failed load remains a failure");
require(robot.state.switches == 1, "failed loading does not resend switch");
}
{
FakeRobot robot(Fault::WrongCurrentMap);
const auto result = SeerAgvMapClient::switchMap(robot.connection, mapName, {});
require(!result.success && result.accepted, "successful load with different current map does not confirm target");
require(robot.state.switches == 1, "confirmation timeout never resends switch");
}
}
void cancellationChecks()
{
{
FakeRobot robot;
const auto result = SeerAgvMapClient::saveMap(robot.connection, mapName, completeMap, [] { return true; });
require(!result.success && !result.accepted && robot.state.uploads == 0 && robot.state.acquires == 0,
"pre-cancelled save makes no mutations");
}
{
FakeRobot robot(Fault::SilentUpload);
QElapsedTimer elapsed;
elapsed.start();
const auto result = SeerAgvMapClient::saveMap(robot.connection, mapName, completeMap,
[&robot] { return robot.state.uploads.load() != 0; });
require(!result.success && result.uncertain, "cancel after upload retains uncertain outcome");
require(robot.state.uploads == 1 && elapsed.elapsed() < 3000, "in-flight cancellation is bounded and never retries write");
}
}
} // namespace
int main(int argc, char **argv)
{
QCoreApplication application(argc, argv);
readChecks();
saveChecks();
switchChecks();
cancellationChecks();
std::cout << "PASS SEER map direct TCP: raw payload preservation, fragmented frames, strict response identity,"
" state gates, authority, ACK rejection, loading confirmation, no mutation retry, cancellation\n";
return 0;
}