CmvrControlStation/src/mainwindow_ui.cpp

1564 lines
75 KiB
C++
Raw Normal View History

2026-09-18 16:22:20 +08:00
#include "mainwindow.h"
#include "audiostreammanager.h"
#include "robotclient.h"
#include "rpcservicewidget.h"
#include "uiicons.h"
#include "urdfviewerwidget.h"
#include "ui_agvservicepage.h"
#include "ui_agvstatusdialog.h"
#include "ui_audioservicepage.h"
#include "ui_armservicepage.h"
#include "ui_cameraservicepage.h"
#include "ui_diagnosticspage.h"
#include "ui_quicserverpage.h"
#include "ui_systemservicepage.h"
#include <QAbstractItemView>
#include <QAbstractButton>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QDir>
#include <QDialog>
#include <QDoubleSpinBox>
#include <QFileDialog>
#include <QFile>
#include <QFileInfo>
#include <QFrame>
#include <QGraphicsDropShadowEffect>
#include <QGridLayout>
#include <QHeaderView>
#include <QLineEdit>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPushButton>
#include <QPainter>
#include <QRegularExpression>
#include <QSignalBlocker>
#include <QSlider>
#include <QSpinBox>
#include <QSplitter>
#include <QStyledItemDelegate>
#include <QTabWidget>
#include <QTableWidget>
#include <QTextDocument>
#include <QTextEdit>
#include <QTimer>
#include <QVBoxLayout>
#include <QtMath>
namespace {
class FramelessToolDialog final : public QDialog
{
public:
explicit FramelessToolDialog(QWidget *parent = nullptr)
: QDialog(parent, Qt::Tool | Qt::FramelessWindowHint
| Qt::WindowStaysOnTopHint)
{
setAttribute(Qt::WA_TranslucentBackground);
}
void setDragHandle(QWidget *handle)
{
m_dragHandle = handle;
if (!m_dragHandle)
return;
m_dragHandle->installEventFilter(this);
const QList<QWidget *> children = m_dragHandle->findChildren<QWidget *>();
for (QWidget *child : children) {
if (!qobject_cast<QAbstractButton *>(child))
child->installEventFilter(this);
}
}
protected:
bool eventFilter(QObject *watched, QEvent *event) override
{
if (m_dragHandle && event) {
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::LeftButton) {
m_dragging = true;
m_dragOffset = mouseEvent->globalPos() - frameGeometry().topLeft();
return true;
}
} else if (event->type() == QEvent::MouseMove && m_dragging) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->buttons() & Qt::LeftButton) {
move(mouseEvent->globalPos() - m_dragOffset);
return true;
}
} else if (event->type() == QEvent::MouseButtonRelease) {
m_dragging = false;
}
}
return QDialog::eventFilter(watched, event);
}
private:
QWidget *m_dragHandle = nullptr;
QPoint m_dragOffset;
bool m_dragging = false;
};
class AccentRowDelegate final : public QStyledItemDelegate
{
public:
explicit AccentRowDelegate(QObject *parent = nullptr)
: QStyledItemDelegate(parent)
{
}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override
{
QStyleOptionViewItem cleanOption(option);
cleanOption.state &= ~QStyle::State_HasFocus;
QStyledItemDelegate::paint(painter, cleanOption, index);
if ((option.state & QStyle::State_Selected) && index.column() == 0) {
painter->save();
painter->fillRect(QRect(option.rect.left(), option.rect.top(),
3, option.rect.height()),
QColor(QStringLiteral("#237ddd")));
painter->restore();
}
}
};
QStringList armJointNames(bool leftArm)
{
const QString prefix = leftArm ? QStringLiteral("L_") : QStringLiteral("R_");
return {
prefix + QStringLiteral("SHOULDER_P"), prefix + QStringLiteral("SHOULDER_R"),
prefix + QStringLiteral("SHOULDER_Y"), prefix + QStringLiteral("ELBOW_R"),
prefix + QStringLiteral("WRIST_P"), prefix + QStringLiteral("WRIST_Y"),
prefix + QStringLiteral("WRIST_R")
};
}
bool isArmJointForSide(const QString &jointName, bool leftArm)
{
const QString upper = jointName.toUpper();
return leftArm ? (upper.startsWith(QStringLiteral("L_"))
|| upper.contains(QStringLiteral("LEFT")))
: (upper.startsWith(QStringLiteral("R_"))
|| upper.contains(QStringLiteral("RIGHT")));
}
QWidget *withRpcExplorer(QWidget *commonPage, RobotClient *client,
const QString &serviceName)
{
QTabWidget *tabs = new QTabWidget;
tabs->setObjectName(QStringLiteral("serviceTabs"));
tabs->setDocumentMode(true);
tabs->addTab(commonPage, QStringLiteral("常用操作"));
tabs->addTab(new RpcServiceWidget(serviceName, client), QStringLiteral("全部接口"));
return tabs;
}
}
QWidget *MainWindow::createSystemPage()
{
QWidget *page = new QWidget;
Ui::SystemServicePage ui;
ui.setupUi(page);
m_cpuValue = ui.cpuValue;
m_memoryValue = ui.memoryValue;
m_diskValue = ui.diskValue;
m_deviceValue = ui.deviceValue;
m_systemNameValue = ui.systemNameValue;
m_systemVersionValue = ui.systemVersionValue;
m_systemOsValue = ui.systemOsValue;
m_systemTargetEdit = ui.systemTargetEdit;
m_systemRefreshButton = ui.systemRefreshButton;
m_systemStopButton = ui.systemStopButton;
m_systemRefreshButton->setIcon(style()->standardIcon(QStyle::SP_BrowserReload));
m_systemStopButton->setIcon(style()->standardIcon(QStyle::SP_MediaStop));
connect(m_systemRefreshButton, &QPushButton::clicked,
m_client, &RobotClient::requestSystemRefresh);
connect(m_systemStopButton, &QPushButton::clicked, this, [this]() {
m_client->requestSystemStopAll(m_systemTargetEdit->text().trimmed());
});
m_serviceButtons << m_systemRefreshButton << m_systemStopButton;
return withRpcExplorer(page, m_client, QStringLiteral("cmvr.api.SystemService"));
}
QWidget *MainWindow::createArmPage()
{
QWidget *page = new QWidget;
Ui::ArmServicePage ui;
ui.setupUi(page);
m_armHeaderControls = new QWidget(this);
m_armHeaderControls->setObjectName(QStringLiteral("armHeaderControls"));
QHBoxLayout *armHeaderLayout = new QHBoxLayout(m_armHeaderControls);
armHeaderLayout->setContentsMargins(0, 0, 0, 0);
armHeaderLayout->setSpacing(8);
ui.armDeviceLabel->hide();
ui.armIdEdit->setParent(m_armHeaderControls);
ui.armTelemetryButton->setParent(m_armHeaderControls);
m_armSideCombo = new QComboBox(m_armHeaderControls);
m_armSideCombo->setObjectName(QStringLiteral("armSideCombo"));
m_armSideCombo->addItem(QStringLiteral("右臂"), QStringLiteral("right"));
m_armSideCombo->addItem(QStringLiteral("左臂"), QStringLiteral("left"));
m_armSideCombo->setFixedWidth(92);
m_armSideCombo->setToolTip(QStringLiteral("选择当前控制和遥测的机械臂"));
ui.armIdEdit->setMinimumWidth(172);
ui.armIdEdit->setMaximumWidth(172);
ui.armIdEdit->setFixedWidth(172);
ui.armTelemetryButton->setObjectName(QStringLiteral("armTelemetryStatus"));
ui.armTelemetryButton->setText(QStringLiteral("遥测 未启动"));
ui.armTelemetryButton->setIcon(UiIcons::icon(
QStringLiteral(":/icons/activity.svg"),
QColor(QStringLiteral("#62706b")), QColor(QStringLiteral("#177553")),
QColor(QStringLiteral("#9aa3ad")), 15));
ui.armTelemetryButton->setIconSize(QSize(15, 15));
ui.armTelemetryButton->setFixedWidth(136);
armHeaderLayout->addWidget(m_armSideCombo);
armHeaderLayout->addWidget(ui.armIdEdit);
armHeaderLayout->addWidget(ui.armTelemetryButton);
m_armGlobalStopButton = new QPushButton(QStringLiteral("全局停止"), m_armHeaderControls);
m_armGlobalStopButton->setObjectName(QStringLiteral("dangerButton"));
m_armGlobalStopButton->setIcon(UiIcons::icon(
QStringLiteral(":/icons/octagon-x.svg"), Qt::white, Qt::white,
QColor(QStringLiteral("#f4dddd")), 16));
m_armGlobalStopButton->setIconSize(QSize(16, 16));
m_armGlobalStopButton->setFixedWidth(110);
m_armGlobalStopButton->setToolTip(QStringLiteral("调用 SystemService.stopAll"));
armHeaderLayout->addWidget(m_armGlobalStopButton);
if (m_headerLayout)
m_headerLayout->insertWidget(2, m_armHeaderControls);
ui.serviceHeader->hide();
const int modelTabIndex = ui.armTabs->indexOf(ui.urdfTab);
if (modelTabIndex >= 0) {
ui.armTabs->removeTab(modelTabIndex);
ui.armTabs->insertTab(0, ui.urdfTab, QStringLiteral("模型与控制"));
}
// Keep device safety controls, the model, MoveJ targets and teaching in one workspace.
ui.commandPanel->setParent(ui.urdfTab);
ui.urdfTabLayout->insertWidget(0, ui.commandPanel);
QSplitter *modelMotionWorkspace = new QSplitter(Qt::Vertical, ui.urdfTab);
modelMotionWorkspace->setObjectName(QStringLiteral("armModelMotionSplitter"));
modelMotionWorkspace->setChildrenCollapsible(false);
modelMotionWorkspace->setHandleWidth(8);
ui.urdfTabLayout->removeWidget(ui.urdfViewer);
modelMotionWorkspace->addWidget(ui.urdfViewer);
modelMotionWorkspace->addWidget(ui.targetsPanel);
modelMotionWorkspace->setStretchFactor(0, 5);
modelMotionWorkspace->setStretchFactor(1, 4);
modelMotionWorkspace->setSizes({500, 350});
ui.targetsPanel->setMinimumHeight(360);
ui.targetsPanel->setMaximumHeight(440);
ui.urdfTabLayout->insertWidget(1, modelMotionWorkspace, 1);
ui.urdfTabLayout->setStretch(0, 0);
ui.urdfTabLayout->setStretch(1, 1);
QWidget *telemetryTab = new QWidget;
QVBoxLayout *telemetryTabLayout = new QVBoxLayout(telemetryTab);
telemetryTabLayout->setContentsMargins(0, 0, 0, 0);
ui.telemetryPanel->setParent(telemetryTab);
telemetryTabLayout->addWidget(ui.telemetryPanel);
const int commandTabIndex = ui.armTabs->indexOf(ui.jointControlTab);
if (commandTabIndex >= 0) {
ui.armTabs->removeTab(commandTabIndex);
ui.jointControlTab->hide();
}
ui.armTabs->addTab(telemetryTab, QStringLiteral("实时状态"));
ui.armTabs->addTab(new RpcServiceWidget(QStringLiteral("cmvr.api.ArmService"), m_client),
QStringLiteral("全部接口"));
ui.armTabs->setCurrentWidget(ui.urdfTab);
m_armIdEdit = ui.armIdEdit;
m_armTelemetryButton = ui.armTelemetryButton;
m_armDeviceSummary = ui.commandSubtitle;
m_servoStatusValue = ui.servoStatusValue;
m_faultStatusValue = ui.faultStatusValue;
m_velocitySpin = ui.velocitySpin;
m_accelerationSpin = ui.accelerationSpin;
m_torqueOnButton = ui.torqueOnButton;
m_torqueOffButton = ui.torqueOffButton;
m_clearFaultButton = ui.clearFaultButton;
m_zeroJointCombo = ui.zeroJointCombo;
m_calibrateZeroButton = ui.calibrateZeroButton;
m_stopButton = ui.stopButton;
m_motionTable = ui.motionTable;
m_sendMoveButton = ui.sendMoveButton;
m_jointTable = ui.jointTable;
m_poseValue = ui.poseValue;
m_updatedValue = ui.updatedValue;
m_urdfViewer = ui.urdfViewer;
m_teachModeButton = ui.teachModeButton;
m_teachRestoreButton = ui.teachRestoreButton;
m_teachSendButton = ui.teachSendButton;
m_teachSelectedLabel = ui.teachSelectedLabel;
m_teachPositionSpin = ui.teachPositionSpin;
m_teachJointTable = ui.teachJointTable;
ui.jointTitle->setContentsMargins(16, 0, 0, 4);
m_motionCommandTabs = new QTabWidget(ui.targetsPanel);
m_motionCommandTabs->setObjectName(QStringLiteral("armMotionCommandTabs"));
m_motionCommandTabs->setDocumentMode(true);
QWidget *moveJPage = new QWidget(m_motionCommandTabs);
QVBoxLayout *moveJLayout = new QVBoxLayout(moveJPage);
moveJLayout->setContentsMargins(0, 0, 0, 0);
QSplitter *armTargetTables = new QSplitter(Qt::Horizontal, moveJPage);
armTargetTables->setObjectName(QStringLiteral("armTargetTables"));
armTargetTables->setChildrenCollapsible(false);
QWidget *leftTargets = new QWidget(armTargetTables);
QVBoxLayout *leftTargetsLayout = new QVBoxLayout(leftTargets);
leftTargetsLayout->setContentsMargins(0, 4, 6, 0);
QLabel *leftTargetsTitle = new QLabel(QStringLiteral("左臂 · eyou_left_arm"), leftTargets);
leftTargetsTitle->setObjectName(QStringLiteral("eyebrow"));
m_leftMotionTable = new QTableWidget(7, 4, leftTargets);
m_leftMotionTable->setObjectName(QStringLiteral("leftMotionTable"));
leftTargetsLayout->addWidget(leftTargetsTitle);
leftTargetsLayout->addWidget(m_leftMotionTable);
QWidget *rightTargets = new QWidget(armTargetTables);
QVBoxLayout *rightTargetsLayout = new QVBoxLayout(rightTargets);
rightTargetsLayout->setContentsMargins(6, 4, 0, 0);
QLabel *rightTargetsTitle = new QLabel(QStringLiteral("右臂 · eyou_right_arm"), rightTargets);
rightTargetsTitle->setObjectName(QStringLiteral("eyebrow"));
m_motionTable->setParent(rightTargets);
rightTargetsLayout->addWidget(rightTargetsTitle);
rightTargetsLayout->addWidget(m_motionTable);
armTargetTables->addWidget(leftTargets);
armTargetTables->addWidget(rightTargets);
armTargetTables->setSizes({500, 500});
moveJLayout->addWidget(armTargetTables);
m_motionCommandTabs->addTab(moveJPage, QStringLiteral("MoveJ 关节角"));
QWidget *moveLPage = new QWidget(m_motionCommandTabs);
QVBoxLayout *moveLLayout = new QVBoxLayout(moveLPage);
moveLLayout->setContentsMargins(16, 10, 16, 8);
moveLLayout->setSpacing(10);
QGridLayout *poseGrid = new QGridLayout;
poseGrid->setHorizontalSpacing(12);
poseGrid->setVerticalSpacing(8);
const QStringList poseLabels = {
QStringLiteral("X"), QStringLiteral("Y"), QStringLiteral("Z"),
QStringLiteral("RX"), QStringLiteral("RY"), QStringLiteral("RZ")
};
for (int i = 0; i < poseLabels.size(); ++i) {
QWidget *field = new QWidget(moveLPage);
QVBoxLayout *fieldLayout = new QVBoxLayout(field);
fieldLayout->setContentsMargins(0, 0, 0, 0);
fieldLayout->setSpacing(4);
QLabel *label = new QLabel(poseLabels.at(i), field);
label->setObjectName(QStringLiteral("eyebrow"));
QDoubleSpinBox *spin = new QDoubleSpinBox(field);
spin->setObjectName(QStringLiteral("moveJPoseSpin"));
spin->setDecimals(4);
spin->setRange(i < 3 ? -10.0 : -6.2832, i < 3 ? 10.0 : 6.2832);
spin->setSingleStep(i < 3 ? 0.01 : 0.05);
spin->setSuffix(i < 3 ? QStringLiteral(" m") : QStringLiteral(" rad"));
spin->setMinimumHeight(36);
fieldLayout->addWidget(label);
fieldLayout->addWidget(spin);
poseGrid->addWidget(field, i / 3, i % 3);
m_moveJPoseSpins.append(spin);
}
moveLLayout->addLayout(poseGrid);
QHBoxLayout *moveLOptions = new QHBoxLayout;
moveLOptions->setSpacing(8);
QLabel *frameLabel = new QLabel(QStringLiteral("服务端基坐标系"), moveLPage);
frameLabel->setObjectName(QStringLiteral("eyebrow"));
m_moveJPoseBaseLinkCombo = new QComboBox(moveLPage);
m_moveJPoseBaseLinkCombo->setEditable(false);
m_moveJPoseBaseLinkCombo->addItem(QStringLiteral("PELVIS_S"));
m_copyCurrentPoseButton = new QPushButton(
UiIcons::icon(QStringLiteral(":/icons/copy.svg")), QStringLiteral("填入当前位姿"),
moveLPage);
moveLOptions->addWidget(frameLabel);
moveLOptions->addWidget(m_moveJPoseBaseLinkCombo);
moveLOptions->addStretch(1);
moveLOptions->addWidget(m_copyCurrentPoseButton);
moveLLayout->addLayout(moveLOptions);
m_motionCommandTabs->addTab(moveLPage, QStringLiteral("MoveL 末端位姿"));
ui.targetsLayout->removeWidget(m_motionTable);
ui.targetsLayout->insertWidget(1, m_motionCommandTabs, 1);
m_torqueOnButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/power.svg")));
m_torqueOffButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/power-off.svg")));
m_clearFaultButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/shield-check.svg")));
m_calibrateZeroButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/crosshair.svg")));
m_stopButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/square.svg"), Qt::white,
Qt::white, QColor(QStringLiteral("#f4dddd"))));
m_sendMoveButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/send.svg"), Qt::white,
Qt::white, QColor(QStringLiteral("#e8eef5"))));
m_teachModeButton->setIcon(UiIcons::icon(
QStringLiteral(":/icons/hand.svg"), QColor(QStringLiteral("#46535f")),
QColor(QStringLiteral("#155dcc"))));
m_teachRestoreButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/rotate-ccw.svg")));
m_teachSendButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/send.svg"), Qt::white,
Qt::white, QColor(QStringLiteral("#e8eef5"))));
// The MoveJ table already presents every joint target. Keep teaching as a
// mode of the model workspace instead of duplicating the joint list in a
// separate side panel.
ui.teachModeLayout->removeWidget(m_teachModeButton);
ui.teachModeLayout->removeWidget(m_teachRestoreButton);
m_teachModeButton->setParent(ui.targetsPanel);
m_teachRestoreButton->setParent(ui.targetsPanel);
m_teachRestoreButton->setText(QStringLiteral("恢复实际姿态"));
const int zeroButtonIndex = ui.targetsHeader->indexOf(ui.zeroButton);
ui.targetsHeader->insertWidget(zeroButtonIndex, m_teachModeButton);
ui.targetsHeader->insertWidget(zeroButtonIndex + 1, m_teachRestoreButton);
m_teachModeButton->show();
m_teachRestoreButton->show();
ui.urdfTabLayout->removeWidget(ui.teachPanel);
ui.teachPanel->hide();
m_stopButton->setMinimumWidth(136);
m_stopButton->setParent(ui.targetsPanel);
ui.targetsFooter->insertWidget(ui.targetsFooter->count() - 1, m_stopButton);
connect(m_armIdEdit, &QLineEdit::textChanged, m_armDeviceSummary,
&QLabel::setText);
connect(m_armGlobalStopButton, &QPushButton::clicked, this, [this]() {
const QString target = m_armIdEdit->text().trimmed();
m_client->requestSystemStopAll(target.isEmpty() ? QStringLiteral("*") : target);
});
connect(m_armTelemetryButton, &QPushButton::clicked, this, [this](bool enabled) {
const QString deviceId = m_armIdEdit->text().trimmed();
if (enabled && deviceId.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("ArmService"),
QStringLiteral("请先填写机械臂设备 ID。"));
m_armTelemetryButton->setChecked(false);
return;
}
m_armTelemetryButton->setText(enabled ? QStringLiteral("遥测 10 Hz")
: QStringLiteral("遥测 未启动"));
m_armTelemetryButton->setProperty("active", enabled);
m_armTelemetryButton->style()->unpolish(m_armTelemetryButton);
m_armTelemetryButton->style()->polish(m_armTelemetryButton);
m_armIdEdit->setEnabled(!enabled);
m_client->setArmTelemetry(deviceId, enabled);
});
connect(m_torqueOnButton, &QPushButton::clicked, this, [this]() {
m_client->requestTorque(m_armIdEdit->text().trimmed(), true);
});
connect(m_torqueOffButton, &QPushButton::clicked, this, [this]() {
m_client->requestTorque(m_armIdEdit->text().trimmed(), false);
});
connect(m_clearFaultButton, &QPushButton::clicked, this, [this]() {
m_client->requestArmClearFault(m_armIdEdit->text().trimmed());
});
connect(m_calibrateZeroButton, &QPushButton::clicked, this, [this]() {
const QString deviceId = m_armIdEdit->text().trimmed();
const QString jointName = m_zeroJointCombo->currentText().trimmed();
if (deviceId.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("零位标定"),
QStringLiteral("请先填写机械臂设备 ID。"));
return;
}
if (jointName.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("零位标定"),
QStringLiteral("请选择需要设置零位的关节。"));
return;
}
const QString prompt = QStringLiteral(
"即将把设备 %1 的关节 %2 当前位置设置为零位。\n\n"
"该操作会改变关节坐标基准,是否继续?")
.arg(deviceId, jointName);
if (QMessageBox::warning(this, QStringLiteral("确认零位标定"), prompt,
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel) != QMessageBox::Yes) {
return;
}
m_client->requestArmCalibrateZero(deviceId, jointName);
});
connect(m_stopButton, &QPushButton::clicked, this, [this]() {
m_client->requestArmStop(m_armIdEdit->text().trimmed());
});
connect(ui.zeroButton, &QPushButton::clicked, this, [this]() {
const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left");
const int offset = leftArm ? 0 : 7;
for (int i = 0; i < 7 && offset + i < m_targetSpins.size(); ++i)
m_targetSpins.at(offset + i)->setValue(0.0);
});
connect(m_sendMoveButton, &QPushButton::clicked, this, [this]() {
if (m_motionCommandTabs && m_motionCommandTabs->currentIndex() == 1)
sendMoveJPose();
else
sendMoveJ();
});
connect(m_copyCurrentPoseButton, &QPushButton::clicked, this, [this]() {
if (m_latestArmPose.isEmpty()) {
QMessageBox::information(this, QStringLiteral("MoveL"),
QStringLiteral("尚未收到当前机械臂的末端位姿,请先开启遥测。"));
return;
}
static const QStringList keys = {
QStringLiteral("x"), QStringLiteral("y"), QStringLiteral("z"),
QStringLiteral("rx"), QStringLiteral("ry"), QStringLiteral("rz")
};
for (int i = 0; i < keys.size() && i < m_moveJPoseSpins.size(); ++i)
m_moveJPoseSpins.at(i)->setValue(m_latestArmPose.value(keys.at(i)).toDouble());
});
connect(m_motionCommandTabs, &QTabWidget::currentChanged, this,
[this, targetsTitle = ui.targetsTitle, targetsSubtitle = ui.targetsSubtitle,
zeroButton = ui.zeroButton](int index) {
const bool moveJ = index == 0;
targetsTitle->setText(moveJ ? QStringLiteral("MoveJ 关节目标")
: QStringLiteral("MoveL 末端位姿目标"));
targetsSubtitle->setText(moveJ
? QStringLiteral("目标以度输入,发送时转换为弧度;示教模式下与模型同步")
: QStringLiteral("服务端按笛卡尔直线轨迹执行 MoveL"));
m_sendMoveButton->setText(moveJ ? QStringLiteral("发送 MoveJ")
: QStringLiteral("发送 MoveL"));
m_velocitySpin->setSuffix(moveJ ? QStringLiteral(" rad/s")
: QStringLiteral(" m/s"));
m_accelerationSpin->setSuffix(moveJ ? QStringLiteral(" rad/s²")
: QStringLiteral(" m/s²"));
m_teachModeButton->setVisible(moveJ);
m_teachRestoreButton->setVisible(moveJ);
zeroButton->setVisible(moveJ);
if (!moveJ && m_teachModeButton->isChecked())
m_teachModeButton->setChecked(false);
});
connect(m_urdfViewer, &UrdfViewerWidget::logMessage,
this, &MainWindow::appendLog);
const auto configureMotionTable = [](QTableWidget *table) {
table->setHorizontalHeaderLabels({QStringLiteral("关节"), QStringLiteral("当前"),
QStringLiteral("目标角度"), QStringLiteral("目标弧度")});
table->setAlternatingRowColors(true);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::SingleSelection);
table->setShowGrid(false);
table->verticalHeader()->setVisible(false);
table->verticalHeader()->setDefaultSectionSize(32);
table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
};
configureMotionTable(m_leftMotionTable);
configureMotionTable(m_motionTable);
m_jointTable->setHorizontalHeaderLabels({QStringLiteral("关节"), QStringLiteral("位置 rad"),
QStringLiteral("速度 rad/s"), QStringLiteral("负载")});
m_jointTable->setAlternatingRowColors(true);
m_jointTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_jointTable->setSelectionMode(QAbstractItemView::NoSelection);
m_jointTable->verticalHeader()->setVisible(false);
m_jointTable->verticalHeader()->setDefaultSectionSize(28);
m_jointTable->horizontalHeader()->setStretchLastSection(true);
m_targetSpins.clear();
const auto populateMotionTable = [this](QTableWidget *table, bool leftArm) {
const QStringList jointNames = armJointNames(leftArm);
table->clearContents();
table->setRowCount(jointNames.size());
for (int row = 0; row < jointNames.size(); ++row) {
const QString jointName = jointNames.at(row);
table->setItem(row, 0, new QTableWidgetItem(jointName));
table->setItem(row, 1, new QTableWidgetItem(QStringLiteral("--")));
QDoubleSpinBox *target = new QDoubleSpinBox(table);
target->setRange(-180.0, 180.0);
target->setDecimals(3);
target->setSingleStep(1.0);
target->setSuffix(QStringLiteral(" °"));
target->setFrame(false);
target->setEnabled(m_connected);
m_targetSpins.append(target);
table->setCellWidget(row, 2, target);
QTableWidgetItem *radians = new QTableWidgetItem(QStringLiteral("0.000000"));
radians->setFlags(radians->flags() & ~Qt::ItemIsEditable);
table->setItem(row, 3, radians);
connect(target, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
[this, table, row, jointName](double degrees) {
if (row < table->rowCount() && table->item(row, 3))
table->item(row, 3)->setText(
QString::number(qDegreesToRadians(degrees), 'f', 6));
if (m_teachModeButton->isChecked())
m_urdfViewer->setTeachingJointPosition(
jointName, qDegreesToRadians(degrees));
});
}
};
populateMotionTable(m_leftMotionTable, true);
populateMotionTable(m_motionTable, false);
const QStringList allJointNames = armJointNames(true) + armJointNames(false);
m_jointTable->clearContents();
m_jointTable->setRowCount(allJointNames.size());
for (int row = 0; row < allJointNames.size(); ++row) {
m_jointTable->setItem(row, 0, new QTableWidgetItem(allJointNames.at(row)));
for (int column = 1; column < 4; ++column)
m_jointTable->setItem(row, column, new QTableWidgetItem(QStringLiteral("--")));
}
const auto refreshActiveArmControls = [this]() {
const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left");
m_activeArmJointNames = armJointNames(leftArm);
QStringList zeroJointNames;
const QStringList urdfNames = m_urdfViewer->jointNames();
for (const QString &name : urdfNames) {
if (isArmJointForSide(name, leftArm))
zeroJointNames.append(name);
}
if (zeroJointNames.isEmpty())
zeroJointNames = m_activeArmJointNames;
const QString selectedJoint = m_zeroJointCombo->currentText();
const QSignalBlocker blocker(m_zeroJointCombo);
m_zeroJointCombo->clear();
m_zeroJointCombo->addItems(zeroJointNames);
const int selectedIndex = m_zeroJointCombo->findText(selectedJoint);
if (selectedIndex >= 0)
m_zeroJointCombo->setCurrentIndex(selectedIndex);
m_zeroJointCombo->setEnabled(!zeroJointNames.isEmpty());
m_calibrateZeroButton->setEnabled(m_connected && !zeroJointNames.isEmpty());
};
refreshActiveArmControls();
connect(m_armSideCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
[this, refreshActiveArmControls, poseSubtitle = ui.poseSubtitle](int) {
const QString oldDeviceId = m_armIdEdit->text().trimmed();
const bool telemetryRunning = m_armTelemetryButton->isChecked();
if (telemetryRunning)
m_client->setArmTelemetry(oldDeviceId, false);
const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left");
m_armIdEdit->setText(leftArm ? QStringLiteral("eyou_left_arm")
: QStringLiteral("eyou_right_arm"));
m_latestArmPose.clear();
m_poseValue->setText(QStringLiteral("X --\nY --\nZ --\n\nRX --\nRY --\nRZ --"));
poseSubtitle->setText(leftArm ? QStringLiteral("PELVIS_S → L_FINGER_TIP")
: QStringLiteral("PELVIS_S → R_FINGER_TIP"));
refreshActiveArmControls();
if (m_teachModeButton->isChecked() && !m_activeArmJointNames.isEmpty())
m_urdfViewer->selectTeachingJoint(m_activeArmJointNames.first());
if (telemetryRunning)
m_client->setArmTelemetry(m_armIdEdit->text().trimmed(), true);
});
connect(m_urdfViewer, &UrdfViewerWidget::modelLoaded, this,
[this, refreshActiveArmControls](const QString &, int, int) {
refreshActiveArmControls();
m_teachModeButton->setEnabled(!m_urdfViewer->jointNames().isEmpty());
});
connect(m_teachModeButton, &QPushButton::toggled, this, [this](bool enabled) {
m_urdfViewer->setTeachingEnabled(enabled);
if (enabled && !m_activeArmJointNames.isEmpty())
m_urdfViewer->selectTeachingJoint(m_activeArmJointNames.first());
});
connect(m_urdfViewer, &UrdfViewerWidget::teachingModeChanged, this,
[this](bool enabled) {
const QSignalBlocker blocker(m_teachModeButton);
m_teachModeButton->setChecked(enabled);
m_teachModeButton->setText(enabled ? QStringLiteral("退出示教")
: QStringLiteral("示教模式"));
m_teachRestoreButton->setEnabled(enabled);
if (!enabled) {
m_teachSelectedJoint.clear();
m_leftMotionTable->clearSelection();
m_motionTable->clearSelection();
}
});
connect(m_urdfViewer, &UrdfViewerWidget::teachingJointSelected, this,
[this](const QString &jointName, double, double, double) {
const int row = m_activeArmJointNames.indexOf(jointName);
if (row < 0) {
if (!m_activeArmJointNames.isEmpty())
m_urdfViewer->selectTeachingJoint(m_activeArmJointNames.first());
return;
}
m_teachSelectedJoint = jointName;
const int zeroIndex = m_zeroJointCombo->findText(jointName);
if (zeroIndex >= 0)
m_zeroJointCombo->setCurrentIndex(zeroIndex);
const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left");
(leftArm ? m_leftMotionTable : m_motionTable)->selectRow(row);
});
connect(m_urdfViewer, &UrdfViewerWidget::teachingPositionsChanged, this,
[this](const QHash<QString, double> &positions) {
for (int side = 0; side < 2; ++side) {
const bool leftArm = side == 0;
QTableWidget *table = leftArm ? m_leftMotionTable : m_motionTable;
const QStringList names = armJointNames(leftArm);
const int offset = leftArm ? 0 : 7;
for (int row = 0; row < names.size() && offset + row < m_targetSpins.size(); ++row) {
if (!positions.contains(names.at(row)))
continue;
const double radians = positions.value(names.at(row));
const QSignalBlocker blocker(m_targetSpins.at(offset + row));
m_targetSpins.at(offset + row)->setValue(qRadiansToDegrees(radians));
table->item(row, 3)->setText(QString::number(radians, 'f', 6));
}
}
});
connect(m_teachRestoreButton, &QPushButton::clicked,
m_urdfViewer, &UrdfViewerWidget::restoreTeachingFromTelemetry);
const auto connectMotionTable = [this](QTableWidget *table, bool leftArm) {
connect(table, &QTableWidget::cellClicked, this,
[this, leftArm](int row, int) {
const int sideIndex = m_armSideCombo->findData(
leftArm ? QStringLiteral("left") : QStringLiteral("right"));
if (sideIndex >= 0 && sideIndex != m_armSideCombo->currentIndex())
m_armSideCombo->setCurrentIndex(sideIndex);
const QStringList names = armJointNames(leftArm);
if (m_teachModeButton->isChecked() && row >= 0 && row < names.size())
m_urdfViewer->selectTeachingJoint(names.at(row));
});
};
connectMotionTable(m_leftMotionTable, true);
connectMotionTable(m_motionTable, false);
m_serviceButtons << m_armTelemetryButton << m_armGlobalStopButton
<< m_torqueOnButton << m_torqueOffButton
<< m_clearFaultButton << m_calibrateZeroButton
<< m_stopButton << m_sendMoveButton;
return page;
}
QStringList MainWindow::configuredCameraIds() const
{
if (!m_cameraIdEdit)
return {};
const QStringList values = m_cameraIdEdit->text().split(
QRegularExpression(QStringLiteral("[,;\\s]+")), QString::SkipEmptyParts);
QStringList result;
QSet<QString> seen;
for (const QString &value : values) {
const QString cameraId = value.trimmed();
if (!cameraId.isEmpty() && !seen.contains(cameraId)) {
seen.insert(cameraId);
result.append(cameraId);
}
}
return result;
}
void MainWindow::rebuildCameraPreviewGrid(const QStringList &cameraIds)
{
if (!m_cameraPreviewGrid || !m_cameraPreviewContainer)
return;
QSet<QString> requested;
for (const QString &cameraId : cameraIds)
requested.insert(cameraId);
const QStringList existingIds = m_cameraPreviewTiles.keys();
for (const QString &cameraId : existingIds) {
if (requested.contains(cameraId))
continue;
CameraPreviewTile tile = m_cameraPreviewTiles.take(cameraId);
m_cameraPreviewGrid->removeWidget(tile.container);
delete tile.container;
}
for (const QString &cameraId : cameraIds) {
if (m_cameraPreviewTiles.contains(cameraId))
continue;
CameraPreviewTile tile;
QFrame *container = new QFrame(m_cameraPreviewContainer);
container->setObjectName(QStringLiteral("cameraPreviewTile"));
container->setFrameShape(QFrame::StyledPanel);
QVBoxLayout *layout = new QVBoxLayout(container);
layout->setContentsMargins(8, 8, 8, 8);
layout->setSpacing(6);
QHBoxLayout *header = new QHBoxLayout;
QLabel *title = new QLabel(cameraId, container);
title->setObjectName(QStringLiteral("sectionTitle"));
QLabel *status = new QLabel(QStringLiteral("已停止"), container);
status->setObjectName(QStringLiteral("panelSubtitle"));
header->addWidget(title);
header->addStretch(1);
header->addWidget(status);
VideoRenderWidget *render = new VideoRenderWidget(container);
render->setObjectName(QStringLiteral("imageView"));
render->setMinimumSize(280, 180);
render->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
render->clearFrame(QStringLiteral("等待视频流"));
QLabel *meta = new QLabel(QStringLiteral("等待连接"), container);
meta->setObjectName(QStringLiteral("panelSubtitle"));
meta->setTextInteractionFlags(Qt::TextSelectableByMouse);
layout->addLayout(header);
layout->addWidget(render, 1);
layout->addWidget(meta);
tile.container = container;
tile.render = render;
tile.status = status;
tile.meta = meta;
m_cameraPreviewTiles.insert(cameraId, tile);
}
for (const QString &cameraId : cameraIds)
m_cameraPreviewGrid->removeWidget(m_cameraPreviewTiles.value(cameraId).container);
const int columns = cameraIds.size() <= 1 ? 1 : 2;
for (int index = 0; index < cameraIds.size(); ++index) {
CameraPreviewTile &tile = m_cameraPreviewTiles[cameraIds.at(index)];
m_cameraPreviewGrid->addWidget(tile.container, index / columns, index % columns);
}
for (int column = 0; column < 2; ++column)
m_cameraPreviewGrid->setColumnStretch(column, column < columns ? 1 : 0);
m_videoRender = cameraIds.isEmpty()
? nullptr : m_cameraPreviewTiles.value(cameraIds.first()).render;
}
void MainWindow::refreshCameraStreamControls()
{
m_cameraStreaming = !m_runningCameraIds.isEmpty();
m_cameraStreamButton->setEnabled(m_connected);
m_cameraStreamButton->setText(m_cameraStreaming ? QStringLiteral("停止全部预览")
: QStringLiteral("开始预览"));
m_cameraStreamButton->setIcon(style()->standardIcon(
m_cameraStreaming ? QStyle::SP_MediaStop : QStyle::SP_MediaPlay));
m_cameraStreamButton->setObjectName(m_cameraStreaming
? QStringLiteral("dangerButton") : QStringLiteral("primaryButton"));
m_cameraStreamButton->style()->unpolish(m_cameraStreamButton);
m_cameraStreamButton->style()->polish(m_cameraStreamButton);
m_cameraIdEdit->setEnabled(!m_cameraStreaming && !m_cameraRecording);
m_cameraCodecCombo->setEnabled(!m_cameraStreaming);
m_cameraStreamModeCombo->setEnabled(!m_cameraStreaming);
m_snapshotButton->setEnabled(m_connected && !m_cameraStreaming);
m_cameraStreamStateLabel->setText(m_cameraStreaming
? QStringLiteral("%1 路播放中").arg(m_runningCameraIds.size())
: QStringLiteral("已停止"));
}
QWidget *MainWindow::createCameraPage()
{
QWidget *page = new QWidget;
Ui::CameraServicePage ui;
ui.setupUi(page);
m_imageMetaLabel = ui.imageMetaLabel;
m_saveImageButton = ui.saveImageButton;
ui.viewerLayout->removeWidget(ui.imageLabel);
ui.imageLabel->hide();
ui.imageLabel->deleteLater();
m_videoRender = nullptr;
m_cameraPreviewContainer = new QWidget(page);
m_cameraPreviewGrid = new QGridLayout(m_cameraPreviewContainer);
m_cameraPreviewGrid->setContentsMargins(0, 0, 0, 0);
m_cameraPreviewGrid->setSpacing(10);
ui.viewerLayout->addWidget(m_cameraPreviewContainer, 1);
m_cameraIdEdit = ui.cameraIdEdit;
m_snapshotButton = ui.snapshotButton;
m_cameraStreamButton = ui.cameraStreamButton;
m_cameraCodecCombo = ui.codecCombo;
m_cameraStreamModeCombo = ui.streamModeCombo;
// Qt 5.12's uic does not preserve QComboBox item userData from this UI
// file, so set the protocol values explicitly before reading currentData().
m_cameraStreamModeCombo->setItemData(0, QStringLiteral("rgb"));
m_cameraStreamModeCombo->setItemData(1, QStringLiteral("depth"));
m_cameraStreamModeCombo->setItemData(2, QStringLiteral("rgbd"));
m_cameraStreamStateLabel = ui.cameraStreamStateLabel;
m_cameraRecordPathEdit = ui.recordPathEdit;
m_cameraRecordButton = ui.cameraRecordButton;
m_cameraRecordStateLabel = ui.cameraRecordStateLabel;
m_saveImageButton->setIcon(style()->standardIcon(QStyle::SP_DialogSaveButton));
m_snapshotButton->setIcon(style()->standardIcon(QStyle::SP_DialogOpenButton));
m_cameraStreamButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
m_cameraRecordButton->setIcon(style()->standardIcon(QStyle::SP_DialogSaveButton));
connect(m_saveImageButton, &QPushButton::clicked, this, &MainWindow::saveSnapshot);
connect(m_snapshotButton, &QPushButton::clicked, this, [this]() {
const QStringList cameraIds = configuredCameraIds();
if (!cameraIds.isEmpty())
m_client->requestSnapshot(cameraIds.first());
});
connect(m_cameraCodecCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, [this](int index) {
const QString codec = index == 1 ? QStringLiteral("h265") : QStringLiteral("h264");
m_client->setCameraStreamCodec(codec);
if (m_cameraStreaming) {
m_cameraStreamStateLabel->setText(
QStringLiteral("切换至 %1,等待关键帧")
.arg(index == 1 ? QStringLiteral("H.265") : QStringLiteral("H.264")));
}
});
connect(m_cameraIdEdit, &QLineEdit::editingFinished, this, [this]() {
if (!m_cameraStreaming)
rebuildCameraPreviewGrid(configuredCameraIds());
});
connect(m_cameraStreamButton, &QPushButton::clicked, this, [this]() {
if (m_cameraStreaming) {
m_cameraStreamButton->setEnabled(false);
m_cameraStreamButton->setText(QStringLiteral("正在停止..."));
m_client->stopCameraStream();
} else {
const QStringList cameraIds = configuredCameraIds();
if (cameraIds.isEmpty()) {
appendLog(QStringLiteral("WARN"),
QStringLiteral("请至少填写一个摄像头设备 ID"));
return;
}
saveSettings();
rebuildCameraPreviewGrid(cameraIds);
const QString codec = m_cameraCodecCombo->currentIndex() == 1
? QStringLiteral("h265") : QStringLiteral("h264");
const QString mode = m_cameraStreamModeCombo->currentData().toString().isEmpty()
? QStringLiteral("rgb") : m_cameraStreamModeCombo->currentData().toString();
for (const QString &cameraId : cameraIds)
m_client->startCameraStream(cameraId, codec, mode);
}
});
connect(m_cameraRecordButton, &QPushButton::clicked, this, [this]() {
m_cameraRecordButton->setEnabled(false);
if (m_cameraRecording) {
m_cameraRecordButton->setText(QStringLiteral("正在停止..."));
const QStringList cameraIds = configuredCameraIds();
if (!cameraIds.isEmpty())
m_client->stopCameraRecording(cameraIds.first());
} else {
const QString path = m_cameraRecordPathEdit->text().trimmed();
if (path.isEmpty()) {
m_cameraRecordButton->setEnabled(m_connected);
appendLog(QStringLiteral("WARN"), QStringLiteral("请填写服务端录像保存路径"));
return;
}
saveSettings();
m_cameraRecordButton->setText(QStringLiteral("正在启动..."));
const QStringList cameraIds = configuredCameraIds();
if (cameraIds.isEmpty()) {
m_cameraRecordButton->setEnabled(m_connected);
appendLog(QStringLiteral("WARN"),
QStringLiteral("请先填写摄像头设备 ID"));
return;
}
m_client->startCameraRecording(cameraIds.first(), path);
}
});
rebuildCameraPreviewGrid(configuredCameraIds());
m_serviceButtons << m_snapshotButton << m_cameraStreamButton << m_cameraRecordButton;
return withRpcExplorer(page, m_client, QStringLiteral("cmvr.api.CameraService"));
}
QWidget *MainWindow::createAgvPage()
{
QWidget *page = new QWidget;
Ui::AgvServicePage ui;
ui.setupUi(page);
FramelessToolDialog *statusDialog = new FramelessToolDialog(this);
m_agvStatusDialog = statusDialog;
m_agvStatusDialog->setAttribute(Qt::WA_DeleteOnClose, false);
Ui::AgvStatusDialog statusUi;
statusUi.setupUi(m_agvStatusDialog);
QGraphicsDropShadowEffect *dialogShadow =
new QGraphicsDropShadowEffect(statusUi.agvDialogSurface);
dialogShadow->setBlurRadius(28.0);
dialogShadow->setOffset(0.0, 5.0);
dialogShadow->setColor(QColor(24, 34, 44, 78));
statusUi.agvDialogSurface->setGraphicsEffect(dialogShadow);
statusDialog->setDragHandle(statusUi.agvDialogTitleBar);
statusUi.agvDialogCloseButton->setIcon(UiIcons::icon(
QStringLiteral(":/icons/x.svg"), QColor(QStringLiteral("#4f5964")),
QColor(QStringLiteral("#4f5964"))));
connect(statusUi.agvDialogCloseButton, &QPushButton::clicked,
m_agvStatusDialog, &QDialog::reject);
statusUi.statusLayout->setColumnStretch(1, 1);
statusUi.statusLayout->setColumnStretch(3, 1);
m_agvIdEdit = ui.agvIdEdit;
m_agvStatusSwitch = ui.agvStatusSwitch;
m_agvStatusRefreshTimer = new QTimer(page);
m_agvStatusRefreshTimer->setInterval(1000);
m_agvConnectionValue = statusUi.agvConnectionValue;
m_agvPoseValue = statusUi.agvPoseValue;
m_agvMotionValue = statusUi.agvMotionValue;
m_agvBatteryValue = statusUi.agvBatteryValue;
m_agvMapValue = statusUi.agvMapValue;
m_agvNavigationValue = statusUi.agvNavigationValue;
m_agvErrorValue = statusUi.agvErrorValue;
m_agvModeValue = statusUi.agvModeValue;
m_agvMotionStateValue = statusUi.agvMotionStateValue;
m_agvSafetyValue = statusUi.agvSafetyValue;
m_agvPowerValue = statusUi.agvPowerValue;
m_agvTimestampValue = statusUi.agvTimestampValue;
m_agvMapOverview = ui.agvMapOverview;
m_agvMappingPreview = ui.mappingPreview;
m_agvMappingStateLabel = ui.mappingStateLabel;
m_agvProgress = statusUi.agvProgress;
m_agvXSpin = ui.agvXSpin;
m_agvYSpin = ui.agvYSpin;
m_agvThetaSpin = ui.agvThetaSpin;
m_agvMaxSpeedSpin = ui.agvMaxSpeedSpin;
m_agvVxSpin = ui.agvVxSpin;
m_agvVySpin = ui.agvVySpin;
m_agvWzSpin = ui.agvWzSpin;
m_agvMapCombo = ui.agvMapCombo;
m_agvStationCombo = ui.agvStationCombo;
m_agvStationTable = ui.agvStationTable;
ui.refreshButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/rotate-ccw.svg"),
QColor(QStringLiteral("#66727d"))));
ui.emergencyButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/octagon-x.svg"),
QColor(QStringLiteral("#ffffff"))));
m_agvStationCombo->lineEdit()->setPlaceholderText(QStringLiteral("选择或输入站点 ID"));
m_agvMapCombo->lineEdit()->setPlaceholderText(QStringLiteral("地图名称"));
m_agvStationTable->setHorizontalHeaderLabels({QStringLiteral("站点"), QStringLiteral("类型"),
QStringLiteral("X"), QStringLiteral("Y")});
m_agvStationTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_agvStationTable->setSelectionBehavior(QAbstractItemView::SelectRows);
m_agvStationTable->verticalHeader()->setVisible(false);
m_agvStationTable->horizontalHeader()->setStretchLastSection(true);
connect(ui.refreshButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
});
connect(statusUi.refreshDialogButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
});
connect(m_agvStatusRefreshTimer, &QTimer::timeout, this, [this]() {
if (m_connected && m_agvStatusSwitch && m_agvStatusSwitch->isChecked())
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
});
connect(m_agvStatusSwitch, &QCheckBox::toggled, this, [this](bool checked) {
if (!m_agvStatusDialog)
return;
if (!checked) {
m_agvStatusRefreshTimer->stop();
m_agvStatusDialog->hide();
return;
}
const QRect owner = frameGeometry();
const int x = qMax(owner.left() + 24,
owner.right() - m_agvStatusDialog->width() - 24);
m_agvStatusDialog->move(x, owner.top() + 88);
m_agvStatusDialog->show();
m_agvStatusDialog->raise();
m_agvStatusDialog->activateWindow();
if (m_connected) {
m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed());
m_agvStatusRefreshTimer->start();
}
});
connect(m_agvStatusDialog, &QDialog::finished, this, [this](int) {
if (m_agvStatusSwitch)
m_agvStatusSwitch->setChecked(false);
});
connect(ui.navigatePoseButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvNavigatePose(m_agvIdEdit->text().trimmed(), m_agvXSpin->value(),
m_agvYSpin->value(), m_agvThetaSpin->value(),
m_agvMaxSpeedSpin->value());
});
connect(ui.navigateStationButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvNavigateStation(m_agvIdEdit->text().trimmed(),
m_agvStationCombo->currentText().trimmed(),
m_agvMaxSpeedSpin->value());
});
connect(ui.pauseButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("Pause"));
});
connect(ui.resumeButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("Resume"));
});
connect(ui.cancelButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("Cancel"));
});
connect(ui.velocityButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), m_agvVxSpin->value(),
m_agvVySpin->value(), m_agvWzSpin->value());
});
const auto sendManualVelocity = [this](double vx, double vy, double wz) {
m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), vx, vy, wz);
};
connect(ui.forwardButton, &QPushButton::clicked, this, [this, sendManualVelocity]() {
sendManualVelocity(qAbs(m_agvVxSpin->value()), 0.0, 0.0);
});
connect(ui.backwardButton, &QPushButton::clicked, this, [this, sendManualVelocity]() {
sendManualVelocity(-qAbs(m_agvVxSpin->value()), 0.0, 0.0);
});
connect(ui.leftButton, &QPushButton::clicked, this, [this, sendManualVelocity]() {
sendManualVelocity(0.0, qAbs(m_agvVySpin->value()), 0.0);
});
connect(ui.rightButton, &QPushButton::clicked, this, [this, sendManualVelocity]() {
sendManualVelocity(0.0, -qAbs(m_agvVySpin->value()), 0.0);
});
connect(ui.rotateLeftButton, &QPushButton::clicked, this, [this, sendManualVelocity]() {
sendManualVelocity(0.0, 0.0, qAbs(m_agvWzSpin->value()));
});
connect(ui.rotateRightButton, &QPushButton::clicked, this, [this, sendManualVelocity]() {
sendManualVelocity(0.0, 0.0, -qAbs(m_agvWzSpin->value()));
});
connect(ui.manualStopButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(),
QStringLiteral("StopVelocity"));
});
connect(ui.zeroVelocityButton, &QPushButton::clicked, this, [this]() {
m_agvVxSpin->setValue(0.0);
m_agvVySpin->setValue(0.0);
m_agvWzSpin->setValue(0.0);
});
connect(statusUi.stopVelocityButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(),
QStringLiteral("StopVelocity"));
});
connect(statusUi.clearFaultButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("ClearFault"));
});
connect(ui.emergencyButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(),
QStringLiteral("EmergencyStop"));
});
connect(ui.inventoryButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvInventory(m_agvIdEdit->text().trimmed());
});
connect(ui.switchMapButton, &QPushButton::clicked, this, [this]() {
m_client->requestAgvSwitchMap(m_agvIdEdit->text().trimmed(),
m_agvMapCombo->currentText().trimmed());
});
connect(ui.uploadMapButton, &QPushButton::clicked, this, [this]() {
const QString path = QFileDialog::getOpenFileName(
this, QStringLiteral("选择需要上传的地图文件"));
if (path.isEmpty())
return;
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::warning(this, QStringLiteral("上传地图"),
QStringLiteral("无法读取地图文件:%1").arg(path));
return;
}
QString mapName = m_agvMapCombo->currentText().trimmed();
if (mapName.isEmpty())
mapName = QFileInfo(path).completeBaseName();
QJsonObject request;
request.insert(QStringLiteral("mapName"), mapName);
request.insert(QStringLiteral("content"), QString::fromUtf8(file.readAll()));
m_client->requestRpc(QStringLiteral("cmvr.api.AgvService"),
QStringLiteral("uploadMap"),
QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)),
m_agvIdEdit->text().trimmed());
});
connect(ui.downloadMapButton, &QPushButton::clicked, this, [this]() {
const QString mapName = m_agvMapCombo->currentText().trimmed();
if (mapName.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("下载地图"),
QStringLiteral("请先选择或输入地图名称"));
return;
}
m_agvDownloadPath = QFileDialog::getSaveFileName(
this, QStringLiteral("保存地图"), mapName + QStringLiteral(".json"));
if (m_agvDownloadPath.isEmpty())
return;
QJsonObject request;
request.insert(QStringLiteral("mapName"), mapName);
m_client->requestRpc(QStringLiteral("cmvr.api.AgvService"),
QStringLiteral("downloadMap"),
QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)),
m_agvIdEdit->text().trimmed());
});
connect(m_client, &RobotClient::rpcFinished, page,
[this](const QString &service, const QString &method,
bool success, const QString &responseJson) {
if (service != QStringLiteral("cmvr.api.AgvService") ||
method != QStringLiteral("downloadMap") || m_agvDownloadPath.isEmpty())
return;
const QString outputPath = m_agvDownloadPath;
m_agvDownloadPath.clear();
if (!success)
return;
const QJsonDocument response = QJsonDocument::fromJson(responseJson.toUtf8());
QFile output(outputPath);
if (!response.isObject() || !output.open(QIODevice::WriteOnly)) {
appendLog(QStringLiteral("ERROR"),
QStringLiteral("AGV 地图无法保存到 %1").arg(outputPath));
return;
}
output.write(response.object().value(QStringLiteral("content")).toString().toUtf8());
output.close();
appendLog(QStringLiteral("OK"),
QStringLiteral("AGV 地图已保存到 %1").arg(outputPath));
});
connect(m_agvStationTable, &QTableWidget::cellDoubleClicked, this,
[this, ui](int row, int) {
if (QTableWidgetItem *item = m_agvStationTable->item(row, 0)) {
m_agvStationCombo->setCurrentText(item->text());
ui.agvTabs->setCurrentWidget(ui.navigationTab);
}
});
connect(ui.followPathButton, &QPushButton::clicked, this, [this, ui]() {
QVariantList path;
const QStringList lines = ui.agvPathEdit->toPlainText().split(
QLatin1Char('\n'), QString::SkipEmptyParts);
for (int row = 0; row < lines.size(); ++row) {
const QStringList pair = lines.at(row).split(QLatin1Char(','), QString::KeepEmptyParts);
if (pair.size() != 2 || pair.at(0).trimmed().isEmpty()
|| pair.at(1).trimmed().isEmpty()) {
QMessageBox::warning(
this, QStringLiteral("路径格式错误"),
QStringLiteral("第 %1 行格式无效,请使用“起点站点,终点站点”。").arg(row + 1));
return;
}
QVariantMap segment;
segment.insert(QStringLiteral("sourceStation"), pair.at(0).trimmed());
segment.insert(QStringLiteral("targetStation"), pair.at(1).trimmed());
path.append(segment);
}
if (path.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("路径为空"),
QStringLiteral("请至少输入一个路径段。"));
return;
}
m_client->requestAgvFollowPath(m_agvIdEdit->text().trimmed(), path,
m_agvMaxSpeedSpin->value());
});
connect(ui.startMappingButton, &QPushButton::clicked, this, [this, ui]() {
static const QStringList dimensions = {
QStringLiteral("AGV_MAP_2D"), QStringLiteral("AGV_MAP_3D"),
QStringLiteral("AGV_MAP_2D_AND_3D")
};
QJsonObject request;
request.insert(QStringLiteral("dimension"),
dimensions.value(ui.mappingDimensionCombo->currentIndex()));
request.insert(QStringLiteral("mapName"), ui.mappingNameEdit->text().trimmed());
request.insert(QStringLiteral("realTime"), ui.mappingRealtimeCheck->isChecked());
m_client->requestRpc(QStringLiteral("cmvr.api.AgvService"),
QStringLiteral("startMapping"),
QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)),
m_agvIdEdit->text().trimmed());
ui.mappingStateLabel->setText(QStringLiteral("建图启动请求已发送"));
});
connect(ui.stopMappingButton, &QPushButton::clicked, this, [this, ui]() {
m_client->requestAgvAction(m_agvIdEdit->text().trimmed(),
QStringLiteral("StopMapping"));
ui.mappingStateLabel->setText(QStringLiteral("正在停止建图"));
});
connect(ui.startMapStreamButton, &QPushButton::clicked, this, [this, ui]() {
m_client->startAgvMapStream(
m_agvIdEdit->text().trimmed(), ui.mappingNameEdit->text().trimmed(),
ui.mappingDimensionCombo->currentIndex() + 1,
ui.streamSnapshotCheck->isChecked(),
ui.streamIncrementalCheck->isChecked());
});
connect(ui.stopMapStreamButton, &QPushButton::clicked, this, [this]() {
m_client->stopAgvMapStream();
});
ui.agvTabs->addTab(new RpcServiceWidget(QStringLiteral("cmvr.api.AgvService"), m_client),
QStringLiteral("全部接口"));
m_serviceButtons << ui.refreshButton << ui.navigatePoseButton << ui.navigateStationButton
<< ui.pauseButton << ui.resumeButton << ui.cancelButton
<< ui.velocityButton << statusUi.stopVelocityButton
<< statusUi.clearFaultButton
<< ui.emergencyButton << ui.inventoryButton << ui.switchMapButton
<< ui.forwardButton << ui.backwardButton << ui.leftButton << ui.rightButton
<< ui.rotateLeftButton << ui.rotateRightButton << ui.manualStopButton
<< ui.followPathButton << ui.startMappingButton << ui.stopMappingButton
<< ui.startMapStreamButton << ui.stopMapStreamButton
<< ui.uploadMapButton << ui.downloadMapButton;
return page;
}
QWidget *MainWindow::createAudioPage(bool speaker)
{
QWidget *page = new QWidget;
Ui::AudioServicePage ui;
ui.setupUi(page);
const QString serviceName = speaker ? QStringLiteral("cmvr.api.SpeakerService")
: QStringLiteral("cmvr.api.MicPhoneService");
ui.serviceTitle->setText(speaker ? QStringLiteral("扬声器服务")
: QStringLiteral("麦克风服务"));
ui.serviceSubtitle->setText(
speaker ? QStringLiteral("采集麦克风或解码本地文件,并以 PCM 音频流发送到设备")
: QStringLiteral("从设备拉取音频流,实时解码并通过本机扬声器播放"));
ui.pathLabel->setText(speaker ? QStringLiteral("服务端音频路径")
: QStringLiteral("服务端录音路径"));
ui.pathEdit->setPlaceholderText(
speaker ? QStringLiteral("例如 C:/audio/test.wav(由设备端读取)")
: QStringLiteral("例如 C:/record/mic.wav(由设备端写入)"));
ui.startButton->setText(speaker ? QStringLiteral("播放音频")
: QStringLiteral("开始录音"));
ui.speakerStreamWidget->setVisible(speaker);
ui.microphoneStreamWidget->setVisible(!speaker);
ui.streamTitle->setText(speaker ? QStringLiteral("流式发送")
: QStringLiteral("拉流播放"));
ui.browseLocalFileButton->setIcon(style()->standardIcon(QStyle::SP_DirOpenIcon));
ui.browseLocalFileButton->setText(QString());
if (speaker) {
m_speakerStreamStartButton = ui.streamStartButton;
m_speakerStreamStopButton = ui.streamStopButton;
ui.inputDeviceCombo->addItems(AudioStreamManager::inputDeviceNames());
if (ui.inputDeviceCombo->count() == 0)
ui.inputDeviceCombo->addItem(QStringLiteral("未检测到音频输入设备"));
auto updateSourceControls = [sourceCombo = ui.sourceCombo,
inputCombo = ui.inputDeviceCombo,
fileEdit = ui.localFileEdit,
browseButton = ui.browseLocalFileButton]() {
const bool fileSource = sourceCombo->currentIndex() == 1;
inputCombo->setEnabled(!fileSource);
fileEdit->setEnabled(fileSource);
browseButton->setEnabled(fileSource);
};
connect(ui.sourceCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
page, [updateSourceControls](int) { updateSourceControls(); });
updateSourceControls();
connect(ui.browseLocalFileButton, &QPushButton::clicked, page,
[this, fileEdit = ui.localFileEdit]() {
const QString fileName = QFileDialog::getOpenFileName(
this, QStringLiteral("选择音频文件"), fileEdit->text(),
QStringLiteral("音频文件 (*.wav *.mp3 *.aac *.m4a *.wma);;所有文件 (*.*)"));
if (!fileName.isEmpty())
fileEdit->setText(QDir::toNativeSeparators(fileName));
});
connect(ui.streamStartButton, &QPushButton::clicked, page,
[this, deviceEdit = ui.deviceIdEdit, sourceCombo = ui.sourceCombo,
inputCombo = ui.inputDeviceCombo, fileEdit = ui.localFileEdit,
sampleRateCombo = ui.sampleRateCombo,
channelsCombo = ui.channelsCombo, stateLabel = ui.streamStateLabel]() {
const QString deviceId = deviceEdit->text().trimmed();
if (deviceId.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("流式发送"),
QStringLiteral("请填写扬声器设备 ID。"));
return;
}
const int sampleRate = sampleRateCombo->currentText().toInt();
const int channels = channelsCombo->currentIndex() + 1;
m_client->startSpeakerAudioStream(deviceId);
const bool started = sourceCombo->currentIndex() == 0
? m_audioManager->startCapture(inputCombo->currentText(), sampleRate, channels)
: m_audioManager->startFileDecode(fileEdit->text().trimmed(), sampleRate, channels);
if (!started)
m_client->stopSpeakerAudioStream();
else
stateLabel->setText(QStringLiteral("正在启动流式发送..."));
});
connect(ui.streamStopButton, &QPushButton::clicked, page, [this]() {
m_audioManager->stopSource();
m_client->stopSpeakerAudioStream();
});
connect(m_audioManager, &AudioStreamManager::sourceStateChanged, page,
[this, startButton = ui.streamStartButton, stopButton = ui.streamStopButton,
deviceEdit = ui.deviceIdEdit, stateLabel = ui.streamStateLabel]
(bool running, const QString &detail) {
startButton->setEnabled(m_connected && !running);
stopButton->setEnabled(m_connected && running);
deviceEdit->setEnabled(!running);
stateLabel->setText(detail);
if (!running)
m_client->stopSpeakerAudioStream();
});
} else {
m_microphoneStreamStartButton = ui.playbackStartButton;
m_microphoneStreamStopButton = ui.playbackStopButton;
ui.outputDeviceCombo->addItems(AudioStreamManager::outputDeviceNames());
if (ui.outputDeviceCombo->count() == 0)
ui.outputDeviceCombo->addItem(QStringLiteral("未检测到音频输出设备"));
connect(ui.localVolumeSlider, &QSlider::valueChanged, page,
[this, valueLabel = ui.localVolumeValue](int value) {
valueLabel->setText(QStringLiteral("%1 %").arg(value));
m_audioManager->setOutputVolume(value);
});
connect(ui.playbackStartButton, &QPushButton::clicked, page,
[this, deviceEdit = ui.deviceIdEdit,
outputCombo = ui.outputDeviceCombo,
volumeSlider = ui.localVolumeSlider,
stateLabel = ui.streamStateLabel]() {
const QString deviceId = deviceEdit->text().trimmed();
if (deviceId.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("拉流播放"),
QStringLiteral("请填写麦克风设备 ID。"));
return;
}
m_audioManager->setOutputDevice(outputCombo->currentText());
m_audioManager->setOutputVolume(volumeSlider->value());
m_client->startMicrophoneAudioStream(deviceId);
stateLabel->setText(QStringLiteral("正在建立音频拉流..."));
});
connect(ui.playbackStopButton, &QPushButton::clicked, page, [this]() {
m_client->stopMicrophoneAudioStream();
m_audioManager->stopPlayback();
});
connect(m_audioManager, &AudioStreamManager::playbackStateChanged, page,
[this, stateLabel = ui.streamStateLabel](bool running, const QString &detail) {
stateLabel->setText(detail);
if (!running && m_connected)
m_client->stopMicrophoneAudioStream();
});
connect(m_audioManager, &AudioStreamManager::playbackStatistics, page,
[statsLabel = ui.streamStatsLabel](quint64 frames, quint64 bytes,
qint64 durationMs) {
statsLabel->setText(QStringLiteral("%1 帧 / %2 KB / %3 s")
.arg(frames).arg(bytes / 1024.0, 0, 'f', 1)
.arg(durationMs / 1000.0, 0, 'f', 1));
});
}
connect(m_client, &RobotClient::audioStreamStateChanged, page,
[this, serviceName, speaker, startButton = speaker ? ui.streamStartButton
: ui.playbackStartButton,
stopButton = speaker ? ui.streamStopButton : ui.playbackStopButton,
deviceEdit = ui.deviceIdEdit, stateLabel = ui.streamStateLabel]
(const QString &service, bool running, const QString &detail) {
if (service != (speaker ? QStringLiteral("SpeakerService")
: QStringLiteral("MicPhoneService")))
return;
startButton->setEnabled(m_connected && !running);
stopButton->setEnabled(m_connected && running);
deviceEdit->setEnabled(!running);
stateLabel->setText(detail);
if (!running) {
if (speaker)
m_audioManager->stopSource();
else
m_audioManager->stopPlayback();
}
});
connect(m_client, &RobotClient::audioStreamStatistics, page,
[serviceName, statsLabel = ui.streamStatsLabel]
(const QString &service, quint64 frames, quint64 bytes, qint64 durationMs) {
const QString expected = serviceName.section(QLatin1Char('.'), -1);
if (service != expected)
return;
statsLabel->setText(QStringLiteral("%1 帧 / %2 KB / %3 s")
.arg(frames).arg(bytes / 1024.0, 0, 'f', 1)
.arg(durationMs / 1000.0, 0, 'f', 1));
});
auto request = [this, serviceName, deviceEdit = ui.deviceIdEdit,
pathEdit = ui.pathEdit, volumeSpin = ui.volumeSpin,
speaker](const QString &method) {
QJsonObject header;
header.insert(QStringLiteral("deviceId"), deviceEdit->text().trimmed());
QJsonObject document;
document.insert(QStringLiteral("header"), header);
if (method == QStringLiteral("PlayAudio"))
document.insert(QStringLiteral("audioPath"), pathEdit->text().trimmed());
else if (method == QStringLiteral("StartRecord"))
document.insert(QStringLiteral("filePath"), pathEdit->text().trimmed());
else if (method == QStringLiteral("SetVolume"))
document.insert(QStringLiteral("volume"), volumeSpin->value());
m_client->requestRpc(serviceName, method,
QString::fromUtf8(QJsonDocument(document).toJson(QJsonDocument::Compact)),
deviceEdit->text().trimmed());
Q_UNUSED(speaker)
};
connect(ui.statusButton, &QPushButton::clicked, this,
[request]() { request(QStringLiteral("GetStatus")); });
connect(ui.startButton, &QPushButton::clicked, this,
[request, speaker]() { request(speaker ? QStringLiteral("PlayAudio")
: QStringLiteral("StartRecord")); });
connect(ui.pauseButton, &QPushButton::clicked, this,
[request, speaker]() { request(speaker ? QStringLiteral("PausePlayback")
: QStringLiteral("PauseRecord")); });
connect(ui.resumeButton, &QPushButton::clicked, this,
[request, speaker]() { request(speaker ? QStringLiteral("ResumePlayback")
: QStringLiteral("ResumeRecord")); });
connect(ui.stopButton, &QPushButton::clicked, this,
[request, speaker]() { request(speaker ? QStringLiteral("StopPlayback")
: QStringLiteral("StopRecord")); });
connect(ui.getVolumeButton, &QPushButton::clicked, this,
[request]() { request(QStringLiteral("GetVolume")); });
connect(ui.setVolumeButton, &QPushButton::clicked, this,
[request]() { request(QStringLiteral("SetVolume")); });
QLabel *resultLabel = ui.resultLabel;
connect(m_client, &RobotClient::rpcFinished, page,
[serviceName, resultLabel](const QString &service, const QString &method,
bool success, const QString &response) {
if (service != serviceName)
return;
resultLabel->setText(QStringLiteral("%1 %2\n%3")
.arg(method, success ? QStringLiteral("成功")
: QStringLiteral("失败"),
response.left(1000)));
});
m_serviceButtons << ui.statusButton << ui.startButton << ui.pauseButton
<< ui.resumeButton << ui.stopButton << ui.getVolumeButton
<< ui.setVolumeButton;
return withRpcExplorer(page, m_client, serviceName);
}
QWidget *MainWindow::createRpcPage(const QString &serviceName)
{
return new RpcServiceWidget(serviceName, m_client);
}
QWidget *MainWindow::createQuicPage()
{
QWidget *page = new QWidget;
Ui::QuicServerPage ui;
ui.setupUi(page);
m_quicBindEdit = ui.quicBindEdit;
m_quicPortSpin = ui.quicPortSpin;
m_quicAlpnEdit = ui.quicAlpnEdit;
m_quicCertificateEdit = ui.quicCertificateEdit;
m_quicPasswordEdit = ui.quicPasswordEdit;
m_quicToggleButton = ui.quicToggleButton;
m_quicStateValue = ui.quicStateValue;
m_quicBoundValue = ui.quicBoundValue;
m_quicClientValue = ui.quicClientValue;
m_quicRegistrationValue = ui.quicRegistrationValue;
m_quicHeartbeatValue = ui.quicHeartbeatValue;
m_quicDatagramValue = ui.quicDatagramValue;
m_quicDatagramBytesValue = ui.quicDatagramBytesValue;
m_quicNodeValue = ui.quicNodeValue;
m_quicBootValue = ui.quicBootValue;
m_quicGrpcValue = ui.quicGrpcValue;
m_quicPeerValue = ui.quicPeerValue;
m_quicLogView = ui.quicLogView;
ui.browseCertificateButton->setIcon(style()->standardIcon(QStyle::SP_DirOpenIcon));
ui.clearQuicLogButton->setIcon(style()->standardIcon(QStyle::SP_DialogResetButton));
ui.configurationGrid->setColumnStretch(0, 3);
ui.configurationGrid->setColumnStretch(1, 1);
ui.configurationGrid->setColumnStretch(2, 2);
for (int column = 0; column < 6; ++column)
ui.statusLayout->setColumnStretch(column, column == 0 ? 2 : 1);
for (int column = 0; column < 4; ++column)
ui.nodeLayout->setColumnStretch(column, 1);
m_quicLogView->document()->setMaximumBlockCount(800);
connect(ui.browseCertificateButton, &QPushButton::clicked, this, [this]() {
const QString path = QFileDialog::getOpenFileName(
this, QStringLiteral("选择 QUIC 测试证书"), m_quicCertificateEdit->text(),
QStringLiteral("PKCS#12 证书 (*.pfx *.p12);;所有文件 (*.*)"));
if (!path.isEmpty())
m_quicCertificateEdit->setText(QDir::toNativeSeparators(path));
});
connect(m_quicToggleButton, &QPushButton::clicked,
this, &MainWindow::toggleQuicServer);
connect(ui.clearQuicLogButton, &QPushButton::clicked,
m_quicLogView, &QTextEdit::clear);
return page;
}
QWidget *MainWindow::createDiagnosticsPage()
{
QWidget *page = new QWidget;
Ui::DiagnosticsPage ui;
ui.setupUi(page);
m_endpointValue = ui.endpointValue;
m_backendValue = ui.backendValue;
m_buildValue = ui.buildValue;
m_logView = ui.logView;
m_backendValue->setText(m_client->grpcAvailable()
? QStringLiteral("gRPC C++")
: QStringLiteral("Demo only"));
m_buildValue->setText(QStringLiteral("Qt %1 · %2")
.arg(QString::fromLatin1(qVersion()),
#ifdef QT_NO_DEBUG
QStringLiteral("Release")));
#else
QStringLiteral("Debug")));
#endif
ui.infoLayout->setColumnStretch(0, 2);
ui.infoLayout->setColumnStretch(1, 1);
ui.infoLayout->setColumnStretch(2, 1);
ui.clearLogButton->setIcon(style()->standardIcon(QStyle::SP_DialogResetButton));
m_logView->document()->setMaximumBlockCount(1200);
connect(ui.clearLogButton, &QPushButton::clicked, m_logView, &QTextEdit::clear);
return page;
}