CmvrControlStation/src/mainwindow.cpp

2749 lines
123 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "mainwindow.h"
#include "tactileheatmapwidget.h"
#include "jointfloweditor.h"
#include "videorenderwidget.h"
#include "agvmapviewwidget.h"
#include "audiostreammanager.h"
#include "configeditorwidget.h"
#include "robotclient.h"
#include "quictestserver.h"
#include "rpcservicewidget.h"
#include "trendwidget.h"
#include "uiicons.h"
#include "urdfviewerwidget.h"
#include "ui_mainwindow.h"
#include <QAbstractSpinBox>
#include <QApplication>
#include <QButtonGroup>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QCursor>
#include <QDateTime>
#include <QDoubleSpinBox>
#include <QDir>
#include <QEvent>
#include <QFileDialog>
#include <QFileInfo>
#include <QFrame>
#include <QHeaderView>
#include <QHBoxLayout>
#include <QImage>
#include <QKeyEvent>
#include <QJsonDocument>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include <QMessageBox>
#include <QPainter>
#include <QPixmap>
#include <QProgressBar>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QResizeEvent>
#include <QScrollArea>
#include <QSettings>
#include <QSpinBox>
#include <QStackedWidget>
#include <QStyle>
#include <QTableWidget>
#include <QTextEdit>
#include <QTimer>
#include <QVBoxLayout>
#include <QtMath>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
namespace {
const QStringList kPageTitles = {
QStringLiteral("系统概览"), QStringLiteral("机械臂"),
QStringLiteral("相机"), QStringLiteral("AGV"),
QStringLiteral("扬声器"), QStringLiteral("麦克风"),
QStringLiteral("灵巧手"), QStringLiteral("仿生头"),
QStringLiteral("HLC 控制"), QStringLiteral("接口调试"),
QStringLiteral("QUIC Server"), QStringLiteral("设备管理"),
QStringLiteral("运行日志"), QStringLiteral("工具坐标标定"),
QStringLiteral("手眼标定")
};
const QStringList kPageSubtitles = {
QStringLiteral("系统信息、运行资源与全局停止"),
QStringLiteral("设备服务 / ArmService"),
QStringLiteral("相机状态、图像采集与预览"),
QStringLiteral("底盘状态、导航、速度与地图操作"),
QStringLiteral("扬声器状态、音频播放、流式音频与音量控制"),
QStringLiteral("麦克风状态、录音、音频流与音量控制"),
QStringLiteral("灵巧手状态、位置、角度、力、速度与传感器"),
QStringLiteral("仿生头状态、表情、说话动作与紧急停止"),
QStringLiteral("触控坐标与最大作用力控制"),
QStringLiteral("测试服务原始请求与反馈"),
QStringLiteral("监听 edge 接入、注册、心跳与媒体数据报"),
QStringLiteral("设备清单以及 cmvr_es 项目配置的查看、校验与编辑"),
QStringLiteral("检查连接信息与 RPC 执行记录"),
QStringLiteral("机械臂工具中心点与工具坐标系标定入口"),
QStringLiteral("相机与机械臂坐标系的手眼标定入口")
};
QWidget *createCalibrationEntryPage(const QString &title, const QString &description,
QWidget *parent)
{
QWidget *page = new QWidget(parent);
QVBoxLayout *pageLayout = new QVBoxLayout(page);
pageLayout->setContentsMargins(26, 22, 26, 22);
QFrame *panel = new QFrame(page);
panel->setObjectName(QStringLiteral("panel"));
QVBoxLayout *panelLayout = new QVBoxLayout(panel);
panelLayout->setContentsMargins(24, 22, 24, 22);
panelLayout->setSpacing(8);
QLabel *titleLabel = new QLabel(title, panel);
titleLabel->setObjectName(QStringLiteral("sectionTitle"));
QLabel *descriptionLabel = new QLabel(description, panel);
descriptionLabel->setObjectName(QStringLiteral("mutedLabel"));
descriptionLabel->setWordWrap(true);
QLabel *stateLabel = new QLabel(
QStringLiteral("功能入口已接入侧栏,标定服务接口将在后续版本中接入。"), panel);
stateLabel->setObjectName(QStringLiteral("statusChip"));
stateLabel->setAlignment(Qt::AlignCenter);
stateLabel->setMinimumWidth(320);
panelLayout->addWidget(titleLabel);
panelLayout->addWidget(descriptionLabel);
panelLayout->addSpacing(12);
panelLayout->addWidget(stateLabel, 0, Qt::AlignLeft);
panelLayout->addStretch(1);
pageLayout->addWidget(panel);
return page;
}
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), m_client(new RobotClient(this)),
m_audioManager(new AudioStreamManager(this)),
m_quicServer(new QuicTestServer(this))
{
#ifdef Q_OS_WIN
setWindowFlags(Qt::Window | Qt::FramelessWindowHint
| Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint
| Qt::WindowCloseButtonHint);
setAttribute(Qt::WA_NativeWindow);
#else
// The custom resize/drag implementation below uses Windows native
// messages. Keep the desktop window manager decorations on Linux.
setWindowFlags(Qt::Window);
#endif
Ui::MainWindowForm ui;
ui.setupUi(this);
m_windowSurface = ui.windowSurface;
m_customTitleBar = ui.customTitleBar;
m_titleBarPage = ui.titleBarPage;
m_titleBarBuild = ui.titleBarBuild;
m_minimizeWindowButton = ui.minimizeWindowButton;
m_maximizeWindowButton = ui.maximizeWindowButton;
m_closeWindowButton = ui.closeWindowButton;
#ifndef Q_OS_WIN
m_minimizeWindowButton->hide();
m_maximizeWindowButton->hide();
m_closeWindowButton->hide();
#endif
m_pages = ui.pages;
m_hostEdit = ui.hostEdit;
m_portSpin = ui.portSpin;
m_demoCheck = ui.demoCheck;
m_connectButton = ui.connectButton;
m_pageTitle = ui.pageTitle;
m_pageSubtitle = ui.pageSubtitle;
m_headerLayout = ui.headerLayout;
m_latencyLabel = ui.latencyLabel;
m_connectionDot = ui.connectionDot;
m_connectionText = ui.connectionText;
m_bottomLogLevel = ui.bottomLogLevel;
m_bottomLogMessage = ui.bottomLogMessage;
m_bottomVersion = ui.bottomVersion;
m_titleBarBuild->setText(QStringLiteral("Qt %1 · %2")
.arg(QString::fromLatin1(qVersion()),
#ifdef QT_NO_DEBUG
QStringLiteral("Release")));
#else
QStringLiteral("Debug")));
#endif
m_minimizeWindowButton->setIcon(UiIcons::icon(
QStringLiteral(":/icons/minus.svg"), QColor(QStringLiteral("#4f5964")),
QColor(QStringLiteral("#202832"))));
m_maximizeWindowButton->setIcon(UiIcons::icon(
QStringLiteral(":/icons/square.svg"), QColor(QStringLiteral("#4f5964")),
QColor(QStringLiteral("#202832"))));
m_closeWindowButton->setIcon(UiIcons::icon(
QStringLiteral(":/icons/x.svg"), QColor(QStringLiteral("#4f5964")),
QColor(QStringLiteral("#ffffff"))));
connect(m_minimizeWindowButton, &QPushButton::clicked,
this, &QWidget::showMinimized);
connect(m_maximizeWindowButton, &QPushButton::clicked, this, [this]() {
isMaximized() ? showNormal() : showMaximized();
});
connect(m_closeWindowButton, &QPushButton::clicked, this, &QWidget::close);
m_latencyLabel->setObjectName(QStringLiteral("statusChip"));
ui.workspaceLabel->setContentsMargins(18, 0, 0, 8);
ui.connectionTitle->hide();
m_bottomVersion->setText(QStringLiteral("CMVR %1").arg(
QCoreApplication::applicationVersion()));
QWidget *sidebarState = new QWidget(ui.connectionPanel);
sidebarState->setObjectName(QStringLiteral("sidebarConnectionState"));
QHBoxLayout *sidebarStateLayout = new QHBoxLayout(sidebarState);
sidebarStateLayout->setContentsMargins(0, 0, 0, 0);
sidebarStateLayout->setSpacing(6);
m_connectionDot->setParent(sidebarState);
m_connectionText->setParent(sidebarState);
m_latencyLabel->setParent(sidebarState);
sidebarStateLayout->addWidget(m_connectionDot);
sidebarStateLayout->addWidget(m_connectionText);
sidebarStateLayout->addStretch(1);
sidebarStateLayout->addWidget(m_latencyLabel);
ui.connectionLayout->insertWidget(0, sidebarState);
m_sidebarEndpointValue = new QLabel(QStringLiteral("--"), ui.connectionPanel);
m_sidebarEndpointValue->setObjectName(QStringLiteral("sidebarEndpoint"));
m_sidebarQuicValue = new QLabel(QStringLiteral("QUIC 未启动"), ui.connectionPanel);
m_sidebarQuicValue->setObjectName(QStringLiteral("sidebarDetail"));
m_sidebarQuicValue->setWordWrap(true);
ui.connectionLayout->insertWidget(1, m_sidebarEndpointValue);
ui.connectionLayout->insertWidget(2, m_sidebarQuicValue);
ui.workspaceLabel->setText(QStringLiteral("导航"));
const QList<QPushButton *> existingNavButtons = {
ui.systemNavButton, ui.armNavButton, ui.cameraNavButton,
ui.agvNavButton, ui.speakerNavButton, ui.microphoneNavButton,
ui.dexhandNavButton, ui.bioheadNavButton, ui.hlcNavButton,
ui.testNavButton, ui.quicNavButton, ui.configurationNavButton,
ui.diagnosticsNavButton
};
for (QPushButton *button : existingNavButtons)
ui.sidebarLayout->removeWidget(button);
for (int i = 0; i < ui.sidebarLayout->count(); ++i) {
QLayoutItem *item = ui.sidebarLayout->itemAt(i);
if (!item || !item->spacerItem())
continue;
delete ui.sidebarLayout->takeAt(i);
break;
}
QScrollArea *navScroll = new QScrollArea(ui.sidebar);
navScroll->setObjectName(QStringLiteral("navScroll"));
navScroll->setFrameShape(QFrame::NoFrame);
navScroll->setWidgetResizable(true);
navScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
QWidget *navTree = new QWidget(navScroll);
navTree->setObjectName(QStringLiteral("navTree"));
QVBoxLayout *navTreeLayout = new QVBoxLayout(navTree);
navTreeLayout->setContentsMargins(0, 0, 0, 0);
navTreeLayout->setSpacing(0);
navScroll->setWidget(navTree);
ui.sidebarLayout->insertWidget(ui.sidebarLayout->indexOf(ui.workspaceLabel) + 1,
navScroll, 1);
auto createNavContainer = [](QWidget *parent) {
QWidget *container = new QWidget(parent);
container->setObjectName(QStringLiteral("navGroupContent"));
QVBoxLayout *layout = new QVBoxLayout(container);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
return qMakePair(container, layout);
};
auto createGroupButton = [](const QString &text, QWidget *parent, int level) {
QPushButton *button = new QPushButton(text, parent);
button->setObjectName(QStringLiteral("navGroupButton"));
button->setProperty("navLevel", level);
button->setCheckable(true);
button->setChecked(true);
button->setIconSize(QSize(16, 16));
return button;
};
auto createPageButton = [](const QString &text, QWidget *parent, int level) {
QPushButton *button = new QPushButton(text, parent);
button->setObjectName(QStringLiteral("navButton"));
button->setProperty("navLevel", level);
button->setCheckable(true);
button->setIconSize(QSize(18, 18));
return button;
};
QPushButton *grpcGroupButton = createGroupButton(QStringLiteral("gRPC"), navTree, 0);
const auto grpcSection = createNavContainer(navTree);
QWidget *grpcContent = grpcSection.first;
QVBoxLayout *grpcLayout = grpcSection.second;
ui.configurationNavButton->setText(QStringLiteral("设备管理"));
ui.configurationNavButton->setObjectName(QStringLiteral("navSectionPageButton"));
ui.configurationNavButton->setProperty("navLevel", 1);
QPushButton *deviceGroupPageButton = ui.configurationNavButton;
const auto deviceSection = createNavContainer(grpcContent);
QWidget *deviceContent = deviceSection.first;
QVBoxLayout *deviceLayout = deviceSection.second;
const QList<QPushButton *> deviceButtons = {
ui.armNavButton, ui.cameraNavButton, ui.agvNavButton,
ui.speakerNavButton, ui.microphoneNavButton,
ui.dexhandNavButton, ui.bioheadNavButton
};
ui.agvNavButton->setText(QStringLiteral("AGV"));
for (QPushButton *button : deviceButtons) {
button->setParent(deviceContent);
button->setProperty("navLevel", 2);
deviceLayout->addWidget(button);
}
QPushButton *complexGroupButton = createGroupButton(
QStringLiteral("复杂控制"), grpcContent, 1);
const auto complexSection = createNavContainer(grpcContent);
QWidget *complexContent = complexSection.first;
QVBoxLayout *complexLayout = complexSection.second;
QPushButton *toolCalibrationNavButton = createPageButton(
QStringLiteral("工具坐标标定"), complexContent, 2);
QPushButton *handEyeNavButton = createPageButton(
QStringLiteral("手眼标定"), complexContent, 2);
ui.hlcNavButton->setParent(complexContent);
ui.hlcNavButton->setProperty("navLevel", 2);
complexLayout->addWidget(toolCalibrationNavButton);
complexLayout->addWidget(handEyeNavButton);
complexLayout->addWidget(ui.hlcNavButton);
ui.configurationNavButton->setParent(grpcContent);
grpcLayout->addWidget(ui.configurationNavButton);
grpcLayout->addWidget(deviceContent);
grpcLayout->addWidget(complexGroupButton);
grpcLayout->addWidget(complexContent);
ui.systemNavButton->setParent(navTree);
ui.systemNavButton->setProperty("navLevel", 0);
ui.testNavButton->setParent(navTree);
ui.testNavButton->setProperty("navLevel", 0);
ui.quicNavButton->setParent(navTree);
ui.quicNavButton->setProperty("navLevel", 0);
ui.diagnosticsNavButton->setParent(navTree);
ui.diagnosticsNavButton->setProperty("navLevel", 0);
navTreeLayout->addWidget(ui.systemNavButton);
navTreeLayout->addWidget(grpcGroupButton);
navTreeLayout->addWidget(grpcContent);
navTreeLayout->addWidget(ui.testNavButton);
navTreeLayout->addWidget(ui.quicNavButton);
navTreeLayout->addWidget(ui.diagnosticsNavButton);
navTreeLayout->addStretch(1);
m_navGroup = new QButtonGroup(this);
m_navGroup->setExclusive(true);
m_navButtons = {
ui.systemNavButton, ui.armNavButton, ui.cameraNavButton,
ui.agvNavButton, ui.speakerNavButton, ui.microphoneNavButton,
ui.dexhandNavButton, ui.bioheadNavButton, ui.hlcNavButton,
ui.testNavButton, ui.quicNavButton, ui.configurationNavButton,
ui.diagnosticsNavButton, toolCalibrationNavButton, handEyeNavButton
};
const QStringList icons = {
QStringLiteral(":/icons/activity.svg"),
QStringLiteral(":/icons/bot.svg"),
QStringLiteral(":/icons/camera.svg"),
QStringLiteral(":/icons/move.svg"),
QStringLiteral(":/icons/volume-2.svg"),
QStringLiteral(":/icons/mic.svg"),
QStringLiteral(":/icons/hand.svg"),
QStringLiteral(":/icons/scan-face.svg"),
QStringLiteral(":/icons/crosshair.svg"),
QStringLiteral(":/icons/braces.svg"),
QStringLiteral(":/icons/radio-tower.svg"),
QStringLiteral(":/icons/folder-open.svg"),
QStringLiteral(":/icons/scroll-text.svg"),
QStringLiteral(":/icons/crosshair.svg"),
QStringLiteral(":/icons/camera.svg")
};
for (int i = 0; i < m_navButtons.size(); ++i) {
m_navButtons.at(i)->setIcon(UiIcons::icon(
icons.at(i), QColor(QStringLiteral("#b8c2cc")),
QColor(QStringLiteral("#ffffff")),
QColor(QStringLiteral("#66727d"))));
m_navGroup->addButton(m_navButtons.at(i), i);
}
auto setGroupExpanded = [](QPushButton *button, QWidget *content, bool expanded) {
content->setVisible(expanded);
button->setChecked(expanded);
button->setIcon(UiIcons::icon(
expanded ? QStringLiteral(":/icons/chevron-up.svg")
: QStringLiteral(":/icons/chevron-down.svg"),
QColor(QStringLiteral("#8995a1")), QColor(QStringLiteral("#ffffff")),
QColor(QStringLiteral("#66727d")), 16));
button->setToolTip(expanded ? QStringLiteral("折叠目录")
: QStringLiteral("展开目录"));
};
setGroupExpanded(grpcGroupButton, grpcContent, true);
setGroupExpanded(complexGroupButton, complexContent, true);
auto updateDeviceIcon = [deviceGroupPageButton, deviceContent]() {
const bool expanded = deviceContent->isVisible();
deviceGroupPageButton->setIcon(UiIcons::icon(
expanded ? QStringLiteral(":/icons/chevron-up.svg")
: QStringLiteral(":/icons/chevron-down.svg"),
QColor(QStringLiteral("#8995a1")), QColor(QStringLiteral("#ffffff")),
QColor(QStringLiteral("#66727d")), 16));
deviceGroupPageButton->setToolTip(
expanded ? QStringLiteral("打开设备管理并折叠设备目录")
: QStringLiteral("打开设备管理并展开设备目录"));
};
updateDeviceIcon();
connect(grpcGroupButton, &QPushButton::clicked, this,
[grpcGroupButton, grpcContent, setGroupExpanded](bool expanded) {
setGroupExpanded(grpcGroupButton, grpcContent, expanded);
});
connect(complexGroupButton, &QPushButton::clicked, this,
[complexGroupButton, complexContent, setGroupExpanded](bool expanded) {
setGroupExpanded(complexGroupButton, complexContent, expanded);
});
connect(deviceGroupPageButton, &QPushButton::clicked, this,
[deviceContent, updateDeviceIcon]() {
deviceContent->setVisible(!deviceContent->isVisible());
updateDeviceIcon();
});
connect(m_navGroup, QOverload<int>::of(&QButtonGroup::buttonClicked),
this, &MainWindow::selectPage);
connect(m_connectButton, &QPushButton::clicked, this, &MainWindow::toggleConnection);
m_pages->addWidget(createSystemPage());
m_pages->addWidget(createArmPage());
m_pages->addWidget(createCameraPage());
m_pages->addWidget(createAgvPage());
m_pages->addWidget(createAudioPage(true));
m_pages->addWidget(createAudioPage(false));
m_pages->addWidget(createDexHandPage());
m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.BioHeadService")));
m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.HlcService")));
m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.TestService")));
m_pages->addWidget(createQuicPage());
auto *deviceManager = new ConfigEditorWidget(m_client, m_pages);
m_pages->addWidget(deviceManager);
connect(deviceManager, &ConfigEditorWidget::deviceNavigationRequested, this,
[this](int deviceType, const QString &deviceId) {
int pageIndex = -1;
switch (deviceType) {
case 6:
pageIndex = 1;
if (m_armSideCombo) {
int index = m_armSideCombo->findData(deviceId);
if (index < 0) {
m_armSideCombo->addItem(deviceId, deviceId);
index = m_armSideCombo->count() - 1;
}
m_armSideCombo->setCurrentIndex(index);
} else if (m_armIdEdit) {
m_armIdEdit->setText(deviceId);
}
break;
case 2:
pageIndex = 2;
if (m_cameraDeviceCombo) {
int index = m_cameraDeviceCombo->findData(deviceId);
if (index < 0) {
m_cameraDeviceCombo->addItem(deviceId, deviceId);
index = m_cameraDeviceCombo->count() - 1;
}
m_cameraDeviceCombo->setCurrentIndex(index);
}
break;
case 3:
pageIndex = 6;
if (m_dexHandDeviceCombo) {
int index = m_dexHandDeviceCombo->findData(deviceId);
if (index < 0) {
m_dexHandDeviceCombo->addItem(deviceId, deviceId);
index = m_dexHandDeviceCombo->count() - 1;
}
m_dexHandDeviceCombo->setCurrentIndex(index);
}
break;
case 0:
pageIndex = 3;
if (m_agvIdEdit) m_agvIdEdit->setText(deviceId);
break;
case 7:
pageIndex = 4;
if (m_speakerIdEdit) m_speakerIdEdit->setText(deviceId);
break;
case 5:
pageIndex = 5;
if (m_microphoneIdEdit) m_microphoneIdEdit->setText(deviceId);
break;
case 8:
pageIndex = 7;
break;
default:
break;
}
if (pageIndex < 0)
return;
if (auto *rpcPage = qobject_cast<RpcServiceWidget *>(m_pages->widget(pageIndex)))
rpcPage->setDeviceId(deviceId);
selectPage(pageIndex);
});
m_pages->addWidget(createDiagnosticsPage());
m_pages->addWidget(createCalibrationEntryPage(
QStringLiteral("工具坐标标定"),
QStringLiteral("用于建立工具中心点(TCP)及其相对于机械臂末端的坐标变换。"),
m_pages));
m_pages->addWidget(createCalibrationEntryPage(
QStringLiteral("手眼标定"),
QStringLiteral("用于求解相机坐标系与机械臂基座或末端坐标系之间的变换关系。"),
m_pages));
const QString comboPopupStyle = QStringLiteral(
"QListView {"
" background: #ffffff; color: #33404c;"
" border: 1px solid #cfd4da; border-radius: 4px;"
" padding: 4px; outline: 0;"
"}"
"QListView::item {"
" min-height: 32px; padding: 0 10px;"
" border: none; border-radius: 3px;"
"}"
"QListView::item:hover {"
" color: #27313b; background: #f3f7fb;"
"}"
"QListView::item:selected {"
" color: #145da8; background: #e8f2ff; font-weight: 600;"
"}"
);
const QList<QComboBox *> comboBoxes = findChildren<QComboBox *>();
for (QComboBox *comboBox : comboBoxes) {
QListView *popupView = new QListView(comboBox);
popupView->setObjectName(QStringLiteral("comboPopupView"));
popupView->setSpacing(1);
popupView->setUniformItemSizes(true);
popupView->setStyleSheet(comboPopupStyle);
comboBox->setView(popupView);
}
connect(m_client, &RobotClient::connectionChanged, this, &MainWindow::updateConnection);
connect(m_client, &RobotClient::armInfoReceived, this, &MainWindow::updateArmInfo);
connect(m_client, &RobotClient::telemetryReceived, this, &MainWindow::updateTelemetry);
connect(m_client, &RobotClient::armTelemetryHealthChanged,
this, &MainWindow::updateArmTelemetryHealth);
connect(m_client, &RobotClient::systemStatusReceived, this, &MainWindow::updateSystemStatus);
connect(m_client, &RobotClient::systemInfoReceived, this, &MainWindow::updateSystemInfo);
connect(m_client, &RobotClient::imageReceived, this, &MainWindow::updateImage);
connect(m_client, &RobotClient::cameraStatusReceived, this,
[this](const QString &cameraId, const QVariantMap &state) {
if (!m_cameraDeviceCombo || !m_cameraCodecCombo
|| m_cameraDeviceCombo->currentData().toString() != cameraId) {
return;
}
const QString codec = state.value(QStringLiteral("codec")).toString().toLower();
if (codec.isEmpty())
return;
const bool isH265 = codec.contains(QStringLiteral("265"))
|| codec.contains(QStringLiteral("hevc"));
{
const QSignalBlocker blocker(m_cameraCodecCombo);
m_cameraCodecCombo->setCurrentIndex(isH265 ? 1 : 0);
}
m_cameraCodecCombo->setToolTip(
QStringLiteral("服务端当前编码器:%1").arg(codec.toUpper()));
m_client->setCameraStreamCodec(isH265 ? QStringLiteral("h265")
: QStringLiteral("h264"));
});
connect(m_client, &RobotClient::dexHandStatusReceived,
this, &MainWindow::updateDexHandStatus);
connect(m_client, &RobotClient::dexHandTactileReceived,
this, &MainWindow::updateDexHandTactile);
connect(m_client, &RobotClient::dexHandTactileStreamStateChanged,
this, [this](bool running, const QString &detail) {
if (m_dexHandTactileStateLabel) m_dexHandTactileStateLabel->setText(detail);
if (m_dexHandTactileStartButton) m_dexHandTactileStartButton->setEnabled(!running);
if (m_dexHandTactileStopButton) m_dexHandTactileStopButton->setEnabled(running);
});
connect(m_client, &RobotClient::videoFrameReceived, this, &MainWindow::updateVideoFrame);
connect(m_client, &RobotClient::cameraStreamStateChanged,
this, &MainWindow::updateCameraStreamState);
connect(m_client, &RobotClient::cameraRecordingStateChanged,
this, &MainWindow::updateCameraRecordingState);
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 QVariantMap &metadata,
const QString &detail) {
m_pendingAgvMapImage = image;
m_pendingAgvMapMetadata = metadata;
m_pendingAgvMapDetail = detail;
m_agvMapFramePending = true;
const int intervalMs = m_agvMapRefreshCombo
? m_agvMapRefreshCombo->currentData().toInt() : 0;
if (intervalMs <= 0) {
presentPendingAgvMapFrame();
} else if (m_agvMapRefreshTimer && !m_agvMapRefreshTimer->isActive()) {
presentPendingAgvMapFrame();
m_agvMapRefreshTimer->setInterval(intervalMs);
m_agvMapRefreshTimer->start();
}
});
connect(m_client, &RobotClient::agvMapStreamStateChanged, this,
[this](bool running, const QString &detail) {
m_agvMapStreamActive = running;
const int intervalMs = m_agvMapRefreshCombo
? m_agvMapRefreshCombo->currentData().toInt() : 0;
if (m_agvMapRefreshTimer) {
if (running && intervalMs > 0) {
m_agvMapRefreshTimer->setInterval(intervalMs);
m_agvMapRefreshTimer->start();
} else if (!running) {
presentPendingAgvMapFrame();
m_agvMapRefreshTimer->stop();
}
}
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);
m_agvMappingStateLabel->style()->polish(m_agvMappingStateLabel);
});
connect(m_client, &RobotClient::commandFinished, this, &MainWindow::handleCommand);
connect(m_client, &RobotClient::logMessage, this, &MainWindow::appendLog);
connect(m_audioManager, &AudioStreamManager::speakerFrameReady,
m_client, &RobotClient::sendSpeakerAudioFrame);
connect(m_client, &RobotClient::audioFrameReceived,
m_audioManager, &AudioStreamManager::playPcmFrame);
connect(m_audioManager, &AudioStreamManager::logMessage,
this, &MainWindow::appendLog);
connect(m_quicServer, &QuicTestServer::runningChanged,
this, &MainWindow::updateQuicRunning);
connect(m_quicServer, &QuicTestServer::clientCountChanged, this, [this](int count) {
m_quicClientValue->setText(QString::number(count));
});
connect(m_quicServer, &QuicTestServer::statisticsChanged, this,
[this](quint64 registrations, quint64 heartbeats,
quint64 datagrams, quint64 datagramBytes) {
m_quicRegistrationValue->setText(QString::number(registrations));
m_quicHeartbeatValue->setText(QString::number(heartbeats));
m_quicDatagramValue->setText(QString::number(datagrams));
m_quicDatagramBytesValue->setText(QString::number(datagramBytes));
});
connect(m_quicServer, &QuicTestServer::nodeRegistered, this,
[this](const QString &nodeId, const QString &bootId,
const QString &grpcEndpoint, const QString &peerAddress) {
m_quicNodeValue->setText(nodeId);
m_quicBootValue->setText(bootId);
m_quicGrpcValue->setText(grpcEndpoint);
m_quicPeerValue->setText(peerAddress);
});
connect(m_quicServer, &QuicTestServer::logMessage,
this, &MainWindow::appendQuicLog);
loadSettings();
const QStringList startupArguments = QCoreApplication::arguments();
const int cameraCodecArgument = startupArguments.indexOf(
QStringLiteral("--camera-codec"));
if (cameraCodecArgument >= 0 && cameraCodecArgument + 1 < startupArguments.size()) {
const QString codec = startupArguments.at(cameraCodecArgument + 1).trimmed().toLower();
m_cameraCodecCombo->setCurrentIndex(
codec == QStringLiteral("h265") || codec == QStringLiteral("hevc") ? 1 : 0);
}
int initialPage = 0;
const QStringList arguments = startupArguments;
const int pageArgument = arguments.indexOf(QStringLiteral("--page-index"));
if (pageArgument >= 0 && pageArgument + 1 < arguments.size()) {
bool validPage = false;
const int requestedPage = arguments.at(pageArgument + 1).toInt(&validPage);
if (validPage && requestedPage >= 0 && requestedPage < m_pages->count())
initialPage = requestedPage;
}
selectPage(initialPage);
setControlsEnabled(false);
qApp->installEventFilter(this);
appendLog(QStringLiteral("INFO"), QStringLiteral("CMVR 控制台已启动"));
appendLog(QStringLiteral("INFO"), m_client->grpcAvailable()
? QStringLiteral("原生 gRPC 后端可用")
: QStringLiteral("当前为界面构建,真实 gRPC 后端未编译"));
QTimer::singleShot(250, this, [this]() {
if (m_demoCheck->isChecked())
toggleConnection();
});
QTimer::singleShot(0, this, &MainWindow::updateWindowChrome);
}
MainWindow::~MainWindow()
{
qApp->removeEventFilter(this);
stopAgvManualMotion(false);
if (m_client)
m_client->stopAgvMapStream();
m_audioManager->stopSource();
m_audioManager->stopPlayback();
m_client->stopSpeakerAudioStream();
m_client->stopMicrophoneAudioStream();
m_quicServer->stopServer();
saveSettings();
}
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
#ifdef Q_OS_WIN
Q_UNUSED(eventType)
MSG *nativeMessage = static_cast<MSG *>(message);
if (nativeMessage && nativeMessage->message == WM_GETMINMAXINFO && result) {
MINMAXINFO *minMaxInfo = reinterpret_cast<MINMAXINFO *>(nativeMessage->lParam);
MONITORINFO monitorInfo = {};
monitorInfo.cbSize = sizeof(MONITORINFO);
const HMONITOR monitor = MonitorFromWindow(nativeMessage->hwnd,
MONITOR_DEFAULTTONEAREST);
if (minMaxInfo && GetMonitorInfoW(monitor, &monitorInfo)) {
const RECT &workArea = monitorInfo.rcWork;
const RECT &monitorArea = monitorInfo.rcMonitor;
minMaxInfo->ptMaxPosition.x = workArea.left - monitorArea.left;
minMaxInfo->ptMaxPosition.y = workArea.top - monitorArea.top;
minMaxInfo->ptMaxSize.x = workArea.right - workArea.left;
minMaxInfo->ptMaxSize.y = workArea.bottom - workArea.top;
minMaxInfo->ptMaxTrackSize = minMaxInfo->ptMaxSize;
*result = 0;
return true;
}
}
if (nativeMessage && nativeMessage->message == WM_NCHITTEST && result) {
const QPoint localPosition = mapFromGlobal(QCursor::pos());
const int resizeBorder = 7;
if (!isMaximized()) {
const bool left = localPosition.x() >= 0
&& localPosition.x() < resizeBorder;
const bool right = localPosition.x() < width()
&& localPosition.x() >= width() - resizeBorder;
const bool top = localPosition.y() >= 0
&& localPosition.y() < resizeBorder;
const bool bottom = localPosition.y() < height()
&& localPosition.y() >= height() - resizeBorder;
if (top && left) { *result = HTTOPLEFT; return true; }
if (top && right) { *result = HTTOPRIGHT; return true; }
if (bottom && left) { *result = HTBOTTOMLEFT; return true; }
if (bottom && right) { *result = HTBOTTOMRIGHT; return true; }
if (left) { *result = HTLEFT; return true; }
if (right) { *result = HTRIGHT; return true; }
if (top) { *result = HTTOP; return true; }
if (bottom) { *result = HTBOTTOM; return true; }
}
if (m_customTitleBar) {
const QPoint titlePosition = m_customTitleBar->mapFrom(this, localPosition);
if (m_customTitleBar->rect().contains(titlePosition)) {
QWidget *target = childAt(localPosition);
while (target && target != m_customTitleBar) {
if (qobject_cast<QPushButton *>(target)) {
*result = HTCLIENT;
return true;
}
target = target->parentWidget();
}
*result = HTCAPTION;
return true;
}
}
}
#else
Q_UNUSED(eventType)
Q_UNUSED(message)
Q_UNUSED(result)
#endif
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<QLineEdit *>(focus)
|| qobject_cast<QAbstractSpinBox *>(focus)
|| qobject_cast<QTextEdit *>(focus)
|| qobject_cast<QPlainTextEdit *>(focus)) {
return QMainWindow::eventFilter(watched, event);
}
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(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);
if (event && event->type() == QEvent::WindowStateChange)
updateWindowChrome();
}
void MainWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event);
updateWindowChrome();
}
void MainWindow::updateWindowChrome()
{
if (!m_windowSurface || !m_maximizeWindowButton || m_updatingWindowChrome)
return;
const bool maximized = isMaximized();
const bool stateChanged = !m_windowChromeInitialized
|| m_windowChromeMaximized != maximized;
const bool sizeChanged = !m_windowChromeInitialized
|| m_windowChromeSize != size();
if (!stateChanged && !sizeChanged)
return;
m_updatingWindowChrome = true;
if (stateChanged) {
m_windowSurface->setProperty("maximized", maximized);
m_windowSurface->style()->unpolish(m_windowSurface);
m_windowSurface->style()->polish(m_windowSurface);
m_windowSurface->update();
}
if (stateChanged) {
m_maximizeWindowButton->setIcon(UiIcons::icon(
maximized ? QStringLiteral(":/icons/copy.svg")
: QStringLiteral(":/icons/square.svg"),
QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#202832"))));
m_maximizeWindowButton->setToolTip(
maximized ? QStringLiteral("还原") : QStringLiteral("最大化"));
}
m_windowChromeSize = size();
m_windowChromeMaximized = maximized;
m_windowChromeInitialized = true;
m_updatingWindowChrome = false;
}
void MainWindow::toggleQuicServer()
{
if (m_quicServer->isRunning()) {
m_quicToggleButton->setEnabled(false);
m_quicStateValue->setText(QStringLiteral("正在停止..."));
m_quicServer->stopServer();
return;
}
saveSettings();
m_quicToggleButton->setEnabled(false);
m_quicStateValue->setText(QStringLiteral("正在启动..."));
m_quicServer->startServer(m_quicBindEdit->text().trimmed(),
static_cast<quint16>(m_quicPortSpin->value()),
m_quicAlpnEdit->text().trimmed(),
m_quicCertificateEdit->text().trimmed(),
m_quicPasswordEdit->text());
}
void MainWindow::updateQuicRunning(bool running, quint16 port, const QString &detail)
{
m_quicToggleButton->setEnabled(true);
m_quicToggleButton->setText(running ? QStringLiteral("停止 QUIC Server")
: QStringLiteral("启动 QUIC Server"));
m_quicToggleButton->setObjectName(running ? QStringLiteral("dangerButton")
: QStringLiteral("primaryButton"));
m_quicToggleButton->style()->unpolish(m_quicToggleButton);
m_quicToggleButton->style()->polish(m_quicToggleButton);
m_quicStateValue->setText(running ? QStringLiteral("运行中") : detail);
m_quicBoundValue->setText(running
? QStringLiteral("%1:%2").arg(m_quicBindEdit->text().trimmed()).arg(port)
: QStringLiteral("--"));
if (m_sidebarQuicValue) {
m_sidebarQuicValue->setText(running
? QStringLiteral("QUIC %1:%2").arg(m_quicBindEdit->text().trimmed()).arg(port)
: QStringLiteral("QUIC 未启动"));
m_sidebarQuicValue->setToolTip(detail);
}
m_quicBindEdit->setEnabled(!running);
m_quicPortSpin->setEnabled(!running);
m_quicAlpnEdit->setEnabled(!running);
m_quicCertificateEdit->setEnabled(!running);
m_quicPasswordEdit->setEnabled(!running);
appendQuicLog(running ? QStringLiteral("OK") : QStringLiteral("INFO"), detail);
}
void MainWindow::appendQuicLog(const QString &level, const QString &message)
{
if (!m_quicLogView)
return;
QString color = QStringLiteral("#aeb6c0");
if (level == QStringLiteral("ERROR"))
color = QStringLiteral("#ff7b72");
else if (level == QStringLiteral("WARN"))
color = QStringLiteral("#e3b341");
else if (level == QStringLiteral("OK"))
color = QStringLiteral("#56d39b");
const QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz");
m_quicLogView->append(QStringLiteral("<span style='color:#747d87'>%1</span> "
"<span style='color:%2;font-weight:600'>[%3]</span> %4")
.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));
if (m_titleBarPage && index < m_navButtons.size())
m_titleBarPage->setText(m_navButtons.at(index)->text());
if (m_armHeaderControls)
m_armHeaderControls->setVisible(index == 1);
if (index == 1)
ensureArmModelLoaded();
if (index == 1 && previousIndex != 1 && m_connected)
setArmTelemetryEnabled(true);
if (index != 3) {
stopAgvManualMotion();
if (m_agvStatusRefreshTimer)
m_agvStatusRefreshTimer->stop();
if (m_agvMapRefreshTimer)
m_agvMapRefreshTimer->stop();
m_agvMapFramePending = false;
m_pendingAgvMapImage = QImage();
m_pendingAgvMapMetadata.clear();
m_pendingAgvMapDetail.clear();
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::presentPendingAgvMapFrame()
{
if (!m_agvMapFramePending)
return;
if (m_agvMapView) {
m_agvMapView->setMapFrame(m_pendingAgvMapImage,
m_pendingAgvMapMetadata);
m_agvMapView->setStreamMessage(m_pendingAgvMapDetail);
}
if (m_agvMappingStateLabel)
m_agvMappingStateLabel->setText(m_pendingAgvMapDetail);
m_agvMapFramePending = false;
m_pendingAgvMapImage = QImage();
m_pendingAgvMapMetadata.clear();
m_pendingAgvMapDetail.clear();
}
void MainWindow::ensureArmModelLoaded()
{
if (!m_urdfViewer || m_pendingUrdfPath.isEmpty()
|| !m_urdfViewer->currentFile().isEmpty() || m_armModelLoadScheduled) {
return;
}
m_armModelLoadScheduled = true;
m_urdfViewer->prepareLoad(m_pendingUrdfPath);
QTimer::singleShot(450, this, [this]() {
if (!m_pages || m_pages->currentIndex() != 1) {
m_armModelLoadScheduled = false;
return;
}
const QString path = m_pendingUrdfPath;
if (m_urdfViewer && m_urdfViewer->currentFile().isEmpty())
m_urdfViewer->loadUrdf(path);
m_armModelLoadScheduled = false;
});
}
void MainWindow::toggleConnection()
{
if (m_connected) {
m_connectButton->setEnabled(false);
m_connectButton->setText(QStringLiteral("正在断开…"));
m_client->disconnectFromServer();
return;
}
if (m_hostEdit->text().trimmed().isEmpty()) {
QMessageBox::warning(this, QStringLiteral("连接参数"), QStringLiteral("请填写主机地址。"));
return;
}
saveSettings();
m_connectButton->setEnabled(false);
m_connectButton->setText(QStringLiteral("正在连接…"));
m_connectionText->setText(QStringLiteral("连接中"));
m_connectionDot->setStyleSheet(QStringLiteral("color:#df8b24; font-size:12px;"));
m_endpointValue->setText(endpoint());
appendLog(QStringLiteral("INFO"), QStringLiteral("正在连接 %1").arg(endpoint()));
m_client->connectToServer(m_hostEdit->text(), m_portSpin->value(), m_demoCheck->isChecked());
}
void MainWindow::updateConnection(bool connected, int latencyMs, const QString &detail)
{
m_connected = connected;
m_connectButton->setEnabled(true);
m_connectButton->setText(connected ? QStringLiteral("断开连接") : QStringLiteral("连接"));
m_connectionText->setText(connected ? QStringLiteral("gRPC 已连接")
: QStringLiteral("gRPC 未连接"));
m_connectionDot->setStyleSheet(QStringLiteral("color:%1; font-size:12px;")
.arg(connected ? QStringLiteral("#25a878") : QStringLiteral("#9aa1aa")));
m_latencyLabel->setText(connected ? QStringLiteral("%1 ms").arg(latencyMs) : QStringLiteral("-- ms"));
if (m_sidebarEndpointValue)
m_sidebarEndpointValue->setText(endpoint());
m_hostEdit->setEnabled(!connected);
m_portSpin->setEnabled(!connected);
m_demoCheck->setEnabled(!connected);
if (QWidget *state = m_connectionText->parentWidget()) {
state->setProperty("connected", connected);
state->style()->unpolish(state);
state->style()->polish(state);
}
setControlsEnabled(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();
for (auto it = m_cameraPreviewTiles.begin();
it != m_cameraPreviewTiles.end(); ++it) {
it->status->setText(QStringLiteral("已断开"));
}
refreshCameraStreamControls();
}
if (!connected && m_armTelemetryButton)
setArmTelemetryEnabled(false);
if (!connected) {
m_armAlertStates.clear();
const QList<QLabel *> armStates = {m_servoStatusValue, m_faultStatusValue};
for (QLabel *label : armStates) {
if (!label)
continue;
label->setText(QStringLiteral("未知"));
label->setProperty("state", QStringLiteral("unknown"));
label->style()->unpolish(label);
label->style()->polish(label);
}
}
if (connected)
m_client->requestSystemRefresh();
appendLog(connected ? QStringLiteral("INFO") : QStringLiteral("WARN"), detail);
}
void MainWindow::rebuildArmJointTables(const QStringList &jointNames)
{
if (!m_jointTable)
return;
m_activeArmJointNames = jointNames;
m_jointTable->clearContents();
m_jointTable->setRowCount(jointNames.size());
for (int row = 0; row < jointNames.size(); ++row) {
m_jointTable->setItem(row, 0, new QTableWidgetItem(jointNames.at(row)));
for (int column = 1; column < 4; ++column)
m_jointTable->setItem(row, column, new QTableWidgetItem(QStringLiteral("--")));
}
if (m_zeroJointCombo) {
const QSignalBlocker blocker(m_zeroJointCombo);
m_zeroJointCombo->clear();
m_zeroJointCombo->addItems(jointNames);
}
if (m_calibrateZeroButton)
m_calibrateZeroButton->setEnabled(m_connected && !jointNames.isEmpty());
m_previousJointVelocities.clear();
m_lastArmTelemetryMs = 0;
rebuildArmJogControls();
}
void MainWindow::rebuildArmJogControls()
{
if (!m_jointJogRowsLayout || !m_jointJogRowsHost)
return;
while (QLayoutItem *item = m_jointJogRowsLayout->takeAt(0)) {
if (QWidget *widget = item->widget())
widget->deleteLater();
delete item;
}
m_jointJogPositionLabels.clear();
m_jointJogPositionSliders.clear();
m_jointJogMinusButtons.clear();
m_jointJogPlusButtons.clear();
for (int jointIndex = 0; jointIndex < m_activeArmJointNames.size(); ++jointIndex) {
QFrame *row = new QFrame(m_jointJogRowsHost);
row->setObjectName(QStringLiteral("jogAxisRow"));
QHBoxLayout *layout = new QHBoxLayout(row);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(6);
QLabel *name = new QLabel(m_activeArmJointNames.at(jointIndex), row);
name->setMinimumWidth(76);
name->setToolTip(m_activeArmJointNames.at(jointIndex));
QLabel *position = new QLabel(QStringLiteral("-- rad"), row);
position->setObjectName(QStringLiteral("jogCurrentValue"));
position->setMinimumWidth(86);
QPushButton *minus = new QPushButton(QStringLiteral("−"), row);
QPushButton *plus = new QPushButton(QStringLiteral("+"), row);
minus->setObjectName(QStringLiteral("jogDirectionButton"));
plus->setObjectName(QStringLiteral("jogDirectionButton"));
minus->setFixedSize(38, 32);
plus->setFixedSize(38, 32);
minus->setToolTip(QStringLiteral("按住使 %1 反向运动").arg(
m_activeArmJointNames.at(jointIndex)));
plus->setToolTip(QStringLiteral("按住使 %1 正向运动").arg(
m_activeArmJointNames.at(jointIndex)));
QSlider *direction = new QSlider(Qt::Horizontal, row);
direction->setObjectName(QStringLiteral("jogDirectionIndicator"));
direction->setRange(0, 1000);
direction->setValue(0);
direction->setToolTip(QStringLiteral("等待 URDF 关节限位和实时位置"));
direction->setEnabled(false);
layout->addWidget(name);
layout->addWidget(position);
layout->addWidget(minus);
layout->addWidget(direction, 1);
layout->addWidget(plus);
connect(minus, &QPushButton::pressed, this,
[this, jointIndex]() { startJointJog(jointIndex, -1); });
connect(plus, &QPushButton::pressed, this,
[this, jointIndex]() { startJointJog(jointIndex, 1); });
connect(minus, &QPushButton::released, this, &MainWindow::stopArmJog);
connect(plus, &QPushButton::released, this, &MainWindow::stopArmJog);
m_jointJogRowsLayout->addWidget(row);
m_jointJogPositionLabels.append(position);
m_jointJogPositionSliders.append(direction);
m_jointJogMinusButtons.append(minus);
m_jointJogPlusButtons.append(plus);
}
m_jointJogRowsLayout->addStretch(1);
}
void MainWindow::startJointJog(int jointIndex, int direction)
{
if (!m_connected || !m_jogSpeedSlider || jointIndex < 0
|| jointIndex >= m_activeArmJointNames.size()) {
return;
}
QVariantList velocities;
for (int index = 0; index < m_activeArmJointNames.size(); ++index)
velocities.append(0.0);
const double ratio = m_jogSpeedSlider->value() / 100.0;
velocities[jointIndex] = direction * m_velocitySpin->value() * ratio;
m_armJogActive = true;
m_client->requestSpeedJ(m_armIdEdit->text().trimmed(), velocities,
m_accelerationSpin->value(), 60.0);
}
void MainWindow::startCartesianJog(int axisIndex, int direction)
{
if (!m_connected || !m_jogSpeedSlider || axisIndex < 0 || axisIndex >= 6)
return;
static const QStringList keys = {
QStringLiteral("vx"), QStringLiteral("vy"), QStringLiteral("vz"),
QStringLiteral("wx"), QStringLiteral("wy"), QStringLiteral("wz")
};
QVariantMap velocity;
for (const QString &key : keys)
velocity.insert(key, 0.0);
const double ratio = m_jogSpeedSlider->value() / 100.0;
const double maximumVelocity = m_cartesianVelocitySpin
? m_cartesianVelocitySpin->value() : 0.25;
velocity.insert(keys.at(axisIndex),
direction * maximumVelocity * ratio);
m_armJogActive = true;
// The current edge protocol applies named base/TCP selections to pose
// queries, while speedL accepts only the Base/Tool enum. Use Base here.
m_client->requestSpeedL(m_armIdEdit->text().trimmed(), velocity,
m_cartesianAccelerationSpin
? m_cartesianAccelerationSpin->value() : 0.5,
60.0, false);
}
void MainWindow::stopArmJog()
{
if (!m_connected || !m_armIdEdit)
return;
m_armJogActive = false;
m_client->requestArmStop(m_armIdEdit->text().trimmed());
}
void MainWindow::updateArmInfo(const QString &deviceId, const QVariantMap &info)
{
if (!m_armIdEdit || deviceId != m_armIdEdit->text().trimmed())
return;
const QString manufacturer = info.value(QStringLiteral("manufacturer")).toString();
const QString model = info.value(QStringLiteral("model")).toString();
const QString subtype = info.value(QStringLiteral("subtype")).toString();
m_armDefaultBaseFrame = info.value(QStringLiteral("defaultBaseFrame")).toString();
m_armDefaultTcpFrame = info.value(QStringLiteral("defaultTcpFrame")).toString();
const QStringList jointNames = info.value(QStringLiteral("jointNames")).toStringList();
rebuildArmJointTables(jointNames);
if (m_baseFrameCombo && m_baseFrameCombo->count() == 0)
m_baseFrameCombo->addItem(m_armDefaultBaseFrame.isEmpty()
? QStringLiteral("base") : m_armDefaultBaseFrame);
if (m_tcpFrameCombo && m_tcpFrameCombo->count() == 0)
m_tcpFrameCombo->addItem(m_armDefaultTcpFrame.isEmpty()
? QStringLiteral("tool0") : m_armDefaultTcpFrame);
if (m_armDeviceSummary) {
const QString identity = subtype.isEmpty()
? QStringLiteral("%1 · %2 %3").arg(deviceId, manufacturer, model)
: QStringLiteral("%1 · %2 %3 (%4)").arg(deviceId, manufacturer, model, subtype);
m_armDeviceSummary->setText(identity);
}
if (m_urdfViewer) {
m_urdfViewer->loadModelForIdentity(
manufacturer, model, subtype,
info.value(QStringLiteral("descriptionId")).toString());
}
m_client->requestArmFrames(deviceId);
appendLog(QStringLiteral("INFO"),
QStringLiteral("机械臂 %1:SDK 型号 %2 %3,自由度 %4")
.arg(deviceId, manufacturer, model)
.arg(jointNames.size()));
}
void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &joints,
const QVariantMap &pose, const QVariantMap &state)
{
if (!m_armIdEdit || deviceId != m_armIdEdit->text().trimmed())
return;
QHash<QString, QVariantMap> byName;
QHash<QString, double> jointPositions;
for (const QVariant &value : joints) {
const QVariantMap joint = value.toMap();
const QString name = joint.value(QStringLiteral("name")).toString();
byName.insert(name, joint);
jointPositions.insert(name, joint.value(QStringLiteral("position")).toDouble());
}
m_latestArmJointPositions = jointPositions;
const qint64 nowMs = QDateTime::currentMSecsSinceEpoch();
const double deltaSeconds = m_lastArmTelemetryMs > 0
? (nowMs - m_lastArmTelemetryMs) / 1000.0 : 0.0;
const QStringList modelJointNames = m_urdfViewer
? m_urdfViewer->jointNames() : QStringList();
const QHash<QString, QPair<double, double>> modelJointLimits = m_urdfViewer
? m_urdfViewer->jointLimits() : QHash<QString, QPair<double, double>>();
if (m_urdfViewer) {
QHash<QString, double> modelPositions = jointPositions;
int directMatches = 0;
for (const QString &name : modelJointNames) {
if (jointPositions.contains(name))
++directMatches;
}
if (directMatches == 0 && modelJointNames.size() == joints.size()) {
for (int index = 0; index < modelJointNames.size(); ++index) {
modelPositions.insert(
modelJointNames.at(index),
joints.at(index).toMap().value(QStringLiteral("position")).toDouble());
}
}
m_urdfViewer->setJointPositions(modelPositions);
}
for (int row = 0; m_jointTable && row < m_jointTable->rowCount(); ++row) {
const QTableWidgetItem *nameItem = m_jointTable->item(row, 0);
if (!nameItem)
continue;
QVariantMap joint = byName.value(nameItem->text());
if (joint.isEmpty() && row < joints.size())
joint = joints.at(row).toMap();
if (joint.isEmpty())
continue;
const double position = joint.value(QStringLiteral("position")).toDouble();
const double velocity = joint.value(QStringLiteral("velocity")).toDouble();
const double acceleration = deltaSeconds > 0.0001
&& m_previousJointVelocities.contains(nameItem->text())
? (velocity - m_previousJointVelocities.value(nameItem->text())) / deltaSeconds
: 0.0;
m_jointTable->item(row, 1)->setText(QString::number(position, 'f', 5));
m_jointTable->item(row, 2)->setText(QString::number(velocity, 'f', 5));
m_jointTable->item(row, 3)->setText(QString::number(acceleration, 'f', 4));
m_previousJointVelocities.insert(nameItem->text(), velocity);
if (row < m_jointJogPositionLabels.size())
m_jointJogPositionLabels.at(row)->setText(
QStringLiteral("%1 rad").arg(position, 0, 'f', 4));
if (row < m_jointJogPositionSliders.size()) {
QSlider *positionSlider = m_jointJogPositionSliders.at(row);
QString limitJointName = nameItem->text();
if (!modelJointLimits.contains(limitJointName)
&& row < modelJointNames.size()) {
limitJointName = modelJointNames.at(row);
}
const auto limitIt = modelJointLimits.constFind(limitJointName);
if (limitIt != modelJointLimits.constEnd()
&& qIsFinite(limitIt.value().first)
&& qIsFinite(limitIt.value().second)
&& limitIt.value().second > limitIt.value().first) {
const double lower = limitIt.value().first;
const double upper = limitIt.value().second;
const double progress = qBound(0.0, (position - lower) / (upper - lower), 1.0);
positionSlider->setValue(qRound(progress * positionSlider->maximum()));
positionSlider->setToolTip(
QStringLiteral("%1:下限 %2 rad · 当前 %3 rad · 上限 %4 rad")
.arg(nameItem->text())
.arg(lower, 0, 'f', 4)
.arg(position, 0, 'f', 4)
.arg(upper, 0, 'f', 4));
} else {
positionSlider->setValue(0);
positionSlider->setToolTip(QStringLiteral("当前 URDF 未提供有效关节限位"));
}
}
if (row == 0 && m_trend)
m_trend->appendSample(position, velocity);
}
const QList<QTableWidget *> motionTables = {m_leftMotionTable, m_motionTable};
for (QTableWidget *table : motionTables) {
if (!table)
continue;
for (int row = 0; row < table->rowCount(); ++row) {
const QTableWidgetItem *nameItem = table->item(row, 0);
if (!nameItem)
continue;
const QVariantMap joint = byName.value(nameItem->text());
if (!joint.isEmpty()) {
const double position = joint.value(QStringLiteral("position")).toDouble();
table->item(row, 1)->setText(QStringLiteral("%1°").arg(
qRadiansToDegrees(position),
0, 'f', 2));
table->item(row, 2)->setText(QString::number(position, 'f', 6));
}
}
}
if (!pose.isEmpty()) {
m_latestArmPose = pose;
static const QStringList keys = {
QStringLiteral("x"), QStringLiteral("y"), QStringLiteral("z"),
QStringLiteral("rx"), QStringLiteral("ry"), QStringLiteral("rz")
};
for (int index = 0; index < keys.size()
&& index < m_poseMetricValues.size(); ++index) {
m_poseMetricValues.at(index)->setText(
QString::number(pose.value(keys.at(index)).toDouble(), 'f', 4));
}
for (int index = 0; index < keys.size()
&& index < m_cartesianJogPoseLabels.size(); ++index) {
m_cartesianJogPoseLabels.at(index)->setText(
QStringLiteral("%1 %2")
.arg(pose.value(keys.at(index)).toDouble(), 0, 'f', 4)
.arg(index < 3 ? QStringLiteral("m") : QStringLiteral("rad")));
}
}
if (!state.isEmpty()) {
const bool connected = state.value(QStringLiteral("connected")).toBool();
const bool powered = state.value(QStringLiteral("poweredOn")).toBool();
const bool moving = state.value(QStringLiteral("moving")).toBool();
const bool fault = state.value(QStringLiteral("fault")).toBool();
const bool emergency = state.value(QStringLiteral("emergencyStopped")).toBool();
const bool protective = state.value(QStringLiteral("protectiveStopped")).toBool();
const bool freedrive = state.value(QStringLiteral("freedrive")).toBool()
|| state.value(QStringLiteral("controlMode")).toInt() == 6;
const int robotMode = state.value(QStringLiteral("robotMode")).toInt();
const int safetyMode = state.value(QStringLiteral("safetyMode")).toInt();
const bool isDisconnected = !connected || robotMode == 1;
const bool isEmergency = emergency || safetyMode == 4 || safetyMode == 6;
const bool isFault = fault || robotMode == 7 || safetyMode == 7;
const bool isProtective = protective || safetyMode == 3 || safetyMode == 5;
const auto setStateLabel = [](QLabel *label, const QString &text,
const QString &visualState) {
if (!label)
return;
label->setText(text);
label->setProperty("state", visualState);
label->style()->unpolish(label);
label->style()->polish(label);
};
setStateLabel(
m_servoStatusValue,
isDisconnected ? QStringLiteral("已断开")
: freedrive ? QStringLiteral("拖动示教")
: powered ? (moving ? QStringLiteral("已使能 · 运动中")
: QStringLiteral("已使能 · 空闲"))
: QStringLiteral("未使能"),
(isDisconnected || isEmergency || isFault || isProtective)
? QStringLiteral("error") : QStringLiteral("good"));
setStateLabel(
m_faultStatusValue,
isDisconnected ? QStringLiteral("通信断开")
: isEmergency ? QStringLiteral("急停")
: isFault ? QStringLiteral("故障")
: isProtective ? QStringLiteral("保护停止")
: freedrive ? QStringLiteral("拖动示教") : QStringLiteral("正常"),
(isDisconnected || isEmergency || isFault || isProtective || freedrive)
? QStringLiteral("error") : QStringLiteral("good"));
if (isDisconnected) {
updateArmAlert(deviceId, QStringLiteral("disconnected"),
QStringLiteral("ERROR"), QStringLiteral("机械臂已断开"),
QStringLiteral("请检查机械臂电源、网线以及控制器地址。"));
} else if (isEmergency) {
updateArmAlert(deviceId, QStringLiteral("emergency-stop"),
QStringLiteral("ERROR"), QStringLiteral("机械臂处于急停状态"),
QStringLiteral("请确认现场安全后释放急停并清除故障。"));
} else if (isFault) {
updateArmAlert(deviceId, QStringLiteral("fault"),
QStringLiteral("ERROR"), QStringLiteral("机械臂发生故障"),
QStringLiteral("请检查控制器告警信息,排除原因后清除故障。"));
} else if (isProtective) {
updateArmAlert(deviceId, QStringLiteral("protective-stop"),
QStringLiteral("WARN"), QStringLiteral("机械臂处于保护停止状态"),
QStringLiteral("请检查碰撞、限位或安全输入。"));
} else if (freedrive) {
updateArmAlert(deviceId, QStringLiteral("freedrive"),
QStringLiteral("WARN"), QStringLiteral("机械臂处于拖动示教状态"),
QStringLiteral("上位机运动控制暂不可用,请退出拖动示教后再操作。"));
} else {
updateArmAlert(deviceId, QString(), QString(), QString());
}
}
if (m_armAlertStates.value(deviceId).isEmpty()
&& m_bottomLogLevel && m_bottomLogMessage) {
m_bottomLogLevel->setText(QStringLiteral("[OK]"));
m_bottomLogLevel->setProperty("level", QStringLiteral("ok"));
m_bottomLogLevel->style()->unpolish(m_bottomLogLevel);
m_bottomLogLevel->style()->polish(m_bottomLogLevel);
m_bottomLogMessage->setText(QStringLiteral("Arm Telemetry · 已接收 %1 个关节状态 · %2")
.arg(joints.size()).arg(QDateTime::currentDateTime().toString("HH:mm:ss.zzz")));
}
}
void MainWindow::updateArmTelemetryHealth(const QString &deviceId, bool available,
const QString &detail)
{
if (!m_armIdEdit || deviceId != m_armIdEdit->text().trimmed())
return;
if (available) {
if (m_armAlertStates.value(deviceId) == QStringLiteral("communication"))
updateArmAlert(deviceId, QString(), QString(), QString());
return;
}
const auto markError = [](QLabel *label, const QString &text) {
if (!label)
return;
label->setText(text);
label->setProperty("state", QStringLiteral("error"));
label->style()->unpolish(label);
label->style()->polish(label);
};
markError(m_servoStatusValue, QStringLiteral("遥测中断"));
markError(m_faultStatusValue, QStringLiteral("通信异常"));
updateArmAlert(deviceId, QStringLiteral("communication"),
QStringLiteral("ERROR"), QStringLiteral("机械臂遥测通信异常"), detail);
}
void MainWindow::updateArmAlert(const QString &deviceId, const QString &alertKey,
const QString &level, const QString &summary,
const QString &detail)
{
const QString previous = m_armAlertStates.value(deviceId);
if (previous == alertKey)
return;
if (alertKey.isEmpty()) {
m_armAlertStates.remove(deviceId);
if (!previous.isEmpty())
appendLog(QStringLiteral("OK"),
QStringLiteral("机械臂 %1 状态已恢复正常").arg(deviceId));
return;
}
m_armAlertStates.insert(deviceId, alertKey);
const QString message = detail.isEmpty()
? QStringLiteral("机械臂 %1:%2").arg(deviceId, summary)
: QStringLiteral("机械臂 %1:%2。%3").arg(deviceId, summary, detail);
appendLog(level, message);
const QString popupKey = deviceId + QLatin1Char('/') + alertKey;
const qint64 nowMs = QDateTime::currentMSecsSinceEpoch();
const qint64 lastPopupMs = m_armLastAlertPopupMs.value(popupKey, 0);
if (lastPopupMs > 0 && nowMs - lastPopupMs < 30000)
return;
m_armLastAlertPopupMs.insert(popupKey, nowMs);
QMessageBox *popup = new QMessageBox(
level == QStringLiteral("ERROR") ? QMessageBox::Critical : QMessageBox::Warning,
QStringLiteral("机械臂状态提醒"), message, QMessageBox::Ok, this);
popup->setAttribute(Qt::WA_DeleteOnClose);
popup->setWindowModality(Qt::NonModal);
popup->open();
}
void MainWindow::updateSystemStatus(double cpu, double memory, double disk,
const QVariantList &devices)
{
m_cpuValue->setText(QString::number(cpu, 'f', 0));
m_memoryValue->setText(QString::number(memory, 'f', 0));
m_diskValue->setText(QString::number(disk, 'f', 0));
m_deviceValue->setText(QString::number(devices.size()));
const QString previousId = m_armIdEdit && !m_armIdEdit->text().trimmed().isEmpty()
? m_armIdEdit->text().trimmed() : m_armSideCombo->currentData().toString();
QString firstArmId;
{
const QSignalBlocker blocker(m_armSideCombo);
m_armSideCombo->clear();
for (const QVariant &value : devices) {
const QVariantMap device = value.toMap();
if (device.value(QStringLiteral("type")).toInt() != 6)
continue;
const QString deviceId = device.value(QStringLiteral("deviceId")).toString();
if (deviceId.isEmpty())
continue;
if (firstArmId.isEmpty())
firstArmId = deviceId;
const QString vendor = device.value(QStringLiteral("vendor")).toString();
const QString driver = device.value(QStringLiteral("driverType")).toString();
const QString detail = !vendor.isEmpty() ? vendor : driver;
m_armSideCombo->addItem(
detail.isEmpty() ? deviceId : QStringLiteral("%1 · %2").arg(deviceId, detail),
deviceId);
}
int index = m_armSideCombo->findData(previousId);
if (index < 0 && m_armSideCombo->count() > 0)
index = 0;
if (index >= 0)
m_armSideCombo->setCurrentIndex(index);
}
const QString selectedId = m_armSideCombo->currentData().toString();
if (m_armIdEdit && !selectedId.isEmpty()
&& (selectedId != previousId || m_activeArmJointNames.isEmpty())) {
m_armIdEdit->setText(selectedId);
m_client->requestArmInfo(selectedId);
m_client->requestArmFrames(selectedId);
} else if (m_armIdEdit && m_armIdEdit->text().trimmed().isEmpty()
&& !firstArmId.isEmpty()) {
m_armIdEdit->setText(firstArmId);
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);
}
if (m_cameraDeviceCombo) {
const QString previousCameraId = m_cameraDeviceCombo->currentData().toString();
{
const QSignalBlocker blocker(m_cameraDeviceCombo);
m_cameraDeviceCombo->clear();
for (const QVariant &value : devices) {
const QVariantMap device = value.toMap();
if (device.value(QStringLiteral("type")).toInt() != 2)
continue;
const QString deviceId = device.value(QStringLiteral("deviceId")).toString();
if (deviceId.isEmpty())
continue;
const QString vendor = device.value(QStringLiteral("vendor")).toString();
const QString driver = device.value(QStringLiteral("driverType")).toString();
const QString detail = !vendor.isEmpty() ? vendor : driver;
m_cameraDeviceCombo->addItem(
detail.isEmpty() ? deviceId
: QStringLiteral("%1 · %2").arg(deviceId, detail),
deviceId);
}
int index = m_cameraDeviceCombo->findData(previousCameraId);
if (index < 0 && m_cameraDeviceCombo->count() > 0)
index = 0;
if (index >= 0)
m_cameraDeviceCombo->setCurrentIndex(index);
}
m_cameraDeviceCombo->setEnabled(!m_cameraStreaming && !m_cameraRecording
&& m_cameraDeviceCombo->count() > 0);
if (!m_cameraStreaming
&& previousCameraId != m_cameraDeviceCombo->currentData().toString())
rebuildCameraPreviewGrid(configuredCameraIds());
const QString cameraId = m_cameraDeviceCombo->currentData().toString();
if (!cameraId.isEmpty()
&& (previousCameraId != cameraId || m_cameraCodecCombo->toolTip().isEmpty()))
m_client->requestCameraStatus(cameraId);
}
if (m_dexHandDeviceCombo) {
const QString previousHandId = m_dexHandDeviceCombo->currentData().toString();
const QSignalBlocker blocker(m_dexHandDeviceCombo);
m_dexHandDeviceCombo->clear();
for (const QVariant &value : devices) {
const QVariantMap device = value.toMap();
if (device.value(QStringLiteral("type")).toInt() != 3)
continue;
const QString deviceId = device.value(QStringLiteral("deviceId")).toString();
if (deviceId.isEmpty())
continue;
const QString driver = device.value(QStringLiteral("driverType")).toString();
m_dexHandDeviceCombo->addItem(
driver.isEmpty() ? deviceId : QStringLiteral("%1 · %2").arg(deviceId, driver),
deviceId);
m_dexHandDeviceCombo->setItemData(m_dexHandDeviceCombo->count() - 1,
driver, Qt::UserRole + 1);
}
int index = m_dexHandDeviceCombo->findData(previousHandId);
if (index < 0 && m_dexHandDeviceCombo->count() > 0)
index = 0;
if (index >= 0)
m_dexHandDeviceCombo->setCurrentIndex(index);
const QString selectedHandId = m_dexHandDeviceCombo->currentData().toString();
if (!selectedHandId.isEmpty())
m_client->requestDexHandStatus(selectedHandId);
}
}
void MainWindow::updateSystemInfo(const QVariantMap &info)
{
m_systemNameValue->setText(info.value(QStringLiteral("name"), QStringLiteral("--")).toString());
m_systemVersionValue->setText(info.value(QStringLiteral("version"), QStringLiteral("--")).toString());
const QString platform = QStringLiteral("%1 · %2")
.arg(info.value(QStringLiteral("os"), QStringLiteral("--")).toString(),
info.value(QStringLiteral("architecture"), QStringLiteral("--")).toString());
m_systemOsValue->setText(platform);
}
void MainWindow::updateDexHandStatus(const QString &deviceId, bool initialized,
bool hasTactileFeedback,
const QString &model,
const QVariantList &freedoms)
{
if (!m_dexHandDeviceCombo
|| m_dexHandDeviceCombo->currentData().toString() != deviceId)
return;
const QString modelText = model.isEmpty() ? QStringLiteral("未知型号") : model;
m_dexHandStateLabel->setText(initialized
? QStringLiteral("%1 · 已初始化 · %2")
.arg(modelText,
hasTactileFeedback ? QStringLiteral("支持触觉")
: QStringLiteral("无触觉"))
: QStringLiteral("%1 · 未初始化").arg(modelText));
m_dexHandStateLabel->setProperty("state", initialized ? QStringLiteral("ok")
: QStringLiteral("warn"));
if (m_dexHandHasTactileFeedback && !hasTactileFeedback)
m_client->stopDexHandTactileStream();
m_dexHandHasTactileFeedback = hasTactileFeedback;
if (m_dexHandTactilePanel)
m_dexHandTactilePanel->setVisible(hasTactileFeedback);
m_dexHandStateTable->setRowCount(6);
const QString driver = m_dexHandDeviceCombo->currentData(Qt::UserRole + 1).toString();
const bool oymotion = driver.contains(QStringLiteral("OYMotion"),
Qt::CaseInsensitive);
const QStringList names = {QStringLiteral("小拇指"), QStringLiteral("无名指"),
QStringLiteral("中指"), QStringLiteral("食指"),
QStringLiteral("大拇指弯曲"), QStringLiteral("大拇指旋转")};
for (int row = 0; row < 6; ++row) {
QVariantMap freedom;
for (const QVariant &value : freedoms) {
if (value.toMap().value(QStringLiteral("id")).toInt() == row) {
freedom = value.toMap();
break;
}
}
const QStringList values = {
names.at(row), oymotion
? QStringLiteral("%1°").arg(
freedom.value(QStringLiteral("angle")).toInt() / 100.0, 0, 'f', 2)
: QString::number(freedom.value(QStringLiteral("angle")).toInt()),
QString::number(freedom.value(QStringLiteral("position")).toInt()),
QString::number(freedom.value(QStringLiteral("speed")).toInt()),
QString::number(freedom.value(QStringLiteral("force")).toInt()),
QString::number(freedom.value(QStringLiteral("current")).toInt()),
QString::number(freedom.value(QStringLiteral("temperature")).toInt()),
freedom.value(QStringLiteral("error")).toInt() == 0
? QStringLiteral("正常")
: freedom.value(QStringLiteral("errors")).toStringList().join(QStringLiteral(";"))};
for (int column = 0; column < values.size(); ++column)
m_dexHandStateTable->setItem(row, column, new QTableWidgetItem(values.at(column)));
}
}
void MainWindow::updateDexHandTactile(const QString &deviceId, int rows, int cols,
const QVariantList &values, quint64 frameCount)
{
if (!m_dexHandDeviceCombo || !m_dexHandTactileHeatmap
|| m_dexHandDeviceCombo->currentData().toString() != deviceId
|| rows <= 0 || cols <= 0 || values.size() < rows * cols)
return;
// Preserve the full-rate gRPC reception while limiting expensive table
// painting to about 30 FPS.
const qint64 now = QDateTime::currentMSecsSinceEpoch();
if (now - m_lastDexHandTactileUiUpdateMs < 33)
return;
m_lastDexHandTactileUiUpdateMs = now;
QVector<int> forceValues;
forceValues.reserve(rows * cols);
int peak = 0;
qint64 totalMilliNewtons = 0;
for (int index = 0; index < rows * cols; ++index) {
const int value = values.at(index).toInt();
forceValues.append(value);
peak = qMax(peak, value);
totalMilliNewtons += value;
}
m_dexHandTactileHeatmap->setTactileData(rows, cols, forceValues);
if (m_dexHandTactileStateLabel)
m_dexHandTactileStateLabel->setText(
QStringLiteral("帧 %1 · 合力 %2 N · 峰值 %3 mN")
.arg(frameCount)
.arg(totalMilliNewtons / 1000.0, 0, 'f', 3)
.arg(peak));
}
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();
const bool emergency = state.value(QStringLiteral("emergency")).toBool();
m_agvConnectionValue->setText(QStringLiteral("%1 · %2%3")
.arg(controllerConnected ? QStringLiteral("在线") : QStringLiteral("离线"),
localized ? QStringLiteral("已定位") : QStringLiteral("未定位"),
(fault || emergency) ? QStringLiteral(" · 异常") : QString()));
m_agvMapValue->setText(QStringLiteral("%1 / %2")
.arg(state.value(QStringLiteral("map"), QStringLiteral("--")).toString(),
state.value(QStringLiteral("station"), QStringLiteral("--")).toString()));
m_agvPoseValue->setText(QStringLiteral("%1, %2, %3")
.arg(state.value(QStringLiteral("x")).toDouble(), 0, 'f', 2)
.arg(state.value(QStringLiteral("y")).toDouble(), 0, 'f', 2)
.arg(state.value(QStringLiteral("theta")).toDouble(), 0, 'f', 2));
m_agvMotionValue->setText(QStringLiteral("%1 / %2 / %3")
.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));
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());
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()
? QStringLiteral("运动中") : QStringLiteral("静止")));
m_agvSafetyValue->setText(QStringLiteral("%1 / %2")
.arg(fault ? QStringLiteral("有故障") : QStringLiteral("正常"),
emergency ? QStringLiteral("已急停") : QStringLiteral("未急停")));
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
? QDateTime::fromMSecsSinceEpoch(qRound64(timestamp * 1000.0))
.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)
{
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);
if (mapIndex >= 0)
m_agvMapCombo->setCurrentIndex(mapIndex);
const QString selectedStation = m_agvStationCombo->currentText();
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));
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);
if (stationIndex >= 0)
m_agvStationCombo->setCurrentIndex(stationIndex);
QPixmap preview(960, 280);
preview.fill(QColor(QStringLiteral("#eef2f6")));
QPainter painter(&preview);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(QPen(QColor(QStringLiteral("#d5dee6")), 1));
for (int x = 60; x < preview.width(); x += 100)
painter.drawLine(x, 24, x, preview.height() - 24);
for (int y = 40; y < preview.height(); y += 60)
painter.drawLine(36, y, preview.width() - 36, y);
if (stations.isEmpty()) {
painter.setPen(QColor(QStringLiteral("#71808e")));
painter.drawText(preview.rect(), Qt::AlignCenter,
QStringLiteral("当前地图没有可显示的站点"));
} else {
double minX = stations.first().toMap().value(QStringLiteral("x")).toDouble();
double maxX = minX;
double minY = stations.first().toMap().value(QStringLiteral("y")).toDouble();
double maxY = minY;
for (const QVariant &entry : stations) {
const QVariantMap station = entry.toMap();
minX = qMin(minX, station.value(QStringLiteral("x")).toDouble());
maxX = qMax(maxX, station.value(QStringLiteral("x")).toDouble());
minY = qMin(minY, station.value(QStringLiteral("y")).toDouble());
maxY = qMax(maxY, station.value(QStringLiteral("y")).toDouble());
}
if (qFuzzyCompare(minX, maxX)) { minX -= 1.0; maxX += 1.0; }
if (qFuzzyCompare(minY, maxY)) { minY -= 1.0; maxY += 1.0; }
QPointF previous;
for (int i = 0; i < stations.size(); ++i) {
const QVariantMap station = stations.at(i).toMap();
const QPointF point(
60.0 + (station.value(QStringLiteral("x")).toDouble() - minX) /
(maxX - minX) * (preview.width() - 120.0),
40.0 + (maxY - station.value(QStringLiteral("y")).toDouble()) /
(maxY - minY) * (preview.height() - 80.0));
if (i > 0) {
painter.setPen(QPen(QColor(QStringLiteral("#9db7ce")), 2));
painter.drawLine(previous, point);
}
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(QStringLiteral("#218c74")));
painter.drawEllipse(point, 7, 7);
painter.setPen(QColor(QStringLiteral("#26323d")));
painter.drawText(point + QPointF(10, -8),
station.value(QStringLiteral("id")).toString());
previous = point;
}
}
painter.end();
m_agvMapOverview->setPixmap(preview.scaled(
m_agvMapOverview->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}
void MainWindow::updateImage(const QImage &image, const QString &detail)
{
m_lastImage = image;
if (m_videoRender)
m_videoRender->setImage(image);
m_imageMetaLabel->setText(detail);
m_saveImageButton->setEnabled(true);
}
void MainWindow::updateVideoFrame(const QString &cameraId, const VideoFrame &frame,
const QString &detail)
{
const QString resolvedId = cameraId.isEmpty() && !m_cameraPreviewTiles.isEmpty()
? m_cameraPreviewTiles.constBegin().key() : cameraId;
const auto it = m_cameraPreviewTiles.find(resolvedId);
if (it == m_cameraPreviewTiles.end())
return;
it->render->setFrame(frame);
it->meta->setText(detail);
m_imageMetaLabel->setText(QStringLiteral("%1 | %2").arg(resolvedId, detail));
m_saveImageButton->setEnabled(true);
}
void MainWindow::updateCameraStreamState(const QString &cameraId, bool running,
const QString &detail)
{
const QString resolvedId = cameraId.isEmpty() && !m_cameraPreviewTiles.isEmpty()
? m_cameraPreviewTiles.constBegin().key() : cameraId;
if (running)
m_runningCameraIds.insert(resolvedId);
else
m_runningCameraIds.remove(resolvedId);
const auto it = m_cameraPreviewTiles.find(resolvedId);
if (it != m_cameraPreviewTiles.end()) {
it->status->setText(running ? QStringLiteral("播放中")
: QStringLiteral("已停止"));
it->status->setToolTip(detail);
if (!running && !detail.isEmpty())
it->meta->setText(detail);
}
refreshCameraStreamControls();
m_cameraStreamStateLabel->setToolTip(detail);
if (!detail.isEmpty()) {
const bool failed = detail.contains(QStringLiteral("失败"));
appendLog(failed ? QStringLiteral("ERROR") : QStringLiteral("INFO"),
QStringLiteral("%1: %2").arg(resolvedId, detail));
}
}
void MainWindow::updateCameraRecordingState(bool recording, const QString &detail)
{
m_cameraRecording = recording;
if (!m_cameraRecordButton || !m_cameraRecordPathEdit || !m_cameraRecordStateLabel)
return;
m_cameraRecordButton->setEnabled(m_connected);
m_cameraRecordButton->setText(recording ? QStringLiteral("停止录像")
: QStringLiteral("开始录像"));
m_cameraRecordButton->setIcon(style()->standardIcon(
recording ? QStyle::SP_MediaStop : QStyle::SP_DialogSaveButton));
m_cameraRecordButton->setObjectName(recording ? QStringLiteral("dangerButton")
: QStringLiteral("primaryButton"));
m_cameraRecordButton->style()->unpolish(m_cameraRecordButton);
m_cameraRecordButton->style()->polish(m_cameraRecordButton);
m_cameraRecordPathEdit->setEnabled(!recording);
m_cameraDeviceCombo->setEnabled(!m_cameraStreaming && !recording
&& m_cameraDeviceCombo->count() > 0);
m_cameraRecordStateLabel->setText(recording ? QStringLiteral("录像中")
: QStringLiteral("未录像"));
m_cameraRecordStateLabel->setToolTip(detail);
if (!detail.isEmpty())
appendLog(QStringLiteral("INFO"), detail);
}
void MainWindow::handleCommand(const QString &command, bool success, const QString &detail)
{
QLabel *stateLabel = nullptr;
QString stateText;
if (command == QStringLiteral("Torque On")) {
stateLabel = m_servoStatusValue;
stateText = success ? QStringLiteral("已使能") : QStringLiteral("使能失败");
} else if (command == QStringLiteral("Torque Off")) {
stateLabel = m_servoStatusValue;
stateText = success ? QStringLiteral("已去使能") : QStringLiteral("操作失败");
} else if (command == QStringLiteral("Clear Fault")) {
stateLabel = m_faultStatusValue;
stateText = success ? QStringLiteral("正常") : QStringLiteral("清除失败");
}
if (stateLabel) {
stateLabel->setText(stateText);
stateLabel->setProperty("state", success ? QStringLiteral("good")
: QStringLiteral("error"));
stateLabel->style()->unpolish(stateLabel);
stateLabel->style()->polish(stateLabel);
}
if (!success && (command == QStringLiteral("Camera Start Recording")
|| 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 StopMapping")) {
const bool asynchronousMappingFrame =
!success
&& detail.contains(QStringLiteral("expected=16101"))
&& detail.contains(QStringLiteral("actual=17002"));
if (asynchronousMappingFrame && !m_agvStopMappingRetryPending) {
m_agvStopMappingRetryPending = true;
if (m_agvMappingStateLabel) {
m_agvMappingStateLabel->setText(
QStringLiteral("正在重新确认停止建图"));
}
appendLog(
QStringLiteral("WARN"),
QStringLiteral("停止建图响应被异步地图帧打断,正在自动重试一次"));
QTimer::singleShot(350, this, [this]() {
if (!m_agvStopMappingRetryPending)
return;
m_client->requestAgvAction(
m_agvIdEdit->text().trimmed(),
QStringLiteral("StopMapping"));
});
return;
}
m_agvStopMappingRetryPending = false;
if (m_agvStopMappingButton)
m_agvStopMappingButton->setEnabled(true);
if (success) {
if (m_agvMappingStateLabel)
m_agvMappingStateLabel->setText(QStringLiteral("建图已停止"));
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed());
restartAgvMapStream();
} else if (m_agvMappingStateLabel) {
m_agvMappingStateLabel->setText(QStringLiteral("停止建图失败"));
}
}
appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"),
QStringLiteral("%1 · %2").arg(command, detail));
if (command == QStringLiteral("MoveJ") && m_jointPointMovePending) {
m_jointPointMovePending = false;
if (!success) {
stopJointPointLoop(QStringLiteral("MoveJ 执行失败:%1").arg(detail));
} else if (m_jointPointLoopActive) {
const int completedIndex = m_jointPointLoopCursor - 1;
const double waitSeconds = completedIndex >= 0
&& completedIndex < m_jointPointExecutionWaits.size()
? m_jointPointExecutionWaits.at(completedIndex) : 0.0;
const int delayMs = qRound(waitSeconds * 1000.0);
QTimer::singleShot(delayMs, this, &MainWindow::advanceJointPointLoop);
}
}
if (!success)
m_connectionText->setToolTip(detail);
}
void MainWindow::appendLog(const QString &level, const QString &message)
{
if (m_bottomLogLevel && m_bottomLogMessage) {
const QString normalizedLevel = level.toLower();
m_bottomLogLevel->setText(QStringLiteral("[%1]").arg(level));
m_bottomLogLevel->setProperty("level", normalizedLevel);
m_bottomLogLevel->style()->unpolish(m_bottomLogLevel);
m_bottomLogLevel->style()->polish(m_bottomLogLevel);
m_bottomLogMessage->setText(QStringLiteral("%1 · %2")
.arg(message, QDateTime::currentDateTime().toString("HH:mm:ss.zzz")));
m_bottomLogMessage->setToolTip(message);
}
if (!m_logView)
return;
QString color = QStringLiteral("#aeb6c0");
if (level == QStringLiteral("ERROR"))
color = QStringLiteral("#ff7b72");
else if (level == QStringLiteral("WARN"))
color = QStringLiteral("#e3b341");
else if (level == QStringLiteral("OK"))
color = QStringLiteral("#56d39b");
const QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz");
m_logView->append(QStringLiteral("<span style='color:#747d87'>%1</span> "
"<span style='color:%2;font-weight:600'>[%3]</span> %4")
.arg(timestamp, color, level, message.toHtmlEscaped()));
}
void MainWindow::sendMoveJ()
{
QVariantList positions;
const bool leftArm = m_armSideCombo
&& m_armSideCombo->currentData().toString() == QStringLiteral("left");
const QList<QDoubleSpinBox *> &spins = leftArm
? m_leftTargetSpins : m_rightTargetSpins;
for (QDoubleSpinBox *spin : spins)
positions.append(qDegreesToRadians(spin->value()));
m_client->requestMoveJ(m_armIdEdit->text().trimmed(), positions,
m_velocitySpin->value(), m_accelerationSpin->value());
}
void MainWindow::refreshRecordedJointPoints()
{
if (!m_jointPointTable)
return;
QStringList pointNames;
for (const RecordedJointPoint &point : m_recordedJointPoints)
pointNames.append(point.name);
if (m_jointFlowEditor)
m_jointFlowEditor->setAvailablePointNames(pointNames);
m_jointPointTable->setRowCount(m_recordedJointPoints.size());
for (int row = 0; row < m_recordedJointPoints.size(); ++row) {
const RecordedJointPoint &point = m_recordedJointPoints.at(row);
QStringList values;
for (double position : point.positions)
values.append(QString::number(position, 'f', 6));
m_jointPointTable->setItem(row, 0, new QTableWidgetItem(point.name));
m_jointPointTable->setItem(row, 1, new QTableWidgetItem(
point.side == QStringLiteral("left") ? QStringLiteral("左臂")
: QStringLiteral("右臂")));
m_jointPointTable->setItem(row, 2, new QTableWidgetItem(point.deviceId));
m_jointPointTable->setItem(row, 3, new QTableWidgetItem(
QString::number(point.positions.size())));
QTableWidgetItem *positionsItem = new QTableWidgetItem(values.join(QStringLiteral(", ")));
positionsItem->setToolTip(QStringLiteral("关节顺序:%1\n角度(rad):%2")
.arg(point.jointNames.join(QStringLiteral(", ")),
values.join(QStringLiteral(", "))));
m_jointPointTable->setItem(row, 4, positionsItem);
}
}
void MainWindow::refreshJointFlowTable()
{
if (m_jointFlowEditor)
m_jointFlowEditor->update();
}
void MainWindow::recordCurrentJointPoint()
{
const QString name = m_jointPointNameEdit
? m_jointPointNameEdit->text().trimmed() : QString();
if (name.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("记录关节点位"),
QStringLiteral("请输入动作名称。"));
return;
}
for (const RecordedJointPoint &point : m_recordedJointPoints) {
if (point.name.compare(name, Qt::CaseInsensitive) == 0) {
QMessageBox::warning(this, QStringLiteral("记录关节点位"),
QStringLiteral("动作名称“%1”已存在,请使用其他名称。")
.arg(name));
return;
}
}
const bool leftArm = m_armSideCombo
&& m_armSideCombo->currentData().toString() == QStringLiteral("left");
const QStringList jointNames = leftArm ? m_leftArmJointNames : m_rightArmJointNames;
if (jointNames.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("记录关节点位"),
QStringLiteral("当前 URDF 中没有该机械臂的可运动关节。"));
return;
}
RecordedJointPoint point;
point.name = name;
point.side = leftArm ? QStringLiteral("left") : QStringLiteral("right");
point.deviceId = m_armIdEdit->text().trimmed();
point.jointNames = jointNames;
QStringList missing;
for (const QString &jointName : jointNames) {
if (!m_latestArmJointPositions.contains(jointName)) {
missing.append(jointName);
continue;
}
point.positions.append(m_latestArmJointPositions.value(jointName));
}
if (!missing.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("记录关节点位"),
QStringLiteral("尚未收到以下关节的实时角度:\n%1\n\n请先启动遥测。")
.arg(missing.join(QStringLiteral(", "))));
return;
}
if (point.deviceId.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("记录关节点位"),
QStringLiteral("当前 Device ID 为空。"));
return;
}
m_recordedJointPoints.append(point);
refreshRecordedJointPoints();
QSettings settings;
saveJointPrograms(settings);
m_jointPointNameEdit->clear();
m_jointPointTable->selectRow(m_recordedJointPoints.size() - 1);
appendLog(QStringLiteral("OK"),
QStringLiteral("已记录动作“%1”,%2 个关节(rad)")
.arg(point.name).arg(point.positions.size()));
}
void MainWindow::executeSelectedJointPoint()
{
if (m_jointPointLoopActive || m_jointPointMovePending)
return;
const QModelIndexList selected = m_jointPointTable
? m_jointPointTable->selectionModel()->selectedRows() : QModelIndexList();
if (selected.isEmpty()) {
QMessageBox::information(this, QStringLiteral("执行关节点位"),
QStringLiteral("请先选择一个已记录动作。"));
return;
}
const int row = selected.first().row();
if (row < 0 || row >= m_recordedJointPoints.size())
return;
const RecordedJointPoint &point = m_recordedJointPoints.at(row);
QVariantList positions;
for (double position : point.positions)
positions.append(position);
m_jointPointMovePending = true;
m_client->requestMoveJ(point.deviceId, positions,
m_velocitySpin->value(), m_accelerationSpin->value());
if (m_jointPointLoopStatus)
m_jointPointLoopStatus->setText(QStringLiteral("执行:%1").arg(point.name));
}
void MainWindow::startJointPointLoop()
{
if (m_jointPointLoopActive || m_jointPointMovePending)
return;
if (!m_jointFlowEditor || m_jointFlowEditor->isEmpty()) {
QMessageBox::information(this, QStringLiteral("执行自定义流程"),
QStringLiteral("请先向自定义流程中添加步骤。"));
return;
}
m_jointPointLoopRows.clear();
m_jointPointExecutionWaits.clear();
m_jointPointExecutionNodeIds.clear();
const auto pointRow = [this](const QString &name) {
for (int row = 0; row < m_recordedJointPoints.size(); ++row) {
if (m_recordedJointPoints.at(row).name == name)
return row;
}
return -1;
};
QString flowError;
const QList<JointFlowEditor::ExecutionStep> steps =
m_jointFlowEditor->expandedSteps(&flowError);
if (!flowError.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("执行自定义流程"), flowError);
return;
}
for (const JointFlowEditor::ExecutionStep &step : steps) {
const int row = pointRow(step.pointName);
if (row < 0) {
QMessageBox::warning(this, QStringLiteral("执行自定义流程"),
QStringLiteral("流程引用的点位“%1”已不存在。").arg(step.pointName));
m_jointPointLoopRows.clear();
m_jointPointExecutionWaits.clear();
m_jointPointExecutionNodeIds.clear();
return;
}
m_jointPointLoopRows.append(row);
m_jointPointExecutionWaits.append(step.intervalSeconds);
m_jointPointExecutionNodeIds.append(step.nodeId);
}
if (m_jointPointLoopRows.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("执行自定义流程"),
QStringLiteral("流程引用的点位已不存在。"));
return;
}
m_jointPointLoopCursor = 0;
m_jointPointLoopTarget = m_jointPointLoopRows.size();
m_jointPointLoopActive = true;
m_startJointPointLoopButton->setEnabled(false);
m_runJointPointButton->setEnabled(false);
m_deleteJointPointButton->setEnabled(false);
m_recordJointPointButton->setEnabled(false);
m_stopJointPointLoopButton->setEnabled(true);
m_jointPointTable->setEnabled(false);
advanceJointPointLoop();
}
void MainWindow::advanceJointPointLoop()
{
if (!m_jointPointLoopActive || m_jointPointMovePending)
return;
if (m_jointPointLoopCursor >= m_jointPointLoopRows.size()) {
stopJointPointLoop(QStringLiteral("循环执行完成"));
return;
}
const int executionIndex = m_jointPointLoopCursor;
const int row = m_jointPointLoopRows.at(m_jointPointLoopCursor++);
if (row < 0 || row >= m_recordedJointPoints.size()) {
stopJointPointLoop(QStringLiteral("点位列表已发生变化"));
return;
}
const RecordedJointPoint &point = m_recordedJointPoints.at(row);
if (m_jointFlowEditor && executionIndex < m_jointPointExecutionNodeIds.size())
m_jointFlowEditor->setActiveNode(m_jointPointExecutionNodeIds.at(executionIndex));
QVariantList positions;
for (double position : point.positions)
positions.append(position);
m_jointPointMovePending = true;
m_jointPointLoopStatus->setText(QStringLiteral("步骤 %1/%2 · %3")
.arg(executionIndex + 1).arg(m_jointPointLoopRows.size()).arg(point.name));
m_client->requestMoveJ(point.deviceId, positions,
m_velocitySpin->value(), m_accelerationSpin->value());
}
void MainWindow::stopJointPointLoop(const QString &reason)
{
const bool wasActive = m_jointPointLoopActive;
m_jointPointLoopActive = false;
m_jointPointMovePending = false;
m_jointPointLoopRows.clear();
m_jointPointExecutionWaits.clear();
m_jointPointExecutionNodeIds.clear();
if (m_jointFlowEditor)
m_jointFlowEditor->setActiveNode(QString());
if (m_startJointPointLoopButton)
m_startJointPointLoopButton->setEnabled(true);
if (m_runJointPointButton)
m_runJointPointButton->setEnabled(true);
if (m_deleteJointPointButton)
m_deleteJointPointButton->setEnabled(true);
if (m_recordJointPointButton)
m_recordJointPointButton->setEnabled(true);
if (m_stopJointPointLoopButton)
m_stopJointPointLoopButton->setEnabled(false);
if (m_jointPointTable)
m_jointPointTable->setEnabled(true);
if (m_jointPointLoopStatus)
m_jointPointLoopStatus->setText(reason.isEmpty() ? QStringLiteral("未运行") : reason);
if (wasActive && !reason.isEmpty())
appendLog(reason == QStringLiteral("循环执行完成") ? QStringLiteral("OK")
: QStringLiteral("WARN"),
reason);
}
void MainWindow::sendMoveJPose()
{
if (m_moveJPoseSpins.size() != 6 || !m_moveJPoseBaseLinkCombo)
return;
QVariantMap pose;
static const QStringList keys = {
QStringLiteral("x"), QStringLiteral("y"), QStringLiteral("z"),
QStringLiteral("rx"), QStringLiteral("ry"), QStringLiteral("rz")
};
for (int i = 0; i < keys.size(); ++i)
pose.insert(keys.at(i), m_moveJPoseSpins.at(i)->value());
m_client->requestMoveJPose(m_armIdEdit->text().trimmed(), pose,
m_armDefaultBaseFrame,
m_armDefaultTcpFrame,
m_velocitySpin->value(), m_accelerationSpin->value());
}
void MainWindow::saveSnapshot()
{
QImage image = m_cameraStreaming && m_videoRender
? m_videoRender->grabFramebuffer() : m_lastImage;
if (image.isNull())
return;
const QString defaultName = QStringLiteral("cmvr_rgb_%1.png")
.arg(QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss"));
const QString path = QFileDialog::getSaveFileName(this, QStringLiteral("保存 RGB 图像"),
defaultName, QStringLiteral("PNG 图像 (*.png);;JPEG 图像 (*.jpg)"));
if (path.isEmpty())
return;
const bool saved = image.save(path);
appendLog(saved ? QStringLiteral("OK") : QStringLiteral("ERROR"),
saved ? QStringLiteral("图像已保存:%1").arg(path)
: QStringLiteral("图像保存失败:%1").arg(path));
}
void MainWindow::loadSettings()
{
QSettings settings;
loadJointPrograms(settings);
m_hostEdit->setText(settings.value(QStringLiteral("connection/host"), QStringLiteral("192.168.0.28")).toString());
m_hostEdit->setCursorPosition(0);
m_portSpin->setValue(settings.value(QStringLiteral("connection/port"), 50052).toInt());
m_demoCheck->setChecked(settings.value(QStringLiteral("connection/demo"), true).toBool());
m_systemTargetEdit->setText(settings.value(QStringLiteral("system/target"), QStringLiteral("*")).toString());
const QString armSide = settings.value(QStringLiteral("arm/side"),
QStringLiteral("right")).toString();
if (m_armSideCombo) {
const int sideIndex = m_armSideCombo->findData(armSide);
if (sideIndex >= 0)
m_armSideCombo->setCurrentIndex(sideIndex);
}
const QString defaultArmDeviceId = armSide == QStringLiteral("left")
? QStringLiteral("left_ethercat_arm") : QStringLiteral("right_ethercat_arm");
QString armDeviceId = settings.value(QStringLiteral("arm/device"),
defaultArmDeviceId).toString().trimmed();
if (armDeviceId == QStringLiteral("left_arm") ||
armDeviceId == QStringLiteral("eyou_left_arm")) {
armDeviceId = QStringLiteral("left_ethercat_arm");
} else if (armDeviceId == QStringLiteral("right_arm") ||
armDeviceId == QStringLiteral("eyou_arm") ||
armDeviceId == QStringLiteral("eyou_right_arm")) {
armDeviceId = QStringLiteral("right_ethercat_arm");
}
m_armIdEdit->setText(armDeviceId);
if (m_armSideCombo && !armDeviceId.isEmpty())
m_armSideCombo->addItem(armDeviceId, armDeviceId);
const QString cameraDeviceId = settings.value(QStringLiteral("camera/device"), QString()).toString().trimmed();
if (m_cameraDeviceCombo && !cameraDeviceId.isEmpty())
m_cameraDeviceCombo->addItem(cameraDeviceId, cameraDeviceId);
rebuildCameraPreviewGrid(configuredCameraIds());
m_cameraRecordPathEdit->setText(settings.value(
QStringLiteral("camera/recordPath"),
QStringLiteral("/mnt/data/cmvr/record/camera.mp4")).toString());
const QString cameraCodec = settings.value(QStringLiteral("camera/codec"),
QStringLiteral("h264")).toString().toLower();
m_cameraCodecCombo->setCurrentIndex(
cameraCodec == QStringLiteral("h265") || cameraCodec == QStringLiteral("hevc") ? 1 : 0);
if (m_cameraStreamModeCombo) {
const QString cameraMode = settings.value(QStringLiteral("camera/streamMode"),
QStringLiteral("rgb")).toString().toLower();
const int modeIndex = m_cameraStreamModeCombo->findData(cameraMode);
if (modeIndex >= 0)
m_cameraStreamModeCombo->setCurrentIndex(modeIndex);
}
m_agvIdEdit->setText(settings.value(QStringLiteral("agv/device"), QStringLiteral("agv")).toString());
if (m_agvMapRefreshCombo) {
const int intervalMs = settings.value(
QStringLiteral("agv/mapRefreshIntervalMs"), 0).toInt();
const int index = m_agvMapRefreshCombo->findData(intervalMs);
m_agvMapRefreshCombo->setCurrentIndex(index >= 0 ? index : 0);
}
m_velocitySpin->setValue(settings.value(
QStringLiteral("motion/speedJVelocity"),
settings.value(QStringLiteral("motion/velocity"), 1.0)).toDouble());
m_accelerationSpin->setValue(settings.value(
QStringLiteral("motion/speedJAcceleration"),
settings.value(QStringLiteral("motion/acceleration"), 0.5)).toDouble());
if (m_cartesianVelocitySpin)
m_cartesianVelocitySpin->setValue(settings.value(
QStringLiteral("motion/speedLVelocity"), 0.25).toDouble());
if (m_cartesianAccelerationSpin)
m_cartesianAccelerationSpin->setValue(settings.value(
QStringLiteral("motion/speedLAcceleration"), 0.5).toDouble());
const QDir applicationDirectory(QCoreApplication::applicationDirPath());
const QString defaultUrdf = applicationDirectory.filePath(QStringLiteral("models/demo_arm.urdf"));
QString configuredUrdf = settings.value(QStringLiteral("arm/urdf"), defaultUrdf)
.toString().trimmed();
if (!configuredUrdf.isEmpty() && QFileInfo(configuredUrdf).isRelative())
configuredUrdf = applicationDirectory.absoluteFilePath(configuredUrdf);
m_pendingUrdfPath = QFileInfo::exists(configuredUrdf)
? QFileInfo(configuredUrdf).absoluteFilePath()
: (QFileInfo::exists(defaultUrdf) ? QFileInfo(defaultUrdf).absoluteFilePath()
: QString());
m_quicBindEdit->setText(settings.value(QStringLiteral("quic/bindAddress"),
QStringLiteral("127.0.0.1")).toString());
m_quicPortSpin->setValue(settings.value(QStringLiteral("quic/port"), 4433).toInt());
m_quicAlpnEdit->setText(settings.value(QStringLiteral("quic/alpn"),
QStringLiteral("cmvr-quic-edge/1")).toString());
const QDir applicationDir(QCoreApplication::applicationDirPath());
const QString defaultCertificate = applicationDir.filePath(
QStringLiteral("quic-test-server.pfx"));
QString certificatePath = settings.value(
QStringLiteral("quic/certificate"),
QStringLiteral("quic-test-server.pfx")).toString().trimmed();
if (QFileInfo(certificatePath).isRelative())
certificatePath = applicationDir.filePath(certificatePath);
if (!QFileInfo(certificatePath).isFile()) {
certificatePath = defaultCertificate;
settings.setValue(QStringLiteral("quic/certificate"),
QStringLiteral("quic-test-server.pfx"));
}
m_quicCertificateEdit->setText(QDir::toNativeSeparators(certificatePath));
m_quicPasswordEdit->setText(QStringLiteral("cmvr-test"));
m_endpointValue->setText(endpoint());
if (m_sidebarEndpointValue)
m_sidebarEndpointValue->setText(endpoint());
}
void MainWindow::saveSettings()
{
QSettings settings;
saveJointPrograms(settings);
settings.setValue(QStringLiteral("connection/host"), m_hostEdit->text().trimmed());
settings.setValue(QStringLiteral("connection/port"), m_portSpin->value());
settings.setValue(QStringLiteral("connection/demo"), m_demoCheck->isChecked());
settings.setValue(QStringLiteral("system/target"), m_systemTargetEdit->text().trimmed());
settings.setValue(QStringLiteral("arm/device"), m_armIdEdit->text().trimmed());
settings.setValue(QStringLiteral("camera/device"),
configuredCameraIds().value(0));
settings.setValue(QStringLiteral("camera/recordPath"),
m_cameraRecordPathEdit->text().trimmed());
settings.setValue(QStringLiteral("camera/codec"),
m_cameraCodecCombo->currentIndex() == 1
? QStringLiteral("h265") : QStringLiteral("h264"));
if (m_cameraStreamModeCombo)
settings.setValue(QStringLiteral("camera/streamMode"),
m_cameraStreamModeCombo->currentData().toString());
settings.setValue(QStringLiteral("agv/device"), m_agvIdEdit->text().trimmed());
if (m_agvMapRefreshCombo)
settings.setValue(QStringLiteral("agv/mapRefreshIntervalMs"),
m_agvMapRefreshCombo->currentData().toInt());
settings.setValue(QStringLiteral("motion/speedJVelocity"), m_velocitySpin->value());
settings.setValue(QStringLiteral("motion/speedJAcceleration"),
m_accelerationSpin->value());
if (m_cartesianVelocitySpin)
settings.setValue(QStringLiteral("motion/speedLVelocity"),
m_cartesianVelocitySpin->value());
if (m_cartesianAccelerationSpin)
settings.setValue(QStringLiteral("motion/speedLAcceleration"),
m_cartesianAccelerationSpin->value());
if (m_urdfViewer && !m_urdfViewer->currentFile().isEmpty())
settings.setValue(QStringLiteral("arm/urdf"), m_urdfViewer->currentFile());
else if (!m_pendingUrdfPath.isEmpty())
settings.setValue(QStringLiteral("arm/urdf"), m_pendingUrdfPath);
settings.setValue(QStringLiteral("quic/bindAddress"), m_quicBindEdit->text().trimmed());
settings.setValue(QStringLiteral("quic/port"), m_quicPortSpin->value());
settings.setValue(QStringLiteral("quic/alpn"), m_quicAlpnEdit->text().trimmed());
const QString certificatePath = QDir::fromNativeSeparators(
m_quicCertificateEdit->text().trimmed());
const QString bundledCertificate = QDir(QCoreApplication::applicationDirPath())
.filePath(QStringLiteral("quic-test-server.pfx"));
settings.setValue(
QStringLiteral("quic/certificate"),
QFileInfo(certificatePath).absoluteFilePath() ==
QFileInfo(bundledCertificate).absoluteFilePath()
? QStringLiteral("quic-test-server.pfx")
: certificatePath);
}
void MainWindow::loadJointPrograms(QSettings &settings)
{
m_recordedJointPoints.clear();
const int pointCount = settings.beginReadArray(QStringLiteral("arm/jointPoints"));
for (int i = 0; i < pointCount; ++i) {
settings.setArrayIndex(i);
RecordedJointPoint point;
point.name = settings.value(QStringLiteral("name")).toString();
point.side = settings.value(QStringLiteral("side")).toString();
point.deviceId = settings.value(QStringLiteral("deviceId")).toString();
point.jointNames = settings.value(QStringLiteral("jointNames")).toStringList();
const QVariantList storedPositions = settings.value(QStringLiteral("positions")).toList();
for (const QVariant &value : storedPositions)
point.positions.append(value.toDouble());
if (!point.name.isEmpty() && point.jointNames.size() == point.positions.size())
m_recordedJointPoints.append(point);
}
settings.endArray();
if (m_jointFlowEditor) {
m_jointFlowEditor->clear();
const QByteArray flowJson = settings.value(QStringLiteral("arm/jointFlowGraph")).toByteArray();
const QJsonDocument document = QJsonDocument::fromJson(flowJson);
if (document.isArray()) {
m_jointFlowEditor->fromJson(document.array());
} else {
struct LegacyStep { QString point; double wait = 1.0; QString group; int count = 1; };
QList<LegacyStep> legacy;
const int flowCount = settings.beginReadArray(QStringLiteral("arm/jointFlow"));
for (int i = 0; i < flowCount; ++i) {
settings.setArrayIndex(i);
LegacyStep step;
step.point = settings.value(QStringLiteral("pointName")).toString();
step.wait = settings.value(QStringLiteral("waitSeconds"), 1.0).toDouble();
step.group = settings.value(QStringLiteral("loopGroup")).toString();
step.count = qMax(1, settings.value(QStringLiteral("loopCount"), 1).toInt());
if (!step.point.isEmpty()) legacy.append(step);
}
settings.endArray();
for (int i = 0; i < legacy.size();) {
if (legacy.at(i).group.isEmpty()) {
m_jointFlowEditor->addSingleNode(legacy.at(i).point,
legacy.at(i).point,
legacy.at(i).wait);
++i;
continue;
}
int end = i + 1;
while (end < legacy.size() && legacy.at(end).group == legacy.at(i).group) ++end;
for (int repeat = 0; repeat < legacy.at(i).count; ++repeat)
for (int index = i; index < end; ++index)
m_jointFlowEditor->addSingleNode(legacy.at(index).point,
legacy.at(index).point,
legacy.at(index).wait);
i = end;
}
}
}
refreshRecordedJointPoints();
refreshJointFlowTable();
}
void MainWindow::saveJointPrograms(QSettings &settings) const
{
settings.remove(QStringLiteral("arm/jointPoints"));
settings.beginWriteArray(QStringLiteral("arm/jointPoints"));
for (int i = 0; i < m_recordedJointPoints.size(); ++i) {
settings.setArrayIndex(i);
const RecordedJointPoint &point = m_recordedJointPoints.at(i);
QVariantList positions;
for (double value : point.positions)
positions.append(value);
settings.setValue(QStringLiteral("name"), point.name);
settings.setValue(QStringLiteral("side"), point.side);
settings.setValue(QStringLiteral("deviceId"), point.deviceId);
settings.setValue(QStringLiteral("jointNames"), point.jointNames);
settings.setValue(QStringLiteral("positions"), positions);
}
settings.endArray();
if (m_jointFlowEditor) {
settings.setValue(QStringLiteral("arm/jointFlowGraph"),
QJsonDocument(m_jointFlowEditor->toJson()).toJson(QJsonDocument::Compact));
settings.remove(QStringLiteral("arm/jointFlow"));
}
}
void MainWindow::setControlsEnabled(bool enabled)
{
for (QPushButton *button : m_serviceButtons) {
if (button)
button->setEnabled(enabled);
}
for (QDoubleSpinBox *spin : m_targetSpins)
spin->setEnabled(enabled);
for (QDoubleSpinBox *spin : m_moveJPoseSpins)
spin->setEnabled(enabled);
if (m_moveJPoseBaseLinkCombo)
m_moveJPoseBaseLinkCombo->setEnabled(enabled);
if (m_velocitySpin)
m_velocitySpin->setEnabled(enabled);
if (m_accelerationSpin)
m_accelerationSpin->setEnabled(enabled);
if (m_cartesianVelocitySpin)
m_cartesianVelocitySpin->setEnabled(enabled);
if (m_cartesianAccelerationSpin)
m_cartesianAccelerationSpin->setEnabled(enabled);
if (m_calibrateZeroButton)
m_calibrateZeroButton->setEnabled(enabled && m_zeroJointCombo
&& m_zeroJointCombo->count() > 0);
if (m_teachSendButton)
m_teachSendButton->setEnabled(enabled && m_teachModeButton
&& m_teachModeButton->isChecked());
if (m_speakerStreamStartButton)
m_speakerStreamStartButton->setEnabled(enabled);
if (m_speakerStreamStopButton)
m_speakerStreamStopButton->setEnabled(false);
if (m_microphoneStreamStartButton)
m_microphoneStreamStartButton->setEnabled(enabled);
if (m_microphoneStreamStopButton)
m_microphoneStreamStopButton->setEnabled(false);
if (m_agvDeleteMapButton)
m_agvDeleteMapButton->setEnabled(false);
}
QString MainWindow::endpoint() const
{
return QStringLiteral("%1:%2").arg(m_hostEdit->text().trimmed()).arg(m_portSpin->value());
}