diff --git a/CMakeLists.txt b/CMakeLists.txt index d51ab7a..55df4c3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -152,6 +152,8 @@ if(CMVR_WITH_MSQUIC) endif() set(CMVR_SOURCES + src/agvmapviewwidget.cpp + src/agvmapviewwidget.h src/audiostreammanager.cpp src/audiostreammanager.h src/configeditorwidget.cpp diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index d2633e4..dbb8f81 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -237,6 +237,7 @@ CONFIG(debug, debug|release) { !exists($$ASSIMP_SCENE_PARSER): error("Qt3D Assimp scene parser not found in the selected Qt Kit.") SOURCES += \ + src/agvmapviewwidget.cpp \ src/audiostreammanager.cpp \ src/configeditorwidget.cpp \ src/main.cpp \ @@ -252,6 +253,7 @@ SOURCES += \ ui/handeyecalibrationwidget.cpp HEADERS += \ + src/agvmapviewwidget.h \ src/audiostreammanager.h \ src/configeditorwidget.h \ src/mainwindow.h \ diff --git a/protos/cmvr/api/agv_command.proto b/protos/cmvr/api/agv_command.proto index d6c6649..7ddb71b 100644 --- a/protos/cmvr/api/agv_command.proto +++ b/protos/cmvr/api/agv_command.proto @@ -37,6 +37,23 @@ message AgvNavigationStatusCommand { } } + +// 在当前活动地图中重新设置 AGV 定位位姿。 +message AgvRelocalizeCommand { + message Request { + // header.device_id 指定目标 AGV 设备。 + CommandHeader.Request header = 1; + // x/y 单位:米,theta 单位:弧度,逆时针为正。 + cmvr.msgs.AgvPose2d pose = 2; + } + + message Feedback { + // 成功仅表示控制器接受命令,不表示定位已经收敛。 + CommandHeader.Feedback header = 1; + } +} + + // 导航到指定地图位姿命令。 message AgvNavigateToPoseCommand { // 请求体。 @@ -45,7 +62,7 @@ message AgvNavigateToPoseCommand { CommandHeader.Request header = 1; // 目标位姿。x/y 单位:米,theta 单位:弧度。 cmvr.msgs.AgvPose2d pose = 2; - // 通用运动约束和执行选项。 + // 通用运动约束和执行选项;默认同步阻塞至任务终态并确认停车。 cmvr.msgs.AgvMotionOptions options = 3; // AGV 适配器扩展参数,用于传递厂商特有选项。 cmvr.msgs.AgvAdapterParams adapter_params = 4; @@ -65,7 +82,7 @@ message AgvNavigateToStationCommand { CommandHeader.Request header = 1; // 目标站点 id。 string station_id = 2; - // 通用运动约束和执行选项。 + // 通用运动约束和执行选项;默认同步阻塞至任务终态并确认停车。 cmvr.msgs.AgvMotionOptions options = 3; // AGV 适配器扩展参数,用于传递厂商特有选项。 cmvr.msgs.AgvAdapterParams adapter_params = 4; @@ -85,7 +102,7 @@ message AgvFollowPathCommand { CommandHeader.Request header = 1; // 路径段列表。每段包含起点站点 id 和终点站点 id。 repeated cmvr.msgs.AgvPathSegment path = 2; - // 通用执行选项。上位机使用异步模式提交任务,并通过导航状态接口跟踪进度。 + // 通用执行选项;默认同步阻塞至整条路径终态并确认停车。 cmvr.msgs.AgvMotionOptions options = 3; } // 反馈体。 @@ -95,6 +112,23 @@ message AgvFollowPathCommand { } } + +// 按指定速度执行固定距离平移命令。 +message AgvTranslateCommand { + message Request { + // 通用请求头。header.device_id 指定目标 AGV 设备。 + CommandHeader.Request header = 1; + // 固定距离平移参数。 + cmvr.msgs.AgvTranslation translation = 2; + } + + message Feedback { + // 仅表示控制器是否接受命令,不表示平移已经完成。 + CommandHeader.Feedback header = 1; + } +} + + // 下发底盘速度命令。 message AgvSetVelocityCommand { // 请求体。 diff --git a/protos/cmvr/api/agv_service.proto b/protos/cmvr/api/agv_service.proto index f0bdc5b..b8de93d 100644 --- a/protos/cmvr/api/agv_service.proto +++ b/protos/cmvr/api/agv_service.proto @@ -20,6 +20,9 @@ service AgvService { // 清除可恢复故障或告警。 rpc clearFault(CommandHeader.Request) returns (CommandHeader.Feedback); + // 在当前活动地图中重新设置定位位姿。调用前 AGV 必须已经停止。 + rpc relocalize(AgvRelocalizeCommand.Request)returns (AgvRelocalizeCommand.Feedback); + // 导航到指定地图位姿。目标位姿 x/y 单位为米,theta 单位为弧度。 rpc navigateToPose(AgvNavigateToPoseCommand.Request) returns (AgvNavigateToPoseCommand.Feedback); @@ -69,4 +72,8 @@ service AgvService { // 停止当前建图/扫图会话。 rpc stopMapping(CommandHeader.Request) returns (CommandHeader.Feedback); + + + // 按指定速度平移固定距离。成功返回仅表示控制器已接受命令。 + rpc translate(AgvTranslateCommand.Request) returns (AgvTranslateCommand.Feedback); } diff --git a/protos/cmvr/msgs/agv.proto b/protos/cmvr/msgs/agv.proto index 54439ee..39109f4 100644 --- a/protos/cmvr/msgs/agv.proto +++ b/protos/cmvr/msgs/agv.proto @@ -1,5 +1,7 @@ syntax = "proto3"; +// 文件随 AGV API 定义统一放在 cmvr/api 下,但保留 cmvr.msgs package, +// 以兼容既有生成代码、消息完整名称和 Any type URL。 package cmvr.msgs; // AGV 在地图平面坐标系中的二维位姿。 @@ -12,6 +14,29 @@ message AgvPose2d { double theta = 3; } +// 固定距离平移使用的距离参考模式。 +enum AgvTranslationMode { + // 根据底盘里程计算运动距离。 + AGV_TRANSLATION_MODE_ODOMETRY = 0; + // 根据定位结果计算运动距离。 + AGV_TRANSLATION_MODE_LOCALIZATION = 1; +} + + + +// AGV 车体坐标系下的固定距离平移参数。 +message AgvTranslation { + // 平移距离的绝对值,单位:米,必须大于 0。 + double distance = 1; + // 车体 X 方向速度,单位:米/秒;正为向前,负为向后。 + double vx = 2; + // 车体 Y 方向速度,单位:米/秒;正为向左,负为向右。 + double vy = 3; + // 距离参考模式;默认使用里程模式。 + AgvTranslationMode mode = 4; +} + + // AGV 车体坐标系下的平面速度。 message AgvVelocity { // 车体 X 方向线速度,单位:米/秒。 @@ -22,6 +47,9 @@ message AgvVelocity { double wz = 3; } + + + // AGV 电池状态。 message AgvBatteryState { // 电量比例,范围:[0, 1],例如 0.8 表示 80%。 @@ -52,8 +80,17 @@ message AgvMotionOptions { double reach_angle = 6; // 速度比例,范围通常为 [0, 1];1 表示不降速。 double speed_ratio = 7; - // 是否异步执行;true 表示下发任务后立即返回。 + // 是否异步执行;false(默认)表示到达、失败、取消或遇障停止后才返回, + // true 表示任务被控制器接受后立即返回。 bool asynchronous = 8; + // 同步导航的最大等待时间,单位:毫秒;0 表示使用适配器默认值。 + // gRPC deadline 应大于该值或预计行程时间,否则服务端会安全取消导航。 + int32 wait_timeout_ms = 9; + // 同步导航的状态轮询周期,单位:毫秒;0 表示使用适配器默认值。 + int32 poll_interval_ms = 10; + // 连续遇障且底盘停止时的最大等待时间,单位:毫秒; + // 0 或未传表示使用适配器默认值 60000 毫秒。 + int32 blocked_timeout_ms = 11; } // AGV 适配器扩展参数。用于传递厂商或控制器特有的参数。 diff --git a/src/agvmapviewwidget.cpp b/src/agvmapviewwidget.cpp new file mode 100644 index 0000000..ef13cc6 --- /dev/null +++ b/src/agvmapviewwidget.cpp @@ -0,0 +1,286 @@ +#include "agvmapviewwidget.h" + +#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; +} + +AgvMapViewWidget::AgvMapViewWidget(QWidget *parent) + : QWidget(parent) +{ + setMinimumSize(420, 320); + setMouseTracking(true); + setCursor(Qt::OpenHandCursor); + setFocusPolicy(Qt::StrongFocus); + setAutoFillBackground(false); +} + +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(); + } + m_image = image; + m_metadata = metadata; + update(); +} + +void AgvMapViewWidget::updateRobotPose(double x, double y, double theta, + bool localized) +{ + m_robotX = x; + m_robotY = y; + m_robotTheta = theta; + m_localized = localized; + m_hasPose = qIsFinite(x) && qIsFinite(y) && qIsFinite(theta); + + if (m_hasPose && localized && canProjectPose()) { + const QPointF next(x, y); + if (m_trajectory.isEmpty() + || QLineF(m_trajectory.constLast(), next).length() + >= kTrajectoryMinimumDistance) { + m_trajectory.append(next); + if (m_trajectory.size() > kMaximumTrajectoryPoints) + m_trajectory.remove(0, m_trajectory.size() + - kMaximumTrajectoryPoints); + } + } + update(); +} + +void AgvMapViewWidget::setStreamMessage(const QString &message) +{ + m_streamMessage = message; + update(); +} + +void AgvMapViewWidget::zoomIn() +{ + changeZoom(1.25, rect().center()); +} + +void AgvMapViewWidget::zoomOut() +{ + changeZoom(0.8, rect().center()); +} + +void AgvMapViewWidget::resetView() +{ + m_zoom = 1.0; + m_pan = QPointF(); + update(); +} + +void AgvMapViewWidget::clearTrajectory() +{ + m_trajectory.clear(); + update(); +} + +bool AgvMapViewWidget::canProjectPose() const +{ + 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; +} + +QPointF AgvMapViewWidget::worldToImage(double x, double y) const +{ + const double originX = m_metadata.value(QStringLiteral("originX")).toDouble(); + const double originY = m_metadata.value(QStringLiteral("originY")).toDouble(); + const double originTheta = m_metadata.value(QStringLiteral("originTheta")).toDouble(); + const double resolution = m_metadata.value(QStringLiteral("resolution")).toDouble(); + const double renderScale = m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble(); + + const double dx = x - originX; + const double dy = y - originY; + const double cosine = qCos(originTheta); + const double sine = qSin(originTheta); + const double gridX = (cosine * dx + sine * dy) / resolution; + const double gridY = (-sine * dx + cosine * dy) / resolution; + return QPointF(gridX * renderScale, + m_image.height() - gridY * renderScale); +} + +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()); + return qMin(horizontal, vertical) * m_zoom; +} + +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; +} + +QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const +{ + return imageTopLeft() + point * viewScale(); +} + +void AgvMapViewWidget::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event) + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.fillRect(rect(), QColor(QStringLiteral("#eef2f6"))); + + if (m_image.isNull()) { + painter.setPen(QColor(QStringLiteral("#71808e"))); + painter.drawText(rect(), Qt::AlignCenter, + m_streamMessage.isEmpty() + ? QStringLiteral("等待 AGV 返回地图数据") + : m_streamMessage); + return; + } + + const double scale = viewScale(); + const QPointF topLeft = imageTopLeft(); + const QRectF target(topLeft, + QSizeF(m_image.width() * scale, + m_image.height() * scale)); + painter.setRenderHint(QPainter::SmoothPixmapTransform, true); + painter.drawImage(target, m_image); + painter.setPen(QPen(QColor(QStringLiteral("#c9d4de")), 1)); + painter.setBrush(Qt::NoBrush); + painter.drawRect(target); + + if (canProjectPose() && m_trajectory.size() > 1) { + QPainterPath path; + path.moveTo(imageToWidget(worldToImage( + m_trajectory.first().x(), m_trajectory.first().y()))); + for (int index = 1; index < m_trajectory.size(); ++index) { + path.lineTo(imageToWidget(worldToImage( + m_trajectory.at(index).x(), m_trajectory.at(index).y()))); + } + painter.setPen(QPen(QColor(QStringLiteral("#2f6fed")), 2, + Qt::DashLine, Qt::RoundCap, Qt::RoundJoin)); + painter.drawPath(path); + } + + if (canProjectPose() && m_hasPose) { + const QPointF center = imageToWidget(worldToImage(m_robotX, m_robotY)); + const double originTheta = m_metadata.value( + QStringLiteral("originTheta")).toDouble(); + 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; + 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.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); + } + + 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); + } +} + +void AgvMapViewWidget::changeZoom(double factor, const QPointF &anchor) +{ + if (m_image.isNull()) + return; + const double oldScale = viewScale(); + const QPointF imagePoint = (anchor - imageTopLeft()) / oldScale; + 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); + m_pan = anchor - imagePoint * newScale - centeredTopLeft; + update(); +} + +void AgvMapViewWidget::wheelEvent(QWheelEvent *event) +{ + changeZoom(event->angleDelta().y() > 0 ? 1.15 : 0.87, event->pos()); + event->accept(); +} + +void AgvMapViewWidget::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + m_dragging = true; + m_lastMousePosition = event->pos(); + setCursor(Qt::ClosedHandCursor); + event->accept(); + return; + } + QWidget::mousePressEvent(event); +} + +void AgvMapViewWidget::mouseMoveEvent(QMouseEvent *event) +{ + if (m_dragging) { + m_pan += event->pos() - m_lastMousePosition; + m_lastMousePosition = event->pos(); + update(); + event->accept(); + return; + } + QWidget::mouseMoveEvent(event); +} + +void AgvMapViewWidget::mouseReleaseEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton && m_dragging) { + m_dragging = false; + setCursor(Qt::OpenHandCursor); + event->accept(); + return; + } + QWidget::mouseReleaseEvent(event); +} diff --git a/src/agvmapviewwidget.h b/src/agvmapviewwidget.h new file mode 100644 index 0000000..5a1d5cf --- /dev/null +++ b/src/agvmapviewwidget.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +class QMouseEvent; +class QPaintEvent; +class QWheelEvent; + +class AgvMapViewWidget final : public QWidget +{ +public: + explicit AgvMapViewWidget(QWidget *parent = nullptr); + + void setMapFrame(const QImage &image, const QVariantMap &metadata); + void updateRobotPose(double x, double y, double theta, bool localized); + void setStreamMessage(const QString &message); + void zoomIn(); + void zoomOut(); + void resetView(); + void clearTrajectory(); + +protected: + 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; + +private: + bool canProjectPose() const; + QPointF worldToImage(double x, double y) const; + QPointF imageToWidget(const QPointF &point) const; + double viewScale() const; + QPointF imageTopLeft() const; + void changeZoom(double factor, const QPointF &anchor); + + QImage m_image; + QVariantMap m_metadata; + QVector m_trajectory; + QString m_streamMessage; + QString m_mapId; + QPointF m_pan; + QPoint m_lastMousePosition; + double m_zoom = 1.0; + double m_robotX = 0.0; + double m_robotY = 0.0; + double m_robotTheta = 0.0; + bool m_localized = false; + bool m_hasPose = false; + bool m_dragging = false; +}; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 18ccab8..afe4b03 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,6 +1,7 @@ #include "mainwindow.h" #include "videorenderwidget.h" +#include "agvmapviewwidget.h" #include "audiostreammanager.h" #include "configeditorwidget.h" #include "robotclient.h" @@ -11,6 +12,8 @@ #include "urdfviewerwidget.h" #include "ui_mainwindow.h" +#include +#include #include #include #include @@ -26,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -33,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -515,15 +520,22 @@ MainWindow::MainWindow(QWidget *parent) connect(m_client, &RobotClient::agvStateReceived, this, &MainWindow::updateAgvState); connect(m_client, &RobotClient::agvInventoryReceived, this, &MainWindow::updateAgvInventory); connect(m_client, &RobotClient::agvMapFrameReceived, this, - [this](const QImage &image, const QString &detail) { - m_agvMappingPreview->setText(QString()); - m_agvMappingPreview->setPixmap(QPixmap::fromImage(image).scaled( - m_agvMappingPreview->size(), Qt::KeepAspectRatio, - Qt::SmoothTransformation)); - m_agvMappingStateLabel->setText(detail); + [this](const QImage &image, const QVariantMap &metadata, + const QString &detail) { + if (m_agvMapView) { + m_agvMapView->setMapFrame(image, metadata); + m_agvMapView->setStreamMessage(detail); + } + if (m_agvMappingStateLabel) + m_agvMappingStateLabel->setText(detail); }); connect(m_client, &RobotClient::agvMapStreamStateChanged, this, [this](bool running, const QString &detail) { + m_agvMapStreamActive = running; + if (m_agvMapView) + m_agvMapView->setStreamMessage(detail); + if (!m_agvMappingStateLabel) + return; m_agvMappingStateLabel->setProperty("running", running); m_agvMappingStateLabel->setText(detail); m_agvMappingStateLabel->style()->unpolish(m_agvMappingStateLabel); @@ -581,6 +593,7 @@ MainWindow::MainWindow(QWidget *parent) } selectPage(initialPage); setControlsEnabled(false); + qApp->installEventFilter(this); appendLog(QStringLiteral("INFO"), QStringLiteral("CMVR 控制台已启动")); appendLog(QStringLiteral("INFO"), m_client->grpcAvailable() ? QStringLiteral("原生 gRPC 后端可用") @@ -595,6 +608,10 @@ MainWindow::MainWindow(QWidget *parent) MainWindow::~MainWindow() { + qApp->removeEventFilter(this); + stopAgvManualMotion(false); + if (m_client) + m_client->stopAgvMapStream(); m_audioManager->stopSource(); m_audioManager->stopPlayback(); m_client->stopSpeakerAudioStream(); @@ -672,6 +689,74 @@ bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *r return QMainWindow::nativeEvent(eventType, message, result); } +bool MainWindow::eventFilter(QObject *watched, QEvent *event) +{ + if (event && (event->type() == QEvent::WindowDeactivate + || event->type() == QEvent::ApplicationDeactivate)) { + stopAgvManualMotion(); + } + + const bool agvControlVisible = m_connected && m_pages + && m_pages->currentIndex() == 3 && m_agvControlWorkspace + && m_agvControlWorkspace->isVisible(); + if (!event || !agvControlVisible + || (event->type() != QEvent::KeyPress + && event->type() != QEvent::KeyRelease)) { + return QMainWindow::eventFilter(watched, event); + } + + QWidget *focus = QApplication::focusWidget(); + if (qobject_cast(focus) + || qobject_cast(focus) + || qobject_cast(focus) + || qobject_cast(focus)) { + return QMainWindow::eventFilter(watched, event); + } + + QKeyEvent *keyEvent = static_cast(event); + if (keyEvent->isAutoRepeat() + || (keyEvent->modifiers() & (Qt::ControlModifier | Qt::AltModifier + | Qt::MetaModifier))) { + return QMainWindow::eventFilter(watched, event); + } + + double vx = 0.0; + double vy = 0.0; + double wz = 0.0; + bool directionKey = true; + switch (keyEvent->key()) { + case Qt::Key_W: + vx = qAbs(m_agvVxSpin->value()); + break; + case Qt::Key_S: + vx = -qAbs(m_agvVxSpin->value()); + break; + case Qt::Key_A: + vy = qAbs(m_agvVySpin->value()); + break; + case Qt::Key_D: + vy = -qAbs(m_agvVySpin->value()); + break; + case Qt::Key_Q: + wz = qAbs(m_agvWzSpin->value()); + break; + case Qt::Key_E: + wz = -qAbs(m_agvWzSpin->value()); + break; + default: + directionKey = false; + break; + } + if (!directionKey) + return QMainWindow::eventFilter(watched, event); + + if (event->type() == QEvent::KeyPress) + startAgvManualMotion(vx, vy, wz); + else + stopAgvManualMotion(); + return true; +} + void MainWindow::changeEvent(QEvent *event) { QMainWindow::changeEvent(event); @@ -794,10 +879,38 @@ void MainWindow::appendQuicLog(const QString &level, const QString &message) .arg(timestamp, color, level, message.toHtmlEscaped())); } +void MainWindow::setArmTelemetryEnabled(bool enabled) +{ + if (!m_armTelemetryButton || !m_client || !m_armIdEdit) + return; + + const QString deviceId = m_armIdEdit->text().trimmed(); + const bool shouldEnable = enabled && m_connected && !deviceId.isEmpty(); + m_armTelemetryButton->setChecked(shouldEnable); + m_armTelemetryButton->setText( + shouldEnable ? QStringLiteral("遥测 10 Hz") + : QStringLiteral("遥测 未启动")); + m_armTelemetryButton->setProperty("active", shouldEnable); + m_armTelemetryButton->style()->unpolish(m_armTelemetryButton); + m_armTelemetryButton->style()->polish(m_armTelemetryButton); + if (m_armSideCombo) + m_armSideCombo->setEnabled(true); + + if (shouldEnable) { + m_client->requestArmInfo(deviceId); + m_client->requestArmFrames(deviceId); + } + m_client->setArmTelemetry(deviceId, shouldEnable); +} + + void MainWindow::selectPage(int index) { if (!m_pages || index < 0 || index >= kPageTitles.size()) return; + const int previousIndex = m_pages->currentIndex(); + if (previousIndex == 1 && index != 1) + setArmTelemetryEnabled(false); m_pages->setCurrentIndex(index); m_pageTitle->setText(kPageTitles.at(index)); m_pageSubtitle->setText(kPageSubtitles.at(index)); @@ -807,12 +920,67 @@ void MainWindow::selectPage(int index) m_armHeaderControls->setVisible(index == 1); if (index == 1) ensureArmModelLoaded(); - if (index != 3 && m_agvStatusSwitch && m_agvStatusSwitch->isChecked()) - m_agvStatusSwitch->setChecked(false); + if (index == 1 && previousIndex != 1 && m_connected) + setArmTelemetryEnabled(true); + if (index != 3) { + stopAgvManualMotion(); + if (m_agvStatusRefreshTimer) + m_agvStatusRefreshTimer->stop(); + if (m_agvMapStreamActive) { + m_client->stopAgvMapStream(); + m_agvMapStreamActive = false; + } + } else if (m_connected) { + m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); + m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); + m_agvStatusRefreshTimer->start(); + restartAgvMapStream(); + } if (index < m_navButtons.size()) m_navButtons.at(index)->setChecked(true); } +void MainWindow::startAgvManualMotion(double vx, double vy, double wz) +{ + if (!m_connected || !m_client || !m_agvIdEdit + || 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); + if (m_agvManualVelocityTimer && !m_agvManualVelocityTimer->isActive()) + m_agvManualVelocityTimer->start(); +} + +void MainWindow::stopAgvManualMotion(bool sendStop) +{ + const bool wasActive = m_agvManualMotionActive; + m_agvManualMotionActive = false; + 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")); + } +} + +void MainWindow::restartAgvMapStream(const QString &mapName) +{ + 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(); + m_client->stopAgvMapStream(); + m_client->startAgvMapStream(m_agvIdEdit->text().trimmed(), selectedMap, + 1, true, true); +} + void MainWindow::ensureArmModelLoaded() { if (!m_urdfViewer || m_pendingUrdfPath.isEmpty() @@ -878,16 +1046,24 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString & state->style()->polish(state); } setControlsEnabled(connected); - if (m_agvStatusRefreshTimer && m_agvStatusSwitch - && m_agvStatusSwitch->isChecked()) { - if (connected) { + if (connected && m_pages && m_pages->currentIndex() == 1) + setArmTelemetryEnabled(true); + if (m_agvStatusRefreshTimer) { + if (connected && m_pages && m_pages->currentIndex() == 3) { m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); + m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); m_agvStatusRefreshTimer->start(); + restartAgvMapStream(); } else { m_agvStatusRefreshTimer->stop(); } } if (!connected) { + stopAgvManualMotion(false); + m_client->stopAgvMapStream(); + m_agvMapStreamActive = false; + if (m_agvMapView) + m_agvMapView->setStreamMessage(QStringLiteral("连接已断开")); m_audioManager->stopSource(); m_audioManager->stopPlayback(); m_runningCameraIds.clear(); @@ -897,15 +1073,8 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString & } refreshCameraStreamControls(); } - if (!connected && m_armTelemetryButton) { - m_armTelemetryButton->setChecked(false); - m_armTelemetryButton->setText(QStringLiteral("遥测 未启动")); - m_armTelemetryButton->setProperty("active", false); - m_armTelemetryButton->style()->unpolish(m_armTelemetryButton); - m_armTelemetryButton->style()->polish(m_armTelemetryButton); - if (m_armSideCombo) - m_armSideCombo->setEnabled(true); - } + if (!connected && m_armTelemetryButton) + setArmTelemetryEnabled(false); if (!connected) { m_armAlertStates.clear(); const QList armStates = {m_servoStatusValue, m_faultStatusValue}; @@ -1396,6 +1565,13 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk, m_client->requestArmInfo(firstArmId); m_client->requestArmFrames(firstArmId); } + if (m_connected && m_pages && m_pages->currentIndex() == 1 + && !selectedId.isEmpty() && m_armTelemetryButton + && (selectedId != previousId + || !m_armTelemetryButton->isChecked())) { + setArmTelemetryEnabled(true); + } + } void MainWindow::updateSystemInfo(const QVariantMap &info) @@ -1410,6 +1586,7 @@ void MainWindow::updateSystemInfo(const QVariantMap &info) void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &navigation) { + m_latestAgvState = state; const bool controllerConnected = state.value(QStringLiteral("connected")).toBool(); const bool localized = state.value(QStringLiteral("localized")).toBool(); const bool fault = state.value(QStringLiteral("fault")).toBool(); @@ -1429,12 +1606,22 @@ void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &nav .arg(state.value(QStringLiteral("vx")).toDouble(), 0, 'f', 2) .arg(state.value(QStringLiteral("vy")).toDouble(), 0, 'f', 2) .arg(state.value(QStringLiteral("wz")).toDouble(), 0, 'f', 2)); - m_agvBatteryValue->setText(QStringLiteral("%1%").arg( - state.value(QStringLiteral("battery")).toDouble() * 100.0, 0, 'f', 0)); + const bool charging = state.value(QStringLiteral("charging")).toBool(); + m_agvBatteryValue->setText( + QStringLiteral("%1%").arg( + state.value(QStringLiteral("battery")).toDouble() * 100.0, 0, 'f', 0) + + (charging ? QStringLiteral(" · 充电中") : QString())); m_agvNavigationValue->setText(navigation.value(QStringLiteral("message"), QStringLiteral("--")).toString()); m_agvErrorValue->setText(state.value(QStringLiteral("error"), QStringLiteral("无")).toString()); - m_agvModeValue->setText(QStringLiteral("模式 %1").arg( - state.value(QStringLiteral("mode")).toInt())); + static const QStringList modeNames = { + QStringLiteral("未知"), QStringLiteral("离线"), QStringLiteral("空闲"), + QStringLiteral("手动"), QStringLiteral("自动"), QStringLiteral("充电"), + QStringLiteral("暂停"), QStringLiteral("已停止"), QStringLiteral("故障"), + QStringLiteral("急停") + }; + const int mode = state.value(QStringLiteral("mode")).toInt(); + m_agvModeValue->setText(modeNames.value( + mode, QStringLiteral("模式 %1").arg(mode))); m_agvMotionStateValue->setText(QStringLiteral("%1 / %2") .arg(localized ? QStringLiteral("已定位") : QStringLiteral("未定位"), state.value(QStringLiteral("moving")).toBool() @@ -1442,9 +1629,12 @@ void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &nav m_agvSafetyValue->setText(QStringLiteral("%1 / %2") .arg(fault ? QStringLiteral("有故障") : QStringLiteral("正常"), emergency ? QStringLiteral("已急停") : QStringLiteral("未急停"))); - m_agvPowerValue->setText(QStringLiteral("%1 V / %2 A / %3 °C") - .arg(state.value(QStringLiteral("voltage")).toDouble(), 0, 'f', 2) - .arg(state.value(QStringLiteral("current")).toDouble(), 0, 'f', 2) + const double voltage = state.value(QStringLiteral("voltage")).toDouble(); + const double current = state.value(QStringLiteral("current")).toDouble(); + m_agvPowerValue->setText(QStringLiteral("%1 V / %2 A / %3 W / %4 °C") + .arg(voltage, 0, 'f', 2) + .arg(current, 0, 'f', 2) + .arg(qAbs(voltage * current), 0, 'f', 1) .arg(state.value(QStringLiteral("temperature")).toDouble(), 0, 'f', 1)); const double timestamp = state.value(QStringLiteral("timestamp")).toDouble(); m_agvTimestampValue->setText(timestamp > 0.0 @@ -1452,11 +1642,19 @@ 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); + } } void MainWindow::updateAgvInventory(const QStringList &maps, const QVariantList &stations) { - const QString selectedMap = m_agvMapCombo->currentText(); + QString selectedMap = m_agvMapCombo->currentText(); + if (selectedMap.trimmed().isEmpty()) + selectedMap = m_latestAgvState.value(QStringLiteral("map")).toString(); m_agvMapCombo->clear(); m_agvMapCombo->addItems(maps); const int mapIndex = m_agvMapCombo->findText(selectedMap); @@ -1632,12 +1830,15 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri || command == QStringLiteral("Camera Stop Recording"))) { updateCameraRecordingState(m_cameraRecording, detail); } - if (success && m_agvStatusSwitch - && (command == QStringLiteral("AGV NavigateToPose") - || command == QStringLiteral("AGV NavigateToStation") - || command == QStringLiteral("AGV FollowPath"))) { - m_agvStatusSwitch->setChecked(true); + if (success && command == QStringLiteral("AGV SwitchMap")) { + m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); + restartAgvMapStream(m_agvMapCombo->currentText()); } + if (success && command == QStringLiteral("AGV StopMapping")) { + m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); + restartAgvMapStream(); + } + appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"), QStringLiteral("%1 · %2").arg(command, detail)); if (!success) @@ -1872,6 +2073,8 @@ void MainWindow::setControlsEnabled(bool enabled) m_microphoneStreamStartButton->setEnabled(enabled); if (m_microphoneStreamStopButton) m_microphoneStreamStopButton->setEnabled(false); + if (m_agvDeleteMapButton) + m_agvDeleteMapButton->setEnabled(false); } QString MainWindow::endpoint() const diff --git a/src/mainwindow.h b/src/mainwindow.h index cb9d409..5a9b7c1 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -39,6 +39,7 @@ class QuicTestServer; class UrdfViewerWidget; class AudioStreamManager; class VideoRenderWidget; +class AgvMapViewWidget; class MainWindow : public QMainWindow { @@ -50,6 +51,7 @@ public: protected: bool nativeEvent(const QByteArray &eventType, void *message, long *result) override; + bool eventFilter(QObject *watched, QEvent *event) override; void changeEvent(QEvent *event) override; void resizeEvent(QResizeEvent *event) override; @@ -101,9 +103,13 @@ private: void ensureArmModelLoaded(); void rebuildArmJointTables(const QStringList &jointNames); void rebuildArmJogControls(); + void setArmTelemetryEnabled(bool enabled); void startJointJog(int jointIndex, int direction); void startCartesianJog(int axisIndex, int direction); void stopArmJog(); + void startAgvManualMotion(double vx, double vy, double wz); + void stopAgvManualMotion(bool sendStop = true); + void restartAgvMapStream(const QString &mapName = QString()); void updateArmAlert(const QString &deviceId, const QString &alertKey, const QString &level, const QString &summary, const QString &detail = QString()); @@ -244,8 +250,8 @@ private: QLineEdit *m_agvIdEdit = nullptr; QDialog *m_agvStatusDialog = nullptr; - QCheckBox *m_agvStatusSwitch = nullptr; QTimer *m_agvStatusRefreshTimer = nullptr; + QTimer *m_agvManualVelocityTimer = nullptr; QLabel *m_agvConnectionValue = nullptr; QLabel *m_agvPoseValue = nullptr; QLabel *m_agvMotionValue = nullptr; @@ -261,6 +267,9 @@ private: QLabel *m_agvMapOverview = nullptr; QLabel *m_agvMappingPreview = nullptr; QLabel *m_agvMappingStateLabel = nullptr; + AgvMapViewWidget *m_agvMapView = nullptr; + QWidget *m_agvControlWorkspace = nullptr; + QPushButton *m_agvDeleteMapButton = nullptr; QProgressBar *m_agvProgress = nullptr; QDoubleSpinBox *m_agvXSpin = nullptr; QDoubleSpinBox *m_agvYSpin = nullptr; @@ -273,6 +282,12 @@ private: QComboBox *m_agvStationCombo = nullptr; QTableWidget *m_agvStationTable = nullptr; QString m_agvDownloadPath; + QVariantMap m_latestAgvState; + double m_agvManualVx = 0.0; + double m_agvManualVy = 0.0; + double m_agvManualWz = 0.0; + bool m_agvManualMotionActive = false; + bool m_agvMapStreamActive = false; QList m_serviceButtons; QPushButton *m_speakerStreamStartButton = nullptr; QPushButton *m_speakerStreamStopButton = nullptr; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 3222c2a..4dc4cae 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -1,5 +1,6 @@ #include "mainwindow.h" +#include "agvmapviewwidget.h" #include "audiostreammanager.h" #include "robotclient.h" #include "rpcservicewidget.h" @@ -14,6 +15,7 @@ #include "ui_quicserverpage.h" #include "ui_systemservicepage.h" +#include #include #include #include @@ -31,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -44,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -692,26 +696,13 @@ QWidget *MainWindow::createArmPage() m_client->requestSystemStopAll(target.isEmpty() ? QStringLiteral("*") : target); }); connect(m_armTelemetryButton, &QPushButton::clicked, this, [this](bool enabled) { - const QString deviceId = m_armIdEdit->text().trimmed(); - if (enabled && deviceId.isEmpty()) { + if (enabled && m_armIdEdit->text().trimmed().isEmpty()) { QMessageBox::warning(this, QStringLiteral("ArmService"), - QStringLiteral("请先填写机械臂设备 ID。")); - m_armTelemetryButton->setChecked(false); + QStringLiteral("请先选择机械臂设备。")); + setArmTelemetryEnabled(false); return; } - m_armTelemetryButton->setText(enabled ? QStringLiteral("遥测 10 Hz") - : QStringLiteral("遥测 未启动")); - m_armTelemetryButton->setProperty("active", enabled); - m_armTelemetryButton->style()->unpolish(m_armTelemetryButton); - m_armTelemetryButton->style()->polish(m_armTelemetryButton); - // Keep device selection available while telemetry is running. The - // selection handler transfers polling to the newly selected arm. - m_armSideCombo->setEnabled(true); - if (enabled) { - m_client->requestArmInfo(deviceId); - m_client->requestArmFrames(deviceId); - } - m_client->setArmTelemetry(deviceId, enabled); + setArmTelemetryEnabled(enabled); }); connect(m_torqueOnButton, &QPushButton::clicked, this, [this]() { m_client->requestTorque(m_armIdEdit->text().trimmed(), true); @@ -1094,7 +1085,6 @@ QWidget *MainWindow::createAgvPage() statusUi.statusLayout->setColumnStretch(3, 1); m_agvIdEdit = ui.agvIdEdit; - m_agvStatusSwitch = ui.agvStatusSwitch; m_agvStatusRefreshTimer = new QTimer(page); m_agvStatusRefreshTimer->setInterval(1000); m_agvConnectionValue = statusUi.agvConnectionValue; @@ -1136,41 +1126,251 @@ QWidget *MainWindow::createAgvPage() m_agvStationTable->setSelectionBehavior(QAbstractItemView::SelectRows); m_agvStationTable->verticalHeader()->setVisible(false); 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) + return; + m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), + m_agvManualVx, m_agvManualVy, + m_agvManualWz); + }); + + m_agvControlWorkspace = new QWidget(ui.agvTabs); + m_agvControlWorkspace->setObjectName(QStringLiteral("agvControlWorkspace")); + QHBoxLayout *workspaceLayout = new QHBoxLayout(m_agvControlWorkspace); + workspaceLayout->setContentsMargins(0, 0, 0, 0); + workspaceLayout->setSpacing(12); + + QWidget *leftColumn = new QWidget(m_agvControlWorkspace); + QVBoxLayout *leftLayout = new QVBoxLayout(leftColumn); + leftLayout->setContentsMargins(0, 0, 0, 0); + leftLayout->setSpacing(12); + QWidget *rightColumn = new QWidget(m_agvControlWorkspace); + QVBoxLayout *rightLayout = new QVBoxLayout(rightColumn); + rightLayout->setContentsMargins(0, 0, 0, 0); + rightLayout->setSpacing(12); + workspaceLayout->addWidget(leftColumn, 7); + workspaceLayout->addWidget(rightColumn, 4); + + ui.mappingPreviewPanel->setParent(leftColumn); + ui.mappingPreviewPanel->setMinimumSize(0, 0); + ui.mappingPreviewTitle->setText(QStringLiteral("实时地图")); + ui.mappingPreviewLayout->removeWidget(ui.mappingPreview); + ui.mappingPreview->hide(); + m_agvMappingPreview = nullptr; + + QHBoxLayout *mapToolbar = new QHBoxLayout; + QLabel *mapLegend = new QLabel( + QStringLiteral("蓝色箭头:AGV 当前位姿 · 虚线:运动轨迹"), + ui.mappingPreviewPanel); + mapLegend->setObjectName(QStringLiteral("panelSubtitle")); + QPushButton *zoomOutButton = new QPushButton(QStringLiteral("−"), + ui.mappingPreviewPanel); + QPushButton *zoomInButton = new QPushButton(QStringLiteral("+"), + ui.mappingPreviewPanel); + QPushButton *resetViewButton = new QPushButton(QStringLiteral("适应窗口"), + ui.mappingPreviewPanel); + QPushButton *clearTrackButton = new QPushButton(QStringLiteral("清除轨迹"), + ui.mappingPreviewPanel); + for (QPushButton *button : {zoomOutButton, zoomInButton, + resetViewButton, clearTrackButton}) { + button->setObjectName(QStringLiteral("agvMapToolButton")); + button->setMinimumHeight(30); + } + zoomOutButton->setMaximumWidth(42); + zoomInButton->setMaximumWidth(42); + mapToolbar->addWidget(mapLegend); + mapToolbar->addStretch(); + mapToolbar->addWidget(zoomOutButton); + mapToolbar->addWidget(zoomInButton); + mapToolbar->addWidget(resetViewButton); + mapToolbar->addWidget(clearTrackButton); + ui.mappingPreviewLayout->insertLayout(1, mapToolbar); + + m_agvMapView = new AgvMapViewWidget(ui.mappingPreviewPanel); + m_agvMapView->setObjectName(QStringLiteral("agvLiveMap")); + m_agvMapView->setStreamMessage(QStringLiteral("连接设备后自动加载实时地图")); + ui.mappingPreviewLayout->insertWidget(2, m_agvMapView, 1); + leftLayout->addWidget(ui.mappingPreviewPanel, 1); + + QFrame *mapActionsPanel = new QFrame(leftColumn); + mapActionsPanel->setObjectName(QStringLiteral("panel")); + QVBoxLayout *mapActionsLayout = new QVBoxLayout(mapActionsPanel); + mapActionsLayout->setContentsMargins(18, 14, 18, 14); + mapActionsLayout->setSpacing(9); + QLabel *mapActionsTitle = new QLabel(QStringLiteral("地图与建图"), + mapActionsPanel); + mapActionsTitle->setObjectName(QStringLiteral("sectionTitle")); + QLabel *mapActionsSubtitle = new QLabel( + 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("重新定位"), + mapActionsPanel); + m_agvDeleteMapButton = new QPushButton(QStringLiteral("删除地图"), + mapActionsPanel); + m_agvDeleteMapButton->setObjectName(QStringLiteral("dangerOutlineButton")); + m_agvDeleteMapButton->setEnabled(false); + m_agvDeleteMapButton->setToolTip( + QStringLiteral("当前边缘系统未提供删除地图接口")); + QHBoxLayout *mapOperationRow = new QHBoxLayout; + mapOperationRow->addWidget(addMapButton); + mapOperationRow->addWidget(relocalizeButton); + mapOperationRow->addWidget(m_agvDeleteMapButton); + mapActionsLayout->addLayout(mapOperationRow); + + QGridLayout *mappingForm = new QGridLayout; + QLabel *mappingNameLabel = new QLabel(QStringLiteral("新地图"), + mapActionsPanel); + QLabel *mappingDimensionLabel = new QLabel(QStringLiteral("类型"), + mapActionsPanel); + ui.mappingNameEdit->setParent(mapActionsPanel); + ui.mappingDimensionCombo->setParent(mapActionsPanel); + ui.mappingRealtimeCheck->setParent(mapActionsPanel); + mappingForm->addWidget(mappingNameLabel, 0, 0); + mappingForm->addWidget(ui.mappingNameEdit, 0, 1); + mappingForm->addWidget(mappingDimensionLabel, 0, 2); + mappingForm->addWidget(ui.mappingDimensionCombo, 0, 3); + mappingForm->addWidget(ui.mappingRealtimeCheck, 1, 1, 1, 3); + mappingForm->setColumnStretch(1, 1); + mappingForm->setColumnStretch(3, 1); + mapActionsLayout->addLayout(mappingForm); + + ui.startMappingButton->setParent(mapActionsPanel); + ui.stopMappingButton->setParent(mapActionsPanel); + QHBoxLayout *mappingButtonRow = new QHBoxLayout; + mappingButtonRow->addWidget(ui.startMappingButton); + mappingButtonRow->addWidget(ui.stopMappingButton); + mapActionsLayout->addLayout(mappingButtonRow); + + ui.uploadMapButton->setParent(mapActionsPanel); + ui.downloadMapButton->setParent(mapActionsPanel); + QHBoxLayout *transferRow = new QHBoxLayout; + transferRow->addWidget(ui.uploadMapButton); + transferRow->addWidget(ui.downloadMapButton); + mapActionsLayout->addLayout(transferRow); + leftLayout->addWidget(mapActionsPanel); + + 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); + + ui.velocityPanel->setParent(rightColumn); + ui.velocityPanel->setMinimumSize(0, 0); + ui.velocityTitle->setText(QStringLiteral("手动速度控制")); + ui.velocitySubtitle->setText( + QStringLiteral("按住方向按钮或 Q/W/E/A/S/D 键运动,松开即停止")); + 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); + ui.rotateLeftButton->setText(QStringLiteral("左旋 (Q)")); + ui.forwardButton->setText(QStringLiteral("前进 (W)")); + ui.rotateRightButton->setText(QStringLiteral("右旋 (E)")); + ui.leftButton->setText(QStringLiteral("左移 (A)")); + ui.rightButton->setText(QStringLiteral("右移 (D)")); + ui.backwardButton->setText(QStringLiteral("后退 (S)")); + ui.velocityButton->hide(); + rightLayout->addWidget(ui.velocityPanel, 4); + + const auto removeOriginalTab = [tabs = ui.agvTabs](QWidget *tab) { + const int index = tabs->indexOf(tab); + if (index >= 0) + tabs->removeTab(index); + }; + removeOriginalTab(ui.manualTab); + removeOriginalTab(ui.mapTab); + removeOriginalTab(ui.mappingTab); + ui.agvTabs->insertTab(0, m_agvControlWorkspace, + QStringLiteral("控制与建图")); + ui.agvTabs->setCurrentWidget(m_agvControlWorkspace); + + connect(zoomOutButton, &QPushButton::clicked, + m_agvMapView, &AgvMapViewWidget::zoomOut); + connect(zoomInButton, &QPushButton::clicked, + m_agvMapView, &AgvMapViewWidget::zoomIn); + connect(resetViewButton, &QPushButton::clicked, + m_agvMapView, &AgvMapViewWidget::resetView); + connect(clearTrackButton, &QPushButton::clicked, + m_agvMapView, &AgvMapViewWidget::clearTrajectory); + connect(addMapButton, &QPushButton::clicked, this, + [this, nameEdit = ui.mappingNameEdit]() { + bool accepted = false; + const QString name = QInputDialog::getText( + this, QStringLiteral("新增地图"), QStringLiteral("地图名称"), + QLineEdit::Normal, nameEdit->text(), &accepted).trimmed(); + if (!accepted || name.isEmpty()) + return; + nameEdit->setText(name); + nameEdit->setFocus(); + }); + connect(relocalizeButton, &QPushButton::clicked, this, [this]() { + QDialog dialog(this); + dialog.setWindowTitle(QStringLiteral("AGV 重新定位")); + QFormLayout *form = new QFormLayout(&dialog); + QDoubleSpinBox *xSpin = new QDoubleSpinBox(&dialog); + QDoubleSpinBox *ySpin = new QDoubleSpinBox(&dialog); + QDoubleSpinBox *thetaSpin = new QDoubleSpinBox(&dialog); + for (QDoubleSpinBox *spin : {xSpin, ySpin}) { + spin->setRange(-10000.0, 10000.0); + spin->setDecimals(3); + spin->setSuffix(QStringLiteral(" m")); + } + thetaSpin->setRange(-6.283, 6.283); + thetaSpin->setDecimals(3); + thetaSpin->setSuffix(QStringLiteral(" rad")); + xSpin->setValue(m_latestAgvState.value(QStringLiteral("x")).toDouble()); + ySpin->setValue(m_latestAgvState.value(QStringLiteral("y")).toDouble()); + thetaSpin->setValue( + m_latestAgvState.value(QStringLiteral("theta")).toDouble()); + form->addRow(QStringLiteral("X"), xSpin); + form->addRow(QStringLiteral("Y"), ySpin); + form->addRow(QStringLiteral("航向"), thetaSpin); + QDialogButtonBox *buttons = new QDialogButtonBox( + QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); + connect(buttons, &QDialogButtonBox::accepted, + &dialog, &QDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, + &dialog, &QDialog::reject); + form->addRow(buttons); + if (dialog.exec() == QDialog::Accepted) { + m_client->requestAgvRelocalize( + m_agvIdEdit->text().trimmed(), xSpin->value(), + ySpin->value(), thetaSpin->value()); + } + }); + connect(ui.refreshButton, &QPushButton::clicked, this, [this]() { m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); }); - connect(statusUi.refreshDialogButton, &QPushButton::clicked, this, [this]() { - m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); - }); connect(m_agvStatusRefreshTimer, &QTimer::timeout, this, [this]() { - if (m_connected && m_agvStatusSwitch && m_agvStatusSwitch->isChecked()) + if (m_connected && m_pages && m_pages->currentIndex() == 3) m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); }); - connect(m_agvStatusSwitch, &QCheckBox::toggled, this, [this](bool checked) { - if (!m_agvStatusDialog) - return; - if (!checked) { - m_agvStatusRefreshTimer->stop(); - m_agvStatusDialog->hide(); - return; - } - const QRect owner = frameGeometry(); - const int x = qMax(owner.left() + 24, - owner.right() - m_agvStatusDialog->width() - 24); - m_agvStatusDialog->move(x, owner.top() + 88); - m_agvStatusDialog->show(); - m_agvStatusDialog->raise(); - m_agvStatusDialog->activateWindow(); - if (m_connected) { - m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); - m_agvStatusRefreshTimer->start(); - } - }); - connect(m_agvStatusDialog, &QDialog::finished, this, [this](int) { - if (m_agvStatusSwitch) - m_agvStatusSwitch->setChecked(false); - }); connect(ui.navigatePoseButton, &QPushButton::clicked, this, [this]() { m_client->requestAgvNavigatePose(m_agvIdEdit->text().trimmed(), m_agvXSpin->value(), m_agvYSpin->value(), m_agvThetaSpin->value(), @@ -1190,36 +1390,34 @@ QWidget *MainWindow::createAgvPage() connect(ui.cancelButton, &QPushButton::clicked, this, [this]() { m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("Cancel")); }); - connect(ui.velocityButton, &QPushButton::clicked, this, [this]() { - m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), m_agvVxSpin->value(), - m_agvVySpin->value(), m_agvWzSpin->value()); + connect(ui.forwardButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(qAbs(m_agvVxSpin->value()), 0.0, 0.0); }); - const auto sendManualVelocity = [this](double vx, double vy, double wz) { - m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), vx, vy, wz); - }; - connect(ui.forwardButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(qAbs(m_agvVxSpin->value()), 0.0, 0.0); + connect(ui.backwardButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(-qAbs(m_agvVxSpin->value()), 0.0, 0.0); }); - connect(ui.backwardButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(-qAbs(m_agvVxSpin->value()), 0.0, 0.0); + connect(ui.leftButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(0.0, qAbs(m_agvVySpin->value()), 0.0); }); - connect(ui.leftButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(0.0, qAbs(m_agvVySpin->value()), 0.0); + connect(ui.rightButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(0.0, -qAbs(m_agvVySpin->value()), 0.0); }); - connect(ui.rightButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(0.0, -qAbs(m_agvVySpin->value()), 0.0); + connect(ui.rotateLeftButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(0.0, 0.0, qAbs(m_agvWzSpin->value())); }); - connect(ui.rotateLeftButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(0.0, 0.0, qAbs(m_agvWzSpin->value())); - }); - connect(ui.rotateRightButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(0.0, 0.0, -qAbs(m_agvWzSpin->value())); - }); - connect(ui.manualStopButton, &QPushButton::clicked, this, [this]() { - m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), - QStringLiteral("StopVelocity")); + connect(ui.rotateRightButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(0.0, 0.0, -qAbs(m_agvWzSpin->value())); }); + for (QPushButton *button : { + ui.forwardButton, ui.backwardButton, ui.leftButton, + ui.rightButton, ui.rotateLeftButton, ui.rotateRightButton}) { + connect(button, &QPushButton::released, this, + [this]() { stopAgvManualMotion(); }); + } + connect(ui.manualStopButton, &QPushButton::clicked, this, + [this]() { stopAgvManualMotion(); }); connect(ui.zeroVelocityButton, &QPushButton::clicked, this, [this]() { + stopAgvManualMotion(); m_agvVxSpin->setValue(0.0); m_agvVySpin->setValue(0.0); m_agvWzSpin->setValue(0.0); @@ -1376,7 +1574,7 @@ QWidget *MainWindow::createAgvPage() << ui.pauseButton << ui.resumeButton << ui.cancelButton << ui.velocityButton << statusUi.stopVelocityButton << statusUi.clearFaultButton - << ui.emergencyButton << ui.inventoryButton << ui.switchMapButton + << ui.emergencyButton << ui.inventoryButton << ui.switchMapButton << relocalizeButton << ui.forwardButton << ui.backwardButton << ui.leftButton << ui.rightButton << ui.rotateLeftButton << ui.rotateRightButton << ui.manualStopButton << ui.followPathButton << ui.startMappingButton << ui.stopMappingButton diff --git a/src/robotclient.cpp b/src/robotclient.cpp index fa9e78c..e31b306 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -1337,6 +1337,7 @@ public: state.insert(QStringLiteral("voltage"), 49.2); state.insert(QStringLiteral("current"), -2.9); state.insert(QStringLiteral("temperature"), 28.0); + state.insert(QStringLiteral("charging"), false); state.insert(QStringLiteral("x"), 1.24); state.insert(QStringLiteral("y"), -0.36); state.insert(QStringLiteral("theta"), 0.12); @@ -1380,6 +1381,7 @@ public: state.insert(QStringLiteral("voltage"), source.battery().voltage()); state.insert(QStringLiteral("current"), source.battery().current()); state.insert(QStringLiteral("temperature"), source.battery().temperature()); + state.insert(QStringLiteral("charging"), source.battery().charging()); state.insert(QStringLiteral("x"), source.pose().x()); state.insert(QStringLiteral("y"), source.pose().y()); state.insert(QStringLiteral("theta"), source.pose().theta()); @@ -1401,6 +1403,36 @@ public: #endif } + void agvRelocalize(const QString &deviceId, double x, double y, double theta) + { + const QString command = QStringLiteral("AGV Relocalize"); + if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) + return; + if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(theta)) { + emit commandFinished(command, false, + QStringLiteral("重新定位位姿必须是有效数值")); + return; + } + if (m_demoMode) { + emit commandFinished(command, true, + QStringLiteral("重新定位位姿已下发")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::AgvRelocalizeCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + request.mutable_pose()->set_x(x); + request.mutable_pose()->set_y(y); + request.mutable_pose()->set_theta(theta); + cmvr::api::AgvRelocalizeCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 2500); + const grpc::Status status = m_agv->relocalize(&context, request, &response); + finish(command, status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + void agvNavigatePose(const QString &deviceId, double x, double y, double theta, double maxSpeed) { if (!ensureConnected(QStringLiteral("AGV NavigateToPose")) || @@ -1687,7 +1719,20 @@ public: << QPointF(260, 302); painter.drawPolygon(robot); painter.end(); - emit agvMapFrameReceived(image, QStringLiteral("演示 2D 地图 · 6 个站点")); + QVariantMap metadata; + metadata.insert(QStringLiteral("mapId"), QStringLiteral("demo_map")); + metadata.insert(QStringLiteral("dimension"), 2); + metadata.insert(QStringLiteral("originX"), 0.0); + metadata.insert(QStringLiteral("originY"), 0.0); + metadata.insert(QStringLiteral("originTheta"), 0.0); + metadata.insert(QStringLiteral("resolution"), 0.01); + metadata.insert(QStringLiteral("sourceWidth"), image.width()); + metadata.insert(QStringLiteral("sourceHeight"), image.height()); + metadata.insert(QStringLiteral("renderScale"), 1.0); + metadata.insert(QStringLiteral("timestamp"), + QDateTime::currentMSecsSinceEpoch() / 1000.0); + emit agvMapFrameReceived(image, metadata, + QStringLiteral("演示 2D 地图 · 6 个站点")); return; } @@ -1715,6 +1760,7 @@ public: continue; const auto &update = response.update(); QImage image; + QVariantMap metadata; QString detail; if (update.has_map_2d()) { const auto &map = update.map_2d(); @@ -1773,6 +1819,21 @@ public: } } painter.end(); + metadata.insert(QStringLiteral("mapId"), + QString::fromStdString(update.map_id())); + metadata.insert(QStringLiteral("dimension"), 2); + metadata.insert(QStringLiteral("originX"), map.origin().x()); + metadata.insert(QStringLiteral("originY"), map.origin().y()); + metadata.insert(QStringLiteral("originTheta"), map.origin().theta()); + metadata.insert(QStringLiteral("resolution"), resolution); + metadata.insert(QStringLiteral("sourceWidth"), sourceWidth); + metadata.insert(QStringLiteral("sourceHeight"), sourceHeight); + metadata.insert(QStringLiteral("renderScale"), scale); + metadata.insert(QStringLiteral("timestamp"), map.timestamp()); + metadata.insert(QStringLiteral("sequence"), + static_cast(update.sequence())); + metadata.insert(QStringLiteral("updateType"), + static_cast(update.update_type())); detail = QStringLiteral("%1 · 2D · %2×%3 · seq %4") .arg(QString::fromStdString(update.map_id())) .arg(sourceWidth).arg(sourceHeight) @@ -1803,13 +1864,19 @@ public: } painter.end(); } + metadata.insert(QStringLiteral("mapId"), + QString::fromStdString(update.map_id())); + metadata.insert(QStringLiteral("dimension"), 3); + metadata.insert(QStringLiteral("timestamp"), map.timestamp()); + metadata.insert(QStringLiteral("sequence"), + static_cast(update.sequence())); detail = QStringLiteral("%1 · 3D · %2 points · seq %3") .arg(QString::fromStdString(update.map_id())) .arg(map.points_size()) .arg(static_cast(update.sequence())); } if (!image.isNull()) - emit agvMapFrameReceived(image, detail); + emit agvMapFrameReceived(image, metadata, detail); } const grpc::Status status = reader->Finish(); { @@ -2021,7 +2088,8 @@ public: std::function cameraRecordingStateChanged; std::function agvStateReceived; std::function agvInventoryReceived; - std::function agvMapFrameReceived; + std::function + agvMapFrameReceived; std::function agvMapStreamStateChanged; std::function rpcFinished; std::function audioStreamStateChanged; @@ -3223,9 +3291,11 @@ RobotClient::RobotClient(QObject *parent) emit agvInventoryReceived(maps, stations); }, Qt::QueuedConnection); }; - m_worker->agvMapFrameReceived = [this](const QImage &image, const QString &detail) { - QMetaObject::invokeMethod(this, [this, image, detail]() { - emit agvMapFrameReceived(image, detail); + m_worker->agvMapFrameReceived = [this](const QImage &image, + const QVariantMap &metadata, + const QString &detail) { + QMetaObject::invokeMethod(this, [this, image, metadata, detail]() { + emit agvMapFrameReceived(image, metadata, detail); }, Qt::QueuedConnection); }; m_worker->agvMapStreamStateChanged = [this](bool running, const QString &detail) { @@ -3334,6 +3404,8 @@ RobotClient::RobotClient(QObject *parent) connect(this, &RobotClient::systemRefreshRequested, m_worker, &BackendWorker::systemRefresh); connect(this, &RobotClient::systemStopAllRequested, m_worker, &BackendWorker::systemStopAll); connect(this, &RobotClient::agvRefreshRequested, m_worker, &BackendWorker::agvRefresh); + connect(this, &RobotClient::agvRelocalizeRequested, + m_worker, &BackendWorker::agvRelocalize); connect(this, &RobotClient::agvNavigatePoseRequested, m_worker, &BackendWorker::agvNavigatePose); connect(this, &RobotClient::agvNavigateStationRequested, m_worker, &BackendWorker::agvNavigateStation); connect(this, &RobotClient::agvFollowPathRequested, m_worker, &BackendWorker::agvFollowPath); @@ -3470,6 +3542,11 @@ void RobotClient::stopCameraRecording(const QString &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::requestAgvRelocalize(const QString &deviceId, double x, double y, + double theta) +{ + emit agvRelocalizeRequested(deviceId, x, y, theta); +} void RobotClient::requestAgvNavigatePose(const QString &deviceId, double x, double y, double theta, double maxSpeed) { diff --git a/src/robotclient.h b/src/robotclient.h index 90a7c77..f640b65 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -56,6 +56,8 @@ public slots: void requestSystemRefresh(); void requestSystemStopAll(const QString &deviceId); void requestAgvRefresh(const QString &deviceId); + void requestAgvRelocalize(const QString &deviceId, double x, double y, + double theta); void requestAgvNavigatePose(const QString &deviceId, double x, double y, double theta, double maxSpeed); void requestAgvNavigateStation(const QString &deviceId, const QString &stationId, @@ -116,6 +118,8 @@ signals: void systemRefreshRequested(); void systemStopAllRequested(const QString &deviceId); void agvRefreshRequested(const QString &deviceId); + void agvRelocalizeRequested(const QString &deviceId, double x, double y, + double theta); void agvNavigatePoseRequested(const QString &deviceId, double x, double y, double theta, double maxSpeed); void agvNavigateStationRequested(const QString &deviceId, const QString &stationId, @@ -165,7 +169,8 @@ 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 agvMapFrameReceived(const QImage &image, const QString &detail); + void agvMapFrameReceived(const QImage &image, const QVariantMap &metadata, + const QString &detail); void agvMapStreamStateChanged(bool running, const QString &detail); void rpcFinished(const QString &serviceName, const QString &methodName, bool success, const QString &responseJson); diff --git a/ui/agvservicepage.ui b/ui/agvservicepage.ui index 2e655a2..31cb25f 100644 --- a/ui/agvservicepage.ui +++ b/ui/agvservicepage.ui @@ -23,8 +23,6 @@ 设备 IDeyebrow 220028016777215AGV 设备 ID 1080刷新状态primaryButton - 状态监测eyebrow - 44244424开启或关闭 AGV 实时状态监测agvStatusSwitch 1080AGV 急停dangerButton diff --git a/ui/agvstatusdialog.ui b/ui/agvstatusdialog.ui index f54c54b..2d4979e 100644 --- a/ui/agvstatusdialog.ui +++ b/ui/agvstatusdialog.ui @@ -47,16 +47,6 @@ 14 16 16 - - - 10 - AGV 实时状态pageTitle - 控制器、定位、运动、安全与能源状态panelSubtitle - Qt::Horizontal4020 - ● 实时监测agvLiveIndicator - 刷新880 - - panel