From 22620db6994f01152124edbbb8ff7592b4e18ca2 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 10 Nov 2026 16:10:46 +0800 Subject: [PATCH] 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. --- CMakeLists.txt | 13 +- CmvrControlStation.pro | 11 +- README.md | 16 + assets/agv/LICENSE.txt | 202 +++ assets/agv/SOURCE.md | 26 + assets/agv/demo_scan.smap | 1 + resources.qrc | 1 + src/agvmapdocument.cpp | 1013 ++++++++++++ src/agvmapdocument.h | 89 + src/agvmapeditorwidget.cpp | 1160 +++++++++++++ src/agvmapeditorwidget.h | 103 ++ src/agvmaprasterizer.cpp | 205 +++ src/agvmaprasterizer.h | 11 + src/agvmapviewwidget.cpp | 739 +++++++-- src/agvmapviewwidget.h | 46 + src/agvvelocityramp.h | 153 ++ src/mainwindow.cpp | 614 ++++++- src/mainwindow.h | 66 +- src/mainwindow_ui.cpp | 508 +++++- src/robotclient.cpp | 1298 +++++++++++++-- src/robotclient.h | 70 +- src/seeragvmapclient.cpp | 559 +++++++ src/seeragvmapclient.h | 51 + tests/agvdemo_map_test.cpp | 226 +++ tests/agvmanualmotion_test.cpp | 421 +++++ tests/agvmapdocument_test.cpp | 665 ++++++++ .../agvmapeditor_delete_integration_test.cpp | 503 ++++++ tests/agvmapeditor_delete_test.cpp | 313 ++++ tests/agvmapeditor_failure_test.cpp | 686 ++++++++ tests/agvmapeditor_smoke.cpp | 203 +++ .../agvmapeditor_upload_integration_test.cpp | 645 ++++++++ tests/agvmaprasterizer_test.cpp | 260 +++ tests/agvmapstream_fallback_test.cpp | 644 ++++++++ tests/agvmapviewwidget_test.cpp | 683 ++++++++ tests/agvpage_smoke.cpp | 1458 +++++++++++++++++ tests/agvvelocityramp_test.cpp | 239 +++ tests/robotclient_agvmanualvelocity_test.cpp | 264 +++ .../robotclient_seer_map_integration_test.cpp | 428 +++++ tests/seeragvmapclient_fake.h | 266 +++ tests/seeragvmapclient_test.cpp | 136 ++ 40 files changed, 14699 insertions(+), 296 deletions(-) create mode 100644 assets/agv/LICENSE.txt create mode 100644 assets/agv/SOURCE.md create mode 100644 assets/agv/demo_scan.smap create mode 100644 src/agvmapdocument.cpp create mode 100644 src/agvmapdocument.h create mode 100644 src/agvmapeditorwidget.cpp create mode 100644 src/agvmapeditorwidget.h create mode 100644 src/agvmaprasterizer.cpp create mode 100644 src/agvmaprasterizer.h create mode 100644 src/agvvelocityramp.h create mode 100644 src/seeragvmapclient.cpp create mode 100644 src/seeragvmapclient.h create mode 100644 tests/agvdemo_map_test.cpp create mode 100644 tests/agvmanualmotion_test.cpp create mode 100644 tests/agvmapdocument_test.cpp create mode 100644 tests/agvmapeditor_delete_integration_test.cpp create mode 100644 tests/agvmapeditor_delete_test.cpp create mode 100644 tests/agvmapeditor_failure_test.cpp create mode 100644 tests/agvmapeditor_smoke.cpp create mode 100644 tests/agvmapeditor_upload_integration_test.cpp create mode 100644 tests/agvmaprasterizer_test.cpp create mode 100644 tests/agvmapstream_fallback_test.cpp create mode 100644 tests/agvmapviewwidget_test.cpp create mode 100644 tests/agvpage_smoke.cpp create mode 100644 tests/agvvelocityramp_test.cpp create mode 100644 tests/robotclient_agvmanualvelocity_test.cpp create mode 100644 tests/robotclient_seer_map_integration_test.cpp create mode 100644 tests/seeragvmapclient_fake.h create mode 100644 tests/seeragvmapclient_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 1008af4..ac9a0bb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,7 +30,7 @@ set(PROTO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/protos") set(GENERATED_ROOT "${CMAKE_CURRENT_BINARY_DIR}/generated_cpp") 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) if(CMVR_QMAKE_EXECUTABLE) @@ -152,6 +152,15 @@ if(CMVR_WITH_MSQUIC) endif() 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.h src/audiostreammanager.cpp @@ -259,7 +268,7 @@ if(CMVR_WITH_MSQUIC) endif() 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) # Generate every project-local CMVR message. This avoids source-tree generated diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index b3f2ffd..5eb83bb 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -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 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.") SOURCES += \ + src/seeragvmapclient.cpp \ + src/agvmapdocument.cpp \ + src/agvmaprasterizer.cpp \ + src/agvmapeditorwidget.cpp \ src/applicationsettings.cpp \ src/applicationstyle.cpp \ src/taskorchestrationwidget.cpp \ @@ -272,6 +276,11 @@ SOURCES += \ ui/handeyecalibrationwidget.cpp HEADERS += \ + src/agvvelocityramp.h \ + src/seeragvmapclient.h \ + src/agvmapdocument.h \ + src/agvmaprasterizer.h \ + src/agvmapeditorwidget.h \ src/applicationsettings.h \ src/applicationstyle.h \ src/appmessagebox.h \ diff --git a/README.md b/README.md index eaab6ca..e21b375 100644 --- a/README.md +++ b/README.md @@ -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 通道连接成功时自动调用 `GetSystemInfo` 和 `GetSystemStatus`。 diff --git a/assets/agv/LICENSE.txt b/assets/agv/LICENSE.txt new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/assets/agv/LICENSE.txt @@ -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. \ No newline at end of file diff --git a/assets/agv/SOURCE.md b/assets/agv/SOURCE.md new file mode 100644 index 0000000..f855ee1 --- /dev/null +++ b/assets/agv/SOURCE.md @@ -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. diff --git a/assets/agv/demo_scan.smap b/assets/agv/demo_scan.smap new file mode 100644 index 0000000..9313e8c --- /dev/null +++ b/assets/agv/demo_scan.smap @@ -0,0 +1 @@ +{"advanced_curve_list":[{"class_name":"BezierPath","control_pos1":{"x":-10,"y":2},"control_pos2":{"x":-10,"y":1},"end_pos":{"instance_name":"LM2","pos":{"x":-10,"y":0}},"instance_name":"LM1_LM2","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM1","pos":{"x":-10,"y":3}}},{"class_name":"BezierPath","control_pos1":{"x":-10,"y":1},"control_pos2":{"x":-10,"y":2},"end_pos":{"instance_name":"LM1","pos":{"x":-10,"y":3}},"instance_name":"LM1_LM2_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM2","pos":{"x":-10,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":-9,"y":0},"control_pos2":{"x":-7.999999999999999,"y":0},"end_pos":{"instance_name":"LM7","pos":{"x":-7,"y":0}},"instance_name":"LM2_LM7","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM2","pos":{"x":-10,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":-7.999999999999999,"y":0},"control_pos2":{"x":-9,"y":0},"end_pos":{"instance_name":"LM2","pos":{"x":-10,"y":0}},"instance_name":"LM2_LM7_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM7","pos":{"x":-7,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":-5.999999999999999,"y":0},"control_pos2":{"x":-5,"y":0},"end_pos":{"instance_name":"LM3","pos":{"x":-4,"y":0}},"instance_name":"LM7_LM3","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM7","pos":{"x":-7,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":-5,"y":0},"control_pos2":{"x":-5.999999999999999,"y":0},"end_pos":{"instance_name":"LM7","pos":{"x":-7,"y":0}},"instance_name":"LM7_LM3_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM3","pos":{"x":-4,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":-2.6666666666666665,"y":0},"control_pos2":{"x":-1.3333333333333333,"y":0},"end_pos":{"instance_name":"HOME","pos":{"x":0,"y":0}},"instance_name":"LM3_HOME","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM3","pos":{"x":-4,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":-1.3333333333333333,"y":0},"control_pos2":{"x":-2.6666666666666665,"y":0},"end_pos":{"instance_name":"LM3","pos":{"x":-4,"y":0}},"instance_name":"LM3_HOME_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"HOME","pos":{"x":0,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":0.6666666666666666,"y":0.06666666666666667},"control_pos2":{"x":1.3333333333333333,"y":0.13333333333333333},"end_pos":{"instance_name":"LM10","pos":{"x":2,"y":0.2}},"instance_name":"HOME_LM10","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"HOME","pos":{"x":0,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":1.3333333333333333,"y":0.13333333333333333},"control_pos2":{"x":0.6666666666666666,"y":0.06666666666666667},"end_pos":{"instance_name":"HOME","pos":{"x":0,"y":0}},"instance_name":"HOME_LM10_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM10","pos":{"x":2,"y":0.2}}},{"class_name":"BezierPath","control_pos1":{"x":5.333333333333333,"y":0.2},"control_pos2":{"x":8.666666666666666,"y":0.2},"end_pos":{"instance_name":"LM4","pos":{"x":12,"y":0.2}},"instance_name":"LM10_LM4","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM10","pos":{"x":2,"y":0.2}}},{"class_name":"BezierPath","control_pos1":{"x":8.666666666666666,"y":0.2},"control_pos2":{"x":5.333333333333333,"y":0.2},"end_pos":{"instance_name":"LM10","pos":{"x":2,"y":0.2}},"instance_name":"LM10_LM4_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM4","pos":{"x":12,"y":0.2}}},{"class_name":"BezierPath","control_pos1":{"x":2,"y":1.7999999999999998},"control_pos2":{"x":2,"y":3.4},"end_pos":{"instance_name":"LM9","pos":{"x":2,"y":5}},"instance_name":"LM10_LM9","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM10","pos":{"x":2,"y":0.2}}},{"class_name":"BezierPath","control_pos1":{"x":2,"y":3.4},"control_pos2":{"x":2,"y":1.7999999999999998},"end_pos":{"instance_name":"LM10","pos":{"x":2,"y":0.2}},"instance_name":"LM10_LM9_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM9","pos":{"x":2,"y":5}}},{"class_name":"BezierPath","control_pos1":{"x":4.666666666666666,"y":5},"control_pos2":{"x":7.333333333333333,"y":5},"end_pos":{"instance_name":"LM8","pos":{"x":10,"y":5}},"instance_name":"LM9_LM8","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM9","pos":{"x":2,"y":5}}},{"class_name":"BezierPath","control_pos1":{"x":7.333333333333333,"y":5},"control_pos2":{"x":4.666666666666666,"y":5},"end_pos":{"instance_name":"LM9","pos":{"x":2,"y":5}},"instance_name":"LM9_LM8_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM8","pos":{"x":10,"y":5}}},{"class_name":"BezierPath","control_pos1":{"x":10.666666666666666,"y":3.4},"control_pos2":{"x":11.333333333333332,"y":1.7999999999999998},"end_pos":{"instance_name":"LM4","pos":{"x":12,"y":0.2}},"instance_name":"LM8_LM4","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM8","pos":{"x":10,"y":5}}},{"class_name":"BezierPath","control_pos1":{"x":11.333333333333332,"y":1.7999999999999998},"control_pos2":{"x":10.666666666666666,"y":3.4},"end_pos":{"instance_name":"LM8","pos":{"x":10,"y":5}},"instance_name":"LM8_LM4_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM4","pos":{"x":12,"y":0.2}}},{"class_name":"BezierPath","control_pos1":{"x":-4,"y":-1.3333333333333333},"control_pos2":{"x":-4,"y":-2.6666666666666665},"end_pos":{"instance_name":"LM6","pos":{"x":-4,"y":-4}},"instance_name":"LM3_LM6","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM3","pos":{"x":-4,"y":0}}},{"class_name":"BezierPath","control_pos1":{"x":-4,"y":-2.6666666666666665},"control_pos2":{"x":-4,"y":-1.3333333333333333},"end_pos":{"instance_name":"LM3","pos":{"x":-4,"y":0}},"instance_name":"LM3_LM6_reverse","property":[{"int32_value":0,"key":"direction","type":"int","value":"MA=="},{"int32_value":0,"key":"movestyle","type":"int","value":"MA=="}],"start_pos":{"instance_name":"LM6","pos":{"x":-4,"y":-4}}}],"advanced_point_list":[{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"HOME","description":"起点","pos":{"x":0,"y":0},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM1","description":"站点1","pos":{"x":-10,"y":3},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM2","description":"站点2","pos":{"x":-10,"y":0},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM7","description":"站点7","pos":{"x":-7,"y":0},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM3","description":"站点3","pos":{"x":-4,"y":0},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM4","description":"站点4","pos":{"x":12,"y":0.2},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM8","description":"站点8","pos":{"x":10,"y":5},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM9","description":"站点9","pos":{"x":2,"y":5},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM10","description":"站点10","pos":{"x":2,"y":0.2},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"LandMark","dir":0,"ignore_dir":false,"instance_name":"LM6","description":"站点6","pos":{"x":-4,"y":-4},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]},{"class_name":"ChargePoint","dir":0,"ignore_dir":false,"instance_name":"CP5","description":"充电点","pos":{"x":-4,"y":-4.7},"property":[{"bool_value":false,"key":"spin","type":"bool","value":"ZmFsc2U="}]}],"header":{"map_name":"demo_scan_map","map_type":"2D-Map","max_pos":{"x":15.1,"y":7.460000000000001},"min_pos":{"x":-15.1,"y":-7.74},"resolution":0.04,"source":"demo","version":"demo-scan-v1"},"normal_pos_list":[{"x":-14.72,"y":7.4},{"x":-14.68,"y":7.4},{"x":-14.6,"y":7.4},{"x":-14.52,"y":7.4},{"x":-14.44,"y":7.4},{"x":-14.36,"y":7.4},{"x":-14.28,"y":7.4},{"x":-14.2,"y":7.4},{"x":-14.12,"y":7.4},{"x":-14.04,"y":7.4},{"x":-13.96,"y":7.4},{"x":-13.88,"y":7.4},{"x":-13.8,"y":7.4},{"x":-13.72,"y":7.4},{"x":-13.64,"y":7.4},{"x":-13.56,"y":7.4},{"x":-13.48,"y":7.4},{"x":-13.4,"y":7.4},{"x":-13.32,"y":7.4},{"x":-13.24,"y":7.4},{"x":-13.16,"y":7.4},{"x":-13.08,"y":7.4},{"x":-13,"y":7.4},{"x":-12.92,"y":7.4},{"x":-12.84,"y":7.4},{"x":-12.76,"y":7.44},{"x":-12.68,"y":7.4},{"x":-12.6,"y":7.4},{"x":-12.52,"y":7.44},{"x":-12.44,"y":7.4},{"x":-12.36,"y":7.4},{"x":-12.28,"y":7.44},{"x":-12.2,"y":7.4},{"x":-12.12,"y":7.4},{"x":-12.04,"y":7.44},{"x":-11.96,"y":7.4},{"x":-11.88,"y":7.4},{"x":-11.8,"y":7.44},{"x":-11.72,"y":7.4},{"x":-11.64,"y":7.4},{"x":-11.56,"y":7.4},{"x":-11.48,"y":7.4},{"x":-11.36,"y":7.44},{"x":-11.32,"y":7.4},{"x":-11.24,"y":7.4},{"x":-11.16,"y":7.4},{"x":-11.08,"y":7.4},{"x":-11,"y":7.4},{"x":-10.92,"y":7.4},{"x":-10.84,"y":7.4},{"x":-10.76,"y":7.4},{"x":-10.68,"y":7.4},{"x":-10.6,"y":7.4},{"x":-10.52,"y":7.4},{"x":-10.44,"y":7.4},{"x":-10.36,"y":7.4},{"x":-10.28,"y":7.4},{"x":-10.2,"y":7.4},{"x":-10.12,"y":7.4},{"x":-10.04,"y":7.4},{"x":-9.96,"y":7.4},{"x":-9.88,"y":7.4},{"x":-9.8,"y":7.4},{"x":-9.72,"y":7.4},{"x":-9.64,"y":7.4},{"x":-9.56,"y":7.4},{"x":-9.48,"y":7.4},{"x":-9.4,"y":7.4},{"x":-9.32,"y":7.4},{"x":-9.24,"y":7.4},{"x":-9.16,"y":7.4},{"x":-9.08,"y":7.4},{"x":-9,"y":7.4},{"x":-8.92,"y":7.4},{"x":-8.84,"y":7.4},{"x":-8.76,"y":7.4},{"x":-8.68,"y":7.4},{"x":-8.6,"y":7.4},{"x":-8.52,"y":7.4},{"x":-8.44,"y":7.4},{"x":-8.36,"y":7.4},{"x":-8.28,"y":7.4},{"x":-8.2,"y":7.4},{"x":-8.12,"y":7.4},{"x":-8.04,"y":7.4},{"x":-7.96,"y":7.4},{"x":-7.88,"y":7.4},{"x":-7.8,"y":7.4},{"x":-7.72,"y":7.4},{"x":-7.64,"y":7.4},{"x":-7.36,"y":7.4},{"x":-7.32,"y":7.4},{"x":-7.24,"y":7.4},{"x":-7.16,"y":7.4},{"x":-7.08,"y":7.4},{"x":-7,"y":7.4},{"x":-6.92,"y":7.4},{"x":-6.84,"y":7.4},{"x":-6.76,"y":7.4},{"x":-6.68,"y":7.4},{"x":-6.6,"y":7.4},{"x":-6.52,"y":7.4},{"x":-6.44,"y":7.4},{"x":-6.36,"y":7.4},{"x":-6.28,"y":7.4},{"x":-6.2,"y":7.4},{"x":-6.12,"y":7.4},{"x":-6.04,"y":7.4},{"x":-5.96,"y":7.4},{"x":-5.88,"y":7.4},{"x":-5.8,"y":7.4},{"x":-5.72,"y":7.4},{"x":-5.64,"y":7.4},{"x":-5.56,"y":7.4},{"x":-5.48,"y":7.4},{"x":-5.4,"y":7.4},{"x":-5.32,"y":7.4},{"x":-5.24,"y":7.4},{"x":-5.16,"y":7.4},{"x":-5.08,"y":7.4},{"x":-5,"y":7.4},{"x":-4.92,"y":7.4},{"x":-4.84,"y":7.4},{"x":-4.76,"y":7.4},{"x":-4.68,"y":7.4},{"x":-4.6,"y":7.4},{"x":-4.52,"y":7.4},{"x":-4.44,"y":7.4},{"x":-4.36,"y":7.4},{"x":-4.28,"y":7.4},{"x":-4.2,"y":7.4},{"x":-4.12,"y":7.4},{"x":-4.04,"y":7.4},{"x":-3.96,"y":7.4},{"x":-3.88,"y":7.4},{"x":-3.8,"y":7.4},{"x":-3.72,"y":7.4},{"x":-3.64,"y":7.4},{"x":-3.56,"y":7.4},{"x":-3.48,"y":7.4},{"x":-3.4,"y":7.4},{"x":-3.32,"y":7.4},{"x":-3.24,"y":7.4},{"x":-3.16,"y":7.4},{"x":-3.08,"y":7.4},{"x":-3,"y":7.4},{"x":-2.92,"y":7.4},{"x":-2.84,"y":7.4},{"x":-2.76,"y":7.4},{"x":-2.68,"y":7.4},{"x":-2.6,"y":7.4},{"x":-2.52,"y":7.4},{"x":-2.44,"y":7.4},{"x":-2.36,"y":7.4},{"x":-2.28,"y":7.4},{"x":-2.2,"y":7.4},{"x":-2.12,"y":7.4},{"x":-2.04,"y":7.4},{"x":-1.96,"y":7.4},{"x":-1.88,"y":7.4},{"x":-1.8,"y":7.4},{"x":-1.72,"y":7.4},{"x":-1.64,"y":7.4},{"x":-1.56,"y":7.4},{"x":-1.48,"y":7.4},{"x":-1.4,"y":7.4},{"x":-1.32,"y":7.4},{"x":-1.24,"y":7.4},{"x":-1.16,"y":7.4},{"x":-1.08,"y":7.4},{"x":-1,"y":7.4},{"x":-0.92,"y":7.4},{"x":-0.84,"y":7.4},{"x":-0.76,"y":7.4},{"x":-0.68,"y":7.4},{"x":-0.6,"y":7.4},{"x":-0.52,"y":7.4},{"x":-0.44,"y":7.4},{"x":-0.36,"y":7.4},{"x":-0.28,"y":7.4},{"x":-0.2,"y":7.4},{"x":-0.12,"y":7.4},{"x":0.12,"y":7.4},{"x":0.2,"y":7.4},{"x":0.28,"y":7.4},{"x":0.36,"y":7.4},{"x":0.44,"y":7.4},{"x":0.52,"y":7.4},{"x":0.6,"y":7.4},{"x":0.68,"y":7.4},{"x":0.8,"y":7.44},{"x":0.84,"y":7.4},{"x":0.92,"y":7.4},{"x":1,"y":7.4},{"x":1.08,"y":7.4},{"x":1.16,"y":7.4},{"x":1.24,"y":7.4},{"x":1.32,"y":7.4},{"x":1.4,"y":7.4},{"x":1.48,"y":7.4},{"x":1.6,"y":7.44},{"x":1.64,"y":7.4},{"x":1.72,"y":7.4},{"x":1.8,"y":7.4},{"x":1.88,"y":7.4},{"x":2,"y":7.44},{"x":2.04,"y":7.44},{"x":2.16,"y":7.44},{"x":2.2,"y":7.44},{"x":2.28,"y":7.44},{"x":2.4,"y":7.44},{"x":2.44,"y":7.44},{"x":2.52,"y":7.4},{"x":2.64,"y":7.44},{"x":2.72,"y":7.44},{"x":2.76,"y":7.44},{"x":2.84,"y":7.44},{"x":2.92,"y":7.44},{"x":3,"y":7.4},{"x":3.12,"y":7.44},{"x":3.2,"y":7.44},{"x":3.24,"y":7.4},{"x":3.32,"y":7.44},{"x":3.4,"y":7.44},{"x":3.52,"y":7.44},{"x":3.56,"y":7.44},{"x":3.64,"y":7.44},{"x":3.72,"y":7.44},{"x":3.8,"y":7.44},{"x":3.88,"y":7.44},{"x":3.96,"y":7.44},{"x":4.04,"y":7.44},{"x":4.12,"y":7.44},{"x":4.2,"y":7.44},{"x":4.28,"y":7.44},{"x":4.36,"y":7.4},{"x":4.48,"y":7.44},{"x":4.52,"y":7.44},{"x":4.6,"y":7.44},{"x":4.72,"y":7.44},{"x":4.76,"y":7.44},{"x":4.84,"y":7.44},{"x":4.92,"y":7.44},{"x":5,"y":7.44},{"x":5.08,"y":7.4},{"x":6.04,"y":7.4},{"x":6.24,"y":7.4},{"x":6.28,"y":7.44},{"x":6.4,"y":7.44},{"x":6.44,"y":7.44},{"x":6.52,"y":7.44},{"x":6.6,"y":7.44},{"x":6.68,"y":7.44},{"x":6.76,"y":7.44},{"x":6.84,"y":7.44},{"x":6.92,"y":7.44},{"x":7,"y":7.44},{"x":7.08,"y":7.44},{"x":7.16,"y":7.44},{"x":7.24,"y":7.44},{"x":7.32,"y":7.44},{"x":7.4,"y":7.4},{"x":7.68,"y":7.4},{"x":7.76,"y":7.44},{"x":7.8,"y":7.44},{"x":7.88,"y":7.44},{"x":7.96,"y":7.44},{"x":8.04,"y":7.44},{"x":8.12,"y":7.44},{"x":8.2,"y":7.44},{"x":8.28,"y":7.44},{"x":8.36,"y":7.44},{"x":8.44,"y":7.44},{"x":8.52,"y":7.44},{"x":8.6,"y":7.44},{"x":8.68,"y":7.44},{"x":8.76,"y":7.44},{"x":8.84,"y":7.44},{"x":8.92,"y":7.44},{"x":9,"y":7.44},{"x":9.08,"y":7.44},{"x":9.16,"y":7.44},{"x":9.24,"y":7.44},{"x":9.32,"y":7.44},{"x":9.4,"y":7.44},{"x":9.48,"y":7.44},{"x":9.56,"y":7.44},{"x":9.64,"y":7.44},{"x":9.72,"y":7.44},{"x":9.8,"y":7.44},{"x":9.88,"y":7.44},{"x":9.96,"y":7.44},{"x":10.04,"y":7.44},{"x":10.12,"y":7.44},{"x":10.2,"y":7.44},{"x":10.28,"y":7.44},{"x":10.36,"y":7.44},{"x":10.44,"y":7.44},{"x":10.52,"y":7.44},{"x":10.6,"y":7.44},{"x":10.68,"y":7.44},{"x":10.76,"y":7.44},{"x":10.84,"y":7.44},{"x":10.92,"y":7.44},{"x":11,"y":7.44},{"x":11.08,"y":7.44},{"x":11.16,"y":7.44},{"x":11.24,"y":7.44},{"x":11.32,"y":7.44},{"x":11.4,"y":7.44},{"x":11.48,"y":7.44},{"x":11.56,"y":7.44},{"x":11.64,"y":7.44},{"x":11.72,"y":7.44},{"x":11.8,"y":7.44},{"x":11.88,"y":7.44},{"x":11.96,"y":7.44},{"x":12.04,"y":7.44},{"x":12.12,"y":7.44},{"x":12.2,"y":7.44},{"x":12.28,"y":7.44},{"x":12.36,"y":7.44},{"x":12.44,"y":7.44},{"x":12.52,"y":7.44},{"x":12.6,"y":7.44},{"x":12.68,"y":7.44},{"x":12.76,"y":7.44},{"x":12.84,"y":7.44},{"x":12.92,"y":7.44},{"x":13,"y":7.44},{"x":13.08,"y":7.44},{"x":13.16,"y":7.44},{"x":13.24,"y":7.44},{"x":13.32,"y":7.44},{"x":13.4,"y":7.44},{"x":13.48,"y":7.44},{"x":13.56,"y":7.44},{"x":13.64,"y":7.44},{"x":13.72,"y":7.44},{"x":13.8,"y":7.44},{"x":13.88,"y":7.44},{"x":13.96,"y":7.44},{"x":14.04,"y":7.44},{"x":14.12,"y":7.44},{"x":14.2,"y":7.44},{"x":14.28,"y":7.44},{"x":14.36,"y":7.44},{"x":14.44,"y":7.44},{"x":14.52,"y":7.44},{"x":14.6,"y":7.44},{"x":14.68,"y":7.44},{"x":14.76,"y":7.44},{"x":14.84,"y":7.44},{"x":-14.76,"y":7.36},{"x":-14.68,"y":7.36},{"x":-14.6,"y":7.36},{"x":-14.52,"y":7.36},{"x":-14.44,"y":7.36},{"x":-14.36,"y":7.36},{"x":-14.28,"y":7.36},{"x":-14.2,"y":7.36},{"x":-14.12,"y":7.36},{"x":-14.04,"y":7.36},{"x":-13.96,"y":7.36},{"x":-13.88,"y":7.36},{"x":-13.8,"y":7.36},{"x":-13.72,"y":7.36},{"x":-13.64,"y":7.36},{"x":-13.56,"y":7.36},{"x":-13.48,"y":7.36},{"x":-13.4,"y":7.36},{"x":-13.32,"y":7.36},{"x":-13.24,"y":7.36},{"x":-13.16,"y":7.36},{"x":-13.08,"y":7.36},{"x":-13,"y":7.36},{"x":-12.92,"y":7.36},{"x":-12.84,"y":7.36},{"x":-12.76,"y":7.36},{"x":-12.68,"y":7.36},{"x":-12.6,"y":7.36},{"x":-12.52,"y":7.36},{"x":-12.44,"y":7.36},{"x":-12.36,"y":7.36},{"x":-12.28,"y":7.36},{"x":-12.2,"y":7.36},{"x":-12.12,"y":7.36},{"x":-12.04,"y":7.36},{"x":-11.96,"y":7.36},{"x":-11.88,"y":7.36},{"x":-11.8,"y":7.36},{"x":-11.72,"y":7.36},{"x":-11.64,"y":7.36},{"x":-11.56,"y":7.36},{"x":-11.48,"y":7.36},{"x":-11.4,"y":7.36},{"x":-11.32,"y":7.36},{"x":-11.24,"y":7.36},{"x":-11.16,"y":7.36},{"x":-11.08,"y":7.36},{"x":-11,"y":7.36},{"x":-10.92,"y":7.36},{"x":-10.84,"y":7.36},{"x":-10.76,"y":7.36},{"x":-10.68,"y":7.36},{"x":-10.6,"y":7.36},{"x":-10.52,"y":7.36},{"x":-10.44,"y":7.36},{"x":-10.36,"y":7.36},{"x":-10.28,"y":7.36},{"x":-10.2,"y":7.36},{"x":-10.12,"y":7.36},{"x":-10.04,"y":7.36},{"x":-9.96,"y":7.36},{"x":-9.88,"y":7.36},{"x":-9.8,"y":7.36},{"x":-9.72,"y":7.36},{"x":-9.64,"y":7.36},{"x":-9.56,"y":7.36},{"x":-9.48,"y":7.36},{"x":-9.4,"y":7.36},{"x":-9.32,"y":7.36},{"x":-9.24,"y":7.36},{"x":-9.16,"y":7.36},{"x":-9.08,"y":7.36},{"x":-9,"y":7.36},{"x":-8.92,"y":7.36},{"x":-8.84,"y":7.36},{"x":-8.76,"y":7.36},{"x":-8.68,"y":7.36},{"x":-8.6,"y":7.36},{"x":-8.52,"y":7.36},{"x":-8.44,"y":7.36},{"x":-8.36,"y":7.36},{"x":-8.28,"y":7.36},{"x":-8.2,"y":7.36},{"x":-8.12,"y":7.36},{"x":-8.04,"y":7.36},{"x":-7.96,"y":7.36},{"x":-7.88,"y":7.36},{"x":-7.8,"y":7.36},{"x":-7.72,"y":7.36},{"x":-7.64,"y":7.36},{"x":-7.44,"y":7.32},{"x":-7.4,"y":7.36},{"x":-7.32,"y":7.36},{"x":-7.24,"y":7.36},{"x":-7.16,"y":7.36},{"x":-7.08,"y":7.36},{"x":-7,"y":7.36},{"x":-6.92,"y":7.36},{"x":-6.84,"y":7.36},{"x":-6.76,"y":7.36},{"x":-6.68,"y":7.36},{"x":-6.6,"y":7.36},{"x":-6.52,"y":7.36},{"x":-6.44,"y":7.36},{"x":-6.36,"y":7.36},{"x":-6.28,"y":7.36},{"x":-6.2,"y":7.36},{"x":-6.12,"y":7.36},{"x":-6.04,"y":7.36},{"x":-5.96,"y":7.36},{"x":-5.88,"y":7.36},{"x":-5.8,"y":7.36},{"x":-5.72,"y":7.36},{"x":-5.64,"y":7.36},{"x":-5.56,"y":7.36},{"x":-5.48,"y":7.36},{"x":-5.4,"y":7.36},{"x":-5.32,"y":7.36},{"x":-5.24,"y":7.36},{"x":-5.16,"y":7.36},{"x":-5.08,"y":7.36},{"x":-5,"y":7.36},{"x":-4.92,"y":7.36},{"x":-4.84,"y":7.36},{"x":-4.76,"y":7.36},{"x":-4.68,"y":7.36},{"x":-4.6,"y":7.36},{"x":-4.52,"y":7.36},{"x":-4.44,"y":7.36},{"x":-4.36,"y":7.36},{"x":-4.28,"y":7.36},{"x":-4.2,"y":7.36},{"x":-4.12,"y":7.36},{"x":-4.04,"y":7.36},{"x":-3.96,"y":7.36},{"x":-3.88,"y":7.36},{"x":-3.8,"y":7.36},{"x":-3.72,"y":7.36},{"x":-3.64,"y":7.36},{"x":-3.56,"y":7.36},{"x":-3.48,"y":7.36},{"x":-3.4,"y":7.36},{"x":-3.32,"y":7.36},{"x":-3.24,"y":7.36},{"x":-3.16,"y":7.36},{"x":-3.08,"y":7.36},{"x":-2.96,"y":7.36},{"x":-2.92,"y":7.36},{"x":-2.8,"y":7.36},{"x":-0.12,"y":7.36},{"x":0.2,"y":7.36},{"x":0.84,"y":7.36},{"x":1.36,"y":7.36},{"x":1.72,"y":7.36},{"x":1.84,"y":7.36},{"x":2.2,"y":7.36},{"x":2.28,"y":7.36},{"x":2.44,"y":7.36},{"x":2.56,"y":7.36},{"x":2.6,"y":7.36},{"x":2.68,"y":7.36},{"x":2.88,"y":7.36},{"x":3.04,"y":7.36},{"x":3.24,"y":7.36},{"x":3.32,"y":7.36},{"x":3.4,"y":7.36},{"x":3.6,"y":7.36},{"x":3.68,"y":7.36},{"x":3.72,"y":7.36},{"x":4.24,"y":7.36},{"x":4.48,"y":7.36},{"x":4.56,"y":7.36},{"x":5,"y":7.36},{"x":5.08,"y":7.36},{"x":5.16,"y":7.36},{"x":5.24,"y":7.36},{"x":5.32,"y":7.36},{"x":5.4,"y":7.36},{"x":5.48,"y":7.36},{"x":5.56,"y":7.36},{"x":5.64,"y":7.36},{"x":5.72,"y":7.36},{"x":5.8,"y":7.36},{"x":5.88,"y":7.36},{"x":5.96,"y":7.36},{"x":6.04,"y":7.36},{"x":6.12,"y":7.36},{"x":6.2,"y":7.36},{"x":6.28,"y":7.36},{"x":7.24,"y":7.36},{"x":7.32,"y":7.36},{"x":7.4,"y":7.36},{"x":7.68,"y":7.36},{"x":7.72,"y":7.36},{"x":14.8,"y":7.36},{"x":14.84,"y":7.36},{"x":-14.76,"y":7.28},{"x":-7.6,"y":7.28},{"x":-7.4,"y":7.28},{"x":-7.32,"y":7.28},{"x":-0.12,"y":7.28},{"x":0.2,"y":7.28},{"x":7.4,"y":7.28},{"x":7.68,"y":7.28},{"x":7.72,"y":7.28},{"x":14.8,"y":7.28},{"x":14.84,"y":7.28},{"x":-14.92,"y":7.16},{"x":-14.76,"y":7.2},{"x":-7.6,"y":7.2},{"x":-7.44,"y":7.16},{"x":-7.36,"y":7.2},{"x":-7.32,"y":7.2},{"x":-0.12,"y":7.2},{"x":-0.04,"y":7.16},{"x":0.04,"y":7.16},{"x":0.12,"y":7.16},{"x":0.2,"y":7.2},{"x":7.4,"y":7.2},{"x":7.48,"y":7.16},{"x":7.6,"y":7.2},{"x":7.68,"y":7.2},{"x":7.72,"y":7.2},{"x":14.8,"y":7.2},{"x":14.84,"y":7.2},{"x":14.92,"y":7.2},{"x":15,"y":7.2},{"x":15.08,"y":7.2},{"x":-15,"y":7.12},{"x":-14.92,"y":7.12},{"x":-14.84,"y":7.12},{"x":-14.76,"y":7.12},{"x":-7.6,"y":7.12},{"x":-7.56,"y":7.12},{"x":-7.4,"y":7.12},{"x":-0.16,"y":7.12},{"x":-0.12,"y":7.12},{"x":-0.04,"y":7.12},{"x":0.04,"y":7.12},{"x":0.12,"y":7.12},{"x":15.08,"y":7.12},{"x":-15,"y":7.04},{"x":-7.56,"y":7.04},{"x":-7.48,"y":7.04},{"x":-7.4,"y":7.04},{"x":15.08,"y":7.04},{"x":-15,"y":6.96},{"x":15.08,"y":6.96},{"x":-15,"y":6.88},{"x":15.08,"y":6.88},{"x":-15,"y":6.8},{"x":15.08,"y":6.8},{"x":-15,"y":6.72},{"x":15.08,"y":6.72},{"x":-14.88,"y":6.6},{"x":-14.84,"y":6.64},{"x":15.08,"y":6.64},{"x":-15.04,"y":6.52},{"x":-15,"y":6.52},{"x":-14.88,"y":6.56},{"x":-14.84,"y":6.56},{"x":15.08,"y":6.56},{"x":-15.04,"y":6.48},{"x":-15,"y":6.48},{"x":-14.92,"y":6.48},{"x":-14.84,"y":6.48},{"x":15.08,"y":6.48},{"x":-15.04,"y":6.4},{"x":15.08,"y":6.4},{"x":-15.04,"y":6.32},{"x":15.08,"y":6.32},{"x":-15.04,"y":6.24},{"x":15.08,"y":6.24},{"x":-15.04,"y":6.16},{"x":15.08,"y":6.16},{"x":-15.04,"y":6.08},{"x":15.08,"y":6.08},{"x":-15.04,"y":6},{"x":15.08,"y":6},{"x":-15.04,"y":5.92},{"x":15.08,"y":5.92},{"x":-15.04,"y":5.84},{"x":-15,"y":5.8},{"x":15.08,"y":5.84},{"x":-15.04,"y":5.76},{"x":15.08,"y":5.76},{"x":-15.04,"y":5.68},{"x":-15,"y":5.68},{"x":15.08,"y":5.68},{"x":-15.04,"y":5.6},{"x":15.08,"y":5.6},{"x":-15.04,"y":5.52},{"x":15.08,"y":5.52},{"x":-15.04,"y":5.44},{"x":-15,"y":5.4},{"x":15.08,"y":5.44},{"x":-15.04,"y":5.36},{"x":15.08,"y":5.36},{"x":-15.04,"y":5.28},{"x":-15,"y":5.28},{"x":10.36,"y":5.24},{"x":15.08,"y":5.28},{"x":-15.04,"y":5.2},{"x":-15,"y":5.16},{"x":1.44,"y":5.16},{"x":1.52,"y":5.2},{"x":1.6,"y":5.2},{"x":2.8,"y":5.2},{"x":5.36,"y":5.16},{"x":5.4,"y":5.2},{"x":5.48,"y":5.2},{"x":6.56,"y":5.16},{"x":6.6,"y":5.2},{"x":9.12,"y":5.16},{"x":9.16,"y":5.2},{"x":9.24,"y":5.2},{"x":10.36,"y":5.2},{"x":15.08,"y":5.2},{"x":-15.04,"y":5.12},{"x":-0.92,"y":5.08},{"x":-0.84,"y":5.08},{"x":2.72,"y":5.12},{"x":15.08,"y":5.12},{"x":-15.04,"y":5.04},{"x":-15,"y":5.04},{"x":-1.6,"y":5},{"x":-0.92,"y":5.04},{"x":-0.8,"y":5.04},{"x":15.08,"y":5.04},{"x":-15.04,"y":4.96},{"x":-15,"y":4.96},{"x":-1.68,"y":4.96},{"x":-1.64,"y":4.96},{"x":-1.56,"y":4.96},{"x":-1.28,"y":4.96},{"x":-1.24,"y":4.96},{"x":-0.88,"y":4.96},{"x":-0.84,"y":4.96},{"x":-0.76,"y":4.96},{"x":15.08,"y":4.96},{"x":-15.04,"y":4.88},{"x":-15,"y":4.84},{"x":-1.72,"y":4.88},{"x":-1.64,"y":4.88},{"x":-1.44,"y":4.88},{"x":-1.4,"y":4.88},{"x":-1.32,"y":4.88},{"x":-1.24,"y":4.88},{"x":15.08,"y":4.88},{"x":-15.04,"y":4.8},{"x":-15,"y":4.76},{"x":-1.72,"y":4.8},{"x":-1.6,"y":4.76},{"x":-1.56,"y":4.8},{"x":-1.48,"y":4.8},{"x":-1.4,"y":4.76},{"x":-1.32,"y":4.8},{"x":-0.96,"y":4.76},{"x":-0.84,"y":4.76},{"x":15.08,"y":4.8},{"x":-15.04,"y":4.72},{"x":-15,"y":4.68},{"x":-1.72,"y":4.72},{"x":-1.64,"y":4.72},{"x":-1.52,"y":4.72},{"x":-1.44,"y":4.72},{"x":-1.2,"y":4.72},{"x":-0.84,"y":4.72},{"x":15.08,"y":4.72},{"x":-15.04,"y":4.64},{"x":-15,"y":4.6},{"x":-1.84,"y":4.6},{"x":-1.8,"y":4.64},{"x":-1.72,"y":4.64},{"x":-1.64,"y":4.6},{"x":-1.36,"y":4.6},{"x":-0.8,"y":4.64},{"x":-0.76,"y":4.6},{"x":15.08,"y":4.64},{"x":-15.04,"y":4.56},{"x":-1.84,"y":4.52},{"x":-1.8,"y":4.56},{"x":-1.72,"y":4.56},{"x":-1.52,"y":4.52},{"x":-1.4,"y":4.52},{"x":-0.76,"y":4.56},{"x":15.08,"y":4.56},{"x":-15.04,"y":4.48},{"x":-15,"y":4.48},{"x":-1.96,"y":4.44},{"x":-1.88,"y":4.48},{"x":-1.76,"y":4.48},{"x":-1.72,"y":4.48},{"x":-1.64,"y":4.44},{"x":-1.56,"y":4.48},{"x":-1.44,"y":4.48},{"x":-1.36,"y":4.48},{"x":-1.2,"y":4.44},{"x":-1.08,"y":4.48},{"x":-0.76,"y":4.48},{"x":15.08,"y":4.48},{"x":-15.04,"y":4.4},{"x":-15,"y":4.4},{"x":-2.08,"y":4.36},{"x":-2.04,"y":4.4},{"x":-1.8,"y":4.4},{"x":-1.72,"y":4.4},{"x":-1.6,"y":4.4},{"x":-1.36,"y":4.36},{"x":-1.2,"y":4.36},{"x":-1.16,"y":4.36},{"x":-0.72,"y":4.4},{"x":-0.68,"y":4.36},{"x":15.08,"y":4.4},{"x":-15.04,"y":4.32},{"x":-15,"y":4.28},{"x":-2.08,"y":4.32},{"x":-2.04,"y":4.28},{"x":-1.92,"y":4.28},{"x":-1.76,"y":4.32},{"x":-1.68,"y":4.32},{"x":-1.64,"y":4.32},{"x":-1.48,"y":4.28},{"x":-0.96,"y":4.32},{"x":-0.8,"y":4.32},{"x":-0.68,"y":4.32},{"x":15.08,"y":4.32},{"x":-15.04,"y":4.24},{"x":-15,"y":4.2},{"x":-2.04,"y":4.24},{"x":-1.96,"y":4.24},{"x":-1.88,"y":4.2},{"x":-1.76,"y":4.24},{"x":-1.72,"y":4.24},{"x":-1.6,"y":4.2},{"x":-1.52,"y":4.24},{"x":-1.44,"y":4.2},{"x":-1.36,"y":4.24},{"x":-1,"y":4.2},{"x":-0.92,"y":4.24},{"x":-0.68,"y":4.24},{"x":15.08,"y":4.24},{"x":-15.04,"y":4.16},{"x":-15,"y":4.16},{"x":-2,"y":4.16},{"x":-1.96,"y":4.16},{"x":-1.72,"y":4.16},{"x":-1.6,"y":4.12},{"x":-1.52,"y":4.16},{"x":-1.48,"y":4.16},{"x":-1.28,"y":4.12},{"x":-1.2,"y":4.16},{"x":-1.08,"y":4.16},{"x":-0.88,"y":4.16},{"x":-0.64,"y":4.16},{"x":-0.6,"y":4.12},{"x":15.08,"y":4.16},{"x":-15.04,"y":4.08},{"x":-15,"y":4.04},{"x":-1.96,"y":4.08},{"x":-1.84,"y":4.08},{"x":-1.8,"y":4.08},{"x":-1.68,"y":4.08},{"x":-1.64,"y":4.08},{"x":-1.4,"y":4.04},{"x":-1.32,"y":4.08},{"x":-1.2,"y":4.08},{"x":-1.12,"y":4.08},{"x":-0.92,"y":4.08},{"x":-0.8,"y":4.04},{"x":-0.76,"y":4.08},{"x":-0.6,"y":4.08},{"x":15.08,"y":4.08},{"x":-15.04,"y":4},{"x":-15,"y":4},{"x":-1.92,"y":4},{"x":-1.88,"y":4},{"x":-1.8,"y":4},{"x":-1.68,"y":4},{"x":-1.64,"y":4},{"x":-1.56,"y":3.96},{"x":-1.48,"y":4},{"x":-1.4,"y":3.96},{"x":-1.12,"y":4},{"x":-1.08,"y":4},{"x":-1,"y":3.96},{"x":-0.8,"y":3.96},{"x":-0.76,"y":4},{"x":-0.68,"y":3.96},{"x":-0.6,"y":4},{"x":-0.32,"y":3.96},{"x":-0.28,"y":3.96},{"x":-0.2,"y":3.96},{"x":15.08,"y":4},{"x":-15.04,"y":3.92},{"x":-15,"y":3.92},{"x":-7.72,"y":3.88},{"x":-7.64,"y":3.88},{"x":-7.32,"y":3.88},{"x":-7.24,"y":3.88},{"x":-1.84,"y":3.92},{"x":-1.8,"y":3.88},{"x":-1.72,"y":3.88},{"x":-1.64,"y":3.92},{"x":-1.56,"y":3.88},{"x":-1.48,"y":3.92},{"x":-1.2,"y":3.92},{"x":-1.08,"y":3.92},{"x":-1,"y":3.88},{"x":-0.84,"y":3.88},{"x":-0.76,"y":3.92},{"x":-0.6,"y":3.92},{"x":-0.52,"y":3.88},{"x":-0.44,"y":3.88},{"x":-0.36,"y":3.92},{"x":-0.28,"y":3.92},{"x":7.36,"y":3.88},{"x":7.4,"y":3.88},{"x":7.76,"y":3.88},{"x":7.8,"y":3.88},{"x":15.08,"y":3.92},{"x":-15.04,"y":3.84},{"x":-15,"y":3.8},{"x":-7.72,"y":3.84},{"x":-7.64,"y":3.84},{"x":-7.32,"y":3.84},{"x":-7.24,"y":3.84},{"x":-1.8,"y":3.84},{"x":-1.72,"y":3.84},{"x":-1.6,"y":3.84},{"x":-1.56,"y":3.8},{"x":-1.4,"y":3.84},{"x":-1.32,"y":3.84},{"x":-1.24,"y":3.8},{"x":-1.04,"y":3.84},{"x":-1,"y":3.84},{"x":-0.92,"y":3.8},{"x":-0.72,"y":3.8},{"x":-0.68,"y":3.8},{"x":-0.6,"y":3.84},{"x":-0.52,"y":3.84},{"x":-0.44,"y":3.84},{"x":7.24,"y":3.84},{"x":7.32,"y":3.84},{"x":7.44,"y":3.84},{"x":7.8,"y":3.84},{"x":15.08,"y":3.84},{"x":-15.04,"y":3.76},{"x":-15,"y":3.76},{"x":-7.72,"y":3.76},{"x":-7.64,"y":3.76},{"x":-7.56,"y":3.72},{"x":-7.48,"y":3.72},{"x":-7.4,"y":3.72},{"x":-7.32,"y":3.76},{"x":-7.24,"y":3.76},{"x":-1.76,"y":3.76},{"x":-1.72,"y":3.76},{"x":-1.56,"y":3.76},{"x":-1.48,"y":3.76},{"x":-1.36,"y":3.76},{"x":-1.32,"y":3.76},{"x":-0.96,"y":3.76},{"x":-0.92,"y":3.76},{"x":-0.84,"y":3.76},{"x":-0.76,"y":3.76},{"x":-0.68,"y":3.76},{"x":-0.6,"y":3.76},{"x":7.24,"y":3.76},{"x":7.32,"y":3.76},{"x":7.8,"y":3.76},{"x":15.08,"y":3.76},{"x":-15.04,"y":3.68},{"x":-15,"y":3.68},{"x":-7.72,"y":3.68},{"x":-7.32,"y":3.68},{"x":-7.24,"y":3.68},{"x":-1.72,"y":3.68},{"x":-1.64,"y":3.68},{"x":-1.56,"y":3.68},{"x":-1.44,"y":3.68},{"x":-1.4,"y":3.68},{"x":-1.28,"y":3.68},{"x":-1.2,"y":3.68},{"x":-1.16,"y":3.64},{"x":-1.04,"y":3.68},{"x":-1,"y":3.68},{"x":-0.92,"y":3.68},{"x":-0.8,"y":3.68},{"x":-0.76,"y":3.68},{"x":-0.68,"y":3.68},{"x":7.24,"y":3.68},{"x":7.32,"y":3.68},{"x":7.8,"y":3.68},{"x":15.08,"y":3.68},{"x":-15.04,"y":3.6},{"x":-15,"y":3.6},{"x":-7.72,"y":3.6},{"x":-7.64,"y":3.56},{"x":-7.4,"y":3.56},{"x":-7.28,"y":3.6},{"x":-7.24,"y":3.6},{"x":-1.64,"y":3.6},{"x":-1.56,"y":3.6},{"x":-1.48,"y":3.6},{"x":-1.4,"y":3.56},{"x":-1.28,"y":3.6},{"x":-1.24,"y":3.6},{"x":-1.16,"y":3.6},{"x":-1,"y":3.56},{"x":-0.92,"y":3.6},{"x":-0.84,"y":3.6},{"x":7.24,"y":3.56},{"x":7.32,"y":3.6},{"x":7.44,"y":3.6},{"x":7.48,"y":3.6},{"x":7.56,"y":3.6},{"x":7.64,"y":3.6},{"x":7.72,"y":3.6},{"x":7.8,"y":3.6},{"x":15.08,"y":3.6},{"x":-15.04,"y":3.52},{"x":-15,"y":3.52},{"x":-7.72,"y":3.52},{"x":-7.64,"y":3.52},{"x":-7.56,"y":3.52},{"x":-7.48,"y":3.52},{"x":-7.4,"y":3.52},{"x":-7.32,"y":3.52},{"x":-7.24,"y":3.52},{"x":-1.6,"y":3.52},{"x":-1.56,"y":3.48},{"x":-1.48,"y":3.52},{"x":-1.4,"y":3.52},{"x":-1.12,"y":3.48},{"x":-1.04,"y":3.52},{"x":-1,"y":3.52},{"x":-0.92,"y":3.52},{"x":7.32,"y":3.52},{"x":7.44,"y":3.52},{"x":7.68,"y":3.48},{"x":7.72,"y":3.52},{"x":7.8,"y":3.52},{"x":12.48,"y":3.52},{"x":12.52,"y":3.52},{"x":12.6,"y":3.52},{"x":13.64,"y":3.52},{"x":13.72,"y":3.52},{"x":15.08,"y":3.52},{"x":-15.04,"y":3.44},{"x":-15,"y":3.44},{"x":-7.72,"y":3.44},{"x":-7.64,"y":3.44},{"x":-7.32,"y":3.44},{"x":-7.24,"y":3.44},{"x":-1.56,"y":3.44},{"x":-1.48,"y":3.4},{"x":-1.4,"y":3.44},{"x":-1.2,"y":3.44},{"x":-1.16,"y":3.44},{"x":-1.08,"y":3.44},{"x":7.24,"y":3.4},{"x":7.36,"y":3.44},{"x":7.4,"y":3.44},{"x":7.64,"y":3.4},{"x":7.72,"y":3.44},{"x":7.8,"y":3.44},{"x":12.48,"y":3.44},{"x":12.64,"y":3.44},{"x":12.68,"y":3.44},{"x":12.76,"y":3.44},{"x":12.84,"y":3.44},{"x":12.92,"y":3.44},{"x":13,"y":3.44},{"x":13.08,"y":3.44},{"x":13.16,"y":3.44},{"x":13.24,"y":3.44},{"x":13.32,"y":3.44},{"x":13.4,"y":3.44},{"x":13.48,"y":3.44},{"x":13.56,"y":3.44},{"x":13.64,"y":3.44},{"x":15.08,"y":3.44},{"x":-15.04,"y":3.36},{"x":-15,"y":3.36},{"x":-7.72,"y":3.36},{"x":-7.64,"y":3.36},{"x":-7.32,"y":3.36},{"x":-1.52,"y":3.36},{"x":-1.48,"y":3.36},{"x":-1.4,"y":3.32},{"x":-1.32,"y":3.36},{"x":-1.24,"y":3.36},{"x":12.48,"y":3.36},{"x":12.64,"y":3.36},{"x":15.08,"y":3.36},{"x":-15.04,"y":3.28},{"x":-15,"y":3.28},{"x":-1.48,"y":3.28},{"x":-1.4,"y":3.28},{"x":-1.32,"y":3.28},{"x":12.48,"y":3.28},{"x":12.52,"y":3.28},{"x":12.64,"y":3.28},{"x":12.68,"y":3.28},{"x":12.76,"y":3.28},{"x":12.84,"y":3.28},{"x":12.92,"y":3.28},{"x":13,"y":3.28},{"x":13.08,"y":3.28},{"x":13.16,"y":3.28},{"x":13.24,"y":3.28},{"x":13.32,"y":3.28},{"x":13.4,"y":3.28},{"x":13.48,"y":3.28},{"x":13.56,"y":3.28},{"x":13.64,"y":3.28},{"x":13.72,"y":3.28},{"x":15.08,"y":3.28},{"x":-15.04,"y":3.2},{"x":-14.84,"y":3.16},{"x":12.52,"y":3.2},{"x":12.6,"y":3.2},{"x":12.68,"y":3.2},{"x":12.76,"y":3.2},{"x":12.84,"y":3.2},{"x":12.92,"y":3.2},{"x":13,"y":3.2},{"x":13.08,"y":3.2},{"x":13.16,"y":3.2},{"x":13.24,"y":3.2},{"x":13.32,"y":3.2},{"x":13.4,"y":3.2},{"x":13.48,"y":3.2},{"x":13.56,"y":3.2},{"x":13.64,"y":3.2},{"x":13.72,"y":3.2},{"x":13.8,"y":3.2},{"x":15.08,"y":3.2},{"x":-15,"y":3.12},{"x":-14.92,"y":3.12},{"x":-14.84,"y":3.12},{"x":15.08,"y":3.12},{"x":-14.96,"y":3},{"x":-14.92,"y":3},{"x":-14.84,"y":3.04},{"x":15.08,"y":3.04},{"x":-15,"y":2.96},{"x":-14.92,"y":2.96},{"x":-14.84,"y":2.96},{"x":15.08,"y":2.96},{"x":-15,"y":2.88},{"x":15.08,"y":2.88},{"x":-15,"y":2.8},{"x":15.08,"y":2.8},{"x":-15,"y":2.72},{"x":15.08,"y":2.72},{"x":-15,"y":2.64},{"x":1.52,"y":2.6},{"x":1.6,"y":2.64},{"x":2.64,"y":2.6},{"x":2.68,"y":2.6},{"x":2.8,"y":2.64},{"x":5.44,"y":2.64},{"x":5.48,"y":2.64},{"x":6.48,"y":2.6},{"x":6.64,"y":2.64},{"x":9.16,"y":2.64},{"x":9.24,"y":2.64},{"x":10.36,"y":2.64},{"x":15.08,"y":2.64},{"x":-15,"y":2.56},{"x":1.44,"y":2.56},{"x":1.48,"y":2.56},{"x":1.56,"y":2.56},{"x":2.64,"y":2.56},{"x":2.68,"y":2.56},{"x":2.76,"y":2.56},{"x":5.4,"y":2.56},{"x":6.56,"y":2.56},{"x":9.12,"y":2.56},{"x":15.08,"y":2.56},{"x":-15,"y":2.48},{"x":15.08,"y":2.48},{"x":-15,"y":2.4},{"x":15.08,"y":2.4},{"x":-15,"y":2.32},{"x":15.08,"y":2.32},{"x":-15,"y":2.24},{"x":15.08,"y":2.24},{"x":-15,"y":2.16},{"x":15.08,"y":2.16},{"x":-15,"y":2.08},{"x":15.08,"y":2.08},{"x":-15,"y":2},{"x":15.08,"y":2},{"x":-15,"y":1.92},{"x":15.08,"y":1.92},{"x":-15,"y":1.84},{"x":15.08,"y":1.84},{"x":-15,"y":1.76},{"x":-14.84,"y":1.72},{"x":15.08,"y":1.76},{"x":-14.96,"y":1.68},{"x":-14.92,"y":1.68},{"x":-14.84,"y":1.68},{"x":15.08,"y":1.68},{"x":-15,"y":1.56},{"x":-14.88,"y":1.56},{"x":-14.84,"y":1.6},{"x":15.08,"y":1.6},{"x":-15.04,"y":1.52},{"x":-15,"y":1.52},{"x":-14.92,"y":1.52},{"x":-14.84,"y":1.52},{"x":15.08,"y":1.52},{"x":-15.04,"y":1.44},{"x":-15,"y":1.44},{"x":15.08,"y":1.44},{"x":-15.04,"y":1.36},{"x":-15,"y":1.36},{"x":15.08,"y":1.36},{"x":-15.04,"y":1.28},{"x":-15,"y":1.28},{"x":15.08,"y":1.28},{"x":-15.04,"y":1.2},{"x":-15,"y":1.2},{"x":15.08,"y":1.2},{"x":-15.04,"y":1.12},{"x":-15,"y":1.12},{"x":15.08,"y":1.12},{"x":-15.04,"y":1.04},{"x":-15,"y":1.04},{"x":15.08,"y":1.04},{"x":-15.04,"y":0.96},{"x":-15,"y":0.96},{"x":15.08,"y":0.96},{"x":-15.04,"y":0.88},{"x":-15,"y":0.88},{"x":15.08,"y":0.88},{"x":-15.04,"y":0.8},{"x":-15,"y":0.8},{"x":15.08,"y":0.8},{"x":-15.04,"y":0.72},{"x":-15,"y":0.72},{"x":15.08,"y":0.72},{"x":-15.04,"y":0.64},{"x":-15,"y":0.64},{"x":15.08,"y":0.64},{"x":-15.04,"y":0.56},{"x":-15,"y":0.56},{"x":15.08,"y":0.56},{"x":-15.04,"y":0.48},{"x":-15,"y":0.48},{"x":15.08,"y":0.48},{"x":-15.04,"y":0.4},{"x":-15,"y":0.4},{"x":15.08,"y":0.4},{"x":-15.04,"y":0.32},{"x":-15,"y":0.32},{"x":15.08,"y":0.32},{"x":-15.04,"y":0.24},{"x":-15,"y":0.24},{"x":15.08,"y":0.24},{"x":-15.04,"y":0.16},{"x":-15,"y":0.16},{"x":15.08,"y":0.16},{"x":-15.04,"y":0.08},{"x":-15,"y":0.08},{"x":1.44,"y":0.04},{"x":1.52,"y":0.04},{"x":1.56,"y":0.04},{"x":1.64,"y":0.04},{"x":2.68,"y":0.04},{"x":2.76,"y":0.04},{"x":5.44,"y":0.04},{"x":5.48,"y":0.04},{"x":6.6,"y":0.04},{"x":6.68,"y":0.04},{"x":9.16,"y":0.04},{"x":9.24,"y":0.04},{"x":10.36,"y":0.04},{"x":10.44,"y":0.04},{"x":15.08,"y":0.08},{"x":-15.04,"y":0},{"x":-15,"y":0},{"x":1.44,"y":0},{"x":1.52,"y":0},{"x":1.56,"y":0},{"x":1.64,"y":0},{"x":2.68,"y":0},{"x":2.76,"y":0},{"x":5.44,"y":0},{"x":5.48,"y":0},{"x":6.6,"y":0},{"x":6.68,"y":0},{"x":9.16,"y":0},{"x":10.4,"y":0},{"x":15.08,"y":0},{"x":-15.04,"y":-0.08},{"x":-15,"y":-0.08},{"x":15.08,"y":-0.08},{"x":-15.04,"y":-0.16},{"x":-15,"y":-0.16},{"x":15.08,"y":-0.16},{"x":-15.04,"y":-0.24},{"x":-15,"y":-0.24},{"x":15.08,"y":-0.24},{"x":-15.04,"y":-0.32},{"x":-15,"y":-0.32},{"x":15.08,"y":-0.32},{"x":-15.04,"y":-0.4},{"x":-15,"y":-0.4},{"x":15.08,"y":-0.4},{"x":-15.04,"y":-0.48},{"x":-15,"y":-0.48},{"x":15.08,"y":-0.48},{"x":-15.04,"y":-0.56},{"x":-15,"y":-0.56},{"x":15.08,"y":-0.56},{"x":-15.04,"y":-0.64},{"x":-15,"y":-0.64},{"x":15.08,"y":-0.64},{"x":-15.04,"y":-0.72},{"x":-15,"y":-0.72},{"x":15.08,"y":-0.72},{"x":-15.04,"y":-0.8},{"x":-15,"y":-0.8},{"x":15.08,"y":-0.8},{"x":-15.04,"y":-0.88},{"x":-15,"y":-0.88},{"x":15.08,"y":-0.88},{"x":-15.04,"y":-0.96},{"x":-15,"y":-0.96},{"x":15.08,"y":-0.96},{"x":-15.04,"y":-1.04},{"x":-15,"y":-1.04},{"x":15.08,"y":-1.04},{"x":-15.04,"y":-1.12},{"x":-15,"y":-1.12},{"x":15.08,"y":-1.12},{"x":-15.04,"y":-1.2},{"x":-15,"y":-1.2},{"x":15.08,"y":-1.2},{"x":-15.04,"y":-1.28},{"x":-15,"y":-1.28},{"x":15.08,"y":-1.28},{"x":-15.04,"y":-1.36},{"x":-15,"y":-1.36},{"x":15.08,"y":-1.36},{"x":-15.04,"y":-1.44},{"x":-15,"y":-1.44},{"x":15.08,"y":-1.44},{"x":-15.04,"y":-1.52},{"x":-15,"y":-1.52},{"x":15.08,"y":-1.52},{"x":-15.04,"y":-1.6},{"x":-15,"y":-1.6},{"x":-0.44,"y":-1.64},{"x":-0.36,"y":-1.64},{"x":-0.28,"y":-1.64},{"x":-0.2,"y":-1.64},{"x":-0.12,"y":-1.64},{"x":-0.04,"y":-1.64},{"x":0.04,"y":-1.64},{"x":0.12,"y":-1.64},{"x":0.2,"y":-1.64},{"x":0.28,"y":-1.64},{"x":0.36,"y":-1.64},{"x":0.44,"y":-1.64},{"x":0.52,"y":-1.64},{"x":0.6,"y":-1.64},{"x":0.68,"y":-1.64},{"x":0.76,"y":-1.64},{"x":0.84,"y":-1.64},{"x":0.92,"y":-1.64},{"x":2.68,"y":-1.64},{"x":2.84,"y":-1.64},{"x":2.96,"y":-1.64},{"x":3.08,"y":-1.64},{"x":3.32,"y":-1.64},{"x":3.4,"y":-1.64},{"x":3.56,"y":-1.64},{"x":3.76,"y":-1.64},{"x":3.8,"y":-1.64},{"x":3.88,"y":-1.64},{"x":15.08,"y":-1.6},{"x":-15.04,"y":-1.68},{"x":-15,"y":-1.68},{"x":-0.36,"y":-1.68},{"x":-0.28,"y":-1.68},{"x":-0.2,"y":-1.68},{"x":-0.12,"y":-1.68},{"x":-0.04,"y":-1.68},{"x":0.04,"y":-1.68},{"x":0.12,"y":-1.68},{"x":0.2,"y":-1.68},{"x":0.28,"y":-1.68},{"x":0.36,"y":-1.68},{"x":0.44,"y":-1.68},{"x":0.52,"y":-1.68},{"x":0.6,"y":-1.68},{"x":0.68,"y":-1.68},{"x":0.76,"y":-1.68},{"x":0.84,"y":-1.68},{"x":0.92,"y":-1.68},{"x":2.56,"y":-1.68},{"x":2.6,"y":-1.68},{"x":2.68,"y":-1.68},{"x":2.76,"y":-1.68},{"x":2.84,"y":-1.68},{"x":2.92,"y":-1.68},{"x":3,"y":-1.68},{"x":3.08,"y":-1.68},{"x":3.16,"y":-1.68},{"x":3.24,"y":-1.68},{"x":3.32,"y":-1.68},{"x":3.4,"y":-1.68},{"x":3.48,"y":-1.68},{"x":3.56,"y":-1.68},{"x":3.64,"y":-1.68},{"x":3.72,"y":-1.68},{"x":3.8,"y":-1.68},{"x":3.88,"y":-1.68},{"x":4.76,"y":-1.72},{"x":4.84,"y":-1.72},{"x":4.92,"y":-1.72},{"x":5,"y":-1.72},{"x":5.36,"y":-1.68},{"x":5.44,"y":-1.72},{"x":5.48,"y":-1.68},{"x":5.56,"y":-1.68},{"x":5.64,"y":-1.68},{"x":5.72,"y":-1.68},{"x":5.8,"y":-1.68},{"x":5.88,"y":-1.68},{"x":5.96,"y":-1.68},{"x":6.04,"y":-1.68},{"x":6.12,"y":-1.68},{"x":6.2,"y":-1.68},{"x":6.28,"y":-1.68},{"x":6.36,"y":-1.68},{"x":6.44,"y":-1.68},{"x":6.52,"y":-1.68},{"x":6.6,"y":-1.68},{"x":8,"y":-1.68},{"x":8.04,"y":-1.68},{"x":8.12,"y":-1.68},{"x":8.2,"y":-1.68},{"x":8.28,"y":-1.68},{"x":8.36,"y":-1.68},{"x":8.44,"y":-1.68},{"x":8.52,"y":-1.68},{"x":8.6,"y":-1.68},{"x":8.68,"y":-1.68},{"x":8.76,"y":-1.68},{"x":8.84,"y":-1.68},{"x":8.92,"y":-1.68},{"x":9,"y":-1.68},{"x":9.08,"y":-1.68},{"x":9.16,"y":-1.68},{"x":9.24,"y":-1.68},{"x":9.32,"y":-1.68},{"x":10.76,"y":-1.68},{"x":10.84,"y":-1.68},{"x":10.92,"y":-1.68},{"x":11,"y":-1.68},{"x":11.08,"y":-1.68},{"x":11.16,"y":-1.68},{"x":11.24,"y":-1.68},{"x":11.32,"y":-1.68},{"x":11.4,"y":-1.68},{"x":11.48,"y":-1.68},{"x":11.56,"y":-1.68},{"x":11.64,"y":-1.68},{"x":11.72,"y":-1.68},{"x":11.8,"y":-1.68},{"x":11.88,"y":-1.68},{"x":11.96,"y":-1.68},{"x":12.04,"y":-1.68},{"x":12.12,"y":-1.68},{"x":15.08,"y":-1.68},{"x":-15.04,"y":-1.76},{"x":-15,"y":-1.76},{"x":-14.92,"y":-1.8},{"x":-14.84,"y":-1.8},{"x":-0.36,"y":-1.76},{"x":-0.12,"y":-1.76},{"x":0.08,"y":-1.76},{"x":0.12,"y":-1.76},{"x":0.32,"y":-1.76},{"x":0.36,"y":-1.8},{"x":0.48,"y":-1.76},{"x":0.52,"y":-1.76},{"x":0.68,"y":-1.8},{"x":0.76,"y":-1.76},{"x":0.96,"y":-1.76},{"x":2.56,"y":-1.76},{"x":2.6,"y":-1.76},{"x":3.88,"y":-1.76},{"x":4.68,"y":-1.76},{"x":4.76,"y":-1.76},{"x":4.84,"y":-1.76},{"x":4.92,"y":-1.76},{"x":5,"y":-1.76},{"x":5.36,"y":-1.76},{"x":5.4,"y":-1.76},{"x":5.48,"y":-1.8},{"x":5.56,"y":-1.76},{"x":6.64,"y":-1.76},{"x":7.96,"y":-1.76},{"x":9.36,"y":-1.76},{"x":9.4,"y":-1.8},{"x":10.64,"y":-1.76},{"x":10.76,"y":-1.76},{"x":10.84,"y":-1.76},{"x":10.92,"y":-1.76},{"x":11.04,"y":-1.76},{"x":11.2,"y":-1.8},{"x":11.32,"y":-1.76},{"x":11.44,"y":-1.76},{"x":11.64,"y":-1.76},{"x":11.72,"y":-1.76},{"x":11.88,"y":-1.76},{"x":12.12,"y":-1.76},{"x":15.08,"y":-1.76},{"x":-15,"y":-1.84},{"x":-14.92,"y":-1.84},{"x":-14.84,"y":-1.84},{"x":-0.32,"y":-1.84},{"x":-0.28,"y":-1.84},{"x":-0.12,"y":-1.84},{"x":0.08,"y":-1.84},{"x":0.12,"y":-1.84},{"x":0.24,"y":-1.84},{"x":0.28,"y":-1.84},{"x":0.36,"y":-1.84},{"x":0.48,"y":-1.84},{"x":0.52,"y":-1.84},{"x":0.68,"y":-1.84},{"x":0.96,"y":-1.84},{"x":2.56,"y":-1.84},{"x":2.6,"y":-1.84},{"x":3.88,"y":-1.84},{"x":4.68,"y":-1.84},{"x":4.76,"y":-1.84},{"x":4.96,"y":-1.84},{"x":5,"y":-1.84},{"x":5.32,"y":-1.84},{"x":5.4,"y":-1.84},{"x":6.64,"y":-1.84},{"x":6.68,"y":-1.84},{"x":7.88,"y":-1.88},{"x":7.96,"y":-1.84},{"x":9.36,"y":-1.84},{"x":10.6,"y":-1.88},{"x":10.76,"y":-1.84},{"x":10.96,"y":-1.84},{"x":11.4,"y":-1.84},{"x":11.88,"y":-1.84},{"x":12.12,"y":-1.84},{"x":15.08,"y":-1.84},{"x":-14.84,"y":-1.92},{"x":-0.32,"y":-1.92},{"x":-0.12,"y":-1.92},{"x":0.08,"y":-1.92},{"x":0.12,"y":-1.96},{"x":0.24,"y":-1.96},{"x":0.32,"y":-1.92},{"x":0.96,"y":-1.92},{"x":1,"y":-1.96},{"x":2.52,"y":-1.92},{"x":2.6,"y":-1.92},{"x":3.88,"y":-1.92},{"x":4.64,"y":-1.92},{"x":4.68,"y":-1.92},{"x":4.76,"y":-1.92},{"x":4.96,"y":-1.92},{"x":5,"y":-1.92},{"x":5.36,"y":-1.92},{"x":5.4,"y":-1.92},{"x":5.48,"y":-1.92},{"x":6.64,"y":-1.92},{"x":7.88,"y":-1.96},{"x":7.96,"y":-1.92},{"x":9.36,"y":-1.92},{"x":10.64,"y":-1.96},{"x":10.76,"y":-1.92},{"x":11.2,"y":-1.92},{"x":11.44,"y":-1.92},{"x":11.64,"y":-1.92},{"x":12.12,"y":-1.92},{"x":15.08,"y":-1.92},{"x":-14.96,"y":-2},{"x":-14.92,"y":-2},{"x":-14.84,"y":-2},{"x":-0.64,"y":-2.04},{"x":-0.56,"y":-2},{"x":-0.52,"y":-2},{"x":-0.44,"y":-2},{"x":-0.36,"y":-2},{"x":-0.28,"y":-2},{"x":-0.2,"y":-2},{"x":-0.12,"y":-2},{"x":0,"y":-2},{"x":0.08,"y":-2},{"x":0.12,"y":-2},{"x":0.2,"y":-2},{"x":0.28,"y":-2},{"x":0.96,"y":-2},{"x":2.52,"y":-2},{"x":2.6,"y":-2},{"x":3.88,"y":-2},{"x":4.64,"y":-2.04},{"x":4.68,"y":-2},{"x":4.76,"y":-2},{"x":4.96,"y":-2},{"x":5,"y":-2},{"x":5.36,"y":-2},{"x":5.44,"y":-2},{"x":5.48,"y":-2},{"x":6.64,"y":-2},{"x":6.68,"y":-2},{"x":7.88,"y":-2.04},{"x":7.96,"y":-2},{"x":9.36,"y":-2},{"x":9.4,"y":-2},{"x":10.76,"y":-2},{"x":11.64,"y":-2.04},{"x":12.12,"y":-2},{"x":15.08,"y":-2},{"x":-14.96,"y":-2.08},{"x":-0.6,"y":-2.08},{"x":-0.52,"y":-2.08},{"x":-0.32,"y":-2.08},{"x":-0.12,"y":-2.12},{"x":0.08,"y":-2.08},{"x":0.12,"y":-2.08},{"x":0.24,"y":-2.12},{"x":0.28,"y":-2.08},{"x":0.96,"y":-2.08},{"x":2.52,"y":-2.08},{"x":2.6,"y":-2.08},{"x":3.88,"y":-2.08},{"x":4.64,"y":-2.08},{"x":4.68,"y":-2.08},{"x":4.76,"y":-2.08},{"x":4.96,"y":-2.08},{"x":5,"y":-2.08},{"x":5.44,"y":-2.08},{"x":6.64,"y":-2.08},{"x":7.96,"y":-2.08},{"x":9.32,"y":-2.08},{"x":10.76,"y":-2.08},{"x":11.2,"y":-2.08},{"x":12.12,"y":-2.08},{"x":15.08,"y":-2.08},{"x":-14.96,"y":-2.16},{"x":-0.68,"y":-2.2},{"x":-0.6,"y":-2.16},{"x":-0.52,"y":-2.16},{"x":-0.36,"y":-2.16},{"x":-0.28,"y":-2.16},{"x":-0.12,"y":-2.16},{"x":0.08,"y":-2.16},{"x":0.96,"y":-2.16},{"x":2.52,"y":-2.16},{"x":2.6,"y":-2.16},{"x":3.88,"y":-2.16},{"x":4.68,"y":-2.16},{"x":4.76,"y":-2.16},{"x":4.96,"y":-2.16},{"x":5,"y":-2.16},{"x":5.44,"y":-2.16},{"x":5.48,"y":-2.2},{"x":6.64,"y":-2.16},{"x":6.68,"y":-2.16},{"x":7.96,"y":-2.16},{"x":9.32,"y":-2.16},{"x":9.4,"y":-2.2},{"x":10.76,"y":-2.16},{"x":11.4,"y":-2.2},{"x":11.64,"y":-2.16},{"x":12.12,"y":-2.16},{"x":15.08,"y":-2.16},{"x":-14.96,"y":-2.24},{"x":-0.84,"y":-2.24},{"x":-0.76,"y":-2.24},{"x":-0.68,"y":-2.24},{"x":-0.6,"y":-2.24},{"x":-0.52,"y":-2.24},{"x":-0.36,"y":-2.24},{"x":-0.24,"y":-2.24},{"x":-0.12,"y":-2.24},{"x":0.04,"y":-2.24},{"x":0.96,"y":-2.24},{"x":2.52,"y":-2.24},{"x":2.6,"y":-2.24},{"x":3.88,"y":-2.24},{"x":4.68,"y":-2.24},{"x":4.76,"y":-2.28},{"x":4.96,"y":-2.24},{"x":5,"y":-2.24},{"x":5.44,"y":-2.24},{"x":5.48,"y":-2.24},{"x":6.64,"y":-2.24},{"x":6.68,"y":-2.28},{"x":8,"y":-2.24},{"x":9.32,"y":-2.24},{"x":10.76,"y":-2.24},{"x":11.4,"y":-2.24},{"x":11.64,"y":-2.28},{"x":12.12,"y":-2.24},{"x":15.08,"y":-2.24},{"x":-14.96,"y":-2.32},{"x":-0.8,"y":-2.32},{"x":-0.76,"y":-2.32},{"x":-0.6,"y":-2.32},{"x":-0.52,"y":-2.32},{"x":-0.36,"y":-2.32},{"x":-0.28,"y":-2.36},{"x":-0.12,"y":-2.32},{"x":0.04,"y":-2.32},{"x":0.12,"y":-2.36},{"x":0.96,"y":-2.32},{"x":2.52,"y":-2.32},{"x":2.6,"y":-2.32},{"x":3.88,"y":-2.32},{"x":4.76,"y":-2.32},{"x":4.96,"y":-2.36},{"x":5,"y":-2.32},{"x":5.44,"y":-2.32},{"x":5.48,"y":-2.32},{"x":6.64,"y":-2.32},{"x":8,"y":-2.32},{"x":9.32,"y":-2.32},{"x":10.76,"y":-2.32},{"x":11.64,"y":-2.36},{"x":12.12,"y":-2.32},{"x":15.08,"y":-2.32},{"x":-14.96,"y":-2.4},{"x":-0.8,"y":-2.4},{"x":-0.76,"y":-2.4},{"x":-0.6,"y":-2.4},{"x":-0.52,"y":-2.4},{"x":-0.36,"y":-2.4},{"x":-0.28,"y":-2.4},{"x":0.08,"y":-2.4},{"x":0.96,"y":-2.4},{"x":2.52,"y":-2.4},{"x":2.6,"y":-2.4},{"x":3.88,"y":-2.4},{"x":4.76,"y":-2.4},{"x":4.96,"y":-2.4},{"x":5,"y":-2.4},{"x":5.44,"y":-2.4},{"x":5.48,"y":-2.4},{"x":6.64,"y":-2.4},{"x":6.68,"y":-2.44},{"x":8,"y":-2.4},{"x":9.36,"y":-2.4},{"x":9.4,"y":-2.44},{"x":10.76,"y":-2.4},{"x":11.88,"y":-2.44},{"x":12.12,"y":-2.4},{"x":15.08,"y":-2.4},{"x":-14.96,"y":-2.48},{"x":-0.76,"y":-2.48},{"x":-0.68,"y":-2.48},{"x":-0.6,"y":-2.48},{"x":-0.52,"y":-2.48},{"x":-0.36,"y":-2.48},{"x":-0.12,"y":-2.48},{"x":0.04,"y":-2.52},{"x":0.96,"y":-2.48},{"x":2.52,"y":-2.52},{"x":2.6,"y":-2.48},{"x":3.88,"y":-2.48},{"x":4.76,"y":-2.48},{"x":4.84,"y":-2.52},{"x":4.92,"y":-2.52},{"x":5,"y":-2.48},{"x":5.44,"y":-2.48},{"x":5.48,"y":-2.48},{"x":6.64,"y":-2.48},{"x":8,"y":-2.48},{"x":9.32,"y":-2.48},{"x":10.76,"y":-2.48},{"x":11.4,"y":-2.48},{"x":11.68,"y":-2.48},{"x":11.88,"y":-2.48},{"x":12.12,"y":-2.48},{"x":15.08,"y":-2.48},{"x":-14.96,"y":-2.56},{"x":-0.6,"y":-2.56},{"x":-0.52,"y":-2.56},{"x":-0.36,"y":-2.56},{"x":-0.24,"y":-2.6},{"x":0.96,"y":-2.56},{"x":2.52,"y":-2.56},{"x":2.6,"y":-2.56},{"x":3.88,"y":-2.56},{"x":5.44,"y":-2.56},{"x":5.48,"y":-2.56},{"x":6.64,"y":-2.56},{"x":6.68,"y":-2.6},{"x":8,"y":-2.56},{"x":9.32,"y":-2.56},{"x":10.76,"y":-2.56},{"x":12.12,"y":-2.56},{"x":15.08,"y":-2.56},{"x":-14.96,"y":-2.64},{"x":-0.6,"y":-2.64},{"x":-0.52,"y":-2.64},{"x":-0.36,"y":-2.64},{"x":-0.24,"y":-2.64},{"x":-0.12,"y":-2.68},{"x":0.72,"y":-2.68},{"x":0.96,"y":-2.64},{"x":2.52,"y":-2.64},{"x":2.6,"y":-2.64},{"x":3.88,"y":-2.64},{"x":5.44,"y":-2.64},{"x":5.48,"y":-2.64},{"x":6.64,"y":-2.64},{"x":8,"y":-2.64},{"x":9.32,"y":-2.64},{"x":9.4,"y":-2.68},{"x":10.76,"y":-2.64},{"x":12.12,"y":-2.64},{"x":15.08,"y":-2.64},{"x":-14.96,"y":-2.72},{"x":-0.36,"y":-2.72},{"x":-0.28,"y":-2.72},{"x":0.72,"y":-2.76},{"x":0.96,"y":-2.72},{"x":2.52,"y":-2.72},{"x":2.6,"y":-2.72},{"x":3.88,"y":-2.72},{"x":5.44,"y":-2.72},{"x":5.48,"y":-2.72},{"x":6.64,"y":-2.72},{"x":6.68,"y":-2.76},{"x":8,"y":-2.72},{"x":9.36,"y":-2.72},{"x":10.76,"y":-2.72},{"x":12.12,"y":-2.72},{"x":15.08,"y":-2.72},{"x":-14.96,"y":-2.8},{"x":-0.36,"y":-2.8},{"x":-0.28,"y":-2.84},{"x":-0.12,"y":-2.8},{"x":0.72,"y":-2.84},{"x":0.76,"y":-2.84},{"x":0.96,"y":-2.8},{"x":2.52,"y":-2.84},{"x":2.6,"y":-2.8},{"x":3.88,"y":-2.8},{"x":5.44,"y":-2.8},{"x":5.48,"y":-2.84},{"x":5.6,"y":-2.84},{"x":5.64,"y":-2.84},{"x":5.84,"y":-2.84},{"x":5.88,"y":-2.84},{"x":5.96,"y":-2.84},{"x":6.04,"y":-2.84},{"x":6.2,"y":-2.84},{"x":6.28,"y":-2.84},{"x":6.4,"y":-2.84},{"x":6.44,"y":-2.84},{"x":6.64,"y":-2.8},{"x":8,"y":-2.8},{"x":9.32,"y":-2.8},{"x":10.76,"y":-2.8},{"x":11.64,"y":-2.84},{"x":12.12,"y":-2.8},{"x":15.08,"y":-2.8},{"x":-14.96,"y":-2.88},{"x":-0.36,"y":-2.88},{"x":-0.24,"y":-2.88},{"x":-0.12,"y":-2.88},{"x":0.04,"y":-2.88},{"x":0.12,"y":-2.92},{"x":0.52,"y":-2.92},{"x":0.72,"y":-2.88},{"x":0.76,"y":-2.92},{"x":0.96,"y":-2.88},{"x":2.52,"y":-2.88},{"x":2.6,"y":-2.88},{"x":3.88,"y":-2.88},{"x":5.44,"y":-2.88},{"x":5.48,"y":-2.88},{"x":5.56,"y":-2.88},{"x":5.64,"y":-2.88},{"x":5.72,"y":-2.88},{"x":5.8,"y":-2.88},{"x":5.88,"y":-2.88},{"x":5.96,"y":-2.88},{"x":6.04,"y":-2.88},{"x":6.12,"y":-2.88},{"x":6.2,"y":-2.88},{"x":6.28,"y":-2.88},{"x":6.36,"y":-2.88},{"x":6.44,"y":-2.88},{"x":6.52,"y":-2.88},{"x":6.6,"y":-2.88},{"x":8,"y":-2.88},{"x":8.04,"y":-2.92},{"x":8.12,"y":-2.92},{"x":8.2,"y":-2.92},{"x":8.28,"y":-2.92},{"x":8.36,"y":-2.92},{"x":8.44,"y":-2.92},{"x":8.52,"y":-2.92},{"x":8.6,"y":-2.92},{"x":8.68,"y":-2.92},{"x":8.76,"y":-2.92},{"x":8.84,"y":-2.92},{"x":8.92,"y":-2.92},{"x":9,"y":-2.92},{"x":9.08,"y":-2.92},{"x":9.16,"y":-2.92},{"x":9.24,"y":-2.92},{"x":9.32,"y":-2.88},{"x":10.76,"y":-2.88},{"x":10.84,"y":-2.92},{"x":10.92,"y":-2.92},{"x":11,"y":-2.92},{"x":11.08,"y":-2.92},{"x":11.16,"y":-2.92},{"x":11.24,"y":-2.92},{"x":11.32,"y":-2.92},{"x":11.4,"y":-2.92},{"x":11.48,"y":-2.92},{"x":11.56,"y":-2.92},{"x":11.64,"y":-2.92},{"x":11.72,"y":-2.92},{"x":11.8,"y":-2.92},{"x":11.88,"y":-2.92},{"x":11.96,"y":-2.92},{"x":12.04,"y":-2.92},{"x":12.12,"y":-2.88},{"x":15.08,"y":-2.88},{"x":-14.96,"y":-2.96},{"x":-0.36,"y":-2.96},{"x":-0.28,"y":-3},{"x":-0.12,"y":-2.96},{"x":0.12,"y":-2.96},{"x":0.28,"y":-2.96},{"x":0.52,"y":-2.96},{"x":0.72,"y":-2.96},{"x":0.76,"y":-2.96},{"x":0.84,"y":-3},{"x":0.96,"y":-2.96},{"x":2.52,"y":-3},{"x":2.6,"y":-2.96},{"x":2.84,"y":-3},{"x":3.12,"y":-3},{"x":3.4,"y":-3},{"x":3.72,"y":-3},{"x":3.88,"y":-2.96},{"x":15.08,"y":-2.96},{"x":-14.96,"y":-3.04},{"x":-0.36,"y":-3.04},{"x":-0.28,"y":-3.04},{"x":-0.2,"y":-3.04},{"x":-0.12,"y":-3.04},{"x":-0.04,"y":-3.04},{"x":0.04,"y":-3.04},{"x":0.12,"y":-3.04},{"x":0.2,"y":-3.04},{"x":0.28,"y":-3.04},{"x":0.36,"y":-3.04},{"x":0.44,"y":-3.04},{"x":0.52,"y":-3.04},{"x":0.6,"y":-3.04},{"x":0.68,"y":-3.04},{"x":0.76,"y":-3.04},{"x":0.84,"y":-3.04},{"x":0.92,"y":-3.04},{"x":2.52,"y":-3.04},{"x":2.6,"y":-3.04},{"x":2.68,"y":-3.04},{"x":2.76,"y":-3.04},{"x":2.84,"y":-3.04},{"x":2.92,"y":-3.04},{"x":3,"y":-3.04},{"x":3.08,"y":-3.04},{"x":3.16,"y":-3.04},{"x":3.24,"y":-3.04},{"x":3.32,"y":-3.04},{"x":3.4,"y":-3.04},{"x":3.48,"y":-3.04},{"x":3.56,"y":-3.04},{"x":3.64,"y":-3.04},{"x":3.72,"y":-3.04},{"x":3.8,"y":-3.04},{"x":3.88,"y":-3.04},{"x":15.08,"y":-3.04},{"x":-14.96,"y":-3.12},{"x":15.08,"y":-3.12},{"x":-14.96,"y":-3.2},{"x":-14.92,"y":-3.24},{"x":-14.84,"y":-3.24},{"x":15.08,"y":-3.2},{"x":-14.96,"y":-3.28},{"x":-14.92,"y":-3.28},{"x":-14.84,"y":-3.28},{"x":15.08,"y":-3.28},{"x":-14.84,"y":-3.36},{"x":15.08,"y":-3.36},{"x":-15,"y":-3.44},{"x":-14.92,"y":-3.44},{"x":-14.84,"y":-3.44},{"x":15,"y":-3.44},{"x":15.08,"y":-3.44},{"x":-15,"y":-3.52},{"x":15,"y":-3.52},{"x":-15.04,"y":-3.64},{"x":-15,"y":-3.6},{"x":-7.68,"y":-3.64},{"x":-7.64,"y":-3.64},{"x":-7.32,"y":-3.64},{"x":-7.24,"y":-3.64},{"x":7.36,"y":-3.6},{"x":7.4,"y":-3.6},{"x":7.76,"y":-3.6},{"x":7.8,"y":-3.6},{"x":15,"y":-3.6},{"x":-15.04,"y":-3.68},{"x":-15,"y":-3.68},{"x":-7.68,"y":-3.68},{"x":-7.64,"y":-3.68},{"x":-7.32,"y":-3.68},{"x":-7.24,"y":-3.68},{"x":7.36,"y":-3.68},{"x":7.44,"y":-3.68},{"x":7.76,"y":-3.68},{"x":7.8,"y":-3.68},{"x":15,"y":-3.68},{"x":-15.04,"y":-3.76},{"x":-15,"y":-3.76},{"x":-7.68,"y":-3.76},{"x":-7.64,"y":-3.76},{"x":-7.56,"y":-3.76},{"x":-7.48,"y":-3.76},{"x":-7.4,"y":-3.8},{"x":-7.32,"y":-3.76},{"x":-7.24,"y":-3.76},{"x":7.36,"y":-3.76},{"x":7.44,"y":-3.76},{"x":7.48,"y":-3.76},{"x":7.56,"y":-3.76},{"x":7.64,"y":-3.76},{"x":7.72,"y":-3.76},{"x":7.8,"y":-3.76},{"x":15,"y":-3.76},{"x":-15.04,"y":-3.84},{"x":-15,"y":-3.84},{"x":-7.68,"y":-3.84},{"x":-7.32,"y":-3.84},{"x":-7.24,"y":-3.84},{"x":7.36,"y":-3.84},{"x":7.8,"y":-3.84},{"x":15,"y":-3.84},{"x":-15.04,"y":-3.92},{"x":-15,"y":-3.92},{"x":-7.68,"y":-3.92},{"x":-7.32,"y":-3.96},{"x":-7.24,"y":-3.92},{"x":5.88,"y":-3.96},{"x":5.96,"y":-3.96},{"x":6.16,"y":-3.96},{"x":7.36,"y":-3.92},{"x":7.44,"y":-3.92},{"x":7.48,"y":-3.92},{"x":7.56,"y":-3.92},{"x":7.64,"y":-3.92},{"x":7.72,"y":-3.92},{"x":7.8,"y":-3.92},{"x":8.96,"y":-3.96},{"x":9,"y":-3.96},{"x":9.12,"y":-3.96},{"x":9.2,"y":-3.96},{"x":15,"y":-3.92},{"x":-15.04,"y":-4},{"x":-15,"y":-4},{"x":-7.68,"y":-4},{"x":-7.6,"y":-4.04},{"x":-7.32,"y":-4.04},{"x":-7.24,"y":-4},{"x":-0.36,"y":-4},{"x":-0.28,"y":-4},{"x":-0.12,"y":-4},{"x":0,"y":-4},{"x":0.12,"y":-4},{"x":0.64,"y":-4.04},{"x":2.56,"y":-4.04},{"x":2.6,"y":-4.04},{"x":2.68,"y":-4.04},{"x":2.8,"y":-4},{"x":2.84,"y":-4},{"x":2.92,"y":-4},{"x":3.04,"y":-4},{"x":3.08,"y":-4},{"x":3.16,"y":-4},{"x":3.28,"y":-4},{"x":3.32,"y":-4},{"x":3.4,"y":-4},{"x":3.48,"y":-4.04},{"x":3.56,"y":-4.04},{"x":3.64,"y":-4.04},{"x":3.72,"y":-4.04},{"x":3.8,"y":-4.04},{"x":3.88,"y":-4.04},{"x":5.4,"y":-4.04},{"x":5.48,"y":-4.04},{"x":5.56,"y":-4.04},{"x":5.64,"y":-4.04},{"x":5.72,"y":-4.04},{"x":5.8,"y":-4.04},{"x":5.88,"y":-4},{"x":6,"y":-4},{"x":6.04,"y":-4},{"x":6.12,"y":-4},{"x":6.24,"y":-4},{"x":6.48,"y":-4.04},{"x":6.52,"y":-4.04},{"x":6.6,"y":-4.04},{"x":6.68,"y":-4.04},{"x":7.36,"y":-4},{"x":7.44,"y":-4},{"x":7.72,"y":-4},{"x":7.8,"y":-4},{"x":8.04,"y":-4.04},{"x":8.12,"y":-4},{"x":8.2,"y":-4.04},{"x":8.28,"y":-4.04},{"x":8.36,"y":-4.04},{"x":8.48,"y":-4},{"x":8.52,"y":-4.04},{"x":8.64,"y":-4},{"x":8.68,"y":-4.04},{"x":8.8,"y":-4},{"x":8.84,"y":-4.04},{"x":8.92,"y":-4},{"x":9,"y":-4},{"x":9.12,"y":-4},{"x":9.16,"y":-4.04},{"x":9.24,"y":-4.04},{"x":9.32,"y":-4.04},{"x":10.84,"y":-4.04},{"x":10.92,"y":-4.04},{"x":11,"y":-4.04},{"x":11.08,"y":-4.04},{"x":11.16,"y":-4.04},{"x":11.24,"y":-4.04},{"x":11.32,"y":-4.04},{"x":11.4,"y":-4.04},{"x":11.48,"y":-4.04},{"x":11.56,"y":-4.04},{"x":11.64,"y":-4.04},{"x":11.72,"y":-4.04},{"x":11.8,"y":-4.04},{"x":11.88,"y":-4.04},{"x":11.96,"y":-4.04},{"x":12.04,"y":-4.04},{"x":15,"y":-4},{"x":-15.04,"y":-4.08},{"x":-15,"y":-4.08},{"x":-7.68,"y":-4.08},{"x":-7.6,"y":-4.08},{"x":-7.28,"y":-4.12},{"x":-7.24,"y":-4.08},{"x":-0.36,"y":-4.08},{"x":-0.28,"y":-4.08},{"x":-0.2,"y":-4.08},{"x":-0.12,"y":-4.08},{"x":-0.04,"y":-4.08},{"x":0.04,"y":-4.08},{"x":0.12,"y":-4.08},{"x":0.24,"y":-4.08},{"x":0.28,"y":-4.08},{"x":0.36,"y":-4.08},{"x":0.44,"y":-4.08},{"x":0.52,"y":-4.08},{"x":0.6,"y":-4.08},{"x":0.68,"y":-4.08},{"x":0.76,"y":-4.08},{"x":0.84,"y":-4.08},{"x":0.92,"y":-4.08},{"x":2.52,"y":-4.08},{"x":2.6,"y":-4.08},{"x":2.8,"y":-4.08},{"x":2.92,"y":-4.08},{"x":3,"y":-4.08},{"x":3.08,"y":-4.08},{"x":3.16,"y":-4.08},{"x":3.24,"y":-4.08},{"x":3.36,"y":-4.08},{"x":3.4,"y":-4.08},{"x":3.48,"y":-4.08},{"x":3.56,"y":-4.08},{"x":3.64,"y":-4.08},{"x":3.76,"y":-4.08},{"x":3.8,"y":-4.08},{"x":3.88,"y":-4.08},{"x":5.4,"y":-4.08},{"x":5.92,"y":-4.08},{"x":5.96,"y":-4.08},{"x":6.04,"y":-4.08},{"x":6.12,"y":-4.08},{"x":6.2,"y":-4.08},{"x":6.28,"y":-4.08},{"x":6.36,"y":-4.08},{"x":6.44,"y":-4.08},{"x":6.52,"y":-4.08},{"x":6.6,"y":-4.08},{"x":6.68,"y":-4.08},{"x":7.36,"y":-4.08},{"x":7.4,"y":-4.08},{"x":7.72,"y":-4.08},{"x":7.8,"y":-4.08},{"x":8.04,"y":-4.08},{"x":8.28,"y":-4.08},{"x":8.72,"y":-4.08},{"x":8.88,"y":-4.12},{"x":9,"y":-4.08},{"x":9.08,"y":-4.08},{"x":9.16,"y":-4.08},{"x":9.24,"y":-4.08},{"x":9.32,"y":-4.08},{"x":10.8,"y":-4.08},{"x":10.84,"y":-4.08},{"x":11.88,"y":-4.08},{"x":12.08,"y":-4.08},{"x":15,"y":-4.08},{"x":-15.04,"y":-4.16},{"x":-15,"y":-4.16},{"x":-0.32,"y":-4.16},{"x":-0.28,"y":-4.16},{"x":-0.12,"y":-4.16},{"x":0.96,"y":-4.16},{"x":2.52,"y":-4.16},{"x":2.64,"y":-4.16},{"x":3.88,"y":-4.16},{"x":5.4,"y":-4.16},{"x":6.68,"y":-4.16},{"x":8.04,"y":-4.16},{"x":9.12,"y":-4.16},{"x":9.32,"y":-4.16},{"x":10.8,"y":-4.16},{"x":10.84,"y":-4.16},{"x":12.08,"y":-4.16},{"x":15,"y":-4.16},{"x":-15.04,"y":-4.24},{"x":-15,"y":-4.24},{"x":-0.36,"y":-4.24},{"x":-0.28,"y":-4.24},{"x":0.92,"y":-4.24},{"x":2.52,"y":-4.24},{"x":2.64,"y":-4.24},{"x":3.92,"y":-4.24},{"x":5.4,"y":-4.24},{"x":6.68,"y":-4.24},{"x":8.04,"y":-4.24},{"x":9.32,"y":-4.24},{"x":10.8,"y":-4.24},{"x":10.84,"y":-4.24},{"x":12.08,"y":-4.24},{"x":15,"y":-4.24},{"x":-15.04,"y":-4.32},{"x":-15,"y":-4.32},{"x":-0.32,"y":-4.32},{"x":-0.28,"y":-4.32},{"x":0.92,"y":-4.32},{"x":2.52,"y":-4.36},{"x":2.64,"y":-4.32},{"x":3.92,"y":-4.32},{"x":5.4,"y":-4.32},{"x":6.68,"y":-4.32},{"x":8.04,"y":-4.32},{"x":9.32,"y":-4.32},{"x":10.8,"y":-4.36},{"x":10.84,"y":-4.32},{"x":12.08,"y":-4.32},{"x":15,"y":-4.32},{"x":-15.04,"y":-4.4},{"x":-15,"y":-4.4},{"x":-0.32,"y":-4.4},{"x":-0.28,"y":-4.4},{"x":0.92,"y":-4.4},{"x":2.52,"y":-4.44},{"x":2.64,"y":-4.4},{"x":3.92,"y":-4.4},{"x":5.4,"y":-4.4},{"x":6.68,"y":-4.4},{"x":8.04,"y":-4.4},{"x":9.32,"y":-4.4},{"x":10.8,"y":-4.4},{"x":10.84,"y":-4.4},{"x":12.08,"y":-4.4},{"x":15,"y":-4.4},{"x":-15.04,"y":-4.48},{"x":-15,"y":-4.48},{"x":-0.32,"y":-4.48},{"x":-0.28,"y":-4.48},{"x":0.92,"y":-4.48},{"x":2.64,"y":-4.48},{"x":3.92,"y":-4.48},{"x":5.4,"y":-4.48},{"x":6.68,"y":-4.48},{"x":8.04,"y":-4.48},{"x":9.32,"y":-4.48},{"x":10.8,"y":-4.52},{"x":10.84,"y":-4.48},{"x":12.08,"y":-4.48},{"x":15,"y":-4.48},{"x":-15.04,"y":-4.56},{"x":-15,"y":-4.56},{"x":-0.32,"y":-4.56},{"x":-0.28,"y":-4.56},{"x":0.92,"y":-4.56},{"x":2.52,"y":-4.56},{"x":2.64,"y":-4.56},{"x":3.88,"y":-4.56},{"x":5.4,"y":-4.56},{"x":6.68,"y":-4.56},{"x":8.04,"y":-4.56},{"x":9.32,"y":-4.56},{"x":10.8,"y":-4.56},{"x":10.84,"y":-4.56},{"x":12.08,"y":-4.56},{"x":15,"y":-4.56},{"x":15.08,"y":-4.6},{"x":-15.04,"y":-4.64},{"x":-15,"y":-4.64},{"x":-0.32,"y":-4.64},{"x":-0.28,"y":-4.64},{"x":0.96,"y":-4.64},{"x":2.52,"y":-4.68},{"x":2.64,"y":-4.64},{"x":3.92,"y":-4.64},{"x":5.4,"y":-4.64},{"x":6.68,"y":-4.64},{"x":8.04,"y":-4.64},{"x":9.32,"y":-4.64},{"x":10.8,"y":-4.64},{"x":10.84,"y":-4.64},{"x":12.08,"y":-4.64},{"x":15.04,"y":-4.64},{"x":15.08,"y":-4.64},{"x":-15.04,"y":-4.72},{"x":-15,"y":-4.72},{"x":-0.32,"y":-4.72},{"x":-0.28,"y":-4.72},{"x":-0.2,"y":-4.72},{"x":-0.04,"y":-4.72},{"x":0.96,"y":-4.72},{"x":2.64,"y":-4.72},{"x":3.92,"y":-4.72},{"x":5.4,"y":-4.72},{"x":6.68,"y":-4.72},{"x":8.04,"y":-4.72},{"x":9.32,"y":-4.72},{"x":10.84,"y":-4.72},{"x":12.08,"y":-4.72},{"x":15.08,"y":-4.72},{"x":-15.04,"y":-4.8},{"x":-15,"y":-4.8},{"x":-0.32,"y":-4.8},{"x":-0.28,"y":-4.8},{"x":0.96,"y":-4.8},{"x":2.64,"y":-4.8},{"x":3.92,"y":-4.8},{"x":5.4,"y":-4.8},{"x":6.68,"y":-4.8},{"x":8.04,"y":-4.8},{"x":9.32,"y":-4.8},{"x":10.84,"y":-4.8},{"x":12.08,"y":-4.8},{"x":15.08,"y":-4.8},{"x":-15.04,"y":-4.88},{"x":-15,"y":-4.88},{"x":-0.32,"y":-4.88},{"x":-0.28,"y":-4.88},{"x":0.92,"y":-4.88},{"x":2.64,"y":-4.88},{"x":3.92,"y":-4.88},{"x":5.4,"y":-4.88},{"x":6.68,"y":-4.88},{"x":8.04,"y":-4.88},{"x":9.32,"y":-4.88},{"x":10.84,"y":-4.88},{"x":12.08,"y":-4.88},{"x":15.08,"y":-4.88},{"x":-15.04,"y":-4.96},{"x":-15,"y":-4.96},{"x":-0.32,"y":-4.96},{"x":-0.28,"y":-4.96},{"x":0.96,"y":-4.96},{"x":2.64,"y":-4.96},{"x":3.92,"y":-4.96},{"x":5.4,"y":-4.96},{"x":6.68,"y":-4.96},{"x":8.04,"y":-4.96},{"x":9.32,"y":-4.96},{"x":10.8,"y":-4.96},{"x":10.84,"y":-4.96},{"x":12.08,"y":-4.96},{"x":15.08,"y":-4.96},{"x":-15.04,"y":-5.04},{"x":-15,"y":-5.04},{"x":-0.32,"y":-5.04},{"x":-0.28,"y":-5.04},{"x":0.92,"y":-5.04},{"x":2.64,"y":-5.04},{"x":3.92,"y":-5.04},{"x":5.4,"y":-5.04},{"x":6.68,"y":-5.04},{"x":8.04,"y":-5.04},{"x":9.32,"y":-5.04},{"x":10.84,"y":-5.04},{"x":12.08,"y":-5.04},{"x":15.08,"y":-5.04},{"x":-15.04,"y":-5.12},{"x":-15,"y":-5.12},{"x":-0.32,"y":-5.12},{"x":-0.28,"y":-5.12},{"x":0.92,"y":-5.12},{"x":2.64,"y":-5.12},{"x":3.92,"y":-5.12},{"x":5.4,"y":-5.12},{"x":6.68,"y":-5.12},{"x":8.04,"y":-5.12},{"x":9.32,"y":-5.12},{"x":10.84,"y":-5.12},{"x":12.08,"y":-5.12},{"x":15.08,"y":-5.12},{"x":-15.04,"y":-5.2},{"x":-15,"y":-5.2},{"x":-0.32,"y":-5.2},{"x":-0.28,"y":-5.2},{"x":0.96,"y":-5.2},{"x":2.64,"y":-5.2},{"x":3.28,"y":-5.24},{"x":3.56,"y":-5.24},{"x":3.76,"y":-5.24},{"x":3.8,"y":-5.24},{"x":3.92,"y":-5.2},{"x":5.4,"y":-5.2},{"x":5.8,"y":-5.24},{"x":5.88,"y":-5.24},{"x":5.96,"y":-5.24},{"x":6.36,"y":-5.24},{"x":6.44,"y":-5.24},{"x":6.52,"y":-5.24},{"x":6.64,"y":-5.24},{"x":6.68,"y":-5.2},{"x":8.04,"y":-5.2},{"x":8.24,"y":-5.24},{"x":8.28,"y":-5.24},{"x":8.36,"y":-5.24},{"x":8.44,"y":-5.24},{"x":8.52,"y":-5.2},{"x":8.64,"y":-5.2},{"x":8.68,"y":-5.24},{"x":8.92,"y":-5.24},{"x":9,"y":-5.24},{"x":9.08,"y":-5.24},{"x":9.2,"y":-5.2},{"x":9.28,"y":-5.24},{"x":9.32,"y":-5.2},{"x":10.84,"y":-5.2},{"x":11.16,"y":-5.24},{"x":11.24,"y":-5.24},{"x":11.36,"y":-5.24},{"x":11.4,"y":-5.24},{"x":11.76,"y":-5.24},{"x":11.88,"y":-5.24},{"x":11.96,"y":-5.24},{"x":12.08,"y":-5.2},{"x":15.08,"y":-5.2},{"x":-15.04,"y":-5.28},{"x":-15,"y":-5.28},{"x":-0.32,"y":-5.28},{"x":-0.28,"y":-5.28},{"x":-0.2,"y":-5.32},{"x":-0.12,"y":-5.32},{"x":-0.04,"y":-5.32},{"x":0.04,"y":-5.32},{"x":0.12,"y":-5.32},{"x":0.2,"y":-5.32},{"x":0.28,"y":-5.32},{"x":0.36,"y":-5.32},{"x":0.44,"y":-5.32},{"x":0.52,"y":-5.32},{"x":0.6,"y":-5.32},{"x":0.68,"y":-5.32},{"x":0.76,"y":-5.32},{"x":0.84,"y":-5.32},{"x":0.96,"y":-5.28},{"x":1,"y":-5.28},{"x":2.64,"y":-5.28},{"x":2.68,"y":-5.28},{"x":2.76,"y":-5.28},{"x":2.84,"y":-5.28},{"x":2.92,"y":-5.28},{"x":3,"y":-5.28},{"x":3.08,"y":-5.28},{"x":3.16,"y":-5.28},{"x":3.24,"y":-5.28},{"x":3.32,"y":-5.28},{"x":3.4,"y":-5.28},{"x":3.48,"y":-5.28},{"x":3.56,"y":-5.28},{"x":3.64,"y":-5.28},{"x":3.72,"y":-5.28},{"x":3.8,"y":-5.28},{"x":3.88,"y":-5.28},{"x":5.4,"y":-5.28},{"x":5.48,"y":-5.28},{"x":5.56,"y":-5.32},{"x":5.64,"y":-5.32},{"x":5.76,"y":-5.28},{"x":5.8,"y":-5.28},{"x":5.88,"y":-5.32},{"x":6,"y":-5.28},{"x":6.04,"y":-5.28},{"x":6.12,"y":-5.32},{"x":6.2,"y":-5.32},{"x":6.28,"y":-5.32},{"x":6.36,"y":-5.28},{"x":6.44,"y":-5.28},{"x":6.52,"y":-5.32},{"x":6.64,"y":-5.28},{"x":6.68,"y":-5.28},{"x":8.04,"y":-5.28},{"x":8.12,"y":-5.28},{"x":8.2,"y":-5.28},{"x":8.28,"y":-5.28},{"x":8.36,"y":-5.28},{"x":8.44,"y":-5.28},{"x":8.52,"y":-5.28},{"x":8.6,"y":-5.28},{"x":8.68,"y":-5.28},{"x":8.76,"y":-5.28},{"x":8.84,"y":-5.28},{"x":8.92,"y":-5.28},{"x":9,"y":-5.28},{"x":9.08,"y":-5.28},{"x":9.16,"y":-5.28},{"x":9.24,"y":-5.28},{"x":9.32,"y":-5.28},{"x":10.8,"y":-5.28},{"x":10.84,"y":-5.28},{"x":10.92,"y":-5.32},{"x":11,"y":-5.32},{"x":11.08,"y":-5.28},{"x":11.16,"y":-5.32},{"x":11.24,"y":-5.28},{"x":11.36,"y":-5.28},{"x":11.4,"y":-5.28},{"x":11.48,"y":-5.32},{"x":11.56,"y":-5.32},{"x":11.64,"y":-5.32},{"x":11.76,"y":-5.28},{"x":11.8,"y":-5.28},{"x":11.88,"y":-5.32},{"x":11.96,"y":-5.28},{"x":12.04,"y":-5.28},{"x":15.08,"y":-5.28},{"x":-15.04,"y":-5.36},{"x":-15,"y":-5.36},{"x":0.04,"y":-5.36},{"x":1,"y":-5.36},{"x":15.08,"y":-5.36},{"x":-15.04,"y":-5.44},{"x":-15,"y":-5.44},{"x":15.08,"y":-5.44},{"x":-15.04,"y":-5.52},{"x":-15,"y":-5.52},{"x":15.08,"y":-5.52},{"x":-15.04,"y":-5.6},{"x":-15,"y":-5.6},{"x":15.08,"y":-5.6},{"x":-15.04,"y":-5.68},{"x":-15,"y":-5.68},{"x":-0.32,"y":-5.68},{"x":-0.28,"y":-5.68},{"x":-0.2,"y":-5.68},{"x":-0.12,"y":-5.68},{"x":-0.04,"y":-5.68},{"x":0.04,"y":-5.68},{"x":0.12,"y":-5.68},{"x":0.2,"y":-5.68},{"x":0.28,"y":-5.68},{"x":0.36,"y":-5.68},{"x":0.44,"y":-5.68},{"x":0.52,"y":-5.68},{"x":15.08,"y":-5.68},{"x":-15.04,"y":-5.76},{"x":-15,"y":-5.76},{"x":-0.32,"y":-5.76},{"x":0.48,"y":-5.76},{"x":0.52,"y":-5.76},{"x":15.08,"y":-5.76},{"x":-15.04,"y":-5.84},{"x":-15,"y":-5.84},{"x":-0.32,"y":-5.84},{"x":-0.28,"y":-5.88},{"x":-0.2,"y":-5.88},{"x":-0.12,"y":-5.88},{"x":0,"y":-5.84},{"x":0.04,"y":-5.88},{"x":0.12,"y":-5.88},{"x":0.2,"y":-5.84},{"x":0.28,"y":-5.84},{"x":0.36,"y":-5.84},{"x":0.48,"y":-5.84},{"x":0.52,"y":-5.84},{"x":15.08,"y":-5.84},{"x":-15.04,"y":-5.92},{"x":-15,"y":-5.92},{"x":15.08,"y":-5.92},{"x":-15.04,"y":-6},{"x":-15,"y":-6},{"x":15.08,"y":-6},{"x":-15.04,"y":-6.08},{"x":-15,"y":-6.08},{"x":15.08,"y":-6.08},{"x":-15.04,"y":-6.16},{"x":-15,"y":-6.16},{"x":15.08,"y":-6.16},{"x":-15.04,"y":-6.24},{"x":-15,"y":-6.24},{"x":15.08,"y":-6.24},{"x":-15.04,"y":-6.32},{"x":-15,"y":-6.32},{"x":15.08,"y":-6.32},{"x":-15.04,"y":-6.4},{"x":-15,"y":-6.4},{"x":15.08,"y":-6.4},{"x":-15.04,"y":-6.48},{"x":-15,"y":-6.48},{"x":15.08,"y":-6.48},{"x":-15.04,"y":-6.56},{"x":-15,"y":-6.56},{"x":15.08,"y":-6.56},{"x":-15.04,"y":-6.64},{"x":-15,"y":-6.64},{"x":15.08,"y":-6.64},{"x":-15.04,"y":-6.72},{"x":-15,"y":-6.72},{"x":-14.92,"y":-6.72},{"x":-14.84,"y":-6.76},{"x":15.08,"y":-6.72},{"x":-14.96,"y":-6.8},{"x":-14.92,"y":-6.8},{"x":-14.84,"y":-6.8},{"x":15.08,"y":-6.8},{"x":-14.84,"y":-6.88},{"x":15.08,"y":-6.88},{"x":-14.92,"y":-7},{"x":15.08,"y":-6.96},{"x":-14.96,"y":-7.04},{"x":-14.92,"y":-7.04},{"x":15.08,"y":-7.04},{"x":-14.96,"y":-7.12},{"x":-14.92,"y":-7.12},{"x":15.08,"y":-7.12},{"x":-14.96,"y":-7.2},{"x":-14.92,"y":-7.2},{"x":-7.52,"y":-7.24},{"x":-7.48,"y":-7.24},{"x":-7.4,"y":-7.24},{"x":15.08,"y":-7.2},{"x":-14.96,"y":-7.28},{"x":-14.92,"y":-7.28},{"x":-7.56,"y":-7.28},{"x":-7.48,"y":-7.28},{"x":-7.4,"y":-7.28},{"x":-7.32,"y":-7.28},{"x":7.44,"y":-7.32},{"x":7.48,"y":-7.32},{"x":7.56,"y":-7.32},{"x":7.64,"y":-7.32},{"x":7.72,"y":-7.32},{"x":14.84,"y":-7.32},{"x":14.92,"y":-7.32},{"x":15,"y":-7.32},{"x":15.08,"y":-7.28},{"x":-14.96,"y":-7.36},{"x":-14.92,"y":-7.36},{"x":-14.84,"y":-7.36},{"x":-14.76,"y":-7.36},{"x":-14.68,"y":-7.4},{"x":-7.6,"y":-7.36},{"x":-7.56,"y":-7.36},{"x":-7.44,"y":-7.36},{"x":-7.4,"y":-7.36},{"x":-7.32,"y":-7.36},{"x":-0.08,"y":-7.36},{"x":-0.04,"y":-7.36},{"x":0.04,"y":-7.36},{"x":0.12,"y":-7.36},{"x":0.2,"y":-7.36},{"x":7.44,"y":-7.36},{"x":7.48,"y":-7.36},{"x":7.72,"y":-7.36},{"x":14.84,"y":-7.36},{"x":14.92,"y":-7.36},{"x":15,"y":-7.36},{"x":-14.92,"y":-7.44},{"x":-14.84,"y":-7.44},{"x":-14.76,"y":-7.44},{"x":-14.68,"y":-7.44},{"x":-7.6,"y":-7.48},{"x":-7.56,"y":-7.44},{"x":-7.44,"y":-7.48},{"x":-7.4,"y":-7.44},{"x":-7.32,"y":-7.44},{"x":-0.08,"y":-7.44},{"x":-0.04,"y":-7.44},{"x":0.2,"y":-7.44},{"x":7.44,"y":-7.44},{"x":7.48,"y":-7.44},{"x":7.72,"y":-7.44},{"x":14.84,"y":-7.44},{"x":-14.72,"y":-7.52},{"x":-14.68,"y":-7.52},{"x":-7.6,"y":-7.52},{"x":-7.56,"y":-7.52},{"x":-7.36,"y":-7.52},{"x":-7.32,"y":-7.52},{"x":-6.24,"y":-7.52},{"x":-6.2,"y":-7.52},{"x":-6.12,"y":-7.56},{"x":-6.04,"y":-7.56},{"x":-5.96,"y":-7.56},{"x":-5.88,"y":-7.56},{"x":-5.8,"y":-7.56},{"x":-5.72,"y":-7.56},{"x":-5.64,"y":-7.56},{"x":-5.56,"y":-7.56},{"x":-5.48,"y":-7.56},{"x":-5.4,"y":-7.56},{"x":-5.28,"y":-7.52},{"x":-5.24,"y":-7.56},{"x":-5.16,"y":-7.52},{"x":-5.08,"y":-7.56},{"x":-0.08,"y":-7.52},{"x":-0.04,"y":-7.52},{"x":0.2,"y":-7.52},{"x":2.8,"y":-7.56},{"x":3.64,"y":-7.56},{"x":3.8,"y":-7.56},{"x":4.08,"y":-7.56},{"x":4.24,"y":-7.56},{"x":4.28,"y":-7.56},{"x":4.56,"y":-7.56},{"x":4.6,"y":-7.56},{"x":4.76,"y":-7.56},{"x":4.84,"y":-7.56},{"x":4.96,"y":-7.56},{"x":5,"y":-7.56},{"x":5.08,"y":-7.56},{"x":5.16,"y":-7.56},{"x":5.24,"y":-7.56},{"x":5.32,"y":-7.56},{"x":5.44,"y":-7.56},{"x":5.48,"y":-7.56},{"x":5.56,"y":-7.56},{"x":5.64,"y":-7.56},{"x":5.72,"y":-7.56},{"x":5.8,"y":-7.56},{"x":5.88,"y":-7.56},{"x":5.96,"y":-7.56},{"x":6.04,"y":-7.56},{"x":6.12,"y":-7.56},{"x":6.2,"y":-7.56},{"x":6.28,"y":-7.56},{"x":6.36,"y":-7.56},{"x":6.44,"y":-7.56},{"x":6.56,"y":-7.56},{"x":6.6,"y":-7.56},{"x":6.72,"y":-7.56},{"x":6.76,"y":-7.56},{"x":6.84,"y":-7.56},{"x":6.92,"y":-7.56},{"x":7,"y":-7.56},{"x":7.08,"y":-7.56},{"x":7.16,"y":-7.56},{"x":7.24,"y":-7.56},{"x":7.32,"y":-7.56},{"x":7.44,"y":-7.52},{"x":7.48,"y":-7.52},{"x":7.72,"y":-7.52},{"x":7.84,"y":-7.56},{"x":8,"y":-7.56},{"x":8.12,"y":-7.56},{"x":8.24,"y":-7.56},{"x":8.36,"y":-7.56},{"x":8.48,"y":-7.56},{"x":8.72,"y":-7.56},{"x":8.8,"y":-7.56},{"x":8.92,"y":-7.56},{"x":9,"y":-7.56},{"x":9.08,"y":-7.56},{"x":9.2,"y":-7.56},{"x":9.24,"y":-7.56},{"x":9.36,"y":-7.56},{"x":9.44,"y":-7.56},{"x":9.52,"y":-7.56},{"x":9.64,"y":-7.56},{"x":9.72,"y":-7.56},{"x":9.88,"y":-7.56},{"x":10.04,"y":-7.56},{"x":10.16,"y":-7.56},{"x":11.44,"y":-7.56},{"x":11.88,"y":-7.56},{"x":12.36,"y":-7.56},{"x":14.32,"y":-7.56},{"x":14.8,"y":-7.56},{"x":14.84,"y":-7.52},{"x":-14.72,"y":-7.6},{"x":-14.68,"y":-7.6},{"x":-14.6,"y":-7.64},{"x":-14.52,"y":-7.64},{"x":-14.44,"y":-7.64},{"x":-14.36,"y":-7.64},{"x":-14.28,"y":-7.64},{"x":-14.2,"y":-7.64},{"x":-14.12,"y":-7.64},{"x":-14.04,"y":-7.64},{"x":-13.96,"y":-7.64},{"x":-13.88,"y":-7.64},{"x":-13.8,"y":-7.64},{"x":-13.72,"y":-7.64},{"x":-13.64,"y":-7.64},{"x":-13.56,"y":-7.64},{"x":-13.48,"y":-7.64},{"x":-13.4,"y":-7.64},{"x":-13.32,"y":-7.64},{"x":-13.24,"y":-7.64},{"x":-13.16,"y":-7.64},{"x":-13.08,"y":-7.64},{"x":-13,"y":-7.64},{"x":-12.92,"y":-7.64},{"x":-12.84,"y":-7.64},{"x":-12.76,"y":-7.64},{"x":-12.68,"y":-7.64},{"x":-12.6,"y":-7.64},{"x":-12.52,"y":-7.64},{"x":-12.44,"y":-7.64},{"x":-12.36,"y":-7.64},{"x":-12.28,"y":-7.64},{"x":-12.2,"y":-7.64},{"x":-12.12,"y":-7.64},{"x":-12.04,"y":-7.64},{"x":-11.96,"y":-7.64},{"x":-11.88,"y":-7.64},{"x":-11.8,"y":-7.64},{"x":-11.72,"y":-7.64},{"x":-11.64,"y":-7.64},{"x":-11.56,"y":-7.64},{"x":-11.48,"y":-7.64},{"x":-11.4,"y":-7.64},{"x":-11.32,"y":-7.64},{"x":-11.24,"y":-7.64},{"x":-11.16,"y":-7.64},{"x":-11.08,"y":-7.64},{"x":-11,"y":-7.64},{"x":-10.92,"y":-7.64},{"x":-10.84,"y":-7.64},{"x":-10.76,"y":-7.64},{"x":-10.68,"y":-7.64},{"x":-10.6,"y":-7.64},{"x":-10.52,"y":-7.64},{"x":-10.44,"y":-7.64},{"x":-10.36,"y":-7.64},{"x":-10.28,"y":-7.64},{"x":-10.2,"y":-7.64},{"x":-10.12,"y":-7.64},{"x":-10.04,"y":-7.64},{"x":-9.96,"y":-7.64},{"x":-9.88,"y":-7.64},{"x":-9.8,"y":-7.6},{"x":-9.68,"y":-7.6},{"x":-9.6,"y":-7.6},{"x":-9.56,"y":-7.6},{"x":-9.48,"y":-7.6},{"x":-9.4,"y":-7.6},{"x":-9.32,"y":-7.6},{"x":-9.24,"y":-7.6},{"x":-9.16,"y":-7.6},{"x":-9.08,"y":-7.6},{"x":-9,"y":-7.6},{"x":-8.92,"y":-7.6},{"x":-8.84,"y":-7.6},{"x":-8.76,"y":-7.6},{"x":-8.68,"y":-7.6},{"x":-8.6,"y":-7.6},{"x":-8.52,"y":-7.6},{"x":-8.44,"y":-7.6},{"x":-8.36,"y":-7.6},{"x":-8.28,"y":-7.6},{"x":-8.2,"y":-7.6},{"x":-8.12,"y":-7.6},{"x":-8.04,"y":-7.6},{"x":-7.96,"y":-7.6},{"x":-7.88,"y":-7.6},{"x":-7.8,"y":-7.6},{"x":-7.72,"y":-7.6},{"x":-7.64,"y":-7.6},{"x":-7.56,"y":-7.6},{"x":-7.4,"y":-7.6},{"x":-7.32,"y":-7.6},{"x":-7.24,"y":-7.6},{"x":-7.16,"y":-7.6},{"x":-7.08,"y":-7.6},{"x":-7,"y":-7.6},{"x":-6.92,"y":-7.6},{"x":-6.84,"y":-7.6},{"x":-6.76,"y":-7.6},{"x":-6.68,"y":-7.6},{"x":-6.6,"y":-7.6},{"x":-6.52,"y":-7.6},{"x":-6.44,"y":-7.6},{"x":-6.36,"y":-7.6},{"x":-6.28,"y":-7.6},{"x":-6.12,"y":-7.6},{"x":-6.04,"y":-7.6},{"x":-5.96,"y":-7.6},{"x":-5.88,"y":-7.6},{"x":-5.76,"y":-7.6},{"x":-5.72,"y":-7.6},{"x":-5.16,"y":-7.6},{"x":-5.08,"y":-7.6},{"x":-5,"y":-7.6},{"x":-4.92,"y":-7.6},{"x":-4.84,"y":-7.6},{"x":-4.76,"y":-7.6},{"x":-4.68,"y":-7.6},{"x":-4.6,"y":-7.6},{"x":-4.52,"y":-7.6},{"x":-4.44,"y":-7.6},{"x":-4.36,"y":-7.6},{"x":-4.28,"y":-7.6},{"x":-4.2,"y":-7.6},{"x":-4.12,"y":-7.6},{"x":-4.04,"y":-7.6},{"x":-3.96,"y":-7.6},{"x":-3.88,"y":-7.6},{"x":-3.8,"y":-7.6},{"x":-3.72,"y":-7.6},{"x":-3.64,"y":-7.6},{"x":-3.56,"y":-7.6},{"x":-3.48,"y":-7.6},{"x":-3.4,"y":-7.6},{"x":-3.32,"y":-7.6},{"x":-3.24,"y":-7.6},{"x":-3.16,"y":-7.6},{"x":-3.08,"y":-7.6},{"x":-3,"y":-7.6},{"x":-2.92,"y":-7.6},{"x":-2.84,"y":-7.6},{"x":-2.76,"y":-7.6},{"x":-2.68,"y":-7.6},{"x":-2.6,"y":-7.6},{"x":-2.52,"y":-7.6},{"x":-2.44,"y":-7.6},{"x":-2.36,"y":-7.6},{"x":-2.28,"y":-7.6},{"x":-2.2,"y":-7.6},{"x":-2.12,"y":-7.6},{"x":-2.04,"y":-7.6},{"x":-1.96,"y":-7.6},{"x":-1.88,"y":-7.6},{"x":-1.8,"y":-7.6},{"x":-1.72,"y":-7.6},{"x":-1.64,"y":-7.6},{"x":-1.56,"y":-7.6},{"x":-1.48,"y":-7.6},{"x":-1.4,"y":-7.6},{"x":-1.32,"y":-7.6},{"x":-1.24,"y":-7.6},{"x":-1.16,"y":-7.6},{"x":-1.08,"y":-7.6},{"x":-1,"y":-7.6},{"x":-0.92,"y":-7.6},{"x":-0.84,"y":-7.6},{"x":-0.76,"y":-7.6},{"x":-0.68,"y":-7.6},{"x":-0.6,"y":-7.6},{"x":-0.52,"y":-7.6},{"x":-0.44,"y":-7.6},{"x":-0.36,"y":-7.6},{"x":-0.28,"y":-7.6},{"x":-0.2,"y":-7.6},{"x":-0.12,"y":-7.6},{"x":-0.04,"y":-7.6},{"x":0.2,"y":-7.6},{"x":0.28,"y":-7.6},{"x":0.36,"y":-7.6},{"x":0.44,"y":-7.6},{"x":0.52,"y":-7.6},{"x":0.6,"y":-7.6},{"x":0.68,"y":-7.6},{"x":0.76,"y":-7.6},{"x":0.84,"y":-7.6},{"x":0.92,"y":-7.6},{"x":1,"y":-7.6},{"x":1.08,"y":-7.6},{"x":1.16,"y":-7.6},{"x":1.24,"y":-7.6},{"x":1.32,"y":-7.6},{"x":1.4,"y":-7.6},{"x":1.48,"y":-7.6},{"x":1.56,"y":-7.6},{"x":1.64,"y":-7.6},{"x":1.72,"y":-7.6},{"x":1.8,"y":-7.6},{"x":1.88,"y":-7.6},{"x":1.96,"y":-7.6},{"x":2.04,"y":-7.6},{"x":2.12,"y":-7.6},{"x":2.2,"y":-7.6},{"x":2.28,"y":-7.6},{"x":2.36,"y":-7.6},{"x":2.44,"y":-7.6},{"x":2.52,"y":-7.6},{"x":2.6,"y":-7.6},{"x":2.68,"y":-7.6},{"x":2.76,"y":-7.6},{"x":2.84,"y":-7.6},{"x":2.92,"y":-7.6},{"x":3,"y":-7.6},{"x":3.08,"y":-7.6},{"x":3.16,"y":-7.6},{"x":3.24,"y":-7.6},{"x":3.32,"y":-7.6},{"x":3.4,"y":-7.6},{"x":3.48,"y":-7.6},{"x":3.56,"y":-7.6},{"x":3.64,"y":-7.6},{"x":3.72,"y":-7.6},{"x":3.8,"y":-7.6},{"x":3.88,"y":-7.6},{"x":3.96,"y":-7.6},{"x":4.04,"y":-7.6},{"x":4.12,"y":-7.6},{"x":4.2,"y":-7.6},{"x":4.28,"y":-7.6},{"x":4.36,"y":-7.6},{"x":4.44,"y":-7.6},{"x":4.52,"y":-7.6},{"x":4.6,"y":-7.6},{"x":4.68,"y":-7.6},{"x":4.76,"y":-7.6},{"x":4.84,"y":-7.6},{"x":4.92,"y":-7.6},{"x":5,"y":-7.6},{"x":5.08,"y":-7.6},{"x":5.16,"y":-7.6},{"x":5.24,"y":-7.6},{"x":5.32,"y":-7.6},{"x":5.4,"y":-7.6},{"x":5.48,"y":-7.6},{"x":5.56,"y":-7.6},{"x":5.64,"y":-7.6},{"x":5.72,"y":-7.6},{"x":5.8,"y":-7.6},{"x":5.88,"y":-7.6},{"x":5.96,"y":-7.6},{"x":6.04,"y":-7.6},{"x":6.12,"y":-7.6},{"x":6.2,"y":-7.6},{"x":6.28,"y":-7.6},{"x":6.36,"y":-7.6},{"x":6.44,"y":-7.6},{"x":6.52,"y":-7.6},{"x":6.6,"y":-7.6},{"x":6.68,"y":-7.6},{"x":6.76,"y":-7.6},{"x":6.84,"y":-7.6},{"x":6.92,"y":-7.6},{"x":7,"y":-7.6},{"x":7.08,"y":-7.6},{"x":7.16,"y":-7.6},{"x":7.24,"y":-7.6},{"x":7.32,"y":-7.6},{"x":7.4,"y":-7.6},{"x":7.48,"y":-7.6},{"x":7.72,"y":-7.6},{"x":7.8,"y":-7.6},{"x":7.88,"y":-7.6},{"x":7.96,"y":-7.6},{"x":8.04,"y":-7.6},{"x":8.12,"y":-7.6},{"x":8.2,"y":-7.6},{"x":8.28,"y":-7.6},{"x":8.36,"y":-7.6},{"x":8.44,"y":-7.6},{"x":8.52,"y":-7.6},{"x":8.6,"y":-7.6},{"x":8.68,"y":-7.6},{"x":8.76,"y":-7.6},{"x":8.84,"y":-7.6},{"x":8.92,"y":-7.6},{"x":9,"y":-7.6},{"x":9.08,"y":-7.6},{"x":9.16,"y":-7.6},{"x":9.24,"y":-7.6},{"x":9.32,"y":-7.6},{"x":9.4,"y":-7.6},{"x":9.48,"y":-7.6},{"x":9.56,"y":-7.6},{"x":9.64,"y":-7.6},{"x":9.72,"y":-7.6},{"x":9.8,"y":-7.6},{"x":9.88,"y":-7.6},{"x":9.96,"y":-7.6},{"x":10.04,"y":-7.6},{"x":10.12,"y":-7.6},{"x":10.2,"y":-7.6},{"x":10.28,"y":-7.6},{"x":10.36,"y":-7.6},{"x":10.44,"y":-7.6},{"x":10.52,"y":-7.6},{"x":10.6,"y":-7.6},{"x":10.68,"y":-7.6},{"x":10.76,"y":-7.6},{"x":10.84,"y":-7.6},{"x":10.92,"y":-7.6},{"x":11,"y":-7.6},{"x":11.08,"y":-7.6},{"x":11.16,"y":-7.6},{"x":11.24,"y":-7.6},{"x":11.32,"y":-7.6},{"x":11.4,"y":-7.6},{"x":11.48,"y":-7.6},{"x":11.56,"y":-7.6},{"x":11.64,"y":-7.6},{"x":11.72,"y":-7.6},{"x":11.8,"y":-7.6},{"x":11.88,"y":-7.6},{"x":11.96,"y":-7.6},{"x":12.04,"y":-7.6},{"x":12.12,"y":-7.6},{"x":12.2,"y":-7.6},{"x":12.28,"y":-7.6},{"x":12.36,"y":-7.6},{"x":12.44,"y":-7.6},{"x":12.52,"y":-7.6},{"x":12.6,"y":-7.6},{"x":12.68,"y":-7.6},{"x":12.76,"y":-7.6},{"x":12.84,"y":-7.6},{"x":12.92,"y":-7.6},{"x":13,"y":-7.6},{"x":13.08,"y":-7.6},{"x":13.16,"y":-7.6},{"x":13.24,"y":-7.6},{"x":13.32,"y":-7.6},{"x":13.4,"y":-7.6},{"x":13.48,"y":-7.6},{"x":13.56,"y":-7.6},{"x":13.64,"y":-7.6},{"x":13.72,"y":-7.6},{"x":13.8,"y":-7.6},{"x":13.88,"y":-7.6},{"x":13.96,"y":-7.6},{"x":14.04,"y":-7.6},{"x":14.12,"y":-7.6},{"x":14.2,"y":-7.6},{"x":14.28,"y":-7.6},{"x":14.36,"y":-7.6},{"x":14.44,"y":-7.6},{"x":14.52,"y":-7.6},{"x":14.6,"y":-7.6},{"x":14.68,"y":-7.6},{"x":14.76,"y":-7.6},{"x":14.84,"y":-7.6},{"x":-14.68,"y":-7.68},{"x":-14.6,"y":-7.68},{"x":-14.52,"y":-7.68},{"x":-14.44,"y":-7.68},{"x":-14.36,"y":-7.68},{"x":-14.28,"y":-7.68},{"x":-14.2,"y":-7.68},{"x":-14.12,"y":-7.68},{"x":-14.04,"y":-7.68},{"x":-13.96,"y":-7.68},{"x":-13.88,"y":-7.68},{"x":-13.8,"y":-7.68},{"x":-13.72,"y":-7.68},{"x":-13.64,"y":-7.68},{"x":-13.56,"y":-7.68},{"x":-13.48,"y":-7.68},{"x":-13.4,"y":-7.68},{"x":-13.32,"y":-7.68},{"x":-13.24,"y":-7.68},{"x":-13.16,"y":-7.68},{"x":-13.08,"y":-7.68},{"x":-13,"y":-7.68},{"x":-12.92,"y":-7.68},{"x":-12.84,"y":-7.68},{"x":-12.76,"y":-7.68},{"x":-12.68,"y":-7.68},{"x":-12.6,"y":-7.68},{"x":-12.52,"y":-7.68},{"x":-12.44,"y":-7.68},{"x":-12.36,"y":-7.68},{"x":-12.28,"y":-7.68},{"x":-12.2,"y":-7.68},{"x":-12.12,"y":-7.68},{"x":-12.04,"y":-7.68},{"x":-11.96,"y":-7.68},{"x":-11.88,"y":-7.68},{"x":-11.8,"y":-7.68},{"x":-11.72,"y":-7.68},{"x":-11.64,"y":-7.68},{"x":-11.56,"y":-7.68},{"x":-11.48,"y":-7.68},{"x":-11.4,"y":-7.68},{"x":-11.32,"y":-7.68},{"x":-11.24,"y":-7.68},{"x":-11.16,"y":-7.68},{"x":-11.08,"y":-7.68},{"x":-11,"y":-7.68},{"x":-10.92,"y":-7.68},{"x":-10.84,"y":-7.68},{"x":-10.76,"y":-7.68},{"x":-10.68,"y":-7.68},{"x":-10.6,"y":-7.68},{"x":-10.52,"y":-7.68},{"x":-10.44,"y":-7.68},{"x":-10.36,"y":-7.68},{"x":-10.28,"y":-7.68},{"x":-10.2,"y":-7.68},{"x":-10.12,"y":-7.68},{"x":-10.04,"y":-7.68},{"x":-9.96,"y":-7.68},{"x":-9.88,"y":-7.68},{"x":-9.8,"y":-7.68},{"x":-9.72,"y":-7.68},{"x":-9.64,"y":-7.68},{"x":-9.56,"y":-7.68},{"x":-9.48,"y":-7.68},{"x":-9.4,"y":-7.68},{"x":-9.32,"y":-7.68},{"x":-9.24,"y":-7.68},{"x":-9.16,"y":-7.68},{"x":-9.08,"y":-7.68},{"x":-9,"y":-7.68},{"x":-8.92,"y":-7.68},{"x":-8.84,"y":-7.68},{"x":-8.76,"y":-7.68},{"x":-8.56,"y":-7.68},{"x":-8.52,"y":-7.68},{"x":-8.36,"y":-7.68},{"x":-8.16,"y":-7.68},{"x":-8.04,"y":-7.68}]} \ No newline at end of file diff --git a/resources.qrc b/resources.qrc index 0e24e20..407ec78 100644 --- a/resources.qrc +++ b/resources.qrc @@ -1,6 +1,7 @@ styles.qss + assets/agv/demo_scan.smap icons/cmvr-app.ico icons/cmvr-app.svg icons/settings.svg diff --git a/src/agvmapdocument.cpp b/src/agvmapdocument.cpp new file mode 100644 index 0000000..97bd062 --- /dev/null +++ b/src/agvmapdocument.cpp @@ -0,0 +1,1013 @@ +#include "agvmapdocument.h" + +#include +#include +#include +#include + +#include +#include + +namespace { + +bool fail(QString *error, const QString &message) +{ + if (error) + *error = message; + return false; +} + +QJsonValue field(const QJsonObject &object, const char *snake, const char *camel) +{ + const QString snakeKey = QString::fromLatin1(snake); + return object.contains(snakeKey) ? object.value(snakeKey) + : object.value(QString::fromLatin1(camel)); +} + +QString objectId(const QJsonObject &object) +{ + return field(object, "instance_name", "instanceName").toString(); +} + +bool validIdentifier(const QString &id) +{ + if (id.isEmpty() || id.contains(QLatin1Char(','))) + return false; + for (const QChar &character : id) { + if (character.category() == QChar::Other_Control) + return false; + } + return true; +} + +// The controller reports numeric station-ID collisions even when the textual +// prefixes differ (for example LM1 and STATION_1). Compare decimal suffixes as +// text so leading zeroes and values larger than uint64 remain unambiguous. +QString stationNumber(const QString &id) +{ + int start = id.size(); + while (start > 0 && id.at(start - 1) >= QLatin1Char('0') + && id.at(start - 1) <= QLatin1Char('9')) + --start; + if (start == id.size()) + return {}; + while (start + 1 < id.size() && id.at(start) == QLatin1Char('0')) + ++start; + return id.mid(start); +} + +QString stationNumberError(const QString &id, const QString &existingId, + const QString &number) +{ + return QStringLiteral("站点 %1 与已有站点 %2 使用相同数字编号 %3;请修改站点 ID,显示名称可以保持不变。") + .arg(id, existingId, number); +} + +void incrementDecimal(QString *number) +{ + for (int index = number->size() - 1; index >= 0; --index) { + if (number->at(index) != QLatin1Char('9')) { + (*number)[index] = QChar(static_cast(number->at(index).unicode() + 1)); + return; + } + (*number)[index] = QLatin1Char('0'); + } + number->prepend(QLatin1Char('1')); +} + +bool finiteNumber(const QJsonObject &object, const QString &name, double *value) +{ + const QJsonValue json = object.value(name); + if (json.isUndefined()) { + *value = 0.0; // Protobuf JSON may omit primitive zero values. + return true; + } + if (!json.isDouble() || !std::isfinite(json.toDouble())) + return false; + *value = json.toDouble(); + return true; +} + +bool readPoint(const QJsonValue &value, QPointF *point) +{ + if (!value.isObject()) + return false; + double x = 0.0; + double y = 0.0; + if (!finiteNumber(value.toObject(), QStringLiteral("x"), &x) + || !finiteNumber(value.toObject(), QStringLiteral("y"), &y)) + return false; + *point = QPointF(x, y); + return true; +} + +QJsonObject pointJson(const QPointF &point) +{ + return {{QStringLiteral("x"), point.x()}, {QStringLiteral("y"), point.y()}}; +} + +int skipWhitespace(const QString &source, int position) +{ + while (position < source.size() && source.at(position).isSpace()) + ++position; + return position; +} + +int stringEnd(const QString &source, int position) +{ + for (int index = position + 1; index < source.size(); ++index) { + if (source.at(index) == QLatin1Char('\\')) + ++index; + else if (source.at(index) == QLatin1Char('"')) + return index + 1; + } + return -1; +} + +int valueEnd(const QString &source, int position) +{ + if (source.at(position) == QLatin1Char('"')) + return stringEnd(source, position); + if (source.at(position) != QLatin1Char('{') + && source.at(position) != QLatin1Char('[')) { + int index = position; + while (index < source.size() && source.at(index) != QLatin1Char(',') + && source.at(index) != QLatin1Char('}') + && source.at(index) != QLatin1Char(']')) + ++index; + return index; + } + int depth = 0; + for (int index = position; index < source.size(); ++index) { + const QChar character = source.at(index); + if (character == QLatin1Char('"')) { + index = stringEnd(source, index) - 1; + if (index < 0) + return -1; + } else if (character == QLatin1Char('{') || character == QLatin1Char('[')) { + ++depth; + } else if (character == QLatin1Char('}') || character == QLatin1Char(']')) { + if (--depth == 0) + return index + 1; + } + } + return -1; +} + +// Locate the original top-level arrays so appending does not reserialize +// unknown fields, large integer values, existing objects or occupancy data. +bool arrayClosingPosition(const QString &source, const QString &wanted, + int *closingPosition, int *openingPosition = nullptr) +{ + int position = skipWhitespace(source, 0) + 1; + int matches = 0; + *closingPosition = -1; + if (openingPosition) + *openingPosition = -1; + while (position < source.size()) { + position = skipWhitespace(source, position); + if (source.at(position) == QLatin1Char('}')) + break; + const int endOfKey = stringEnd(source, position); + if (endOfKey < 0) + return false; + const QJsonArray decoded = QJsonDocument::fromJson( + (QLatin1Char('[') + source.mid(position, endOfKey - position) + + QLatin1Char(']')).toUtf8()).array(); + position = skipWhitespace(source, endOfKey) + 1; // Colon. + position = skipWhitespace(source, position); + const int endOfValue = valueEnd(source, position); + if (endOfValue < 0) + return false; + if (!decoded.isEmpty() && decoded.first().toString() == wanted) { + ++matches; + if (source.at(position) != QLatin1Char('[')) + return false; + *closingPosition = endOfValue - 1; + if (openingPosition) + *openingPosition = position; + } + position = skipWhitespace(source, endOfValue); + if (source.at(position) == QLatin1Char(',')) + ++position; + } + return matches <= 1; +} + +// Locate one property in an original station without serializing that station. +// Duplicate description fields remain readable but are unsafe to rename. +bool propertyRange(const QString &source, int objectStart, int objectEnd, + const QString &wanted, int *valueStart, int *valueLength) +{ + int position = objectStart + 1; + int matches = 0; + *valueStart = -1; + *valueLength = 0; + while (position < objectEnd) { + position = skipWhitespace(source, position); + if (source.at(position) == QLatin1Char('}')) + break; + const int endOfKey = stringEnd(source, position); + if (endOfKey < 0) + return false; + const QJsonArray decoded = QJsonDocument::fromJson( + (QLatin1Char('[') + source.mid(position, endOfKey - position) + + QLatin1Char(']')).toUtf8()).array(); + position = skipWhitespace(source, endOfKey) + 1; + position = skipWhitespace(source, position); + const int endOfValue = valueEnd(source, position); + if (endOfValue < 0 || endOfValue > objectEnd) + return false; + if (!decoded.isEmpty() && decoded.first().toString() == wanted) { + ++matches; + *valueStart = position; + *valueLength = endOfValue - position; + } + position = skipWhitespace(source, endOfValue); + if (source.at(position) == QLatin1Char(',')) + ++position; + } + return matches <= 1; +} + +QString arrayElements(const QJsonArray &array) +{ + const QString serialized = QString::fromUtf8( + QJsonDocument(array).toJson(QJsonDocument::Compact)); + return serialized.mid(1, serialized.size() - 2); +} + +// Compare complete edited objects without converting original integer tokens to +// doubles. Whitespace, object key order and equivalent string escapes may vary +// on a fresh download; a changed numeric token is conservatively a conflict. +QString canonicalOriginalJson(const QString &source, int start, int end) +{ + start = skipWhitespace(source, start); + while (end > start && source.at(end - 1).isSpace()) + --end; + if (source.at(start) == QLatin1Char('"')) { + const QJsonArray decoded = QJsonDocument::fromJson( + (QLatin1Char('[') + source.mid(start, end - start) + QLatin1Char(']')).toUtf8()).array(); + return arrayElements(decoded); + } + const bool object = source.at(start) == QLatin1Char('{'); + if (!object && source.at(start) != QLatin1Char('[')) + return source.mid(start, end - start); + QStringList entries; + QSet keys; + bool duplicate = false; + int position = start + 1; + while ((position = skipWhitespace(source, position)) < end - 1) { + QString key; + if (object) { + const int keyEnd = stringEnd(source, position); + key = canonicalOriginalJson(source, position, keyEnd); + duplicate = duplicate || keys.contains(key); + keys.insert(key); + position = skipWhitespace(source, keyEnd) + 1; + position = skipWhitespace(source, position); + } + const int itemEnd = valueEnd(source, position); + entries.append(key + (object ? QStringLiteral(":") : QString()) + + canonicalOriginalJson(source, position, itemEnd)); + position = skipWhitespace(source, itemEnd); + if (position < end && source.at(position) == QLatin1Char(',')) + ++position; + } + // Duplicate keys are unsafe to normalize because their order may matter. + if (duplicate) + return source.mid(start, end - start); + if (object) + entries.sort(); + return (object ? QStringLiteral("{") : QStringLiteral("[")) + + entries.join(QLatin1Char(',')) + + (object ? QStringLiteral("}") : QStringLiteral("]")); +} + +QVariantList routeGeometry(const QJsonObject &route) +{ + QPointF start; + QPointF end; + if (!readPoint(field(route, "start_pos", "startPos").toObject() + .value(QStringLiteral("pos")), &start) + || !readPoint(field(route, "end_pos", "endPos").toObject() + .value(QStringLiteral("pos")), &end)) + return {}; + QVector controlPoints{start}; + const QString className = field(route, "class_name", "className").toString(); + if (className == QStringLiteral("BezierPath")) { + for (int index = 1; index <= 4; ++index) { + const QByteArray snake = QStringLiteral("control_pos%1").arg(index).toLatin1(); + const QByteArray camel = QStringLiteral("controlPos%1").arg(index).toLatin1(); + const QJsonValue control = field(route, snake.constData(), camel.constData()); + if (control.isUndefined()) + continue; + QPointF point; + if (!readPoint(control, &point)) + return {}; + controlPoints.append(point); + } + } + controlPoints.append(end); + QVariantList points; + const int samples = controlPoints.size() > 2 ? 32 : 1; + for (int step = 0; step <= samples; ++step) { + const double ratio = static_cast(step) / samples; + QVector interpolation = controlPoints; + for (int count = interpolation.size() - 1; count > 0; --count) { + for (int index = 0; index < count; ++index) + interpolation[index] = interpolation[index] * (1.0 - ratio) + + interpolation[index + 1] * ratio; + } + points.append(QVariantMap{{QStringLiteral("x"), interpolation.first().x()}, + {QStringLiteral("y"), interpolation.first().y()}}); + } + return points; +} + +} // namespace + +QString AgvMapDocument::key(const char *snake, const char *camel) const +{ + return QString::fromLatin1(m_camelCase ? camel : snake); +} + +bool AgvMapDocument::load(const QString &source, QString *error) +{ + if (error) + error->clear(); + QJsonParseError parseError; + const QJsonDocument document = QJsonDocument::fromJson(source.toUtf8(), &parseError); + if (parseError.error != QJsonParseError::NoError || !document.isObject()) + return fail(error, QStringLiteral("地图不是可编辑的 SEER 2D JSON;不支持 ZIP/二进制地图。")); + const QJsonObject root = document.object(); + const bool camel = root.contains(QStringLiteral("advancedPointList")); + const bool snake = root.contains(QStringLiteral("advanced_point_list")); + if (camel == snake) + return fail(error, QStringLiteral("无法识别地图站点格式,或地图混用了两套字段名称。")); + const QString stationKey = camel ? QStringLiteral("advancedPointList") + : QStringLiteral("advanced_point_list"); + const QString routeKey = camel ? QStringLiteral("advancedCurveList") + : QStringLiteral("advanced_curve_list"); + const QString alternateRouteKey = camel ? QStringLiteral("advanced_curve_list") + : QStringLiteral("advancedCurveList"); + if (!root.value(stationKey).isArray() || root.contains(alternateRouteKey) + || (root.contains(routeKey) && !root.value(routeKey).isArray()) + || !root.value(QStringLiteral("header")).isObject()) + return fail(error, QStringLiteral("地图站点、路线或 header 结构不受支持。")); + const QJsonObject header = root.value(QStringLiteral("header")).toObject(); + const QJsonValue mapType = field(header, "map_type", "mapType"); + double resolution = 0.0; + if ((!mapType.isUndefined() && mapType.toString() != QStringLiteral("2D-Map")) + || !finiteNumber(header, QStringLiteral("resolution"), &resolution) + || resolution <= 0.0) + return fail(error, QStringLiteral("仅支持具有有效分辨率的 SEER 2D 地图。")); + QSet stationIds; + const QJsonArray stationArray = root.value(stationKey).toArray(); + for (const QJsonValue &value : stationArray) { + const QJsonObject station = value.toObject(); + const QString id = objectId(station); + QPointF point; + double heading = 0.0; + if (!value.isObject() || id.isEmpty() || stationIds.contains(id) + || !readPoint(station.value(QStringLiteral("pos")), &point) + || !finiteNumber(station, QStringLiteral("dir"), &heading)) + return fail(error, QStringLiteral("地图含无效坐标、重复 ID 或无法识别的站点。")); + stationIds.insert(id); + } + for (const QJsonValue &value : root.value(routeKey).toArray()) { + if (!value.isObject()) + return fail(error, QStringLiteral("地图路线对象结构无效。")); + } + int stationArrayEnd = -1; + int stationArrayStart = -1; + int routeArrayEnd = -1; + int routeArrayStart = -1; + if (!arrayClosingPosition(source, stationKey, &stationArrayEnd, &stationArrayStart) + || !arrayClosingPosition(source, routeKey, &routeArrayEnd, &routeArrayStart) + || stationArrayEnd < 0) + return fail(error, QStringLiteral("地图语义数组出现重复字段,无法安全追加内容。")); + + QHash stationSources; + QVector stationElements; + QVector routeElements; + int position = stationArrayStart + 1; + for (const QJsonValue &value : stationArray) { + position = skipWhitespace(source, position); + const int end = valueEnd(source, position); + if (end < 0 || end > stationArrayEnd) + return fail(error, QStringLiteral("无法安全定位地图站点原文。")); + const QJsonObject station = value.toObject(); + const QJsonValue description = station.value(QStringLiteral("description")); + StationSource original; + original.originalName = description.toString(); + original.hasDescription = !description.isUndefined(); + original.objectEnd = end - 1; + original.editableName = propertyRange(source, position, end, + QStringLiteral("description"), + &original.descriptionStart, + &original.descriptionLength) + && (description.isUndefined() || description.isString()); + stationSources.insert(objectId(station), original); + stationElements.append({objectId(station), position, end}); + position = skipWhitespace(source, end); + if (source.at(position) == QLatin1Char(',')) + ++position; + } + position = routeArrayStart + 1; + for (const QJsonValue &value : root.value(routeKey).toArray()) { + position = skipWhitespace(source, position); + const int end = valueEnd(source, position); + if (end < 0 || end > routeArrayEnd) + return fail(error, QStringLiteral("无法安全定位地图路线原文。")); + routeElements.append({objectId(value.toObject()), position, end}); + position = skipWhitespace(source, end); + if (source.at(position) == QLatin1Char(',')) + ++position; + } + + clear(); + m_root = root; + m_source = source; + m_camelCase = camel; + m_stationKey = stationKey; + m_routeKey = routeKey; + m_stationArrayEnd = stationArrayEnd; + m_routeArrayEnd = routeArrayEnd; + m_rootEnd = source.lastIndexOf(QLatin1Char('}')); + m_originalStationCount = stationArray.size(); + m_originalRouteCount = root.value(routeKey).toArray().size(); + m_stationSources = stationSources; + m_stationElements = stationElements; + m_routeElements = routeElements; + m_loaded = true; + return true; +} + +QJsonObject AgvMapDocument::stationObject(const QString &id) const +{ + for (const QJsonValue &value : m_root.value(m_stationKey).toArray()) { + if (objectId(value.toObject()) == id) + return value.toObject(); + } + return {}; +} + +bool AgvMapDocument::hasStation(const QString &id) const +{ + return !stationObject(id.trimmed()).isEmpty(); +} + +bool AgvMapDocument::idInUse(const QString &id) const +{ + if (hasStation(id) || m_removedStations.contains(id) || m_removedRoutes.contains(id)) + return true; + for (const QJsonValue &value : m_root.value(m_routeKey).toArray()) { + if (objectId(value.toObject()) == id) + return true; + } + return false; +} + +QString AgvMapDocument::nextAvailableStationId() const +{ + if (!m_loaded) + return {}; + QSet usedNumbers; + for (const QJsonValue &value : m_root.value(m_stationKey).toArray()) { + const QString number = stationNumber(objectId(value.toObject())); + if (!number.isEmpty()) + usedNumbers.insert(number); + } + for (const QString &id : m_removedStations) { + const QString number = stationNumber(id); + if (!number.isEmpty()) + usedNumbers.insert(number); + } + QSet routeIds; + for (const QJsonValue &value : m_root.value(m_routeKey).toArray()) + routeIds.insert(objectId(value.toObject())); + routeIds.unite(m_removedRoutes); + QString number = QStringLiteral("1"); + while (usedNumbers.contains(number) + || routeIds.contains(QStringLiteral("LM") + number)) + incrementDecimal(&number); + return QStringLiteral("LM") + number; +} + +bool AgvMapDocument::validateStationIds(QString *error) const +{ + if (error) + error->clear(); + if (!m_loaded) + return fail(error, QStringLiteral("请先读取可编辑的 AGV 地图。")); + QHash idsByNumber; + for (const QJsonValue &value : m_root.value(m_stationKey).toArray()) { + const QString id = objectId(value.toObject()); + const QString number = stationNumber(id); + if (number.isEmpty()) + continue; + if (idsByNumber.contains(number)) + return fail(error, stationNumberError(id, idsByNumber.value(number), number)); + idsByNumber.insert(number, id); + } + return true; +} + +bool AgvMapDocument::addStation(const QString &requestedId, double x, double y, + double theta, QString *error, const QString &name) +{ + if (error) + error->clear(); + if (!m_loaded) + return fail(error, QStringLiteral("请先读取可编辑的 AGV 地图。")); + const QString id = requestedId.trimmed(); + if (!validIdentifier(id)) + return fail(error, QStringLiteral("站点 ID 不能为空,且不能包含逗号、换行或控制字符。")); + if (idInUse(id)) + return fail(error, QStringLiteral("站点 ID 不能与已有站点或路线重复。")); + const QString number = stationNumber(id); + if (!number.isEmpty()) { + for (const QJsonValue &value : m_root.value(m_stationKey).toArray()) { + const QString existingId = objectId(value.toObject()); + if (stationNumber(existingId) == number) + return fail(error, stationNumberError(id, existingId, number)); + } + for (const QString &existingId : m_removedStations) { + if (stationNumber(existingId) == number) + return fail(error, stationNumberError(id, existingId, number)); + } + } + if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(theta)) + return fail(error, QStringLiteral("站点坐标和朝向必须为有限数值。")); + QJsonObject spin{{QStringLiteral("key"), QStringLiteral("spin")}, + {QStringLiteral("type"), QStringLiteral("bool")}, + {QStringLiteral("value"), QStringLiteral("ZmFsc2U=")}, + {key("bool_value", "boolValue"), false}}; + QJsonObject station{{key("class_name", "className"), QStringLiteral("LandMark")}, + {key("instance_name", "instanceName"), id}, + {QStringLiteral("pos"), pointJson(QPointF(x, y))}, + {QStringLiteral("dir"), theta}, + {QStringLiteral("description"), name}, + {key("ignore_dir", "ignoreDir"), false}, + {QStringLiteral("property"), QJsonArray{spin}}}; + QJsonArray stationArray = m_root.value(m_stationKey).toArray(); + stationArray.append(station); + m_root.insert(m_stationKey, stationArray); + m_addedStations.append(station); + m_draftStations.insert(id); + m_dirty = true; + return true; +} + +bool AgvMapDocument::setStationName(const QString &requestedId, const QString &name, + QString *error) +{ + if (error) + error->clear(); + if (!m_loaded) + return fail(error, QStringLiteral("请先读取可编辑的 AGV 地图。")); + const QString id = requestedId.trimmed(); + QJsonArray stationArray = m_root.value(m_stationKey).toArray(); + for (int index = 0; index < stationArray.size(); ++index) { + QJsonObject station = stationArray.at(index).toObject(); + if (objectId(station) != id) + continue; + const bool draft = m_draftStations.contains(id); + const StationSource original = m_stationSources.value(id); + if (!draft && !original.editableName) + return fail(error, QStringLiteral("该站点的 description 不是唯一字符串,无法安全修改名称。")); + if (station.value(QStringLiteral("description")).toString() == name) + return true; + + if (!draft && name == original.originalName) { + m_stationNameChanges.remove(id); + if (original.hasDescription) + station.insert(QStringLiteral("description"), name); + else + station.remove(QStringLiteral("description")); + } else { + station.insert(QStringLiteral("description"), name); + if (!draft) + m_stationNameChanges.insert(id, name); + } + stationArray.replace(index, station); + m_root.insert(m_stationKey, stationArray); + if (draft) { + for (int addedIndex = 0; addedIndex < m_addedStations.size(); ++addedIndex) { + if (objectId(m_addedStations.at(addedIndex).toObject()) == id) { + m_addedStations.replace(addedIndex, station); + break; + } + } + } + updateDirty(); + return true; + } + return fail(error, QStringLiteral("地图中不存在该站点。")); +} + +QJsonObject AgvMapDocument::makeRoute(const QString &id, const QJsonObject &source, + const QJsonObject &target) const +{ + const QJsonObject sourcePosition = source.value(QStringLiteral("pos")).toObject(); + const QJsonObject targetPosition = target.value(QStringLiteral("pos")).toObject(); + const QPointF start(sourcePosition.value(QStringLiteral("x")).toDouble(), + sourcePosition.value(QStringLiteral("y")).toDouble()); + const QPointF end(targetPosition.value(QStringLiteral("x")).toDouble(), + targetPosition.value(QStringLiteral("y")).toDouble()); + QJsonObject startReference{{key("instance_name", "instanceName"), objectId(source)}, + {QStringLiteral("pos"), pointJson(start)}}; + QJsonObject endReference{{key("instance_name", "instanceName"), objectId(target)}, + {QStringLiteral("pos"), pointJson(end)}}; + QJsonArray properties; + for (const QString &propertyName : {QStringLiteral("direction"), QStringLiteral("movestyle")}) { + properties.append(QJsonObject{{QStringLiteral("key"), propertyName}, + {QStringLiteral("type"), QStringLiteral("int")}, + {QStringLiteral("value"), QStringLiteral("MA==")}, + {key("int32_value", "int32Value"), 0}}); + } + // The vendor sample represents straight travel using a BezierPath with + // collinear control points at one and two thirds of the segment. + return {{key("class_name", "className"), QStringLiteral("BezierPath")}, + {key("instance_name", "instanceName"), id}, + {key("start_pos", "startPos"), startReference}, + {key("end_pos", "endPos"), endReference}, + {key("control_pos1", "controlPos1"), pointJson(start * (2.0 / 3.0) + end * (1.0 / 3.0))}, + {key("control_pos2", "controlPos2"), pointJson(start * (1.0 / 3.0) + end * (2.0 / 3.0))}, + {QStringLiteral("property"), properties}}; +} + +bool AgvMapDocument::addRoute(const QString &requestedId, const QString &requestedSource, + const QString &requestedTarget, bool bidirectional, + QString *error) +{ + if (error) + error->clear(); + if (!m_loaded) + return fail(error, QStringLiteral("请先读取可编辑的 AGV 地图。")); + const QString id = requestedId.trimmed(); + const QString source = requestedSource.trimmed(); + const QString target = requestedTarget.trimmed(); + const QString reverseId = id + QStringLiteral("_reverse"); + if (!validIdentifier(id)) + return fail(error, QStringLiteral("路线 ID 不能为空,且不能包含逗号、换行或控制字符。")); + if (idInUse(id) || (bidirectional && idInUse(reverseId))) + return fail(error, QStringLiteral("路线 ID 或自动生成的反向路线 ID 与已有对象重复。")); + if (!validIdentifier(source) || !validIdentifier(target)) + return fail(error, QStringLiteral("路线端点 ID 包含逗号或控制字符,无法用于站点路径导航。")); + if (source == target || !hasStation(source) || !hasStation(target)) + return fail(error, QStringLiteral("路线两端必须是地图中存在的不同站点。")); + const QJsonObject sourceStation = stationObject(source); + const QJsonObject targetStation = stationObject(target); + QPointF sourcePoint; + QPointF targetPoint; + readPoint(sourceStation.value(QStringLiteral("pos")), &sourcePoint); + readPoint(targetStation.value(QStringLiteral("pos")), &targetPoint); + if (sourcePoint == targetPoint) + return fail(error, QStringLiteral("两个站点坐标重合,无法创建零长度路线。")); + + QJsonArray additions{makeRoute(id, sourceStation, targetStation)}; + if (bidirectional) + additions.append(makeRoute(reverseId, targetStation, sourceStation)); + QJsonArray routeArray = m_root.value(m_routeKey).toArray(); + for (const QJsonValue &route : additions) { + routeArray.append(route); + m_addedRoutes.append(route); + m_draftRoutes.insert(objectId(route.toObject())); + } + m_root.insert(m_routeKey, routeArray); + m_dirty = true; + return true; +} + +void AgvMapDocument::updateDirty() +{ + m_dirty = !m_addedStations.isEmpty() || !m_addedRoutes.isEmpty() + || !m_stationNameChanges.isEmpty() || !m_removedStations.isEmpty() + || !m_removedRoutes.isEmpty(); +} + +QStringList AgvMapDocument::connectedRouteIds(const QString &requestedId) const +{ + QStringList ids; + const QString id = requestedId.trimmed(); + for (const QJsonValue &value : m_root.value(m_routeKey).toArray()) { + const QJsonObject route = value.toObject(); + if (objectId(field(route, "start_pos", "startPos").toObject()) == id + || objectId(field(route, "end_pos", "endPos").toObject()) == id) + ids.append(objectId(route)); + } + return ids; +} + +QStringList AgvMapDocument::removedStationIds() const +{ + QStringList ids = m_removedStations.values(); + ids.sort(); + return ids; +} + +QStringList AgvMapDocument::removedRouteIds() const +{ + QStringList ids = m_removedRoutes.values(); + ids.sort(); + return ids; +} + +bool AgvMapDocument::removeRoute(const QString &requestedId, QString *error) +{ + if (error) + error->clear(); + if (!m_loaded) + return fail(error, QStringLiteral("请先读取可编辑的 AGV 地图。")); + const QString id = requestedId.trimmed(); + QJsonArray routeArray = m_root.value(m_routeKey).toArray(); + int found = -1; + for (int index = 0; index < routeArray.size(); ++index) { + if (objectId(routeArray.at(index).toObject()) == id) { + if (found >= 0 || id.isEmpty()) + return fail(error, QStringLiteral("路线 ID 为空或重复,无法安全定位要删除的路线。")); + found = index; + } + } + if (found < 0) + return fail(error, QStringLiteral("地图中不存在该路线。")); + routeArray.removeAt(found); + m_root.insert(m_routeKey, routeArray); + if (m_draftRoutes.remove(id)) { + for (int index = m_addedRoutes.size() - 1; index >= 0; --index) { + if (objectId(m_addedRoutes.at(index).toObject()) == id) + m_addedRoutes.removeAt(index); + } + } else { + m_removedRoutes.insert(id); + } + updateDirty(); + return true; +} + +bool AgvMapDocument::removeStation(const QString &requestedId, bool removeConnectedRoutes, + QString *error) +{ + if (error) + error->clear(); + if (!m_loaded) + return fail(error, QStringLiteral("请先读取可编辑的 AGV 地图。")); + const QString id = requestedId.trimmed(); + if (!hasStation(id)) + return fail(error, QStringLiteral("地图中不存在该站点。")); + const QStringList connected = connectedRouteIds(id); + if (!connected.isEmpty() && !removeConnectedRoutes) + return fail(error, QStringLiteral("站点 %1 仍连接 %2 条路线;请确认同时删除这些关联路线。") + .arg(id).arg(connected.size())); + // Work on a copy so an ambiguous connected route cannot cause half a delete. + AgvMapDocument candidate = *this; + for (const QString &routeId : connected) { + if (!candidate.removeRoute(routeId, error)) + return false; + } + QJsonArray stationArray = candidate.m_root.value(candidate.m_stationKey).toArray(); + for (int index = 0; index < stationArray.size(); ++index) { + if (objectId(stationArray.at(index).toObject()) == id) { + stationArray.removeAt(index); + break; + } + } + candidate.m_root.insert(candidate.m_stationKey, stationArray); + candidate.m_stationNameChanges.remove(id); + if (candidate.m_draftStations.remove(id)) { + for (int index = candidate.m_addedStations.size() - 1; index >= 0; --index) { + if (objectId(candidate.m_addedStations.at(index).toObject()) == id) + candidate.m_addedStations.removeAt(index); + } + } else { + candidate.m_removedStations.insert(id); + } + candidate.updateDirty(); + *this = candidate; + return true; +} + +QString AgvMapDocument::originalObject(const QString &id, bool station, int *matches) const +{ + const QVector &elements = station ? m_stationElements : m_routeElements; + QString object; + int count = 0; + for (const ObjectSource &element : elements) { + if (element.id == id) { + ++count; + object = canonicalOriginalJson(m_source, element.start, element.end); + } + } + if (matches) + *matches = count; + return object; +} + +bool AgvMapDocument::mergeRemovalsInto(AgvMapDocument *latest, QString *error) const +{ + if (error) + error->clear(); + if (m_removedStations.isEmpty() && m_removedRoutes.isEmpty()) + return true; + if (!m_loaded || !latest || !latest->m_loaded) + return fail(error, QStringLiteral("请先读取可编辑的 AGV 地图。")); + // Validate every target and reference before mutating the fresh snapshot. + for (bool station : {false, true}) { + const QSet &ids = station ? m_removedStations : m_removedRoutes; + for (const QString &id : ids) { + int originalCount = 0; + int latestCount = 0; + const QString original = originalObject(id, station, &originalCount); + const QString current = latest->originalObject(id, station, &latestCount); + if (originalCount != 1 || latestCount > 1 + || (latestCount == 1 && original != current)) + return fail(error, QStringLiteral("%1 %2 已被其他客户端修改,未删除;请重新读取地图后确认。") + .arg(station ? QStringLiteral("站点") : QStringLiteral("路线"), id)); + } + } + for (const QString &id : m_removedStations) { + for (const QString &routeId : latest->connectedRouteIds(id)) { + if (!m_removedRoutes.contains(routeId)) + return fail(error, QStringLiteral("站点 %1 新增了关联路线 %2,未自动删除;请重新读取地图后确认。") + .arg(id, routeId)); + } + } + AgvMapDocument candidate = *latest; + for (const QString &id : m_removedRoutes) { + bool present = false; + for (const QVariant &route : candidate.routes()) { + if (route.toMap().value(QStringLiteral("id")).toString() == id) { + present = true; + break; + } + } + if (present && !candidate.removeRoute(id, error)) + return false; + } + for (const QString &id : m_removedStations) { + if (candidate.hasStation(id) && !candidate.removeStation(id, false, error)) + return false; + } + *latest = candidate; + return true; +} + +bool AgvMapDocument::verifyRemovals(const AgvMapDocument &readback, QString *error) const +{ + if (error) + error->clear(); + if (m_removedStations.isEmpty() && m_removedRoutes.isEmpty()) + return true; + if (!readback.m_loaded) + return fail(error, QStringLiteral("尚未读回有效地图,无法确认删除。")); + for (const QString &id : m_removedStations) { + if (readback.hasStation(id) || !readback.connectedRouteIds(id).isEmpty()) + return fail(error, QStringLiteral("车端仍存在待删除站点 %1 或指向该站点的路线。").arg(id)); + } + for (const QJsonValue &value : readback.m_root.value(readback.m_routeKey).toArray()) { + const QString id = objectId(value.toObject()); + if (m_removedRoutes.contains(id)) + return fail(error, QStringLiteral("车端仍存在待删除路线 %1。").arg(id)); + } + return true; +} + +QVariantList AgvMapDocument::stations() const +{ + QVariantList output; + for (const QJsonValue &value : m_root.value(m_stationKey).toArray()) { + const QJsonObject station = value.toObject(); + const QJsonObject position = station.value(QStringLiteral("pos")).toObject(); + const QString id = objectId(station); + const QString description = station.value(QStringLiteral("description")).toString(); + output.append(QVariantMap{{QStringLiteral("id"), id}, + {QStringLiteral("description"), description}, + {QStringLiteral("name"), description.isEmpty() ? id : description}, + {QStringLiteral("nameChanged"), m_stationNameChanges.contains(id)}, + {QStringLiteral("originalName"), m_stationSources.value(id).originalName}, + {QStringLiteral("type"), field(station, "class_name", "className").toString()}, + {QStringLiteral("x"), position.value(QStringLiteral("x")).toDouble()}, + {QStringLiteral("y"), position.value(QStringLiteral("y")).toDouble()}, + {QStringLiteral("theta"), station.value(QStringLiteral("dir")).toDouble()}, + {QStringLiteral("draft"), m_draftStations.contains(id)}}); + } + return output; +} + +QVariantList AgvMapDocument::routes() const +{ + QVariantList output; + for (const QJsonValue &value : m_root.value(m_routeKey).toArray()) { + const QJsonObject route = value.toObject(); + const QString id = objectId(route); + output.append(QVariantMap{ + {QStringLiteral("id"), id}, + {QStringLiteral("sourceStation"), objectId(field(route, "start_pos", "startPos").toObject())}, + {QStringLiteral("targetStation"), objectId(field(route, "end_pos", "endPos").toObject())}, + {QStringLiteral("points"), routeGeometry(route)}, + {QStringLiteral("draft"), m_draftRoutes.contains(id)}}); + } + return output; +} + +QStringList AgvMapDocument::stationIds() const +{ + QStringList ids; + for (const QVariant &value : stations()) + ids.append(value.toMap().value(QStringLiteral("id")).toString()); + return ids; +} + +QString AgvMapDocument::content() const +{ + if (!m_loaded || !m_dirty) + return m_source; + struct Edit { int position; int length; QString text; }; + QVector edits; + const auto appendRemovals = [&edits](const QVector &elements, + const QSet &removed) { + for (int index = 0; index < elements.size(); ++index) { + if (!removed.contains(elements.at(index).id)) + continue; + const int first = index; + while (index + 1 < elements.size() && removed.contains(elements.at(index + 1).id)) + ++index; + int start = elements.at(first).start; + int end = elements.at(index).end; + if (index + 1 < elements.size()) + end = elements.at(index + 1).start; + else if (first > 0) + start = elements.at(first - 1).end; + edits.append({start, end - start, QString()}); + } + }; + appendRemovals(m_stationElements, m_removedStations); + appendRemovals(m_routeElements, m_removedRoutes); + for (auto iterator = m_stationNameChanges.constBegin(); + iterator != m_stationNameChanges.constEnd(); ++iterator) { + const StationSource original = m_stationSources.value(iterator.key()); + const QString encodedName = arrayElements(QJsonArray{iterator.value()}); + if (original.descriptionStart >= 0) + edits.append({original.descriptionStart, original.descriptionLength, encodedName}); + else + edits.append({original.objectEnd, 0, QStringLiteral(",\"description\":") + encodedName}); + } + if (!m_addedStations.isEmpty()) { + edits.append({m_stationArrayEnd, 0, + (m_originalStationCount > m_removedStations.size() ? QStringLiteral(",") : QString()) + + arrayElements(m_addedStations)}); + } + if (!m_addedRoutes.isEmpty()) { + if (m_routeArrayEnd >= 0) { + edits.append({m_routeArrayEnd, 0, + (m_originalRouteCount > m_removedRoutes.size() ? QStringLiteral(",") : QString()) + + arrayElements(m_addedRoutes)}); + } else { + edits.append({m_rootEnd, 0, QStringLiteral(",\"%1\":[%2]") + .arg(m_routeKey, arrayElements(m_addedRoutes))}); + } + } + std::sort(edits.begin(), edits.end(), [](const Edit &left, const Edit &right) { + return left.position > right.position; + }); + QString output = m_source; + for (const Edit &edit : edits) + output.replace(edit.position, edit.length, edit.text); + return output; +} + +void AgvMapDocument::markSaved() +{ + if (!m_loaded) + return; + const QString savedContent = content(); + load(savedContent); +} + +void AgvMapDocument::clear() +{ + m_root = {}; + m_source.clear(); + m_stationKey.clear(); + m_routeKey.clear(); + m_addedStations = {}; + m_addedRoutes = {}; + m_draftStations.clear(); + m_draftRoutes.clear(); + m_removedStations.clear(); + m_removedRoutes.clear(); + m_stationElements.clear(); + m_routeElements.clear(); + m_stationSources.clear(); + m_stationNameChanges.clear(); + m_stationArrayEnd = -1; + m_routeArrayEnd = -1; + m_rootEnd = -1; + m_originalStationCount = 0; + m_originalRouteCount = 0; + m_camelCase = false; + m_loaded = false; + m_dirty = false; +} diff --git a/src/agvmapdocument.h b/src/agvmapdocument.h new file mode 100644 index 0000000..f393340 --- /dev/null +++ b/src/agvmapdocument.h @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// 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 m_draftStations; + QSet m_draftRoutes; + QSet m_removedStations; + QSet m_removedRoutes; + QVector m_stationElements; + QVector m_routeElements; + QHash m_stationSources; + QHash 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; +}; diff --git a/src/agvmapeditorwidget.cpp b/src/agvmapeditorwidget.cpp new file mode 100644 index 0000000..4523502 --- /dev/null +++ b/src/agvmapeditorwidget.cpp @@ -0,0 +1,1160 @@ +#include "agvmapeditorwidget.h" + +#include "agvmapviewwidget.h" +#include "robotclient.h" +#include "uiicons.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int kSaveVerificationAttempts = 6; +constexpr int kSaveVerificationIntervalMs = 500; +constexpr int kSaveVerificationTimeoutMs = 12000; + +QVariantMap objectWithId(const QVariantList &objects, const QString &id) +{ + for (const QVariant &value : objects) { + if (value.toMap().value(QStringLiteral("id")).toString() == id) + return value.toMap(); + } + return {}; +} + +bool closeCoordinate(double actual, double expected) +{ + return std::isfinite(actual) && std::isfinite(expected) + && std::abs(actual - expected) <= 0.000001; +} + +bool sameStation(const QVariantMap &actual, const QVariantMap &expected) +{ + return !actual.isEmpty() && !expected.isEmpty() + && actual.value(QStringLiteral("type")) == expected.value(QStringLiteral("type")) + && actual.value(QStringLiteral("description")) == expected.value(QStringLiteral("description")) + && closeCoordinate(actual.value(QStringLiteral("x")).toDouble(), expected.value(QStringLiteral("x")).toDouble()) + && closeCoordinate(actual.value(QStringLiteral("y")).toDouble(), expected.value(QStringLiteral("y")).toDouble()) + && closeCoordinate(actual.value(QStringLiteral("theta")).toDouble(), expected.value(QStringLiteral("theta")).toDouble()); +} + +bool sameRoute(const QVariantMap &actual, const QVariantMap &expected) +{ + if (actual.isEmpty() || expected.isEmpty() + || actual.value(QStringLiteral("sourceStation")) != expected.value(QStringLiteral("sourceStation")) + || actual.value(QStringLiteral("targetStation")) != expected.value(QStringLiteral("targetStation"))) + return false; + const QVariantList actualPoints = actual.value(QStringLiteral("points")).toList(); + const QVariantList expectedPoints = expected.value(QStringLiteral("points")).toList(); + if (actualPoints.isEmpty() || actualPoints.size() != expectedPoints.size()) + return false; + for (int index = 0; index < actualPoints.size(); ++index) { + const QVariantMap a = actualPoints.at(index).toMap(); + const QVariantMap b = expectedPoints.at(index).toMap(); + if (!closeCoordinate(a.value(QStringLiteral("x")).toDouble(), b.value(QStringLiteral("x")).toDouble()) + || !closeCoordinate(a.value(QStringLiteral("y")).toDouble(), b.value(QStringLiteral("y")).toDouble())) + return false; + } + return true; +} + +bool mapNameMatches(const QString &content, const QString &name) +{ + const QJsonObject header = QJsonDocument::fromJson(content.toUtf8()).object() + .value(QStringLiteral("header")).toObject(); + const QJsonValue camel = header.value(QStringLiteral("mapName")); + const QJsonValue snake = header.value(QStringLiteral("map_name")); + return !(camel.isUndefined() && snake.isUndefined()) + && (camel.isUndefined() || (camel.isString() && camel.toString() == name)) + && (snake.isUndefined() || (snake.isString() && snake.toString() == name)); +} +} // namespace + +QString AgvMapEditorWidget::Context::key() const +{ + return QString::number(endpoint.size()) + QLatin1Char(':') + endpoint + + QString::number(deviceId.size()) + QLatin1Char(':') + deviceId + + QString::number(mapName.size()) + QLatin1Char(':') + mapName + + (demo ? QStringLiteral(":demo") : QStringLiteral(":live")); +} + +AgvMapEditorWidget::AgvMapEditorWidget(RobotClient *client, AgvMapViewWidget *view, + QWidget *parent) + : QWidget(parent), m_client(client), m_view(view) +{ + setObjectName(QStringLiteral("agvMapEditor")); + setStyleSheet(QStringLiteral( + "QWidget#agvMapEditor QPushButton { min-height:26px; padding:4px 12px; " + "border:1px solid #dde5ee; border-radius:7px; background:#ffffff; color:#566a83; font-size:12px; }" + "QWidget#agvMapEditor QPushButton:hover { background:#f2f6fc; border-color:#aac5eb; }" + "QWidget#agvMapEditor QPushButton:checked { background:#edf4ff; border-color:#b5cdf1; color:#236ddb; }" + "QWidget#agvMapEditor QPushButton#agvSaveMapObjectsButton { background:#246fe5; border-color:#246fe5; color:#ffffff; }" + "QWidget#agvMapEditor QPushButton#agvSaveMapObjectsButton:hover { background:#185fcc; }" + "QWidget#agvMapEditor QPushButton:disabled { background:#f5f7fa; border-color:#e7edf3; color:#a5b1bf; }" + "QWidget#agvMapEditor QPushButton#agvSaveMapObjectsButton:disabled { background:#eef2f7; border-color:#e3e9f0; color:#a5b1bf; }" + "QLabel#agvMapEditorStatus { font-size:11px; color:#8593a6; padding:2px 0; }")); + auto *layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(5); + auto *actions = new QHBoxLayout; + actions->setSpacing(6); + m_browseButton = new QPushButton(QStringLiteral("浏览"), this); + m_stationButton = new QPushButton(QStringLiteral("新增站点"), this); + m_routeButton = new QPushButton(QStringLiteral("新增路线"), this); + m_coordinatesButton = new QPushButton(QStringLiteral("坐标新增"), this); + m_manageButton = new QPushButton(QStringLiteral("站点与路线"), this); + m_saveButton = new QPushButton(QStringLiteral("保存到 AGV"), this); + m_undoButton = new QPushButton(QStringLiteral("撤销修改"), this); + m_stationButton->setObjectName(QStringLiteral("agvAddStationButton")); + m_routeButton->setObjectName(QStringLiteral("agvAddRouteButton")); + m_coordinatesButton->setObjectName(QStringLiteral("agvCoordinateStationButton")); + m_manageButton->setObjectName(QStringLiteral("agvManageMapObjectsButton")); + m_saveButton->setObjectName(QStringLiteral("agvSaveMapObjectsButton")); + m_undoButton->setObjectName(QStringLiteral("agvUndoMapObjectsButton")); + const QColor toolColor(QStringLiteral("#657b96")); + const QColor activeColor(QStringLiteral("#236ddb")); + m_browseButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/move.svg"), toolColor, activeColor)); + m_stationButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/plus.svg"), toolColor, activeColor)); + m_routeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/edit-3.svg"), toolColor, activeColor)); + m_manageButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/scroll-text.svg"), toolColor, activeColor)); + m_undoButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/undo-2.svg"), toolColor, activeColor)); + m_saveButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/check.svg"), QColor(Qt::white), QColor(Qt::white))); + auto *modes = new QButtonGroup(this); + for (QPushButton *button : {m_browseButton, m_stationButton, m_routeButton}) { + button->setCheckable(true); + modes->addButton(button); + } + m_browseButton->setChecked(true); + for (QPushButton *button : {m_browseButton, m_stationButton, m_routeButton, + m_coordinatesButton, m_manageButton}) { + button->setMinimumHeight(30); + actions->addWidget(button); + } + actions->addStretch(); + actions->addWidget(m_undoButton); + actions->addWidget(m_saveButton); + layout->addLayout(actions); + m_status = new QLabel(QStringLiteral("新增站点或连接两个站点后,保存到 AGV 地图"), this); + m_status->setObjectName(QStringLiteral("agvMapEditorStatus")); + m_status->setWordWrap(true); + layout->addWidget(m_status); + connect(m_browseButton, &QPushButton::clicked, this, [this]() { resetMode(); }); + connect(m_stationButton, &QPushButton::clicked, this, [this]() { begin(PickStation); }); + connect(m_routeButton, &QPushButton::clicked, this, [this]() { begin(PickRoute); }); + connect(m_coordinatesButton, &QPushButton::clicked, this, + [this]() { begin(CoordinateStation); }); + connect(m_manageButton, &QPushButton::clicked, this, [this]() { begin(Manage); }); + connect(m_saveButton, &QPushButton::clicked, this, &AgvMapEditorWidget::save); + connect(m_undoButton, &QPushButton::clicked, this, &AgvMapEditorWidget::undo); + connect(m_view, &AgvMapViewWidget::mapPointSelected, this, [this](double x, double y) { + if (!m_busy && prepareContext() && m_stationButton->isChecked()) + showStationDialog(x, y); + }); + connect(m_view, &AgvMapViewWidget::stationSelected, this, [this](const QString &id) { + if (m_busy || !prepareContext() || !m_routeButton->isChecked()) + return; + if (m_routeStart.isEmpty()) { + m_routeStart = id; + m_view->setSelectedStation(id); + setMessage(QStringLiteral("起点:%1;请点击终点站点").arg(id)); + } else if (id != m_routeStart) { + showRouteDialog(m_routeStart, id); + m_routeStart.clear(); + m_view->setSelectedStation(QString()); + setMessage(QStringLiteral("请点击下一条路线的起点,或保存新增内容")); + } + }); + connect(m_client, &RobotClient::agvMapContentReceived, + this, &AgvMapEditorWidget::receiveMap); + connect(m_client, &RobotClient::agvMapSaveFinished, + this, &AgvMapEditorWidget::receiveSave); + updateButtons(); +} + +void AgvMapEditorWidget::setContextProvider(std::function provider) +{ + m_contextProvider = std::move(provider); + refreshContext(); +} + +void AgvMapEditorWidget::setAutoLoadEnabled(bool enabled) +{ + if (m_autoLoadEnabled == enabled) + return; + m_autoLoadEnabled = enabled; + refreshContext(); +} + +AgvMapEditorWidget::Context AgvMapEditorWidget::context() const +{ + return m_contextProvider ? m_contextProvider() : Context(); +} + +void AgvMapEditorWidget::refreshContext() +{ + const Context current = context(); + if (!current.connected) { + m_autoLoadAttemptedKeys.clear(); + if (m_autoLoadEnabled && !m_document.isDirty()) { + m_document.clear(); + m_loadedKey.clear(); + m_history.clear(); + } + } + if (m_busy && (!current.connected || current.key() != m_requestContext.key())) { + ++m_requestId; + m_pendingAction = NoAction; + m_reloadingForSave = false; + m_verifyingSave = false; + ++m_saveVerificationGeneration; + setBusy(false); + setMessage(QStringLiteral("连接或地图已变化,请重新加载地图"), true); + } + if (current.connected && mapReady() && current.key() != m_loadedKey) { + // Keep only unsaved work per map. Clean maps are downloaded again on a revisit. + if (!m_loadedKey.isEmpty() && m_document.isDirty()) + m_mapDrafts.insert(m_loadedKey, Draft{m_document, m_history}); + m_document.clear(); + m_history.clear(); + m_loadedKey.clear(); + m_sceneKey.clear(); + const auto draft = m_mapDrafts.find(current.key()); + if (draft != m_mapDrafts.end()) { + m_document = draft->document; + m_history = draft->history; + m_loadedKey = current.key(); + m_mapDrafts.erase(draft); + setMessage(QStringLiteral("已恢复本地图未保存的修改,可继续编辑或保存")); + } + } + if (current.key() != m_loadedKey || !current.connected || !mapReady()) { + resetMode(); + m_view->setEditorObjects({}, {}); + m_sceneKey.clear(); + if (m_document.isDirty() && current.key() != m_loadedKey) + setMessage(QStringLiteral("上一张地图有未保存的修改;返回原地图可继续保存")); + else if (!current.connected || !mapReady()) + setMessage(current.connected + ? QStringLiteral("等待当前设备的地图加载…") + : QStringLiteral("连接设备后加载地图")); + } else if (m_sceneKey != m_loadedKey) { + updateScene(); + } + updateButtons(); + const QString currentKey = current.key(); + QPointF worldCenter; + if (m_autoLoadEnabled && current.connected && !current.deviceId.isEmpty() + && !current.mapName.isEmpty() && !m_busy && !m_document.isDirty() + && currentKey != m_loadedKey && !m_autoLoadAttemptedKeys.contains(currentKey) + && m_view->mapId() == current.mapName + && m_view->widgetToWorld(QPointF(m_view->rect().center()), &worldCenter)) { + // Failed or canceled attempts stay recorded for this connection. + // Successful loads rely on m_loadedKey; explicit actions still retry. + m_autoLoadAttemptedKeys.insert(currentKey); + begin(NoAction); + } +} + +void AgvMapEditorWidget::reloadCleanMap() +{ + if (m_busy || m_document.isDirty()) + return; + m_document.clear(); + m_history.clear(); + m_loadedKey.clear(); + m_sceneKey.clear(); + m_autoLoadAttemptedKeys.remove(context().key()); + refreshContext(); +} + +bool AgvMapEditorWidget::mapReady() const +{ + const Context current = context(); + QPointF world; + return !current.mapName.isEmpty() && m_view->mapId() == current.mapName + && m_view->widgetToWorld(QPointF(m_view->rect().center()), &world); +} + +bool AgvMapEditorWidget::prepareContext() +{ + const Context current = context(); + if (!current.connected || current.deviceId.isEmpty() || current.mapName.isEmpty()) { + setMessage(QStringLiteral("请连接 AGV 并加载要编辑的地图"), true); + resetMode(); + return false; + } + if (!m_view->mapId().isEmpty() && m_view->mapId() != current.mapName) { + setMessage(QStringLiteral("请先点击“加载地图”,使实时地图与所选地图一致"), true); + resetMode(); + return false; + } + return true; +} + +void AgvMapEditorWidget::begin(Action action) +{ + if (m_busy || !prepareContext()) + return; + const Context current = context(); + if (current.key() != m_loadedKey) { + if (m_document.isDirty() + && QMessageBox::question(this, QStringLiteral("切换编辑地图"), + QStringLiteral("上一张地图的修改尚未保存。放弃这些修改并读取当前地图?"), + QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel) + != QMessageBox::Discard) { + resetMode(); + return; + } + m_document.clear(); + m_history.clear(); + m_loadedKey.clear(); + m_requestContext = current; + m_pendingAction = action; + m_reloadingForSave = false; + setBusy(true); + setMessage(QStringLiteral("正在读取 %1 的完整地图…").arg(current.mapName)); + m_client->requestAgvMapContent(++m_requestId, current.deviceId, current.mapName); + return; + } + perform(action); +} + +void AgvMapEditorWidget::perform(Action action) +{ + if (action == PickStation) { + m_stationButton->setChecked(true); + m_routeStart.clear(); + m_view->setSelectedStation(QString()); + m_view->setEditMode(AgvMapViewWidget::AddStationMode); + setMessage(QStringLiteral("点击地图放置站点;拖动仍可平移,也可以使用“坐标新增”")); + } else if (action == PickRoute) { + if (m_document.stationIds().size() < 2) { + resetMode(); + setMessage(QStringLiteral("请先新增站点,路线至少需要两个不同站点"), true); + return; + } + m_routeButton->setChecked(true); + m_routeStart.clear(); + m_view->setSelectedStation(QString()); + m_view->setEditMode(AgvMapViewWidget::AddRouteMode); + setMessage(QStringLiteral("依次点击起点和终点站点;也可在“站点与路线”中选择端点")); + } else if (action == CoordinateStation) { + resetMode(); + const QVariantMap pose = context().pose; + showStationDialog(pose.value(QStringLiteral("x")).toDouble(), + pose.value(QStringLiteral("y")).toDouble()); + } else if (action == Manage) { + resetMode(); + showManager(); + } +} + +void AgvMapEditorWidget::showStationDialog(double x, double y) +{ + QDialog dialog(this); + dialog.setObjectName(QStringLiteral("agvStationDialog")); + dialog.setWindowTitle(QStringLiteral("新增 AGV 站点")); + const QString dialogMapKey = m_loadedKey; + auto *form = new QFormLayout(&dialog); + auto *name = new QLineEdit(&dialog); + name->setObjectName(QStringLiteral("agvNewStationId")); + name->setText(m_document.nextAvailableStationId()); + auto *displayName = new QLineEdit(&dialog); + displayName->setObjectName(QStringLiteral("agvNewStationName")); + displayName->setPlaceholderText(QStringLiteral("例如:上料点、等待点、充电点")); + displayName->setMaxLength(80); + auto *xSpin = new QDoubleSpinBox(&dialog); + auto *ySpin = new QDoubleSpinBox(&dialog); + auto *heading = new QDoubleSpinBox(&dialog); + xSpin->setObjectName(QStringLiteral("agvNewStationX")); + ySpin->setObjectName(QStringLiteral("agvNewStationY")); + heading->setObjectName(QStringLiteral("agvNewStationHeading")); + for (auto *spin : {xSpin, ySpin}) { + spin->setRange(-1000000.0, 1000000.0); + spin->setDecimals(4); + spin->setSuffix(QStringLiteral(" m")); + } + xSpin->setValue(x); + ySpin->setValue(y); + heading->setRange(-180.0, 180.0); + heading->setDecimals(2); + heading->setSuffix(QStringLiteral("°")); + heading->setValue(qRadiansToDegrees(context().pose.value(QStringLiteral("theta")).toDouble())); + form->addRow(QStringLiteral("站点 ID"), name); + form->addRow(QStringLiteral("站点名称"), displayName); + form->addRow(QStringLiteral("地图 X"), xSpin); + form->addRow(QStringLiteral("地图 Y"), ySpin); + form->addRow(QStringLiteral("航向"), heading); + auto *capture = new QPushButton(QStringLiteral("使用 AGV 当前位姿"), &dialog); + capture->setEnabled(context().pose.value(QStringLiteral("localized")).toBool()); + connect(capture, &QPushButton::clicked, &dialog, [this, xSpin, ySpin, heading]() { + const QVariantMap pose = context().pose; + if (!pose.value(QStringLiteral("localized")).toBool()) + return; + xSpin->setValue(pose.value(QStringLiteral("x")).toDouble()); + ySpin->setValue(pose.value(QStringLiteral("y")).toDouble()); + heading->setValue(qRadiansToDegrees(pose.value(QStringLiteral("theta")).toDouble())); + }); + form->addRow(capture); + auto *errorLabel = new QLabel(&dialog); + errorLabel->setStyleSheet(QStringLiteral("color:#c63e3e")); + errorLabel->setWordWrap(true); + form->addRow(errorLabel); + auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); + buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("新增")); + connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + connect(buttons, &QDialogButtonBox::accepted, &dialog, + [this, &dialog, dialogMapKey, name, displayName, xSpin, ySpin, heading, errorLabel]() { + if (!prepareContext() || context().key() != dialogMapKey || m_loadedKey != dialogMapKey) { + errorLabel->setText(QStringLiteral("地图或连接已变化,请关闭窗口重新加载")); + return; + } + QString error; + const AgvMapDocument before = m_document; + if (!m_document.addStation(name->text().trimmed(), xSpin->value(), ySpin->value(), + qDegreesToRadians(heading->value()), &error, displayName->text().trimmed())) { + errorLabel->setText(error); + return; + } + m_history.append(before); + updateScene(); + setMessage(QStringLiteral("站点 %1 已新增;点击“保存到 AGV”写入地图") + .arg(displayName->text().trimmed().isEmpty() ? name->text().trimmed() : displayName->text().trimmed())); + dialog.accept(); + }); + form->addRow(buttons); + dialog.exec(); +} + +void AgvMapEditorWidget::showRouteDialog(const QString &source, const QString &target) +{ + if (m_document.stationIds().size() < 2) { + setMessage(QStringLiteral("路线至少需要两个不同站点"), true); + return; + } + QDialog dialog(this); + dialog.setObjectName(QStringLiteral("agvRouteDialog")); + dialog.setWindowTitle(QStringLiteral("新增 AGV 路线")); + const QString dialogMapKey = m_loadedKey; + auto *form = new QFormLayout(&dialog); + auto *name = new QLineEdit(&dialog); + auto *from = new QComboBox(&dialog); + auto *to = new QComboBox(&dialog); + auto *both = new QCheckBox(QStringLiteral("双向通行,同时新增反向路线"), &dialog); + name->setObjectName(QStringLiteral("agvNewRouteId")); + from->setObjectName(QStringLiteral("agvNewRouteSource")); + to->setObjectName(QStringLiteral("agvNewRouteTarget")); + both->setObjectName(QStringLiteral("agvNewRouteBidirectional")); + const QStringList ids = m_document.stationIds(); + for (const QVariant &value : m_document.stations()) { + const QVariantMap station = value.toMap(); + const QString id = station.value(QStringLiteral("id")).toString(); + const QString label = station.value(QStringLiteral("name"), id).toString(); + const QString text = label == id ? id : label + QStringLiteral(" (%1)").arg(id); + from->addItem(text, id); + to->addItem(text, id); + } + from->setCurrentIndex(from->findData(source.isEmpty() ? ids.first() : source)); + to->setCurrentIndex(to->findData(target.isEmpty() ? ids.at(1) : target)); + const auto updateName = [name, from, to]() { + name->setText(from->currentData().toString() + QLatin1Char('_') + to->currentData().toString()); + }; + updateName(); + connect(from, &QComboBox::currentTextChanged, &dialog, updateName); + connect(to, &QComboBox::currentTextChanged, &dialog, updateName); + form->addRow(QStringLiteral("路线 ID"), name); + form->addRow(QStringLiteral("起点站点"), from); + form->addRow(QStringLiteral("终点站点"), to); + form->addRow(both); + auto *hint = new QLabel(QStringLiteral("路线连接两个站点,新增后需保存到 AGV 地图。"), &dialog); + hint->setWordWrap(true); + form->addRow(hint); + auto *errorLabel = new QLabel(&dialog); + errorLabel->setStyleSheet(QStringLiteral("color:#c63e3e")); + errorLabel->setWordWrap(true); + form->addRow(errorLabel); + auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); + buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("新增")); + connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + connect(buttons, &QDialogButtonBox::accepted, &dialog, + [this, &dialog, dialogMapKey, name, from, to, both, errorLabel]() { + if (!prepareContext() || context().key() != dialogMapKey || m_loadedKey != dialogMapKey) { + errorLabel->setText(QStringLiteral("地图或连接已变化,请关闭窗口重新加载")); + return; + } + QString error; + const AgvMapDocument before = m_document; + if (!m_document.addRoute(name->text().trimmed(), from->currentData().toString(), + to->currentData().toString(), both->isChecked(), &error)) { + errorLabel->setText(error); + return; + } + m_history.append(before); + updateScene(); + setMessage(QStringLiteral("路线 %1 已新增;点击“保存到 AGV”写入地图").arg(name->text().trimmed())); + dialog.accept(); + }); + form->addRow(buttons); + dialog.exec(); +} + +void AgvMapEditorWidget::showManager() +{ + QDialog dialog(this); + dialog.setObjectName(QStringLiteral("agvMapObjectsDialog")); + dialog.setWindowTitle(QStringLiteral("AGV 站点与路线")); + dialog.resize(860, 480); + const QString dialogMapKey = m_loadedKey; + auto *layout = new QVBoxLayout(&dialog); + auto *tabs = new QTabWidget(&dialog); + tabs->setObjectName(QStringLiteral("agvMapObjectsTabs")); + auto *stations = new QTableWidget(tabs); + auto *routes = new QTableWidget(tabs); + stations->setObjectName(QStringLiteral("agvMapStationsTable")); + routes->setObjectName(QStringLiteral("agvMapRoutesTable")); + stations->setColumnCount(6); + stations->setHorizontalHeaderLabels({QStringLiteral("站点 ID"), QStringLiteral("名称"), QStringLiteral("X / m"), + QStringLiteral("Y / m"), QStringLiteral("航向 / °"), QStringLiteral("状态")}); + routes->setColumnCount(4); + routes->setHorizontalHeaderLabels({QStringLiteral("路线 ID"), QStringLiteral("起点"), + QStringLiteral("终点"), QStringLiteral("状态")}); + for (auto *table : {stations, routes}) { + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + table->setSelectionBehavior(QAbstractItemView::SelectRows); + table->setSelectionMode(QAbstractItemView::SingleSelection); + table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + table->verticalHeader()->hide(); + } + auto *stationPage = new QWidget(tabs); + auto *stationLayout = new QVBoxLayout(stationPage); + stationLayout->setContentsMargins(0, 0, 0, 0); + stationLayout->addWidget(stations); + auto *routePage = new QWidget(tabs); + auto *routeLayout = new QVBoxLayout(routePage); + routeLayout->setContentsMargins(0, 0, 0, 0); + routeLayout->addWidget(routes); + auto *routeHint = new QLabel(QStringLiteral("每行是一条有向路线;双向路线分为两行,删除只影响所选方向。"), routePage); + routeHint->setWordWrap(true); + routeLayout->addWidget(routeHint); + tabs->addTab(stationPage, QStringLiteral("站点")); + tabs->addTab(routePage, QStringLiteral("路线")); + layout->addWidget(tabs); + const auto selectedId = [](QTableWidget *table) { + return table->currentRow() >= 0 && table->item(table->currentRow(), 0) + ? table->item(table->currentRow(), 0)->text() : QString(); + }; + const auto refresh = [this, stations, routes, selectedId]() { + const QString selectedStation = selectedId(stations); + const QString selectedRoute = selectedId(routes); + const QVariantList points = m_document.stations(); + stations->setRowCount(points.size()); + for (int i = 0; i < points.size(); ++i) { + const QVariantMap point = points.at(i).toMap(); + const QStringList values = {point.value(QStringLiteral("id")).toString(), + point.value(QStringLiteral("name")).toString(), + QString::number(point.value(QStringLiteral("x")).toDouble(), 'f', 4), + QString::number(point.value(QStringLiteral("y")).toDouble(), 'f', 4), + QString::number(qRadiansToDegrees(point.value(QStringLiteral("theta")).toDouble()), 'f', 2), + point.value(QStringLiteral("draft")).toBool() || point.value(QStringLiteral("nameChanged")).toBool() + ? QStringLiteral("待保存") : QStringLiteral("已保存")}; + for (int c = 0; c < values.size(); ++c) + stations->setItem(i, c, new QTableWidgetItem(values.at(c))); + } + const QVariantList paths = m_document.routes(); + routes->setRowCount(paths.size()); + for (int i = 0; i < paths.size(); ++i) { + const QVariantMap path = paths.at(i).toMap(); + const QStringList values = {path.value(QStringLiteral("id")).toString(), + path.value(QStringLiteral("sourceStation")).toString(), + path.value(QStringLiteral("targetStation")).toString(), + path.value(QStringLiteral("draft")).toBool() ? QStringLiteral("待保存") : QStringLiteral("已保存")}; + for (int c = 0; c < values.size(); ++c) + routes->setItem(i, c, new QTableWidgetItem(values.at(c))); + } + for (auto *table : {stations, routes}) { + const QString id = table == stations ? selectedStation : selectedRoute; + table->clearSelection(); + table->setCurrentItem(nullptr); + for (int row = 0; row < table->rowCount(); ++row) { + if (table->item(row, 0)->text() == id) { + table->setCurrentCell(row, 0); + break; + } + } + } + }; + refresh(); + auto *actions = new QHBoxLayout; + auto *addStation = new QPushButton(QStringLiteral("坐标新增站点"), &dialog); + auto *addRoute = new QPushButton(QStringLiteral("新增路线"), &dialog); + addRoute->setObjectName(QStringLiteral("agvDialogAddRouteButton")); + auto *renameStation = new QPushButton(QStringLiteral("修改站点名称"), &dialog); + renameStation->setObjectName(QStringLiteral("agvRenameStationButton")); + auto *undoButton = new QPushButton(QStringLiteral("撤销修改"), &dialog); + undoButton->setObjectName(QStringLiteral("agvManagerUndoButton")); + auto *deleteStation = new QPushButton(QStringLiteral("删除站点"), &dialog); + deleteStation->setObjectName(QStringLiteral("agvDeleteStationButton")); + auto *deleteRoute = new QPushButton(QStringLiteral("删除路线"), &dialog); + deleteRoute->setObjectName(QStringLiteral("agvDeleteRouteButton")); + auto *stationActions = new QHBoxLayout; + for (auto *button : {addStation, renameStation, deleteStation}) + stationActions->addWidget(button); + stationActions->addStretch(); + stationLayout->addLayout(stationActions); + auto *routeActions = new QHBoxLayout; + routeActions->addWidget(addRoute); + routeActions->addWidget(deleteRoute); + routeActions->addStretch(); + routeLayout->addLayout(routeActions); + auto *draftHint = new QLabel(QStringLiteral("删除和改名先保留为本地修改;关闭窗口后点击“保存到 AGV”才写入车辆,可撤销。"), &dialog); + draftHint->setWordWrap(true); + layout->addWidget(draftHint); + auto *close = new QPushButton(QStringLiteral("关闭"), &dialog); + actions->addWidget(undoButton); + actions->addStretch(); + actions->addWidget(close); + layout->addLayout(actions); + const auto canEdit = [this, dialogMapKey]() { + const Context current = context(); + return current.connected && !current.deviceId.isEmpty() && !m_busy + && mapReady() && current.key() == dialogMapKey && m_loadedKey == dialogMapKey; + }; + const auto updateActions = [this, stations, routes, addStation, addRoute, + renameStation, deleteStation, deleteRoute, undoButton, + canEdit, selectedId]() { + const bool available = canEdit(); + addStation->setEnabled(available); + addRoute->setEnabled(available); + renameStation->setEnabled(available && !selectedId(stations).isEmpty()); + deleteStation->setEnabled(available && !selectedId(stations).isEmpty()); + deleteRoute->setEnabled(available && !selectedId(routes).isEmpty()); + undoButton->setEnabled(available && !m_history.isEmpty()); + stations->setEnabled(available); + routes->setEnabled(available); + }; + connect(stations, &QTableWidget::itemSelectionChanged, &dialog, updateActions); + connect(routes, &QTableWidget::itemSelectionChanged, &dialog, updateActions); + QTimer contextTimer(&dialog); + contextTimer.setInterval(100); + connect(&contextTimer, &QTimer::timeout, &dialog, updateActions); + contextTimer.start(); + updateActions(); + connect(addStation, &QPushButton::clicked, &dialog, [this, canEdit, refresh, updateActions]() { + if (!canEdit()) + return; + const QVariantMap pose = context().pose; + showStationDialog(pose.value(QStringLiteral("x")).toDouble(), pose.value(QStringLiteral("y")).toDouble()); + refresh(); + updateActions(); + }); + connect(addRoute, &QPushButton::clicked, &dialog, [this, canEdit, refresh, updateActions]() { + if (!canEdit()) + return; + showRouteDialog(); refresh(); updateActions(); + }); + connect(renameStation, &QPushButton::clicked, &dialog, [this, stations, canEdit, refresh, updateActions]() { + if (!canEdit()) + return; + const int row = stations->currentRow(); + if (row < 0 || !stations->item(row, 0)) + return; + showStationNameDialog(stations->item(row, 0)->text()); + refresh(); + updateActions(); + }); + const auto confirmDelete = [this, &dialog, canEdit](bool station, + const QString &id, const QStringList &connectedRoutes) { + if (!canEdit()) + return false; + const QString before = m_document.content(); + QString routeList = connectedRoutes.mid(0, 8).join(QStringLiteral("\n")); + if (connectedRoutes.size() > 8) + routeList += QStringLiteral("\n其余 %1 条可展开详细信息查看。") + .arg(connectedRoutes.size() - 8); + const QString text = station + ? (connectedRoutes.isEmpty() + ? QStringLiteral("删除站点 %1?该站点没有关联路线。").arg(id) + : QStringLiteral("删除站点 %1,并一起删除 %2 条关联有向路线?\n%3") + .arg(id).arg(connectedRoutes.size()).arg(routeList)) + : QStringLiteral("删除有向路线 %1?\n只删除所选方向;反向路线和站点保留。").arg(id); + QMessageBox confirmation(QMessageBox::Warning, + station ? QStringLiteral("删除站点") : QStringLiteral("删除路线"), text, + QMessageBox::Yes | QMessageBox::Cancel, &dialog); + confirmation.setObjectName(station ? QStringLiteral("agvDeleteStationConfirmDialog") + : QStringLiteral("agvDeleteRouteConfirmDialog")); + if (connectedRoutes.size() > 8) + confirmation.setDetailedText(connectedRoutes.join(QStringLiteral("\n"))); + auto *accept = confirmation.button(QMessageBox::Yes); + accept->setObjectName(station ? QStringLiteral("agvDeleteStationConfirmButton") + : QStringLiteral("agvDeleteRouteConfirmButton")); + accept->setText(station && !connectedRoutes.isEmpty() + ? QStringLiteral("删除站点及关联路线") : QStringLiteral("删除")); + confirmation.button(QMessageBox::Cancel)->setObjectName(QStringLiteral("agvDeleteCancelButton")); + confirmation.button(QMessageBox::Cancel)->setText(QStringLiteral("取消")); + confirmation.setDefaultButton(QMessageBox::Cancel); + bool contextUnchanged = true; + QTimer confirmationTimer(&confirmation); + confirmationTimer.setInterval(50); + connect(&confirmationTimer, &QTimer::timeout, &confirmation, + [this, &confirmation, &contextUnchanged, before, canEdit, accept]() { + contextUnchanged = contextUnchanged && canEdit() && m_document.content() == before; + accept->setEnabled(contextUnchanged); + if (!contextUnchanged) + confirmation.setInformativeText(QStringLiteral("连接、地图或编辑内容已变化,未执行删除。请取消后重新打开。")); + }); + confirmationTimer.start(); + const bool accepted = confirmation.exec() == QMessageBox::Yes; + if (!accepted) + return false; + if (!contextUnchanged || !canEdit() || m_document.content() != before) { + setMessage(QStringLiteral("连接、地图或编辑内容已变化,未执行删除"), true); + return false; + } + return true; + }; + connect(deleteStation, &QPushButton::clicked, &dialog, + [this, stations, canEdit, selectedId, confirmDelete, refresh, updateActions]() { + const QString id = selectedId(stations); + if (!canEdit() || id.isEmpty() || !m_document.hasStation(id)) + return; + const QStringList paths = m_document.connectedRouteIds(id); + if (!confirmDelete(true, id, paths) || !canEdit()) { + updateActions(); + return; + } + const AgvMapDocument before = m_document; + QString error; + if (!m_document.removeStation(id, true, &error)) { + setMessage(error, true); + return; + } + m_history.append(before); + resetMode(); + updateScene(); + setMessage(QStringLiteral("已删除站点 %1 和 %2 条关联路线;可撤销,点击“保存到 AGV”后生效") + .arg(id).arg(paths.size())); + refresh(); + updateActions(); + }); + connect(deleteRoute, &QPushButton::clicked, &dialog, + [this, routes, canEdit, selectedId, confirmDelete, refresh, updateActions]() { + const QString id = selectedId(routes); + if (!canEdit() || id.isEmpty() || !confirmDelete(false, id, {}) || !canEdit()) { + updateActions(); + return; + } + const AgvMapDocument before = m_document; + QString error; + if (!m_document.removeRoute(id, &error)) { + setMessage(error, true); + return; + } + m_history.append(before); + resetMode(); + updateScene(); + setMessage(QStringLiteral("已删除有向路线 %1;可撤销,点击“保存到 AGV”后生效").arg(id)); + refresh(); + updateActions(); + }); + connect(undoButton, &QPushButton::clicked, &dialog, [this, canEdit, refresh, updateActions]() { + if (!canEdit()) + return; + undo(); refresh(); updateActions(); + }); + connect(close, &QPushButton::clicked, &dialog, &QDialog::accept); + dialog.exec(); +} + +void AgvMapEditorWidget::showStationNameDialog(const QString &id) +{ + QDialog dialog(this); + dialog.setObjectName(QStringLiteral("agvStationNameDialog")); + dialog.setWindowTitle(QStringLiteral("修改站点名称")); + const QString dialogMapKey = m_loadedKey; + auto *form = new QFormLayout(&dialog); + auto *name = new QLineEdit(&dialog); + name->setObjectName(QStringLiteral("agvStationName")); + name->setMaxLength(80); + for (const QVariant &value : m_document.stations()) { + const QVariantMap station = value.toMap(); + if (station.value(QStringLiteral("id")).toString() == id) { + name->setText(station.value(QStringLiteral("name")).toString()); + break; + } + } + form->addRow(QStringLiteral("站点 ID"), new QLabel(id, &dialog)); + form->addRow(QStringLiteral("名称"), name); + auto *errorLabel = new QLabel(&dialog); + errorLabel->setStyleSheet(QStringLiteral("color:#c63e3e")); + errorLabel->setWordWrap(true); + form->addRow(errorLabel); + auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); + buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("确定")); + connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + connect(buttons, &QDialogButtonBox::accepted, &dialog, + [this, &dialog, id, dialogMapKey, name, errorLabel]() { + if (!prepareContext() || context().key() != dialogMapKey || m_loadedKey != dialogMapKey) { + errorLabel->setText(QStringLiteral("地图或连接已变化,请关闭窗口重新加载")); + return; + } + const AgvMapDocument before = m_document; + const QString originalContent = m_document.content(); + QString error; + if (!m_document.setStationName(id, name->text().trimmed(), &error)) { + errorLabel->setText(error); + return; + } + if (originalContent != m_document.content()) + m_history.append(before); + updateScene(); + setMessage(QStringLiteral("站点名称已修改,点击“保存到 AGV”写入地图")); + dialog.accept(); + }); + form->addRow(buttons); + dialog.exec(); +} + +void AgvMapEditorWidget::save() +{ + if (m_busy || !m_document.isDirty() || !prepareContext() || context().key() != m_loadedKey) + return; + QString error; + if (!m_document.validateStationIds(&error)) { + setMessage(error, true); + return; + } + resetMode(); + m_requestContext = context(); + m_reloadingForSave = true; + m_verifyingSave = false; + m_saveCandidate.clear(); + setBusy(true); + setMessage(QStringLiteral("正在读取最新地图并保存到 %1…").arg(m_requestContext.mapName)); + m_client->requestAgvMapContent(++m_requestId, m_requestContext.deviceId, + m_requestContext.mapName); +} + +void AgvMapEditorWidget::undo() +{ + if (m_busy || !mapReady() || m_history.isEmpty() || context().key() != m_loadedKey) + return; + m_document = m_history.takeLast(); + resetMode(); + updateScene(); + setMessage(QStringLiteral("已撤销最后一次修改")); +} + +void AgvMapEditorWidget::resetMode() +{ + m_browseButton->setChecked(true); + m_routeStart.clear(); + m_view->setSelectedStation(QString()); + m_view->setEditMode(AgvMapViewWidget::BrowseMode); +} + +void AgvMapEditorWidget::updateScene() +{ + if (context().key() == m_loadedKey && mapReady()) { + m_view->setEditorObjects(m_document.stations(), m_document.routes(), true); + m_sceneKey = m_loadedKey; + } + updateButtons(); +} + +void AgvMapEditorWidget::updateButtons() +{ + const Context current = context(); + const bool available = current.connected && !current.deviceId.isEmpty() + && mapReady() && !m_busy; + for (auto *button : {m_stationButton, m_routeButton, m_coordinatesButton, m_manageButton}) + button->setEnabled(available); + const bool sameMap = current.key() == m_loadedKey; + m_saveButton->setEnabled(available && sameMap && m_document.isDirty()); + m_undoButton->setEnabled(available && sameMap && !m_history.isEmpty()); +} + +void AgvMapEditorWidget::setBusy(bool busy) +{ + if (m_busy == busy) + return; + m_busy = busy; + if (busy) + resetMode(); + updateButtons(); + emit busyChanged(busy); +} + +void AgvMapEditorWidget::setMessage(const QString &message, bool error) +{ + const QString mapName = context().mapName; + m_status->setText(mapName.isEmpty() ? message : mapName + QStringLiteral(" · ") + message); + m_status->setStyleSheet(error ? QStringLiteral("color:#c63e3e") : QStringLiteral("color:#66727d")); +} + +void AgvMapEditorWidget::receiveMap(quint64 requestId, const QString &deviceId, + const QString &mapName, const QString &content, + bool success, const QString &detail) +{ + if (!m_busy || requestId != m_requestId || deviceId != m_requestContext.deviceId + || mapName != m_requestContext.mapName) + return; + const Action action = m_pendingAction; + m_pendingAction = NoAction; + const bool preparingSave = m_reloadingForSave; + m_reloadingForSave = false; + if (context().key() != m_requestContext.key() || !context().connected) { + m_verifyingSave = false; + setBusy(false); + setMessage(QStringLiteral("地图或连接已变化,请重新加载"), true); + return; + } + if (m_verifyingSave) { + // Consume this read response before scheduling a retry. Duplicate replies + // must not create more than one verification request per attempt. + ++m_requestId; + AgvMapDocument readback; + QString error; + const bool correctMap = mapNameMatches(content, mapName); + if (success && !correctMap) + error = QStringLiteral("读回地图的 header 名称与目标地图不一致"); + const bool confirmed = success && correctMap && readback.load(content, &error) + && verifySavedEdits(readback, &error); + if (confirmed) { + m_verifyingSave = false; + ++m_saveVerificationGeneration; + m_document = readback; + m_history.clear(); + setBusy(false); + updateScene(); + setMessage(context().demo ? QStringLiteral("Demo 地图已保存并读回确认") + : QStringLiteral("站点和路线已保存到 AGV,并已读回核对")); + emit mapSaved(); + return; + } + if (m_saveVerificationAttempts >= kSaveVerificationAttempts + || m_saveVerificationClock.elapsed() >= kSaveVerificationTimeoutMs) { + failSaveVerification(success ? error : detail); + return; + } + const quint64 generation = m_saveVerificationGeneration; + QTimer::singleShot(kSaveVerificationIntervalMs, this, [this, generation]() { + if (m_verifyingSave && m_busy && generation == m_saveVerificationGeneration) + requestSaveVerification(); + }); + return; + } + if (preparingSave) { + AgvMapDocument latest; + QString error; + const bool correctMap = mapNameMatches(content, mapName); + if (success && !correctMap) + error = QStringLiteral("最新地图的 header 名称与目标地图不一致,已取消上传"); + bool merged = success && correctMap && latest.load(content, &error); + if (merged) + merged = m_document.mergeRemovalsInto(&latest, &error); + if (merged) { + for (const QVariant &value : m_document.stations()) { + const QVariantMap station = value.toMap(); + if (!station.value(QStringLiteral("draft")).toBool()) + continue; + const QString id = station.value(QStringLiteral("id")).toString(); + const QVariantMap existing = objectWithId(latest.stations(), id); + if (!existing.isEmpty()) { + merged = sameStation(existing, station); + if (!merged) + error = QStringLiteral("站点 %1 已存在且内容不同;本地修改仍保留").arg(id); + if (!merged) + break; + continue; + } + merged = latest.addStation(station.value(QStringLiteral("id")).toString(), + station.value(QStringLiteral("x")).toDouble(), + station.value(QStringLiteral("y")).toDouble(), + station.value(QStringLiteral("theta")).toDouble(), &error, + station.value(QStringLiteral("description")).toString()); + if (!merged) + break; + } + } + if (merged) { + for (const QVariant &value : m_document.stations()) { + const QVariantMap station = value.toMap(); + if (station.value(QStringLiteral("draft")).toBool() + || !station.value(QStringLiteral("nameChanged")).toBool()) + continue; + const QString id = station.value(QStringLiteral("id")).toString(); + QVariantMap currentStation; + for (const QVariant &candidate : latest.stations()) { + if (candidate.toMap().value(QStringLiteral("id")).toString() == id) { + currentStation = candidate.toMap(); + break; + } + } + if (currentStation.isEmpty() + || (currentStation.value(QStringLiteral("description")).toString() + != station.value(QStringLiteral("originalName")).toString() + && currentStation.value(QStringLiteral("description")).toString() + != station.value(QStringLiteral("description")).toString())) { + merged = false; + error = QStringLiteral("站点 %1 的名称已被其他操作修改,请重新确认;本地修改仍保留").arg(id); + break; + } + merged = latest.setStationName(id, station.value(QStringLiteral("description")).toString(), &error); + if (!merged) + break; + } + } + if (merged) { + for (const QVariant &value : m_document.routes()) { + const QVariantMap route = value.toMap(); + if (!route.value(QStringLiteral("draft")).toBool()) + continue; + const QString id = route.value(QStringLiteral("id")).toString(); + const QVariantMap existing = objectWithId(latest.routes(), id); + if (!existing.isEmpty()) { + merged = sameRoute(existing, route); + if (!merged) + error = QStringLiteral("路线 %1 已存在且内容不同;本地修改仍保留").arg(id); + if (!merged) + break; + continue; + } + merged = latest.addRoute(route.value(QStringLiteral("id")).toString(), + route.value(QStringLiteral("sourceStation")).toString(), + route.value(QStringLiteral("targetStation")).toString(), false, &error); + if (!merged) + break; + } + } + if (merged) + merged = latest.validateStationIds(&error); + if (!merged) { + setBusy(false); + setMessage(QStringLiteral("保存失败:%1;本地修改仍保留") + .arg(success ? error : detail), true); + return; + } + // An upload ACK must not consume the dirty edits or undo history. + m_saveCandidate = latest; + setMessage(QStringLiteral("正在上传 %1 的站点和路线…").arg(mapName)); + m_client->saveAgvMapContent(++m_requestId, deviceId, mapName, m_saveCandidate.content()); + return; + } + setBusy(false); + QString error; + if (!success || !m_document.load(content, &error)) { + resetMode(); + setMessage(success ? error : detail, true); + return; + } + m_loadedKey = m_requestContext.key(); + m_history.clear(); + m_autoLoadAttemptedKeys.remove(m_loadedKey); + updateScene(); + setMessage(QStringLiteral("地图已读取:%1 个站点,%2 条路线") + .arg(m_document.stations().size()).arg(m_document.routes().size())); + perform(action); +} + +void AgvMapEditorWidget::receiveSave(quint64 requestId, const QString &deviceId, + const QString &mapName, bool success, const QString &detail) +{ + if (!m_busy || requestId != m_requestId || deviceId != m_requestContext.deviceId + || mapName != m_requestContext.mapName) + return; + if (context().key() != m_requestContext.key() || !context().connected) { + setBusy(false); + setMessage(QStringLiteral("地图或连接已变化,请重新读取以确认保存结果"), true); + return; + } + if (!success) { + setBusy(false); + setMessage(QStringLiteral("保存失败:%1;本地修改仍保留,可重试") + .arg(detail), true); + return; + } + m_verifyingSave = true; + m_saveVerificationAttempts = 0; + m_saveVerificationClock.start(); + const quint64 generation = ++m_saveVerificationGeneration; + QTimer::singleShot(kSaveVerificationTimeoutMs, this, [this, generation]() { + if (m_verifyingSave && m_busy && generation == m_saveVerificationGeneration) + failSaveVerification(QStringLiteral("读回确认超时")); + }); + requestSaveVerification(); +} + +void AgvMapEditorWidget::requestSaveVerification() +{ + if (!m_verifyingSave || !m_busy) + return; + if (context().key() != m_requestContext.key() || !context().connected) { + failSaveVerification(QStringLiteral("连接或地图已变化")); + return; + } + ++m_saveVerificationAttempts; + setMessage(QStringLiteral("上传已接收,正在读回核对站点和路线(%1/%2)…") + .arg(m_saveVerificationAttempts).arg(kSaveVerificationAttempts)); + m_client->requestAgvMapContent(++m_requestId, m_requestContext.deviceId, + m_requestContext.mapName); +} + +void AgvMapEditorWidget::failSaveVerification(const QString &detail) +{ + m_verifyingSave = false; + ++m_saveVerificationGeneration; + ++m_requestId; + setBusy(false); + setMessage(QStringLiteral("上传已接收,但尚未确认车端保存:%1;本地修改仍保留,未自动重复上传") + .arg(detail.isEmpty() ? QStringLiteral("读回内容与修改不一致") : detail), true); +} + +bool AgvMapEditorWidget::verifySavedEdits(const AgvMapDocument &readback, QString *error) const +{ + if (!m_document.verifyRemovals(readback, error) || !readback.validateStationIds(error)) + return false; + for (const QVariant &value : m_document.stations()) { + const QVariantMap edit = value.toMap(); + const bool added = edit.value(QStringLiteral("draft")).toBool(); + const bool renamed = edit.value(QStringLiteral("nameChanged")).toBool(); + if (!added && !renamed) + continue; + const QString id = edit.value(QStringLiteral("id")).toString(); + const QVariantMap actual = objectWithId(readback.stations(), id); + const QVariantMap expected = objectWithId(m_saveCandidate.stations(), id); + if (actual.isEmpty() || expected.isEmpty() + || (added && !sameStation(actual, expected)) + || (renamed && actual.value(QStringLiteral("description")) != expected.value(QStringLiteral("description")))) { + *error = QStringLiteral("站点 %1 尚未读回到一致的编号、名称或坐标").arg(id); + return false; + } + } + for (const QVariant &value : m_document.routes()) { + const QVariantMap edit = value.toMap(); + if (!edit.value(QStringLiteral("draft")).toBool()) + continue; + const QString id = edit.value(QStringLiteral("id")).toString(); + if (!sameRoute(objectWithId(readback.routes(), id), objectWithId(m_saveCandidate.routes(), id))) { + *error = QStringLiteral("路线 %1 尚未读回到一致的起点、终点和路径").arg(id); + return false; + } + } + return true; +} diff --git a/src/agvmapeditorwidget.h b/src/agvmapeditorwidget.h new file mode 100644 index 0000000..f88a19b --- /dev/null +++ b/src/agvmapeditorwidget.h @@ -0,0 +1,103 @@ +#pragma once + +#include "agvmapdocument.h" + +#include +#include +#include +#include +#include +#include +#include + +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 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 m_contextProvider; + AgvMapDocument m_document; + AgvMapDocument m_saveCandidate; + QVector m_history; + struct Draft { + AgvMapDocument document; + QVector history; + }; + QHash 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 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; +}; diff --git a/src/agvmaprasterizer.cpp b/src/agvmaprasterizer.cpp new file mode 100644 index 0000000..f424e96 --- /dev/null +++ b/src/agvmaprasterizer.cpp @@ -0,0 +1,205 @@ +#include "agvmaprasterizer.h" + +#include "agvmapdocument.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +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::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(sourceWidthValue); + const int sourceHeight = static_cast(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(std::ceil(sourceWidth * scale)))); + const int height = std::min(1000, std::max(1, static_cast(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(std::floor(gridX)))); + const int y = std::max(0, std::min(height - 1, static_cast(std::floor(height - gridY)))); + reinterpret_cast(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; +} diff --git a/src/agvmaprasterizer.h b/src/agvmaprasterizer.h new file mode 100644 index 0000000..7d5a908 --- /dev/null +++ b/src/agvmaprasterizer.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include +#include + +// 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); diff --git a/src/agvmapviewwidget.cpp b/src/agvmapviewwidget.cpp index b5e2063..834704f 100644 --- a/src/agvmapviewwidget.cpp +++ b/src/agvmapviewwidget.cpp @@ -1,19 +1,49 @@ #include "agvmapviewwidget.h" +#include +#include #include #include #include #include #include #include +#include +#include #include #include +#include + namespace { constexpr double kMinimumZoom = 0.5; constexpr double kMaximumZoom = 8.0; constexpr int kMaximumTrajectoryPoints = 600; 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) @@ -30,13 +60,50 @@ void AgvMapViewWidget::setMapFrame(const QImage &image, const QVariantMap &metadata) { const QString nextMapId = metadata.value(QStringLiteral("mapId")).toString(); - if (!nextMapId.isEmpty() && nextMapId != m_mapId) { - m_mapId = nextMapId; - clearTrajectory(); - resetView(); - } + const bool mapChanged = !nextMapId.isEmpty() && nextMapId != m_mapId; m_image = image; 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(); } @@ -60,6 +127,7 @@ void AgvMapViewWidget::updateRobotPose(double x, double y, double theta, - kMaximumTrajectoryPoints); } } + refreshAutoFit(); update(); } @@ -71,18 +139,20 @@ void AgvMapViewWidget::setStreamMessage(const QString &message) void AgvMapViewWidget::zoomIn() { - changeZoom(1.25, rect().center()); + changeZoom(1.25, viewportCenter()); } void AgvMapViewWidget::zoomOut() { - changeZoom(0.8, rect().center()); + changeZoom(0.8, viewportCenter()); } void AgvMapViewWidget::resetView() { m_zoom = 1.0; m_pan = QPointF(); + m_autoFit = true; + refreshAutoFit(); update(); } @@ -92,12 +162,91 @@ void AgvMapViewWidget::clearTrajectory() 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 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() && m_metadata.value(QStringLiteral("dimension")).toInt() == 2 - && m_metadata.value(QStringLiteral("resolution")).toDouble() > 0.0 - && m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble() > 0.0; + && validResolution && qIsFinite(resolution) && resolution > 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 @@ -118,24 +267,124 @@ QPointF AgvMapViewWidget::worldToImage(double x, double y) const 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 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 { if (m_image.isNull()) return 1.0; - const double horizontal = qMax(1, width() - 24) - / static_cast(m_image.width()); - const double vertical = qMax(1, height() - 24) - / static_cast(m_image.height()); + const QRectF bounds = fittedBounds(); + const double horizontal = qMax(1, width() - 24) / bounds.width(); + const double vertical = qMax(1, height() - 52) / bounds.height(); 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 { if (m_image.isNull()) return QPointF(); const double scale = viewScale(); - return QPointF((width() - m_image.width() * scale) * 0.5, - (height() - m_image.height() * scale) * 0.5) + m_pan; + return viewportCenter() + - fittedBounds().center() * scale + m_pan; } QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const @@ -143,59 +392,267 @@ QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const 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; - constexpr double panelMargin = 12.0; - constexpr double arrowLength = 27.0; - const QRectF panel(width() - panelMargin - panelSize, - panelMargin, panelSize, panelSize); + painter.save(); + QFont labelFont = painter.font(); + labelFont.setPointSize(9); + labelFont.setBold(true); + 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.setPen(QPen(QColor(QStringLiteral("#c9d4de")), 1)); - painter.setBrush(QColor(255, 255, 255, 232)); - painter.drawRoundedRect(panel, 8, 8); + for (const QVariant &entry : editorRoutes()) { + const QVariantMap route = entry.toMap(); + 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(); - const double originTheta = m_metadata.value( - QStringLiteral("originTheta")).toDouble(); - const QPointF xDirection(qCos(originTheta), qSin(originTheta)); - const QPointF yDirection(qSin(originTheta), -qCos(originTheta)); + double routeLength = 0.0; + for (int index = 1; index < geometry.size(); ++index) + routeLength += QLineF(geometry.at(index - 1), geometry.at(index)).length(); + if (!qIsFinite(routeLength) || routeLength < 20.0) + 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]( - const QPointF &direction, - const QColor &color, - const QString &label) { - const QPointF normal(-direction.y(), direction.x()); - const QPointF tip = center + direction * arrowLength; - painter.setPen(QPen(color, 2.4, Qt::SolidLine, Qt::RoundCap)); + for (const QVariant &entry : editorStations()) { + const QVariantMap station = entry.toMap(); + QPointF world; + if (!objectPosition(station, &world)) + continue; + const QPointF center = imageToWidget(worldToImage(world.x(), world.y())); + 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.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; - arrowHead << tip - << tip - direction * 8.0 + normal * 4.5 - << tip - direction * 8.0 - normal * 4.5; - painter.setPen(Qt::NoPen); - painter.drawPolygon(arrowHead); +double AgvMapViewWidget::gridStep() const +{ + if (!canProjectPose()) + return 1.0; + const double pixelsPerMeter = viewScale() + * 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; - const QRectF labelRect(labelCenter.x() - 9.0, - labelCenter.y() - 9.0, 18.0, 18.0); - QFont labelFont = painter.font(); - labelFont.setBold(true); - painter.setFont(labelFont); - painter.setPen(color); - painter.drawText(labelRect, Qt::AlignCenter, label); +void AgvMapViewWidget::drawWorldGrid(QPainter &painter) const +{ + if (!canProjectPose()) + return; + const QRectF visible = QRectF(rect()).adjusted(8, 8, -8, -8); + const QList corners = {visible.topLeft(), visible.topRight(), + visible.bottomLeft(), visible.bottomRight()}; + 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")), - QStringLiteral("X")); - drawArrow(yDirection, QColor(QStringLiteral("#2f9e69")), - QStringLiteral("Y")); - painter.setPen(Qt::NoPen); - painter.setBrush(QColor(QStringLiteral("#374151"))); - painter.drawEllipse(center, 3.2, 3.2); +void AgvMapViewWidget::drawCoordinateAxes(QPainter &painter) const +{ + QPointF leftWorld; + QPointF rightWorld; + const double left = 12.0; + const double right = width() - 48.0; + 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(); } @@ -204,7 +661,12 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event) Q_UNUSED(event) QPainter painter(this); 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()) { painter.setPen(QColor(QStringLiteral("#71808e"))); @@ -212,6 +674,7 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event) m_streamMessage.isEmpty() ? QStringLiteral("等待 AGV 返回地图数据") : m_streamMessage); + painter.restore(); return; } @@ -220,12 +683,11 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event) const QRectF target(topLeft, QSizeF(m_image.width() * scale, m_image.height() * scale)); + drawWorldGrid(painter); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); 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) { QPainterPath path; path.moveTo(imageToWidget(worldToImage( @@ -234,11 +696,13 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event) path.lineTo(imageToWidget(worldToImage( 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)); painter.drawPath(path); } + drawEditorObjects(painter); + if (canProjectPose() && m_hasPose) { const QPointF center = imageToWidget(worldToImage(m_robotX, m_robotY)); const double originTheta = m_metadata.value( @@ -246,46 +710,57 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event) const double angle = m_robotTheta - originTheta; const QPointF forward(qCos(angle), -qSin(angle)); const QPointF lateral(-forward.y(), forward.x()); - const double size = 13.0; + const double size = 10.0; QPolygonF robot; robot << center + forward * size << center - forward * size * 0.7 + lateral * size * 0.65 << center - forward * size * 0.7 - lateral * size * 0.65; - painter.setPen(Qt::NoPen); - painter.setBrush(QColor(47, 111, 237, m_localized ? 48 : 24)); - painter.drawEllipse(center, 25, 25); - painter.setBrush(m_localized - ? QColor(QStringLiteral("#2f6fed")) - : QColor(QStringLiteral("#df8b24"))); + painter.setPen(QPen(QColor(QStringLiteral("#ffffff")), 1.4)); + QColor robotColor = kRouteColor; + robotColor.setAlpha(m_localized ? 255 : 150); + painter.setBrush(robotColor); painter.drawPolygon(robot); painter.setPen(QColor(QStringLiteral("#ffffff"))); painter.drawLine(center - forward * 2, center + forward * 7); - const QString poseText = QStringLiteral("(%1, %2, %3°)") - .arg(m_robotX, 0, 'f', 2) - .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); + drawObjectLabel(painter, QStringLiteral("AGV"), center + QPointF(11, -22), + kRouteColor); } + painter.restore(); if (canProjectPose()) drawCoordinateAxes(painter); - if (!m_streamMessage.isEmpty()) { - const QRect messageRect(12, height() - 36, width() - 24, 24); - painter.setPen(QColor(QStringLiteral("#5c6975"))); - painter.drawText(messageRect, Qt::AlignLeft | Qt::AlignVCenter, - m_streamMessage); + if (m_metadata.value(QStringLiteral("demo")).toBool()) { + QFont badgeFont = painter.font(); + badgeFont.setPointSize(9); + painter.setFont(badgeFont); + 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) @@ -294,11 +769,11 @@ void AgvMapViewWidget::changeZoom(double factor, const QPointF &anchor) return; const double oldScale = viewScale(); const QPointF imagePoint = (anchor - imageTopLeft()) / oldScale; + m_autoFit = false; m_zoom = qBound(kMinimumZoom, m_zoom * factor, kMaximumZoom); const double newScale = viewScale(); - const QPointF centeredTopLeft( - (width() - m_image.width() * newScale) * 0.5, - (height() - m_image.height() * newScale) * 0.5); + const QPointF centeredTopLeft = viewportCenter() + - fittedBounds().center() * newScale; m_pan = anchor - imagePoint * newScale - centeredTopLeft; update(); } @@ -311,19 +786,53 @@ void AgvMapViewWidget::wheelEvent(QWheelEvent *event) void AgvMapViewWidget::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) { + if (event->button() == Qt::LeftButton || event->button() == Qt::RightButton) { m_dragging = true; + m_mouseMoved = false; + m_pressedButton = event->button(); + m_mousePressPosition = event->pos(); m_lastMousePosition = event->pos(); - setCursor(Qt::ClosedHandCursor); + if (m_editMode == BrowseMode || m_pressedButton == Qt::RightButton) + setCursor(Qt::ClosedHandCursor); event->accept(); return; } QWidget::mousePressEvent(event); } +bool AgvMapViewWidget::event(QEvent *event) +{ + if (event->type() == QEvent::ToolTip && !m_dragging) { + auto *help = static_cast(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("%1").arg(text.toHtmlEscaped().replace( + QLatin1Char('\n'), QStringLiteral("
"))), this); + event->accept(); + return true; + } + } + return QWidget::event(event); +} + void AgvMapViewWidget::mouseMoveEvent(QMouseEvent *event) { 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_lastMousePosition = event->pos(); update(); @@ -335,11 +844,51 @@ void AgvMapViewWidget::mouseMoveEvent(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; - 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(); return; } QWidget::mouseReleaseEvent(event); } + +void AgvMapViewWidget::updateInteractionCursor() +{ + setCursor(m_editMode == BrowseMode ? Qt::OpenHandCursor : Qt::CrossCursor); +} + +void AgvMapViewWidget::resizeEvent(QResizeEvent *event) +{ + QWidget::resizeEvent(event); + refreshAutoFit(); +} diff --git a/src/agvmapviewwidget.h b/src/agvmapviewwidget.h index 5e8c625..1644d0b 100644 --- a/src/agvmapviewwidget.h +++ b/src/agvmapviewwidget.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -11,44 +12,86 @@ class QMouseEvent; class QPainter; class QPaintEvent; +class QResizeEvent; class QWheelEvent; class AgvMapViewWidget final : public QWidget { + Q_OBJECT + public: + enum EditMode { BrowseMode, AddStationMode, AddRouteMode }; + explicit AgvMapViewWidget(QWidget *parent = nullptr); void setMapFrame(const QImage &image, const QVariantMap &metadata); + void clearMapFrame(const QString &message); void updateRobotPose(double x, double y, double theta, bool localized); + void clearRobotPose(); void setStreamMessage(const QString &message); void zoomIn(); void zoomOut(); void resetView(); 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: + bool event(QEvent *event) override; void paintEvent(QPaintEvent *event) override; void wheelEvent(QWheelEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; + void resizeEvent(QResizeEvent *event) override; private: bool canProjectPose() const; QPointF worldToImage(double x, double y) 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; + QPointF viewportCenter() const; QPointF imageTopLeft() const; + double gridStep() const; + void drawWorldGrid(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 updateInteractionCursor(); QImage m_image; QVariantMap m_metadata; QVector m_trajectory; + QVariantList m_editorStations; + QVariantList m_editorRoutes; + QVariantList m_mapStations; + QVariantList m_mapRoutes; QString m_streamMessage; QString m_mapId; + QString m_selectedStationId; + QString m_editorMapId; QPointF m_pan; + QRectF m_fitBounds; + QPoint m_mousePressPosition; QPoint m_lastMousePosition; + EditMode m_editMode = BrowseMode; + Qt::MouseButton m_pressedButton = Qt::NoButton; double m_zoom = 1.0; double m_robotX = 0.0; double m_robotY = 0.0; @@ -56,4 +99,7 @@ private: bool m_localized = false; bool m_hasPose = false; bool m_dragging = false; + bool m_mouseMoved = false; + bool m_autoFit = true; + bool m_hasEditorObjects = false; }; diff --git a/src/agvvelocityramp.h b/src/agvvelocityramp.h new file mode 100644 index 0000000..2110db2 --- /dev/null +++ b/src/agvvelocityramp.h @@ -0,0 +1,153 @@ +#pragma once + +#include +#include + +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 ¤t, + 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; + } +}; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 90b9c7e..585ee69 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -10,6 +10,7 @@ #include "videorenderwidget.h" #include "agvmapviewwidget.h" +#include "agvmapeditorwidget.h" #include "audiostreammanager.h" #include "configeditorwidget.h" #include "robotclient.h" @@ -1035,10 +1036,30 @@ MainWindow::MainWindow(QWidget *parent) } }); 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, [this](const QImage &image, const QVariantMap &metadata, 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_pendingAgvMapMetadata = metadata; m_pendingAgvMapDetail = detail; @@ -1054,9 +1075,18 @@ MainWindow::MainWindow(QWidget *parent) m_agvMapRefreshTimer->start(); } }); - connect(m_client, &RobotClient::agvMapStreamStateChanged, this, - [this](bool running, const QString &detail) { + connect(m_client, &RobotClient::agvMapStreamStateChangedForContext, this, + [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; + if (!context.value(QStringLiteral("error")).toString().isEmpty()) + m_agvMapReadError = context.value(QStringLiteral("error")).toString(); const int intervalMs = m_agvMapRefreshCombo ? m_agvMapRefreshCombo->currentData().toInt() : 0; if (m_agvMapRefreshTimer) { @@ -1070,6 +1100,13 @@ MainWindow::MainWindow(QWidget *parent) } if (m_agvMapView) 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()), ¢er); + m_agvMapRecoveryNeeded = !hasFrame && !m_agvMapRecoveryAttempted; + } + updateAgvMapSwitchStatus(); if (!m_agvMappingStateLabel) return; m_agvMappingStateLabel->setProperty("running", running); @@ -1219,7 +1256,7 @@ MainWindow::~MainWindow() if (m_touchOperation) m_touchOperation->stop(); if (m_tcpJog) m_tcpJog->stop(); qApp->removeEventFilter(this); - stopAgvManualMotion(false); + stopAgvManualMotion(); if (m_client) m_client->stopAgvMapStream(); m_audioManager->stopSource(); @@ -1307,9 +1344,19 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event) 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(event); + if (!key->isAutoRepeat() && key->key() == m_agvManualKey) { + m_agvManualKey = 0; + decelerateAgvManualMotion(); + return true; + } + } + const bool agvControlVisible = m_connected && m_pages && m_pages->currentIndex() == 3 && m_agvControlWorkspace - && m_agvControlWorkspace->isVisible(); + && m_agvControlWorkspace->isVisible() && m_agvVxSpin && m_agvVxSpin->isVisible(); if (!event || !agvControlVisible || (event->type() != QEvent::KeyPress && event->type() != QEvent::KeyRelease)) { @@ -1361,10 +1408,11 @@ bool MainWindow::eventFilter(QObject *watched, QEvent *event) if (!directionKey) return QMainWindow::eventFilter(watched, event); - if (event->type() == QEvent::KeyPress) + if (event->type() == QEvent::KeyPress) { startAgvManualMotion(vx, vy, wz); - else - stopAgvManualMotion(); + m_agvManualButton.clear(); + m_agvManualKey = m_agvManualMotionActive ? keyEvent->key() : 0; + } return true; } @@ -1553,11 +1601,15 @@ void MainWindow::selectPage(int index) m_client->stopAgvMapStream(); 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->requestAgvInventory(m_agvIdEdit->text().trimmed()); m_agvStatusRefreshTimer->start(); - restartAgvMapStream(); + if (m_agvStateAvailable && !m_agvMapStreamPaused) + restartAgvMapStream(); } if (index < m_navButtons.size()) m_navButtons.at(index)->setChecked(true); @@ -1565,43 +1617,364 @@ void MainWindow::selectPage(int index) 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()) { return; } - m_agvManualVx = vx; - m_agvManualVy = vy; - m_agvManualWz = wz; - m_agvManualMotionActive = true; - m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), vx, vy, wz); + const AgvManualVelocity target{vx, vy, wz}; + if (AgvVelocityRamp::isZero(target)) { + decelerateAgvManualMotion(); + return; + } + 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()) 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) { const bool wasActive = m_agvManualMotionActive; + const QString deviceId = m_agvManualDeviceId; m_agvManualMotionActive = false; + m_agvManualVelocityInFlight = false; + ++m_agvManualVelocityRequestId; + m_agvManualTarget = {}; + m_agvManualVelocity = {}; + m_agvManualDeviceId.clear(); + m_agvManualKey = 0; + m_agvManualButton.clear(); if (m_agvManualVelocityTimer) m_agvManualVelocityTimer->stop(); - if (sendStop && wasActive && m_connected && m_client && m_agvIdEdit - && !m_agvIdEdit->text().trimmed().isEmpty()) { - m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), - QStringLiteral("StopVelocity")); - } + if (m_client) + m_client->cancelAgvManualVelocity(); + if (sendStop && wasActive && m_connected && m_client && !deviceId.isEmpty()) + 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 || m_agvIdEdit->text().trimmed().isEmpty()) { return; } - const QString selectedMap = mapName.trimmed().isEmpty() && m_agvMapCombo - ? m_agvMapCombo->currentText().trimmed() : mapName.trimmed(); + // A transient status failure must not replace an explicitly selected map + // 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->startAgvMapStream(m_agvIdEdit->text().trimmed(), selectedMap, - 1, true, true); + if (!selectedMap.isEmpty()) + 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(m_agvIdEdit), + static_cast(m_agvMapCombo), + static_cast(m_agvSwitchMapButton)}) { + if (control) + control->setEnabled(m_connected && !m_agvMapEditorBusy && !m_agvMapSwitchPending); + } + updateAgvMapSwitchStatus(); } void MainWindow::presentPendingAgvMapFrame() @@ -1613,6 +1986,12 @@ void MainWindow::presentPendingAgvMapFrame() m_agvMapView->setMapFrame(m_pendingAgvMapImage, m_pendingAgvMapMetadata); 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) m_agvMappingStateLabel->setText(m_pendingAgvMapDetail); @@ -1646,8 +2025,12 @@ void MainWindow::ensureArmModelLoaded() void MainWindow::toggleConnection() { + m_agvMapStreamPaused = false; if (m_connected) { if (m_tcpJog) m_tcpJog->stop(); + clearAgvDisplay(QStringLiteral("正在断开连接")); + if (m_agvStatusRefreshTimer) + m_agvStatusRefreshTimer->stop(); m_connectButton->setEnabled(false); m_connectButton->setText(QStringLiteral("正在断开…")); m_client->disconnectFromServer(); @@ -1659,6 +2042,7 @@ void MainWindow::toggleConnection() return; } saveSettings(); + clearAgvDisplay(QStringLiteral("等待当前设备状态")); // Freeze the endpoint while the worker connects so TCP records retain // the identity of the server that actually owns the feedback. m_hostEdit->setEnabled(false); @@ -1684,6 +2068,9 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString & if (!connected && m_taskOrchestration) m_taskOrchestration->failActiveTask( detail.isEmpty() ? QStringLiteral("gRPC 连接已断开") : detail); + if (!connected) { + clearAgvDisplay(QStringLiteral("连接已断开")); + } m_connectButton->setEnabled(true); m_connectButton->setText(connected ? QStringLiteral("断开连接") : QStringLiteral("连接")); m_connectionText->setText(connected ? QStringLiteral("gRPC 已连接") @@ -1702,12 +2089,18 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString & state->style()->polish(state); } setControlsEnabled(connected); + configureAgvMapDirectConnection(); 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->requestAgvInventory(m_agvIdEdit->text().trimmed()); m_agvStatusRefreshTimer->start(); - restartAgvMapStream(); } else { 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) { + 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; 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 fault = state.value(QStringLiteral("fault")).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")) : QStringLiteral("--")); m_agvProgress->setValue(qBound(0, qRound(navigation.value(QStringLiteral("progress")).toDouble() * 100.0), 100)); - if (m_agvMapView) { - m_agvMapView->updateRobotPose( - state.value(QStringLiteral("x")).toDouble(), - state.value(QStringLiteral("y")).toDouble(), - state.value(QStringLiteral("theta")).toDouble(), localized); + updateAgvMapRobotPose(); + updateAgvMapSwitchStatus(); + refreshConfirmedAgvMap(m_agvMapSwitchToken); + if (m_agvMapRecoveryNeeded && !m_agvMapStreamPaused && m_connected && m_pages + && 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) { + const QSignalBlocker mapSignals(m_agvMapCombo); QString selectedMap = m_agvMapCombo->currentText(); if (selectedMap.trimmed().isEmpty()) selectedMap = m_latestAgvState.value(QStringLiteral("map")).toString(); m_agvMapCombo->clear(); 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); if (mapIndex >= 0) 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_agvStationTable->setRowCount(stations.size()); for (int row = 0; row < stations.size(); ++row) { const QVariantMap station = stations.at(row).toMap(); const QString stationId = station.value(QStringLiteral("id")).toString(); - m_agvStationCombo->addItem(stationId); - m_agvStationTable->setItem(row, 0, new QTableWidgetItem(stationId)); + const QString stationName = station.value(QStringLiteral("name"), + 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, 2, new QTableWidgetItem(QString::number( station.value(QStringLiteral("x")).toDouble(), 'f', 3))); m_agvStationTable->setItem(row, 3, new QTableWidgetItem(QString::number( station.value(QStringLiteral("y")).toDouble(), 'f', 3))); } - const int stationIndex = m_agvStationCombo->findText(selectedStation); + const int stationIndex = m_agvStationCombo->findData(selectedStation); if (stationIndex >= 0) m_agvStationCombo->setCurrentIndex(stationIndex); @@ -3141,9 +3590,37 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri || command == QStringLiteral("Camera Stop Recording"))) { updateCameraRecordingState(m_cameraRecording, detail); } - if (success && command == QStringLiteral("AGV SwitchMap")) { - m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); - restartAgvMapStream(m_agvMapCombo->currentText()); + if (command == QStringLiteral("AGV SwitchMap") && m_agvMapSwitchPending) { + const QString target = m_agvSwitchMapTarget; + 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(m_agvMapCombo), + static_cast(m_agvIdEdit), + static_cast(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")) { const bool asynchronousMappingFrame = @@ -3176,14 +3653,18 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri if (m_agvMappingStateLabel) m_agvMappingStateLabel->setText(QStringLiteral("建图已停止")); m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); - restartAgvMapStream(); + if (!m_agvMapStreamPaused && m_pages && m_pages->currentIndex() == 3) + restartAgvMapStream(); } else if (m_agvMappingStateLabel) { 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"), - QStringLiteral("%1 · %2").arg(command, detail)); + QStringLiteral("%1 · %2").arg(command, commandDetail)); if (!success) m_connectionText->setToolTip(detail); } @@ -3568,6 +4049,23 @@ void MainWindow::saveSnapshot() void MainWindow::loadSettings() { 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); m_hostEdit->setText(settings.value(QStringLiteral("connection/host"), QStringLiteral("192.168.0.28")).toString()); m_hostEdit->setCursorPosition(0); @@ -3597,13 +4095,25 @@ void MainWindow::loadSettings() if (modeIndex >= 0) 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) { - const int intervalMs = settings.value( - QStringLiteral("agv/mapRefreshIntervalMs"), 0).toInt(); - const int index = m_agvMapRefreshCombo->findData(intervalMs); + const int index = m_agvMapRefreshCombo->findData(agvMapRefreshInterval); 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 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( QStringLiteral("motion/speedJVelocity"), settings.value(QStringLiteral("motion/velocity"), 1.0)).toDouble()); @@ -3671,9 +4181,21 @@ void MainWindow::saveSettings() settings.setValue(QStringLiteral("camera/streamMode"), m_cameraStreamModeCombo->currentData().toString()); 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) settings.setValue(QStringLiteral("agv/mapRefreshIntervalMs"), 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/speedJAcceleration"), m_accelerationSpin->value()); diff --git a/src/mainwindow.h b/src/mainwindow.h index 65372f2..8ab0b5c 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -3,9 +3,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -15,6 +17,7 @@ #include "videoframe.h" #include "jointpointdata.h" +#include "agvvelocityramp.h" class QButtonGroup; class QCheckBox; @@ -50,6 +53,7 @@ class TcpJogController; class HandEyeCalibrationWidget; class HandEyeMotionWidget; class AgvMapViewWidget; +class AgvMapEditorWidget; class TactileHeatmapWidget; class JointFlowEditor; class TaskOrchestrationWidget; @@ -158,9 +162,18 @@ private: void setupTouchOperation(); void syncHandEyeContext(); void startAgvManualMotion(double vx, double vy, double wz); + void decelerateAgvManualMotion(); + void advanceAgvManualMotion(); void stopAgvManualMotion(bool sendStop = true); - void restartAgvMapStream(const QString &mapName = QString()); + void restartAgvMapStream(const QString &mapName = QString(), bool recovering = false); 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, const QString &level, const QString &summary, const QString &detail = QString()); @@ -438,6 +451,7 @@ private: QLabel *m_agvMappingPreview = nullptr; QLabel *m_agvMappingStateLabel = nullptr; AgvMapViewWidget *m_agvMapView = nullptr; + AgvMapEditorWidget *m_agvMapEditor = nullptr; QWidget *m_agvControlWorkspace = nullptr; QPushButton *m_agvDeleteMapButton = nullptr; QPushButton *m_agvStopMappingButton = nullptr; @@ -449,20 +463,64 @@ private: QDoubleSpinBox *m_agvVxSpin = nullptr; QDoubleSpinBox *m_agvVySpin = 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_agvMapDirectMode = nullptr; + QLineEdit *m_agvMapDirectHost = nullptr; + QList 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_agvStationCombo = nullptr; + QPushButton *m_agvSwitchMapButton = nullptr; QTableWidget *m_agvStationTable = nullptr; QString m_agvDownloadPath; QVariantMap m_latestAgvState; QImage m_pendingAgvMapImage; QVariantMap m_pendingAgvMapMetadata; QString m_pendingAgvMapDetail; - double m_agvManualVx = 0.0; - double m_agvManualVy = 0.0; - double m_agvManualWz = 0.0; + QString m_agvRequestedMap; + QString m_agvStreamDeviceId; + 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 m_agvManualButton; + int m_agvManualKey = 0; bool m_agvManualMotionActive = 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_agvStopMappingRetryPending = false; QList m_serviceButtons; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 6d092fa..40a12f8 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -1,6 +1,7 @@ #include "mainwindow.h" #include "agvmapviewwidget.h" +#include "agvmapeditorwidget.h" #include "audiostreammanager.h" #include "cameracapabilities.h" #include "robotclient.h" @@ -27,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -53,6 +55,7 @@ #include #include #include +#include #include #include #include @@ -1918,6 +1921,21 @@ QWidget *MainWindow::createAgvPage() QWidget *page = new QWidget; Ui::AgvServicePage ui; 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); m_agvStatusDialog = statusDialog; @@ -1958,6 +1976,10 @@ QWidget *MainWindow::createAgvPage() m_agvSafetyValue = statusUi.agvSafetyValue; m_agvPowerValue = statusUi.agvPowerValue; 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_agvMappingPreview = ui.mappingPreview; m_agvMappingStateLabel = ui.mappingStateLabel; @@ -1970,6 +1992,7 @@ QWidget *MainWindow::createAgvPage() m_agvVySpin = ui.agvVySpin; m_agvWzSpin = ui.agvWzSpin; m_agvMapCombo = ui.agvMapCombo; + m_agvSwitchMapButton = ui.switchMapButton; m_agvStationCombo = ui.agvStationCombo; m_agvStationTable = ui.agvStationTable; 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"), QColor(QStringLiteral("#ffffff")))); 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("类型"), QStringLiteral("X"), QStringLiteral("Y")}); @@ -1987,13 +2015,25 @@ QWidget *MainWindow::createAgvPage() m_agvStationTable->horizontalHeader()->setStretchLastSection(true); m_agvStatusRefreshTimer->setInterval(500); m_agvManualVelocityTimer = new QTimer(page); - m_agvManualVelocityTimer->setInterval(150); - connect(m_agvManualVelocityTimer, &QTimer::timeout, this, [this]() { - if (!m_agvManualMotionActive || !m_connected) + m_agvManualVelocityTimer->setObjectName(QStringLiteral("agvManualVelocityTimer")); + m_agvManualVelocityTimer->setTimerType(Qt::PreciseTimer); + 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; - m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), - m_agvManualVx, m_agvManualVy, - m_agvManualWz); + m_agvManualVelocityInFlight = false; + if (!success) { + 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); @@ -2010,19 +2050,29 @@ QWidget *MainWindow::createAgvPage() QVBoxLayout *rightLayout = new QVBoxLayout(rightColumn); rightLayout->setContentsMargins(0, 0, 0, 0); rightLayout->setSpacing(12); - workspaceLayout->addWidget(leftColumn, 7); - workspaceLayout->addWidget(rightColumn, 4); + auto *sidebar = new QScrollArea(m_agvControlWorkspace); + 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->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.mappingPreview->hide(); + ui.mappingStateLabel->hide(); m_agvMappingPreview = nullptr; QHBoxLayout *mapToolbar = new QHBoxLayout; QLabel *mapLegend = new QLabel( - QStringLiteral("蓝色箭头:AGV 当前位姿 · 虚线:运动轨迹"), + QStringLiteral("橙色站点 · 蓝色路线 · 箭头表示方向"), ui.mappingPreviewPanel); mapLegend->setObjectName(QStringLiteral("panelSubtitle")); QLabel *mapRefreshLabel = new QLabel(QStringLiteral("刷新率"), @@ -2042,10 +2092,18 @@ QWidget *MainWindow::createAgvPage() ui.mappingPreviewPanel); QPushButton *zoomInButton = new QPushButton(QStringLiteral("+"), ui.mappingPreviewPanel); - QPushButton *resetViewButton = new QPushButton(QStringLiteral("适应窗口"), + QPushButton *resetViewButton = new QPushButton(QStringLiteral("显示全图"), ui.mappingPreviewPanel); QPushButton *clearTrackButton = new QPushButton(QStringLiteral("清除轨迹"), 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, resetViewButton, clearTrackButton}) { button->setObjectName(QStringLiteral("agvMapToolButton")); @@ -2053,6 +2111,9 @@ QWidget *MainWindow::createAgvPage() } zoomOutButton->setMaximumWidth(42); zoomInButton->setMaximumWidth(42); + ui.mappingPreviewLayout->removeWidget(ui.mappingPreviewTitle); + mapToolbar->addWidget(ui.mappingPreviewTitle); + mapToolbar->addSpacing(8); mapToolbar->addWidget(mapLegend); mapToolbar->addStretch(); mapToolbar->addWidget(mapRefreshLabel); @@ -2062,40 +2123,215 @@ QWidget *MainWindow::createAgvPage() mapToolbar->addWidget(zoomInButton); mapToolbar->addWidget(resetViewButton); mapToolbar->addWidget(clearTrackButton); - ui.mappingPreviewLayout->insertLayout(1, mapToolbar); + mapToolbar->addWidget(expandMapButton); + ui.mappingPreviewLayout->insertLayout(0, mapToolbar); m_agvMapView = new AgvMapViewWidget(ui.mappingPreviewPanel); m_agvMapView->setObjectName(QStringLiteral("agvLiveMap")); + m_agvMapView->setMinimumHeight(320); 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(&QSpinBox::valueChanged), this, resetAgvSource); + connect(m_demoCheck, &QCheckBox::toggled, this, resetAgvSource); + connect(m_agvMapDirectMode, qOverload(&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(m_agvIdEdit), + static_cast(m_agvMapCombo), + static_cast(ui.switchMapButton), + static_cast(ui.uploadMapButton), + static_cast(ui.downloadMapButton), + static_cast(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); - 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")); QVBoxLayout *mapActionsLayout = new QVBoxLayout(mapActionsPanel); - mapActionsLayout->setContentsMargins(18, 14, 18, 14); + mapActionsLayout->setContentsMargins(14, 14, 14, 14); mapActionsLayout->setSpacing(9); QLabel *mapActionsTitle = new QLabel(QStringLiteral("地图与建图"), mapActionsPanel); mapActionsTitle->setObjectName(QStringLiteral("sectionTitle")); QLabel *mapActionsSubtitle = new QLabel( - QStringLiteral("加载已有地图、重新定位,或创建新的建图会话"), + QStringLiteral("管理地图与建图会话"), mapActionsPanel); mapActionsSubtitle->setObjectName(QStringLiteral("panelSubtitle")); mapActionsLayout->addWidget(mapActionsTitle); 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("新增地图"), mapActionsPanel); QPushButton *relocalizeButton = new QPushButton(QStringLiteral("重新定位"), @@ -2113,13 +2349,14 @@ QWidget *MainWindow::createAgvPage() mapActionsLayout->addLayout(mapOperationRow); QGridLayout *mappingForm = new QGridLayout; - QLabel *mappingNameLabel = new QLabel(QStringLiteral("新地图"), + QLabel *mappingNameLabel = new QLabel(QStringLiteral("名称"), mapActionsPanel); QLabel *mappingDimensionLabel = new QLabel(QStringLiteral("类型"), mapActionsPanel); ui.mappingNameEdit->setParent(mapActionsPanel); ui.mappingDimensionCombo->setParent(mapActionsPanel); ui.mappingRealtimeCheck->setParent(mapActionsPanel); + ui.mappingDimensionCombo->setMaximumWidth(120); mappingForm->addWidget(mappingNameLabel, 0, 0); mappingForm->addWidget(ui.mappingNameEdit, 0, 1); mappingForm->addWidget(mappingDimensionLabel, 0, 2); @@ -2142,26 +2379,115 @@ QWidget *MainWindow::createAgvPage() transferRow->addWidget(ui.uploadMapButton); transferRow->addWidget(ui.downloadMapButton); mapActionsLayout->addLayout(transferRow); - leftLayout->addWidget(mapActionsPanel); + mapActionsLayout->addStretch(); + controlTools->addTab(mapActionsPanel, QStringLiteral("地图与建图")); statusUi.agvDialogSurface->setGraphicsEffect(nullptr); statusUi.agvDialogSurface->setParent(rightColumn); statusUi.agvDialogSurface->setMinimumSize(0, 0); statusUi.agvDialogTitleBar->hide(); statusUi.agvDialogContentLayout->setContentsMargins(0, 0, 0, 0); - statusUi.navigationStatusPanel->setMaximumHeight(150); - rightLayout->addWidget(statusUi.agvDialogSurface, 3); + statusUi.runtimeLayout->setContentsMargins(14, 12, 14, 12); + statusUi.runtimeLayout->setSpacing(8); + statusUi.statusLayout->setVerticalSpacing(6); + statusUi.statusLayout->setHorizontalSpacing(14); + while (QLayoutItem *item = statusUi.statusLayout->takeAt(0)) + delete item; + const QVector> 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.velocityTitle->setText(QStringLiteral("手动速度控制")); 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_agvVySpin->setMinimum(0.0); m_agvWzSpin->setMinimum(0.0); if (qFuzzyIsNull(m_agvVySpin->value())) 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(&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.forwardButton->setText(QStringLiteral("前进 (W)")); ui.rotateRightButton->setText(QStringLiteral("右旋 (E)")); @@ -2169,7 +2495,13 @@ QWidget *MainWindow::createAgvPage() ui.rightButton->setText(QStringLiteral("右移 (D)")); ui.backwardButton->setText(QStringLiteral("后退 (S)")); 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 int index = tabs->indexOf(tab); @@ -2253,10 +2585,18 @@ QWidget *MainWindow::createAgvPage() 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()); }); 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()); }); connect(ui.navigatePoseButton, &QPushButton::clicked, this, [this]() { @@ -2265,8 +2605,11 @@ QWidget *MainWindow::createAgvPage() m_agvMaxSpeedSpin->value()); }); 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_agvStationCombo->currentText().trimmed(), + stationId, m_agvMaxSpeedSpin->value()); }); connect(ui.pauseButton, &QPushButton::clicked, this, [this]() { @@ -2280,37 +2623,53 @@ QWidget *MainWindow::createAgvPage() }); connect(ui.forwardButton, &QPushButton::pressed, this, [this]() { startAgvManualMotion(qAbs(m_agvVxSpin->value()), 0.0, 0.0); + m_agvManualKey = 0; + m_agvManualButton = m_agvManualMotionActive ? qobject_cast(sender()) : nullptr; }); connect(ui.backwardButton, &QPushButton::pressed, this, [this]() { startAgvManualMotion(-qAbs(m_agvVxSpin->value()), 0.0, 0.0); + m_agvManualKey = 0; + m_agvManualButton = m_agvManualMotionActive ? qobject_cast(sender()) : nullptr; }); connect(ui.leftButton, &QPushButton::pressed, this, [this]() { startAgvManualMotion(0.0, qAbs(m_agvVySpin->value()), 0.0); + m_agvManualKey = 0; + m_agvManualButton = m_agvManualMotionActive ? qobject_cast(sender()) : nullptr; }); connect(ui.rightButton, &QPushButton::pressed, this, [this]() { startAgvManualMotion(0.0, -qAbs(m_agvVySpin->value()), 0.0); + m_agvManualKey = 0; + m_agvManualButton = m_agvManualMotionActive ? qobject_cast(sender()) : nullptr; }); connect(ui.rotateLeftButton, &QPushButton::pressed, this, [this]() { startAgvManualMotion(0.0, 0.0, qAbs(m_agvWzSpin->value())); + m_agvManualKey = 0; + m_agvManualButton = m_agvManualMotionActive ? qobject_cast(sender()) : nullptr; }); connect(ui.rotateRightButton, &QPushButton::pressed, this, [this]() { startAgvManualMotion(0.0, 0.0, -qAbs(m_agvWzSpin->value())); + m_agvManualKey = 0; + m_agvManualButton = m_agvManualMotionActive ? qobject_cast(sender()) : nullptr; }); for (QPushButton *button : { ui.forwardButton, ui.backwardButton, ui.leftButton, ui.rightButton, ui.rotateLeftButton, ui.rotateRightButton}) { connect(button, &QPushButton::released, this, - [this]() { stopAgvManualMotion(); }); + [this, button]() { + if (m_agvManualButton == button) + decelerateAgvManualMotion(); + }); } connect(ui.manualStopButton, &QPushButton::clicked, this, - [this]() { stopAgvManualMotion(); }); + [this]() { decelerateAgvManualMotion(); }); connect(ui.zeroVelocityButton, &QPushButton::clicked, this, [this]() { - stopAgvManualMotion(); + decelerateAgvManualMotion(); m_agvVxSpin->setValue(0.0); m_agvVySpin->setValue(0.0); m_agvWzSpin->setValue(0.0); }); connect(statusUi.stopVelocityButton, &QPushButton::clicked, this, [this]() { + stopAgvManualMotion(false); m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("StopVelocity")); }); @@ -2318,6 +2677,7 @@ QWidget *MainWindow::createAgvPage() m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("ClearFault")); }); connect(ui.emergencyButton, &QPushButton::clicked, this, [this]() { + stopAgvManualMotion(false); m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("EmergencyStop")); }); @@ -2325,8 +2685,34 @@ QWidget *MainWindow::createAgvPage() m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); }); connect(ui.switchMapButton, &QPushButton::clicked, this, [this]() { - m_client->requestAgvSwitchMap(m_agvIdEdit->text().trimmed(), - m_agvMapCombo->currentText().trimmed()); + if (!m_connected || m_agvMapSwitchPending || m_agvMapEditorBusy || m_agvDirectBusy) + 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]() { const QString path = QFileDialog::getOpenFileName( @@ -2448,6 +2834,30 @@ QWidget *MainWindow::createAgvPage() ui.mappingStateLabel->setText(QStringLiteral("正在停止建图")); }); 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_agvIdEdit->text().trimmed(), ui.mappingNameEdit->text().trimmed(), ui.mappingDimensionCombo->currentIndex() + 1, @@ -2455,7 +2865,16 @@ QWidget *MainWindow::createAgvPage() ui.streamIncrementalCheck->isChecked()); }); 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_agvMappingStateLabel->setText(QStringLiteral("地图流已停止")); + m_agvMapView->setStreamMessage(QStringLiteral("地图流已停止")); }); 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.startMapStreamButton << ui.stopMapStreamButton << 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; } diff --git a/src/robotclient.cpp b/src/robotclient.cpp index 22ffe89..3968ec3 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -1,13 +1,17 @@ #include "robotclient.h" +#include "agvmaprasterizer.h" +#include "seeragvmapclient.h" #include "videodecoder.h" #include "tcpjogcontroller.h" #include #include +#include #include #include #include #include +#include #include #include #include @@ -33,6 +37,7 @@ #include #include #include +#include #include #include "cmvr/api/agv_command.pb.h" #include "cmvr/api/agv_service.grpc.pb.h" @@ -50,9 +55,24 @@ #include "cmvr/api/speaker_service.grpc.pb.h" #include "cmvr/api/system_command.pb.h" #include "cmvr/api/system_service.grpc.pb.h" +#include "cmvr/config/agv_config/agv_config.pb.h" #endif namespace { +QString agvStationDisplayName(QString description, const QString &id, + bool decodeJson = false) +{ + // Unified properties may carry the original SMAP value as a JSON string. + if (decodeJson) { + const QJsonDocument json = QJsonDocument::fromJson( + (QLatin1Char('[') + description + QLatin1Char(']')).toUtf8()); + if (json.isArray() && json.array().size() == 1 && json.array().first().isString()) + description = json.array().first().toString(); + } + description = description.trimmed(); + return description.isEmpty() ? id : description; +} + #ifdef CMVR_WITH_GRPC constexpr int kGrpcMaxMessageBytes = 64 * 1024 * 1024; constexpr int kArmMotionTimeoutMs = 120000; @@ -79,6 +99,141 @@ std::shared_ptr createGrpcChannel(const std::string &endpoint) return grpc::CreateCustomChannel(endpoint, grpc::InsecureChannelCredentials(), arguments); } +// The map-only configuration lookup owns a separate channel. It never changes +// the configuration editor's connection or writes a configuration file. +class DirectMapRpcCancellation +{ +public: + DirectMapRpcCancellation(grpc::ClientContext &context, + const std::shared_ptr> &cancel) + : m_thread([this, &context, cancel]() { + std::unique_lock lock(m_mutex); + while (!m_finished) { + if (cancel->load()) { + context.TryCancel(); + return; + } + m_condition.wait_for(lock, std::chrono::milliseconds(20)); + } + }) {} + ~DirectMapRpcCancellation() + { + { + std::lock_guard lock(m_mutex); + m_finished = true; + } + m_condition.notify_all(); + m_thread.join(); + } +private: + std::mutex m_mutex; + std::condition_variable m_condition; + bool m_finished = false; + std::thread m_thread; +}; + +bool resolveDirectMapConnection(const QString &configHost, int configPort, + const QString &deviceId, + const std::shared_ptr> &cancel, + SeerAgvMapConnection &connection, QString &error) +{ + if (configHost.isEmpty() || configPort < 1 || configPort > 65535) { + error = QStringLiteral("请填写车辆 IP,或设置可用的配置服务地址以读取 AGV 配置"); + return false; + } + const QString host = configHost.contains(QLatin1Char(':')) + && !configHost.startsWith(QLatin1Char('[')) + ? QLatin1Char('[') + configHost + QLatin1Char(']') : configHost; + auto stub = cmvr::api::ConfigurationService::NewStub( + createGrpcChannel(QStringLiteral("%1:%2").arg(host).arg(configPort).toStdString())); + cmvr::api::ListConfigFilesCommand::Request listRequest; + cmvr::api::ListConfigFilesCommand::Feedback listResponse; + grpc::ClientContext listContext; + listContext.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3)); + grpc::Status listStatus; + { + DirectMapRpcCancellation cancellation(listContext, cancel); + listStatus = stub->ListConfigFiles(&listContext, listRequest, &listResponse); + } + if (cancel->load()) { + error = QStringLiteral("地图直连配置读取已取消"); + return false; + } + if (!listStatus.ok() || !listResponse.header().success()) { + error = QStringLiteral("无法读取 AGV 配置列表:%1;可手动填写车辆 IP") + .arg(QString::fromStdString(listStatus.ok() + ? listResponse.header().error_message() : listStatus.error_message())); + return false; + } + int matches = 0; + for (const auto &file : listResponse.files()) { + if (file.message_type() != "cmvr.config.AGVRootConfig") + continue; + cmvr::api::ReadConfigFileCommand::Request readRequest; + readRequest.set_relative_path(file.relative_path()); + cmvr::api::ReadConfigFileCommand::Feedback readResponse; + grpc::ClientContext readContext; + readContext.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3)); + grpc::Status readStatus; + { + DirectMapRpcCancellation cancellation(readContext, cancel); + readStatus = stub->ReadConfigFile(&readContext, readRequest, &readResponse); + } + if (cancel->load()) { + error = QStringLiteral("地图直连配置读取已取消"); + return false; + } + if (!readStatus.ok() || !readResponse.header().success()) { + error = QStringLiteral("无法完整核查 AGV 配置 %1:%2;未连接车辆") + .arg(QString::fromStdString(file.relative_path()), + QString::fromStdString(readStatus.ok() + ? readResponse.header().error_message() : readStatus.error_message())); + return false; + } + cmvr::config::AGVRootConfig root; + if (!google::protobuf::TextFormat::ParseFromString(readResponse.content(), &root)) { + error = QStringLiteral("AGV 配置 %1 解析失败;未连接车辆") + .arg(QString::fromStdString(file.relative_path())); + return false; + } + for (const auto &device : root.agv().agvs()) { + const QString configuredId = QString::fromStdString(device.id()).trimmed(); + if (configuredId != deviceId) + continue; + ++matches; + if (!device.has_seer_robokit_agv()) { + error = QStringLiteral("设备 %1 不是 SEER Robokit,不能使用地图直连").arg(deviceId); + return false; + } + const auto &seer = device.seer_robokit_agv(); + const QString backendId = QString::fromStdString(seer.id()).trimmed(); + if (!backendId.isEmpty() && backendId != deviceId) { + error = QStringLiteral("设备 %1 的内外配置 ID 不一致,未连接车辆").arg(deviceId); + return false; + } + connection.host = QString::fromStdString(seer.ip()).trimmed(); + const int statusPort = seer.port_status() == 0 ? 19204 : seer.port_status(); + const int controlPort = seer.port_control() == 0 ? 19205 : seer.port_control(); + const int mapPort = seer.port_config() == 0 ? 19207 : seer.port_config(); + if (connection.host.isEmpty() || statusPort < 1 || statusPort > 65535 + || controlPort < 1 || controlPort > 65535 || mapPort < 1 || mapPort > 65535) { + error = QStringLiteral("设备 %1 的车辆地址或端口无效,未连接车辆").arg(deviceId); + return false; + } + connection.statusPort = static_cast(statusPort); + connection.controlPort = static_cast(controlPort); + connection.configPort = static_cast(mapPort); + } + } + if (matches != 1) { + error = matches == 0 + ? QStringLiteral("配置中未找到设备 %1 的 SEER 地址;可手动填写车辆 IP").arg(deviceId) + : QStringLiteral("设备 %1 在配置中有多个匹配,未连接车辆").arg(deviceId); + return false; + } + return !cancel->load(); +} + cmvr::api::DeviceType deviceTypeFromKind(cmvr::api::DeviceKind kind, cmvr::api::DeviceType fallback) { @@ -2679,19 +2834,24 @@ public: void agvRefresh(const QString &deviceId) { - if (!ensureConnected(QStringLiteral("AGV Refresh")) || - !ensureDeviceId(QStringLiteral("AGV Refresh"), deviceId)) + if (!ensureConnected(QStringLiteral("AGV Refresh"))) { + emitAgvStateUnavailable(deviceId, QStringLiteral("设备尚未连接")); return; + } + if (!ensureDeviceId(QStringLiteral("AGV Refresh"), deviceId)) { + emitAgvStateUnavailable(deviceId, QStringLiteral("请填写 AGV 设备 ID")); + return; + } if (m_demoMode) { - QVariantMap state; + QVariantMap state = agvContext(deviceId); state.insert(QStringLiteral("connected"), true); state.insert(QStringLiteral("timestamp"), QDateTime::currentMSecsSinceEpoch() / 1000.0); - state.insert(QStringLiteral("mode"), 1); + state.insert(QStringLiteral("mode"), 2); state.insert(QStringLiteral("localized"), true); state.insert(QStringLiteral("moving"), false); state.insert(QStringLiteral("fault"), false); state.insert(QStringLiteral("emergency"), false); - state.insert(QStringLiteral("map"), QStringLiteral("demo_map")); + state.insert(QStringLiteral("map"), demoAgvCurrentMap(deviceId)); state.insert(QStringLiteral("station"), QStringLiteral("HOME")); state.insert(QStringLiteral("battery"), 0.82); state.insert(QStringLiteral("voltage"), 49.2); @@ -2727,7 +2887,7 @@ public: if (stateStatus.ok() && stateResponse.header().success()) { const auto &source = stateResponse.state(); - QVariantMap state; + QVariantMap state = agvContext(deviceId); state.insert(QStringLiteral("connected"), source.connected()); state.insert(QStringLiteral("timestamp"), source.timestamp()); state.insert(QStringLiteral("mode"), source.mode()); @@ -2757,6 +2917,17 @@ public: navigation.insert(QStringLiteral("message"), QString::fromStdString(navResponse.status().message())); } emit agvStateReceived(state, navigation); + } else { + const QString responseError = QString::fromStdString(stateResponse.header().error_message()); + QString detail = responseError.isEmpty() ? QStringLiteral("设备拒绝了状态查询") + : responseError; + if (!stateStatus.ok()) { + const QString message = QString::fromStdString(stateStatus.error_message()); + detail = QStringLiteral("gRPC code %1:%2") + .arg(static_cast(stateStatus.error_code())) + .arg(message.isEmpty() ? QStringLiteral("服务端未返回错误详情") : message); + } + emitAgvStateUnavailable(deviceId, detail); } finish(QStringLiteral("AGV Refresh"), stateStatus, stateResponse.header().success(), QString::fromStdString(stateResponse.header().error_message())); @@ -2889,14 +3060,24 @@ public: #endif } - void agvVelocity(const QString &deviceId, double vx, double vy, double wz) + bool agvVelocity(const QString &deviceId, double vx, double vy, double wz, + QString *resultDetail = nullptr) { - if (!ensureConnected(QStringLiteral("AGV SetVelocity")) || - !ensureDeviceId(QStringLiteral("AGV SetVelocity"), deviceId)) - return; + if (!ensureConnected(QStringLiteral("AGV SetVelocity"))) { + if (resultDetail) + *resultDetail = QStringLiteral("设备尚未连接"); + return false; + } + if (!ensureDeviceId(QStringLiteral("AGV SetVelocity"), deviceId)) { + if (resultDetail) + *resultDetail = QStringLiteral("请在对应服务页填写设备 ID"); + return false; + } if (m_demoMode) { + if (resultDetail) + *resultDetail = QStringLiteral("底盘速度已下发"); emit commandFinished(QStringLiteral("AGV SetVelocity"), true, QStringLiteral("底盘速度已下发")); - return; + return true; } #ifdef CMVR_WITH_GRPC cmvr::api::AgvSetVelocityCommand::Request request; @@ -2908,8 +3089,12 @@ public: grpc::ClientContext context; setDeadline(context, 1200); const grpc::Status status = m_agv->setVelocity(&context, request, &response); - finish(QStringLiteral("AGV SetVelocity"), status, response.header().success(), - QString::fromStdString(response.header().error_message())); + return finishAgvVelocity(QStringLiteral("AGV SetVelocity"), status, response.header().success(), + QString::fromStdString(response.header().error_message()), resultDetail); +#else + if (resultDetail) + *resultDetail = QStringLiteral("当前程序未编译 gRPC 支持"); + return false; #endif } @@ -2957,15 +3142,18 @@ public: !ensureDeviceId(QStringLiteral("AGV Inventory"), deviceId)) return; if (m_demoMode) { - QVariantList stations; - QVariantMap home; - home.insert(QStringLiteral("id"), QStringLiteral("HOME")); - home.insert(QStringLiteral("type"), QStringLiteral("charge")); - home.insert(QStringLiteral("x"), 0.0); - home.insert(QStringLiteral("y"), 0.0); - stations.append(home); - const QStringList maps = {QStringLiteral("demo_map"), QStringLiteral("warehouse")}; - emit agvInventoryReceived(maps, stations); + QStringList maps = {QStringLiteral("demo_map"), QStringLiteral("warehouse")}; + const QString keyPrefix = demoAgvMapKey(deviceId, QString()); + for (auto it = m_demoAgvMapContents.cbegin(); it != m_demoAgvMapContents.cend(); ++it) { + if (it.key().startsWith(keyPrefix)) { + const QString name = it.key().mid(keyPrefix.size()); + if (!maps.contains(name)) + maps.append(name); + } + } + const QVariantList stations = demoAgvStations( + demoAgvMapContent(deviceId, demoAgvCurrentMap(deviceId))); + emit agvInventoryReceived(agvContext(deviceId), maps, stations); emit commandFinished(QStringLiteral("AGV Inventory"), true, QStringLiteral("地图与站点已刷新")); return; } @@ -3001,7 +3189,7 @@ public: stations.append(station); } } - emit agvInventoryReceived(maps, stations); + emit agvInventoryReceived(agvContext(deviceId), maps, stations); } finish(QStringLiteral("AGV Inventory"), mapsStatus, mapsResponse.header().success(), QString::fromStdString(mapsResponse.header().error_message())); @@ -3018,6 +3206,8 @@ public: return; } if (m_demoMode) { + m_demoAgvCurrentMaps.insert(deviceId.trimmed(), mapName.trimmed()); + demoAgvMapContent(deviceId, mapName); emit commandFinished(QStringLiteral("AGV SwitchMap"), true, QStringLiteral("已切换到地图 %1").arg(mapName)); return; @@ -3035,145 +3225,456 @@ public: #endif } - void startAgvMapStream(const QString &deviceId, const QString &mapName, - int dimension, bool snapshot, bool incremental) + void requestAgvMapContent(quint64 requestId, const QString &deviceId, + const QString &mapName) { - if (!ensureConnected(QStringLiteral("AGV StreamMap")) || - !ensureDeviceId(QStringLiteral("AGV StreamMap"), deviceId)) + const QString validationError = agvMapRequestError(deviceId, mapName); + if (!validationError.isEmpty()) { + emit agvMapContentReceived(requestId, deviceId, mapName, QString(), + false, validationError); return; + } + if (m_demoMode) { + emit agvMapContentReceived(requestId, deviceId, mapName, + demoAgvMapContent(deviceId, mapName), true, + QStringLiteral("演示地图已读取")); + return; + } +#ifdef CMVR_WITH_GRPC + if (!m_agv) { + emit agvMapContentReceived(requestId, deviceId, mapName, QString(), + false, QStringLiteral("AGV 服务尚未连接")); + return; + } + cmvr::api::AgvMapCommand::Request request; + fillHeader(request.mutable_header(), deviceId.trimmed(), 4000); + request.set_map_name(mapName.trimmed().toStdString()); + cmvr::api::AgvMapCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 4000); + const grpc::Status status = m_agv->downloadMap(&context, request, &response); + const bool success = status.ok() && response.header().success(); + QString detail = success ? QStringLiteral("地图已读取") + : QString::fromStdString(status.ok() ? response.header().error_message() + : status.error_message()); + if (detail.isEmpty()) + detail = QStringLiteral("读取地图失败,服务端未返回错误详情"); + emit agvMapContentReceived(requestId, deviceId, mapName, + success ? QString::fromStdString(response.content()) : QString(), + success, detail); +#else + emit agvMapContentReceived(requestId, deviceId, mapName, QString(), false, + QStringLiteral("当前程序未编译 gRPC 支持")); +#endif + } + + void saveAgvMapContent(quint64 requestId, const QString &deviceId, + const QString &mapName, const QString &content) + { + const QString validationError = agvMapRequestError(deviceId, mapName); + if (!validationError.isEmpty()) { + emit agvMapSaveFinished(requestId, deviceId, mapName, false, validationError); + return; + } + if (m_demoMode) { + m_demoAgvMapContents.insert(demoAgvMapKey(deviceId, mapName), content); + emit agvMapSaveFinished(requestId, deviceId, mapName, true, + QStringLiteral("演示地图已保存")); + return; + } +#ifdef CMVR_WITH_GRPC + if (!m_agv) { + emit agvMapSaveFinished(requestId, deviceId, mapName, false, + QStringLiteral("AGV 服务尚未连接")); + return; + } + cmvr::api::AgvMapCommand::Request request; + fillHeader(request.mutable_header(), deviceId.trimmed(), 10000); + request.set_map_name(mapName.trimmed().toStdString()); + request.set_content(content.toStdString()); + cmvr::api::AgvMapCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 10000); + const grpc::Status status = m_agv->uploadMap(&context, request, &response); + const bool success = status.ok() && response.header().success(); + QString detail = success ? QStringLiteral("地图已保存") + : QString::fromStdString(status.ok() ? response.header().error_message() + : status.error_message()); + if (detail.isEmpty()) + detail = QStringLiteral("保存地图失败,服务端未返回错误详情"); + emit agvMapSaveFinished(requestId, deviceId, mapName, success, detail); +#else + emit agvMapSaveFinished(requestId, deviceId, mapName, false, + QStringLiteral("当前程序未编译 gRPC 支持")); +#endif + } + + void startAgvMapStream(const QString &deviceId, const QString &mapName, + int dimension, bool snapshot, bool incremental, + quint64 generation, bool preview) + { + QVariantMap sourceContext = agvContext(deviceId); + sourceContext.insert(QStringLiteral("mapId"), mapName.trimmed()); + sourceContext.insert(QStringLiteral("streamGeneration"), generation); + sourceContext.insert(QStringLiteral("preview"), preview); + if (!ensureConnected(QStringLiteral("AGV StreamMap")) || + !ensureDeviceId(QStringLiteral("AGV StreamMap"), deviceId)) { + emit agvMapStreamStateChanged(sourceContext, false, + deviceId.trimmed().isEmpty() ? QStringLiteral("AGV 设备 ID 不能为空") + : QStringLiteral("AGV 尚未连接")); + return; + } stopAgvMapStreamInternal(); + m_agvMapStreamSourceContext = sourceContext; m_agvMapStreamStop.store(false); m_agvMapStreamRunning.store(true); - emit agvMapStreamStateChanged(true, QStringLiteral("正在等待地图数据")); + emit agvMapStreamStateChanged(sourceContext, true, QStringLiteral("正在等待地图数据")); if (m_demoMode) { - QImage image(1280, 720, QImage::Format_RGB32); - image.fill(QColor(QStringLiteral("#eef2f6"))); + const QString demoMap = mapName.trimmed().isEmpty() + ? demoAgvCurrentMap(deviceId) : mapName.trimmed(); + const QJsonObject root = QJsonDocument::fromJson( + demoAgvMapContent(deviceId, demoMap).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 = header.value(QStringLiteral("resolution")).toDouble(0.04); + const double originX = minimum.value(QStringLiteral("x")).toDouble(); + const double originY = minimum.value(QStringLiteral("y")).toDouble(); + const int width = qRound((maximum.value(QStringLiteral("x")).toDouble() - originX) / resolution); + const int height = qRound((maximum.value(QStringLiteral("y")).toDouble() - originY) / resolution); + if (width <= 0 || height <= 0) { + m_agvMapStreamRunning.store(false); + emit agvMapStreamStateChanged(sourceContext, false, QStringLiteral("演示扫描地图资源加载失败")); + return; + } + // The raster and editable SMAP share the same measured scan coordinates. + QImage image(width, height, QImage::Format_ARGB32_Premultiplied); + image.fill(Qt::transparent); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); - painter.setPen(QPen(QColor(QStringLiteral("#d3dde6")), 1)); - for (int x = 60; x < image.width(); x += 80) - painter.drawLine(x, 30, x, image.height() - 30); - for (int y = 40; y < image.height(); y += 60) - painter.drawLine(30, y, image.width() - 30, y); - const QVector stations = { - QPointF(180, 160), QPointF(460, 220), QPointF(760, 150), - QPointF(1050, 260), QPointF(850, 500), QPointF(400, 540) - }; - for (int i = 1; i < stations.size(); ++i) { - painter.setPen(QPen(QColor(QStringLiteral("#9db7ce")), 4)); - painter.drawLine(stations.at(i - 1), stations.at(i)); + painter.setPen(QPen(QColor(107, 125, 140, 210), 1.3, + Qt::SolidLine, Qt::RoundCap)); + for (const QJsonValue &value : root.value(QStringLiteral("normal_pos_list")).toArray()) { + const QJsonObject point = value.toObject(); + painter.drawPoint(QPointF( + (point.value(QStringLiteral("x")).toDouble() - originX) / resolution, + height - (point.value(QStringLiteral("y")).toDouble() - originY) / resolution)); } - for (int i = 0; i < stations.size(); ++i) { - painter.setPen(Qt::NoPen); - painter.setBrush(QColor(QStringLiteral("#218c74"))); - painter.drawEllipse(stations.at(i), 11, 11); - painter.setPen(QColor(QStringLiteral("#26323d"))); - painter.drawText(stations.at(i) + QPointF(15, -10), - QStringLiteral("STATION_%1").arg(i + 1)); - } - painter.setBrush(QColor(QStringLiteral("#237ddd"))); - painter.setPen(Qt::NoPen); - QPolygonF robot; - robot << QPointF(290, 320) << QPointF(260, 338) - << QPointF(260, 302); - painter.drawPolygon(robot); painter.end(); - QVariantMap metadata; - metadata.insert(QStringLiteral("mapId"), QStringLiteral("demo_map")); + QVariantMap metadata = sourceContext; + metadata.insert(QStringLiteral("mapId"), demoMap); metadata.insert(QStringLiteral("dimension"), 2); - metadata.insert(QStringLiteral("originX"), 0.0); - metadata.insert(QStringLiteral("originY"), 0.0); + metadata.insert(QStringLiteral("originX"), originX); + metadata.insert(QStringLiteral("originY"), originY); metadata.insert(QStringLiteral("originTheta"), 0.0); - metadata.insert(QStringLiteral("resolution"), 0.01); + metadata.insert(QStringLiteral("resolution"), resolution); metadata.insert(QStringLiteral("sourceWidth"), image.width()); metadata.insert(QStringLiteral("sourceHeight"), image.height()); metadata.insert(QStringLiteral("renderScale"), 1.0); + metadata.insert(QStringLiteral("demo"), true); metadata.insert(QStringLiteral("timestamp"), QDateTime::currentMSecsSinceEpoch() / 1000.0); - emit agvMapFrameReceived(image, metadata, - QStringLiteral("演示 2D 地图 · 6 个站点")); + emit agvMapFrameReceived(image, metadata, QStringLiteral("演示扫描地图 · Demo")); return; } #ifdef CMVR_WITH_GRPC m_agvMapStreamThread = std::thread( - [this, deviceId, mapName, dimension, snapshot, incremental]() { + [this, deviceId, mapName, dimension, snapshot, incremental, sourceContext, preview]() { cmvr::api::AgvMapStreamCommand::Request request; fillHeader(request.mutable_header(), deviceId); request.set_map_name(mapName.toStdString()); request.set_dimension(static_cast(dimension)); request.set_snapshot(snapshot); - request.set_incremental(incremental); + request.set_incremental(preview ? false : incremental); request.set_max_chunk_bytes(1024 * 1024); grpc::ClientContext context; { std::lock_guard lock(m_agvMapStreamContextMutex); m_agvMapStreamContext = &context; + // Stop may run before this thread publishes its context. + // Check under the same lock used by Stop so cancellation is + // remembered even when no RPC existed at that point. + if (m_agvMapStreamStop.load()) + context.TryCancel(); + } + QString streamError; + QString rawMapId; + QString rawAttemptId; + QString rawAttemptError; + QImage rawMapImage; + QVariantMap rawMapMetadata; + bool frameDelivered = false; + bool incompleteReported = false; + const auto readRawMap = [&](const QString &actualMap) { + if (rawMapId == actualMap) + return true; + if (rawAttemptId == actualMap) + return false; + rawAttemptId = actualMap; + rawAttemptError.clear(); + emit agvMapStreamStateChanged(sourceContext, true, + QStringLiteral("正在读取地图 %1…").arg(actualMap)); + cmvr::api::AgvMapCommand::Request rawRequest; + fillHeader(rawRequest.mutable_header(), deviceId.trimmed(), 4000); + rawRequest.set_map_name(actualMap.toStdString()); + cmvr::api::AgvMapCommand::Feedback rawResponse; + grpc::ClientContext rawContext; + setDeadline(rawContext, 4000); + const grpc::Status rawStatus = m_agv->downloadMap( + &rawContext, rawRequest, &rawResponse); + if (!rawStatus.ok() || !rawResponse.header().success()) { + rawAttemptError = QStringLiteral("读取地图 %1 失败:%2").arg(actualMap, + QString::fromStdString(rawStatus.ok() + ? rawResponse.header().error_message() : rawStatus.error_message())); + return false; + } + QString renderError; + if (!renderAgvSmap2d(QString::fromStdString(rawResponse.content()), + rawMapImage, rawMapMetadata, renderError)) { + rawAttemptError = QStringLiteral("地图 %1 无法显示:%2").arg(actualMap, renderError); + return false; + } + const QString returnedMap = rawMapMetadata.value(QStringLiteral("mapId")).toString(); + if (!returnedMap.isEmpty() && returnedMap != actualMap) { + rawAttemptError = QStringLiteral("请求地图 %1,车端却返回了 %2").arg(actualMap, returnedMap); + return false; + } + rawMapId = actualMap; + return true; + }; + // A selected saved map can be displayed even when the vehicle's + // live stream is silent or still reports its previous active map. + const QString selectedMap = mapName.trimmed(); + const bool rawLoaded = dimension == 1 && !selectedMap.isEmpty() && readRawMap(selectedMap); + if (rawLoaded && !m_agvMapStreamStop.load()) { + QVariantMap previewMetadata = rawMapMetadata; + for (auto it = sourceContext.cbegin(); it != sourceContext.cend(); ++it) + previewMetadata.insert(it.key(), it.value()); + previewMetadata.insert(QStringLiteral("mapId"), selectedMap); + previewMetadata.insert(QStringLiteral("timestamp"), QDateTime::currentMSecsSinceEpoch() / 1000.0); + previewMetadata.insert(QStringLiteral("sequence"), static_cast(0)); + previewMetadata.insert(QStringLiteral("updateType"), + static_cast(cmvr::msgs::AGV_MAP_UPDATE_SNAPSHOT)); + emit agvMapFrameReceived(rawMapImage, previewMetadata, + QStringLiteral("%1 · 2D · 扫描地图").arg(selectedMap)); + frameDelivered = true; + } else if (!rawAttemptError.isEmpty() && !m_agvMapStreamStop.load()) { + // A silent stream must not hide the completed raw-read error. + // Keep reading: legacy servers may still provide a usable grid. + QVariantMap errorContext = sourceContext; + errorContext.insert(QStringLiteral("error"), rawAttemptError); + emit agvMapStreamStateChanged(errorContext, true, + rawAttemptError + QStringLiteral(";等待统一地图数据")); } std::unique_ptr> reader = m_agv->streamMap(&context, request); cmvr::api::AgvMapStreamCommand::Feedback response; while (!m_agvMapStreamStop.load() && reader->Read(&response)) { - if (!response.header().success()) - continue; + if (!response.header().success()) { + streamError = QString::fromStdString(response.header().error_message()); + if (streamError.isEmpty()) + streamError = QStringLiteral("服务端拒绝了地图读取"); + context.TryCancel(); + break; + } const auto &update = response.update(); + if (preview && rawLoaded) { + // Saved-map preview has an independent complete source. + // Live deltas, chunks and grids cannot overwrite that source. + QVariantMap values = rawMapMetadata; + for (auto it = sourceContext.cbegin(); it != sourceContext.cend(); ++it) + values.insert(it.key(), it.value()); + values.insert(QStringLiteral("mapId"), selectedMap); + values.insert(QStringLiteral("streamMapId"), QString::fromStdString(update.map_id())); + values.insert(QStringLiteral("timestamp"), update.timestamp()); + values.insert(QStringLiteral("sequence"), static_cast(update.sequence())); + values.insert(QStringLiteral("updateType"), static_cast(update.update_type())); + values.insert(QStringLiteral("chunkIndex"), static_cast(update.chunk_index())); + values.insert(QStringLiteral("chunkCount"), static_cast(update.chunk_count())); + emit agvMapFrameReceived(rawMapImage, values, + QStringLiteral("%1 · 2D · 扫描地图预览").arg(selectedMap)); + frameDelivered = true; + continue; + } + if (preview && !rawLoaded && !selectedMap.isEmpty() + && QString::fromStdString(update.map_id()) != selectedMap) { + // A failed named download cannot fall back to another + // map's grid or hide its error by marking it delivered. + continue; + } + if (preview && !update.has_map_2d()) { + if (!incompleteReported) { + incompleteReported = true; + emit agvMapStreamStateChanged(sourceContext, true, + rawAttemptError + QStringLiteral(";等待完整的 2D 统一地图")); + } + continue; + } QImage image; - QVariantMap metadata; + QVariantMap metadata = sourceContext; QString detail; if (update.has_map_2d()) { const auto &map = update.map_2d(); const int sourceWidth = static_cast(map.width()); const int sourceHeight = static_cast(map.height()); - if (sourceWidth <= 0 || sourceHeight <= 0) + if (sourceWidth <= 0 || sourceHeight <= 0 || map.data_size() == 0) { + // Older services omit camelCase SMAP bounds and scan cells. + // Read the selected device's original map once per stream. + const QString actualMap = mapName.trimmed().isEmpty() + ? QString::fromStdString(update.map_id()).trimmed() : mapName.trimmed(); + if (actualMap.isEmpty()) { + streamError = QStringLiteral("车端返回空地图,且未提供地图名称"); + context.TryCancel(); + break; + } + if (!readRawMap(actualMap)) { + streamError = rawAttemptError; + context.TryCancel(); + break; + } + if (m_agvMapStreamStop.load()) + break; + QVariantMap rawMetadata = rawMapMetadata; + for (auto it = sourceContext.cbegin(); it != sourceContext.cend(); ++it) + rawMetadata.insert(it.key(), it.value()); + rawMetadata.insert(QStringLiteral("mapId"), actualMap); + rawMetadata.insert(QStringLiteral("timestamp"), update.timestamp()); + rawMetadata.insert(QStringLiteral("sequence"), + static_cast(update.sequence())); + rawMetadata.insert(QStringLiteral("updateType"), + static_cast(update.update_type())); + emit agvMapFrameReceived(rawMapImage, rawMetadata, + QStringLiteral("%1 · 2D · 扫描地图").arg(actualMap)); + frameDelivered = true; continue; + } + if (preview && ((update.update_type() != cmvr::msgs::AGV_MAP_UPDATE_UNSPECIFIED + && update.update_type() != cmvr::msgs::AGV_MAP_UPDATE_SNAPSHOT) + || update.chunk_count() > 1 || update.chunk_index() > 0 + || qint64(sourceWidth) * sourceHeight != map.data_size())) { + if (!incompleteReported) { + incompleteReported = true; + emit agvMapStreamStateChanged(sourceContext, true, + rawAttemptError + QStringLiteral(";等待完整单帧地图,已忽略增量或分片数据")); + } + continue; + } const double scale = qMin( 1.0, qMin(1600.0 / sourceWidth, 1000.0 / sourceHeight)); - const int width = qMax(1, qRound(sourceWidth * scale)); - const int height = qMax(1, qRound(sourceHeight * scale)); - image = QImage(width, height, QImage::Format_RGB32); + const int width = qMax(1, qCeil(sourceWidth * scale)); + const int height = qMax(1, qCeil(sourceHeight * scale)); + image = QImage(width, height, QImage::Format_ARGB32_Premultiplied); for (int y = 0; y < height; ++y) { QRgb *line = reinterpret_cast( image.scanLine(height - 1 - y)); const int sourceY = qMin(sourceHeight - 1, qFloor(y / scale)); + const int endY = qMin(sourceHeight, qCeil((y + 1) / scale)); for (int x = 0; x < width; ++x) { const int sourceX = qMin(sourceWidth - 1, qFloor(x / scale)); - const int index = sourceY * sourceWidth + sourceX; - const int value = index < map.data_size() - ? map.data(index) : -1; + const int endX = qMin(sourceWidth, qCeil((x + 1) / scale)); + // Retain thin scanned walls when reducing a large map. + int value = -1; + for (int sy = sourceY; sy < endY; ++sy) + for (int sx = sourceX; sx < endX; ++sx) { + const qint64 index = qint64(sy) * sourceWidth + sx; + if (index < map.data_size()) + value = qMax(value, map.data(static_cast(index))); + } if (value < 0) - line[x] = qRgb(205, 212, 219); + line[x] = qPremultiply(qRgba(203, 213, 225, 35)); else if (value == 0) - line[x] = qRgb(248, 250, 252); - else { - const int shade = qBound(35, 235 - value * 2, 210); - line[x] = qRgb(shade, shade, shade); - } + line[x] = 0; + else + line[x] = qPremultiply(qRgba(107, 125, 140, + qBound(45, 45 + value * 2, 245))); } } QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); const double resolution = map.resolution() > 0.0 ? map.resolution() : 1.0; + QVariantList stations; + QVariantList routes; + const double c = qCos(map.origin().theta()); + const double s = qSin(map.origin().theta()); for (const auto &object : map.objects()) { + const QString objectId = QString::fromStdString(object.id()).trimmed(); + auto classProperty = object.properties().find("class_name"); + if (classProperty == object.properties().end()) + classProperty = object.properties().find("className"); + const QString className = classProperty != object.properties().end() + ? QString::fromStdString(classProperty->second) : QString(); + QVariantList worldPoints; QPolygonF geometry; for (const auto &point : object.points()) { + worldPoints.append(QVariantMap{ + {QStringLiteral("x"), point.x()}, + {QStringLiteral("y"), point.y()}}); + const double dx = point.x() - map.origin().x(); + const double dy = point.y() - map.origin().y(); geometry.append(QPointF( - (point.x() - map.origin().x()) / resolution * scale, - height - (point.y() - map.origin().y()) / - resolution * scale)); + (c * dx + s * dy) / resolution * scale, + height - (-s * dx + c * dy) / resolution * scale)); } + if (geometry.size() == 1 + && (object.type() == cmvr::msgs::AGV_MAP_OBJECT_STATION + || object.type() == cmvr::msgs::AGV_MAP_OBJECT_EXTERNAL_DEVICE)) { + QVariantMap station = worldPoints.first().toMap(); + station.insert(QStringLiteral("id"), objectId); + const auto description = object.properties().find("description"); + station.insert(QStringLiteral("name"), agvStationDisplayName( + description != object.properties().end() + ? QString::fromStdString(description->second) : QString(), objectId, true)); + station.insert(QStringLiteral("theta"), object.heading()); + station.insert(QStringLiteral("type"), className.isEmpty() + ? QStringLiteral("LandMark") : className); + stations.append(station); + continue; + } + const bool navigationPath = className == QStringLiteral("BezierPath") + || className == QStringLiteral("StraightPath") + || className == QStringLiteral("ArcPath"); + if (geometry.size() > 1 && object.type() == cmvr::msgs::AGV_MAP_OBJECT_LINE + && navigationPath) { + // SEER's unified stream carries Bezier control points. + // Sample the curve rather than displaying its control polygon. + if (className == QStringLiteral("BezierPath") && worldPoints.size() > 2) { + const QVariantList controls = worldPoints; + worldPoints.clear(); + for (int sample = 0; sample <= 32; ++sample) { + QVector work; + for (const QVariant &value : controls) { + const QVariantMap point = value.toMap(); + work.append(QPointF(point.value(QStringLiteral("x")).toDouble(), + point.value(QStringLiteral("y")).toDouble())); + } + const double t = sample / 32.0; + for (int count = work.size() - 1; count > 0; --count) + for (int i = 0; i < count; ++i) + work[i] = work.at(i) * (1.0 - t) + work.at(i + 1) * t; + worldPoints.append(QVariantMap{ + {QStringLiteral("x"), work.first().x()}, + {QStringLiteral("y"), work.first().y()}}); + } + } + routes.append(QVariantMap{{QStringLiteral("id"), objectId}, + {QStringLiteral("points"), worldPoints}}); + continue; + } + // Keep non-navigation semantic geometry such as regions and reflectors. painter.setPen(QPen(QColor(QStringLiteral("#218c74")), 2)); - painter.setBrush(QColor(33, 140, 116, 70)); + painter.setBrush(QColor(33, 140, 116, 30)); if (geometry.size() == 1) painter.drawEllipse(geometry.first(), 6, 6); + else if (geometry.size() > 2 && object.type() == cmvr::msgs::AGV_MAP_OBJECT_AREA) + painter.drawPolygon(geometry); else if (geometry.size() > 1) painter.drawPolyline(geometry); - const QString objectId = QString::fromStdString( - object.id()).trimmed(); if (!geometry.isEmpty() && !objectId.isEmpty() && objectId != QStringLiteral("0")) { painter.setPen(QColor(QStringLiteral("#145da8"))); @@ -3182,6 +3683,9 @@ public: } } painter.end(); + metadata.insert(QStringLiteral("stations"), stations); + metadata.insert(QStringLiteral("routes"), routes); + metadata.insert(QStringLiteral("deviceId"), deviceId.trimmed()); metadata.insert(QStringLiteral("mapId"), QString::fromStdString(update.map_id())); metadata.insert(QStringLiteral("dimension"), 2); @@ -3227,6 +3731,7 @@ public: } painter.end(); } + metadata.insert(QStringLiteral("deviceId"), deviceId.trimmed()); metadata.insert(QStringLiteral("mapId"), QString::fromStdString(update.map_id())); metadata.insert(QStringLiteral("dimension"), 3); @@ -3238,9 +3743,13 @@ public: .arg(map.points_size()) .arg(static_cast(update.sequence())); } - if (!image.isNull()) + if (!image.isNull()) { emit agvMapFrameReceived(image, metadata, detail); + frameDelivered = true; + } } + if (m_agvMapStreamStop.load()) + context.TryCancel(); const grpc::Status status = reader->Finish(); { std::lock_guard lock(m_agvMapStreamContextMutex); @@ -3249,17 +3758,21 @@ public: m_agvMapStreamRunning.store(false); const QString detail = m_agvMapStreamStop.load() ? QStringLiteral("地图流已停止") + : !streamError.isEmpty() ? streamError + : !frameDelivered && !rawAttemptError.isEmpty() ? rawAttemptError : status.ok() ? QStringLiteral("地图流已结束") : QString::fromStdString(status.error_message()); - emit agvMapStreamStateChanged(false, detail); + emit agvMapStreamStateChanged(sourceContext, false, detail); }); #endif } - void stopAgvMapStream() + void stopAgvMapStream(quint64 generation) { stopAgvMapStreamInternal(); - emit agvMapStreamStateChanged(false, QStringLiteral("地图流已停止")); + QVariantMap context = m_agvMapStreamSourceContext; + context.insert(QStringLiteral("streamGeneration"), generation); + emit agvMapStreamStateChanged(context, false, QStringLiteral("地图流已停止")); } void invokeRpc(const QString &serviceName, const QString &methodName, @@ -3467,10 +3980,14 @@ public: cameraStreamStateChangedForCamera; std::function cameraRecordingStateChanged; std::function agvStateReceived; - std::function agvInventoryReceived; + std::function agvInventoryReceived; + std::function agvMapContentReceived; + std::function agvMapSaveFinished; std::function agvMapFrameReceived; - std::function agvMapStreamStateChanged; + std::function agvMapStreamStateChanged; std::function rpcFinished; std::function audioStreamStateChanged; std::function audioStreamStatistics; @@ -3840,6 +4357,77 @@ private: #endif } + QString agvMapRequestError(const QString &deviceId, const QString &mapName) const + { + if (deviceId.trimmed().isEmpty()) + return QStringLiteral("AGV 设备 ID 不能为空"); + if (mapName.trimmed().isEmpty()) + return QStringLiteral("地图名称不能为空"); + if (!m_connected) + return QStringLiteral("设备尚未连接"); + return QString(); + } + + static QString demoAgvMapKey(const QString &deviceId, const QString &mapName) + { + const QString device = deviceId.trimmed(); + return QString::number(device.size()) + QLatin1Char(':') + device + mapName.trimmed(); + } + + QString demoAgvCurrentMap(const QString &deviceId) const + { + return m_demoAgvCurrentMaps.value(deviceId.trimmed(), QStringLiteral("demo_map")); + } + + QString demoAgvMapContent(const QString &deviceId, const QString &mapName) + { + const QString key = demoAgvMapKey(deviceId, mapName); + const auto existing = m_demoAgvMapContents.constFind(key); + if (existing != m_demoAgvMapContents.cend()) + return existing.value(); + QFile sample(QStringLiteral(":/assets/agv/demo_scan.smap")); + if (!sample.open(QIODevice::ReadOnly)) + return QString(); + QJsonObject root = QJsonDocument::fromJson(sample.readAll()).object(); + QJsonObject header = root.value(QStringLiteral("header")).toObject(); + header.insert(QStringLiteral("map_name"), mapName.trimmed()); + root.insert(QStringLiteral("header"), header); + const QString content = QString::fromUtf8(QJsonDocument(root).toJson(QJsonDocument::Indented)); + m_demoAgvMapContents.insert(key, content); + return content; + } + + static QVariantList demoAgvStations(const QString &content) + { + const QJsonObject root = QJsonDocument::fromJson(content.toUtf8()).object(); + const QJsonArray points = root.contains(QStringLiteral("advanced_point_list")) + ? root.value(QStringLiteral("advanced_point_list")).toArray() + : root.value(QStringLiteral("advancedPointList")).toArray(); + QVariantList stations; + for (const auto &value : points) { + const QJsonObject point = value.toObject(); + const QString className = point.value(QStringLiteral("class_name")).toString( + point.value(QStringLiteral("className")).toString()); + const QString id = point.value(QStringLiteral("instance_name")).toString( + point.value(QStringLiteral("instanceName")).toString()); + if (className.compare(QStringLiteral("LandMark"), Qt::CaseInsensitive) != 0 + || id.trimmed().isEmpty()) + continue; + const QJsonObject position = point.value(QStringLiteral("pos")).toObject(); + QVariantMap station; + station.insert(QStringLiteral("id"), id); + station.insert(QStringLiteral("name"), agvStationDisplayName( + point.value(QStringLiteral("description")).toString(), id)); + station.insert(QStringLiteral("type"), className); + station.insert(QStringLiteral("description"), point.value(QStringLiteral("description")).toString()); + station.insert(QStringLiteral("x"), position.value(QStringLiteral("x")).toDouble()); + station.insert(QStringLiteral("y"), position.value(QStringLiteral("y")).toDouble()); + station.insert(QStringLiteral("theta"), point.value(QStringLiteral("dir")).toDouble()); + stations.append(station); + } + return stations; + } + bool ensureConnected(const QString &command) { if (m_connected) @@ -3856,6 +4444,22 @@ private: return false; } + QVariantMap agvContext(const QString &deviceId) const + { + return {{QStringLiteral("deviceId"), deviceId.trimmed()}, + {QStringLiteral("endpoint"), QStringLiteral("%1:%2").arg(m_host).arg(m_port)}, + {QStringLiteral("demo"), m_demoMode}, + {QStringLiteral("available"), true}}; + } + + void emitAgvStateUnavailable(const QString &deviceId, const QString &detail) + { + QVariantMap state = agvContext(deviceId); + state.insert(QStringLiteral("available"), false); + state.insert(QStringLiteral("error"), detail); + emit agvStateReceived(state, QVariantMap()); + } + void pollDemo() { ++m_tick; @@ -4566,6 +5170,28 @@ private: emit logMessage(terminalError.isEmpty() ? QStringLiteral("INFO") : QStringLiteral("ERROR"), summary); } + bool finishAgvVelocity(const QString &command, const grpc::Status &status, bool responseSuccess, + const QString &responseError, QString *resultDetail = nullptr) + { + const bool success = status.ok() && responseSuccess; + QString detail; + if (!status.ok()) { + const QString message = QString::fromStdString(status.error_message()); + detail = QStringLiteral("gRPC code %1:%2") + .arg(static_cast(status.error_code())) + .arg(message.isEmpty() ? QStringLiteral("服务端未返回错误详情") + : message); + } + else if (!responseSuccess) + detail = responseError.isEmpty() ? QStringLiteral("设备拒绝了命令") : responseError; + else + detail = QStringLiteral("命令执行成功"); + if (resultDetail) + *resultDetail = detail; + emit commandFinished(command, success, detail); + return success; + } + void finish(const QString &command, const grpc::Status &status, bool responseSuccess, const QString &responseError) { @@ -4869,17 +5495,27 @@ private: std::atomic m_agvMapStreamRunning{false}; std::atomic m_agvMapStreamStop{false}; std::thread m_agvMapStreamThread; + QVariantMap m_agvMapStreamSourceContext; + QHash m_demoAgvMapContents; + QHash m_demoAgvCurrentMaps; QVector m_demoTargets; }; RobotClient::RobotClient(QObject *parent) : QObject(parent), m_worker(new BackendWorker) { + m_agvMapDirectWorker = new QObject; + m_agvMapDirectWorker->moveToThread(&m_agvMapDirectThread); + connect(&m_agvMapDirectThread, &QThread::finished, + m_agvMapDirectWorker, &QObject::deleteLater); + m_agvMapDirectThread.start(); qRegisterMetaType("QImage"); qRegisterMetaType("VideoFrame"); m_worker->connectionChanged = [this](bool connected, int latencyMs, const QString &detail) { QMetaObject::invokeMethod(this, [this, connected, latencyMs, detail]() { + if (!connected) + interruptAgvManualVelocity(); emit connectionChanged(connected, latencyMs, detail); }, Qt::QueuedConnection); }; @@ -5031,20 +5667,49 @@ RobotClient::RobotClient(QObject *parent) emit agvStateReceived(state, navigation); }, Qt::QueuedConnection); }; - m_worker->agvInventoryReceived = [this](const QStringList &maps, const QVariantList &stations) { - QMetaObject::invokeMethod(this, [this, maps, stations]() { + m_worker->agvInventoryReceived = [this](const QVariantMap &context, + const QStringList &maps, const QVariantList &stations) { + QMetaObject::invokeMethod(this, [this, context, maps, stations]() { emit agvInventoryReceived(maps, stations); + emit agvInventoryReceivedForContext(context, maps, stations); }, Qt::QueuedConnection); }; + m_worker->agvMapContentReceived = + [this](quint64 requestId, const QString &deviceId, const QString &mapName, + const QString &content, bool success, const QString &detail) { + QMetaObject::invokeMethod( + this, [this, requestId, deviceId, mapName, content, success, detail]() { + emit agvMapContentReceived(requestId, deviceId, mapName, content, success, detail); + }, Qt::QueuedConnection); + }; + m_worker->agvMapSaveFinished = + [this](quint64 requestId, const QString &deviceId, const QString &mapName, + bool success, const QString &detail) { + QMetaObject::invokeMethod( + this, [this, requestId, deviceId, mapName, success, detail]() { + emit agvMapSaveFinished(requestId, deviceId, mapName, success, detail); + }, Qt::QueuedConnection); + }; m_worker->agvMapFrameReceived = [this](const QImage &image, const QVariantMap &metadata, const QString &detail) { QMetaObject::invokeMethod(this, [this, image, metadata, detail]() { + if (metadata.value(QStringLiteral("streamGeneration")).toULongLong() + != agvMapStreamGeneration()) + return; emit agvMapFrameReceived(image, metadata, detail); }, Qt::QueuedConnection); }; - m_worker->agvMapStreamStateChanged = [this](bool running, const QString &detail) { - QMetaObject::invokeMethod(this, [this, running, detail]() { + m_worker->agvMapStreamStateChanged = [this](const QVariantMap &context, bool running, const QString &detail) { + QMetaObject::invokeMethod(this, [this, context, running, detail]() { + if (context.value(QStringLiteral("streamGeneration")).toULongLong() + != agvMapStreamGeneration()) + return; + emit agvMapStreamStateChangedForContext(context, running, detail); + // A contextual receiver may restart the stream synchronously. + if (context.value(QStringLiteral("streamGeneration")).toULongLong() + != agvMapStreamGeneration()) + return; emit agvMapStreamStateChanged(running, detail); }, Qt::QueuedConnection); }; @@ -5205,10 +5870,53 @@ RobotClient::RobotClient(QObject *parent) connect(this, &RobotClient::agvNavigatePoseRequested, m_worker, &BackendWorker::agvNavigatePose); connect(this, &RobotClient::agvNavigateStationRequested, m_worker, &BackendWorker::agvNavigateStation); connect(this, &RobotClient::agvFollowPathRequested, m_worker, &BackendWorker::agvFollowPath); - connect(this, &RobotClient::agvVelocityRequested, m_worker, &BackendWorker::agvVelocity); + connect(this, &RobotClient::agvVelocityRequested, m_worker, + [this](const QString &deviceId, double vx, double vy, double wz) { + m_worker->agvVelocity(deviceId, vx, vy, wz); + }); + connect(this, &RobotClient::agvManualVelocityRequested, this, + [this](quint64 requestId, const QString &deviceId, double vx, double vy, double wz) { + if (m_agvManualBusy) { + emit agvManualVelocityFinished(requestId, false, + QStringLiteral("上一条手动速度尚未完成,本次请求未排队")); + return; + } + m_agvManualBusy = true; + const auto generationState = m_agvManualGeneration; + const quint64 generation = generationState->load(); + QElapsedTimer queuedAt; + queuedAt.start(); + QMetaObject::invokeMethod(m_worker, + [this, requestId, deviceId, vx, vy, wz, generationState, generation, queuedAt]() { + bool success = false; + QString detail; + // Never read GUI-owned state from this worker. Cancellation + // invalidates a queued packet before its RPC may begin. + if (generationState->load() != generation) + detail = QStringLiteral("手动速度已取消,未下发"); + else if (queuedAt.elapsed() > 300) + detail = QStringLiteral("手动速度排队超过 300 ms,已丢弃"); + else + success = m_worker->agvVelocity(deviceId, vx, vy, wz, &detail); + QMetaObject::invokeMethod(this, + [this, requestId, generationState, generation, success, detail]() { + // Keep physical single-flight admission locked even + // after cancel until this worker has actually left. + m_agvManualBusy = false; + const bool current = generationState->load() == generation; + emit agvManualVelocityFinished(requestId, current && success, + current ? detail : QStringLiteral( + "手动速度上下文已取消;若已发出,结果不再用于推进速度")); + }, Qt::QueuedConnection); + }, Qt::QueuedConnection); + }, Qt::DirectConnection); connect(this, &RobotClient::agvActionRequested, m_worker, &BackendWorker::agvAction); connect(this, &RobotClient::agvInventoryRequested, m_worker, &BackendWorker::agvInventory); connect(this, &RobotClient::agvSwitchMapRequested, m_worker, &BackendWorker::agvSwitchMap); + connect(this, &RobotClient::agvMapContentRequested, + m_worker, &BackendWorker::requestAgvMapContent, Qt::QueuedConnection); + connect(this, &RobotClient::agvMapSaveRequested, + m_worker, &BackendWorker::saveAgvMapContent, Qt::QueuedConnection); connect(this, &RobotClient::agvMapStreamStartRequested, m_worker, &BackendWorker::startAgvMapStream); connect(this, &RobotClient::agvMapStreamStopRequested, @@ -5243,6 +5951,12 @@ RobotClient::RobotClient(QObject *parent) RobotClient::~RobotClient() { + cancelAgvManualVelocity(); + cancelAgvMapDirect(false); + m_agvMapDirectThread.quit(); + // All network waits are bounded and observe the cancellation token. Join + // before destroying callbacks which still refer to this client. + m_agvMapDirectThread.wait(); if (m_thread.isRunning()) { QMetaObject::invokeMethod(m_worker, [this]() { m_worker->disconnectConfigurationServer(); @@ -5262,12 +5976,27 @@ bool RobotClient::grpcAvailable() const #endif } +quint64 RobotClient::agvMapStreamGeneration() const +{ + return m_agvMapStreamGeneration.load(); +} + void RobotClient::connectToServer(const QString &host, int port, bool demoMode) { + interruptAgvManualVelocity(); + cancelAgvMapDirect(); + m_agvMapDirectDemo = demoMode; + ++m_agvMapStreamGeneration; emit connectRequested(host, port, demoMode); } -void RobotClient::disconnectFromServer() { emit disconnectRequested(); } +void RobotClient::disconnectFromServer() +{ + interruptAgvManualVelocity(); + cancelAgvMapDirect(); + ++m_agvMapStreamGeneration; + emit disconnectRequested(); +} void RobotClient::setArmTelemetry(const QString &deviceId, bool enabled) { emit armTelemetryRequested(deviceId, enabled); @@ -5442,49 +6171,367 @@ void RobotClient::stopCameraRecording(const QString &cameraId) emit cameraRecordingStopRequested(cameraId); } void RobotClient::requestSystemRefresh() { emit systemRefreshRequested(); } -void RobotClient::requestSystemStopAll(const QString &deviceId) { emit systemStopAllRequested(deviceId); } -void RobotClient::requestAgvRefresh(const QString &deviceId) { emit agvRefreshRequested(deviceId); } +void RobotClient::requestSystemStopAll(const QString &deviceId) +{ + interruptAgvManualVelocity(false); + cancelAgvMapDirect(); + emit systemStopAllRequested(deviceId); +} +void RobotClient::requestAgvRefresh(const QString &deviceId) +{ + observeAgvMapDirectDevice(deviceId); + emit agvRefreshRequested(deviceId); +} void RobotClient::requestAgvRelocalize(const QString &deviceId, double x, double y, double theta) { + interruptAgvManualVelocity(); + observeAgvMapDirectDevice(deviceId); + if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV Relocalize"))) + return; emit agvRelocalizeRequested(deviceId, x, y, theta); } void RobotClient::requestAgvNavigatePose(const QString &deviceId, double x, double y, double theta, double maxSpeed) { + interruptAgvManualVelocity(); + observeAgvMapDirectDevice(deviceId); + if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV NavigateToPose"))) + return; emit agvNavigatePoseRequested(deviceId, x, y, theta, maxSpeed); } void RobotClient::requestAgvNavigateStation(const QString &deviceId, const QString &stationId, double maxSpeed) { + interruptAgvManualVelocity(); + observeAgvMapDirectDevice(deviceId); + if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV NavigateToStation"))) + return; emit agvNavigateStationRequested(deviceId, stationId, maxSpeed); } void RobotClient::requestAgvFollowPath(const QString &deviceId, const QVariantList &path, double maxSpeed) { + interruptAgvManualVelocity(); + observeAgvMapDirectDevice(deviceId); + if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV FollowPath"))) + return; emit agvFollowPathRequested(deviceId, path, maxSpeed); } void RobotClient::requestAgvVelocity(const QString &deviceId, double vx, double vy, double wz) { + interruptAgvManualVelocity(); + observeAgvMapDirectDevice(deviceId); + if (vx == 0.0 && vy == 0.0 && wz == 0.0) + cancelAgvMapDirect(); + else if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV SetVelocity"))) + return; emit agvVelocityRequested(deviceId, vx, vy, wz); } + +void RobotClient::beginAgvManualControl(const QString &deviceId) +{ + // Synchronize device context before the UI marks a fresh hold active. + // This is local bookkeeping only; it never sends a robot command. + observeAgvMapDirectDevice(deviceId); +} + +void RobotClient::requestAgvManualVelocity(quint64 requestId, const QString &deviceId, + double vx, double vy, double wz) +{ + const quint64 contextGeneration = m_agvManualGeneration->load(); + observeAgvMapDirectDevice(deviceId); + // A device-change observer may synchronously end the held UI control. + // Do not admit the remainder of that canceled call in the new generation. + if (m_agvManualGeneration->load() != contextGeneration) { + emit agvManualVelocityFinished(requestId, false, + QStringLiteral("手动控制上下文已变更,本次速度未下发")); + return; + } + if (deviceId.trimmed().isEmpty() || !qIsFinite(vx) || !qIsFinite(vy) || !qIsFinite(wz)) { + emit agvManualVelocityFinished(requestId, false, + QStringLiteral("手动速度需要有效设备 ID 和有限数值")); + return; + } + if (m_agvMapDirectBusy || m_agvManualBusy || !m_thread.isRunning()) { + emit agvManualVelocityFinished(requestId, false, + m_agvMapDirectBusy ? QStringLiteral("地图直连操作进行中,手动速度未下发") + : QStringLiteral("速度通道忙或已停止,本次请求未排队")); + return; + } + emit agvManualVelocityRequested(requestId, deviceId, vx, vy, wz); +} + +void RobotClient::cancelAgvManualVelocity() +{ + m_agvManualGeneration->fetch_add(1); +} + +void RobotClient::interruptAgvManualVelocity(bool requestStop) +{ + cancelAgvManualVelocity(); + emit agvManualControlInterrupted(requestStop); +} + void RobotClient::requestAgvAction(const QString &deviceId, const QString &action) { + interruptAgvManualVelocity(action != QStringLiteral("EmergencyStop") + && action != QStringLiteral("StopVelocity")); + observeAgvMapDirectDevice(deviceId); + const bool stopAction = action == QStringLiteral("EmergencyStop") + || action == QStringLiteral("StopVelocity") || action == QStringLiteral("Pause") + || action == QStringLiteral("Cancel") || action == QStringLiteral("StopMapping"); + if (stopAction) + cancelAgvMapDirect(); + else if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV %1").arg(action))) + return; emit agvActionRequested(deviceId, action); } -void RobotClient::requestAgvInventory(const QString &deviceId) { emit agvInventoryRequested(deviceId); } +void RobotClient::requestAgvInventory(const QString &deviceId) +{ + observeAgvMapDirectDevice(deviceId); + emit agvInventoryRequested(deviceId); +} + +void RobotClient::configureAgvMapDirect(bool enabled, const QString &vehicleHost, + const QString &configHost, int configPort) +{ + const QString host = vehicleHost.trimmed(); + const QString configurationHost = configHost.trimmed(); + if (m_agvMapDirectEnabled == enabled && m_agvMapDirectHost == host + && m_agvMapDirectConfigHost == configurationHost + && m_agvMapDirectConfigPort == configPort) + return; + cancelAgvMapDirect(); + m_agvMapDirectEnabled = enabled; + m_agvMapDirectHost = host; + m_agvMapDirectConfigHost = configurationHost; + m_agvMapDirectConfigPort = configPort; +} + +void RobotClient::cancelAgvMapDirectRequests() +{ + cancelAgvMapDirect(); +} + +void RobotClient::observeAgvMapDirectDevice(const QString &deviceId) +{ + const QString id = deviceId.trimmed(); + if (m_agvMapDirectDevice == id) + return; + if (!m_agvMapDirectDevice.isEmpty() || m_agvManualBusy) + interruptAgvManualVelocity(); + cancelAgvMapDirect(); + m_agvMapDirectDevice = id; +} + +void RobotClient::cancelAgvMapDirect(bool reportCancellation) +{ + ++m_agvMapDirectGeneration; + if (!m_agvMapDirectCancel || m_agvMapDirectCancel->exchange(true)) + return; + if (!reportCancellation) + return; + const QString detail = QStringLiteral("地图直连操作已取消;若命令已发送,车端结果待核查,未自动重试"); + if (m_agvMapDirectOperation == DirectMapOperation::Read) + emit agvMapContentReceived(m_agvMapDirectRequestId, m_agvMapDirectRequestDevice, + m_agvMapDirectRequestMap, QString(), false, detail); + else if (m_agvMapDirectOperation == DirectMapOperation::Save) + emit agvMapSaveFinished(m_agvMapDirectRequestId, m_agvMapDirectRequestDevice, + m_agvMapDirectRequestMap, false, detail); + else + emit commandFinished(QStringLiteral("AGV SwitchMap"), false, detail); + // Keep the physical worker busy until it has left the socket operation. + // Changing context must never queue another write behind a cancelled one. +} + +bool RobotClient::rejectAgvWhileMapDirectBusy(const QString &command) +{ + if (!m_agvMapDirectBusy) + return false; + emit commandFinished(command, false, + QStringLiteral("地图直连操作进行中,请结束后再执行;停止和急停仍可使用")); + return true; +} + +void RobotClient::requestAgvMapDirect(DirectMapOperation operation, quint64 requestId, + const QString &deviceId, const QString &mapName, + const QString &content) +{ + const auto reportFailure = [this, operation, requestId, deviceId, mapName](const QString &detail) { + if (operation == DirectMapOperation::Read) + emit agvMapContentReceived(requestId, deviceId, mapName, QString(), false, detail); + else if (operation == DirectMapOperation::Save) + emit agvMapSaveFinished(requestId, deviceId, mapName, false, detail); + else + emit commandFinished(QStringLiteral("AGV SwitchMap"), false, detail); + }; + if (deviceId.trimmed().isEmpty() || mapName.trimmed().isEmpty()) { + reportFailure(QStringLiteral("AGV 设备 ID 和地图名称不能为空")); + return; + } + if (m_agvMapDirectBusy) { + reportFailure(QStringLiteral("已有地图直连操作进行中,本次请求未发送,请稍后重试")); + return; + } + const QString vehicleHost = m_agvMapDirectHost; + const QString configHost = m_agvMapDirectConfigHost; + const int configPort = m_agvMapDirectConfigPort; + const QString id = deviceId.trimmed(); + const QString map = mapName.trimmed(); + m_agvMapDirectBusy = true; + // The UI stops any held manual-motion timer synchronously here. Its stop + // command joins the backend queue before the barrier below. Do not create + // this operation's cancellation token until that preparatory stop returns. + emit agvMapDirectBusyChanged(true); + interruptAgvManualVelocity(); + if (!m_agvMapDirectEnabled || m_agvMapDirectDemo || m_agvMapDirectDevice != id + || m_agvMapDirectHost != vehicleHost || m_agvMapDirectConfigHost != configHost + || m_agvMapDirectConfigPort != configPort) { + m_agvMapDirectBusy = false; + emit agvMapDirectBusyChanged(false); + reportFailure(QStringLiteral("地图直连上下文已变更,本次请求未发送")); + return; + } + const quint64 generation = m_agvMapDirectGeneration; + const auto cancel = std::make_shared>(false); + m_agvMapDirectCancel = cancel; + m_agvMapDirectOperation = operation; + m_agvMapDirectRequestId = requestId; + m_agvMapDirectRequestDevice = deviceId; + m_agvMapDirectRequestMap = mapName; + const auto runDirect = + [this, operation, requestId, deviceId, mapName, content, generation, cancel, + vehicleHost, configHost, configPort, id, map]() { + SeerAgvMapConnection connection; + connection.host = vehicleHost; + connection.nickName = QStringLiteral("CMVRControlStation-map-%1").arg(id); + QString lookupError; + bool resolved = !connection.host.isEmpty(); +#ifdef CMVR_WITH_GRPC + if (!resolved && !cancel->load()) + resolved = resolveDirectMapConnection(configHost, configPort, id, + cancel, connection, lookupError); +#else + Q_UNUSED(configHost) + Q_UNUSED(configPort) + if (!resolved) + lookupError = QStringLiteral("当前程序未编译 gRPC 支持,请手动填写车辆 IP"); +#endif + SeerAgvMapResult result; + if (cancel->load()) + result.detail = QStringLiteral("地图直连操作已取消"); + else if (!resolved) + result.detail = lookupError; + else { + const auto cancelled = [cancel]() { return cancel->load(); }; + if (operation == DirectMapOperation::Read) + result = SeerAgvMapClient::readMap(connection, map, cancelled); + else if (operation == DirectMapOperation::Save) + result = SeerAgvMapClient::saveMap(connection, map, content, cancelled); + else + result = SeerAgvMapClient::switchMap(connection, map, cancelled); + } + QMetaObject::invokeMethod(this, + [this, operation, requestId, deviceId, mapName, map, generation, cancel, result]() { + if (m_agvMapDirectCancel != cancel) + return; + m_agvMapDirectCancel.reset(); + m_agvMapDirectBusy = false; + emit agvMapDirectBusyChanged(false); + if (cancel->load() || generation != m_agvMapDirectGeneration) + return; + if (operation == DirectMapOperation::Read) + emit agvMapContentReceived(requestId, deviceId, mapName, + result.success ? result.content : QString(), result.success, result.detail); + else if (operation == DirectMapOperation::Save) + emit agvMapSaveFinished(requestId, deviceId, mapName, + result.success, result.detail); + else { + const bool confirmed = result.success && result.currentMap == map; + QString detail = result.detail; + if (!confirmed && result.accepted && result.uncertain + && !detail.contains(QStringLiteral("待确认"))) + detail += QStringLiteral(";切图请求已接受,车辆当前地图待确认"); + emit commandFinished(QStringLiteral("AGV SwitchMap"), + result.success || (result.accepted && result.uncertain), detail); + if (confirmed && !cancel->load() + && generation == m_agvMapDirectGeneration) + emit agvDirectMapSwitchConfirmed(deviceId, mapName, detail); + } + }, Qt::QueuedConnection); + }; + // Drain all already-admitted backend commands before opening a direct + // socket. The backend thread only posts back to this QObject; it never + // reads GUI-owned state or retains the direct worker's lifetime. + QMetaObject::invokeMethod(m_worker, [this, generation, cancel, runDirect]() { + QMetaObject::invokeMethod(this, [this, generation, cancel, runDirect]() { + if (m_agvMapDirectCancel != cancel) + return; + if (cancel->load() || generation != m_agvMapDirectGeneration) { + m_agvMapDirectCancel.reset(); + m_agvMapDirectBusy = false; + emit agvMapDirectBusyChanged(false); + return; + } + QMetaObject::invokeMethod(m_agvMapDirectWorker, runDirect, Qt::QueuedConnection); + }, Qt::QueuedConnection); + }, Qt::QueuedConnection); +} + void RobotClient::requestAgvSwitchMap(const QString &deviceId, const QString &mapName) { + interruptAgvManualVelocity(); + observeAgvMapDirectDevice(deviceId); + if (m_agvMapDirectEnabled && !m_agvMapDirectDemo) { + requestAgvMapDirect(DirectMapOperation::Switch, 0, deviceId, mapName); + return; + } + if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV SwitchMap"))) + return; emit agvSwitchMapRequested(deviceId, mapName); } +void RobotClient::requestAgvMapContent(quint64 requestId, const QString &deviceId, + const QString &mapName) +{ + observeAgvMapDirectDevice(deviceId); + if (m_agvMapDirectEnabled && !m_agvMapDirectDemo) { + requestAgvMapDirect(DirectMapOperation::Read, requestId, deviceId, mapName); + return; + } + emit agvMapContentRequested(requestId, deviceId, mapName); +} +void RobotClient::saveAgvMapContent(quint64 requestId, const QString &deviceId, + const QString &mapName, const QString &content) +{ + observeAgvMapDirectDevice(deviceId); + if (m_agvMapDirectEnabled && !m_agvMapDirectDemo) { + requestAgvMapDirect(DirectMapOperation::Save, requestId, deviceId, mapName, content); + return; + } + if (m_agvMapDirectBusy) { + emit agvMapSaveFinished(requestId, deviceId, mapName, false, + QStringLiteral("上一项地图直连操作仍在结束,未发送保存请求")); + return; + } + emit agvMapSaveRequested(requestId, deviceId, mapName, content); +} void RobotClient::startAgvMapStream(const QString &deviceId, const QString &mapName, int dimension, bool snapshot, bool incremental) { - emit agvMapStreamStartRequested(deviceId, mapName, dimension, snapshot, incremental); + observeAgvMapDirectDevice(deviceId); + emit agvMapStreamStartRequested(deviceId, mapName, dimension, snapshot, incremental, + ++m_agvMapStreamGeneration, false); +} +void RobotClient::startAgvMapPreview(const QString &deviceId, const QString &mapName) +{ + observeAgvMapDirectDevice(deviceId); + emit agvMapStreamStartRequested(deviceId, mapName, 1, true, false, + ++m_agvMapStreamGeneration, true); } void RobotClient::stopAgvMapStream() { - emit agvMapStreamStopRequested(); + emit agvMapStreamStopRequested(++m_agvMapStreamGeneration); } void RobotClient::requestUserCoordinates(const QString &deviceId, const QVariantMap ¶meters, quint64 token) { @@ -5502,6 +6549,49 @@ void RobotClient::requestRpc(const QString &serviceName, const QString &methodNa if (serviceName.contains(QStringLiteral("ArmService"), Qt::CaseInsensitive) && !method.startsWith(QStringLiteral("get")) && !method.startsWith(QStringLiteral("list"))) emit tcpReferenceInvalidated(deviceId); + if ((serviceName == QStringLiteral("cmvr.api.SystemService") + || serviceName == QStringLiteral("SystemService")) + && (methodName == QStringLiteral("StopAll") || methodName == QStringLiteral("stopAll"))) { + interruptAgvManualVelocity(false); + cancelAgvMapDirect(); + } + if (serviceName == QStringLiteral("cmvr.api.AgvService") + || serviceName == QStringLiteral("AgvService")) { + observeAgvMapDirectDevice(deviceId); + const bool stop = methodName == QStringLiteral("emergencyStop") + || methodName == QStringLiteral("stopVelocityControl") + || methodName == QStringLiteral("cancelNavigation") + || methodName == QStringLiteral("pauseNavigation") + || methodName == QStringLiteral("stopMapping"); + const bool read = methodName == QStringLiteral("getRuntimeState") + || methodName == QStringLiteral("getNavigationStatus") + || methodName == QStringLiteral("listMaps") + || methodName == QStringLiteral("listStations") + || methodName == QStringLiteral("downloadMap") + || methodName == QStringLiteral("streamMap"); + if (!read) + interruptAgvManualVelocity(methodName != QStringLiteral("emergencyStop") + && methodName != QStringLiteral("stopVelocityControl")); + bool zeroVelocity = false; + if (methodName == QStringLiteral("setVelocity")) { + const QJsonObject velocity = QJsonDocument::fromJson(requestJson.toUtf8()) + .object().value(QStringLiteral("velocity")).toObject(); + zeroVelocity = !velocity.isEmpty() + && velocity.value(QStringLiteral("vx")).toDouble() == 0.0 + && velocity.value(QStringLiteral("vy")).toDouble() == 0.0 + && velocity.value(QStringLiteral("wz")).toDouble() == 0.0; + } + if (stop || zeroVelocity) + cancelAgvMapDirect(); + else if (!read && m_agvMapDirectBusy) { + const QString error = QStringLiteral("地图直连操作进行中,该 AGV 命令未发送;停止和急停仍可使用"); + emit rpcFinished(serviceName, methodName, false, + QString::fromUtf8(QJsonDocument(QJsonObject{{QStringLiteral("error"), error}}) + .toJson(QJsonDocument::Compact))); + emit commandFinished(QStringLiteral("%1.%2").arg(serviceName, methodName), false, error); + return; + } + } emit rpcRequested(serviceName, methodName, requestJson, deviceId); } diff --git a/src/robotclient.h b/src/robotclient.h index 4fe22b3..f70767e 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -11,6 +11,9 @@ #include #include +#include +#include + #include "videoframe.h" class BackendWorker; @@ -24,6 +27,7 @@ public: ~RobotClient() override; bool grpcAvailable() const; + quint64 agvMapStreamGeneration() const; public slots: void requestUserCoordinates(const QString &deviceId, const QVariantMap ¶meters, quint64 token); @@ -95,11 +99,23 @@ public slots: void requestAgvFollowPath(const QString &deviceId, const QVariantList &path, double maxSpeed); 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 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 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, int dimension, bool snapshot, bool incremental); + void startAgvMapPreview(const QString &deviceId, const QString &mapName); void stopAgvMapStream(); void requestRpc(const QString &serviceName, const QString &methodName, const QString &requestJson, const QString &deviceId = QString()); @@ -202,12 +218,21 @@ signals: void agvFollowPathRequested(const QString &deviceId, const QVariantList &path, double maxSpeed); 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 agvInventoryRequested(const QString &deviceId); 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, - int dimension, bool snapshot, bool incremental); - void agvMapStreamStopRequested(); + int dimension, bool snapshot, bool incremental, + quint64 generation, bool preview); + void agvMapStreamStopRequested(quint64 generation); void rpcRequested(const QString &serviceName, const QString &methodName, const QString &requestJson, const QString &deviceId); void speakerAudioStreamStartRequested(const QString &deviceId); @@ -265,9 +290,23 @@ signals: void cameraRecordingStateChanged(bool recording, const QString &detail); void agvStateReceived(const QVariantMap &state, const QVariantMap &navigation); 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, 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, bool success, const QString &responseJson); void audioStreamStateChanged(const QString &serviceName, bool running, @@ -290,8 +329,35 @@ signals: void logMessage(const QString &level, const QString &message); private: + void interruptAgvManualVelocity(bool requestStop = true); + std::shared_ptr> m_agvManualGeneration = + std::make_shared>(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> m_agvMapDirectCancel; + DirectMapOperation m_agvMapDirectOperation = DirectMapOperation::Read; + quint64 m_agvMapDirectRequestId = 0; + QString m_agvMapDirectRequestDevice; + QString m_agvMapDirectRequestMap; QThread m_thread; BackendWorker *m_worker = nullptr; + std::atomic m_agvMapStreamGeneration{0}; QMutex m_videoFrameMutex; struct PendingVideoFrame { VideoFrame frame; diff --git a/src/seeragvmapclient.cpp b/src/seeragvmapclient.cpp new file mode 100644 index 0000000..d552402 --- /dev/null +++ b/src/seeragvmapclient.cpp @@ -0,0 +1,559 @@ +#include "seeragvmapclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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::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; +} diff --git a/src/seeragvmapclient.h b/src/seeragvmapclient.h new file mode 100644 index 0000000..dae93b5 --- /dev/null +++ b/src/seeragvmapclient.h @@ -0,0 +1,51 @@ +#ifndef SEERAGVMAPCLIENT_H +#define SEERAGVMAPCLIENT_H + +#include +#include +#include + +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; + + 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 diff --git a/tests/agvdemo_map_test.cpp b/tests/agvdemo_map_test.cpp new file mode 100644 index 0000000..b0a3842 --- /dev/null +++ b/tests/agvdemo_map_test.cpp @@ -0,0 +1,226 @@ +#include "agvmapdocument.h" +#include "robotclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +void require(bool condition, const char *message) +{ + if (!condition) + qFatal("AGV Demo map test failed: %s", message); +} + +void waitUntil(const std::function &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; +} diff --git a/tests/agvmanualmotion_test.cpp b/tests/agvmanualmotion_test.cpp new file mode 100644 index 0000000..b3971cf --- /dev/null +++ b/tests/agvmanualmotion_test.cpp @@ -0,0 +1,421 @@ +#include "mainwindow.h" +#include "robotclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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 &condition, const char *message, + int milliseconds = 3500) +{ + QElapsedTimer clock; + clock.start(); + while (!condition() && clock.elapsed() < milliseconds) + pump(3); + require(condition(), message); +} + +template +T *child(QObject &parent, const char *name) +{ + T *result = parent.findChild(QString::fromLatin1(name)); + require(result != nullptr, name); + return result; +} + +QPushButton *button(QObject &parent, const QString &text) +{ + for (QPushButton *candidate : parent.findChildren()) + 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 frames; + std::vector> 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(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(); + require(client != nullptr, "MainWindow has its RobotClient"); + Recorder record(client); + auto *id = child(window, "agvIdEdit"); + auto *host = child(window, "hostEdit"); + auto *demo = child(window, "demoCheck"); + auto *tools = child(window, "agvControlTools"); + auto *tabs = child(window, "agvTabs"); + auto *timer = child(window, "agvManualVelocityTimer"); + auto *linearAcceleration = child(window, "agvLinearAccelerationSpin"); + auto *linearDeceleration = child(window, "agvLinearDecelerationSpin"); + auto *angularAcceleration = child(window, "agvAngularAccelerationSpin"); + auto *angularDeceleration = child(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(window, "agvVxSpin")->setValue(0.2); + child(window, "agvVySpin")->setValue(0.2); + child(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(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 &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(window, "agvControlSidebar"); + sidebar->ensureWidgetVisible(angularDeceleration); + pump(40); + require(window.grab().save(QString::fromLocal8Bit(argv[1])), + "optional manual settings screenshot is exported"); + } + return 0; +} diff --git a/tests/agvmapdocument_test.cpp b/tests/agvmapdocument_test.cpp new file mode 100644 index 0000000..98c791c --- /dev/null +++ b/tests/agvmapdocument_test.cpp @@ -0,0 +1,665 @@ +#include "agvmapdocument.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +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::infinity(), 2, 0, &error), "infinite x rejected"); + require(!document.addStation("C", 1, 2, std::numeric_limits::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; +} diff --git a/tests/agvmapeditor_delete_integration_test.cpp b/tests/agvmapeditor_delete_integration_test.cpp new file mode 100644 index 0000000..29d3e18 --- /dev/null +++ b/tests/agvmapeditor_delete_integration_test.cpp @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { +void require(bool condition, const char *message) +{ + if (!condition) + qFatal("AGV delete integration failed: %s", message); +} + +void waitFor(const std::function &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 &action) +{ + auto *timer = new QTimer(qApp); + timer->setInterval(5); + QObject::connect(timer, &QTimer::timeout, timer, [=]() { + auto *dialog = qobject_cast(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(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 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 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(request->content().size())); + m_result = Persist; + response->mutable_header()->set_success(true); + return grpc::Status::OK; + } + + void replace(const QString &content) + { + std::lock_guard lock(m_mutex); + m_maps["delete_map"] = content; + } + void next(Result result) + { + std::lock_guard lock(m_mutex); + m_result = result; + } + int reads() + { + std::lock_guard lock(m_mutex); + return m_reads; + } + int uploads() + { + std::lock_guard lock(m_mutex); + return static_cast(m_uploads.size()); + } + QString stored() + { + std::lock_guard lock(m_mutex); + return m_maps.value("delete_map"); + } + QString uploaded() + { + std::lock_guard 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(request.content().size())); + } + +private: + std::mutex m_mutex; + QHash m_maps; + std::vector 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("agvManageMapObjectsButton"); + save = editor->findChild("agvSaveMapObjectsButton"); + undo = editor->findChild("agvUndoMapObjectsButton"); + status = editor->findChild("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 &action) + { + nextModal("agvMapObjectsDialog", [=](QDialog *dialog) { + auto *stations = dialog->findChild("agvMapStationsTable"); + auto *routes = dialog->findChild("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("agvMapObjectsTabs"); + auto *table = dialog->findChild(station ? "agvMapStationsTable" : "agvMapRoutesTable"); + auto *button = dialog->findChild(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(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 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; +} diff --git a/tests/agvmapeditor_delete_test.cpp b/tests/agvmapeditor_delete_test.cpp new file mode 100644 index 0000000..a5f07e9 --- /dev/null +++ b/tests/agvmapeditor_delete_test.cpp @@ -0,0 +1,313 @@ +#include "agvmapdocument.h" +#include "agvmapeditorwidget.h" +#include "agvmapviewwidget.h" +#include "robotclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 &action) +{ + auto *timer = new QTimer(qApp); + timer->setInterval(10); + QObject::connect(timer, &QTimer::timeout, timer, [timer, action]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog || !action(dialog)) + return; + timer->stop(); + timer->deleteLater(); + }); + timer->start(); + QTimer::singleShot(7000, qApp, [guard = QPointer(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 &extra = {}) +{ + nextModal([=](QDialog *dialog) { + const QString expected = station ? QStringLiteral("agvDeleteStationConfirmDialog") + : QStringLiteral("agvDeleteRouteConfirmDialog"); + if (dialog->objectName() != expected) + return false; + auto *box = qobject_cast(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 &extra = {}) +{ + auto *tabs = dialog->findChild("agvMapObjectsTabs"); + auto *table = dialog->findChild(station ? "agvMapStationsTable" : "agvMapRoutesTable"); + auto *remove = dialog->findChild(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 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("agvManageMapObjectsButton"); + auto *save = editor->findChild("agvSaveMapObjectsButton"); + auto *undo = editor->findChild("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 &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("agvDeleteStationButton"); + auto *removeRoute = dialog->findChild("agvDeleteRouteButton"); + require(!removeStation->isEnabled() && !removeRoute->isEnabled(), + "deletion is disabled without a selection"); + if (!screenshotDir.isEmpty()) { + auto *stations = dialog->findChild("agvMapStationsTable"); + auto *routes = dialog->findChild("agvMapRoutesTable"); + auto *tabs = dialog->findChild("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("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("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("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("agvMapStationsTable"), "LM1") >= 0, + "station cancellation preserves station"); + deleteInManager(dialog, true, QStringLiteral("LM1"), true); + require(rowFor(dialog->findChild("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("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("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("agvDeleteRouteButton")->isEnabled(), + "map change disables stale manager actions"); + }); + selectedMap = QStringLiteral("delete_map"); + setViewMap(); + editor->refreshContext(); + manager([&](QDialog *dialog) { + require(rowFor(dialog->findChild("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; +} diff --git a/tests/agvmapeditor_failure_test.cpp b/tests/agvmapeditor_failure_test.cpp new file mode 100644 index 0000000..8721014 --- /dev/null +++ b/tests/agvmapeditor_failure_test.cpp @@ -0,0 +1,686 @@ +#include "agvmapdocument.h" +#include "agvmapeditorwidget.h" +#include "agvmapviewwidget.h" +#include "robotclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 &fill) +{ + auto *timer = new QTimer(qApp); + timer->setInterval(10); + QObject::connect(timer, &QTimer::timeout, timer, [timer, fill]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog || !fill(dialog)) + return; + timer->stop(); + timer->deleteLater(); + }); + timer->start(); + QTimer::singleShot(7000, qApp, [guard = QPointer(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("agvNewStationId"); + auto *label = dialog->findChild("agvNewStationName"); + auto *xSpin = dialog->findChild("agvNewStationX"); + auto *ySpin = dialog->findChild("agvNewStationY"); + auto *box = dialog->findChild(); + 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("agvNewRouteId"); + auto *both = dialog->findChild("agvNewRouteBidirectional"); + auto *box = dialog->findChild(); + 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 &inspect) +{ + fillNextModal([=](QDialog *dialog) { + if (dialog->objectName() != QStringLiteral("agvMapObjectsDialog")) + return false; + auto *stations = dialog->findChild("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("agvMapStationsTable"); + auto *rename = dialog->findChild("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("agvStationName"); + auto *box = nameDialog->findChild(); + 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 reads; + QVector 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("agvCoordinateStationButton"); + auto *save = editor->findChild("agvSaveMapObjectsButton"); + auto *undo = editor->findChild("agvUndoMapObjectsButton"); + auto *manage = editor->findChild("agvManageMapObjectsButton"); + auto *addStation = editor->findChild("agvAddStationButton"); + auto *addRoute = editor->findChild("agvAddRouteButton"); + auto *status = editor->findChild("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; +} diff --git a/tests/agvmapeditor_smoke.cpp b/tests/agvmapeditor_smoke.cpp new file mode 100644 index 0000000..e2b52d1 --- /dev/null +++ b/tests/agvmapeditor_smoke.cpp @@ -0,0 +1,203 @@ +#include "agvmapdocument.h" +#include "agvmapeditorwidget.h" +#include "agvmapviewwidget.h" +#include "robotclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +void require(bool condition, const char *message) +{ + if (!condition) + qFatal("AGV editor smoke failed: %s", message); +} + +void waitFor(const std::function &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 &fill) +{ + auto *timer = new QTimer(qApp); + timer->setInterval(10); + QObject::connect(timer, &QTimer::timeout, timer, [timer, kind, fill]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog || dialog->objectName() != kind) + return; + timer->stop(); + fill(dialog); + auto *box = dialog->findChild(); + require(box != nullptr, "dialog has action buttons"); + box->button(QDialogButtonBox::Ok)->click(); + timer->deleteLater(); + }); + timer->start(); + QTimer::singleShot(7000, qApp, [guard = QPointer(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("agvCoordinateStationButton"); + auto *route = editor->findChild("agvAddRouteButton"); + auto *save = editor->findChild("agvSaveMapObjectsButton"); + auto *status = editor->findChild("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("agvNewStationId")->setText(id); + dialog->findChild("agvNewStationX")->setValue(x); + dialog->findChild("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("agvNewRouteId")->setText("HOME_P1"); + dialog->findChild("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; +} diff --git a/tests/agvmapeditor_upload_integration_test.cpp b/tests/agvmapeditor_upload_integration_test.cpp new file mode 100644 index 0000000..bb910bd --- /dev/null +++ b/tests/agvmapeditor_upload_integration_test.cpp @@ -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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { +void require(bool condition, const char *message) +{ + if (!condition) + qFatal("AGV editor upload integration failed: %s", message); +} + +void waitFor(const std::function &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 &fill) +{ + auto *timer = new QTimer(qApp); + timer->setInterval(5); + QObject::connect(timer, &QTimer::timeout, timer, [timer, kind, fill]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog || dialog->objectName() != kind) + return; + timer->stop(); + fill(dialog); + dialog->findChild()->button(QDialogButtonBox::Ok)->click(); + timer->deleteLater(); + }); + timer->start(); + QTimer::singleShot(7000, qApp, [guard = QPointer(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 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 guard(m_mutex); + const qint64 deadlineMs = std::chrono::duration_cast( + 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(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 guard(m_mutex); + m_content = content; + } + void nextResult(Result result) + { + std::lock_guard guard(m_mutex); + m_nextResult = result; + } + void denyNextRead() + { + std::lock_guard guard(m_mutex); + m_failRead = true; + } + int downloads() + { + std::lock_guard guard(m_mutex); + return static_cast(m_downloads.size()); + } + int uploads() + { + std::lock_guard guard(m_mutex); + return static_cast(m_uploads.size()); + } + Upload upload(int index) + { + std::lock_guard guard(m_mutex); + return m_uploads.at(index); + } + QString stored() + { + std::lock_guard guard(m_mutex); + return m_content; + } + QStringList events() + { + std::lock_guard guard(m_mutex); + return m_events; + } + +private: + std::mutex m_mutex; + QString m_name; + QString m_content; + QString m_pendingContent; + std::vector m_downloads; + std::vector 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 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("agvCoordinateStationButton"); + auto *route = editor->findChild("agvAddRouteButton"); + auto *save = editor->findChild("agvSaveMapObjectsButton"); + auto *undo = editor->findChild("agvUndoMapObjectsButton"); + auto *status = editor->findChild("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("agvNewStationId")->setText(id); + dialog->findChild("agvNewStationName")->setText(QStringLiteral("\"本地工位\"")); + dialog->findChild("agvNewStationX")->setValue(1.25); + dialog->findChild("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("agvNewRouteId")->setText("LOCAL_ROUTE"); + dialog->findChild("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(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(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("agvNewRouteId")->setText("VERIFY_BOTH_DIRECTIONS"); + dialog->findChild("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; +} diff --git a/tests/agvmaprasterizer_test.cpp b/tests/agvmaprasterizer_test.cpp new file mode 100644 index 0000000..9a60c6b --- /dev/null +++ b/tests/agvmaprasterizer_test.cpp @@ -0,0 +1,260 @@ +#include "agvmapdocument.h" +#include "agvmaprasterizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +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(std::floor(x)))), + std::max(0, std::min(image.height() - 1, + static_cast(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(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; +} diff --git a/tests/agvmapstream_fallback_test.cpp b/tests/agvmapstream_fallback_test.cpp new file mode 100644 index 0000000..ad3282c --- /dev/null +++ b/tests/agvmapstream_fallback_test.cpp @@ -0,0 +1,644 @@ +#include "robotclient.h" +#include "cmvr/api/agv_service.grpc.pb.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +void require(bool condition, const char *message) +{ + if (!condition) + qFatal("AGV map stream fallback test failed: %s", message); +} + +void waitUntil(const std::function &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 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 *writer) override + { + const std::string name = request->map_name(); + { + std::lock_guard 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 guard(m_mutex); + ++m_completedStreams[name]; + } + return grpc::Status::OK; + } + + int downloads(const std::string &name) + { + std::lock_guard guard(m_mutex); + return m_downloads[name]; + } + + std::string downloadedDevice(const std::string &name) + { + std::lock_guard 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 guard(m_mutex); + return m_completedStreams[name]; + } + + bool lastIncremental(const std::string &name) + { + std::lock_guard guard(m_mutex); + return m_lastIncremental[name]; + } + +private: + std::mutex m_mutex; + std::map m_downloads; + std::map m_downloadDevices; + std::map m_completedStreams; + std::map m_lastIncremental; + std::atomic m_headerFailureCancellations{0}; + std::atomic m_staleMapUpdates{0}; + std::atomic m_previewStreamsStarted{0}; + std::atomic m_previewStreamCancellations{0}; + std::atomic m_heldStreamsStarted{0}; + std::atomic 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 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 frames; + QString stoppedDetail; + bool stopped = false; + QStringList stateDetails; + QVector 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; +} diff --git a/tests/agvmapviewwidget_test.cpp b/tests/agvmapviewwidget_test.cpp new file mode 100644 index 0000000..0c7d80f --- /dev/null +++ b/tests/agvmapviewwidget_test.cpp @@ -0,0 +1,683 @@ +#include "agvmapviewwidget.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +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::quiet_NaN(), 312), &world)); + + QImage image(400, 300, QImage::Format_RGB32); + const QList 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::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 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("curved"); + QTest::addColumn("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 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(¢erlineMask); + 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(212, 312), QStringLiteral("A")}, + QPair{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" diff --git a/tests/agvpage_smoke.cpp b/tests/agvpage_smoke.cpp new file mode 100644 index 0000000..4a10bc1 --- /dev/null +++ b/tests/agvpage_smoke.cpp @@ -0,0 +1,1458 @@ +#include "agvmapdocument.h" +#include "agvmapeditorwidget.h" +#include "agvmapviewwidget.h" +#include "mainwindow.h" +#include "robotclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +void require(bool condition, const char *message) +{ + if (!condition) + qFatal("AGV page smoke failed: %s", message); +} + +void waitFor(const std::function &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 &fill) +{ + auto *timer = new QTimer(qApp); + timer->setInterval(10); + QObject::connect(timer, &QTimer::timeout, timer, [timer, kind, fill]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog || dialog->objectName() != kind) + return; + timer->stop(); + fill(dialog); + dialog->findChild()->button(QDialogButtonBox::Ok)->click(); + QTimer::singleShot(100, qApp, [guard = QPointer(dialog)]() { + if (guard && guard->isVisible()) { + QStringList labels; + for (const QLabel *label : guard->findChildren()) + labels.append(label->text()); + qFatal("AGV page smoke failed: dialog rejected fixture: %s", qPrintable(labels.join(" | "))); + } + }); + timer->deleteLater(); + }); + timer->start(); + QTimer::singleShot(7000, qApp, [guard = QPointer(timer), kind]() { + if (guard && guard->isActive()) + qFatal("AGV page smoke failed: expected dialog did not open: %s", qPrintable(kind)); + }); +} +} + +int main(int argc, char *argv[]) +{ + qInstallMessageHandler([](QtMsgType, const QMessageLogContext &, const QString &message) { + const QByteArray text = message.toUtf8(); + std::fprintf(stderr, "%s\n", text.constData()); + std::fflush(stderr); + }); + QApplication app(argc, argv); + Q_INIT_RESOURCE(resources); + app.setOrganizationName("CMVR-Tests"); + app.setApplicationName("AGV Page Smoke"); + app.setStyle("Fusion"); + QSettings::setDefaultFormat(QSettings::IniFormat); + QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, + app.applicationDirPath() + "/agv-page-test-settings"); + const QString startupDevice = QStringLiteral("startup_agv_fixture"); + const QString startupCamera = QStringLiteral("real_cam_startup_fixture"); + constexpr int startupRefreshMs = 500; + { + QSettings startupSettings; + // This application-specific test path is isolated from the user's + // control-station settings. Restoring a camera selection invokes the + // existing save callback before the AGV controls have been restored. + startupSettings.clear(); + startupSettings.setValue("agv/device", startupDevice); + startupSettings.setValue("agv/mapRefreshIntervalMs", startupRefreshMs); + startupSettings.setValue("agv/mapDirect", true); + startupSettings.setValue("agv/mapDirectHost", "127.0.0.1"); + startupSettings.setValue("camera/device", startupCamera); + startupSettings.setValue("connection/demo", false); + startupSettings.sync(); + require(startupSettings.status() == QSettings::NoError, + "isolated startup settings with saved AGV and camera devices are written"); + } + QFile style(QStringLiteral(":/styles.qss")); + require(style.open(QIODevice::ReadOnly), "production stylesheet is available in test resources"); + app.setStyleSheet(QString::fromUtf8(style.readAll())); + MainWindow window; + auto *client = window.findChild(); + auto *editor = window.findChild(); + auto *view = window.findChild(); + auto *id = window.findChild("agvIdEdit"); + auto *map = window.findChild("agvMapCombo"); + auto *stations = window.findChild("agvStationCombo"); + auto *demo = window.findChild("demoCheck"); + auto *host = window.findChild("hostEdit"); + auto *port = window.findChild("systemConnectionPort"); + require(client && editor && view && id && map && stations && demo && host && port, + "MainWindow exposes AGV controls"); + auto *mapDirectMode = window.findChild("agvMapDirectMode"); + auto *mapDirectHost = window.findChild("agvMapDirectHost"); + require(mapDirectMode && mapDirectHost && mapDirectMode->currentData().toBool() + && mapDirectHost->text() == QStringLiteral("127.0.0.1"), + "startup restores the explicit map connection and vehicle address despite other settings callbacks"); + // The remaining smoke scenarios exercise the original service and Demo + // paths. Direct TCP and configuration discovery are tested on loopback. + mapDirectMode->setCurrentIndex(0); + auto *startupCameraCombo = window.findChild("cameraDeviceCombo"); + auto *startupRefresh = window.findChild("agvMapRefreshCombo"); + require(startupCameraCombo && startupCameraCombo->currentData().toString() == startupCamera, + "construction restores a nonempty saved camera device through its normal selection callback"); + require(id->text() == startupDevice && startupRefresh + && startupRefresh->currentData().toInt() == startupRefreshMs, + "camera restoration cannot erase the saved AGV device or map refresh interval during startup"); + { + QSettings restoredSettings; + restoredSettings.sync(); + require(restoredSettings.status() == QSettings::NoError + && restoredSettings.value("agv/device").toString() == startupDevice + && restoredSettings.value("agv/mapRefreshIntervalMs").toInt() == startupRefreshMs, + "startup also preserves the persisted AGV device and refresh interval for the next launch"); + } + qInfo("PASS phase: startup preserves saved AGV device and refresh interval when saved camera selection also loads"); + if (argc > 1 && QString::fromLocal8Bit(argv[1]) == QStringLiteral("--startup-settings-only")) + return 0; + // Keep the later frame-timing fixtures in their original automatic mode. + startupRefresh->setCurrentIndex(startupRefresh->findData(0)); + // An empty ID in live mode must stay empty; no backend connection is made. + id->clear(); + demo->setChecked(false); + require(QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, + Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("test live UI"))), + "live UI connection state injected"); + require(id->text().isEmpty(), "live mode does not fill a Demo device ID"); + QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, + Q_ARG(bool, false), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("test disconnected"))); + host->setText(QStringLiteral("127.0.0.1")); + port->setValue(50052); + const QString expectedDevice = argc > 2 ? QString::fromLocal8Bit(argv[2]) + : QStringLiteral("demo_agv_1"); + if (argc > 2) + id->setText(expectedDevice); + demo->setChecked(true); + require(QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, + Q_ARG(int, 3)), "AGV page selected"); + window.showMaximized(); + auto *coordinate = editor->findChild("agvCoordinateStationButton"); + auto *route = editor->findChild("agvAddRouteButton"); + auto *save = editor->findChild("agvSaveMapObjectsButton"); + auto *undo = editor->findChild("agvUndoMapObjectsButton"); + auto *manage = editor->findChild("agvManageMapObjectsButton"); + auto *loadMap = window.findChild("switchMapButton"); + auto *editorStatus = editor->findChild("agvMapEditorStatus"); + auto *connectionValue = window.findChild("agvConnectionValue"); + auto *modeValue = window.findChild("agvModeValue"); + auto *mapValue = window.findChild("agvMapValue"); + auto *errorValue = window.findChild("agvErrorValue"); + require(coordinate && route && save && undo && manage && loadMap && editorStatus, + "map editing and actual map loading controls exist"); + require(connectionValue && modeValue && mapValue && errorValue, + "AGV availability, mode, map and error fields are individually observable"); + const auto contextFor = [&](const QString &device, bool demoMode) { + return QVariantMap{{"deviceId", device}, {"endpoint", QStringLiteral("%1:%2") + .arg(host->text().trimmed()).arg(port->value())}, {"demo", demoMode}, {"available", true}}; + }; + const auto emitFrame = [&](const QImage &image, QVariantMap metadata, const QString &detail) { + // Local fixtures must follow the same generation contract as the + // worker bridge. An explicit old generation is retained for rejection tests. + if (!metadata.contains("streamGeneration")) + metadata.insert("streamGeneration", QVariant::fromValue(client->agvMapStreamGeneration())); + client->agvMapFrameReceived(image, metadata, detail); + }; + QVariantMap latestDemoState; + QImage latestDemoImage; + QVariantMap latestDemoMetadata; + QObject::connect(client, &RobotClient::agvStateReceived, + [&](const QVariantMap &state, const QVariantMap &) { + if (state.value("available").toBool() && state.value("demo").toBool() + && state.value("deviceId").toString() == expectedDevice) + latestDemoState = state; + }); + QObject::connect(client, &RobotClient::agvMapFrameReceived, + [&](const QImage &image, const QVariantMap &metadata, const QString &) { + if (metadata.value("demo").toBool() && metadata.value("deviceId").toString() == expectedDevice) { + latestDemoImage = image; + latestDemoMetadata = metadata; + } + }); + QHash mapReads; + QHash expectedStationNames; + quint64 verificationToken = 20000; + quint64 completedToken = 0; + QString downloaded; + int switches = 0; + bool observeDemoSwitches = true; + QObject::connect(client, &RobotClient::agvMapContentReceived, + [&](quint64 token, const QString &device, const QString &name, + const QString &content, bool ok, const QString &) { + if (device != expectedDevice) + return; + if (ok) + ++mapReads[name]; + if (token >= 20000) { + require(ok, "map verification read succeeds"); + completedToken = token; + downloaded = content; + } + }); + QObject::connect(client, &RobotClient::commandFinished, + [&](const QString &command, bool ok, const QString &) { + if (command == "AGV SwitchMap" && observeDemoSwitches) { + require(ok, "actual map switch succeeds"); + ++switches; + } + }); + const auto readMap = [&](const QString &name) { + const quint64 token = ++verificationToken; + client->requestAgvMapContent(token, expectedDevice, name); + waitFor([&]() { return completedToken == token; }, "complete map downloaded for verification"); + AgvMapDocument result; + QString error; + require(result.load(downloaded, &error), "downloaded map remains editable SMAP"); + return result; + }; + const auto hasRoute = [](const AgvMapDocument &document, const QString &name) { + for (const QVariant &entry : document.routes()) + if (entry.toMap().value("id").toString() == name) + return true; + return false; + }; + const auto stationIndex = [&](const QString &name) { + return stations->findData(name); + }; + const auto stationName = [](const AgvMapDocument &document, const QString &id) { + for (const QVariant &entry : document.stations()) { + const QVariantMap station = entry.toMap(); + if (station.value("id").toString() == id) + return station.value("name").toString(); + } + return QString(); + }; + const auto loadPhysicalMap = [&](const QString &name) { + require(map->findText(name) >= 0, "target map is listed"); + const int previousSwitches = switches; + map->setCurrentText(name); + waitFor([&]() { return loadMap->isEnabled(); }, "actual map load button is ready"); + loadMap->click(); + const quint64 firstPreviewGeneration = client->agvMapStreamGeneration(); + waitFor([&]() { return switches > previousSwitches && view->mapId() == name + && coordinate->isEnabled() && id->isEnabled() + && client->agvMapStreamGeneration() > firstPreviewGeneration; }, + "selected map is confirmed and its fresh post-switch raster is ready"); + }; + const auto loadEditableMap = [&](const QString &name) { + const int previousReads = mapReads.value(name); + loadPhysicalMap(name); + waitFor([&]() { return mapReads.value(name) > previousReads + && editorStatus->text().contains(QStringLiteral("地图已读取")) + && coordinate->isEnabled() && !save->isEnabled(); }, + "selected map's complete station/route document loads automatically"); + }; + const auto inspectObjects = [&](const QStringList &requiredObjects, const QStringList &absentObjects) { + waitFor([&]() { return manage->isEnabled(); }, "object manager is ready after confirmed-map refresh"); + bool inspected = false; + auto *timer = new QTimer(qApp); + timer->setInterval(10); + QObject::connect(timer, &QTimer::timeout, timer, [&, timer]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog || dialog->windowTitle() != QStringLiteral("AGV 站点与路线")) + return; + timer->stop(); + auto *stationTable = dialog->findChild("agvMapStationsTable"); + require(stationTable && stationTable->columnCount() >= 2, + "manager exposes station ID and name columns"); + QStringList cells; + for (QTableWidget *table : dialog->findChildren()) + for (int row = 0; row < table->rowCount(); ++row) + for (int column = 0; column < table->columnCount(); ++column) + if (table->item(row, column)) + cells.append(table->item(row, column)->text()); + for (const QString &object : requiredObjects) { + require(cells.contains(object), "current map's saved/draft objects appear in editor manager"); + if (!expectedStationNames.contains(object)) + continue; + bool pairedName = false; + for (int row = 0; row < stationTable->rowCount(); ++row) + if (stationTable->item(row, 0)->text() == object) + pairedName = stationTable->item(row, 1)->text() == expectedStationNames.value(object); + require(pairedName, "manager keeps the station's display name paired with its ID"); + } + for (const QString &object : absentObjects) + require(!cells.contains(object), "other map's objects stay out of editor manager"); + inspected = true; + dialog->accept(); + timer->deleteLater(); + }); + timer->start(); + QTimer::singleShot(7000, qApp, [guard = QPointer(timer)]() { + if (guard && guard->isActive()) + qFatal("AGV page smoke failed: object manager did not open"); + }); + manage->click(); + require(inspected, "editor object manager inspected"); + }; + const auto addStation = [&](const QString &stationId, const QString &stationName, double x, double y) { + waitFor([&]() { return coordinate->isEnabled(); }, "coordinate action is ready after confirmed-map refresh"); + fillNextDialog("agvStationDialog", [=](QDialog *dialog) { + dialog->findChild("agvNewStationId")->setText(stationId); + auto *name = dialog->findChild("agvNewStationName"); + require(name != nullptr, "new station dialog exposes a display name field"); + name->setText(stationName); + dialog->findChild("agvNewStationX")->setValue(x); + dialog->findChild("agvNewStationY")->setValue(y); + }); + coordinate->click(); + waitFor([&]() { return save->isEnabled() && undo->isEnabled(); }, + "station created in current map"); + expectedStationNames.insert(stationId, stationName); + }; + const auto addBidirectionalRoute = [&](const QString &routeId, const QString &target) { + waitFor([&]() { return route->isEnabled(); }, "route action is ready after confirmed-map refresh"); + fillNextDialog("agvRouteDialog", [=](QDialog *dialog) { + dialog->findChild("agvNewRouteId")->setText(routeId); + dialog->findChild("agvNewRouteBidirectional")->setChecked(true); + }); + route->click(); + view->stationSelected("HOME"); + view->stationSelected(target); + require(save->isEnabled(), "bidirectional route remains a current-map draft"); + }; + const auto renameStation = [&](const QString &stationId, const QString &newName) { + waitFor([&]() { return manage->isEnabled(); }, "rename manager is ready after confirmed-map refresh"); + fillNextDialog("agvStationNameDialog", [=](QDialog *dialog) { + dialog->findChild("agvStationName")->setText(newName); + }); + bool renamed = false; + auto *timer = new QTimer(qApp); + timer->setInterval(10); + QObject::connect(timer, &QTimer::timeout, timer, [&, timer]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog || dialog->objectName() != "agvMapObjectsDialog") + return; + timer->stop(); + auto *table = dialog->findChild("agvMapStationsTable"); + auto *rename = dialog->findChild("agvRenameStationButton"); + require(table && rename, "manager exposes station rename controls"); + int selected = -1; + for (int row = 0; row < table->rowCount(); ++row) + if (table->item(row, 0)->text() == stationId) + selected = row; + require(selected >= 0, "station to rename is present in current map manager"); + table->selectRow(selected); + rename->click(); + renamed = true; + dialog->accept(); + timer->deleteLater(); + }); + timer->start(); + QTimer::singleShot(7000, qApp, [guard = QPointer(timer)]() { + if (guard && guard->isActive()) + qFatal("AGV page smoke failed: rename manager did not open"); + }); + manage->click(); + require(renamed && save->isEnabled() && undo->isEnabled(), "name change remains an undoable draft"); + expectedStationNames.insert(stationId, newName); + }; + waitFor([&]() { return coordinate->isEnabled() && map->currentText() == "demo_map" + && view->mapId() == "demo_map" && editorStatus + && editorStatus->text().contains(QStringLiteral("地图已读取")); }, + "map and existing stations/routes load automatically before editing"); + require(id->text() == expectedDevice, "Demo fills only an empty device ID"); + waitFor([&]() { return !latestDemoState.isEmpty() && connectionValue->text().contains(QStringLiteral("在线")) + && modeValue->text() == QStringLiteral("空闲"); }, + "available connected Demo state renders online and Idle consistently"); + qInfo("AGV layout dimensions: window=%dx%d map=%dx%d", window.width(), window.height(), + view->width(), view->height()); + if (argc > 1) + window.grab().save(QString::fromLocal8Bit(argv[1])); + require(view->height() >= window.height() / 2, "map occupies the main workspace height"); + auto *sidebar = window.findChild("agvControlSidebar"); + auto *expand = window.findChild("agvExpandMapButton"); + auto *tools = window.findChild("agvControlTools"); + require(sidebar && expand && tools, "map expansion and sidebar tools exist"); + auto *mapSelector = window.findChild("agvMapSelectorBar"); + require(mapSelector != nullptr, "map selector has a persistent main-workspace row"); + auto *mapListSummary = mapSelector->findChild("agvMapListSummary"); + require(mapListSummary && mapListSummary->text().contains(QStringLiteral("演示")) + && mapListSummary->text().contains(QStringLiteral("2 张地图")), + "map selector reports actual Demo map count rather than a hidden library"); + QPushButton *refreshMaps = nullptr; + for (QPushButton *button : mapSelector->findChildren()) + if (button->text() == QStringLiteral("刷新地图列表")) + refreshMaps = button; + require(refreshMaps && loadMap->text() == QStringLiteral("切换地图"), + "map selector exposes clear refresh and switch actions"); + bool mapSelectionLabel = false; + for (QLabel *label : mapSelector->findChildren()) + mapSelectionLabel |= label->text() == QStringLiteral("地图"); + require(mapSelectionLabel, "map selector labels the pending map choice"); + const auto verifyMapSelector = [&]() { + require(mapSelector->isVisible() && mapSelector->parentWidget()->isAncestorOf(view) + && !sidebar->isAncestorOf(mapSelector), + "map selector belongs to the visible main map panel rather than sidebar"); + for (QWidget *control : {static_cast(map), + static_cast(refreshMaps), + static_cast(loadMap)}) { + require(mapSelector->isAncestorOf(control) && !sidebar->isAncestorOf(control) + && control->isVisible(), "all map selection actions stay visible outside sidebar"); + require(mapSelector->rect().contains(QRect(control->mapTo(mapSelector, QPoint()), control->size())), + "map selection controls fit their workspace row without clipping"); + } + }; + verifyMapSelector(); + const int originalMapWidth = view->width(); + expand->click(); + waitFor([&]() { return !sidebar->isVisible() && view->width() > originalMapWidth; }, + "map expands when sidebar is hidden"); + verifyMapSelector(); + expand->click(); + waitFor([&]() { return sidebar->isVisible() && view->width() == originalMapWidth; }, + "sidebar and map restore after expansion"); + verifyMapSelector(); + tools->setCurrentIndex(1); + require(tools->tabText(1) == QStringLiteral("手动控制") && tools->currentWidget()->isVisible(), + "manual controls remain available in sidebar"); + verifyMapSelector(); + waitFor([&]() { return sidebar->widget()->width() <= sidebar->viewport()->width(); }, + "manual controls fit sidebar width without clipping"); + tools->setCurrentIndex(0); + waitFor([&]() { return sidebar->widget()->width() <= sidebar->viewport()->width(); }, + "map controls fit sidebar after switching tabs"); + verifyMapSelector(); + + // Inject inventory only: selecting mocked names must never issue SwitchMap. + QStringList manyMaps{"demo_map", "warehouse"}; + for (int index = 0; index < 62; ++index) + manyMaps.append(QStringLiteral("map_%1_区域站点路线编辑示例").arg(index, 2, 10, QLatin1Char('0'))); + const int switchesBeforeInventory = switches; + client->agvInventoryReceivedForContext(contextFor(expectedDevice, true), manyMaps, {}); + require(map->count() == manyMaps.size(), "all 64 inventory maps remain available in selector"); + require(mapListSummary->text().contains(QStringLiteral("64 张地图")), + "map count updates from complete inventory instead of a fixed Demo number"); + for (int index = 0; index < manyMaps.size(); ++index) { + require(map->itemText(index) == manyMaps.at(index), "inventory map names are retained without truncation"); + map->setCurrentIndex(index); + require(map->currentText() == manyMaps.at(index), "every listed map can be selected in full"); + } + map->showPopup(); + const QModelIndex finalMap = map->model()->index(manyMaps.size() - 1, 0); + map->view()->scrollTo(finalMap, QAbstractItemView::PositionAtBottom); + waitFor([&]() { return map->view()->isVisible() + && map->view()->viewport()->rect().contains(map->view()->visualRect(finalMap).center()); }, + "last map in a long inventory is reachable in dropdown popup"); + require(finalMap.data().toString() == manyMaps.last(), "last dropdown entry displays its complete map name"); + map->hidePopup(); + require(switches == switchesBeforeInventory && view->mapId() == "demo_map", + "mock inventory and selection do not switch the actual displayed map"); + map->setCurrentText("demo_map"); + refreshMaps->click(); + waitFor([&]() { return map->count() == 2 && map->findText("warehouse") >= 0 + && map->currentText() == "demo_map" && stationIndex("HOME") >= 0 + && mapListSummary->text().contains(QStringLiteral("2 张地图")); }, + "refresh action restores actual Demo inventory after long-list verification"); + require(switches == switchesBeforeInventory, "inventory refresh does not issue a mock switch command"); + verifyMapSelector(); + qInfo("PASS phase: map selector remains visible in expanded/manual views and retains all 64 inventory entries"); + const int originalRouteCountA = readMap("demo_map").routes().size(); + // A pending dropdown selection alone must not redirect A's editor/save. + map->setCurrentText("warehouse"); + QApplication::processEvents(); + require(view->mapId() == "demo_map" && coordinate->isEnabled(), + "selecting map B without loading leaves editing attached to displayed map A"); + addStation("P101", QStringLiteral("起点A"), 2.0, 3.0); + addBidirectionalRoute("A_HOME_P1", "P101"); + int saves = 0; + QObject::connect(editor, &AgvMapEditorWidget::mapSaved, [&]() { ++saves; }); + save->click(); + waitFor([&]() { return saves == 1 && stationIndex("P101") >= 0 + && coordinate->isEnabled() && id->isEnabled() + && view->mapId() == "demo_map"; }, + "save refreshes navigation stations and restores controls"); + require(!save->isEnabled(), "saved state survives inventory and stream refresh"); + AgvMapDocument mapA = readMap("demo_map"); + require(mapA.hasStation("P101") && hasRoute(mapA, "A_HOME_P1") + && mapA.routes().size() == originalRouteCountA + 2 + && stationName(mapA, "P101") == QStringLiteral("起点A") + && stations->itemText(stationIndex("P101")).contains(QStringLiteral("起点A")), + "map A stores station name and both route directions with navigation ID intact"); + inspectObjects({"P101", "A_HOME_P1", QStringLiteral("起点A")}, + {"P_B", "B_HOME_P_B", QStringLiteral("终点B")}); + qInfo("PASS phase: pending map selection keeps named station/route save on map A"); + + loadEditableMap("warehouse"); + AgvMapDocument mapB = readMap("warehouse"); + const int originalRouteCountB = mapB.routes().size(); + require(!mapB.hasStation("P101") && !hasRoute(mapB, "A_HOME_P1") + && stationIndex("P101") < 0, "map A objects are absent from newly loaded map B"); + addStation("UNDO_B", "undo B", 3.0, 3.0); + inspectObjects({"UNDO_B"}, {"P101"}); + undo->click(); + require(!save->isEnabled() && !undo->isEnabled(), "map B station draft can be undone"); + inspectObjects({}, {"UNDO_B", "P101"}); + addStation("P_B", QStringLiteral("终点B"), -1.0, 1.0); + addBidirectionalRoute("B_HOME_P_B", "P_B"); + undo->click(); + require(save->isEnabled() && undo->isEnabled(), "undoing map B route retains its station draft"); + inspectObjects({"P_B"}, {"B_HOME_P_B", "P101"}); + addBidirectionalRoute("B_HOME_P_B", "P_B"); + save->click(); + waitFor([&]() { return saves == 2 && stationIndex("P_B") >= 0 + && coordinate->isEnabled() && !save->isEnabled(); }, + "map B station and route saved and available in navigation inventory"); + mapB = readMap("warehouse"); + require(mapB.hasStation("P_B") && !mapB.hasStation("UNDO_B") + && !mapB.hasStation("P101") && hasRoute(mapB, "B_HOME_P_B") + && !hasRoute(mapB, "A_HOME_P1") && mapB.routes().size() == originalRouteCountB + 2 + && stationName(mapB, "P_B") == QStringLiteral("终点B") + && stations->itemText(stationIndex("P_B")).contains(QStringLiteral("终点B")), + "map B stores its named station and routes with no undone/other-map objects"); + renameStation("P_B", QStringLiteral("暂改名B")); + inspectObjects({"P_B", QStringLiteral("暂改名B")}, {QStringLiteral("起点A")}); + undo->click(); + expectedStationNames.insert("P_B", QStringLiteral("终点B")); + require(!save->isEnabled(), "undoing a name change restores the saved map"); + inspectObjects({"P_B", QStringLiteral("终点B")}, {QStringLiteral("暂改名B")}); + renameStation("P_B", QStringLiteral("终点B已命名")); + save->click(); + waitFor([&]() { return saves == 3 && !save->isEnabled() + && stationIndex("P_B") >= 0 + && stations->itemText(stationIndex("P_B")).contains(QStringLiteral("终点B已命名")); }, + "renamed station saves and navigation label refreshes without changing ID"); + mapB = readMap("warehouse"); + require(stationName(mapB, "P_B") == QStringLiteral("终点B已命名") + && mapB.routes().size() == originalRouteCountB + 2 && hasRoute(mapB, "B_HOME_P_B"), + "saved rename retains station ID and route references"); + qInfo("PASS phase: map B add/undo/save and name change/undo/save preserve route references"); + + loadEditableMap("demo_map"); + mapA = readMap("demo_map"); + require(mapA.hasStation("P101") && !mapA.hasStation("P_B") + && hasRoute(mapA, "A_HOME_P1") && !hasRoute(mapA, "B_HOME_P_B") + && stationIndex("P101") >= 0 && stationIndex("P_B") < 0 + && stationName(mapA, "P101") == QStringLiteral("起点A"), + "returning to map A restores its saved station/route without map B edits"); + inspectObjects({"P101", "A_HOME_P1", QStringLiteral("起点A")}, + {"P_B", "B_HOME_P_B", QStringLiteral("终点B已命名")}); + loadEditableMap("warehouse"); + require(stationIndex("P_B") >= 0 && stationIndex("P101") < 0, + "returning to map B restores its saved navigation station"); + inspectObjects({"P_B", "B_HOME_P_B", QStringLiteral("终点B已命名")}, + {"P101", "A_HOME_P1", "UNDO_B", QStringLiteral("起点A")}); + qInfo("PASS phase: both maps reload saved objects and display names without leakage"); + + // Keep A's draft while B can load/edit/undo independently, then save A. + loadEditableMap("demo_map"); + addStation("A_DRAFT", QStringLiteral("草稿A"), -2.0, 1.0); + loadEditableMap("warehouse"); + inspectObjects({"P_B", QStringLiteral("终点B已命名")}, {"A_DRAFT", QStringLiteral("草稿A")}); + addStation("B_TEMP", QStringLiteral("临时B"), 4.0, 2.0); + inspectObjects({"B_TEMP", "P_B"}, {"A_DRAFT", "P101"}); + undo->click(); + require(!save->isEnabled() && !undo->isEnabled(), "map B can undo while map A's draft is retained"); + inspectObjects({"P_B"}, {"B_TEMP", "A_DRAFT"}); + loadPhysicalMap("demo_map"); + waitFor([&]() { return save->isEnabled() && undo->isEnabled(); }, + "returning to A restores its unsaved draft"); + inspectObjects({"A_DRAFT", "P101", "A_HOME_P1", QStringLiteral("草稿A")}, + {"P_B", "B_HOME_P_B", "B_TEMP"}); + require(!readMap("demo_map").hasStation("A_DRAFT") + && !readMap("warehouse").hasStation("A_DRAFT"), + "retained unsaved A draft has not been written into either map"); + save->click(); + waitFor([&]() { return saves == 4 && !save->isEnabled() && stationIndex("A_DRAFT") >= 0; }, + "restored A draft can be saved to A and offered for navigation"); + mapA = readMap("demo_map"); + mapB = readMap("warehouse"); + require(mapA.hasStation("A_DRAFT") && stationName(mapA, "A_DRAFT") == QStringLiteral("草稿A") + && !mapA.hasStation("B_TEMP") && !mapA.hasStation("P_B") + && !mapB.hasStation("A_DRAFT") && !mapB.hasStation("B_TEMP") + && stationName(mapB, "P_B") == QStringLiteral("终点B已命名"), + "saving restored A draft preserves map B's objects and names without leakage"); + loadEditableMap("warehouse"); + inspectObjects({"P_B", "B_HOME_P_B", QStringLiteral("终点B已命名")}, + {"A_DRAFT", "P101", QStringLiteral("草稿A"), QStringLiteral("起点A")}); + loadEditableMap("demo_map"); + inspectObjects({"P101", "A_DRAFT", "A_HOME_P1", QStringLiteral("起点A"), QStringLiteral("草稿A")}, + {"P_B", "B_HOME_P_B", QStringLiteral("终点B已命名")}); + qInfo("PASS phase: map A draft survives map B editing, returns and saves only to A"); + // Process a periodic AGV state update to check the editor context remains stable. + QElapsedTimer settle; + settle.start(); + while (settle.elapsed() < 900) { + app.processEvents(); + QThread::msleep(10); + } + require(coordinate->isEnabled() && !save->isEnabled(), "periodic refresh keeps editor ready"); + require(view->visibleRegion().contains(view->rect()), "map view fits its parent without clipping"); + for (QPushButton *button : sidebar->widget()->findChildren()) { + if (!button->isVisible()) + continue; + const QPoint position = button->mapTo(sidebar->viewport(), QPoint()); + require(position.x() >= 0 && position.x() + button->width() <= sidebar->viewport()->width(), + "all visible sidebar actions fit horizontally"); + } + if (argc > 1) + require(window.grab().save(QString::fromLocal8Bit(argv[1])), "AGV page screenshot saved"); + + const QVariantMap oldDemoState = latestDemoState; + const QImage oldDemoImage = latestDemoImage; + const QVariantMap oldDemoMetadata = latestDemoMetadata; + require(!oldDemoState.isEmpty() && !oldDemoImage.isNull(), "Demo snapshots are available for late callback checks"); + const auto requireEmptyMap = [&]() { + QPointF point; + require(view->mapId().isEmpty() && !view->widgetToWorld(QPointF(view->rect().center()), &point), + "context reset clears map ID, image and projection metadata"); + }; + const auto requireUnavailable = [&]() { + require(connectionValue->text().contains(QStringLiteral("状态不可用")) + && !connectionValue->text().contains(QStringLiteral("在线")) + && modeValue->text() != QStringLiteral("空闲"), + "unavailable state is visibly unavailable rather than inherited online/Idle state"); + requireEmptyMap(); + }; + const auto injectUnrelated = [&](QVariantMap context) { + QVariantMap state = context; + state.insert("connected", true); + state.insert("mode", 2); + state.insert("map", "FOREIGN_MAP"); + state.insert("error", "FOREIGN_ERROR"); + client->agvStateReceived(state, {}); + client->agvInventoryReceivedForContext(context, {"FOREIGN_MAP"}, + {QVariantMap{{"id", "FOREIGN_STATION"}, {"name", "foreign"}}}); + QVariantMap metadata = oldDemoMetadata; + for (auto it = context.cbegin(); it != context.cend(); ++it) + metadata.insert(it.key(), it.value()); + metadata.insert("mapId", "FOREIGN_MAP"); + emitFrame(oldDemoImage, metadata, "FOREIGN_DEMO_FRAME"); + }; + + // Changing only the device on this Demo connection immediately invalidates its UI. + const QString otherDevice = expectedDevice + QStringLiteral("_other"); + editorStatus->setText(QStringLiteral("旧 warehouse / demo_agv_1 读取失败")); + editorStatus->setStyleSheet(QStringLiteral("color:#c63e3e")); + id->setText(otherDevice); + requireEmptyMap(); + require(map->count() == 0 && stations->count() == 0 + && !connectionValue->text().contains(QStringLiteral("在线")) + && !editorStatus->text().contains(QStringLiteral("warehouse")) + && !editorStatus->text().contains(QStringLiteral("demo_agv_1")) + && !editorStatus->styleSheet().contains(QStringLiteral("#c63e3e")), + "device change clears old online state, inventories and old editor error"); + injectUnrelated(contextFor(expectedDevice, true)); + injectUnrelated(contextFor(otherDevice, false)); + QVariantMap otherEndpoint = contextFor(otherDevice, true); + otherEndpoint.insert("endpoint", "127.0.0.1:59999"); + injectUnrelated(otherEndpoint); + requireEmptyMap(); + require(map->count() == 0 && stations->count() == 0 + && !mapValue->text().contains("FOREIGN") && !errorValue->text().contains("FOREIGN"), + "late device/Demo/endpoint state, inventory and frames are all ignored"); + require(QMetaObject::invokeMethod(id, "editingFinished", Qt::DirectConnection), + "new Demo device edit completed"); + waitFor([&]() { return view->mapId() == "demo_map" && coordinate->isEnabled() + && map->count() == 2 && stations->findData("HOME") >= 0 + && connectionValue->text().contains(QStringLiteral("在线")) + && modeValue->text() == QStringLiteral("空闲"); }, + "new device's successful state, inventory and first map restore usable UI"); + require(stations->findData("P101") < 0 && stations->findData("A_DRAFT") < 0, + "same-connection device switch does not reuse previous device's saved stations"); + QVariantMap failedDemo = contextFor(otherDevice, true); + failedDemo.insert("available", false); + failedDemo.insert("connected", true); // A stale field must not override availability. + failedDemo.insert("mode", 2); + failedDemo.insert("error", "test unavailable runtime state"); + client->agvStateReceived(failedDemo, {}); + requireUnavailable(); + require(errorValue->text().contains("test unavailable runtime state"), "current state failure displays its actual detail"); + client->requestAgvRefresh(otherDevice); + client->requestAgvInventory(otherDevice); + waitFor([&]() { return connectionValue->text().contains(QStringLiteral("在线")) + && modeValue->text() == QStringLiteral("空闲") && view->mapId() == "demo_map" + && coordinate->isEnabled(); }, "successful Demo refresh restores availability after failure"); + id->setText(expectedDevice); + requireEmptyMap(); + QMetaObject::invokeMethod(id, "editingFinished", Qt::DirectConnection); + waitFor([&]() { return view->mapId() == "demo_map" && coordinate->isEnabled() + && stationIndex("P101") >= 0 && stationIndex("A_DRAFT") >= 0; }, + "returning to original device reloads only its saved objects"); + inspectObjects({"P101", "A_DRAFT", QStringLiteral("起点A")}, {"FOREIGN_STATION"}); + qInfo("PASS phase: device context reset, stale state/inventory/frame filtering and unavailable-state recovery"); + + client->disconnectFromServer(); + waitFor([&]() { return !coordinate->isEnabled(); }, "disconnect disables map editing"); + requireEmptyMap(); + client->connectToServer(host->text().trimmed(), port->value(), true); + waitFor([&]() { return coordinate->isEnabled() && view->mapId() == "demo_map"; }, + "Demo reconnect restores AGV editing and map stream"); + require(id->text() == expectedDevice, "Demo reconnect preserves device ID"); + client->disconnectFromServer(); + waitFor([&]() { return !coordinate->isEnabled(); }, "Demo disconnected after reconnect check"); + requireEmptyMap(); + + // Final real-mode UI fixture: no real server is contacted. Typed raw-map + // requests are answered locally after the worker has been disconnected. + editorStatus->setText(QStringLiteral("旧 warehouse / demo_agv_1 红字")); + demo->setChecked(false); + port->setValue(50053); + const QString liveDevice = QStringLiteral("src1100_test"); + id->setText(liveDevice); + require(QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, + Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic real UI only"))), + "real-mode UI connection state injected without starting transport"); + requireEmptyMap(); + require(map->count() == 0 && stations->count() == 0 + && !editorStatus->text().contains("warehouse") && !editorStatus->text().contains("demo_agv_1") + && !editorStatus->styleSheet().contains(QStringLiteral("#c63e3e")), + "Demo-to-real connection reset clears old raster, list and editor error"); + const QVariantMap liveContext = contextFor(liveDevice, false); + QVariantMap lateDemo = liveContext; + lateDemo.insert("demo", true); + injectUnrelated(lateDemo); + requireEmptyMap(); + require(map->count() == 0, "old Demo inventory cannot populate a real-mode connection"); + + const QString rawLive = QStringLiteral(R"({"header":{"map_type":"2D-Map","map_name":"real_map","resolution":0.05,"source":"test-real-context","min_pos":{"x":-5,"y":-2.5},"max_pos":{"x":5,"y":2.5}},"advanced_point_list":[{"class_name":"LandMark","instance_name":"REAL_HOME","description":"真实上下文测试点","pos":{"x":0,"y":0},"dir":0}],"advanced_curve_list":[]})"); + QObject::disconnect(client, &RobotClient::agvMapContentRequested, nullptr, nullptr); + QString rawPreviewB = rawLive; + rawPreviewB.replace("\"map_name\":\"real_map\"", "\"map_name\":\"real_map_0\""); + rawPreviewB.replace("REAL_HOME", "REAL_B"); + rawPreviewB.replace("真实上下文测试点", "目标预览测试点"); + rawPreviewB.replace("\"resolution\":0.05", "\"resolution\":0.1"); + rawPreviewB.replace("\"x\":-5", "\"x\":-10"); + rawPreviewB.replace("\"x\":5", "\"x\":10"); + rawPreviewB.replace("\"y\":-2.5", "\"y\":-5"); + rawPreviewB.replace("\"y\":2.5", "\"y\":5"); + QHash localMapContents{{"real_map", rawLive}, {"real_map_0", rawPreviewB}}; + QString fixtureDevice = liveDevice; + QObject::connect(client, &RobotClient::agvMapContentRequested, client, + [&](quint64 token, const QString &device, const QString &name) { + if (device == fixtureDevice && localMapContents.contains(name)) { + const QString content = localMapContents.value(name); + QTimer::singleShot(0, client, [=]() { + client->agvMapContentReceived(token, device, name, content, true, "local UI fixture"); + }); + } + }); + QStringList liveMaps{"real_map"}; + for (int index = 0; index < 32; ++index) + liveMaps.append(QStringLiteral("real_map_%1").arg(index)); + const QVariantList liveStations{QVariantMap{{"id", "REAL_HOME"}, {"name", QStringLiteral("真实上下文测试点")}}}; + QVariantMap liveState = liveContext; + liveState.insert("connected", true); + liveState.insert("mode", 2); + liveState.insert("localized", true); + liveState.insert("map", "real_map"); + liveState.insert("station", "REAL_HOME"); + client->agvStateReceived(liveState, {}); + client->agvInventoryReceivedForContext(liveContext, liveMaps, liveStations); + QImage liveImage(200, 100, QImage::Format_ARGB32_Premultiplied); + liveImage.fill(QColor("#acbdce")); + QVariantMap liveMetadata = liveContext; + liveMetadata.insert("mapId", "real_map"); + liveMetadata.insert("dimension", 2); + liveMetadata.insert("resolution", 0.05); + liveMetadata.insert("originX", -5.0); + liveMetadata.insert("originY", -2.5); + liveMetadata.insert("originTheta", 0.0); + liveMetadata.insert("renderScale", 1.0); + emitFrame(liveImage, liveMetadata, "local real-mode map fixture"); + waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() + && editorStatus->text().contains(QStringLiteral("地图已读取")); }, + "first current real-mode frame restores map projection and loads its editor document"); + require(map->count() == 33 && stations->findData("REAL_HOME") >= 0 + && map->findText("demo_map") < 0 && !mapListSummary->text().contains(QStringLiteral("演示")) + && connectionValue->text().contains(QStringLiteral("在线")), + "real inventory and online state replace Demo data without leftover badges"); + const QPointF probe = QPointF(view->rect().center()) + QPointF(60, 20); + QPointF beforeLateFrame; + require(view->widgetToWorld(probe, &beforeLateFrame), "new real-mode frame has valid projection"); + QVariantMap sameMapLateDemo = oldDemoMetadata; + sameMapLateDemo.insert("deviceId", liveDevice); + sameMapLateDemo.insert("endpoint", liveContext.value("endpoint")); + sameMapLateDemo.insert("demo", true); + sameMapLateDemo.insert("mapId", "real_map"); + emitFrame(oldDemoImage, sameMapLateDemo, "late DEMO frame with matching map ID"); + client->agvInventoryReceivedForContext(lateDemo, {"demo_map", "warehouse"}, {}); + QVariantMap staleState = liveState; + staleState.insert("demo", true); + staleState.insert("connected", false); + staleState.insert("mode", 1); + client->agvStateReceived(staleState, {}); + QPointF afterLateFrame; + require(view->widgetToWorld(probe, &afterLateFrame) + && (afterLateFrame - beforeLateFrame).manhattanLength() < 1e-9 + && map->count() == 33 && connectionValue->text().contains(QStringLiteral("在线")) + && modeValue->text() == QStringLiteral("空闲"), + "late Demo payloads cannot overwrite real image metadata, inventory or online state"); + QVariantMap liveOffline = liveState; + liveOffline.insert("connected", false); + liveOffline.insert("mode", 1); + client->agvStateReceived(liveOffline, {}); + require(connectionValue->text().contains(QStringLiteral("离线")) + && !connectionValue->text().contains(QStringLiteral("在线")) + && modeValue->text() == QStringLiteral("离线"), + "current real controller's disconnected mode is shown faithfully instead of forced online"); + client->agvStateReceived(liveState, {}); + QVariantMap failedLive = liveState; + failedLive.insert("available", false); + failedLive.insert("error", "real fixture unavailable"); + client->agvStateReceived(failedLive, {}); + requireUnavailable(); + client->agvStateReceived(liveState, {}); + client->agvInventoryReceivedForContext(liveContext, liveMaps, liveStations); + emitFrame(liveImage, liveMetadata, "recovered real-mode map fixture"); + waitFor([&]() { return connectionValue->text().contains(QStringLiteral("在线")) + && view->mapId() == "real_map" && coordinate->isEnabled(); }, + "successful current real-mode payloads restore usable UI after unavailability"); + qInfo("PASS phase: Demo-to-real clearing, first-frame recovery and same-map late Demo rejection without transport"); + + // Control ACK and runtime status independently: target preview must work + // before the vehicle accepts or actually completes a map switch. + observeDemoSwitches = false; + QObject::disconnect(client, &RobotClient::agvSwitchMapRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvMapSaveRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvMapStreamStartRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvMapStreamStopRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvRefreshRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvInventoryRequested, nullptr, nullptr); + int streamRequests = 0; + QString streamTarget; + bool streamPreview = false; + QObject::connect(client, &RobotClient::agvMapStreamStartRequested, + [&](const QString &device, const QString &target, int dimension, + bool, bool, quint64 generation, bool preview) { + require(device == fixtureDevice && dimension == 1 + && generation == client->agvMapStreamGeneration(), + "local stream request captures current device, 2D dimension and generation"); + ++streamRequests; + streamTarget = target; + streamPreview = preview; + }); + int previewRequests = 0; + QString requestedPreview; + QStringList localSaveMaps; + QObject::connect(client, &RobotClient::agvSwitchMapRequested, + [&](const QString &device, const QString &target) { + require(device == fixtureDevice, "synthetic switch targets the current fixture device"); + ++previewRequests; + requestedPreview = target; + }); + QObject::connect(client, &RobotClient::agvMapSaveRequested, client, + [&](quint64 token, const QString &device, const QString &name, const QString &content) { + require(device == fixtureDevice && localMapContents.contains(name), + "synthetic save targets a known current-device map"); + localSaveMaps.append(name); + localMapContents.insert(name, content); + QTimer::singleShot(0, client, [=]() { + client->agvMapSaveFinished(token, device, name, true, "local fixture saved without transport"); + }); + }); + auto *switchStatus = window.findChild("agvMapSwitchStatus"); + require(switchStatus != nullptr, "map-switch acceptance and vehicle confirmation have an observable status label"); + const auto robotPixels = [&]() { + const QImage rendered = view->grab().toImage(); + int count = 0; + for (int y = 0; y < rendered.height(); ++y) { + for (int x = 0; x < rendered.width(); ++x) { + const QColor color = rendered.pixelColor(x, y); + // These fixtures have no routes; saturated route-blue pixels + // therefore belong only to the AGV marker/label. + if (color.blue() > 200 && color.red() < 100 && color.green() < 160) + ++count; + } + } + return count; + }; + for (bool demoMode : {false, true}) { + localMapContents.insert("real_map", rawLive); + localMapContents.insert("real_map_0", rawPreviewB); + localSaveMaps.clear(); + fixtureDevice = demoMode ? liveDevice + "_preview_demo" : liveDevice; + demo->setChecked(demoMode); + id->setText(fixtureDevice); + QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, + Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic switch fixture"))); + const QVariantMap previewContext = contextFor(fixtureDevice, demoMode); + QVariantMap runtimeA = previewContext; + runtimeA.insert("connected", true); + runtimeA.insert("localized", true); + runtimeA.insert("mode", 2); + runtimeA.insert("map", "real_map"); + runtimeA.insert("station", "REAL_HOME"); + QVariantMap runtimeB = runtimeA; + runtimeB.insert("map", "real_map_0"); + runtimeB.insert("station", "REAL_B"); + QVariantMap metadataA = liveMetadata; + QVariantMap metadataB = liveMetadata; + for (auto it = previewContext.cbegin(); it != previewContext.cend(); ++it) { + metadataA.insert(it.key(), it.value()); + metadataB.insert(it.key(), it.value()); + } + metadataA.insert("mapId", "real_map"); + metadataB.insert("mapId", "real_map_0"); + metadataB.insert("resolution", 0.1); + metadataB.insert("originX", -10.0); + metadataB.insert("originY", -5.0); + QImage previewImage = liveImage; + previewImage.fill(QColor("#dcc9ad")); + client->agvStateReceived(runtimeA, {}); + client->agvInventoryReceivedForContext(previewContext, liveMaps, liveStations); + emitFrame(liveImage, metadataA, "synthetic map A"); + waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() + && !save->isEnabled(); }, "synthetic map A starts with a clean editable document"); + const QString draft = demoMode ? "PREVIEW_A_DEMO" : "PREVIEW_A_REAL"; + const QString failedDraft = demoMode ? "REJECT_A_DEMO" : "REJECT_A_REAL"; + addStation(draft, QStringLiteral("切图前草稿A"), 1.0, 0.5); + + const auto beginPreview = [&](const QString &target) { + const int previous = previewRequests; + map->setCurrentText(target); + waitFor([&]() { return loadMap->isEnabled(); }, "switch control is ready for explicit target preview"); + loadMap->click(); + require(previewRequests == previous + 1 && requestedPreview == target, + "click dispatches one explicit target switch while withholding ACK"); + requireEmptyMap(); + require(!coordinate->isEnabled(), "old map editing is disabled immediately before the target frame"); + }; + beginPreview("real_map_0"); + emitFrame(liveImage, metadataA, "late map A before target frame"); + requireEmptyMap(); + emitFrame(previewImage, metadataB, "target B before switch ACK"); + waitFor([&]() { return view->mapId() == "real_map_0"; }, + "target B is displayed before switch ACK arrives despite dirty map A"); + require(!coordinate->isEnabled(), "pending vehicle ACK keeps editing locked while B preview is displayed"); + QVariantMap unavailableDuringSwitch = runtimeA; + unavailableDuringSwitch.insert("available", false); + unavailableDuringSwitch.insert("error", "state refresh failed while switch pending"); + client->agvStateReceived(unavailableDuringSwitch, {}); + QPointF unavailableProjection; + require(view->mapId() == "real_map_0" && view->widgetToWorld(probe, &unavailableProjection) + && connectionValue->text().contains(QStringLiteral("状态不可用")) + && !connectionValue->text().contains(QStringLiteral("在线")) + && errorValue->text().contains("state refresh failed while switch pending"), + "unavailable same-context state during a pending switch preserves target B image and reports unavailability"); + client->agvStateReceived(runtimeA, {}); + QApplication::processEvents(); + require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map /"), + "recovery to runtime A during a pending switch cannot restore map A over target B preview"); + QPointF targetProjection; + require(view->widgetToWorld(probe, &targetProjection), "target B projection is usable before ACK"); + emitFrame(liveImage, metadataA, "late map A after target frame"); + QPointF afterOldA; + require(view->mapId() == "real_map_0" && view->widgetToWorld(probe, &afterOldA) + && (targetProjection - afterOldA).manhattanLength() < 1e-9, + "old A frames cannot replace target B projection before ACK"); + client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); + client->agvStateReceived(runtimeA, {}); + emitFrame(liveImage, metadataA, "late map A after accepted request"); + QApplication::processEvents(); + require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map /") + && switchStatus->text().contains(QStringLiteral("等待")) + && !switchStatus->text().contains(QStringLiteral("已确认")), + "accepted ACK with runtime A keeps B preview and honestly waits for vehicle confirmation"); + waitFor([&]() { return coordinate->isEnabled() + && editorStatus->text().contains(QStringLiteral("地图已读取")); }, + "after ACK target B is editable even while the vehicle still reports A"); + inspectObjects({"REAL_B"}, {draft, "REAL_HOME"}); + require(robotPixels() == 0, "vehicle A pose is hidden on a B preview while confirmation is pending"); + QVariantMap offlineRuntimeB = runtimeB; + offlineRuntimeB.insert("connected", false); + const int switchesBeforeOfflineState = previewRequests; + client->agvStateReceived(offlineRuntimeB, {}); + require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map_0 /") + && connectionValue->text().contains(QStringLiteral("离线")) + && !connectionValue->text().contains(QStringLiteral("在线")) + && switchStatus->text().contains(QStringLiteral("尚未确认")) + && !switchStatus->text().contains(QStringLiteral("已确认")), + "accepted ACK with an offline cached target map cannot confirm the current vehicle map"); + require(robotPixels() == 0, "offline cached target pose is hidden on its matching map preview"); + require(previewRequests == switchesBeforeOfflineState, + "offline cached target state never automatically resends the switch command"); + const int beforeConfirmedRefresh = streamRequests; + client->agvStateReceived(runtimeB, {}); + require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map_0 /") + && switchStatus->text().contains(QStringLiteral("已确认")), + "fresh matching runtime B confirms the vehicle map without changing its preview"); + require(streamRequests == beforeConfirmedRefresh + 1, + "vehicle confirmation re-reads the selected snapshot once after the initial pre-switch preview"); + for (int repeat = 0; repeat < 3; ++repeat) + client->agvStateReceived(runtimeB, {}); + require(streamRequests == beforeConfirmedRefresh + 1 + && previewRequests == switchesBeforeOfflineState, + "repeated confirmed runtime cannot refresh repeatedly or send another switch command"); + require(robotPixels() > 20, "matching runtime B makes its AGV marker visible on the B map"); + + beginPreview("real_map"); + emitFrame(liveImage, metadataA, "returning to map A draft"); + waitFor([&]() { return view->mapId() == "real_map"; }, + "returning to A displays its preview before ACK"); + client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); + client->agvStateReceived(runtimeA, {}); + waitFor([&]() { return coordinate->isEnabled() && save->isEnabled() && undo->isEnabled(); }, + "returning to A restores its unsaved draft after pending ACK releases editing"); + inspectObjects({draft, "REAL_HOME", QStringLiteral("切图前草稿A")}, {"REAL_B"}); + save->click(); + waitFor([&]() { return localSaveMaps.size() == 1 && !save->isEnabled(); }, + "restored A draft can be saved through only the local A fixture"); + AgvMapDocument savedA; + AgvMapDocument savedB; + QString error; + require(localSaveMaps.first() == "real_map" + && savedA.load(localMapContents.value("real_map"), &error) && savedA.hasStation(draft) + && savedB.load(localMapContents.value("real_map_0"), &error) && !savedB.hasStation(draft), + "A draft save retains map identity and never leaks into B content"); + + emitFrame(liveImage, metadataA, "map A refreshed after local save"); + waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() + && !save->isEnabled(); }, "saved map A remains ready after its preview refresh"); + + addStation(failedDraft, QStringLiteral("拒绝后保留草稿A"), 2.0, 0.5); + beginPreview("real_map_0"); + emitFrame(previewImage, metadataB, "target B pending rejected switch"); + waitFor([&]() { return view->mapId() == "real_map_0"; }, + "B preview appears before a rejected switch ACK"); + client->commandFinished("AGV SwitchMap", false, QStringLiteral("测试切换拒绝:请先定位")); + client->agvStateReceived(runtimeA, {}); + emitFrame(liveImage, metadataA, "late A after rejected switch"); + QApplication::processEvents(); + require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map /") + && switchStatus->text().contains(QStringLiteral("测试切换拒绝")), + "rejected ACK preserves B preview, displays its reason and keeps the actual vehicle on A"); + waitFor([&]() { return coordinate->isEnabled(); }, "rejected vehicle switch still releases B preview editing"); + require(robotPixels() == 0, "rejected B switch cannot show vehicle A's marker on B"); + inspectObjects({"REAL_B"}, {failedDraft, draft}); + const int switchesBeforeMatchingFailedState = previewRequests; + client->agvStateReceived(runtimeB, {}); + require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map_0 /") + && switchStatus->text().contains(QStringLiteral("车端当前使用该地图")) + && switchStatus->text().contains(QStringLiteral("此前切图请求失败")) + && switchStatus->text().contains(QStringLiteral("测试切换拒绝")) + && !switchStatus->text().contains(QStringLiteral("已确认")), + "online matching map state reports current use without rewriting a failed switch request as success"); + require(previewRequests == switchesBeforeMatchingFailedState, + "matching map state after a failed request never automatically resends the switch command"); + client->agvStateReceived(runtimeA, {}); + require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map /") + && switchStatus->text().contains(QStringLiteral("测试切换拒绝")) + && !switchStatus->text().contains(QStringLiteral("车端当前使用该地图")) + && !switchStatus->text().contains(QStringLiteral("已确认")) + && previewRequests == switchesBeforeMatchingFailedState, + "later runtime A retains the original failed-request detail and the selected B preview without a retry"); + require(robotPixels() == 0, "returning runtime A hides its marker from the retained B preview after a failed request"); + beginPreview("real_map"); + emitFrame(liveImage, metadataA, "A draft survives rejected B switch"); + waitFor([&]() { return view->mapId() == "real_map"; }, "A preview returns after a rejected B switch"); + client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); + client->agvStateReceived(runtimeA, {}); + waitFor([&]() { return coordinate->isEnabled() && save->isEnabled(); }, + "A draft survives a rejected switch and restores after its return ACK"); + inspectObjects({failedDraft, draft, "REAL_HOME"}, {"REAL_B"}); + require(localSaveMaps.size() == 1 && !savedB.hasStation(failedDraft), + "rejected switch never implicitly saves A draft or writes B"); + qInfo("PASS phase: %s target preview before ACK, runtime confirmation, rejected-switch preview and retained A drafts", + demoMode ? "synthetic Demo" : "synthetic real"); + + // The target has no first frame: a later fresh runtime state may + // recover its preview once, but repeated failures must stay bounded. + beginPreview("real_map_0"); + client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); + const quint64 firstAttempt = client->agvMapStreamGeneration(); + const int firstRequestCount = streamRequests; + const auto streamContext = [&](quint64 generation, const QString &error = QString()) { + QVariantMap result = previewContext; + result.insert("mapId", "real_map_0"); + result.insert("streamGeneration", QVariant::fromValue(generation)); + result.insert("preview", true); + if (!error.isEmpty()) + result.insert("error", error); + return result; + }; + QVariantMap staleB = metadataB; + staleB.insert("streamGeneration", QVariant::fromValue(firstAttempt - 1)); + emitFrame(previewImage, staleB, "old generation of the same target B"); + client->agvMapStreamStateChangedForContext( + streamContext(firstAttempt - 1, "stale generation error"), false, "stale generation stop"); + client->agvStateReceived(runtimeA, {}); + requireEmptyMap(); + require(streamRequests == firstRequestCount + && !switchStatus->text().contains("stale generation error"), + "same-map old generation frames and stop callbacks cannot display or restart the current preview"); + client->agvMapStreamStateChanged(false, "legacy generic stop without context"); + client->agvStateReceived(runtimeA, {}); + require(streamRequests == firstRequestCount, + "legacy generic stream state cannot initiate current UI recovery"); + + client->agvMapStreamStateChangedForContext( + streamContext(firstAttempt, "fixture first preview read failed"), false, + "fixture first preview read failed"); + require(switchStatus->text().contains("fixture first preview read failed"), + "current typed preview failure exposes its actual read error"); + client->agvStateReceived(runtimeA, {}); + require(streamRequests == firstRequestCount + 1 && streamTarget == "real_map_0" && streamPreview, + "fresh runtime A automatically retries the selected B preview exactly once"); + const quint64 retryAttempt = client->agvMapStreamGeneration(); + require(retryAttempt > firstAttempt, "automatic recovery creates a new stream generation"); + staleB.insert("streamGeneration", QVariant::fromValue(firstAttempt)); + emitFrame(previewImage, staleB, "late first-attempt B during its retry"); + requireEmptyMap(); + client->agvMapStreamStateChangedForContext( + streamContext(retryAttempt, "fixture retry preview read failed"), false, + "fixture retry preview read failed"); + for (int repeat = 0; repeat < 5; ++repeat) + client->agvStateReceived(runtimeA, {}); + require(streamRequests == firstRequestCount + 1 + && switchStatus->text().contains("fixture retry preview read failed"), + "repeated fresh state after the retry fails cannot create an automatic recovery loop"); + + QPushButton *refreshState = nullptr; + auto *agvPage = window.findChild("agvPage"); + require(agvPage != nullptr, "AGV page exists for its manual state refresh"); + for (QPushButton *button : agvPage->findChildren()) + if (button->text() == QStringLiteral("刷新状态")) + refreshState = button; + require(refreshState && refreshState->isEnabled(), "user can explicitly retry through the state refresh button"); + refreshState->click(); + client->agvStateReceived(runtimeA, {}); + require(streamRequests == firstRequestCount + 2 && streamTarget == "real_map_0" && streamPreview, + "manual refresh resets the retry budget and keeps the selected target B"); + emitFrame(previewImage, metadataB, "target B recovered after manual refresh"); + waitFor([&]() { return view->mapId() == "real_map_0" && coordinate->isEnabled(); }, + "current-generation first frame restores selected B after manual recovery"); + const int readyRequestCount = streamRequests; + client->agvMapStreamStateChangedForContext( + streamContext(client->agvMapStreamGeneration()), false, "static preview completed normally"); + for (int repeat = 0; repeat < 3; ++repeat) + client->agvStateReceived(runtimeA, {}); + require(streamRequests == readyRequestCount && view->mapId() == "real_map_0", + "a completed static preview with a valid frame does not restart on subsequent state refreshes"); + beginPreview("real_map"); + emitFrame(liveImage, metadataA, "A draft returns after bounded B recovery"); + client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); + client->agvStateReceived(runtimeA, {}); + waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() && save->isEnabled(); }, + "bounded recovery retains A's unsaved draft across target retry and manual refresh"); + inspectObjects({failedDraft, draft, "REAL_HOME"}, {"REAL_B"}); + require(localSaveMaps.size() == 1, "preview recovery never implicitly uploads an unsaved draft"); + qInfo("PASS phase: %s current-generation typed state, same-map stale callbacks and bounded target-preview recovery", + demoMode ? "synthetic Demo" : "synthetic real"); + + QPushButton *startLiveStream = nullptr; + QPushButton *stopLiveStream = nullptr; + for (QPushButton *button : agvPage->findChildren()) { + if (button->text() == QStringLiteral("启动地图流")) + startLiveStream = button; + if (button->text() == QStringLiteral("停止地图流")) + stopLiveStream = button; + } + auto *mappingName = agvPage->findChild("mappingNameEdit"); + require(startLiveStream && stopLiveStream && mappingName + && startLiveStream->isEnabled() && stopLiveStream->isEnabled(), + "live mapping stream controls remain available for explicit start and stop"); + mappingName->setText("real_map"); + const int beforeLiveStart = streamRequests; + startLiveStream->click(); + require(streamRequests == beforeLiveStart + 1 && streamTarget == "real_map" && !streamPreview, + "manual live start retains the original stream API instead of the static preview API"); + emitFrame(liveImage, metadataA, "manual live A first frame"); + waitFor([&]() { return coordinate->isEnabled() && save->isEnabled(); }, + "manual live start retains the current A draft"); + stopLiveStream->click(); + const int pausedRequestCount = streamRequests; + QVariantMap unavailableAfterStop = runtimeA; + unavailableAfterStop.insert("available", false); + unavailableAfterStop.insert("error", "fixture unavailable after manual stop"); + client->agvStateReceived(unavailableAfterStop, {}); + requireUnavailable(); + for (int repeat = 0; repeat < 3; ++repeat) + client->agvStateReceived(runtimeA, {}); + require(streamRequests == pausedRequestCount, + "manual stop remains paused across unavailable state clearing and subsequent successful refreshes"); + client->commandFinished("AGV StopMapping", true, "delayed stop-mapping ACK after manual stream stop"); + require(streamRequests == pausedRequestCount, + "a delayed successful StopMapping ACK cannot bypass manual stream pause"); + QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 0)); + client->commandFinished("AGV StopMapping", true, "delayed stop-mapping ACK outside the AGV page"); + require(streamRequests == pausedRequestCount, + "a successful StopMapping ACK outside AGV cannot start an invisible stream"); + QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 3)); + client->agvStateReceived(runtimeA, {}); + require(streamRequests == pausedRequestCount, + "leaving and reopening AGV cannot implicitly restart a manually stopped stream"); + requireEmptyMap(); + refreshState->click(); + client->agvStateReceived(runtimeA, {}); + require(streamRequests == pausedRequestCount + 1 && streamTarget == "real_map" && streamPreview, + "explicit refresh releases manual pause and reloads the fresh current map once"); + emitFrame(liveImage, metadataA, "A resumes only after explicit refresh"); + waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() && save->isEnabled(); }, + "explicit refresh restores the A frame and its retained test-owned draft"); + inspectObjects({failedDraft, draft, "REAL_HOME"}, {"REAL_B"}); + require(localSaveMaps.size() == 1, "manual stop and explicit recovery do not upload a draft"); + qInfo("PASS phase: %s manual stop survives failed/successful state, delayed StopMapping ACK and page changes until explicit refresh", + demoMode ? "synthetic Demo" : "synthetic real"); + + // Refresh is tied to each explicit switch, including switching to the + // same map. A target name in an old cache or before the ACK is no proof. + QVariantMap timedA = runtimeA; + timedA.insert("timestamp", 100.0); + client->agvStateReceived(timedA, {}); + const int sameMapSwitches = previewRequests; + const int sameMapStreams = streamRequests; + map->setCurrentText("real_map"); + loadMap->click(); + require(previewRequests == sameMapSwitches + 1 && streamRequests == sameMapStreams + 1, + "same-map click sends one switch and one initial preview"); + const quint64 beforeActivationGeneration = client->agvMapStreamGeneration(); + QVariantMap freshA = timedA; + freshA.insert("timestamp", 101.0); + client->agvStateReceived(freshA, {}); + require(streamRequests == sameMapStreams + 1, + "matching target state before ACK cannot trigger activation refresh"); + client->commandFinished("AGV SwitchMap", true, "same-map ACK"); + client->agvStateReceived(timedA, {}); + QVariantMap untypedA = freshA; + untypedA.remove("deviceId"); + untypedA.remove("endpoint"); + untypedA.remove("demo"); + client->agvStateReceived(untypedA, {}); + QVariantMap oldGenerationA = freshA; + oldGenerationA.insert("streamGeneration", QVariant::fromValue(beforeActivationGeneration - 1)); + client->agvStateReceived(oldGenerationA, {}); + require(streamRequests == sameMapStreams + 1 + && !switchStatus->text().contains(QStringLiteral("已确认")), + "same-map cached timestamp and untyped target state do not confirm the new request"); + client->agvStateReceived(freshA, {}); + require(streamRequests == sameMapStreams + 2 + && client->agvMapStreamGeneration() > beforeActivationGeneration, + "fresh post-ACK same-map state causes one new snapshot generation"); + QVariantMap oldSameMap = metadataA; + oldSameMap.insert("streamGeneration", QVariant::fromValue(beforeActivationGeneration)); + emitFrame(liveImage, oldSameMap, "old pre-activation same-map frame"); + for (int repeat = 0; repeat < 3; ++repeat) { + client->agvStateReceived(freshA, {}); + client->commandFinished("AGV SwitchMap", true, "duplicate old ACK"); + } + require(streamRequests == sameMapStreams + 2 && previewRequests == sameMapSwitches + 1, + "old same-map frames, duplicate ACKs and repeated state cannot repeat the confirmed refresh"); + loadMap->click(); + const int nextSameMapStreams = streamRequests; + client->commandFinished("AGV SwitchMap", false, "same-map rejected ACK"); + freshA.insert("timestamp", 102.0); + client->agvStateReceived(freshA, {}); + require(streamRequests == nextSameMapStreams && previewRequests == sameMapSwitches + 2, + "a failed same-map request cannot inherit the preceding request's confirmation"); + qInfo("PASS phase: %s one activation refresh per explicit request, fresh timestamps, typed context, same-map switches and failed-request isolation", + demoMode ? "synthetic Demo" : "synthetic real"); + } + // Exercise the direct-mode UI with synthetic signals only. Keep its TCP + // implementation disabled in RobotClient; all relevant service signals + // were disconnected above, and no direct operation reaches the worker. + editor->setAutoLoadEnabled(false); + QObject::disconnect(client, &RobotClient::agvActionRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvVelocityRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvNavigatePoseRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvNavigateStationRequested, nullptr, nullptr); + QObject::disconnect(client, &RobotClient::agvFollowPathRequested, nullptr, nullptr); + fixtureDevice = liveDevice + QStringLiteral("_direct_ui"); + demo->setChecked(false); + id->setText(fixtureDevice); + mapDirectMode->setCurrentIndex(1); + QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, + Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic direct UI only"))); + const auto disableDirectTransport = [&]() { + client->configureAgvMapDirect(false, QString(), host->text().trimmed(), 50053); + }; + disableDirectTransport(); + const auto directContext = contextFor(fixtureDevice, false); + QVariantMap directRuntimeA = directContext; + directRuntimeA.insert("connected", true); + directRuntimeA.insert("localized", true); + directRuntimeA.insert("mode", 2); + directRuntimeA.insert("map", "real_map"); + directRuntimeA.insert("station", "REAL_HOME"); + QVariantMap directRuntimeB = directRuntimeA; + directRuntimeB.insert("map", "real_map_0"); + directRuntimeB.insert("station", "REAL_B"); + QVariantMap directMetadataA = liveMetadata; + QVariantMap directMetadataB = liveMetadata; + for (auto it = directContext.cbegin(); it != directContext.cend(); ++it) { + directMetadataA.insert(it.key(), it.value()); + directMetadataB.insert(it.key(), it.value()); + } + directMetadataA.insert("mapId", "real_map"); + directMetadataB.insert("mapId", "real_map_0"); + client->agvStateReceived(directRuntimeA, {}); + client->agvInventoryReceivedForContext(directContext, liveMaps, liveStations); + emitFrame(liveImage, directMetadataA, "synthetic direct map A"); + waitFor([&]() { return view->mapId() == "real_map" && loadMap->isEnabled(); }, + "synthetic direct UI starts with a usable local map and no TCP operation"); + + auto *directPage = window.findChild("agvPage"); + require(directPage != nullptr, "direct UI controls belong to the AGV page"); + const auto buttonWithText = [&](const QString &text) { + for (QPushButton *button : directPage->findChildren()) + if (button->text() == text) + return button; + return static_cast(nullptr); + }; + auto *directNavigate = buttonWithText(QStringLiteral("导航到目标位姿")); + auto *directForward = buttonWithText(QStringLiteral("前进 (W)")); + auto *directStop = buttonWithText(QStringLiteral("停止")); + auto *directVelocityStop = buttonWithText(QStringLiteral("停止速度")); + auto *directEmergency = buttonWithText(QStringLiteral("AGV 急停")); + require(directNavigate && directForward && directStop && directVelocityStop && directEmergency, + "direct UI exposes navigation, manual motion, stop and emergency controls"); + require(directNavigate->isEnabled() && directForward->isEnabled() + && mapDirectMode->isEnabled() && mapDirectHost->isEnabled(), + "direct UI motion and connection controls are ready before a map operation"); + QStringList syntheticStops; + QObject::connect(client, &RobotClient::agvActionRequested, client, + [&](const QString &device, const QString &action) { + require(device == fixtureDevice, "synthetic stop retains the selected direct device"); + syntheticStops.append(action); + }); + client->agvMapDirectBusyChanged(true); + require(!directNavigate->isEnabled() && !directForward->isEnabled() + && !mapDirectMode->isEnabled() && !mapDirectHost->isEnabled() + && !loadMap->isEnabled() && directStop->isEnabled() + && directVelocityStop->isEnabled() && directEmergency->isEnabled(), + "direct busy disables navigation, manual motion, switching and connection options while retaining stop controls"); + directStop->click(); + directVelocityStop->click(); + directEmergency->click(); + require(syntheticStops.contains(QStringLiteral("StopVelocity")) + && syntheticStops.contains(QStringLiteral("EmergencyStop")), + "busy direct UI can dispatch stop and emergency through disconnected synthetic service signals"); + client->agvMapDirectBusyChanged(false); + require(directNavigate->isEnabled() && directForward->isEnabled() + && mapDirectMode->isEnabled() && mapDirectHost->isEnabled() && loadMap->isEnabled(), + "physical direct completion restores motion and connection controls"); + + map->setCurrentText("real_map_0"); + const int directSwitchCount = previewRequests; + loadMap->click(); + require(previewRequests == directSwitchCount + 1 + && switchStatus->text().contains(QStringLiteral("正在请求车辆切换")), + "direct-mode presentation stays pending until a synthetic command acknowledgement arrives"); + emitFrame(liveImage, directMetadataB, "synthetic direct target B"); + waitFor([&]() { return view->mapId() == "real_map_0"; }, + "direct target preview is independent of vehicle switch acknowledgement"); + client->agvDirectMapSwitchConfirmed(fixtureDevice, "real_map_0", "old confirmation before this ACK"); + require(!switchStatus->text().contains(QStringLiteral("已确认")), + "a typed confirmation delivered before this request's ACK cannot confirm the new direct switch"); + client->commandFinished("AGV SwitchMap", true, + QStringLiteral("切图请求已接受,车辆当前地图待确认")); + client->agvStateReceived(directRuntimeB, {}); + require(switchStatus->text().contains(QStringLiteral("待确认")) + && !switchStatus->text().contains(QStringLiteral("已确认")) + && !switchStatus->styleSheet().contains(QStringLiteral("#16835e")), + "matching connected service-cache map cannot promote an uncertain direct switch to confirmed green"); + QVariantMap cachedOfflineTarget = directRuntimeB; + cachedOfflineTarget.insert("connected", false); + client->agvStateReceived(cachedOfflineTarget, {}); + require(switchStatus->text().contains(QStringLiteral("待确认")) + && !switchStatus->text().contains(QStringLiteral("已确认")), + "matching offline service-cache map also leaves the direct request unconfirmed"); + client->agvDirectMapSwitchConfirmed("wrong_direct_device", "real_map_0", "wrong-context fixture"); + client->agvDirectMapSwitchConfirmed(fixtureDevice, "real_map", "wrong-map fixture"); + require(!switchStatus->text().contains(QStringLiteral("已确认")), + "typed direct confirmation rejects a different device or target map"); + const int directBeforeConfirmedRefresh = streamRequests; + client->agvMapDirectBusyChanged(true); + client->agvDirectMapSwitchConfirmed(fixtureDevice, "real_map_0", "synthetic direct completion"); + require(streamRequests == directBeforeConfirmedRefresh, + "direct confirmation waits for the previous transport operation to physically finish before re-reading"); + client->agvMapDirectBusyChanged(false); + waitFor([&]() { return streamRequests == directBeforeConfirmedRefresh + 1; }, + "direct transport completion releases one deferred snapshot refresh"); + require(switchStatus->text().contains(QStringLiteral("车辆直连已确认本次切图完成")) + && switchStatus->styleSheet().contains(QStringLiteral("#16835e")), + "only matching typed direct confirmation marks this switch completed and green"); + require(previewRequests == directSwitchCount + 1, + "cache changes and typed confirmation never resend a direct switch request"); + require(streamRequests == directBeforeConfirmedRefresh + 1, + "matching typed direct completion refreshes the selected snapshot once"); + client->agvDirectMapSwitchConfirmed(fixtureDevice, "real_map_0", "duplicate direct completion"); + client->agvStateReceived(directRuntimeB, {}); + require(streamRequests == directBeforeConfirmedRefresh + 1, + "duplicate direct confirmation and service-cache state cannot repeat the snapshot refresh"); + + // A port-only source change must invalidate the prior typed confirmation, + // even though the direct vehicle/configuration settings would be equal. + port->setValue(port->value() == 50053 ? 50054 : 50053); + disableDirectTransport(); + require(switchStatus->isHidden() && mapDirectHost->text().isEmpty(), + "source-port change clears the previous direct confirmation and vehicle override"); + const QVariantMap changedDirectContext = contextFor(fixtureDevice, false); + for (auto it = changedDirectContext.cbegin(); it != changedDirectContext.cend(); ++it) { + directRuntimeB.insert(it.key(), it.value()); + directMetadataB.insert(it.key(), it.value()); + } + directRuntimeB.insert("connected", true); + client->agvStateReceived(directRuntimeB, {}); + client->agvInventoryReceivedForContext(changedDirectContext, liveMaps, liveStations); + emitFrame(liveImage, directMetadataB, "synthetic direct B after source change"); + waitFor([&]() { return view->mapId() == "real_map_0" && loadMap->isEnabled(); }, + "source-changed direct UI accepts only the new local map context"); + map->setCurrentText("real_map_0"); + loadMap->click(); + client->commandFinished("AGV SwitchMap", true, + QStringLiteral("切图请求已接受,新的连接仍待确认")); + client->agvStateReceived(directRuntimeB, {}); + require(switchStatus->text().contains(QStringLiteral("待确认")) + && !switchStatus->text().contains(QStringLiteral("已确认")) + && !switchStatus->styleSheet().contains(QStringLiteral("#16835e")), + "a new source cannot reuse the previous map's typed direct confirmation"); + qInfo("PASS phase: synthetic direct pending/uncertain/confirmed states, service-cache isolation, busy controls and source invalidation without TCP"); + + QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, + Q_ARG(bool, false), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic test complete"))); + if (argc > 1) { + QFile log(QString::fromLocal8Bit(argv[1]) + ".log"); + require(log.open(QIODevice::WriteOnly | QIODevice::Text), "test log opened"); + log.write("PASS: AGV initialization/layout, 64-map inventory, two-map edits/names/drafts, device and Demo/real context reset, late callbacks, availability recovery, staged map-switch ACK and bounded generation-safe preview recovery\n"); + } + qInfo("PASS: AGV page layout/64 entries, two-map edits/names/drafts, device/Demo-real context reset, staged map-switch ACK and bounded generation-safe preview recovery"); + return 0; +} diff --git a/tests/agvvelocityramp_test.cpp b/tests/agvvelocityramp_test.cpp new file mode 100644 index 0000000..d725420 --- /dev/null +++ b/tests/agvvelocityramp_test.cpp @@ -0,0 +1,239 @@ +#include "../src/agvvelocityramp.h" + +#include +#include +#include +#include + +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::quiet_NaN(); + const auto infinity = std::numeric_limits::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; +} diff --git a/tests/robotclient_agvmanualvelocity_test.cpp b/tests/robotclient_agvmanualvelocity_test.cpp new file mode 100644 index 0000000..e4f5324 --- /dev/null +++ b/tests/robotclient_agvmanualvelocity_test.cpp @@ -0,0 +1,264 @@ +#include "robotclient.h" +#include "cmvr/api/agv_service.grpc.pb.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 &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 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 velocities{0}; + std::atomic stops{0}; + std::atomic hold{false}; + std::atomic reject{false}; + std::atomic rpcFail{false}; + std::mutex mutex; + std::vector receivedIds; + std::vector 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> 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; +} diff --git a/tests/robotclient_seer_map_integration_test.cpp b/tests/robotclient_seer_map_integration_test.cpp new file mode 100644 index 0000000..6a84527 --- /dev/null +++ b/tests/robotclient_seer_map_integration_test.cpp @@ -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 + +#include +#include + +#include + +namespace { +const QString deviceId = QStringLiteral("fixture_seer"); + +void waitFor(const std::function &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 lists{0}; + std::atomic 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 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 reads{0}; + std::atomic uploads{0}; + std::atomic switches{0}; + std::atomic velocities{0}; + std::atomic velocitiesFinished{0}; + std::atomic 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 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 busyEvents; + std::map> readEvents; + std::map> saveEvents; + std::vector switchEvents; + std::vector> 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 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; +} diff --git a/tests/seeragvmapclient_fake.h b/tests/seeragvmapclient_fake.h new file mode 100644 index 0000000..501a1ca --- /dev/null +++ b/tests/seeragvmapclient_fake.h @@ -0,0 +1,266 @@ +#pragma once +#include "seeragvmapclient.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +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 reads{0}; + std::atomic uploads{0}; + std::atomic switches{0}; + std::atomic acquires{0}; + std::atomic speedReads{0}; + std::atomic taskReads{0}; + std::atomic loadReads{0}; + std::atomic currentMapReads{0}; + std::atomic fragment{false}; + std::atomic readDelayMs{0}; + std::mutex captureMutex; + QByteArray uploaded; + QString requestedReadName; + QString requestedSwitchName; + QString nickName; + std::vector order; + + QByteArray response(quint16 command, const QByteArray &body) + { + const QJsonObject json = QJsonDocument::fromJson(body).object(); + { + std::lock_guard 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 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 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 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 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(m_port.load()); } + +private: + struct Peer { + std::unique_ptr 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(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(replySequence, reinterpret_cast(packet.data() + 2)); + qToBigEndian(static_cast(body.size()), reinterpret_cast(packet.data() + 4)); + qToBigEndian(replyType, reinterpret_cast(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 peers; + while (!m_stop.load()) { + listener.waitForNewConnection(2); + while (listener.hasPendingConnections()) + peers.push_back({std::unique_ptr(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(peer.buffered.constData()); + require(header[0] == 0x5a && header[1] == 1, "request uses valid SEER frame header"); + const quint32 length = qFromBigEndian(header + 4); + require(length <= 64 * 1024 * 1024, "request payload bounded"); + if (static_cast(peer.buffered.size()) < 16ULL + length) + break; + const quint16 sequence = qFromBigEndian(header + 2); + const quint16 command = qFromBigEndian(header + 8); + require(sequence != 0, "requests have nonzero sequence"); + const QByteArray body = peer.buffered.mid(16, static_cast(length)); + peer.buffered.remove(0, 16 + static_cast(length)); + reply(peer, command, sequence, m_fixture.response(command, body)); + } + } + } + } + + Fixture &m_fixture; + std::atomic m_stop{false}; + std::atomic m_failed{false}; + std::atomic 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 diff --git a/tests/seeragvmapclient_test.cpp b/tests/seeragvmapclient_test.cpp new file mode 100644 index 0000000..1e16038 --- /dev/null +++ b/tests/seeragvmapclient_test.cpp @@ -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 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 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 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; +}