CmvrControlStation/src/mainwindow.cpp

3956 lines
192 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 "applicationsettings.h"
#include "applicationstyle.h"
#include "tactileheatmapwidget.h"
#include "jointfloweditor.h"
#include "taskorchestrationwidget.h"
#include "bioheadoperations.h"
#include "bioheadwidget.h"
#include "motordebugwidget.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 "tcpcalibrationwidget.h"
#include "tcpjogcontroller.h"
#include "../ui/handeyecalibrationwidget.h"
#include "handeyemotionwidget.h"
#include "touchoperationwidget.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 <QDialog>
#include <QDialogButtonBox>
#include <QListWidget>
#include <QEvent>
#include <QFileDialog>
#include <QFile>
#include <QFileInfo>
#include <QFrame>
#include <QHeaderView>
#include <QHBoxLayout>
#include <QImage>
#include <QKeyEvent>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include "appmessagebox.h"
#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QProgressBar>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QResizeEvent>
#include <QStandardItemModel>
#include <QScrollArea>
#include <QSettings>
#include <QScrollBar>
#include <QTextDocument>
#include <QSaveFile>
#include <QScopedValueRollback>
#include <QSignalBlocker>
#include <QSpinBox>
#include <QStackedWidget>
#include <QStandardPaths>
#include <QStyle>
#include <QTableWidget>
#include <QTextEdit>
#include <QTimer>
#include <QVBoxLayout>
#include <QtMath>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
namespace {
class TaskMediaDialog final : public QDialog
{
public:
TaskMediaDialog(const QString &title, QWidget *parent)
: QDialog(parent, Qt::Window | Qt::FramelessWindowHint)
{
setAttribute(Qt::WA_TranslucentBackground);
setObjectName(QStringLiteral("jointFlowChildDialog"));
resize(900, 650);
setMinimumSize(560, 420);
auto *outer = new QVBoxLayout(this);
outer->setContentsMargins(12, 12, 12, 12);
outer->setSpacing(0);
auto *surface = new QFrame(this);
surface->setObjectName(QStringLiteral("jointFlowChildSurface"));
auto *surfaceLayout = new QVBoxLayout(surface);
surfaceLayout->setContentsMargins(0, 0, 0, 0);
surfaceLayout->setSpacing(0);
m_titleBar = new QWidget(surface);
m_titleBar->setObjectName(QStringLiteral("jointFlowChildTitleBar"));
m_titleBar->setFixedHeight(44);
auto *titleLayout = new QHBoxLayout(m_titleBar);
titleLayout->setContentsMargins(12, 0, 0, 0);
titleLayout->setSpacing(9);
auto *mark = new QLabel(QStringLiteral("C"), m_titleBar);
mark->setObjectName(QStringLiteral("jointFlowDialogMark"));
mark->setAlignment(Qt::AlignCenter);
mark->setFixedSize(24, 24);
auto *titleLabel = new QLabel(title, m_titleBar);
titleLabel->setObjectName(QStringLiteral("jointFlowDialogTitle"));
auto *closeButton = new QPushButton(m_titleBar);
closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton"));
closeButton->setFixedSize(46, 43);
closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"),
QColor("#4f5964"), QColor("#4f5964")));
titleLayout->addWidget(mark);
titleLayout->addWidget(titleLabel);
titleLayout->addStretch();
titleLayout->addWidget(closeButton);
surfaceLayout->addWidget(m_titleBar);
m_content = new QWidget(surface);
m_content->setObjectName(QStringLiteral("jointFlowChildContent"));
m_layout = new QVBoxLayout(m_content);
m_layout->setContentsMargins(16, 16, 16, 16);
m_layout->setSpacing(10);
surfaceLayout->addWidget(m_content, 1);
outer->addWidget(surface);
m_titleBar->installEventFilter(this);
titleLabel->installEventFilter(this);
mark->installEventFilter(this);
connect(closeButton, &QPushButton::clicked, this, &QWidget::hide);
}
QVBoxLayout *contentLayout() const { return m_layout; }
protected:
bool eventFilter(QObject *watched, QEvent *event) override
{
if ((watched == m_titleBar || (watched && watched->parent() == m_titleBar)) && event) {
if (event->type() == QEvent::MouseButtonPress) {
auto *mouse = static_cast<QMouseEvent *>(event);
if (mouse->button() == Qt::LeftButton) {
m_dragging = true;
m_offset = mouse->globalPos() - frameGeometry().topLeft();
return true;
}
} else if (event->type() == QEvent::MouseMove && m_dragging) {
move(static_cast<QMouseEvent *>(event)->globalPos() - m_offset);
return true;
} else if (event->type() == QEvent::MouseButtonRelease) {
m_dragging = false;
}
}
return QDialog::eventFilter(watched, event);
}
private:
QWidget *m_titleBar = nullptr;
QWidget *m_content = nullptr;
QVBoxLayout *m_layout = nullptr;
QPoint m_offset;
bool m_dragging = false;
};
bool pageUsesArmTelemetry(int index)
{
return index == 1 || index == 13 || index == 14 || index == 15;
}
const QStringList kPageTitles = {
QStringLiteral("系统概览"), QStringLiteral("机械臂"),
QStringLiteral("相机"), QStringLiteral("AGV"),
QStringLiteral("扬声器"), QStringLiteral("麦克风"),
QStringLiteral("灵巧手"), QStringLiteral("仿生头"),
QStringLiteral("HLC 控制"), QStringLiteral("接口调试"),
QStringLiteral("QUIC Server"), QStringLiteral("设备管理"),
QStringLiteral("运行日志"), QStringLiteral("工具坐标标定"),
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("相机与机械臂坐标系的手眼标定入口"),
QStringLiteral("视觉取点与触控笔单击、双击、滑动"),
QStringLiteral("跨设备任务、循环与执行等待编排"),
QStringLiteral("MotorManager / 单电机接口与位置、速度、加速度、力矩曲线")
};
}
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);
}
auto *motorNavButton=createPageButton(QStringLiteral("电机调试"),deviceContent,2);
deviceLayout->addWidget(motorNavButton);
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);
QPushButton *touchNavButton = createPageButton(
QStringLiteral("末端操作"), complexContent, 2);
QPushButton *taskOrchestrationNavButton = createPageButton(
QStringLiteral("任务编排"), grpcContent, 1);
ui.hlcNavButton->setParent(complexContent);
ui.hlcNavButton->setProperty("navLevel", 2);
complexLayout->addWidget(toolCalibrationNavButton);
complexLayout->addWidget(handEyeNavButton);
complexLayout->addWidget(touchNavButton);
complexLayout->addWidget(ui.hlcNavButton);
ui.configurationNavButton->setParent(grpcContent);
grpcLayout->addWidget(ui.configurationNavButton);
grpcLayout->addWidget(deviceContent);
grpcLayout->addWidget(taskOrchestrationNavButton);
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);
auto *settingsButton = new QPushButton(QStringLiteral("软件设置"), navTree);
settingsButton->setObjectName(QStringLiteral("navButton"));
settingsButton->setProperty("navLevel", 0);
settingsButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/settings.svg"),
QColor("#aab7c6"), QColor("#ffffff")));
settingsButton->setIconSize(QSize(18, 18));
settingsButton->setToolTip(QStringLiteral("外观、模型预览、启动与日志设置"));
navTreeLayout->addWidget(settingsButton);
connect(settingsButton, &QPushButton::clicked, this, [this]() {
showApplicationSettings(this, [this]() {
const auto &options = ApplicationSettings::instance().options();
if (m_logView) m_logView->document()->setMaximumBlockCount(options.logMaximumLines);
if (m_quicLogView) m_quicLogView->document()->setMaximumBlockCount(options.logMaximumLines);
appendLog(QStringLiteral("OK"), QStringLiteral("软件设置已保存;模型预览和启动设置在下次启动时生效"));
});
});
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, touchNavButton,
taskOrchestrationNavButton, motorNavButton
};
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"), QStringLiteral(":/icons/crosshair.svg"),
QStringLiteral(":/icons/braces.svg"), QStringLiteral(":/icons/activity.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());
auto *bioheadPage = new BioHeadWidget(m_client, m_pages);
connect(bioheadPage, &BioHeadWidget::statusMessage, this, &MainWindow::appendLog);
m_pages->addWidget(bioheadPage);
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);
if (auto *headPage = qobject_cast<BioHeadWidget *>(m_pages->widget(pageIndex)))
headPage->setDeviceId(deviceId);
selectPage(pageIndex);
});
m_pages->addWidget(createDiagnosticsPage());
// Fill the existing TCP navigation slot; keep page order and sidebar intact.
auto *tcpCalibration = new TcpCalibrationWidget(m_pages);
m_tcpCalibration = tcpCalibration;
m_tcpJog = new TcpJogController(this);
connect(m_tcpJog, &TcpJogController::captureRequested, m_client, &RobotClient::requestTcpCalibrationPose);
connect(m_client, &RobotClient::tcpCalibrationPoseReceived, m_tcpJog, &TcpJogController::acceptPose);
connect(m_tcpJog, &TcpJogController::moveRequested, m_client, &RobotClient::requestTcpJogMove);
connect(m_client, &RobotClient::commandFinished, m_tcpJog, &TcpJogController::acceptCommand);
connect(m_tcpJog, &TcpJogController::stopRequested, m_client, &RobotClient::requestArmStop);
connect(m_tcpJog, &TcpJogController::errorOccurred, this, [this](const QString &error) {
appendLog(QStringLiteral("ERROR"), error);
AppMessageBox::warning(this, QStringLiteral("TCP 点动"), error);
});
// A global/other stop must invalidate any pending local continuation too.
connect(m_client, &RobotClient::armStopRequested, m_tcpJog, &TcpJogController::stop);
connect(m_client, &RobotClient::systemStopAllRequested, m_tcpJog, &TcpJogController::stop);
connect(tcpCalibration, &TcpCalibrationWidget::referenceChanged, this, [this] {
m_tcpJog->setContext(endpoint(), m_armIdEdit->text().trimmed(),
m_tcpCalibration->referenceConfirmed(), m_tcpCalibration->activeOffset());
});
connect(m_client, &RobotClient::tcpReferenceInvalidated, tcpCalibration,
[this,tcpCalibration](const QString &device) {
if (device.trimmed().isEmpty() || device.trimmed() == m_armIdEdit->text().trimmed())
tcpCalibration->invalidateReference();
});
connect(tcpCalibration, &TcpCalibrationWidget::toolsChanged, this,
[this](const QString &host, const QString &device, const QString &name) {
if (host != endpoint() || device != m_armIdEdit->text().trimmed()) return;
m_tcpJog->stop();
refreshTcpChoices(name);
});
m_pages->addWidget(tcpCalibration);
connect(tcpCalibration, &TcpCalibrationWidget::captureRequested,
m_client, &RobotClient::requestTcpCalibrationPose);
connect(tcpCalibration, &TcpCalibrationWidget::controllerOffsetRequested,
m_client, &RobotClient::requestControllerTcpOffset);
connect(m_client, &RobotClient::controllerTcpOffsetReceived,
tcpCalibration, &TcpCalibrationWidget::acceptControllerOffset);
connect(m_client, &RobotClient::tcpCalibrationPoseReceived,
tcpCalibration, &TcpCalibrationWidget::acceptPose);
connect(tcpCalibration, &TcpCalibrationWidget::logMessage,
this, &MainWindow::appendLog);
const auto syncTcpContext = [this, tcpCalibration]() {
tcpCalibration->setContext(endpoint(), m_armIdEdit->text().trimmed(),
m_connected, m_demoCheck->isChecked());
refreshTcpChoices();
};
connect(m_armIdEdit, &QLineEdit::textChanged, tcpCalibration,
[syncTcpContext](const QString &) { syncTcpContext(); });
connect(m_hostEdit, &QLineEdit::textChanged, tcpCalibration,
[syncTcpContext](const QString &) { syncTcpContext(); });
connect(m_portSpin, QOverload<int>::of(&QSpinBox::valueChanged), tcpCalibration,
[syncTcpContext](int) { syncTcpContext(); });
connect(m_demoCheck, &QCheckBox::toggled, tcpCalibration,
[syncTcpContext](bool) { syncTcpContext(); });
connect(m_client, &RobotClient::connectionChanged, tcpCalibration,
[this, tcpCalibration](bool connected, int, const QString &) {
tcpCalibration->setContext(endpoint(), m_armIdEdit->text().trimmed(),
connected, m_demoCheck->isChecked());
if (!connected) {
m_controllerBaseFrames.clear();
m_controllerTcpFrames.clear();
}
refreshTcpChoices();
});
// Invalidate in-flight captures immediately, before the worker processes disconnect.
connect(m_client, &RobotClient::disconnectRequested, tcpCalibration,
[this, tcpCalibration]() {
tcpCalibration->setContext(endpoint(), m_armIdEdit->text().trimmed(),
false, m_demoCheck->isChecked());
});
syncTcpContext();
setupHandEye();
setupTouchOperation();
m_taskOrchestration = new TaskOrchestrationWidget(m_pages);
m_pages->addWidget(m_taskOrchestration);
auto *motorDebugPage=new MotorDebugWidget(m_client,m_pages);
m_pages->addWidget(motorDebugPage);
connect(motorDebugPage,&MotorDebugWidget::statusMessage,this,&MainWindow::appendLog);
connect(m_taskOrchestration, &TaskOrchestrationWidget::statusMessage,
this, &MainWindow::appendLog);
connect(m_taskOrchestration, &TaskOrchestrationWidget::taskRequested, this,
[this](const QString &deviceType, const QString &deviceId,
const QString &action, const QJsonObject &parameters) {
bool dispatched = false;
if (deviceType == QStringLiteral("机械臂")) {
if (action == QStringLiteral("MoveJ")) {
dispatched = true;
QVariantList positions;
for (const QJsonValue &value : parameters.value(QStringLiteral("positions")).toArray())
positions.append(value.toDouble());
m_client->requestMoveJ(deviceId, positions,
parameters.value(QStringLiteral("velocity")).toDouble(0.1),
parameters.value(QStringLiteral("acceleration")).toDouble(0.1));
} else if (action == QStringLiteral("使能")) {
dispatched = true;
m_client->requestTorque(deviceId, true);
} else if (action == QStringLiteral("去使能")) {
dispatched = true;
m_client->requestTorque(deviceId, false);
} else if (action == QStringLiteral("停止")) {
dispatched = true;
m_client->requestArmStop(deviceId);
} else if (action == QStringLiteral("清除故障")) {
dispatched = true;
m_client->requestArmClearFault(deviceId);
}
} else if (deviceType == QStringLiteral("相机")) {
if (action == QStringLiteral("RGB抓图")) {
dispatched = true;
m_taskSnapshotCameraId = deviceId;
showTaskCameraResult(deviceId, QStringLiteral("RGB 抓图"));
m_client->requestSnapshot(deviceId);
} else if (action == QStringLiteral("深度抓图")) {
dispatched = true;
m_taskSnapshotCameraId = deviceId;
showTaskCameraResult(deviceId, QStringLiteral("深度抓图"));
m_client->requestDepthSnapshot(deviceId);
} else if (action == QStringLiteral("开始预览")) {
dispatched = true;
showTaskCameraResult(deviceId, QStringLiteral("视频预览"));
const QString codec = m_cameraCodecById.value(deviceId);
if (codec.isEmpty()) {
m_pendingTaskCameraPreviews.insert(deviceId);
m_taskOrchestration->reportTaskFeedback(
deviceId, QStringLiteral("正在读取设备编码器配置"));
m_client->requestCameraStatus(deviceId);
} else {
m_client->startCameraStream(deviceId, codec, QStringLiteral("rgb"));
}
} else if (action == QStringLiteral("停止预览")) {
dispatched = true;
m_client->stopCameraStream(deviceId);
if (m_taskCameraResults.contains(deviceId))
m_taskCameraResults[deviceId].status->setText(QStringLiteral("正在停止预览…"));
} else if (action == QStringLiteral("开始录像")) {
dispatched = true;
m_taskCameraRecordingId = deviceId;
m_taskCameraRecordingAction = action;
m_client->startCameraRecording(
deviceId, parameters.value(QStringLiteral("path")).toString());
} else if (action == QStringLiteral("停止录像")) {
dispatched = true;
m_taskCameraRecordingId = deviceId;
m_taskCameraRecordingAction = action;
m_client->stopCameraRecording(deviceId);
}
} else if (deviceType == QStringLiteral("AGV")) {
if (action == QStringLiteral("导航站点")) {
dispatched = true;
m_client->requestAgvNavigateStation(deviceId,
parameters.value(QStringLiteral("stationId")).toString(),
parameters.value(QStringLiteral("maxSpeed")).toDouble(0.5));
} else if (action == QStringLiteral("停止")
|| action == QStringLiteral("暂停")
|| action == QStringLiteral("继续")) {
dispatched = true;
const QHash<QString, QString> commands = {
{QStringLiteral("停止"), QStringLiteral("stop")},
{QStringLiteral("暂停"), QStringLiteral("pause")},
{QStringLiteral("继续"), QStringLiteral("resume")}};
m_client->requestAgvAction(deviceId, commands.value(action));
}
} else if (deviceType == QStringLiteral("灵巧手")) {
const QHash<QString, QString> commands = {
{QStringLiteral("设置角度"), QStringLiteral("angle")},
{QStringLiteral("设置位置"), QStringLiteral("position")},
{QStringLiteral("设置速度"), QStringLiteral("speed")},
{QStringLiteral("设置力"), QStringLiteral("force")}};
if (commands.contains(action)) {
dispatched = true;
QVariantList values;
for (const QJsonValue &value : parameters.value(QStringLiteral("values")).toArray())
values.append(value.toDouble());
m_client->requestDexHandCommand(deviceId, commands.value(action), values);
}
} else if (deviceType == QStringLiteral("扬声器")) {
if (action == QStringLiteral("播放服务端文件")
|| action == QStringLiteral("停止文件播放")) {
dispatched = true;
QJsonObject header;
header.insert(QStringLiteral("deviceId"), deviceId);
QJsonObject request;
request.insert(QStringLiteral("header"), header);
const QString method = action == QStringLiteral("播放服务端文件")
? QStringLiteral("PlayAudio") : QStringLiteral("StopPlayback");
if (method == QStringLiteral("PlayAudio"))
request.insert(QStringLiteral("audioPath"),
parameters.value(QStringLiteral("path")).toString());
m_client->requestRpc(QStringLiteral("cmvr.api.SpeakerService"), method,
QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)),
deviceId);
} else if (action == QStringLiteral("本机麦克风流播放")) {
dispatched = true;
m_pendingTaskSpeakerCaptureId = deviceId;
m_pendingTaskSpeakerCaptureParameters = parameters;
m_taskOrchestration->reportTaskFeedback(
deviceId, QStringLiteral("正在建立扬声器音频流"));
m_client->startSpeakerAudioStream(deviceId);
} else if (action == QStringLiteral("开始音频流")) {
dispatched = true;
m_client->startSpeakerAudioStream(deviceId);
} else if (action == QStringLiteral("停止音频流")) {
dispatched = true;
m_audioManager->stopSource();
m_client->stopSpeakerAudioStream();
}
} else if (deviceType == QStringLiteral("麦克风")) {
if (action == QStringLiteral("开始录音")
|| action == QStringLiteral("停止录音")) {
dispatched = true;
QJsonObject header;
header.insert(QStringLiteral("deviceId"), deviceId);
QJsonObject request;
request.insert(QStringLiteral("header"), header);
const QString method = action == QStringLiteral("开始录音")
? QStringLiteral("StartRecord") : QStringLiteral("StopRecord");
if (method == QStringLiteral("StartRecord"))
request.insert(QStringLiteral("filePath"),
parameters.value(QStringLiteral("path")).toString());
m_client->requestRpc(QStringLiteral("cmvr.api.MicPhoneService"), method,
QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)),
deviceId);
} else if (action == QStringLiteral("开始音频流")) {
dispatched = true;
m_client->startMicrophoneAudioStream(deviceId);
} else if (action == QStringLiteral("停止音频流")) {
dispatched = true;
m_client->stopMicrophoneAudioStream();
}
} else if (deviceType == QStringLiteral("仿生头")) {
const QString method = BioHeadOperations::method(action);
if (!method.isEmpty()) {
dispatched = true;
const QJsonObject request{{QStringLiteral("header"),
QJsonObject{{QStringLiteral("deviceId"), deviceId}}}};
m_client->requestRpc(QStringLiteral("cmvr.api.BioHeadService"), method,
QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)),
deviceId);
}
} else if (deviceType == QStringLiteral("通用RPC")) {
dispatched = true;
m_client->requestRpc(parameters.value(QStringLiteral("service")).toString(),
parameters.value(QStringLiteral("method")).toString(),
QString::fromUtf8(QJsonDocument(parameters.value(QStringLiteral("request")).toObject())
.toJson(QJsonDocument::Compact)), deviceId);
}
if (!dispatched)
m_taskOrchestration->completeCurrentTask(
false, QStringLiteral("不支持的任务操作:%1 / %2").arg(deviceType, action));
});
connect(m_client, &RobotClient::rpcFinished, this,
[this](const QString &service, const QString &method,
bool success, const QString &detail) {
if (m_taskOrchestration)
m_taskOrchestration->completeRpcTask(service, method, success, detail);
});
connect(m_client,&RobotClient::cameraStreamStartRequested,this,
[this](const QString &camera,const QString &,const QString &mode) {
m_cameraStreamModes.insert(camera,mode);
if (configuredCameraIds().contains(camera) && m_cameraStreamModeCombo) {
const int index=m_cameraStreamModeCombo->findData(mode);
if (index>=0) {
const QSignalBlocker blocker(m_cameraStreamModeCombo);
m_cameraStreamModeCombo->setCurrentIndex(index);
}
}
});
const auto cancelJointFlow = [this](const QString &device) {
if ((!m_jointPointLoopActive && !m_jointPointMovePending) || m_jointPointDispatching) return;
bool affected=device.isEmpty() || device==QStringLiteral("*");
for (int row:m_jointPointLoopRows) {
if (row>=0 && row<m_recordedJointPoints.size())
for (const auto &t : m_recordedJointPoints.at(row).targets())
if (t.deviceId==device) affected=true;
}
if (m_jointPointMovingDevices.contains(device)) affected=true;
if (affected) { stopJointPointMotion(); stopJointPointLoop(QStringLiteral("流程已停止")); }
};
connect(m_client,&RobotClient::armStopRequested,this,cancelJointFlow);
connect(m_client,&RobotClient::systemStopAllRequested,this,cancelJointFlow);
connect(m_client,&RobotClient::armCommandStarting,this,cancelJointFlow);
connect(m_client,&RobotClient::tcpJogMoveRequested,this,
[cancelJointFlow](const QString &device,const QVariantMap &,double,double,quint64) { cancelJointFlow(device); });
connect(m_client,&RobotClient::disconnectRequested,this,
[this] { ++m_jointPointCaptureToken; m_jointPointCapturePending=false;
m_recordJointPointButton->setEnabled(true);
stopJointPointLoop(QStringLiteral("连接已断开")); });
connect(m_client, &RobotClient::jointPointMoveFinished, this, &MainWindow::finishJointPoint);
connect(m_client, &RobotClient::jointPointCaptured, this,
[this](quint64 token, const QVariantList &targets, bool success, const QString &detail) {
if (token != m_jointPointCaptureToken || !m_jointPointCapturePending) return;
m_jointPointCapturePending=false;
m_recordJointPointButton->setEnabled(!m_jointPointLoopActive);
if (m_activeJointProgramGroup != m_jointPointCaptureGroup) return;
RecordedJointPoint p;
p.name=m_jointPointCaptureName;
for (const auto &v : targets) {
auto t=JointPointTarget::fromJson(QJsonObject::fromVariantMap(v.toMap()));
t.side=t.deviceId.contains(QStringLiteral("left"),Qt::CaseInsensitive)
? QStringLiteral("left")
: t.deviceId.contains(QStringLiteral("right"),Qt::CaseInsensitive)
? QStringLiteral("right") : QString();
p.arms.append(t);
}
if (p.arms.size()==1) { static_cast<JointPointTarget &>(p)=p.arms.first(); p.arms.clear(); }
if (!success || !p.valid()) {
AppMessageBox::warning(m_jointFlowDialog, QStringLiteral("记录点位"),
detail.isEmpty() ? QStringLiteral("设备未返回完整有效的关节名称和角度,未保存点位。") : detail);
return;
}
for (const auto &existing : m_recordedJointPoints) if (existing.name.compare(p.name,Qt::CaseInsensitive)==0) return;
m_recordedJointPoints.append(p);
refreshRecordedJointPoints(); saveJointPrograms();
m_jointPointNameEdit->clear();
m_jointPointTable->selectRow(m_recordedJointPoints.size()-1);
appendLog(QStringLiteral("OK"),QStringLiteral("已记录点位:%1(%2 条机械臂)").arg(p.name).arg(p.targets().size()));
});
const QList<QComboBox *> comboBoxes = findChildren<QComboBox *>();
for (QComboBox *comboBox : comboBoxes)
ApplicationStyle::styleComboBox(comboBox);
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::cameraCapabilitiesReceived,this,[this](quint64 token,const QString& camera,const QVariantMap& caps,bool success,const QString& detail) {
if (m_connected) {
m_cameraCapabilitiesById.insert(camera, success ? caps : QVariantMap());
if (m_taskOrchestration)
m_taskOrchestration->setCameraCapabilities(camera, success ? caps : QVariantMap());
refreshCameraDepthControls();
}
if(token!=m_cameraCapabilitiesToken || camera!=m_activeCameraId || !m_connected) return;
m_cameraCapabilityInFlight=false;
const auto next=success?caps:QVariantMap{};
if(m_activeCameraCapabilities.value("serial")!=next.value("serial")
||m_activeCameraCapabilities.value("sessionGeneration").toULongLong()!=next.value("sessionGeneration").toULongLong()) {
m_client->stopCameraStream(camera); m_runningCameraIds.remove(camera);
}
m_activeCameraCapabilities=next;
if(m_handEyeMotion) m_handEyeMotion->setCameraCapabilities(camera,next);
if(m_handEye) m_handEye->setCameraCapabilities(camera,next);
if(m_touchOperation) m_touchOperation->setCameraCapabilities(camera,next);
if(!success && m_cameraStreamStateLabel) m_cameraStreamStateLabel->setText(detail);
});
connect(m_client,&RobotClient::connectionChanged,this,[this](bool,int,const QString&) {
m_cameraCapabilitiesById.clear();
if (m_taskOrchestration) m_taskOrchestration->setCameraCapabilities(QString(), {});
refreshCameraDepthControls();
++m_cameraCapabilitiesToken; m_cameraCapabilityInFlight=false;
m_activeCameraId.clear(); m_activeCameraCapabilities.clear();
if(m_handEyeMotion) m_handEyeMotion->setCameraCapabilities({},{});
if(m_handEye) m_handEye->setCameraCapabilities({},{});
if(m_touchOperation) m_touchOperation->setCameraCapabilities({},{});
});
auto *capabilityTimer=new QTimer(this); capabilityTimer->setInterval(1500);
connect(capabilityTimer,&QTimer::timeout,this,[this] {
if(!m_connected||m_demoCheck->isChecked()||m_activeCameraId.isEmpty()||m_cameraCapabilityInFlight) return;
m_cameraCapabilityInFlight=true;
m_client->requestCameraCapabilities(m_activeCameraId,++m_cameraCapabilitiesToken);
}); capabilityTimer->start();
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) {
const QString codec = state.value(QStringLiteral("codec")).toString().toLower();
if (!codec.isEmpty())
m_cameraCodecById.insert(cameraId, codec);
if (!codec.isEmpty() && m_pendingTaskCameraPreviews.remove(cameraId) > 0) {
if (m_taskOrchestration)
m_taskOrchestration->reportTaskFeedback(
cameraId, QStringLiteral("使用设备编码器 %1").arg(codec.toUpper()));
m_client->startCameraStream(cameraId, codec, QStringLiteral("rgb"));
}
if (!m_cameraDeviceCombo || !m_cameraCodecCombo
|| m_cameraDeviceCombo->currentData().toString() != cameraId) {
return;
}
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::cameraStreamStateChanged, this,
[this](const QString &cameraId, bool running, const QString &detail) {
if (m_taskCameraResults.contains(cameraId)) {
TaskCameraResult &result = m_taskCameraResults[cameraId];
result.status->setText(running ? QStringLiteral("预览中 · %1").arg(detail)
: QStringLiteral("已停止 · %1").arg(detail));
}
if (m_taskOrchestration && !detail.isEmpty())
m_taskOrchestration->reportTaskFeedback(
cameraId, detail, running || !detail.contains(QStringLiteral("失败")));
if (m_taskOrchestration)
m_taskOrchestration->completeCameraStreamTask(cameraId, running, detail);
});
connect(m_client, &RobotClient::cameraRecordingStateChanged,
this, [this](bool recording, const QString &detail) {
updateCameraRecordingState(recording, detail);
if (!m_taskCameraRecordingId.isEmpty() && m_taskOrchestration) {
const QString action = m_taskCameraRecordingAction;
const QString deviceId = m_taskCameraRecordingId;
m_taskCameraRecordingId.clear();
m_taskCameraRecordingAction.clear();
const bool expectedState = action == QStringLiteral("开始录像");
const bool success = recording == expectedState
&& !detail.contains(QStringLiteral("失败"), Qt::CaseInsensitive)
&& !detail.contains(QStringLiteral("error"), Qt::CaseInsensitive);
m_taskOrchestration->completeActionTask(
QStringLiteral("相机"), deviceId, action, success, detail);
}
});
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_client, &RobotClient::audioStreamStateChanged, this,
[this](const QString &service, bool running, const QString &detail) {
if (!m_taskOrchestration) return;
const bool success = !detail.contains(QStringLiteral("失败"), Qt::CaseInsensitive)
&& !detail.contains(QStringLiteral("error"), Qt::CaseInsensitive);
if (service == QStringLiteral("SpeakerService")) {
if (!m_pendingTaskSpeakerCaptureId.isEmpty()) {
const QString deviceId = m_pendingTaskSpeakerCaptureId;
const QJsonObject parameters = m_pendingTaskSpeakerCaptureParameters;
if (!running) {
m_pendingTaskSpeakerCaptureId.clear();
m_pendingTaskSpeakerCaptureParameters = QJsonObject();
m_taskOrchestration->completeActionTask(
QStringLiteral("扬声器"), deviceId,
QStringLiteral("本机麦克风流播放"), false, detail);
return;
}
if (!m_audioManager->startCapture(
parameters.value(QStringLiteral("inputDevice")).toString(),
parameters.value(QStringLiteral("sampleRate")).toInt(48000),
parameters.value(QStringLiteral("channels")).toInt(1))) {
m_pendingTaskSpeakerCaptureId.clear();
m_pendingTaskSpeakerCaptureParameters = QJsonObject();
m_client->stopSpeakerAudioStream();
m_taskOrchestration->completeActionTask(
QStringLiteral("扬声器"), deviceId,
QStringLiteral("本机麦克风流播放"), false,
QStringLiteral("本机麦克风采集启动失败"));
}
return;
}
if (running) {
m_taskOrchestration->completeActionTask(
QStringLiteral("扬声器"), QString(),
QStringLiteral("开始音频流"), success, detail);
} else {
m_taskOrchestration->completeActionTask(
QStringLiteral("扬声器"), QString(),
QStringLiteral("开始音频流"), false, detail);
m_taskOrchestration->completeActionTask(
QStringLiteral("扬声器"), QString(),
QStringLiteral("停止音频流"), success, detail);
}
} else if (service == QStringLiteral("MicPhoneService")) {
if (running) {
m_taskOrchestration->completeActionTask(
QStringLiteral("麦克风"), QString(),
QStringLiteral("开始音频流"), success, detail);
} else {
m_taskOrchestration->completeActionTask(
QStringLiteral("麦克风"), QString(),
QStringLiteral("开始音频流"), false, detail);
m_taskOrchestration->completeActionTask(
QStringLiteral("麦克风"), QString(),
QStringLiteral("停止音频流"), success, detail);
}
}
});
connect(m_audioManager, &AudioStreamManager::sourceStateChanged, this,
[this](bool running, const QString &detail) {
if (!running || m_pendingTaskSpeakerCaptureId.isEmpty() || !m_taskOrchestration)
return;
const QString deviceId = m_pendingTaskSpeakerCaptureId;
m_pendingTaskSpeakerCaptureId.clear();
m_pendingTaskSpeakerCaptureParameters = QJsonObject();
m_taskOrchestration->completeActionTask(
QStringLiteral("扬声器"), deviceId,
QStringLiteral("本机麦克风流播放"), true, detail);
});
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();
if (m_logView) m_logView->document()->setMaximumBlockCount(ApplicationSettings::instance().options().logMaximumLines);
if (m_quicLogView) m_quicLogView->document()->setMaximumBlockCount(ApplicationSettings::instance().options().logMaximumLines);
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;
}
if (pageArgument < 0) initialPage = ApplicationSettings::instance().options().startupPage;
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()
{
if (m_touchOperation) m_touchOperation->stop();
if (m_tcpJog) m_tcpJog->stop();
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();
ApplicationSettings::instance().saveWindowGeometry(saveGeometry());
}
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::ActivationChange && !isActiveWindow() && m_tcpJog)
m_tcpJog->stop();
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;
const int scrollPosition = m_quicLogView->verticalScrollBar()->value();
QString color = QStringLiteral("#64748b");
if (level == QStringLiteral("ERROR"))
color = QStringLiteral("#bd343b");
else if (level == QStringLiteral("WARN"))
color = QStringLiteral("#a16207");
else if (level == QStringLiteral("OK"))
color = QStringLiteral("#177553");
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()));
if (!ApplicationSettings::instance().options().logAutoScroll)
m_quicLogView->verticalScrollBar()->setValue(scrollPosition);
else
m_quicLogView->verticalScrollBar()->setValue(m_quicLogView->verticalScrollBar()->maximum());
}
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->setArmTelemetry(deviceId, shouldEnable);
}
void MainWindow::selectPage(int index)
{
if (!m_pages || index < 0 || index >= kPageTitles.size())
return;
if (index != 1 && m_tcpJog) m_tcpJog->stop();
if (index != 15 && m_touchOperation) m_touchOperation->stop();
const int previousIndex = m_pages->currentIndex();
if (pageUsesArmTelemetry(previousIndex) && !pageUsesArmTelemetry(index))
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 != 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_urdfViewer->modelPreviewEnabled() || 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) {
if (m_tcpJog) m_tcpJog->stop();
m_connectButton->setEnabled(false);
m_connectButton->setText(QStringLiteral("正在断开…"));
m_client->disconnectFromServer();
return;
}
if (m_hostEdit->text().trimmed().isEmpty()) {
AppMessageBox::warning(this, QStringLiteral("连接参数"), QStringLiteral("请填写主机地址。"));
return;
}
saveSettings();
// Freeze the endpoint while the worker connects so TCP records retain
// the identity of the server that actually owns the feedback.
m_hostEdit->setEnabled(false);
m_portSpin->setEnabled(false);
m_demoCheck->setEnabled(false);
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;
if (!connected) {
++m_jointPointCaptureToken;
m_jointPointCapturePending=false;
stopJointPointLoop(QStringLiteral("连接已断开"));
}
if (!connected && m_taskOrchestration)
m_taskOrchestration->failActiveTask(
detail.isEmpty() ? QStringLiteral("gRPC 连接已断开") : detail);
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 (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;
if (m_armJogActive) stopArmJog();
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 < 5; ++column)
m_jointTable->setItem(row, column, new QTableWidgetItem(QStringLiteral("--")));
}
if (m_motionTable) {
m_motionTable->clearContents();
m_motionTable->setColumnCount(5);
m_motionTable->setRowCount(jointNames.size());
m_targetSpins.clear();
m_targetRadianSpins.clear();
for (int row = 0; row < jointNames.size(); ++row) {
m_motionTable->setItem(row, 0, new QTableWidgetItem(jointNames.at(row)));
QLineEdit *currentDegrees = new QLineEdit(QStringLiteral("--"), m_motionTable);
QLineEdit *currentRadians = new QLineEdit(QStringLiteral("--"), m_motionTable);
for (QLineEdit *current : {currentDegrees, currentRadians}) {
current->setReadOnly(true);
current->setFrame(false);
current->setAlignment(Qt::AlignCenter);
current->setToolTip(QStringLiteral("只读;可选中文本后复制"));
}
m_motionTable->setCellWidget(row, 1, currentDegrees);
m_motionTable->setCellWidget(row, 2, currentRadians);
QDoubleSpinBox *targetDegrees = new QDoubleSpinBox(m_motionTable);
targetDegrees->setRange(-360.0, 360.0);
targetDegrees->setDecimals(3);
targetDegrees->setSingleStep(1.0);
targetDegrees->setSuffix(QStringLiteral(" °"));
targetDegrees->setKeyboardTracking(false);
QDoubleSpinBox *targetRadians = new QDoubleSpinBox(m_motionTable);
targetRadians->setRange(-2.0 * M_PI, 2.0 * M_PI);
targetRadians->setDecimals(6);
targetRadians->setSingleStep(0.01);
targetRadians->setSuffix(QStringLiteral(" rad"));
targetRadians->setKeyboardTracking(false);
m_motionTable->setCellWidget(row, 3, targetDegrees);
m_motionTable->setCellWidget(row, 4, targetRadians);
connect(targetDegrees, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
this, [targetRadians](double degrees) {
const QSignalBlocker blocker(targetRadians);
targetRadians->setValue(qDegreesToRadians(degrees));
});
connect(targetRadians, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
this, [targetDegrees](double radians) {
const QSignalBlocker blocker(targetDegrees);
targetDegrees->setValue(qRadiansToDegrees(radians));
});
m_targetSpins.append(targetDegrees);
m_targetRadianSpins.append(targetRadians);
}
}
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());
if (m_sendMoveButton)
m_sendMoveButton->setEnabled(m_connected && !jointNames.isEmpty());
if (m_syncCurrentToTargetButton)
m_syncCurrentToTargetButton->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();
if (m_activeArmJointNames.isEmpty()) {
auto *empty = new QLabel(QStringLiteral("等待当前机械臂关节数据,连接后自动加载。"), m_jointJogRowsHost);
empty->setObjectName(QStringLiteral("jointJogEmptyState"));
empty->setWordWrap(true);
m_jointJogRowsLayout->addWidget(empty);
}
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);
refreshArmJogAvailability();
if(m_handEye) m_handEye->setJointStates(m_activeArmJointNames,{});
}
void MainWindow::refreshArmJogAvailability()
{
const bool ready = m_connected && !m_activeArmJointNames.isEmpty();
for (auto *button : m_jointJogMinusButtons) button->setEnabled(ready);
for (auto *button : m_jointJogPlusButtons) button->setEnabled(ready);
if (m_jogReadyLabel) m_jogReadyLabel->setText(!m_connected
? QStringLiteral("未连接") : ready ? QStringLiteral("● 控制就绪")
: QStringLiteral("等待关节数据"));
}
void MainWindow::startJointJog(int jointIndex, int direction)
{
if (m_touchOperation && m_touchOperation->running()) { m_touchOperation->stop(); return; }
if (m_tcpJog && m_tcpJog->running()) { m_tcpJog->stop(); return; }
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_touchOperation && m_touchOperation->running()) { m_touchOperation->stop(); return; }
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;
if (selectedLocalTcp()) {
TcpCalibration::Pose offset{};
const auto values = m_tcpFrameCombo->currentData(Qt::UserRole + 1).toList();
if (values.size() != 6 || !m_tcpJog) return;
for (int i=0;i<6;++i) offset[size_t(i)] = values.at(i).toDouble();
m_tcpJog->start(offset, axisIndex, direction, maximumVelocity * ratio,
m_cartesianAccelerationSpin ? m_cartesianAccelerationSpin->value() : .5);
return;
}
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_touchOperation && m_touchOperation->running()) { m_touchOperation->stop(); return; }
if (m_tcpJog && m_tcpJog->running()) { m_tcpJog->stop(); return; }
if (!m_connected || !m_armIdEdit)
return;
m_armJogActive = false;
m_client->requestArmStop(m_armIdEdit->text().trimmed());
}
void MainWindow::syncHandEyeContext()
{
if (!m_handEye || !m_handEyeMotion || !m_tcpCalibration) return;
const QString device=m_armIdEdit->text().trimmed();
const bool reference=m_tcpCalibration->referenceConfirmed();
const auto offset=m_tcpCalibration->activeOffset();
m_handEye->setContext(endpoint(),device,m_connected,m_demoCheck->isChecked(),reference,offset);
m_handEye->setCameraIds(m_demoCheck->isChecked()?configuredCameraIds():m_activeCameraId.isEmpty()?QStringList{}:QStringList{m_activeCameraId});
m_handEyeMotion->setContext(endpoint(),device,m_connected,m_demoCheck->isChecked(),reference,offset);
if (m_touchOperation) { m_touchOperation->setCameraIds(m_demoCheck->isChecked()?configuredCameraIds():m_activeCameraId.isEmpty()?QStringList{}:QStringList{m_activeCameraId}); m_touchOperation->setContext(endpoint(),device,m_connected,m_demoCheck->isChecked(),reference,offset); }
}
void MainWindow::setupTouchOperation()
{
m_touchOperation=new TouchOperationWidget(m_pages);
m_pages->addWidget(m_touchOperation);
connect(m_touchOperation,&TouchOperationWidget::captureRequested,m_client,&RobotClient::requestTcpCalibrationPose);
connect(m_touchOperation,&TouchOperationWidget::imageRequested,this,[this](const QString& camera,quint64 token) {
if(CameraCapabilities::mode(m_activeCameraCapabilities)==CameraCapabilities::Mode::Plane) m_client->requestTouchImage(camera,token);
else m_client->requestTouchRgbdImage(camera,token);
});
connect(m_touchOperation,&TouchOperationWidget::moveRequested,m_client,&RobotClient::requestTcpJogMove);
connect(m_touchOperation,&TouchOperationWidget::stopRequested,m_client,&RobotClient::requestArmStop);
connect(m_touchOperation,&TouchOperationWidget::logMessage,this,&MainWindow::appendLog);
connect(m_client,&RobotClient::tcpCalibrationPoseReceived,m_touchOperation,&TouchOperationWidget::acceptPose);
connect(m_client,&RobotClient::touchRgbdImageReceived,m_touchOperation,&TouchOperationWidget::acceptImage);
connect(m_client,&RobotClient::videoFrameReceived,m_touchOperation,&TouchOperationWidget::acceptFrame);
connect(m_client,&RobotClient::cameraStreamStateChanged,m_touchOperation,&TouchOperationWidget::acceptStreamState);
connect(m_client,&RobotClient::commandFinished,m_touchOperation,&TouchOperationWidget::acceptCommand);
connect(m_client,&RobotClient::tcpReferenceInvalidated,m_touchOperation,[this] { m_touchOperation->stop(); });
connect(m_client,&RobotClient::armCommandStarting,m_touchOperation,[this](const QString &device) {
if(device.trimmed().isEmpty()||device.trimmed()==m_armIdEdit->text().trimmed()) m_touchOperation->stop();
});
connect(m_client,&RobotClient::armStopRequested,m_touchOperation,&TouchOperationWidget::stop);
connect(m_client,&RobotClient::systemStopAllRequested,m_touchOperation,&TouchOperationWidget::stop);
connect(m_client,&RobotClient::connectionChanged,m_touchOperation,[this](bool connected,int,const QString &) {
m_touchOperation->setContext(endpoint(),m_armIdEdit->text().trimmed(),connected,m_demoCheck->isChecked(),m_tcpCalibration->referenceConfirmed(),m_tcpCalibration->activeOffset());
});
connect(m_client,&RobotClient::disconnectRequested,m_touchOperation,[this] {
m_touchOperation->setContext(endpoint(),m_armIdEdit->text().trimmed(),false,m_demoCheck->isChecked(),false,{});
});
connect(m_touchOperation,&TouchOperationWidget::previewRequested,this,[this](const QString &camera,bool start) {
if(start) {
if ((m_runningCameraIds.contains(camera)||m_touchOwnedCamera==camera)
&& m_cameraStreamModes.value(camera,QStringLiteral("rgb"))==QStringLiteral("rgb")) return;
m_touchOwnedCamera=camera;
m_client->startCameraStream(camera,m_cameraCodecCombo->currentIndex()==1?QStringLiteral("h265"):QStringLiteral("h264"),QStringLiteral("rgb"));
} else if(m_touchOwnedCamera==camera) { m_touchOwnedCamera.clear(); m_client->stopCameraStream(camera); }
});
connect(m_client,&RobotClient::cameraStreamStateChanged,this,[this](const QString &camera,bool running,const QString &) {
if(!running&&m_touchOwnedCamera==camera) m_touchOwnedCamera.clear();
});
auto changed=[this](const QString &host,const QString &device,const QString &) {
if(host==endpoint()&&device==m_armIdEdit->text().trimmed()) m_touchOperation->reloadCalibrations();
};
connect(m_handEye,&HandEyeCalibrationWidget::calibrationsChanged,m_touchOperation,changed);
connect(m_tcpCalibration,&TcpCalibrationWidget::toolsChanged,m_touchOperation,changed);
syncHandEyeContext();
}
void MainWindow::setupHandEye()
{
m_handEye=new HandEyeCalibrationWidget(m_pages);
m_pages->addWidget(m_handEye);
connect(m_handEye,&HandEyeCalibrationWidget::captureRequested,m_client,&RobotClient::requestTcpCalibrationPose);
connect(m_handEyeMotion,&HandEyeMotionWidget::captureRequested,m_client,&RobotClient::requestTcpCalibrationPose);
connect(m_client,&RobotClient::tcpCalibrationPoseReceived,m_handEye,&HandEyeCalibrationWidget::acceptPose);
connect(m_client,&RobotClient::tcpCalibrationPoseReceived,m_handEyeMotion,&HandEyeMotionWidget::acceptPose);
connect(m_handEye,&HandEyeCalibrationWidget::jointJogRequested,this,&MainWindow::startJointJog);
connect(m_handEye,&HandEyeCalibrationWidget::jointJogStopped,this,&MainWindow::stopArmJog);
connect(m_handEye,&HandEyeCalibrationWidget::jogRatioChanged,m_jogSpeedSlider,&QSlider::setValue);
connect(m_jogSpeedSlider,&QSlider::valueChanged,m_handEye,&HandEyeCalibrationWidget::setJogRatio);
m_handEye->setJogRatio(m_jogSpeedSlider->value());
connect(m_handEye,&HandEyeCalibrationWidget::imageRequested,m_client,&RobotClient::requestHandEyeImage);
connect(m_client,&RobotClient::handEyeImageReceived,m_handEye,&HandEyeCalibrationWidget::acceptImage);
connect(m_client,&RobotClient::videoFrameReceived,m_handEye,&HandEyeCalibrationWidget::acceptFrame);
connect(m_client,&RobotClient::cameraStreamStateChanged,m_handEye,&HandEyeCalibrationWidget::acceptStreamState);
connect(m_handEye,&HandEyeCalibrationWidget::logMessage,this,&MainWindow::appendLog);
connect(m_handEyeMotion,&HandEyeMotionWidget::logMessage,this,&MainWindow::appendLog);
connect(m_handEyeMotion,&HandEyeMotionWidget::currentUrdfRequested,this,[this] {
if (m_urdfViewer) m_handEyeMotion->setUrdfFile(m_urdfViewer->currentFile());
});
connect(m_handEyeMotion,&HandEyeMotionWidget::urdfUpdated,this,
[this](const QString &host,const QString &device,const QString &path) {
if (host!=endpoint() || device!=m_armIdEdit->text().trimmed() || !m_urdfViewer) return;
const QString previous=m_urdfViewer->currentFile();
if (m_urdfViewer->loadUrdf(path)) {
m_pendingUrdfPath=path;
appendLog(QStringLiteral("OK"),QStringLiteral("标定 URDF 已加载:%1").arg(path));
} else {
if (!previous.isEmpty()) m_urdfViewer->loadUrdf(previous);
AppMessageBox::warning(this,QStringLiteral("URDF 更新"),QStringLiteral("文件已导出,但模型加载失败。请检查网格资源路径。"));
}
});
connect(m_handEye,&HandEyeCalibrationWidget::previewRequested,this,[this](const QString &camera,bool start) {
if (start) {
// Borrow an existing session. Only a stream started for this page
// is stopped when its preview closes; no duplicate camera client.
if ((m_runningCameraIds.contains(camera) || m_handEyeOwnedCamera==camera)
&& m_cameraStreamModes.value(camera,QStringLiteral("rgb"))==QStringLiteral("rgb")) return;
m_handEyeOwnedCamera=camera;
m_client->startCameraStream(camera,m_cameraCodecCombo->currentIndex()==1 ? QStringLiteral("h265") : QStringLiteral("h264"),QStringLiteral("rgb"));
} else if (m_handEyeOwnedCamera==camera) {
m_handEyeOwnedCamera.clear(); m_client->stopCameraStream(camera);
}
});
connect(m_client,&RobotClient::cameraStreamStateChanged,this,[this](const QString &camera,bool running,const QString &) {
if (!running && m_handEyeOwnedCamera==camera) m_handEyeOwnedCamera.clear();
});
connect(m_handEye,&HandEyeCalibrationWidget::calibrationsChanged,this,[this](const QString &host,const QString &device,const QString &name) {
if (host==endpoint() && device==m_armIdEdit->text().trimmed()) m_handEyeMotion->reload(name);
});
connect(m_armIdEdit,&QLineEdit::textChanged,this,[this] { syncHandEyeContext(); });
connect(m_hostEdit,&QLineEdit::textChanged,this,[this] { syncHandEyeContext(); });
connect(m_portSpin,QOverload<int>::of(&QSpinBox::valueChanged),this,[this] { syncHandEyeContext(); });
connect(m_cameraDeviceCombo,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { syncHandEyeContext(); });
connect(m_demoCheck,&QCheckBox::toggled,this,[this] { syncHandEyeContext(); });
connect(m_tcpCalibration,&TcpCalibrationWidget::referenceChanged,this,&MainWindow::syncHandEyeContext);
connect(m_client,&RobotClient::connectionChanged,this,[this](bool connected,int,const QString &) {
const QString device=m_armIdEdit->text().trimmed();
m_handEye->setContext(endpoint(),device,connected,m_demoCheck->isChecked(),m_tcpCalibration->referenceConfirmed(),m_tcpCalibration->activeOffset());
m_handEyeMotion->setContext(endpoint(),device,connected,m_demoCheck->isChecked(),m_tcpCalibration->referenceConfirmed(),m_tcpCalibration->activeOffset());
});
connect(m_client,&RobotClient::disconnectRequested,this,[this] {
const QString device=m_armIdEdit->text().trimmed();
m_handEye->setContext(endpoint(),device,false,m_demoCheck->isChecked(),false,{});
m_handEyeMotion->setContext(endpoint(),device,false,m_demoCheck->isChecked(),false,{});
});
syncHandEyeContext();
}
bool MainWindow::selectedLocalTcp() const
{
return m_tcpFrameCombo && m_tcpFrameCombo->currentData().toString().startsWith(QStringLiteral("local:"));
}
void MainWindow::refreshTcpChoices(const QString &savedName)
{
if (!m_tcpFrameCombo || !m_armIdEdit) return;
const QString device = m_armIdEdit->text().trimmed();
const bool changed = m_tcpChoiceEndpoint != endpoint() || m_tcpChoiceDevice != device;
QString previous = changed ? QString() : m_tcpFrameCombo->currentData().toString();
if (changed) {
if (m_tcpJog) m_tcpJog->stop();
m_controllerTcpFrames.clear();
m_armDefaultTcpFrame.clear();
m_tcpChoiceEndpoint = endpoint(); m_tcpChoiceDevice = device;
}
TcpToolStore::Snapshot snapshot;
QSettings settings; QString error;
if (!device.isEmpty() && !TcpToolStore::load(settings,endpoint(),device,snapshot,error))
appendLog(QStringLiteral("ERROR"),error);
if (!savedName.isEmpty()) previous = QStringLiteral("local:") + savedName;
else if (changed && !snapshot.current.isEmpty()) previous = QStringLiteral("local:") + snapshot.current;
{
const QSignalBlocker blocker(m_tcpFrameCombo);
m_tcpFrameCombo->clear();
QStringList frames = m_controllerTcpFrames;
if (frames.isEmpty()) frames << (m_armDefaultTcpFrame.isEmpty() ? QStringLiteral("tool0") : m_armDefaultTcpFrame);
for (const QString &frame : frames)
m_tcpFrameCombo->addItem(frame, QStringLiteral("controller:") + frame);
for (const auto &tool : snapshot.tools) {
m_tcpFrameCombo->addItem(tool.name + QStringLiteral("(标定)"), QStringLiteral("local:") + tool.name);
QVariantList pose; for (double value : tool.offset) pose.append(value);
m_tcpFrameCombo->setItemData(m_tcpFrameCombo->count()-1,pose,Qt::UserRole+1);
}
const int index=m_tcpFrameCombo->findData(previous);
m_tcpFrameCombo->setCurrentIndex(index>=0 ? index : 0);
}
updateArmPoseFrames();
}
void MainWindow::updateArmPoseFrames()
{
if (!m_tcpFrameCombo || !m_baseFrameCombo || !m_armIdEdit) return;
const bool local = selectedLocalTcp();
if (m_tcpJog) m_tcpJog->stop();
if (local) {
const QSignalBlocker blocker(m_baseFrameCombo);
int base = m_baseFrameCombo->findText(QStringLiteral("base"));
if (base < 0) { m_baseFrameCombo->addItem(QStringLiteral("base")); base=m_baseFrameCombo->count()-1; }
m_baseFrameCombo->setCurrentIndex(base);
}
m_baseFrameCombo->setEnabled(!local);
if (m_armPoseSubtitle) m_armPoseSubtitle->setText(local
? QStringLiteral("base → %1 · 按住工具轴小步点动").arg(m_tcpFrameCombo->currentText())
: QStringLiteral("%1 → %2").arg(m_baseFrameCombo->currentText(),m_tcpFrameCombo->currentText()));
m_tcpFrameCombo->setToolTip(local
? QStringLiteral("使用当前机器人的标定偏移进行点动;单步最多 2 mm / 0.29°,松开即停止")
: QStringLiteral("控制器坐标名称;原速度命令仍使用基座方向"));
// Display fallbacks such as "base" and "tool0" are UI labels only. A
// Metadata defaults use getRobotState.actual_tcp_pose directly. Do not
// duplicate every sample with a named getPose query, or enumerate frames.
const QString baseFrame = m_baseFrameCombo->currentText().trimmed();
const QString tcpFrame = m_tcpFrameCombo->currentText().trimmed();
const bool defaultPair = baseFrame == m_armDefaultBaseFrame
&& tcpFrame == m_armDefaultTcpFrame;
const bool serverFramePair = !local && !defaultPair
&& m_controllerBaseFrames.contains(baseFrame)
&& m_controllerTcpFrames.contains(tcpFrame);
m_client->setArmTelemetryFrames(m_armIdEdit->text().trimmed(),
serverFramePair ? baseFrame : QString(),
serverFramePair ? tcpFrame : QString());
for (auto *label : m_cartesianJogPoseLabels) label->setText(QStringLiteral("--"));
for (auto *label : m_poseMetricValues) label->setText(QStringLiteral("--"));
}
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();
const bool jointInfoOnly = info.value(QStringLiteral("source")).toString()
== QStringLiteral("getJointState");
m_armDefaultBaseFrame = info.value(QStringLiteral("defaultBaseFrame")).toString();
m_armDefaultTcpFrame = info.value(QStringLiteral("defaultTcpFrame")).toString();
const QStringList jointNames = info.value(QStringLiteral("jointNames")).toStringList();
// Some older controllers do not implement joint_names. Do not erase rows
// recovered from real telemetry, or recreate a button while it is held.
if (!jointNames.isEmpty() && jointNames != m_activeArmJointNames)
rebuildArmJointTables(jointNames);
if (!jointInfoOnly && m_baseFrameCombo && m_baseFrameCombo->count() == 0)
m_baseFrameCombo->addItem(m_armDefaultBaseFrame.isEmpty()
? QStringLiteral("base") : m_armDefaultBaseFrame);
if (!jointInfoOnly && m_tcpFrameCombo && m_tcpFrameCombo->count() == 0)
m_tcpFrameCombo->addItem(m_armDefaultTcpFrame.isEmpty()
? QStringLiteral("tool0") : m_armDefaultTcpFrame);
if (m_armDeviceSummary) {
const QString identity = jointInfoOnly
? QStringLiteral("%1 · %2轴 · 型号未提供").arg(deviceId).arg(jointNames.size())
: 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());
}
// Metadata defaults avoid traversing unsupported AUBO frame trees.
m_controllerBaseFrames = m_armDefaultBaseFrame.isEmpty()
? QStringList{} : QStringList{m_armDefaultBaseFrame};
m_controllerTcpFrames = m_armDefaultTcpFrame.isEmpty()
? QStringList{} : QStringList{m_armDefaultTcpFrame};
refreshTcpChoices();
appendLog(QStringLiteral("INFO"), jointInfoOnly
? QStringLiteral("机械臂 %1:已读取 %2 轴关节信息,服务端未提供型号接口")
.arg(deviceId).arg(jointNames.size())
: 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;
if (!joints.isEmpty() && (m_activeArmJointNames.isEmpty()
|| m_activeArmJointNames.size() != joints.size())) {
QStringList names;
bool valid = true;
for (const auto &value : joints) {
const auto joint = value.toMap();
const QString name = joint.value(QStringLiteral("name")).toString().trimmed();
bool numeric = false;
const double position = joint.value(QStringLiteral("position")).toDouble(&numeric);
if (name.isEmpty() || names.contains(name) || !numeric || !qIsFinite(position)) {
valid = false; break;
}
names.append(name);
}
if (valid) rebuildArmJointTables(names);
}
if(m_handEye) m_handEye->setJointStates(m_activeArmJointNames,joints);
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 QVariant currentValue = joint.value(QStringLiteral("current"));
bool currentValid = false;
const double current = currentValue.toDouble(&currentValid);
const QString currentText = !currentValue.isValid() ? QStringLiteral("未提供")
: currentValid && qIsFinite(current) ? QString::number(current, 'f', 0)
: QStringLiteral("无效");
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_jointTable->item(row, 4)->setText(currentText);
if (m_motionTable) {
for (int targetRow = 0; targetRow < m_motionTable->rowCount(); ++targetRow) {
QTableWidgetItem *targetName = m_motionTable->item(targetRow, 0);
if (!targetName || targetName->text() != nameItem->text())
continue;
if (QLineEdit *degrees = qobject_cast<QLineEdit *>(
m_motionTable->cellWidget(targetRow, 1)))
degrees->setText(QString::number(qRadiansToDegrees(position), 'f', 3));
if (QLineEdit *radians = qobject_cast<QLineEdit *>(
m_motionTable->cellWidget(targetRow, 2)))
radians->setText(QString::number(position, 'f', 6));
break;
}
}
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);
}
m_lastArmTelemetryMs = nowMs;
QVariantMap displayPose = pose;
if (pose.isEmpty()) {
m_latestArmPose.clear();
for (auto *label : m_poseMetricValues) label->setText(QStringLiteral("--"));
for (auto *label : m_cartesianJogPoseLabels) label->setText(QStringLiteral("--"));
}
if (selectedLocalTcp()) {
displayPose.clear();
if (m_tcpCalibration && m_tcpCalibration->referenceConfirmed()) {
const QVariantMap actual = state.value(QStringLiteral("activeTcpPose")).toMap();
const auto values=m_tcpFrameCombo->currentData(Qt::UserRole+1).toList();
const char *names[]={"x","y","z","rx","ry","rz"};
TcpCalibration::Pose current{}, offset{}, flange{}, selected{};
bool valid = values.size()==6;
for(int i=0;valid && i<6;++i) {
bool ok=false; current[size_t(i)]=actual.value(names[i]).toDouble(&ok);
valid=ok; offset[size_t(i)]=values.at(i).toDouble();
}
if (valid && TcpCalibration::flangePose(current,m_tcpCalibration->activeOffset(),flange)
&& TcpCalibration::toolPose(flange,offset,selected))
for(int i=0;i<6;++i) displayPose.insert(names[i],selected[size_t(i)]);
}
if (displayPose.isEmpty()) {
for(auto *label:m_poseMetricValues) label->setText(QStringLiteral("--"));
for(auto *label:m_cartesianJogPoseLabels) label->setText(QStringLiteral("--"));
}
}
if (!displayPose.isEmpty()) {
m_latestArmPose = displayPose;
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(displayPose.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(displayPose.value(keys.at(index)).toDouble(), 0, 'f', 4)
.arg(index < 3 ? QStringLiteral("m") : QStringLiteral("rad")));
}
}
if (state.contains(QStringLiteral("robotStateAvailable"))
&& !state.value(QStringLiteral("robotStateAvailable")).toBool()) {
for (QLabel *label : {m_servoStatusValue, m_faultStatusValue}) {
if (!label) continue;
label->setText(QStringLiteral("服务端未提供"));
label->setProperty("state", QStringLiteral("unknown"));
label->setToolTip(QStringLiteral("关节数据正常;服务端未提供整体使能与故障状态接口"));
label->style()->unpolish(label);
label->style()->polish(label);
}
} else if (!state.isEmpty()) {
if (m_servoStatusValue) m_servoStatusValue->setToolTip(QString());
if (m_faultStatusValue) m_faultStatusValue->setToolTip(QString());
const bool connected = state.value(QStringLiteral("connected")).toBool();
const bool powered = state.value(QStringLiteral("poweredOn")).toBool();
const bool enabled = powered && (!state.contains(QStringLiteral("brakeReleased"))
|| state.value(QStringLiteral("brakeReleased")).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("拖动示教")
: enabled ? (moving ? QStringLiteral("已使能 · 运动中")
: QStringLiteral("已使能 · 空闲"))
: powered ? 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);
AppMessageBox *popup = new AppMessageBox(
level == QStringLiteral("ERROR") ? AppMessageBox::Critical : AppMessageBox::Warning,
QStringLiteral("机械臂状态提醒"), message, AppMessageBox::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)
{
if (m_taskOrchestration)
m_taskOrchestration->setAvailableDevices(devices);
if (m_connected) {
for (const QVariant &value : devices) {
const QVariantMap device = value.toMap();
const QString id = device.value(QStringLiteral("deviceId")).toString();
if (device.value(QStringLiteral("type")).toInt() == 2 && !id.isEmpty())
m_client->requestCameraCapabilities(id, 0);
}
}
if(m_connected && !m_demoCheck->isChecked()) {
QStringList cameras,automatic;
for(const auto& value:devices) {
const auto d=value.toMap();
if(d.value("typeName").toString()!=QStringLiteral("Camera")) continue;
cameras<<d.value("deviceId").toString();
if(d.value("driverType").toString()==QStringLiteral("AutoCamera")) automatic<<d.value("deviceId").toString();
}
const QString selected=automatic.size()==1?automatic.front():automatic.isEmpty()&&cameras.size()==1?cameras.front():QString{};
if(selected!=m_activeCameraId) {
++m_cameraCapabilitiesToken; m_cameraCapabilityInFlight=false;
m_activeCameraId=selected; m_activeCameraCapabilities.clear();
if(m_handEye) m_handEye->setCameraCapabilities(selected,{});
if(m_touchOperation) m_touchOperation->setCameraCapabilities(selected,{});
if(!selected.isEmpty()) rebuildCameraPreviewGrid({selected});
}
if(!selected.isEmpty()&&!m_cameraCapabilityInFlight) {
m_cameraCapabilityInFlight=true; m_client->requestCameraCapabilities(selected,++m_cameraCapabilitiesToken);
}
}
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())) {
if (selectedId != previousId && m_armTelemetryButton->isChecked())
setArmTelemetryEnabled(false);
m_armIdEdit->setText(selectedId);
m_client->requestArmInfo(selectedId);
} else if (m_armIdEdit && m_armIdEdit->text().trimmed().isEmpty()
&& !firstArmId.isEmpty()) {
m_armIdEdit->setText(firstArmId);
m_client->requestArmInfo(firstArmId);
}
if (m_cameraDeviceCombo) {
const QString previousCameraId = m_activeCameraId.isEmpty()
? m_cameraDeviceCombo->currentData().toString() : m_activeCameraId;
{
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();
refreshCameraDepthControls();
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::showTaskCameraResult(const QString &cameraId, const QString &title)
{
if (cameraId.isEmpty()) return;
TaskCameraResult &result = m_taskCameraResults[cameraId];
if (!result.window) {
auto *dialog = new TaskMediaDialog(
QStringLiteral("%1 · %2").arg(cameraId, title), this);
dialog->setAttribute(Qt::WA_DeleteOnClose, false);
result.window = dialog;
result.render = new VideoRenderWidget(dialog);
result.render->setMinimumSize(520, 320);
result.status = new QLabel(QStringLiteral("等待媒体数据…"), dialog);
result.status->setObjectName(QStringLiteral("mutedLabel"));
dialog->contentLayout()->addWidget(result.render, 1);
dialog->contentLayout()->addWidget(result.status);
}
result.window->show();
result.window->raise();
result.window->activateWindow();
}
void MainWindow::updateTaskCameraImage(const QString &cameraId, const QImage &image,
const QString &detail)
{
if (cameraId.isEmpty() || !m_taskCameraResults.contains(cameraId)) return;
TaskCameraResult &result = m_taskCameraResults[cameraId];
result.render->setImage(image);
result.status->setText(detail);
if (m_taskOrchestration)
m_taskOrchestration->reportTaskFeedback(cameraId, detail, !image.isNull());
}
void MainWindow::updateTaskCameraFrame(const QString &cameraId, const VideoFrame &frame,
const QString &detail)
{
if (cameraId.isEmpty() || !m_taskCameraResults.contains(cameraId)) return;
TaskCameraResult &result = m_taskCameraResults[cameraId];
result.render->setFrame(frame);
result.status->setText(detail);
}
void MainWindow::updateImage(const QImage &image, const QString &detail)
{
m_lastImage = image;
m_lastImageIsDepth = detail.startsWith(QStringLiteral("深度"));
if (m_videoRender)
m_videoRender->setImage(image);
m_imageMetaLabel->setText(detail);
m_saveImageButton->setEnabled(true);
if (!m_taskSnapshotCameraId.isEmpty()) {
updateTaskCameraImage(m_taskSnapshotCameraId, image, detail);
m_taskSnapshotCameraId.clear();
}
}
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;
// The decoder thread can already have queued frames when a stream is
// stopped. Do not let those stale frames overwrite a later snapshot.
if (!m_runningCameraIds.contains(resolvedId))
return;
updateTaskCameraFrame(resolvedId, frame, detail);
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)
{
if (!success) {
if (command == QStringLiteral("Snapshot")
|| command == QStringLiteral("Depth Snapshot"))
m_taskSnapshotCameraId.clear();
else if (command == QStringLiteral("Camera Stream"))
m_pendingTaskCameraPreviews.clear();
else if (command == QStringLiteral("Camera Start Recording")
|| command == QStringLiteral("Camera Stop Recording")) {
m_taskCameraRecordingId.clear();
m_taskCameraRecordingAction.clear();
} else if (command == QStringLiteral("Speaker Stream")) {
m_pendingTaskSpeakerCaptureId.clear();
m_pendingTaskSpeakerCaptureParameters = QJsonObject();
m_audioManager->stopSource();
}
}
if (m_taskOrchestration)
m_taskOrchestration->completeCommandTask(command, success, 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("清除失败");
} else if (command == QStringLiteral("Enter Teaching Mode")) {
stateLabel = m_deviceTeachingStateLabel;
stateText = success ? QStringLiteral("已进入示教,可拖动机械臂") : QStringLiteral("进入示教失败");
} else if (command == QStringLiteral("Start Trajectory Recording")) {
stateLabel = m_deviceTeachingStateLabel;
stateText = success ? QStringLiteral("正在记录轨迹") : QStringLiteral("开始记录失败");
} else if (command == QStringLiteral("Stop Trajectory Recording")) {
stateLabel = m_deviceTeachingStateLabel;
stateText = success ? QStringLiteral("轨迹记录已停止") : QStringLiteral("停止记录失败");
} else if (command == QStringLiteral("Exit Teaching Mode")) {
stateLabel = m_deviceTeachingStateLabel;
stateText = success ? QStringLiteral("已退出示教") : QStringLiteral("退出示教失败");
} else if (command == QStringLiteral("Complete Teaching")) {
stateLabel = m_deviceTeachingStateLabel;
stateText = success ? QStringLiteral("示教已完成并退出") : QStringLiteral("完成示教失败");
} else if (command == QStringLiteral("Trajectory Start") || command == QStringLiteral("Replay Trajectory")) {
stateLabel = m_deviceTeachingStateLabel;
stateText = !success ? QStringLiteral("轨迹操作失败") : command == QStringLiteral("Trajectory Start")
? QStringLiteral("已到轨迹起点") : QStringLiteral("轨迹回放完成");
}
if (m_trajectoryStatusTimer && (command == QStringLiteral("Start Trajectory Recording")
|| command == QStringLiteral("Stop Trajectory Recording") || command == QStringLiteral("Complete Teaching"))) {
m_client->requestRecordedTrajectories(m_armIdEdit->text().trimmed());
}
if (stateLabel) {
stateLabel->setText(stateText);
stateLabel->setToolTip(detail);
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 (!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;
const int scrollPosition = m_logView->verticalScrollBar()->value();
QString color = QStringLiteral("#64748b");
if (level == QStringLiteral("ERROR"))
color = QStringLiteral("#bd343b");
else if (level == QStringLiteral("WARN"))
color = QStringLiteral("#a16207");
else if (level == QStringLiteral("OK"))
color = QStringLiteral("#177553");
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()));
if (!ApplicationSettings::instance().options().logAutoScroll)
m_logView->verticalScrollBar()->setValue(scrollPosition);
else
m_logView->verticalScrollBar()->setValue(m_logView->verticalScrollBar()->maximum());
}
void MainWindow::sendMoveJ()
{
if (m_armIdEdit->text().trimmed().isEmpty() || m_targetSpins.isEmpty()) {
AppMessageBox::warning(this, QStringLiteral("MoveJ 关节位置控制"),
QStringLiteral("请先选择机械臂并等待关节信息加载完成。"));
return;
}
QVariantList positions;
for (QDoubleSpinBox *spin : m_targetRadianSpins)
positions.append(spin->value());
m_client->requestMoveJ(m_armIdEdit->text().trimmed(), positions,
m_moveJVelocitySpin ? m_moveJVelocitySpin->value()
: m_velocitySpin->value(),
m_moveJAccelerationSpin ? m_moveJAccelerationSpin->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, ids, names;
int count=0;
for (const auto &t : point.targets()) {
QStringList angles;
for (double position : t.positions) angles.append(QString::number(position,'f',6));
ids.append(t.deviceId);
names.append(t.jointNames);
values.append(t.deviceId+QStringLiteral(": ")+angles.join(", "));
count+=t.positions.size();
}
m_jointPointTable->setItem(row, 0, new QTableWidgetItem(point.name));
m_jointPointTable->setItem(row, 1, new QTableWidgetItem(
point.targets().size()>1 ? QStringLiteral("组合 · %1 臂").arg(point.targets().size())
: (point.side == QStringLiteral("left") ? QStringLiteral("左臂")
: point.side == QStringLiteral("right") ? QStringLiteral("右臂") : QStringLiteral("单臂"))));
m_jointPointTable->setItem(row, 2, new QTableWidgetItem(ids.join(" + ")));
m_jointPointTable->setItem(row, 3, new QTableWidgetItem(
QString::number(count)));
QTableWidgetItem *positionsItem = new QTableWidgetItem(values.join(QStringLiteral(" | ")));
positionsItem->setToolTip(QStringLiteral("关节顺序:%1\n角度(rad):%2")
.arg(names.join(QStringLiteral(", ")),
values.join(QStringLiteral("\n"))));
m_jointPointTable->setItem(row, 4, positionsItem);
}
}
void MainWindow::refreshJointFlowTable()
{
if (m_jointFlowEditor)
m_jointFlowEditor->update();
}
void MainWindow::recordCurrentJointPoint()
{
if (m_jointPointCapturePending || m_jointPointMovePending || m_jointPointLoopActive) return;
const QString name = m_jointPointNameEdit
? m_jointPointNameEdit->text().trimmed() : QString();
if (name.isEmpty()) {
AppMessageBox::warning(this, QStringLiteral("记录关节点位"),
QStringLiteral("请输入动作名称。"));
return;
}
for (const RecordedJointPoint &point : m_recordedJointPoints) {
if (point.name.compare(name, Qt::CaseInsensitive) == 0) {
AppMessageBox::warning(this, QStringLiteral("记录关节点位"),
QStringLiteral("动作名称“%1”已存在,请使用其他名称。")
.arg(name));
return;
}
}
QDialog dialog(m_jointFlowDialog);
dialog.setWindowTitle(QStringLiteral("选择记录的机械臂"));
auto *layout=new QVBoxLayout(&dialog);
layout->addWidget(new QLabel(QStringLiteral("勾选一条或多条机械臂,读取当前关节角度。"),&dialog));
auto *list=new QListWidget(&dialog);
for (int i=0;i<m_armSideCombo->count();++i) {
const QString id=m_armSideCombo->itemData(i).toString();
if (id.isEmpty()) continue;
auto *item=new QListWidgetItem(m_armSideCombo->itemText(i),list);
item->setData(Qt::UserRole,id);
item->setFlags(item->flags()|Qt::ItemIsUserCheckable);
item->setCheckState(id==m_armIdEdit->text().trimmed()?Qt::Checked:Qt::Unchecked);
}
layout->addWidget(list);
auto *buttons=new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel,&dialog);
layout->addWidget(buttons);
connect(buttons,&QDialogButtonBox::accepted,&dialog,&QDialog::accept);
connect(buttons,&QDialogButtonBox::rejected,&dialog,&QDialog::reject);
ApplicationStyle::decorateDialog(&dialog);
dialog.resize(520,330);
if (dialog.exec()!=QDialog::Accepted) return;
QStringList devices;
for (int i=0;i<list->count();++i) if (list->item(i)->checkState()==Qt::Checked)
devices.append(list->item(i)->data(Qt::UserRole).toString());
if (devices.isEmpty()) return;
m_jointPointCapturePending=true;
m_jointPointCaptureName=name;
m_jointPointCaptureGroup=m_activeJointProgramGroup;
m_recordJointPointButton->setEnabled(false);
m_client->requestJointPointCapture(devices,++m_jointPointCaptureToken);
}
void MainWindow::combineSelectedJointPoints()
{
if (m_jointPointCapturePending || m_jointPointMovePending || m_jointPointLoopActive) return;
const QString name=m_jointPointNameEdit->text().trimmed();
RecordedJointPoint p; p.name=name;
for (const auto &old : m_recordedJointPoints) if (old.name.compare(name,Qt::CaseInsensitive)==0) {
AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("组合点位"),QStringLiteral("请使用不同的点位名称。")); return;
}
for (const auto &row : m_jointPointTable->selectionModel()->selectedRows())
p.arms.append(m_recordedJointPoints.at(row.row()).targets());
if (p.arms.size()<2 || !p.valid()) {
AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("组合点位"),
QStringLiteral("请填写新名称,并选中不同机械臂的点位。每条机械臂只能出现一次,原点位将保留。")); return;
}
m_recordedJointPoints.append(p); refreshRecordedJointPoints(); saveJointPrograms();
m_jointPointNameEdit->clear(); m_jointPointTable->selectRow(m_recordedJointPoints.size()-1);
}
void MainWindow::dispatchJointPoint(int row)
{
const auto &p=m_recordedJointPoints.at(row);
if (!p.valid()) { stopJointPointLoop(QStringLiteral("点位数据无效,未发送")); return; }
m_jointPointMovingDevices.clear();
for (const auto &t : p.targets()) m_jointPointMovingDevices.append(t.deviceId);
m_jointPointMovePending=true;
m_stopJointPointLoopButton->setEnabled(true);
const QScopedValueRollback<bool> dispatch(m_jointPointDispatching,true);
m_client->requestJointPointMove(p.commandTargets(),m_jointFlowVelocitySpin->value(),
m_jointFlowAccelerationSpin->value(),++m_jointPointRequestToken);
}
void MainWindow::finishJointPoint(quint64 token,bool success,const QString &detail)
{
if (token!=m_jointPointRequestToken || !m_jointPointMovePending) return;
m_jointPointMovePending=false;
m_jointPointMovingDevices.clear();
appendLog(success?QStringLiteral("OK"):QStringLiteral("ERROR"),detail);
if (!success || !m_jointPointLoopActive) { stopJointPointLoop(detail); return; }
const int index=m_jointPointLoopCursor-1;
const int delay=index>=0 && index<m_jointPointExecutionWaits.size()
? qRound(m_jointPointExecutionWaits[index]*1000.0) : 0;
const quint64 generation=m_jointPointLoopGeneration;
QTimer::singleShot(delay,this,[this,generation] {
if (generation==m_jointPointLoopGeneration) advanceJointPointLoop();
});
}
void MainWindow::stopJointPointMotion()
{
const QStringList devices=m_jointPointMovingDevices;
m_jointPointMovingDevices.clear();
const QScopedValueRollback<bool> dispatch(m_jointPointDispatching,true);
for (const auto &id : devices) m_client->requestArmStop(id);
}
void MainWindow::executeSelectedJointPoint()
{
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending)
return;
const QModelIndexList selected = m_jointPointTable
? m_jointPointTable->selectionModel()->selectedRows() : QModelIndexList();
if (selected.isEmpty()) {
AppMessageBox::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);
dispatchJointPoint(row);
if (m_jointPointLoopStatus)
m_jointPointLoopStatus->setText(QStringLiteral("执行:%1").arg(point.name));
}
void MainWindow::startJointPointLoop()
{
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending)
return;
++m_jointPointLoopGeneration;
if (!m_jointFlowEditor || m_jointFlowEditor->isEmpty()) {
AppMessageBox::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()) {
AppMessageBox::warning(this, QStringLiteral("执行自定义流程"), flowError);
return;
}
for (const JointFlowEditor::ExecutionStep &step : steps) {
const int row = pointRow(step.pointName);
if (row < 0) {
AppMessageBox::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()) {
AppMessageBox::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);
m_jointFlowVelocitySpin->setEnabled(false);
m_jointFlowAccelerationSpin->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));
m_jointPointLoopStatus->setText(QStringLiteral("步骤 %1/%2 · %3")
.arg(executionIndex + 1).arg(m_jointPointLoopRows.size()).arg(point.name));
dispatchJointPoint(row);
}
void MainWindow::stopJointPointLoop(const QString &reason)
{
++m_jointPointRequestToken;
m_jointPointMovingDevices.clear();
++m_jointPointLoopGeneration;
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(!m_jointPointCapturePending);
if (m_stopJointPointLoopButton)
m_stopJointPointLoopButton->setEnabled(false);
if (m_jointPointTable)
m_jointPointTable->setEnabled(true);
if (m_jointFlowVelocitySpin)
m_jointFlowVelocitySpin->setEnabled(m_connected);
if (m_jointFlowAccelerationSpin)
m_jointFlowAccelerationSpin->setEnabled(m_connected);
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_%1_%2.png")
.arg(m_lastImageIsDepth ? QStringLiteral("depth")
: QStringLiteral("rgb"),
QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss"));
const QString path = QFileDialog::getSaveFileName(
this, m_lastImageIsDepth ? QStringLiteral("保存深度图像")
: 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());
QString armDeviceId = settings.value(QStringLiteral("arm/device"),
QStringLiteral("demo_arm")).toString().trimmed();
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.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);
}
QString MainWindow::jointProgramsFilePath() const
{
return QDir(QCoreApplication::applicationDirPath())
.filePath(QStringLiteral("joint_programs.json"));
}
void MainWindow::storeCurrentJointProgramGroup()
{
if (m_activeJointProgramGroup < 0
|| m_activeJointProgramGroup >= m_jointProgramGroups.size())
return;
JointProgramGroup &group = m_jointProgramGroups[m_activeJointProgramGroup];
group.points = m_recordedJointPoints;
group.flow = m_jointFlowEditor ? m_jointFlowEditor->toJson() : QJsonArray();
if (m_jointFlowVelocitySpin)
group.moveJVelocity = m_jointFlowVelocitySpin->value();
if (m_jointFlowAccelerationSpin)
group.moveJAcceleration = m_jointFlowAccelerationSpin->value();
}
void MainWindow::activateJointProgramGroup(int index)
{
if (m_updatingJointProgramGroup || index < 0
|| index >= m_jointProgramGroups.size()
|| index == m_activeJointProgramGroup)
return;
++m_jointPointCaptureToken;
m_jointPointCapturePending=false;
if (m_recordJointPointButton) m_recordJointPointButton->setEnabled(true);
if (m_jointPointLoopActive || m_jointPointMovePending)
stopJointPointMotion();
if (m_jointPointLoopActive || m_jointPointMovePending)
stopJointPointLoop(QStringLiteral("切换点位组"));
storeCurrentJointProgramGroup();
m_activeJointProgramGroup = index;
const JointProgramGroup &group = m_jointProgramGroups.at(index);
m_recordedJointPoints = group.points;
if (m_jointFlowEditor) {
const QSignalBlocker blocker(m_jointFlowEditor);
m_jointFlowEditor->clear();
m_jointFlowEditor->fromJson(group.flow);
}
if (m_jointFlowVelocitySpin) {
const QSignalBlocker blocker(m_jointFlowVelocitySpin);
m_jointFlowVelocitySpin->setValue(group.moveJVelocity);
}
if (m_jointFlowAccelerationSpin) {
const QSignalBlocker blocker(m_jointFlowAccelerationSpin);
m_jointFlowAccelerationSpin->setValue(group.moveJAcceleration);
}
refreshRecordedJointPoints();
refreshJointFlowTable();
saveJointPrograms();
}
void MainWindow::loadJointPrograms(QSettings &legacySettings)
{
m_jointProgramGroups.clear();
m_activeJointProgramGroup = -1;
const QString filePath = jointProgramsFilePath();
const QString legacyJsonPath = QDir(
QStandardPaths::writableLocation(QStandardPaths::AppDataLocation))
.filePath(QStringLiteral("joint_programs.json"));
const QString sourcePath = QFileInfo::exists(filePath)
? filePath : legacyJsonPath;
QFile file(sourcePath);
QString activeGroupName;
if (file.open(QIODevice::ReadOnly)) {
QJsonParseError parseError;
const QJsonDocument document = QJsonDocument::fromJson(file.readAll(), &parseError);
const QJsonObject root = document.object();
activeGroupName = root.value(QStringLiteral("activeGroup")).toString();
const QJsonArray groups = root.value(QStringLiteral("groups")).toArray();
for (const QJsonValue &groupValue : groups) {
const QJsonObject groupObject = groupValue.toObject();
JointProgramGroup group;
group.name = groupObject.value(QStringLiteral("name")).toString().trimmed();
group.flow = groupObject.value(QStringLiteral("flow")).toArray();
group.moveJVelocity = groupObject.value(
QStringLiteral("moveJVelocity")).toDouble(0.1);
group.moveJAcceleration = groupObject.value(
QStringLiteral("moveJAcceleration")).toDouble(0.1);
for (const QJsonValue &pointValue : groupObject.value(QStringLiteral("points")).toArray()) {
const QJsonObject pointObject = pointValue.toObject();
const RecordedJointPoint point=RecordedJointPoint::fromJson(pointObject);
if (!point.name.isEmpty()
&& (point.jointNames.size() == point.positions.size() || !point.arms.isEmpty()))
group.points.append(point);
}
if (!group.name.isEmpty())
m_jointProgramGroups.append(group);
}
if (document.isNull())
appendLog(QStringLiteral("WARN"),
QStringLiteral("点位组 JSON 解析失败:%1").arg(parseError.errorString()));
}
if (m_jointProgramGroups.isEmpty()) {
JointProgramGroup migrated;
migrated.name = QStringLiteral("默认组");
const int pointCount = legacySettings.beginReadArray(QStringLiteral("arm/jointPoints"));
for (int i = 0; i < pointCount; ++i) {
legacySettings.setArrayIndex(i);
RecordedJointPoint point;
point.name = legacySettings.value(QStringLiteral("name")).toString();
point.side = legacySettings.value(QStringLiteral("side")).toString();
point.deviceId = legacySettings.value(QStringLiteral("deviceId")).toString();
point.jointNames = legacySettings.value(QStringLiteral("jointNames")).toStringList();
const QVariantList positions =
legacySettings.value(QStringLiteral("positions")).toList();
for (const QVariant &position : positions)
point.positions.append(position.toDouble());
if (!point.name.isEmpty()
&& point.jointNames.size() == point.positions.size())
migrated.points.append(point);
}
legacySettings.endArray();
const QJsonDocument legacyFlow = QJsonDocument::fromJson(
legacySettings.value(QStringLiteral("arm/jointFlowGraph")).toByteArray());
if (legacyFlow.isArray())
migrated.flow = legacyFlow.array();
m_jointProgramGroups.append(migrated);
activeGroupName = migrated.name;
}
int activeIndex = 0;
for (int i = 0; i < m_jointProgramGroups.size(); ++i) {
if (m_jointProgramGroups.at(i).name == activeGroupName) {
activeIndex = i;
break;
}
}
m_activeJointProgramGroup = activeIndex;
m_updatingJointProgramGroup = true;
if (m_jointProgramGroupCombo) {
m_jointProgramGroupCombo->clear();
for (const JointProgramGroup &group : m_jointProgramGroups)
m_jointProgramGroupCombo->addItem(group.name);
m_jointProgramGroupCombo->setCurrentIndex(activeIndex);
}
m_updatingJointProgramGroup = false;
m_recordedJointPoints = m_jointProgramGroups.at(activeIndex).points;
if (m_jointFlowEditor) {
const QSignalBlocker blocker(m_jointFlowEditor);
m_jointFlowEditor->clear();
m_jointFlowEditor->fromJson(m_jointProgramGroups.at(activeIndex).flow);
}
if (m_jointFlowVelocitySpin)
m_jointFlowVelocitySpin->setValue(
m_jointProgramGroups.at(activeIndex).moveJVelocity);
if (m_jointFlowAccelerationSpin)
m_jointFlowAccelerationSpin->setValue(
m_jointProgramGroups.at(activeIndex).moveJAcceleration);
refreshRecordedJointPoints();
refreshJointFlowTable();
if (!QFileInfo::exists(filePath)) {
saveJointPrograms();
if (QFileInfo::exists(legacyJsonPath))
appendLog(QStringLiteral("INFO"),
QStringLiteral("点位规划数据已迁移到程序目录:%1")
.arg(filePath));
}
}
void MainWindow::saveJointPrograms()
{
storeCurrentJointProgramGroup();
if (m_jointProgramGroups.isEmpty())
return;
QJsonArray groups;
for (const JointProgramGroup &group : m_jointProgramGroups) {
QJsonObject groupObject;
groupObject.insert(QStringLiteral("name"), group.name);
QJsonArray points;
for (const RecordedJointPoint &point : group.points) {
points.append(point.toJson());
}
groupObject.insert(QStringLiteral("points"), points);
groupObject.insert(QStringLiteral("flow"), group.flow);
groupObject.insert(QStringLiteral("moveJVelocity"), group.moveJVelocity);
groupObject.insert(QStringLiteral("moveJAcceleration"), group.moveJAcceleration);
groups.append(groupObject);
}
QJsonObject root;
root.insert(QStringLiteral("version"), 2);
root.insert(QStringLiteral("activeGroup"),
m_jointProgramGroups.at(m_activeJointProgramGroup).name);
root.insert(QStringLiteral("groups"), groups);
const QString filePath = jointProgramsFilePath();
QDir().mkpath(QFileInfo(filePath).absolutePath());
QSaveFile file(filePath);
if (!file.open(QIODevice::WriteOnly)
|| file.write(QJsonDocument(root).toJson(QJsonDocument::Indented)) < 0
|| !file.commit()) {
appendLog(QStringLiteral("ERROR"),
QStringLiteral("点位组保存失败:%1").arg(filePath));
}
}
void MainWindow::setControlsEnabled(bool enabled)
{
refreshArmJogAvailability();
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_moveJVelocitySpin)
m_moveJVelocitySpin->setEnabled(enabled);
if (m_moveJAccelerationSpin)
m_moveJAccelerationSpin->setEnabled(enabled);
if (m_jointFlowVelocitySpin)
m_jointFlowVelocitySpin->setEnabled(enabled && !m_jointPointLoopActive);
if (m_jointFlowAccelerationSpin)
m_jointFlowAccelerationSpin->setEnabled(enabled && !m_jointPointLoopActive);
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());
}