CmvrControlStation/src/mainwindow.cpp

1881 lines
86 KiB
C++
Raw Normal View History

2026-09-18 16:22:20 +08:00
#include "mainwindow.h"
#include "videorenderwidget.h"
#include "audiostreammanager.h"
#include "configeditorwidget.h"
#include "robotclient.h"
#include "quictestserver.h"
#include "rpcservicewidget.h"
2026-09-18 16:22:20 +08:00
#include "trendwidget.h"
#include "uiicons.h"
#include "urdfviewerwidget.h"
#include "ui_mainwindow.h"
#include <QButtonGroup>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QCursor>
#include <QDateTime>
#include <QDoubleSpinBox>
#include <QDir>
#include <QEvent>
#include <QFileDialog>
#include <QFileInfo>
#include <QFrame>
2026-09-18 16:22:20 +08:00
#include <QHeaderView>
#include <QHBoxLayout>
#include <QImage>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include <QMessageBox>
#include <QPainter>
#include <QPixmap>
#include <QProgressBar>
#include <QPushButton>
#include <QResizeEvent>
#include <QScrollArea>
2026-09-18 16:22:20 +08:00
#include <QSettings>
#include <QSpinBox>
#include <QStackedWidget>
#include <QStyle>
#include <QTableWidget>
#include <QTextEdit>
#include <QTimer>
#include <QVBoxLayout>
2026-09-18 16:22:20 +08:00
#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("手眼标定")
2026-09-18 16:22:20 +08:00
};
const QStringList kPageSubtitles = {
QStringLiteral("系统信息、运行资源与全局停止"),
QStringLiteral("设备服务 / ArmService"),
QStringLiteral("相机状态、图像采集与预览"),
QStringLiteral("底盘状态、导航、速度与地图操作"),
QStringLiteral("扬声器状态、音频播放、流式音频与音量控制"),
QStringLiteral("麦克风状态、录音、音频流与音量控制"),
QStringLiteral("灵巧手状态、位置、角度、力、速度与传感器"),
QStringLiteral("仿生头状态、表情、说话动作与紧急停止"),
QStringLiteral("触控坐标与最大作用力控制"),
QStringLiteral("测试服务原始请求与反馈"),
QStringLiteral("监听 edge 接入、注册、心跳与媒体数据报"),
QStringLiteral("设备清单以及 cmvr_es 项目配置的查看、校验与编辑"),
QStringLiteral("检查连接信息与 RPC 执行记录"),
QStringLiteral("机械臂工具中心点与工具坐标系标定入口"),
QStringLiteral("相机与机械臂坐标系的手眼标定入口")
2026-09-18 16:22:20 +08:00
};
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;
}
2026-09-18 16:22:20 +08:00
}
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
2026-09-18 16:22:20 +08:00
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
2026-09-18 16:22:20 +08:00
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
2026-09-18 16:22:20 +08:00
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);
2026-09-18 16:22:20 +08:00
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
2026-09-18 16:22:20 +08:00
};
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")
2026-09-18 16:22:20 +08:00
};
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();
});
2026-09-18 16:22:20 +08:00
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(createRpcPage(QStringLiteral("cmvr.api.DexHandService")));
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_cameraIdEdit) m_cameraIdEdit->setText(deviceId);
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 3:
pageIndex = 6;
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);
});
2026-09-18 16:22:20 +08:00
m_pages->addWidget(createDiagnosticsPage());
m_pages->addWidget(createCalibrationEntryPage(
QStringLiteral("工具坐标标定"),
QStringLiteral("用于建立工具中心点(TCP)及其相对于机械臂末端的坐标变换。"),
m_pages));
m_pages->addWidget(createCalibrationEntryPage(
QStringLiteral("手眼标定"),
QStringLiteral("用于求解相机坐标系与机械臂基座或末端坐标系之间的变换关系。"),
m_pages));
2026-09-18 16:22:20 +08:00
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);
2026-09-18 16:22:20 +08:00
connect(m_client, &RobotClient::telemetryReceived, this, &MainWindow::updateTelemetry);
connect(m_client, &RobotClient::armTelemetryHealthChanged,
this, &MainWindow::updateArmTelemetryHealth);
2026-09-18 16:22:20 +08:00
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::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 QString &detail) {
m_agvMappingPreview->setText(QString());
m_agvMappingPreview->setPixmap(QPixmap::fromImage(image).scaled(
m_agvMappingPreview->size(), Qt::KeepAspectRatio,
Qt::SmoothTransformation));
m_agvMappingStateLabel->setText(detail);
});
connect(m_client, &RobotClient::agvMapStreamStateChanged, this,
[this](bool running, const QString &detail) {
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);
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()
{
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);
}
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::selectPage(int index)
{
if (!m_pages || index < 0 || index >= kPageTitles.size())
return;
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 != 3 && m_agvStatusSwitch && m_agvStatusSwitch->isChecked())
m_agvStatusSwitch->setChecked(false);
if (index < m_navButtons.size())
m_navButtons.at(index)->setChecked(true);
}
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);
}
2026-09-18 16:22:20 +08:00
setControlsEnabled(connected);
if (m_agvStatusRefreshTimer && m_agvStatusSwitch
&& m_agvStatusSwitch->isChecked()) {
if (connected) {
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
m_agvStatusRefreshTimer->start();
} else {
m_agvStatusRefreshTimer->stop();
}
}
if (!connected) {
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) {
m_armTelemetryButton->setChecked(false);
m_armTelemetryButton->setText(QStringLiteral("遥测 未启动"));
m_armTelemetryButton->setProperty("active", false);
m_armTelemetryButton->style()->unpolish(m_armTelemetryButton);
m_armTelemetryButton->style()->polish(m_armTelemetryButton);
if (m_armSideCombo)
m_armSideCombo->setEnabled(true);
2026-09-18 16:22:20 +08:00
}
if (!connected) {
m_armAlertStates.clear();
2026-09-18 16:22:20 +08:00
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)
2026-09-18 16:22:20 +08:00
{
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;
2026-09-18 16:22:20 +08:00
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());
}
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);
}
2026-09-18 16:22:20 +08:00
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();
2026-09-18 16:22:20 +08:00
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;
2026-09-18 16:22:20 +08:00
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 未提供有效关节限位"));
}
}
2026-09-18 16:22:20 +08:00
if (row == 0 && m_trend)
m_trend->appendSample(position, velocity);
}
m_lastArmTelemetryMs = nowMs;
2026-09-18 16:22:20 +08:00
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());
}
2026-09-18 16:22:20 +08:00
}
if (m_armAlertStates.value(deviceId).isEmpty()
&& m_bottomLogLevel && m_bottomLogMessage) {
2026-09-18 16:22:20 +08:00
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)
2026-09-18 16:22:20 +08:00
{
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()));
if (!m_armSideCombo)
return;
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);
}
2026-09-18 16:22:20 +08:00
}
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::updateAgvState(const QVariantMap &state, const QVariantMap &navigation)
{
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));
m_agvBatteryValue->setText(QStringLiteral("%1%").arg(
state.value(QStringLiteral("battery")).toDouble() * 100.0, 0, 'f', 0));
m_agvNavigationValue->setText(navigation.value(QStringLiteral("message"), QStringLiteral("--")).toString());
m_agvErrorValue->setText(state.value(QStringLiteral("error"), QStringLiteral("无")).toString());
m_agvModeValue->setText(QStringLiteral("模式 %1").arg(
state.value(QStringLiteral("mode")).toInt()));
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("未急停")));
m_agvPowerValue->setText(QStringLiteral("%1 V / %2 A / %3 °C")
.arg(state.value(QStringLiteral("voltage")).toDouble(), 0, 'f', 2)
.arg(state.value(QStringLiteral("current")).toDouble(), 0, 'f', 2)
.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));
}
void MainWindow::updateAgvInventory(const QStringList &maps, const QVariantList &stations)
{
const QString selectedMap = m_agvMapCombo->currentText();
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_cameraIdEdit->setEnabled(!m_cameraStreaming && !recording);
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 && m_agvStatusSwitch
&& (command == QStringLiteral("AGV NavigateToPose")
|| command == QStringLiteral("AGV NavigateToStation")
|| command == QStringLiteral("AGV FollowPath"))) {
m_agvStatusSwitch->setChecked(true);
}
appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"),
QStringLiteral("%1 · %2").arg(command, detail));
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;
for (QDoubleSpinBox *spin : m_targetSpins)
positions.append(qDegreesToRadians(spin->value()));
2026-09-18 16:22:20 +08:00
m_client->requestMoveJ(m_armIdEdit->text().trimmed(), positions,
m_velocitySpin->value(), m_accelerationSpin->value());
}
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,
2026-09-18 16:22:20 +08:00
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;
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());
QString armDeviceId = settings.value(QStringLiteral("arm/device"),
QStringLiteral("demo_arm")).toString().trimmed();
2026-09-18 16:22:20 +08:00
m_armIdEdit->setText(armDeviceId);
if (m_armSideCombo && !armDeviceId.isEmpty())
m_armSideCombo->addItem(armDeviceId, armDeviceId);
2026-09-18 16:22:20 +08:00
m_cameraIdEdit->setText(settings.value(QStringLiteral("camera/device"), QStringLiteral("camera")).toString());
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());
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());
2026-09-18 16:22:20 +08:00
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;
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"), m_cameraIdEdit->text().trimmed());
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());
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());
2026-09-18 16:22:20 +08:00
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::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);
2026-09-18 16:22:20 +08:00
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);
}
QString MainWindow::endpoint() const
{
return QStringLiteral("%1:%2").arg(m_hostEdit->text().trimmed()).arg(m_portSpin->value());
}