diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index afe4b03..53bf160 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,2083 +1,2153 @@ -#include "mainwindow.h" -#include "videorenderwidget.h" - -#include "agvmapviewwidget.h" -#include "audiostreammanager.h" -#include "configeditorwidget.h" -#include "robotclient.h" -#include "quictestserver.h" -#include "rpcservicewidget.h" -#include "trendwidget.h" -#include "uiicons.h" -#include "urdfviewerwidget.h" -#include "ui_mainwindow.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef Q_OS_WIN -#include -#endif - -namespace { -const QStringList kPageTitles = { - QStringLiteral("系统概览"), QStringLiteral("机械臂"), - QStringLiteral("相机"), QStringLiteral("AGV"), - QStringLiteral("扬声器"), QStringLiteral("麦克风"), - QStringLiteral("灵巧手"), QStringLiteral("仿生头"), - QStringLiteral("HLC 控制"), QStringLiteral("接口调试"), - QStringLiteral("QUIC Server"), QStringLiteral("设备管理"), - QStringLiteral("运行日志"), QStringLiteral("工具坐标标定"), - QStringLiteral("手眼标定") -}; -const QStringList kPageSubtitles = { - QStringLiteral("系统信息、运行资源与全局停止"), - QStringLiteral("设备服务 / ArmService"), - QStringLiteral("相机状态、图像采集与预览"), - QStringLiteral("底盘状态、导航、速度与地图操作"), - QStringLiteral("扬声器状态、音频播放、流式音频与音量控制"), - QStringLiteral("麦克风状态、录音、音频流与音量控制"), - QStringLiteral("灵巧手状态、位置、角度、力、速度与传感器"), - QStringLiteral("仿生头状态、表情、说话动作与紧急停止"), - QStringLiteral("触控坐标与最大作用力控制"), - QStringLiteral("测试服务原始请求与反馈"), - QStringLiteral("监听 edge 接入、注册、心跳与媒体数据报"), - QStringLiteral("设备清单以及 cmvr_es 项目配置的查看、校验与编辑"), - QStringLiteral("检查连接信息与 RPC 执行记录"), - QStringLiteral("机械臂工具中心点与工具坐标系标定入口"), - QStringLiteral("相机与机械臂坐标系的手眼标定入口") -}; - -QWidget *createCalibrationEntryPage(const QString &title, const QString &description, - QWidget *parent) -{ - QWidget *page = new QWidget(parent); - QVBoxLayout *pageLayout = new QVBoxLayout(page); - pageLayout->setContentsMargins(26, 22, 26, 22); - - QFrame *panel = new QFrame(page); - panel->setObjectName(QStringLiteral("panel")); - QVBoxLayout *panelLayout = new QVBoxLayout(panel); - panelLayout->setContentsMargins(24, 22, 24, 22); - panelLayout->setSpacing(8); - - QLabel *titleLabel = new QLabel(title, panel); - titleLabel->setObjectName(QStringLiteral("sectionTitle")); - QLabel *descriptionLabel = new QLabel(description, panel); - descriptionLabel->setObjectName(QStringLiteral("mutedLabel")); - descriptionLabel->setWordWrap(true); - QLabel *stateLabel = new QLabel( - QStringLiteral("功能入口已接入侧栏,标定服务接口将在后续版本中接入。"), panel); - stateLabel->setObjectName(QStringLiteral("statusChip")); - stateLabel->setAlignment(Qt::AlignCenter); - stateLabel->setMinimumWidth(320); - - panelLayout->addWidget(titleLabel); - panelLayout->addWidget(descriptionLabel); - panelLayout->addSpacing(12); - panelLayout->addWidget(stateLabel, 0, Qt::AlignLeft); - panelLayout->addStretch(1); - pageLayout->addWidget(panel); - return page; -} -} - -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), m_client(new RobotClient(this)), - m_audioManager(new AudioStreamManager(this)), - m_quicServer(new QuicTestServer(this)) -{ -#ifdef Q_OS_WIN - setWindowFlags(Qt::Window | Qt::FramelessWindowHint - | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint - | Qt::WindowCloseButtonHint); - setAttribute(Qt::WA_NativeWindow); -#else - // The custom resize/drag implementation below uses Windows native - // messages. Keep the desktop window manager decorations on Linux. - setWindowFlags(Qt::Window); -#endif - - Ui::MainWindowForm ui; - ui.setupUi(this); - m_windowSurface = ui.windowSurface; - m_customTitleBar = ui.customTitleBar; - m_titleBarPage = ui.titleBarPage; - m_titleBarBuild = ui.titleBarBuild; - m_minimizeWindowButton = ui.minimizeWindowButton; - m_maximizeWindowButton = ui.maximizeWindowButton; - m_closeWindowButton = ui.closeWindowButton; -#ifndef Q_OS_WIN - m_minimizeWindowButton->hide(); - m_maximizeWindowButton->hide(); - m_closeWindowButton->hide(); -#endif - m_pages = ui.pages; - m_hostEdit = ui.hostEdit; - m_portSpin = ui.portSpin; - m_demoCheck = ui.demoCheck; - m_connectButton = ui.connectButton; - m_pageTitle = ui.pageTitle; - m_pageSubtitle = ui.pageSubtitle; - m_headerLayout = ui.headerLayout; - m_latencyLabel = ui.latencyLabel; - m_connectionDot = ui.connectionDot; - m_connectionText = ui.connectionText; - m_bottomLogLevel = ui.bottomLogLevel; - m_bottomLogMessage = ui.bottomLogMessage; - m_bottomVersion = ui.bottomVersion; - m_titleBarBuild->setText(QStringLiteral("Qt %1 · %2") - .arg(QString::fromLatin1(qVersion()), -#ifdef QT_NO_DEBUG - QStringLiteral("Release"))); -#else - QStringLiteral("Debug"))); -#endif - m_minimizeWindowButton->setIcon(UiIcons::icon( - QStringLiteral(":/icons/minus.svg"), QColor(QStringLiteral("#4f5964")), - QColor(QStringLiteral("#202832")))); - m_maximizeWindowButton->setIcon(UiIcons::icon( - QStringLiteral(":/icons/square.svg"), QColor(QStringLiteral("#4f5964")), - QColor(QStringLiteral("#202832")))); - m_closeWindowButton->setIcon(UiIcons::icon( - QStringLiteral(":/icons/x.svg"), QColor(QStringLiteral("#4f5964")), - QColor(QStringLiteral("#ffffff")))); - connect(m_minimizeWindowButton, &QPushButton::clicked, - this, &QWidget::showMinimized); - connect(m_maximizeWindowButton, &QPushButton::clicked, this, [this]() { - isMaximized() ? showNormal() : showMaximized(); - }); - connect(m_closeWindowButton, &QPushButton::clicked, this, &QWidget::close); - m_latencyLabel->setObjectName(QStringLiteral("statusChip")); - ui.workspaceLabel->setContentsMargins(18, 0, 0, 8); - ui.connectionTitle->hide(); - m_bottomVersion->setText(QStringLiteral("CMVR %1").arg( - QCoreApplication::applicationVersion())); - - QWidget *sidebarState = new QWidget(ui.connectionPanel); - sidebarState->setObjectName(QStringLiteral("sidebarConnectionState")); - QHBoxLayout *sidebarStateLayout = new QHBoxLayout(sidebarState); - sidebarStateLayout->setContentsMargins(0, 0, 0, 0); - sidebarStateLayout->setSpacing(6); - m_connectionDot->setParent(sidebarState); - m_connectionText->setParent(sidebarState); - m_latencyLabel->setParent(sidebarState); - sidebarStateLayout->addWidget(m_connectionDot); - sidebarStateLayout->addWidget(m_connectionText); - sidebarStateLayout->addStretch(1); - sidebarStateLayout->addWidget(m_latencyLabel); - ui.connectionLayout->insertWidget(0, sidebarState); - m_sidebarEndpointValue = new QLabel(QStringLiteral("--"), ui.connectionPanel); - m_sidebarEndpointValue->setObjectName(QStringLiteral("sidebarEndpoint")); - m_sidebarQuicValue = new QLabel(QStringLiteral("QUIC 未启动"), ui.connectionPanel); - m_sidebarQuicValue->setObjectName(QStringLiteral("sidebarDetail")); - m_sidebarQuicValue->setWordWrap(true); - ui.connectionLayout->insertWidget(1, m_sidebarEndpointValue); - ui.connectionLayout->insertWidget(2, m_sidebarQuicValue); - - ui.workspaceLabel->setText(QStringLiteral("导航")); - - const QList 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 deviceButtons = { - ui.armNavButton, ui.cameraNavButton, ui.agvNavButton, - ui.speakerNavButton, ui.microphoneNavButton, - ui.dexhandNavButton, ui.bioheadNavButton - }; - ui.agvNavButton->setText(QStringLiteral("AGV")); - for (QPushButton *button : deviceButtons) { - button->setParent(deviceContent); - button->setProperty("navLevel", 2); - deviceLayout->addWidget(button); - } - - QPushButton *complexGroupButton = createGroupButton( - QStringLiteral("复杂控制"), grpcContent, 1); - const auto complexSection = createNavContainer(grpcContent); - QWidget *complexContent = complexSection.first; - QVBoxLayout *complexLayout = complexSection.second; - QPushButton *toolCalibrationNavButton = createPageButton( - QStringLiteral("工具坐标标定"), complexContent, 2); - QPushButton *handEyeNavButton = createPageButton( - QStringLiteral("手眼标定"), complexContent, 2); - ui.hlcNavButton->setParent(complexContent); - ui.hlcNavButton->setProperty("navLevel", 2); - complexLayout->addWidget(toolCalibrationNavButton); - complexLayout->addWidget(handEyeNavButton); - complexLayout->addWidget(ui.hlcNavButton); - - ui.configurationNavButton->setParent(grpcContent); - grpcLayout->addWidget(ui.configurationNavButton); - grpcLayout->addWidget(deviceContent); - grpcLayout->addWidget(complexGroupButton); - grpcLayout->addWidget(complexContent); - - ui.systemNavButton->setParent(navTree); - ui.systemNavButton->setProperty("navLevel", 0); - ui.testNavButton->setParent(navTree); - ui.testNavButton->setProperty("navLevel", 0); - ui.quicNavButton->setParent(navTree); - ui.quicNavButton->setProperty("navLevel", 0); - ui.diagnosticsNavButton->setParent(navTree); - ui.diagnosticsNavButton->setProperty("navLevel", 0); - navTreeLayout->addWidget(ui.systemNavButton); - navTreeLayout->addWidget(grpcGroupButton); - navTreeLayout->addWidget(grpcContent); - navTreeLayout->addWidget(ui.testNavButton); - navTreeLayout->addWidget(ui.quicNavButton); - navTreeLayout->addWidget(ui.diagnosticsNavButton); - navTreeLayout->addStretch(1); - - m_navGroup = new QButtonGroup(this); - m_navGroup->setExclusive(true); - m_navButtons = { - ui.systemNavButton, ui.armNavButton, ui.cameraNavButton, - ui.agvNavButton, ui.speakerNavButton, ui.microphoneNavButton, - ui.dexhandNavButton, ui.bioheadNavButton, ui.hlcNavButton, - ui.testNavButton, ui.quicNavButton, ui.configurationNavButton, - ui.diagnosticsNavButton, toolCalibrationNavButton, handEyeNavButton - }; - const QStringList icons = { - QStringLiteral(":/icons/activity.svg"), - QStringLiteral(":/icons/bot.svg"), - QStringLiteral(":/icons/camera.svg"), - QStringLiteral(":/icons/move.svg"), - QStringLiteral(":/icons/volume-2.svg"), - QStringLiteral(":/icons/mic.svg"), - QStringLiteral(":/icons/hand.svg"), - QStringLiteral(":/icons/scan-face.svg"), - QStringLiteral(":/icons/crosshair.svg"), - QStringLiteral(":/icons/braces.svg"), - QStringLiteral(":/icons/radio-tower.svg"), - QStringLiteral(":/icons/folder-open.svg"), - QStringLiteral(":/icons/scroll-text.svg"), - QStringLiteral(":/icons/crosshair.svg"), - QStringLiteral(":/icons/camera.svg") - }; - for (int i = 0; i < m_navButtons.size(); ++i) { - m_navButtons.at(i)->setIcon(UiIcons::icon( - icons.at(i), QColor(QStringLiteral("#b8c2cc")), - QColor(QStringLiteral("#ffffff")), - QColor(QStringLiteral("#66727d")))); - m_navGroup->addButton(m_navButtons.at(i), i); - } - auto setGroupExpanded = [](QPushButton *button, QWidget *content, bool expanded) { - content->setVisible(expanded); - button->setChecked(expanded); - button->setIcon(UiIcons::icon( - expanded ? QStringLiteral(":/icons/chevron-up.svg") - : QStringLiteral(":/icons/chevron-down.svg"), - QColor(QStringLiteral("#8995a1")), QColor(QStringLiteral("#ffffff")), - QColor(QStringLiteral("#66727d")), 16)); - button->setToolTip(expanded ? QStringLiteral("折叠目录") - : QStringLiteral("展开目录")); - }; - setGroupExpanded(grpcGroupButton, grpcContent, true); - setGroupExpanded(complexGroupButton, complexContent, true); - auto updateDeviceIcon = [deviceGroupPageButton, deviceContent]() { - const bool expanded = deviceContent->isVisible(); - deviceGroupPageButton->setIcon(UiIcons::icon( - expanded ? QStringLiteral(":/icons/chevron-up.svg") - : QStringLiteral(":/icons/chevron-down.svg"), - QColor(QStringLiteral("#8995a1")), QColor(QStringLiteral("#ffffff")), - QColor(QStringLiteral("#66727d")), 16)); - deviceGroupPageButton->setToolTip( - expanded ? QStringLiteral("打开设备管理并折叠设备目录") - : QStringLiteral("打开设备管理并展开设备目录")); - }; - updateDeviceIcon(); - connect(grpcGroupButton, &QPushButton::clicked, this, - [grpcGroupButton, grpcContent, setGroupExpanded](bool expanded) { - setGroupExpanded(grpcGroupButton, grpcContent, expanded); - }); - connect(complexGroupButton, &QPushButton::clicked, this, - [complexGroupButton, complexContent, setGroupExpanded](bool expanded) { - setGroupExpanded(complexGroupButton, complexContent, expanded); - }); - connect(deviceGroupPageButton, &QPushButton::clicked, this, - [deviceContent, updateDeviceIcon]() { - deviceContent->setVisible(!deviceContent->isVisible()); - updateDeviceIcon(); - }); - connect(m_navGroup, QOverload::of(&QButtonGroup::buttonClicked), - this, &MainWindow::selectPage); - connect(m_connectButton, &QPushButton::clicked, this, &MainWindow::toggleConnection); - - m_pages->addWidget(createSystemPage()); - m_pages->addWidget(createArmPage()); - m_pages->addWidget(createCameraPage()); - m_pages->addWidget(createAgvPage()); - m_pages->addWidget(createAudioPage(true)); - m_pages->addWidget(createAudioPage(false)); - m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.DexHandService"))); - m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.BioHeadService"))); - m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.HlcService"))); - m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.TestService"))); - m_pages->addWidget(createQuicPage()); - auto *deviceManager = new ConfigEditorWidget(m_client, m_pages); - m_pages->addWidget(deviceManager); - connect(deviceManager, &ConfigEditorWidget::deviceNavigationRequested, this, - [this](int deviceType, const QString &deviceId) { - int pageIndex = -1; - switch (deviceType) { - case 6: - pageIndex = 1; - if (m_armSideCombo) { - int index = m_armSideCombo->findData(deviceId); - if (index < 0) { - m_armSideCombo->addItem(deviceId, deviceId); - index = m_armSideCombo->count() - 1; - } - m_armSideCombo->setCurrentIndex(index); - } else if (m_armIdEdit) { - m_armIdEdit->setText(deviceId); - } - break; - case 2: - pageIndex = 2; - if (m_cameraIdEdit) m_cameraIdEdit->setText(deviceId); - break; - case 0: - pageIndex = 3; - if (m_agvIdEdit) m_agvIdEdit->setText(deviceId); - break; - case 7: - pageIndex = 4; - if (m_speakerIdEdit) m_speakerIdEdit->setText(deviceId); - break; - case 5: - pageIndex = 5; - if (m_microphoneIdEdit) m_microphoneIdEdit->setText(deviceId); - break; - case 3: - pageIndex = 6; - break; - case 8: - pageIndex = 7; - break; - default: - break; - } - if (pageIndex < 0) - return; - if (auto *rpcPage = qobject_cast(m_pages->widget(pageIndex))) - rpcPage->setDeviceId(deviceId); - selectPage(pageIndex); - }); - m_pages->addWidget(createDiagnosticsPage()); - m_pages->addWidget(createCalibrationEntryPage( - QStringLiteral("工具坐标标定"), - QStringLiteral("用于建立工具中心点(TCP)及其相对于机械臂末端的坐标变换。"), - m_pages)); - m_pages->addWidget(createCalibrationEntryPage( - QStringLiteral("手眼标定"), - QStringLiteral("用于求解相机坐标系与机械臂基座或末端坐标系之间的变换关系。"), - m_pages)); - - const QString comboPopupStyle = QStringLiteral( - "QListView {" - " background: #ffffff; color: #33404c;" - " border: 1px solid #cfd4da; border-radius: 4px;" - " padding: 4px; outline: 0;" - "}" - "QListView::item {" - " min-height: 32px; padding: 0 10px;" - " border: none; border-radius: 3px;" - "}" - "QListView::item:hover {" - " color: #27313b; background: #f3f7fb;" - "}" - "QListView::item:selected {" - " color: #145da8; background: #e8f2ff; font-weight: 600;" - "}" - ); - const QList comboBoxes = findChildren(); - for (QComboBox *comboBox : comboBoxes) { - QListView *popupView = new QListView(comboBox); - popupView->setObjectName(QStringLiteral("comboPopupView")); - popupView->setSpacing(1); - popupView->setUniformItemSizes(true); - popupView->setStyleSheet(comboPopupStyle); - comboBox->setView(popupView); - } - - connect(m_client, &RobotClient::connectionChanged, this, &MainWindow::updateConnection); - connect(m_client, &RobotClient::armInfoReceived, this, &MainWindow::updateArmInfo); - connect(m_client, &RobotClient::telemetryReceived, this, &MainWindow::updateTelemetry); - connect(m_client, &RobotClient::armTelemetryHealthChanged, - this, &MainWindow::updateArmTelemetryHealth); - connect(m_client, &RobotClient::systemStatusReceived, this, &MainWindow::updateSystemStatus); - connect(m_client, &RobotClient::systemInfoReceived, this, &MainWindow::updateSystemInfo); - connect(m_client, &RobotClient::imageReceived, this, &MainWindow::updateImage); - connect(m_client, &RobotClient::videoFrameReceived, this, &MainWindow::updateVideoFrame); - connect(m_client, &RobotClient::cameraStreamStateChanged, - this, &MainWindow::updateCameraStreamState); - connect(m_client, &RobotClient::cameraRecordingStateChanged, - this, &MainWindow::updateCameraRecordingState); - connect(m_client, &RobotClient::agvStateReceived, this, &MainWindow::updateAgvState); - connect(m_client, &RobotClient::agvInventoryReceived, this, &MainWindow::updateAgvInventory); - connect(m_client, &RobotClient::agvMapFrameReceived, this, - [this](const QImage &image, const QVariantMap &metadata, - const QString &detail) { - if (m_agvMapView) { - m_agvMapView->setMapFrame(image, metadata); - m_agvMapView->setStreamMessage(detail); - } - if (m_agvMappingStateLabel) - m_agvMappingStateLabel->setText(detail); - }); - connect(m_client, &RobotClient::agvMapStreamStateChanged, this, - [this](bool running, const QString &detail) { - m_agvMapStreamActive = running; - if (m_agvMapView) - m_agvMapView->setStreamMessage(detail); - if (!m_agvMappingStateLabel) - return; - m_agvMappingStateLabel->setProperty("running", running); - m_agvMappingStateLabel->setText(detail); - m_agvMappingStateLabel->style()->unpolish(m_agvMappingStateLabel); - m_agvMappingStateLabel->style()->polish(m_agvMappingStateLabel); - }); - connect(m_client, &RobotClient::commandFinished, this, &MainWindow::handleCommand); - connect(m_client, &RobotClient::logMessage, this, &MainWindow::appendLog); - connect(m_audioManager, &AudioStreamManager::speakerFrameReady, - m_client, &RobotClient::sendSpeakerAudioFrame); - connect(m_client, &RobotClient::audioFrameReceived, - m_audioManager, &AudioStreamManager::playPcmFrame); - connect(m_audioManager, &AudioStreamManager::logMessage, - this, &MainWindow::appendLog); - connect(m_quicServer, &QuicTestServer::runningChanged, - this, &MainWindow::updateQuicRunning); - connect(m_quicServer, &QuicTestServer::clientCountChanged, this, [this](int count) { - m_quicClientValue->setText(QString::number(count)); - }); - connect(m_quicServer, &QuicTestServer::statisticsChanged, this, - [this](quint64 registrations, quint64 heartbeats, - quint64 datagrams, quint64 datagramBytes) { - m_quicRegistrationValue->setText(QString::number(registrations)); - m_quicHeartbeatValue->setText(QString::number(heartbeats)); - m_quicDatagramValue->setText(QString::number(datagrams)); - m_quicDatagramBytesValue->setText(QString::number(datagramBytes)); - }); - connect(m_quicServer, &QuicTestServer::nodeRegistered, this, - [this](const QString &nodeId, const QString &bootId, - const QString &grpcEndpoint, const QString &peerAddress) { - m_quicNodeValue->setText(nodeId); - m_quicBootValue->setText(bootId); - m_quicGrpcValue->setText(grpcEndpoint); - m_quicPeerValue->setText(peerAddress); - }); - connect(m_quicServer, &QuicTestServer::logMessage, - this, &MainWindow::appendQuicLog); - - loadSettings(); - const QStringList startupArguments = QCoreApplication::arguments(); - const int cameraCodecArgument = startupArguments.indexOf( - QStringLiteral("--camera-codec")); - if (cameraCodecArgument >= 0 && cameraCodecArgument + 1 < startupArguments.size()) { - const QString codec = startupArguments.at(cameraCodecArgument + 1).trimmed().toLower(); - m_cameraCodecCombo->setCurrentIndex( - codec == QStringLiteral("h265") || codec == QStringLiteral("hevc") ? 1 : 0); - } - int initialPage = 0; - const QStringList arguments = startupArguments; - const int pageArgument = arguments.indexOf(QStringLiteral("--page-index")); - if (pageArgument >= 0 && pageArgument + 1 < arguments.size()) { - bool validPage = false; - const int requestedPage = arguments.at(pageArgument + 1).toInt(&validPage); - if (validPage && requestedPage >= 0 && requestedPage < m_pages->count()) - initialPage = requestedPage; - } - selectPage(initialPage); - setControlsEnabled(false); - qApp->installEventFilter(this); - appendLog(QStringLiteral("INFO"), QStringLiteral("CMVR 控制台已启动")); - appendLog(QStringLiteral("INFO"), m_client->grpcAvailable() - ? QStringLiteral("原生 gRPC 后端可用") - : QStringLiteral("当前为界面构建,真实 gRPC 后端未编译")); - - QTimer::singleShot(250, this, [this]() { - if (m_demoCheck->isChecked()) - toggleConnection(); - }); - QTimer::singleShot(0, this, &MainWindow::updateWindowChrome); -} - -MainWindow::~MainWindow() -{ - qApp->removeEventFilter(this); - stopAgvManualMotion(false); - if (m_client) - m_client->stopAgvMapStream(); - m_audioManager->stopSource(); - m_audioManager->stopPlayback(); - m_client->stopSpeakerAudioStream(); - m_client->stopMicrophoneAudioStream(); - m_quicServer->stopServer(); - saveSettings(); -} - -bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) -{ -#ifdef Q_OS_WIN - Q_UNUSED(eventType) - MSG *nativeMessage = static_cast(message); - if (nativeMessage && nativeMessage->message == WM_GETMINMAXINFO && result) { - MINMAXINFO *minMaxInfo = reinterpret_cast(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(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(focus) - || qobject_cast(focus) - || qobject_cast(focus) - || qobject_cast(focus)) { - return QMainWindow::eventFilter(watched, event); - } - - QKeyEvent *keyEvent = static_cast(event); - if (keyEvent->isAutoRepeat() - || (keyEvent->modifiers() & (Qt::ControlModifier | Qt::AltModifier - | Qt::MetaModifier))) { - return QMainWindow::eventFilter(watched, event); - } - - double vx = 0.0; - double vy = 0.0; - double wz = 0.0; - bool directionKey = true; - switch (keyEvent->key()) { - case Qt::Key_W: - vx = qAbs(m_agvVxSpin->value()); - break; - case Qt::Key_S: - vx = -qAbs(m_agvVxSpin->value()); - break; - case Qt::Key_A: - vy = qAbs(m_agvVySpin->value()); - break; - case Qt::Key_D: - vy = -qAbs(m_agvVySpin->value()); - break; - case Qt::Key_Q: - wz = qAbs(m_agvWzSpin->value()); - break; - case Qt::Key_E: - wz = -qAbs(m_agvWzSpin->value()); - break; - default: - directionKey = false; - break; - } - if (!directionKey) - return QMainWindow::eventFilter(watched, event); - - if (event->type() == QEvent::KeyPress) - startAgvManualMotion(vx, vy, wz); - else - stopAgvManualMotion(); - return true; -} - -void MainWindow::changeEvent(QEvent *event) -{ - QMainWindow::changeEvent(event); - 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(m_quicPortSpin->value()), - m_quicAlpnEdit->text().trimmed(), - m_quicCertificateEdit->text().trimmed(), - m_quicPasswordEdit->text()); -} - -void MainWindow::updateQuicRunning(bool running, quint16 port, const QString &detail) -{ - m_quicToggleButton->setEnabled(true); - m_quicToggleButton->setText(running ? QStringLiteral("停止 QUIC Server") - : QStringLiteral("启动 QUIC Server")); - m_quicToggleButton->setObjectName(running ? QStringLiteral("dangerButton") - : QStringLiteral("primaryButton")); - m_quicToggleButton->style()->unpolish(m_quicToggleButton); - m_quicToggleButton->style()->polish(m_quicToggleButton); - m_quicStateValue->setText(running ? QStringLiteral("运行中") : detail); - m_quicBoundValue->setText(running - ? QStringLiteral("%1:%2").arg(m_quicBindEdit->text().trimmed()).arg(port) - : QStringLiteral("--")); - if (m_sidebarQuicValue) { - m_sidebarQuicValue->setText(running - ? QStringLiteral("QUIC %1:%2").arg(m_quicBindEdit->text().trimmed()).arg(port) - : QStringLiteral("QUIC 未启动")); - m_sidebarQuicValue->setToolTip(detail); - } - m_quicBindEdit->setEnabled(!running); - m_quicPortSpin->setEnabled(!running); - m_quicAlpnEdit->setEnabled(!running); - m_quicCertificateEdit->setEnabled(!running); - m_quicPasswordEdit->setEnabled(!running); - appendQuicLog(running ? QStringLiteral("OK") : QStringLiteral("INFO"), detail); -} - -void MainWindow::appendQuicLog(const QString &level, const QString &message) -{ - if (!m_quicLogView) - return; - QString color = QStringLiteral("#aeb6c0"); - if (level == QStringLiteral("ERROR")) - color = QStringLiteral("#ff7b72"); - else if (level == QStringLiteral("WARN")) - color = QStringLiteral("#e3b341"); - else if (level == QStringLiteral("OK")) - color = QStringLiteral("#56d39b"); - const QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz"); - m_quicLogView->append(QStringLiteral("%1 " - "[%3] %4") - .arg(timestamp, color, level, message.toHtmlEscaped())); -} - -void MainWindow::setArmTelemetryEnabled(bool enabled) -{ - if (!m_armTelemetryButton || !m_client || !m_armIdEdit) - return; - - const QString deviceId = m_armIdEdit->text().trimmed(); - const bool shouldEnable = enabled && m_connected && !deviceId.isEmpty(); - m_armTelemetryButton->setChecked(shouldEnable); - m_armTelemetryButton->setText( - shouldEnable ? QStringLiteral("遥测 10 Hz") - : QStringLiteral("遥测 未启动")); - m_armTelemetryButton->setProperty("active", shouldEnable); - m_armTelemetryButton->style()->unpolish(m_armTelemetryButton); - m_armTelemetryButton->style()->polish(m_armTelemetryButton); - if (m_armSideCombo) - m_armSideCombo->setEnabled(true); - - if (shouldEnable) { - m_client->requestArmInfo(deviceId); - m_client->requestArmFrames(deviceId); - } - m_client->setArmTelemetry(deviceId, shouldEnable); -} - - -void MainWindow::selectPage(int index) -{ - if (!m_pages || index < 0 || index >= kPageTitles.size()) - return; - const int previousIndex = m_pages->currentIndex(); - if (previousIndex == 1 && index != 1) - setArmTelemetryEnabled(false); - m_pages->setCurrentIndex(index); - m_pageTitle->setText(kPageTitles.at(index)); - m_pageSubtitle->setText(kPageSubtitles.at(index)); - if (m_titleBarPage && index < m_navButtons.size()) - m_titleBarPage->setText(m_navButtons.at(index)->text()); - if (m_armHeaderControls) - m_armHeaderControls->setVisible(index == 1); - if (index == 1) - ensureArmModelLoaded(); - if (index == 1 && previousIndex != 1 && m_connected) - setArmTelemetryEnabled(true); - if (index != 3) { - stopAgvManualMotion(); - if (m_agvStatusRefreshTimer) - m_agvStatusRefreshTimer->stop(); - if (m_agvMapStreamActive) { - m_client->stopAgvMapStream(); - m_agvMapStreamActive = false; - } - } else if (m_connected) { - m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); - m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); - m_agvStatusRefreshTimer->start(); - restartAgvMapStream(); - } - if (index < m_navButtons.size()) - m_navButtons.at(index)->setChecked(true); -} - -void MainWindow::startAgvManualMotion(double vx, double vy, double wz) -{ - if (!m_connected || !m_client || !m_agvIdEdit - || m_agvIdEdit->text().trimmed().isEmpty()) { - return; - } - m_agvManualVx = vx; - m_agvManualVy = vy; - m_agvManualWz = wz; - m_agvManualMotionActive = true; - m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), vx, vy, wz); - if (m_agvManualVelocityTimer && !m_agvManualVelocityTimer->isActive()) - m_agvManualVelocityTimer->start(); -} - -void MainWindow::stopAgvManualMotion(bool sendStop) -{ - const bool wasActive = m_agvManualMotionActive; - m_agvManualMotionActive = false; - if (m_agvManualVelocityTimer) - m_agvManualVelocityTimer->stop(); - if (sendStop && wasActive && m_connected && m_client && m_agvIdEdit - && !m_agvIdEdit->text().trimmed().isEmpty()) { - m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), - QStringLiteral("StopVelocity")); - } -} - -void MainWindow::restartAgvMapStream(const QString &mapName) -{ - if (!m_connected || !m_client || !m_agvIdEdit - || m_agvIdEdit->text().trimmed().isEmpty()) { - return; - } - const QString selectedMap = mapName.trimmed().isEmpty() && m_agvMapCombo - ? m_agvMapCombo->currentText().trimmed() : mapName.trimmed(); - m_client->stopAgvMapStream(); - m_client->startAgvMapStream(m_agvIdEdit->text().trimmed(), selectedMap, - 1, true, true); -} - -void MainWindow::ensureArmModelLoaded() -{ - if (!m_urdfViewer || m_pendingUrdfPath.isEmpty() - || !m_urdfViewer->currentFile().isEmpty() || m_armModelLoadScheduled) { - return; - } - - m_armModelLoadScheduled = true; - m_urdfViewer->prepareLoad(m_pendingUrdfPath); - QTimer::singleShot(450, this, [this]() { - if (!m_pages || m_pages->currentIndex() != 1) { - m_armModelLoadScheduled = false; - return; - } - const QString path = m_pendingUrdfPath; - if (m_urdfViewer && m_urdfViewer->currentFile().isEmpty()) - m_urdfViewer->loadUrdf(path); - m_armModelLoadScheduled = false; - }); -} - -void MainWindow::toggleConnection() -{ - if (m_connected) { - m_connectButton->setEnabled(false); - m_connectButton->setText(QStringLiteral("正在断开…")); - m_client->disconnectFromServer(); - return; - } - - if (m_hostEdit->text().trimmed().isEmpty()) { - QMessageBox::warning(this, QStringLiteral("连接参数"), QStringLiteral("请填写主机地址。")); - return; - } - saveSettings(); - m_connectButton->setEnabled(false); - m_connectButton->setText(QStringLiteral("正在连接…")); - m_connectionText->setText(QStringLiteral("连接中")); - m_connectionDot->setStyleSheet(QStringLiteral("color:#df8b24; font-size:12px;")); - m_endpointValue->setText(endpoint()); - appendLog(QStringLiteral("INFO"), QStringLiteral("正在连接 %1").arg(endpoint())); - m_client->connectToServer(m_hostEdit->text(), m_portSpin->value(), m_demoCheck->isChecked()); -} - -void MainWindow::updateConnection(bool connected, int latencyMs, const QString &detail) -{ - m_connected = connected; - m_connectButton->setEnabled(true); - m_connectButton->setText(connected ? QStringLiteral("断开连接") : QStringLiteral("连接")); - m_connectionText->setText(connected ? QStringLiteral("gRPC 已连接") - : QStringLiteral("gRPC 未连接")); - m_connectionDot->setStyleSheet(QStringLiteral("color:%1; font-size:12px;") - .arg(connected ? QStringLiteral("#25a878") : QStringLiteral("#9aa1aa"))); - m_latencyLabel->setText(connected ? QStringLiteral("%1 ms").arg(latencyMs) : QStringLiteral("-- ms")); - if (m_sidebarEndpointValue) - m_sidebarEndpointValue->setText(endpoint()); - m_hostEdit->setEnabled(!connected); - m_portSpin->setEnabled(!connected); - m_demoCheck->setEnabled(!connected); - if (QWidget *state = m_connectionText->parentWidget()) { - state->setProperty("connected", connected); - state->style()->unpolish(state); - state->style()->polish(state); - } - setControlsEnabled(connected); - if (connected && m_pages && m_pages->currentIndex() == 1) - setArmTelemetryEnabled(true); - if (m_agvStatusRefreshTimer) { - if (connected && m_pages && m_pages->currentIndex() == 3) { - m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); - m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); - m_agvStatusRefreshTimer->start(); - restartAgvMapStream(); - } else { - m_agvStatusRefreshTimer->stop(); - } - } - if (!connected) { - stopAgvManualMotion(false); - m_client->stopAgvMapStream(); - m_agvMapStreamActive = false; - if (m_agvMapView) - m_agvMapView->setStreamMessage(QStringLiteral("连接已断开")); - m_audioManager->stopSource(); - m_audioManager->stopPlayback(); - m_runningCameraIds.clear(); - for (auto it = m_cameraPreviewTiles.begin(); - it != m_cameraPreviewTiles.end(); ++it) { - it->status->setText(QStringLiteral("已断开")); - } - refreshCameraStreamControls(); - } - if (!connected && m_armTelemetryButton) - setArmTelemetryEnabled(false); - if (!connected) { - m_armAlertStates.clear(); - const QList armStates = {m_servoStatusValue, m_faultStatusValue}; - for (QLabel *label : armStates) { - if (!label) - continue; - label->setText(QStringLiteral("未知")); - label->setProperty("state", QStringLiteral("unknown")); - label->style()->unpolish(label); - label->style()->polish(label); - } - } - if (connected) - m_client->requestSystemRefresh(); - appendLog(connected ? QStringLiteral("INFO") : QStringLiteral("WARN"), detail); -} - -void MainWindow::rebuildArmJointTables(const QStringList &jointNames) -{ - if (!m_jointTable) - return; - m_activeArmJointNames = jointNames; - m_jointTable->clearContents(); - m_jointTable->setRowCount(jointNames.size()); - for (int row = 0; row < jointNames.size(); ++row) { - m_jointTable->setItem(row, 0, new QTableWidgetItem(jointNames.at(row))); - for (int column = 1; column < 4; ++column) - m_jointTable->setItem(row, column, new QTableWidgetItem(QStringLiteral("--"))); - } - - if (m_zeroJointCombo) { - const QSignalBlocker blocker(m_zeroJointCombo); - m_zeroJointCombo->clear(); - m_zeroJointCombo->addItems(jointNames); - } - if (m_calibrateZeroButton) - m_calibrateZeroButton->setEnabled(m_connected && !jointNames.isEmpty()); - m_previousJointVelocities.clear(); - m_lastArmTelemetryMs = 0; - rebuildArmJogControls(); -} - -void MainWindow::rebuildArmJogControls() -{ - if (!m_jointJogRowsLayout || !m_jointJogRowsHost) - return; - while (QLayoutItem *item = m_jointJogRowsLayout->takeAt(0)) { - if (QWidget *widget = item->widget()) - widget->deleteLater(); - delete item; - } - m_jointJogPositionLabels.clear(); - m_jointJogPositionSliders.clear(); - m_jointJogMinusButtons.clear(); - m_jointJogPlusButtons.clear(); - - for (int jointIndex = 0; jointIndex < m_activeArmJointNames.size(); ++jointIndex) { - QFrame *row = new QFrame(m_jointJogRowsHost); - row->setObjectName(QStringLiteral("jogAxisRow")); - QHBoxLayout *layout = new QHBoxLayout(row); - layout->setContentsMargins(0, 0, 0, 0); - layout->setSpacing(6); - QLabel *name = new QLabel(m_activeArmJointNames.at(jointIndex), row); - name->setMinimumWidth(76); - name->setToolTip(m_activeArmJointNames.at(jointIndex)); - QLabel *position = new QLabel(QStringLiteral("-- rad"), row); - position->setObjectName(QStringLiteral("jogCurrentValue")); - position->setMinimumWidth(86); - QPushButton *minus = new QPushButton(QStringLiteral("−"), row); - QPushButton *plus = new QPushButton(QStringLiteral("+"), row); - minus->setObjectName(QStringLiteral("jogDirectionButton")); - plus->setObjectName(QStringLiteral("jogDirectionButton")); - minus->setFixedSize(38, 32); - plus->setFixedSize(38, 32); - minus->setToolTip(QStringLiteral("按住使 %1 反向运动").arg( - m_activeArmJointNames.at(jointIndex))); - plus->setToolTip(QStringLiteral("按住使 %1 正向运动").arg( - m_activeArmJointNames.at(jointIndex))); - QSlider *direction = new QSlider(Qt::Horizontal, row); - direction->setObjectName(QStringLiteral("jogDirectionIndicator")); - direction->setRange(0, 1000); - direction->setValue(0); - direction->setToolTip(QStringLiteral("等待 URDF 关节限位和实时位置")); - direction->setEnabled(false); - layout->addWidget(name); - layout->addWidget(position); - layout->addWidget(minus); - layout->addWidget(direction, 1); - layout->addWidget(plus); - connect(minus, &QPushButton::pressed, this, - [this, jointIndex]() { startJointJog(jointIndex, -1); }); - connect(plus, &QPushButton::pressed, this, - [this, jointIndex]() { startJointJog(jointIndex, 1); }); - connect(minus, &QPushButton::released, this, &MainWindow::stopArmJog); - connect(plus, &QPushButton::released, this, &MainWindow::stopArmJog); - m_jointJogRowsLayout->addWidget(row); - m_jointJogPositionLabels.append(position); - m_jointJogPositionSliders.append(direction); - m_jointJogMinusButtons.append(minus); - m_jointJogPlusButtons.append(plus); - } - m_jointJogRowsLayout->addStretch(1); -} - -void MainWindow::startJointJog(int jointIndex, int direction) -{ - if (!m_connected || !m_jogSpeedSlider || jointIndex < 0 - || jointIndex >= m_activeArmJointNames.size()) { - return; - } - QVariantList velocities; - for (int index = 0; index < m_activeArmJointNames.size(); ++index) - velocities.append(0.0); - const double ratio = m_jogSpeedSlider->value() / 100.0; - velocities[jointIndex] = direction * m_velocitySpin->value() * ratio; - m_armJogActive = true; - m_client->requestSpeedJ(m_armIdEdit->text().trimmed(), velocities, - m_accelerationSpin->value(), 60.0); -} - -void MainWindow::startCartesianJog(int axisIndex, int direction) -{ - if (!m_connected || !m_jogSpeedSlider || axisIndex < 0 || axisIndex >= 6) - return; - static const QStringList keys = { - QStringLiteral("vx"), QStringLiteral("vy"), QStringLiteral("vz"), - QStringLiteral("wx"), QStringLiteral("wy"), QStringLiteral("wz") - }; - QVariantMap velocity; - for (const QString &key : keys) - velocity.insert(key, 0.0); - const double ratio = m_jogSpeedSlider->value() / 100.0; - const double maximumVelocity = m_cartesianVelocitySpin - ? m_cartesianVelocitySpin->value() : 0.25; - velocity.insert(keys.at(axisIndex), - direction * maximumVelocity * ratio); - m_armJogActive = true; - // The current edge protocol applies named base/TCP selections to pose - // queries, while speedL accepts only the Base/Tool enum. Use Base here. - m_client->requestSpeedL(m_armIdEdit->text().trimmed(), velocity, - m_cartesianAccelerationSpin - ? m_cartesianAccelerationSpin->value() : 0.5, - 60.0, false); -} - -void MainWindow::stopArmJog() -{ - if (!m_connected || !m_armIdEdit) - return; - m_armJogActive = false; - m_client->requestArmStop(m_armIdEdit->text().trimmed()); -} - -void MainWindow::updateArmInfo(const QString &deviceId, const QVariantMap &info) -{ - if (!m_armIdEdit || deviceId != m_armIdEdit->text().trimmed()) - return; - const QString manufacturer = info.value(QStringLiteral("manufacturer")).toString(); - const QString model = info.value(QStringLiteral("model")).toString(); - const QString subtype = info.value(QStringLiteral("subtype")).toString(); - m_armDefaultBaseFrame = info.value(QStringLiteral("defaultBaseFrame")).toString(); - m_armDefaultTcpFrame = info.value(QStringLiteral("defaultTcpFrame")).toString(); - const QStringList jointNames = info.value(QStringLiteral("jointNames")).toStringList(); - rebuildArmJointTables(jointNames); - if (m_baseFrameCombo && m_baseFrameCombo->count() == 0) - m_baseFrameCombo->addItem(m_armDefaultBaseFrame.isEmpty() - ? QStringLiteral("base") : m_armDefaultBaseFrame); - if (m_tcpFrameCombo && m_tcpFrameCombo->count() == 0) - m_tcpFrameCombo->addItem(m_armDefaultTcpFrame.isEmpty() - ? QStringLiteral("tool0") : m_armDefaultTcpFrame); - if (m_armDeviceSummary) { - const QString identity = subtype.isEmpty() - ? QStringLiteral("%1 · %2 %3").arg(deviceId, manufacturer, model) - : QStringLiteral("%1 · %2 %3 (%4)").arg(deviceId, manufacturer, model, subtype); - m_armDeviceSummary->setText(identity); - } - if (m_urdfViewer) { - m_urdfViewer->loadModelForIdentity( - manufacturer, model, subtype, - info.value(QStringLiteral("descriptionId")).toString()); - } - m_client->requestArmFrames(deviceId); - appendLog(QStringLiteral("INFO"), - QStringLiteral("机械臂 %1:SDK 型号 %2 %3,自由度 %4") - .arg(deviceId, manufacturer, model) - .arg(jointNames.size())); -} - -void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &joints, - const QVariantMap &pose, const QVariantMap &state) -{ - if (!m_armIdEdit || deviceId != m_armIdEdit->text().trimmed()) - return; - QHash byName; - QHash jointPositions; - for (const QVariant &value : joints) { - const QVariantMap joint = value.toMap(); - const QString name = joint.value(QStringLiteral("name")).toString(); - byName.insert(name, joint); - jointPositions.insert(name, joint.value(QStringLiteral("position")).toDouble()); - } - - const qint64 nowMs = QDateTime::currentMSecsSinceEpoch(); - const double deltaSeconds = m_lastArmTelemetryMs > 0 - ? (nowMs - m_lastArmTelemetryMs) / 1000.0 : 0.0; - const QStringList modelJointNames = m_urdfViewer - ? m_urdfViewer->jointNames() : QStringList(); - const QHash> modelJointLimits = m_urdfViewer - ? m_urdfViewer->jointLimits() : QHash>(); - - if (m_urdfViewer) { - QHash modelPositions = jointPositions; - int directMatches = 0; - for (const QString &name : modelJointNames) { - if (jointPositions.contains(name)) - ++directMatches; - } - if (directMatches == 0 && modelJointNames.size() == joints.size()) { - for (int index = 0; index < modelJointNames.size(); ++index) { - modelPositions.insert( - modelJointNames.at(index), - joints.at(index).toMap().value(QStringLiteral("position")).toDouble()); - } - } - m_urdfViewer->setJointPositions(modelPositions); - } - - for (int row = 0; m_jointTable && row < m_jointTable->rowCount(); ++row) { - const QTableWidgetItem *nameItem = m_jointTable->item(row, 0); - if (!nameItem) - continue; - QVariantMap joint = byName.value(nameItem->text()); - if (joint.isEmpty() && row < joints.size()) - joint = joints.at(row).toMap(); - if (joint.isEmpty()) - continue; - const double position = joint.value(QStringLiteral("position")).toDouble(); - const double velocity = joint.value(QStringLiteral("velocity")).toDouble(); - const double acceleration = deltaSeconds > 0.0001 - && m_previousJointVelocities.contains(nameItem->text()) - ? (velocity - m_previousJointVelocities.value(nameItem->text())) / deltaSeconds - : 0.0; - m_jointTable->item(row, 1)->setText(QString::number(position, 'f', 5)); - m_jointTable->item(row, 2)->setText(QString::number(velocity, 'f', 5)); - m_jointTable->item(row, 3)->setText(QString::number(acceleration, 'f', 4)); - m_previousJointVelocities.insert(nameItem->text(), velocity); - if (row < m_jointJogPositionLabels.size()) - m_jointJogPositionLabels.at(row)->setText( - QStringLiteral("%1 rad").arg(position, 0, 'f', 4)); - if (row < m_jointJogPositionSliders.size()) { - QSlider *positionSlider = m_jointJogPositionSliders.at(row); - QString limitJointName = nameItem->text(); - if (!modelJointLimits.contains(limitJointName) - && row < modelJointNames.size()) { - limitJointName = modelJointNames.at(row); - } - const auto limitIt = modelJointLimits.constFind(limitJointName); - if (limitIt != modelJointLimits.constEnd() - && qIsFinite(limitIt.value().first) - && qIsFinite(limitIt.value().second) - && limitIt.value().second > limitIt.value().first) { - const double lower = limitIt.value().first; - const double upper = limitIt.value().second; - const double progress = qBound(0.0, (position - lower) / (upper - lower), 1.0); - positionSlider->setValue(qRound(progress * positionSlider->maximum())); - positionSlider->setToolTip( - QStringLiteral("%1:下限 %2 rad · 当前 %3 rad · 上限 %4 rad") - .arg(nameItem->text()) - .arg(lower, 0, 'f', 4) - .arg(position, 0, 'f', 4) - .arg(upper, 0, 'f', 4)); - } else { - positionSlider->setValue(0); - positionSlider->setToolTip(QStringLiteral("当前 URDF 未提供有效关节限位")); - } - } - if (row == 0 && m_trend) - m_trend->appendSample(position, velocity); - } - m_lastArmTelemetryMs = nowMs; - - if (!pose.isEmpty()) { - m_latestArmPose = pose; - static const QStringList keys = { - QStringLiteral("x"), QStringLiteral("y"), QStringLiteral("z"), - QStringLiteral("rx"), QStringLiteral("ry"), QStringLiteral("rz") - }; - for (int index = 0; index < keys.size() - && index < m_poseMetricValues.size(); ++index) { - m_poseMetricValues.at(index)->setText( - QString::number(pose.value(keys.at(index)).toDouble(), 'f', 4)); - } - for (int index = 0; index < keys.size() - && index < m_cartesianJogPoseLabels.size(); ++index) { - m_cartesianJogPoseLabels.at(index)->setText( - QStringLiteral("%1 %2") - .arg(pose.value(keys.at(index)).toDouble(), 0, 'f', 4) - .arg(index < 3 ? QStringLiteral("m") : QStringLiteral("rad"))); - } - } - if (!state.isEmpty()) { - const bool connected = state.value(QStringLiteral("connected")).toBool(); - const bool powered = state.value(QStringLiteral("poweredOn")).toBool(); - const bool moving = state.value(QStringLiteral("moving")).toBool(); - const bool fault = state.value(QStringLiteral("fault")).toBool(); - const bool emergency = state.value(QStringLiteral("emergencyStopped")).toBool(); - const bool protective = state.value(QStringLiteral("protectiveStopped")).toBool(); - const bool freedrive = state.value(QStringLiteral("freedrive")).toBool() - || state.value(QStringLiteral("controlMode")).toInt() == 6; - const int robotMode = state.value(QStringLiteral("robotMode")).toInt(); - const int safetyMode = state.value(QStringLiteral("safetyMode")).toInt(); - const bool isDisconnected = !connected || robotMode == 1; - const bool isEmergency = emergency || safetyMode == 4 || safetyMode == 6; - const bool isFault = fault || robotMode == 7 || safetyMode == 7; - const bool isProtective = protective || safetyMode == 3 || safetyMode == 5; - - const auto setStateLabel = [](QLabel *label, const QString &text, - const QString &visualState) { - if (!label) - return; - label->setText(text); - label->setProperty("state", visualState); - label->style()->unpolish(label); - label->style()->polish(label); - }; - setStateLabel( - m_servoStatusValue, - isDisconnected ? QStringLiteral("已断开") - : freedrive ? QStringLiteral("拖动示教") - : powered ? (moving ? QStringLiteral("已使能 · 运动中") - : QStringLiteral("已使能 · 空闲")) - : QStringLiteral("未使能"), - (isDisconnected || isEmergency || isFault || isProtective) - ? QStringLiteral("error") : QStringLiteral("good")); - setStateLabel( - m_faultStatusValue, - isDisconnected ? QStringLiteral("通信断开") - : isEmergency ? QStringLiteral("急停") - : isFault ? QStringLiteral("故障") - : isProtective ? QStringLiteral("保护停止") - : freedrive ? QStringLiteral("拖动示教") : QStringLiteral("正常"), - (isDisconnected || isEmergency || isFault || isProtective || freedrive) - ? QStringLiteral("error") : QStringLiteral("good")); - - if (isDisconnected) { - updateArmAlert(deviceId, QStringLiteral("disconnected"), - QStringLiteral("ERROR"), QStringLiteral("机械臂已断开"), - QStringLiteral("请检查机械臂电源、网线以及控制器地址。")); - } else if (isEmergency) { - updateArmAlert(deviceId, QStringLiteral("emergency-stop"), - QStringLiteral("ERROR"), QStringLiteral("机械臂处于急停状态"), - QStringLiteral("请确认现场安全后释放急停并清除故障。")); - } else if (isFault) { - updateArmAlert(deviceId, QStringLiteral("fault"), - QStringLiteral("ERROR"), QStringLiteral("机械臂发生故障"), - QStringLiteral("请检查控制器告警信息,排除原因后清除故障。")); - } else if (isProtective) { - updateArmAlert(deviceId, QStringLiteral("protective-stop"), - QStringLiteral("WARN"), QStringLiteral("机械臂处于保护停止状态"), - QStringLiteral("请检查碰撞、限位或安全输入。")); - } else if (freedrive) { - updateArmAlert(deviceId, QStringLiteral("freedrive"), - QStringLiteral("WARN"), QStringLiteral("机械臂处于拖动示教状态"), - QStringLiteral("上位机运动控制暂不可用,请退出拖动示教后再操作。")); - } else { - updateArmAlert(deviceId, QString(), QString(), QString()); - } - } - if (m_armAlertStates.value(deviceId).isEmpty() - && m_bottomLogLevel && m_bottomLogMessage) { - m_bottomLogLevel->setText(QStringLiteral("[OK]")); - m_bottomLogLevel->setProperty("level", QStringLiteral("ok")); - m_bottomLogLevel->style()->unpolish(m_bottomLogLevel); - m_bottomLogLevel->style()->polish(m_bottomLogLevel); - m_bottomLogMessage->setText(QStringLiteral("Arm Telemetry · 已接收 %1 个关节状态 · %2") - .arg(joints.size()).arg(QDateTime::currentDateTime().toString("HH:mm:ss.zzz"))); - } -} - -void MainWindow::updateArmTelemetryHealth(const QString &deviceId, bool available, - const QString &detail) -{ - if (!m_armIdEdit || deviceId != m_armIdEdit->text().trimmed()) - return; - if (available) { - if (m_armAlertStates.value(deviceId) == QStringLiteral("communication")) - updateArmAlert(deviceId, QString(), QString(), QString()); - return; - } - - const auto markError = [](QLabel *label, const QString &text) { - if (!label) - return; - label->setText(text); - label->setProperty("state", QStringLiteral("error")); - label->style()->unpolish(label); - label->style()->polish(label); - }; - markError(m_servoStatusValue, QStringLiteral("遥测中断")); - markError(m_faultStatusValue, QStringLiteral("通信异常")); - updateArmAlert(deviceId, QStringLiteral("communication"), - QStringLiteral("ERROR"), QStringLiteral("机械臂遥测通信异常"), detail); -} - -void MainWindow::updateArmAlert(const QString &deviceId, const QString &alertKey, - const QString &level, const QString &summary, - const QString &detail) -{ - const QString previous = m_armAlertStates.value(deviceId); - if (previous == alertKey) - return; - if (alertKey.isEmpty()) { - m_armAlertStates.remove(deviceId); - if (!previous.isEmpty()) - appendLog(QStringLiteral("OK"), - QStringLiteral("机械臂 %1 状态已恢复正常").arg(deviceId)); - return; - } - - m_armAlertStates.insert(deviceId, alertKey); - const QString message = detail.isEmpty() - ? QStringLiteral("机械臂 %1:%2").arg(deviceId, summary) - : QStringLiteral("机械臂 %1:%2。%3").arg(deviceId, summary, detail); - appendLog(level, message); - - const QString popupKey = deviceId + QLatin1Char('/') + alertKey; - const qint64 nowMs = QDateTime::currentMSecsSinceEpoch(); - const qint64 lastPopupMs = m_armLastAlertPopupMs.value(popupKey, 0); - if (lastPopupMs > 0 && nowMs - lastPopupMs < 30000) - return; - m_armLastAlertPopupMs.insert(popupKey, nowMs); - - QMessageBox *popup = new QMessageBox( - level == QStringLiteral("ERROR") ? QMessageBox::Critical : QMessageBox::Warning, - QStringLiteral("机械臂状态提醒"), message, QMessageBox::Ok, this); - popup->setAttribute(Qt::WA_DeleteOnClose); - popup->setWindowModality(Qt::NonModal); - popup->open(); -} - -void MainWindow::updateSystemStatus(double cpu, double memory, double disk, - const QVariantList &devices) -{ - m_cpuValue->setText(QString::number(cpu, 'f', 0)); - m_memoryValue->setText(QString::number(memory, 'f', 0)); - m_diskValue->setText(QString::number(disk, 'f', 0)); - m_deviceValue->setText(QString::number(devices.size())); - if (!m_armSideCombo) - return; - - const QString previousId = m_armIdEdit && !m_armIdEdit->text().trimmed().isEmpty() - ? m_armIdEdit->text().trimmed() : m_armSideCombo->currentData().toString(); - QString firstArmId; - { - const QSignalBlocker blocker(m_armSideCombo); - m_armSideCombo->clear(); - for (const QVariant &value : devices) { - const QVariantMap device = value.toMap(); - if (device.value(QStringLiteral("type")).toInt() != 6) - continue; - const QString deviceId = device.value(QStringLiteral("deviceId")).toString(); - if (deviceId.isEmpty()) - continue; - if (firstArmId.isEmpty()) - firstArmId = deviceId; - const QString vendor = device.value(QStringLiteral("vendor")).toString(); - const QString driver = device.value(QStringLiteral("driverType")).toString(); - const QString detail = !vendor.isEmpty() ? vendor : driver; - m_armSideCombo->addItem( - detail.isEmpty() ? deviceId : QStringLiteral("%1 · %2").arg(deviceId, detail), - deviceId); - } - int index = m_armSideCombo->findData(previousId); - if (index < 0 && m_armSideCombo->count() > 0) - index = 0; - if (index >= 0) - m_armSideCombo->setCurrentIndex(index); - } - const QString selectedId = m_armSideCombo->currentData().toString(); - if (m_armIdEdit && !selectedId.isEmpty() - && (selectedId != previousId || m_activeArmJointNames.isEmpty())) { - m_armIdEdit->setText(selectedId); - m_client->requestArmInfo(selectedId); - m_client->requestArmFrames(selectedId); - } else if (m_armIdEdit && m_armIdEdit->text().trimmed().isEmpty() - && !firstArmId.isEmpty()) { - m_armIdEdit->setText(firstArmId); - m_client->requestArmInfo(firstArmId); - m_client->requestArmFrames(firstArmId); - } - if (m_connected && m_pages && m_pages->currentIndex() == 1 - && !selectedId.isEmpty() && m_armTelemetryButton - && (selectedId != previousId - || !m_armTelemetryButton->isChecked())) { - setArmTelemetryEnabled(true); - } - -} - -void MainWindow::updateSystemInfo(const QVariantMap &info) -{ - m_systemNameValue->setText(info.value(QStringLiteral("name"), QStringLiteral("--")).toString()); - m_systemVersionValue->setText(info.value(QStringLiteral("version"), QStringLiteral("--")).toString()); - const QString platform = QStringLiteral("%1 · %2") - .arg(info.value(QStringLiteral("os"), QStringLiteral("--")).toString(), - info.value(QStringLiteral("architecture"), QStringLiteral("--")).toString()); - m_systemOsValue->setText(platform); -} - -void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &navigation) -{ - m_latestAgvState = state; - const bool controllerConnected = state.value(QStringLiteral("connected")).toBool(); - const bool localized = state.value(QStringLiteral("localized")).toBool(); - const bool fault = state.value(QStringLiteral("fault")).toBool(); - const bool emergency = state.value(QStringLiteral("emergency")).toBool(); - m_agvConnectionValue->setText(QStringLiteral("%1 · %2%3") - .arg(controllerConnected ? QStringLiteral("在线") : QStringLiteral("离线"), - localized ? QStringLiteral("已定位") : QStringLiteral("未定位"), - (fault || emergency) ? QStringLiteral(" · 异常") : QString())); - m_agvMapValue->setText(QStringLiteral("%1 / %2") - .arg(state.value(QStringLiteral("map"), QStringLiteral("--")).toString(), - state.value(QStringLiteral("station"), QStringLiteral("--")).toString())); - m_agvPoseValue->setText(QStringLiteral("%1, %2, %3") - .arg(state.value(QStringLiteral("x")).toDouble(), 0, 'f', 2) - .arg(state.value(QStringLiteral("y")).toDouble(), 0, 'f', 2) - .arg(state.value(QStringLiteral("theta")).toDouble(), 0, 'f', 2)); - m_agvMotionValue->setText(QStringLiteral("%1 / %2 / %3") - .arg(state.value(QStringLiteral("vx")).toDouble(), 0, 'f', 2) - .arg(state.value(QStringLiteral("vy")).toDouble(), 0, 'f', 2) - .arg(state.value(QStringLiteral("wz")).toDouble(), 0, 'f', 2)); - const bool charging = state.value(QStringLiteral("charging")).toBool(); - m_agvBatteryValue->setText( - QStringLiteral("%1%").arg( - state.value(QStringLiteral("battery")).toDouble() * 100.0, 0, 'f', 0) - + (charging ? QStringLiteral(" · 充电中") : QString())); - m_agvNavigationValue->setText(navigation.value(QStringLiteral("message"), QStringLiteral("--")).toString()); - m_agvErrorValue->setText(state.value(QStringLiteral("error"), QStringLiteral("无")).toString()); - static const QStringList modeNames = { - QStringLiteral("未知"), QStringLiteral("离线"), QStringLiteral("空闲"), - QStringLiteral("手动"), QStringLiteral("自动"), QStringLiteral("充电"), - QStringLiteral("暂停"), QStringLiteral("已停止"), QStringLiteral("故障"), - QStringLiteral("急停") - }; - const int mode = state.value(QStringLiteral("mode")).toInt(); - m_agvModeValue->setText(modeNames.value( - mode, QStringLiteral("模式 %1").arg(mode))); - m_agvMotionStateValue->setText(QStringLiteral("%1 / %2") - .arg(localized ? QStringLiteral("已定位") : QStringLiteral("未定位"), - state.value(QStringLiteral("moving")).toBool() - ? QStringLiteral("运动中") : QStringLiteral("静止"))); - m_agvSafetyValue->setText(QStringLiteral("%1 / %2") - .arg(fault ? QStringLiteral("有故障") : QStringLiteral("正常"), - emergency ? QStringLiteral("已急停") : QStringLiteral("未急停"))); - const double voltage = state.value(QStringLiteral("voltage")).toDouble(); - const double current = state.value(QStringLiteral("current")).toDouble(); - m_agvPowerValue->setText(QStringLiteral("%1 V / %2 A / %3 W / %4 °C") - .arg(voltage, 0, 'f', 2) - .arg(current, 0, 'f', 2) - .arg(qAbs(voltage * current), 0, 'f', 1) - .arg(state.value(QStringLiteral("temperature")).toDouble(), 0, 'f', 1)); - const double timestamp = state.value(QStringLiteral("timestamp")).toDouble(); - m_agvTimestampValue->setText(timestamp > 0.0 - ? QDateTime::fromMSecsSinceEpoch(qRound64(timestamp * 1000.0)) - .toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")) - : QStringLiteral("--")); - m_agvProgress->setValue(qBound(0, qRound(navigation.value(QStringLiteral("progress")).toDouble() * 100.0), 100)); - if (m_agvMapView) { - m_agvMapView->updateRobotPose( - state.value(QStringLiteral("x")).toDouble(), - state.value(QStringLiteral("y")).toDouble(), - state.value(QStringLiteral("theta")).toDouble(), localized); - } -} - -void MainWindow::updateAgvInventory(const QStringList &maps, const QVariantList &stations) -{ - QString selectedMap = m_agvMapCombo->currentText(); - if (selectedMap.trimmed().isEmpty()) - selectedMap = m_latestAgvState.value(QStringLiteral("map")).toString(); - m_agvMapCombo->clear(); - m_agvMapCombo->addItems(maps); - const int mapIndex = m_agvMapCombo->findText(selectedMap); - if (mapIndex >= 0) - m_agvMapCombo->setCurrentIndex(mapIndex); - - const QString selectedStation = m_agvStationCombo->currentText(); - m_agvStationCombo->clear(); - m_agvStationTable->setRowCount(stations.size()); - for (int row = 0; row < stations.size(); ++row) { - const QVariantMap station = stations.at(row).toMap(); - const QString stationId = station.value(QStringLiteral("id")).toString(); - m_agvStationCombo->addItem(stationId); - m_agvStationTable->setItem(row, 0, new QTableWidgetItem(stationId)); - m_agvStationTable->setItem(row, 1, new QTableWidgetItem(station.value(QStringLiteral("type")).toString())); - m_agvStationTable->setItem(row, 2, new QTableWidgetItem(QString::number( - station.value(QStringLiteral("x")).toDouble(), 'f', 3))); - m_agvStationTable->setItem(row, 3, new QTableWidgetItem(QString::number( - station.value(QStringLiteral("y")).toDouble(), 'f', 3))); - } - const int stationIndex = m_agvStationCombo->findText(selectedStation); - if (stationIndex >= 0) - m_agvStationCombo->setCurrentIndex(stationIndex); - - QPixmap preview(960, 280); - preview.fill(QColor(QStringLiteral("#eef2f6"))); - QPainter painter(&preview); - painter.setRenderHint(QPainter::Antialiasing); - painter.setPen(QPen(QColor(QStringLiteral("#d5dee6")), 1)); - for (int x = 60; x < preview.width(); x += 100) - painter.drawLine(x, 24, x, preview.height() - 24); - for (int y = 40; y < preview.height(); y += 60) - painter.drawLine(36, y, preview.width() - 36, y); - if (stations.isEmpty()) { - painter.setPen(QColor(QStringLiteral("#71808e"))); - painter.drawText(preview.rect(), Qt::AlignCenter, - QStringLiteral("当前地图没有可显示的站点")); - } else { - double minX = stations.first().toMap().value(QStringLiteral("x")).toDouble(); - double maxX = minX; - double minY = stations.first().toMap().value(QStringLiteral("y")).toDouble(); - double maxY = minY; - for (const QVariant &entry : stations) { - const QVariantMap station = entry.toMap(); - minX = qMin(minX, station.value(QStringLiteral("x")).toDouble()); - maxX = qMax(maxX, station.value(QStringLiteral("x")).toDouble()); - minY = qMin(minY, station.value(QStringLiteral("y")).toDouble()); - maxY = qMax(maxY, station.value(QStringLiteral("y")).toDouble()); - } - if (qFuzzyCompare(minX, maxX)) { minX -= 1.0; maxX += 1.0; } - if (qFuzzyCompare(minY, maxY)) { minY -= 1.0; maxY += 1.0; } - QPointF previous; - for (int i = 0; i < stations.size(); ++i) { - const QVariantMap station = stations.at(i).toMap(); - const QPointF point( - 60.0 + (station.value(QStringLiteral("x")).toDouble() - minX) / - (maxX - minX) * (preview.width() - 120.0), - 40.0 + (maxY - station.value(QStringLiteral("y")).toDouble()) / - (maxY - minY) * (preview.height() - 80.0)); - if (i > 0) { - painter.setPen(QPen(QColor(QStringLiteral("#9db7ce")), 2)); - painter.drawLine(previous, point); - } - painter.setPen(Qt::NoPen); - painter.setBrush(QColor(QStringLiteral("#218c74"))); - painter.drawEllipse(point, 7, 7); - painter.setPen(QColor(QStringLiteral("#26323d"))); - painter.drawText(point + QPointF(10, -8), - station.value(QStringLiteral("id")).toString()); - previous = point; - } - } - painter.end(); - m_agvMapOverview->setPixmap(preview.scaled( - m_agvMapOverview->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); -} - -void MainWindow::updateImage(const QImage &image, const QString &detail) -{ - m_lastImage = image; - if (m_videoRender) - m_videoRender->setImage(image); - m_imageMetaLabel->setText(detail); - m_saveImageButton->setEnabled(true); -} - -void MainWindow::updateVideoFrame(const QString &cameraId, const VideoFrame &frame, - const QString &detail) -{ - const QString resolvedId = cameraId.isEmpty() && !m_cameraPreviewTiles.isEmpty() - ? m_cameraPreviewTiles.constBegin().key() : cameraId; - const auto it = m_cameraPreviewTiles.find(resolvedId); - if (it == m_cameraPreviewTiles.end()) - return; - it->render->setFrame(frame); - it->meta->setText(detail); - m_imageMetaLabel->setText(QStringLiteral("%1 | %2").arg(resolvedId, detail)); - m_saveImageButton->setEnabled(true); -} - -void MainWindow::updateCameraStreamState(const QString &cameraId, bool running, - const QString &detail) -{ - const QString resolvedId = cameraId.isEmpty() && !m_cameraPreviewTiles.isEmpty() - ? m_cameraPreviewTiles.constBegin().key() : cameraId; - if (running) - m_runningCameraIds.insert(resolvedId); - else - m_runningCameraIds.remove(resolvedId); - - const auto it = m_cameraPreviewTiles.find(resolvedId); - if (it != m_cameraPreviewTiles.end()) { - it->status->setText(running ? QStringLiteral("播放中") - : QStringLiteral("已停止")); - it->status->setToolTip(detail); - if (!running && !detail.isEmpty()) - it->meta->setText(detail); - } - refreshCameraStreamControls(); - m_cameraStreamStateLabel->setToolTip(detail); - if (!detail.isEmpty()) { - const bool failed = detail.contains(QStringLiteral("失败")); - appendLog(failed ? QStringLiteral("ERROR") : QStringLiteral("INFO"), - QStringLiteral("%1: %2").arg(resolvedId, detail)); - } -} - -void MainWindow::updateCameraRecordingState(bool recording, const QString &detail) -{ - m_cameraRecording = recording; - if (!m_cameraRecordButton || !m_cameraRecordPathEdit || !m_cameraRecordStateLabel) - return; - m_cameraRecordButton->setEnabled(m_connected); - m_cameraRecordButton->setText(recording ? QStringLiteral("停止录像") - : QStringLiteral("开始录像")); - m_cameraRecordButton->setIcon(style()->standardIcon( - recording ? QStyle::SP_MediaStop : QStyle::SP_DialogSaveButton)); - m_cameraRecordButton->setObjectName(recording ? QStringLiteral("dangerButton") - : QStringLiteral("primaryButton")); - m_cameraRecordButton->style()->unpolish(m_cameraRecordButton); - m_cameraRecordButton->style()->polish(m_cameraRecordButton); - m_cameraRecordPathEdit->setEnabled(!recording); - m_cameraIdEdit->setEnabled(!m_cameraStreaming && !recording); - m_cameraRecordStateLabel->setText(recording ? QStringLiteral("录像中") - : QStringLiteral("未录像")); - m_cameraRecordStateLabel->setToolTip(detail); - if (!detail.isEmpty()) - appendLog(QStringLiteral("INFO"), detail); -} - -void MainWindow::handleCommand(const QString &command, bool success, const QString &detail) -{ - QLabel *stateLabel = nullptr; - QString stateText; - if (command == QStringLiteral("Torque On")) { - stateLabel = m_servoStatusValue; - stateText = success ? QStringLiteral("已使能") : QStringLiteral("使能失败"); - } else if (command == QStringLiteral("Torque Off")) { - stateLabel = m_servoStatusValue; - stateText = success ? QStringLiteral("已去使能") : QStringLiteral("操作失败"); - } else if (command == QStringLiteral("Clear Fault")) { - stateLabel = m_faultStatusValue; - stateText = success ? QStringLiteral("正常") : QStringLiteral("清除失败"); - } - if (stateLabel) { - stateLabel->setText(stateText); - stateLabel->setProperty("state", success ? QStringLiteral("good") - : QStringLiteral("error")); - stateLabel->style()->unpolish(stateLabel); - stateLabel->style()->polish(stateLabel); - } - if (!success && (command == QStringLiteral("Camera Start Recording") - || command == QStringLiteral("Camera Stop Recording"))) { - updateCameraRecordingState(m_cameraRecording, detail); - } - if (success && command == QStringLiteral("AGV SwitchMap")) { - m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); - restartAgvMapStream(m_agvMapCombo->currentText()); - } - if (success && command == QStringLiteral("AGV StopMapping")) { - m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); - restartAgvMapStream(); - } - - appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"), - QStringLiteral("%1 · %2").arg(command, detail)); - if (!success) - m_connectionText->setToolTip(detail); -} - -void MainWindow::appendLog(const QString &level, const QString &message) -{ - if (m_bottomLogLevel && m_bottomLogMessage) { - const QString normalizedLevel = level.toLower(); - m_bottomLogLevel->setText(QStringLiteral("[%1]").arg(level)); - m_bottomLogLevel->setProperty("level", normalizedLevel); - m_bottomLogLevel->style()->unpolish(m_bottomLogLevel); - m_bottomLogLevel->style()->polish(m_bottomLogLevel); - m_bottomLogMessage->setText(QStringLiteral("%1 · %2") - .arg(message, QDateTime::currentDateTime().toString("HH:mm:ss.zzz"))); - m_bottomLogMessage->setToolTip(message); - } - if (!m_logView) - return; - QString color = QStringLiteral("#aeb6c0"); - if (level == QStringLiteral("ERROR")) - color = QStringLiteral("#ff7b72"); - else if (level == QStringLiteral("WARN")) - color = QStringLiteral("#e3b341"); - else if (level == QStringLiteral("OK")) - color = QStringLiteral("#56d39b"); - const QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz"); - m_logView->append(QStringLiteral("%1 " - "[%3] %4") - .arg(timestamp, color, level, message.toHtmlEscaped())); -} - -void MainWindow::sendMoveJ() -{ - QVariantList positions; - for (QDoubleSpinBox *spin : m_targetSpins) - positions.append(qDegreesToRadians(spin->value())); - m_client->requestMoveJ(m_armIdEdit->text().trimmed(), positions, - m_velocitySpin->value(), m_accelerationSpin->value()); -} - -void MainWindow::sendMoveJPose() -{ - if (m_moveJPoseSpins.size() != 6 || !m_moveJPoseBaseLinkCombo) - return; - QVariantMap pose; - static const QStringList keys = { - QStringLiteral("x"), QStringLiteral("y"), QStringLiteral("z"), - QStringLiteral("rx"), QStringLiteral("ry"), QStringLiteral("rz") - }; - for (int i = 0; i < keys.size(); ++i) - pose.insert(keys.at(i), m_moveJPoseSpins.at(i)->value()); - m_client->requestMoveJPose(m_armIdEdit->text().trimmed(), pose, - m_armDefaultBaseFrame, - m_armDefaultTcpFrame, - m_velocitySpin->value(), m_accelerationSpin->value()); -} - -void MainWindow::saveSnapshot() -{ - QImage image = m_cameraStreaming && m_videoRender - ? m_videoRender->grabFramebuffer() : m_lastImage; - if (image.isNull()) - return; - const QString defaultName = QStringLiteral("cmvr_rgb_%1.png") - .arg(QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss")); - const QString path = QFileDialog::getSaveFileName(this, QStringLiteral("保存 RGB 图像"), - defaultName, QStringLiteral("PNG 图像 (*.png);;JPEG 图像 (*.jpg)")); - if (path.isEmpty()) - return; - const bool saved = image.save(path); - appendLog(saved ? QStringLiteral("OK") : QStringLiteral("ERROR"), - saved ? QStringLiteral("图像已保存:%1").arg(path) - : QStringLiteral("图像保存失败:%1").arg(path)); -} - -void MainWindow::loadSettings() -{ - QSettings settings; - m_hostEdit->setText(settings.value(QStringLiteral("connection/host"), QStringLiteral("192.168.0.28")).toString()); - m_hostEdit->setCursorPosition(0); - m_portSpin->setValue(settings.value(QStringLiteral("connection/port"), 50052).toInt()); - m_demoCheck->setChecked(settings.value(QStringLiteral("connection/demo"), true).toBool()); - m_systemTargetEdit->setText(settings.value(QStringLiteral("system/target"), QStringLiteral("*")).toString()); - QString armDeviceId = settings.value(QStringLiteral("arm/device"), - QStringLiteral("demo_arm")).toString().trimmed(); - m_armIdEdit->setText(armDeviceId); - if (m_armSideCombo && !armDeviceId.isEmpty()) - m_armSideCombo->addItem(armDeviceId, armDeviceId); - m_cameraIdEdit->setText(settings.value(QStringLiteral("camera/device"), QStringLiteral("camera")).toString()); - rebuildCameraPreviewGrid(configuredCameraIds()); - m_cameraRecordPathEdit->setText(settings.value( - QStringLiteral("camera/recordPath"), - QStringLiteral("/mnt/data/cmvr/record/camera.mp4")).toString()); - const QString cameraCodec = settings.value(QStringLiteral("camera/codec"), - QStringLiteral("h264")).toString().toLower(); - m_cameraCodecCombo->setCurrentIndex( - cameraCodec == QStringLiteral("h265") || cameraCodec == QStringLiteral("hevc") ? 1 : 0); - if (m_cameraStreamModeCombo) { - const QString cameraMode = settings.value(QStringLiteral("camera/streamMode"), - QStringLiteral("rgb")).toString().toLower(); - const int modeIndex = m_cameraStreamModeCombo->findData(cameraMode); - if (modeIndex >= 0) - m_cameraStreamModeCombo->setCurrentIndex(modeIndex); - } - m_agvIdEdit->setText(settings.value(QStringLiteral("agv/device"), QStringLiteral("agv")).toString()); - m_velocitySpin->setValue(settings.value( - QStringLiteral("motion/speedJVelocity"), - settings.value(QStringLiteral("motion/velocity"), 1.0)).toDouble()); - m_accelerationSpin->setValue(settings.value( - QStringLiteral("motion/speedJAcceleration"), - settings.value(QStringLiteral("motion/acceleration"), 0.5)).toDouble()); - if (m_cartesianVelocitySpin) - m_cartesianVelocitySpin->setValue(settings.value( - QStringLiteral("motion/speedLVelocity"), 0.25).toDouble()); - if (m_cartesianAccelerationSpin) - m_cartesianAccelerationSpin->setValue(settings.value( - QStringLiteral("motion/speedLAcceleration"), 0.5).toDouble()); - const QDir applicationDirectory(QCoreApplication::applicationDirPath()); - const QString defaultUrdf = applicationDirectory.filePath(QStringLiteral("models/demo_arm.urdf")); - QString configuredUrdf = settings.value(QStringLiteral("arm/urdf"), defaultUrdf) - .toString().trimmed(); - if (!configuredUrdf.isEmpty() && QFileInfo(configuredUrdf).isRelative()) - configuredUrdf = applicationDirectory.absoluteFilePath(configuredUrdf); - m_pendingUrdfPath = QFileInfo::exists(configuredUrdf) - ? QFileInfo(configuredUrdf).absoluteFilePath() - : (QFileInfo::exists(defaultUrdf) ? QFileInfo(defaultUrdf).absoluteFilePath() - : QString()); - m_quicBindEdit->setText(settings.value(QStringLiteral("quic/bindAddress"), - QStringLiteral("127.0.0.1")).toString()); - m_quicPortSpin->setValue(settings.value(QStringLiteral("quic/port"), 4433).toInt()); - m_quicAlpnEdit->setText(settings.value(QStringLiteral("quic/alpn"), - QStringLiteral("cmvr-quic-edge/1")).toString()); - const QDir applicationDir(QCoreApplication::applicationDirPath()); - const QString defaultCertificate = applicationDir.filePath( - QStringLiteral("quic-test-server.pfx")); - QString certificatePath = settings.value( - QStringLiteral("quic/certificate"), - QStringLiteral("quic-test-server.pfx")).toString().trimmed(); - if (QFileInfo(certificatePath).isRelative()) - certificatePath = applicationDir.filePath(certificatePath); - if (!QFileInfo(certificatePath).isFile()) { - certificatePath = defaultCertificate; - settings.setValue(QStringLiteral("quic/certificate"), - QStringLiteral("quic-test-server.pfx")); - } - m_quicCertificateEdit->setText(QDir::toNativeSeparators(certificatePath)); - m_quicPasswordEdit->setText(QStringLiteral("cmvr-test")); - m_endpointValue->setText(endpoint()); - if (m_sidebarEndpointValue) - m_sidebarEndpointValue->setText(endpoint()); -} - -void MainWindow::saveSettings() -{ - QSettings settings; - settings.setValue(QStringLiteral("connection/host"), m_hostEdit->text().trimmed()); - settings.setValue(QStringLiteral("connection/port"), m_portSpin->value()); - settings.setValue(QStringLiteral("connection/demo"), m_demoCheck->isChecked()); - settings.setValue(QStringLiteral("system/target"), m_systemTargetEdit->text().trimmed()); - settings.setValue(QStringLiteral("arm/device"), m_armIdEdit->text().trimmed()); - settings.setValue(QStringLiteral("camera/device"), m_cameraIdEdit->text().trimmed()); - settings.setValue(QStringLiteral("camera/recordPath"), - m_cameraRecordPathEdit->text().trimmed()); - settings.setValue(QStringLiteral("camera/codec"), - m_cameraCodecCombo->currentIndex() == 1 - ? QStringLiteral("h265") : QStringLiteral("h264")); - if (m_cameraStreamModeCombo) - settings.setValue(QStringLiteral("camera/streamMode"), - m_cameraStreamModeCombo->currentData().toString()); - settings.setValue(QStringLiteral("agv/device"), m_agvIdEdit->text().trimmed()); - settings.setValue(QStringLiteral("motion/speedJVelocity"), m_velocitySpin->value()); - settings.setValue(QStringLiteral("motion/speedJAcceleration"), - m_accelerationSpin->value()); - if (m_cartesianVelocitySpin) - settings.setValue(QStringLiteral("motion/speedLVelocity"), - m_cartesianVelocitySpin->value()); - if (m_cartesianAccelerationSpin) - settings.setValue(QStringLiteral("motion/speedLAcceleration"), - m_cartesianAccelerationSpin->value()); - if (m_urdfViewer && !m_urdfViewer->currentFile().isEmpty()) - settings.setValue(QStringLiteral("arm/urdf"), m_urdfViewer->currentFile()); - else if (!m_pendingUrdfPath.isEmpty()) - settings.setValue(QStringLiteral("arm/urdf"), m_pendingUrdfPath); - settings.setValue(QStringLiteral("quic/bindAddress"), m_quicBindEdit->text().trimmed()); - settings.setValue(QStringLiteral("quic/port"), m_quicPortSpin->value()); - settings.setValue(QStringLiteral("quic/alpn"), m_quicAlpnEdit->text().trimmed()); - const QString certificatePath = QDir::fromNativeSeparators( - m_quicCertificateEdit->text().trimmed()); - const QString bundledCertificate = QDir(QCoreApplication::applicationDirPath()) - .filePath(QStringLiteral("quic-test-server.pfx")); - settings.setValue( - QStringLiteral("quic/certificate"), - QFileInfo(certificatePath).absoluteFilePath() == - QFileInfo(bundledCertificate).absoluteFilePath() - ? QStringLiteral("quic-test-server.pfx") - : certificatePath); -} - -void MainWindow::setControlsEnabled(bool enabled) -{ - for (QPushButton *button : m_serviceButtons) { - if (button) - button->setEnabled(enabled); - } - for (QDoubleSpinBox *spin : m_targetSpins) - spin->setEnabled(enabled); - for (QDoubleSpinBox *spin : m_moveJPoseSpins) - spin->setEnabled(enabled); - if (m_moveJPoseBaseLinkCombo) - m_moveJPoseBaseLinkCombo->setEnabled(enabled); - if (m_velocitySpin) - m_velocitySpin->setEnabled(enabled); - if (m_accelerationSpin) - m_accelerationSpin->setEnabled(enabled); - if (m_cartesianVelocitySpin) - m_cartesianVelocitySpin->setEnabled(enabled); - if (m_cartesianAccelerationSpin) - m_cartesianAccelerationSpin->setEnabled(enabled); - 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()); -} +#include "mainwindow.h" +#include "videorenderwidget.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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef Q_OS_WIN +#include +#endif + +namespace { +const QStringList kPageTitles = { + QStringLiteral("系统概览"), QStringLiteral("机械臂"), + QStringLiteral("相机"), QStringLiteral("AGV"), + QStringLiteral("扬声器"), QStringLiteral("麦克风"), + QStringLiteral("灵巧手"), QStringLiteral("仿生头"), + QStringLiteral("HLC 控制"), QStringLiteral("接口调试"), + QStringLiteral("QUIC Server"), 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("视觉取点与触控笔单击、双击、滑动") +}; + +} + +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 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 deviceButtons = { + ui.armNavButton, ui.cameraNavButton, ui.agvNavButton, + ui.speakerNavButton, ui.microphoneNavButton, + ui.dexhandNavButton, ui.bioheadNavButton + }; + ui.agvNavButton->setText(QStringLiteral("AGV")); + for (QPushButton *button : deviceButtons) { + button->setParent(deviceContent); + button->setProperty("navLevel", 2); + deviceLayout->addWidget(button); + } + + QPushButton *complexGroupButton = createGroupButton( + QStringLiteral("复杂操作"), grpcContent, 1); + const auto complexSection = createNavContainer(grpcContent); + QWidget *complexContent = complexSection.first; + QVBoxLayout *complexLayout = complexSection.second; + QPushButton *toolCalibrationNavButton = createPageButton( + QStringLiteral("工具坐标标定"), complexContent, 2); + QPushButton *handEyeNavButton = createPageButton( + QStringLiteral("手眼标定"), complexContent, 2); + QPushButton *touchNavButton = createPageButton( + QStringLiteral("末端操作"), complexContent, 2); + 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(complexGroupButton); + grpcLayout->addWidget(complexContent); + + ui.systemNavButton->setParent(navTree); + ui.systemNavButton->setProperty("navLevel", 0); + ui.testNavButton->setParent(navTree); + ui.testNavButton->setProperty("navLevel", 0); + ui.quicNavButton->setParent(navTree); + ui.quicNavButton->setProperty("navLevel", 0); + ui.diagnosticsNavButton->setParent(navTree); + ui.diagnosticsNavButton->setProperty("navLevel", 0); + navTreeLayout->addWidget(ui.systemNavButton); + navTreeLayout->addWidget(grpcGroupButton); + navTreeLayout->addWidget(grpcContent); + navTreeLayout->addWidget(ui.testNavButton); + navTreeLayout->addWidget(ui.quicNavButton); + navTreeLayout->addWidget(ui.diagnosticsNavButton); + navTreeLayout->addStretch(1); + + m_navGroup = new QButtonGroup(this); + m_navGroup->setExclusive(true); + m_navButtons = { + ui.systemNavButton, ui.armNavButton, ui.cameraNavButton, + ui.agvNavButton, ui.speakerNavButton, ui.microphoneNavButton, + ui.dexhandNavButton, ui.bioheadNavButton, ui.hlcNavButton, + ui.testNavButton, ui.quicNavButton, ui.configurationNavButton, + ui.diagnosticsNavButton, toolCalibrationNavButton, handEyeNavButton, touchNavButton + }; + 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") + }; + 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::of(&QButtonGroup::buttonClicked), + this, &MainWindow::selectPage); + connect(m_connectButton, &QPushButton::clicked, this, &MainWindow::toggleConnection); + + m_pages->addWidget(createSystemPage()); + m_pages->addWidget(createArmPage()); + m_pages->addWidget(createCameraPage()); + m_pages->addWidget(createAgvPage()); + m_pages->addWidget(createAudioPage(true)); + m_pages->addWidget(createAudioPage(false)); + m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.DexHandService"))); + m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.BioHeadService"))); + m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.HlcService"))); + m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.TestService"))); + m_pages->addWidget(createQuicPage()); + auto *deviceManager = new ConfigEditorWidget(m_client, m_pages); + m_pages->addWidget(deviceManager); + connect(deviceManager, &ConfigEditorWidget::deviceNavigationRequested, this, + [this](int deviceType, const QString &deviceId) { + int pageIndex = -1; + switch (deviceType) { + case 6: + pageIndex = 1; + if (m_armSideCombo) { + int index = m_armSideCombo->findData(deviceId); + if (index < 0) { + m_armSideCombo->addItem(deviceId, deviceId); + index = m_armSideCombo->count() - 1; + } + m_armSideCombo->setCurrentIndex(index); + } else if (m_armIdEdit) { + m_armIdEdit->setText(deviceId); + } + break; + case 2: + pageIndex = 2; + if (m_cameraIdEdit) m_cameraIdEdit->setText(deviceId); + break; + case 0: + pageIndex = 3; + if (m_agvIdEdit) m_agvIdEdit->setText(deviceId); + break; + case 7: + pageIndex = 4; + if (m_speakerIdEdit) m_speakerIdEdit->setText(deviceId); + break; + case 5: + pageIndex = 5; + if (m_microphoneIdEdit) m_microphoneIdEdit->setText(deviceId); + break; + case 3: + pageIndex = 6; + break; + case 8: + pageIndex = 7; + break; + default: + break; + } + if (pageIndex < 0) + return; + if (auto *rpcPage = qobject_cast(m_pages->widget(pageIndex))) + rpcPage->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); + QMessageBox::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(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::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_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(); + + const QString comboPopupStyle = QStringLiteral( + "QListView {" + " background: #ffffff; color: #33404c;" + " border: 1px solid #cfd4da; border-radius: 4px;" + " padding: 4px; outline: 0;" + "}" + "QListView::item {" + " min-height: 32px; padding: 0 10px;" + " border: none; border-radius: 3px;" + "}" + "QListView::item:hover {" + " color: #27313b; background: #f3f7fb;" + "}" + "QListView::item:selected {" + " color: #145da8; background: #e8f2ff; font-weight: 600;" + "}" + ); + const QList comboBoxes = findChildren(); + for (QComboBox *comboBox : comboBoxes) { + QListView *popupView = new QListView(comboBox); + popupView->setObjectName(QStringLiteral("comboPopupView")); + popupView->setSpacing(1); + popupView->setUniformItemSizes(true); + popupView->setStyleSheet(comboPopupStyle); + comboBox->setView(popupView); + } + + connect(m_client, &RobotClient::connectionChanged, this, &MainWindow::updateConnection); + connect(m_client, &RobotClient::armInfoReceived, this, &MainWindow::updateArmInfo); + connect(m_client, &RobotClient::telemetryReceived, this, &MainWindow::updateTelemetry); + connect(m_client, &RobotClient::armTelemetryHealthChanged, + this, &MainWindow::updateArmTelemetryHealth); + connect(m_client, &RobotClient::systemStatusReceived, this, &MainWindow::updateSystemStatus); + connect(m_client, &RobotClient::systemInfoReceived, this, &MainWindow::updateSystemInfo); + connect(m_client, &RobotClient::imageReceived, this, &MainWindow::updateImage); + connect(m_client, &RobotClient::videoFrameReceived, this, &MainWindow::updateVideoFrame); + connect(m_client, &RobotClient::cameraStreamStateChanged, + this, &MainWindow::updateCameraStreamState); + connect(m_client, &RobotClient::cameraRecordingStateChanged, + this, &MainWindow::updateCameraRecordingState); + connect(m_client, &RobotClient::agvStateReceived, this, &MainWindow::updateAgvState); + connect(m_client, &RobotClient::agvInventoryReceived, this, &MainWindow::updateAgvInventory); + connect(m_client, &RobotClient::agvMapFrameReceived, this, + [this](const QImage &image, const QString &detail) { + m_agvMappingPreview->setText(QString()); + m_agvMappingPreview->setPixmap(QPixmap::fromImage(image).scaled( + m_agvMappingPreview->size(), Qt::KeepAspectRatio, + Qt::SmoothTransformation)); + m_agvMappingStateLabel->setText(detail); + }); + connect(m_client, &RobotClient::agvMapStreamStateChanged, this, + [this](bool running, const QString &detail) { + m_agvMappingStateLabel->setProperty("running", running); + m_agvMappingStateLabel->setText(detail); + m_agvMappingStateLabel->style()->unpolish(m_agvMappingStateLabel); + m_agvMappingStateLabel->style()->polish(m_agvMappingStateLabel); + }); + connect(m_client, &RobotClient::commandFinished, this, &MainWindow::handleCommand); + connect(m_client, &RobotClient::logMessage, this, &MainWindow::appendLog); + connect(m_audioManager, &AudioStreamManager::speakerFrameReady, + m_client, &RobotClient::sendSpeakerAudioFrame); + connect(m_client, &RobotClient::audioFrameReceived, + m_audioManager, &AudioStreamManager::playPcmFrame); + connect(m_audioManager, &AudioStreamManager::logMessage, + this, &MainWindow::appendLog); + connect(m_quicServer, &QuicTestServer::runningChanged, + this, &MainWindow::updateQuicRunning); + connect(m_quicServer, &QuicTestServer::clientCountChanged, this, [this](int count) { + m_quicClientValue->setText(QString::number(count)); + }); + connect(m_quicServer, &QuicTestServer::statisticsChanged, this, + [this](quint64 registrations, quint64 heartbeats, + quint64 datagrams, quint64 datagramBytes) { + m_quicRegistrationValue->setText(QString::number(registrations)); + m_quicHeartbeatValue->setText(QString::number(heartbeats)); + m_quicDatagramValue->setText(QString::number(datagrams)); + m_quicDatagramBytesValue->setText(QString::number(datagramBytes)); + }); + connect(m_quicServer, &QuicTestServer::nodeRegistered, this, + [this](const QString &nodeId, const QString &bootId, + const QString &grpcEndpoint, const QString &peerAddress) { + m_quicNodeValue->setText(nodeId); + m_quicBootValue->setText(bootId); + m_quicGrpcValue->setText(grpcEndpoint); + m_quicPeerValue->setText(peerAddress); + }); + connect(m_quicServer, &QuicTestServer::logMessage, + this, &MainWindow::appendQuicLog); + + loadSettings(); + const QStringList startupArguments = QCoreApplication::arguments(); + const int cameraCodecArgument = startupArguments.indexOf( + QStringLiteral("--camera-codec")); + if (cameraCodecArgument >= 0 && cameraCodecArgument + 1 < startupArguments.size()) { + const QString codec = startupArguments.at(cameraCodecArgument + 1).trimmed().toLower(); + m_cameraCodecCombo->setCurrentIndex( + codec == QStringLiteral("h265") || codec == QStringLiteral("hevc") ? 1 : 0); + } + int initialPage = 0; + const QStringList arguments = startupArguments; + const int pageArgument = arguments.indexOf(QStringLiteral("--page-index")); + if (pageArgument >= 0 && pageArgument + 1 < arguments.size()) { + bool validPage = false; + const int requestedPage = arguments.at(pageArgument + 1).toInt(&validPage); + if (validPage && requestedPage >= 0 && requestedPage < m_pages->count()) + initialPage = requestedPage; + } + selectPage(initialPage); + setControlsEnabled(false); + appendLog(QStringLiteral("INFO"), QStringLiteral("CMVR 控制台已启动")); + appendLog(QStringLiteral("INFO"), m_client->grpcAvailable() + ? QStringLiteral("原生 gRPC 后端可用") + : QStringLiteral("当前为界面构建,真实 gRPC 后端未编译")); + + QTimer::singleShot(250, this, [this]() { + if (m_demoCheck->isChecked()) + toggleConnection(); + }); + QTimer::singleShot(0, this, &MainWindow::updateWindowChrome); +} + +MainWindow::~MainWindow() +{ + if (m_touchOperation) m_touchOperation->stop(); + if (m_tcpJog) m_tcpJog->stop(); + m_audioManager->stopSource(); + m_audioManager->stopPlayback(); + m_client->stopSpeakerAudioStream(); + m_client->stopMicrophoneAudioStream(); + m_quicServer->stopServer(); + saveSettings(); +} + +bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) +{ +#ifdef Q_OS_WIN + Q_UNUSED(eventType) + MSG *nativeMessage = static_cast(message); + if (nativeMessage && nativeMessage->message == WM_GETMINMAXINFO && result) { + MINMAXINFO *minMaxInfo = reinterpret_cast(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(target)) { + *result = HTCLIENT; + return true; + } + target = target->parentWidget(); + } + *result = HTCAPTION; + return true; + } + } + } +#else + Q_UNUSED(eventType) + Q_UNUSED(message) + Q_UNUSED(result) +#endif + return QMainWindow::nativeEvent(eventType, message, result); +} + +void MainWindow::changeEvent(QEvent *event) +{ + QMainWindow::changeEvent(event); + if (event && event->type() == QEvent::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(m_quicPortSpin->value()), + m_quicAlpnEdit->text().trimmed(), + m_quicCertificateEdit->text().trimmed(), + m_quicPasswordEdit->text()); +} + +void MainWindow::updateQuicRunning(bool running, quint16 port, const QString &detail) +{ + m_quicToggleButton->setEnabled(true); + m_quicToggleButton->setText(running ? QStringLiteral("停止 QUIC Server") + : QStringLiteral("启动 QUIC Server")); + m_quicToggleButton->setObjectName(running ? QStringLiteral("dangerButton") + : QStringLiteral("primaryButton")); + m_quicToggleButton->style()->unpolish(m_quicToggleButton); + m_quicToggleButton->style()->polish(m_quicToggleButton); + m_quicStateValue->setText(running ? QStringLiteral("运行中") : detail); + m_quicBoundValue->setText(running + ? QStringLiteral("%1:%2").arg(m_quicBindEdit->text().trimmed()).arg(port) + : QStringLiteral("--")); + if (m_sidebarQuicValue) { + m_sidebarQuicValue->setText(running + ? QStringLiteral("QUIC %1:%2").arg(m_quicBindEdit->text().trimmed()).arg(port) + : QStringLiteral("QUIC 未启动")); + m_sidebarQuicValue->setToolTip(detail); + } + m_quicBindEdit->setEnabled(!running); + m_quicPortSpin->setEnabled(!running); + m_quicAlpnEdit->setEnabled(!running); + m_quicCertificateEdit->setEnabled(!running); + m_quicPasswordEdit->setEnabled(!running); + appendQuicLog(running ? QStringLiteral("OK") : QStringLiteral("INFO"), detail); +} + +void MainWindow::appendQuicLog(const QString &level, const QString &message) +{ + if (!m_quicLogView) + return; + QString color = QStringLiteral("#aeb6c0"); + if (level == QStringLiteral("ERROR")) + color = QStringLiteral("#ff7b72"); + else if (level == QStringLiteral("WARN")) + color = QStringLiteral("#e3b341"); + else if (level == QStringLiteral("OK")) + color = QStringLiteral("#56d39b"); + const QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz"); + m_quicLogView->append(QStringLiteral("%1 " + "[%3] %4") + .arg(timestamp, color, level, message.toHtmlEscaped())); +} + +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(); + m_pages->setCurrentIndex(index); + m_pageTitle->setText(kPageTitles.at(index)); + m_pageSubtitle->setText(kPageSubtitles.at(index)); + if (m_titleBarPage && index < m_navButtons.size()) + m_titleBarPage->setText(m_navButtons.at(index)->text()); + if (m_armHeaderControls) + m_armHeaderControls->setVisible(index == 1); + if (index == 1) + ensureArmModelLoaded(); + if (index != 3 && m_agvStatusSwitch && m_agvStatusSwitch->isChecked()) + m_agvStatusSwitch->setChecked(false); + if (index < m_navButtons.size()) + m_navButtons.at(index)->setChecked(true); +} + +void MainWindow::ensureArmModelLoaded() +{ + if (!m_urdfViewer || m_pendingUrdfPath.isEmpty() + || !m_urdfViewer->currentFile().isEmpty() || m_armModelLoadScheduled) { + return; + } + + m_armModelLoadScheduled = true; + m_urdfViewer->prepareLoad(m_pendingUrdfPath); + QTimer::singleShot(450, this, [this]() { + if (!m_pages || m_pages->currentIndex() != 1) { + m_armModelLoadScheduled = false; + return; + } + const QString path = m_pendingUrdfPath; + if (m_urdfViewer && m_urdfViewer->currentFile().isEmpty()) + m_urdfViewer->loadUrdf(path); + m_armModelLoadScheduled = false; + }); +} + +void MainWindow::toggleConnection() +{ + if (m_connected) { + if (m_tcpJog) m_tcpJog->stop(); + m_connectButton->setEnabled(false); + m_connectButton->setText(QStringLiteral("正在断开…")); + m_client->disconnectFromServer(); + return; + } + + if (m_hostEdit->text().trimmed().isEmpty()) { + QMessageBox::warning(this, QStringLiteral("连接参数"), QStringLiteral("请填写主机地址。")); + return; + } + saveSettings(); + // 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; + 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 && m_agvStatusSwitch + && m_agvStatusSwitch->isChecked()) { + if (connected) { + m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); + m_agvStatusRefreshTimer->start(); + } else { + m_agvStatusRefreshTimer->stop(); + } + } + if (!connected) { + m_audioManager->stopSource(); + m_audioManager->stopPlayback(); + m_runningCameraIds.clear(); + for (auto it = m_cameraPreviewTiles.begin(); + it != m_cameraPreviewTiles.end(); ++it) { + it->status->setText(QStringLiteral("已断开")); + } + refreshCameraStreamControls(); + } + if (!connected && m_armTelemetryButton) { + m_armTelemetryButton->setChecked(false); + m_armTelemetryButton->setText(QStringLiteral("遥测 未启动")); + m_armTelemetryButton->setProperty("active", false); + m_armTelemetryButton->style()->unpolish(m_armTelemetryButton); + m_armTelemetryButton->style()->polish(m_armTelemetryButton); + if (m_armSideCombo) + m_armSideCombo->setEnabled(true); + } + if (!connected) { + m_armAlertStates.clear(); + const QList armStates = {m_servoStatusValue, m_faultStatusValue}; + for (QLabel *label : armStates) { + if (!label) + continue; + label->setText(QStringLiteral("未知")); + label->setProperty("state", QStringLiteral("unknown")); + label->style()->unpolish(label); + label->style()->polish(label); + } + } + if (connected) + m_client->requestSystemRefresh(); + appendLog(connected ? QStringLiteral("INFO") : QStringLiteral("WARN"), detail); +} + +void MainWindow::rebuildArmJointTables(const QStringList &jointNames) +{ + if (!m_jointTable) + return; + m_activeArmJointNames = jointNames; + m_jointTable->clearContents(); + m_jointTable->setRowCount(jointNames.size()); + for (int row = 0; row < jointNames.size(); ++row) { + m_jointTable->setItem(row, 0, new QTableWidgetItem(jointNames.at(row))); + for (int column = 1; column < 4; ++column) + m_jointTable->setItem(row, column, new QTableWidgetItem(QStringLiteral("--"))); + } + + if (m_zeroJointCombo) { + const QSignalBlocker blocker(m_zeroJointCombo); + m_zeroJointCombo->clear(); + m_zeroJointCombo->addItems(jointNames); + } + if (m_calibrateZeroButton) + m_calibrateZeroButton->setEnabled(m_connected && !jointNames.isEmpty()); + m_previousJointVelocities.clear(); + m_lastArmTelemetryMs = 0; + rebuildArmJogControls(); +} + +void MainWindow::rebuildArmJogControls() +{ + if (!m_jointJogRowsLayout || !m_jointJogRowsHost) + return; + while (QLayoutItem *item = m_jointJogRowsLayout->takeAt(0)) { + if (QWidget *widget = item->widget()) + widget->deleteLater(); + delete item; + } + m_jointJogPositionLabels.clear(); + m_jointJogPositionSliders.clear(); + m_jointJogMinusButtons.clear(); + m_jointJogPlusButtons.clear(); + + for (int jointIndex = 0; jointIndex < m_activeArmJointNames.size(); ++jointIndex) { + QFrame *row = new QFrame(m_jointJogRowsHost); + row->setObjectName(QStringLiteral("jogAxisRow")); + QHBoxLayout *layout = new QHBoxLayout(row); + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(6); + QLabel *name = new QLabel(m_activeArmJointNames.at(jointIndex), row); + name->setMinimumWidth(76); + name->setToolTip(m_activeArmJointNames.at(jointIndex)); + QLabel *position = new QLabel(QStringLiteral("-- rad"), row); + position->setObjectName(QStringLiteral("jogCurrentValue")); + position->setMinimumWidth(86); + QPushButton *minus = new QPushButton(QStringLiteral("−"), row); + QPushButton *plus = new QPushButton(QStringLiteral("+"), row); + minus->setObjectName(QStringLiteral("jogDirectionButton")); + plus->setObjectName(QStringLiteral("jogDirectionButton")); + minus->setFixedSize(38, 32); + plus->setFixedSize(38, 32); + minus->setToolTip(QStringLiteral("按住使 %1 反向运动").arg( + m_activeArmJointNames.at(jointIndex))); + plus->setToolTip(QStringLiteral("按住使 %1 正向运动").arg( + m_activeArmJointNames.at(jointIndex))); + QSlider *direction = new QSlider(Qt::Horizontal, row); + direction->setObjectName(QStringLiteral("jogDirectionIndicator")); + direction->setRange(0, 1000); + direction->setValue(0); + direction->setToolTip(QStringLiteral("等待 URDF 关节限位和实时位置")); + direction->setEnabled(false); + layout->addWidget(name); + layout->addWidget(position); + layout->addWidget(minus); + layout->addWidget(direction, 1); + layout->addWidget(plus); + connect(minus, &QPushButton::pressed, this, + [this, jointIndex]() { startJointJog(jointIndex, -1); }); + connect(plus, &QPushButton::pressed, this, + [this, jointIndex]() { startJointJog(jointIndex, 1); }); + connect(minus, &QPushButton::released, this, &MainWindow::stopArmJog); + connect(plus, &QPushButton::released, this, &MainWindow::stopArmJog); + m_jointJogRowsLayout->addWidget(row); + m_jointJogPositionLabels.append(position); + m_jointJogPositionSliders.append(direction); + m_jointJogMinusButtons.append(minus); + m_jointJogPlusButtons.append(plus); + } + m_jointJogRowsLayout->addStretch(1); +} + +void MainWindow::startJointJog(int jointIndex, int direction) +{ + if (m_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(configuredCameraIds()); + m_handEyeMotion->setContext(endpoint(),device,m_connected,m_demoCheck->isChecked(),reference,offset); + if (m_touchOperation) 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,m_client,&RobotClient::requestTouchRgbdImage); + 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) 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::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); + QMessageBox::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) 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::of(&QSpinBox::valueChanged),this,[this] { syncHandEyeContext(); }); + connect(m_cameraIdEdit,&QLineEdit::textChanged,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("控制器坐标名称;原速度命令仍使用基座方向")); + // Local names must never be sent to the server's named-frame RPC. + m_client->setArmTelemetryFrames(m_armIdEdit->text().trimmed(), + local ? QStringLiteral("base") : m_baseFrameCombo->currentText(), + local ? QString() : m_tcpFrameCombo->currentText()); + 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(); + m_armDefaultBaseFrame = info.value(QStringLiteral("defaultBaseFrame")).toString(); + m_armDefaultTcpFrame = info.value(QStringLiteral("defaultTcpFrame")).toString(); + const QStringList jointNames = info.value(QStringLiteral("jointNames")).toStringList(); + rebuildArmJointTables(jointNames); + if (m_baseFrameCombo && m_baseFrameCombo->count() == 0) + m_baseFrameCombo->addItem(m_armDefaultBaseFrame.isEmpty() + ? QStringLiteral("base") : m_armDefaultBaseFrame); + if (m_tcpFrameCombo && m_tcpFrameCombo->count() == 0) + m_tcpFrameCombo->addItem(m_armDefaultTcpFrame.isEmpty() + ? QStringLiteral("tool0") : m_armDefaultTcpFrame); + if (m_armDeviceSummary) { + const QString identity = subtype.isEmpty() + ? QStringLiteral("%1 · %2 %3").arg(deviceId, manufacturer, model) + : QStringLiteral("%1 · %2 %3 (%4)").arg(deviceId, manufacturer, model, subtype); + m_armDeviceSummary->setText(identity); + } + if (m_urdfViewer) { + m_urdfViewer->loadModelForIdentity( + manufacturer, model, subtype, + info.value(QStringLiteral("descriptionId")).toString()); + } + m_client->requestArmFrames(deviceId); + appendLog(QStringLiteral("INFO"), + QStringLiteral("机械臂 %1:SDK 型号 %2 %3,自由度 %4") + .arg(deviceId, manufacturer, model) + .arg(jointNames.size())); +} + +void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &joints, + const QVariantMap &pose, const QVariantMap &state) +{ + if (!m_armIdEdit || deviceId != m_armIdEdit->text().trimmed()) + return; + QHash byName; + QHash jointPositions; + for (const QVariant &value : joints) { + const QVariantMap joint = value.toMap(); + const QString name = joint.value(QStringLiteral("name")).toString(); + byName.insert(name, joint); + jointPositions.insert(name, joint.value(QStringLiteral("position")).toDouble()); + } + + const qint64 nowMs = QDateTime::currentMSecsSinceEpoch(); + const double deltaSeconds = m_lastArmTelemetryMs > 0 + ? (nowMs - m_lastArmTelemetryMs) / 1000.0 : 0.0; + const QStringList modelJointNames = m_urdfViewer + ? m_urdfViewer->jointNames() : QStringList(); + const QHash> modelJointLimits = m_urdfViewer + ? m_urdfViewer->jointLimits() : QHash>(); + + if (m_urdfViewer) { + QHash modelPositions = jointPositions; + int directMatches = 0; + for (const QString &name : modelJointNames) { + if (jointPositions.contains(name)) + ++directMatches; + } + if (directMatches == 0 && modelJointNames.size() == joints.size()) { + for (int index = 0; index < modelJointNames.size(); ++index) { + modelPositions.insert( + modelJointNames.at(index), + joints.at(index).toMap().value(QStringLiteral("position")).toDouble()); + } + } + m_urdfViewer->setJointPositions(modelPositions); + } + + for (int row = 0; m_jointTable && row < m_jointTable->rowCount(); ++row) { + const QTableWidgetItem *nameItem = m_jointTable->item(row, 0); + if (!nameItem) + continue; + QVariantMap joint = byName.value(nameItem->text()); + if (joint.isEmpty() && row < joints.size()) + joint = joints.at(row).toMap(); + if (joint.isEmpty()) + continue; + const double position = joint.value(QStringLiteral("position")).toDouble(); + const double velocity = joint.value(QStringLiteral("velocity")).toDouble(); + const double acceleration = deltaSeconds > 0.0001 + && m_previousJointVelocities.contains(nameItem->text()) + ? (velocity - m_previousJointVelocities.value(nameItem->text())) / deltaSeconds + : 0.0; + m_jointTable->item(row, 1)->setText(QString::number(position, 'f', 5)); + m_jointTable->item(row, 2)->setText(QString::number(velocity, 'f', 5)); + m_jointTable->item(row, 3)->setText(QString::number(acceleration, 'f', 4)); + m_previousJointVelocities.insert(nameItem->text(), velocity); + if (row < m_jointJogPositionLabels.size()) + m_jointJogPositionLabels.at(row)->setText( + QStringLiteral("%1 rad").arg(position, 0, 'f', 4)); + if (row < m_jointJogPositionSliders.size()) { + QSlider *positionSlider = m_jointJogPositionSliders.at(row); + QString limitJointName = nameItem->text(); + if (!modelJointLimits.contains(limitJointName) + && row < modelJointNames.size()) { + limitJointName = modelJointNames.at(row); + } + const auto limitIt = modelJointLimits.constFind(limitJointName); + if (limitIt != modelJointLimits.constEnd() + && qIsFinite(limitIt.value().first) + && qIsFinite(limitIt.value().second) + && limitIt.value().second > limitIt.value().first) { + const double lower = limitIt.value().first; + const double upper = limitIt.value().second; + const double progress = qBound(0.0, (position - lower) / (upper - lower), 1.0); + positionSlider->setValue(qRound(progress * positionSlider->maximum())); + positionSlider->setToolTip( + QStringLiteral("%1:下限 %2 rad · 当前 %3 rad · 上限 %4 rad") + .arg(nameItem->text()) + .arg(lower, 0, 'f', 4) + .arg(position, 0, 'f', 4) + .arg(upper, 0, 'f', 4)); + } else { + positionSlider->setValue(0); + positionSlider->setToolTip(QStringLiteral("当前 URDF 未提供有效关节限位")); + } + } + if (row == 0 && m_trend) + m_trend->appendSample(position, velocity); + } + m_lastArmTelemetryMs = nowMs; + + QVariantMap displayPose = pose; + 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.isEmpty()) { + const bool connected = state.value(QStringLiteral("connected")).toBool(); + const bool powered = state.value(QStringLiteral("poweredOn")).toBool(); + const bool moving = state.value(QStringLiteral("moving")).toBool(); + const bool fault = state.value(QStringLiteral("fault")).toBool(); + const bool emergency = state.value(QStringLiteral("emergencyStopped")).toBool(); + const bool protective = state.value(QStringLiteral("protectiveStopped")).toBool(); + const bool freedrive = state.value(QStringLiteral("freedrive")).toBool() + || state.value(QStringLiteral("controlMode")).toInt() == 6; + const int robotMode = state.value(QStringLiteral("robotMode")).toInt(); + const int safetyMode = state.value(QStringLiteral("safetyMode")).toInt(); + const bool isDisconnected = !connected || robotMode == 1; + const bool isEmergency = emergency || safetyMode == 4 || safetyMode == 6; + const bool isFault = fault || robotMode == 7 || safetyMode == 7; + const bool isProtective = protective || safetyMode == 3 || safetyMode == 5; + + const auto setStateLabel = [](QLabel *label, const QString &text, + const QString &visualState) { + if (!label) + return; + label->setText(text); + label->setProperty("state", visualState); + label->style()->unpolish(label); + label->style()->polish(label); + }; + setStateLabel( + m_servoStatusValue, + isDisconnected ? QStringLiteral("已断开") + : freedrive ? QStringLiteral("拖动示教") + : powered ? (moving ? QStringLiteral("已使能 · 运动中") + : QStringLiteral("已使能 · 空闲")) + : QStringLiteral("未使能"), + (isDisconnected || isEmergency || isFault || isProtective) + ? QStringLiteral("error") : QStringLiteral("good")); + setStateLabel( + m_faultStatusValue, + isDisconnected ? QStringLiteral("通信断开") + : isEmergency ? QStringLiteral("急停") + : isFault ? QStringLiteral("故障") + : isProtective ? QStringLiteral("保护停止") + : freedrive ? QStringLiteral("拖动示教") : QStringLiteral("正常"), + (isDisconnected || isEmergency || isFault || isProtective || freedrive) + ? QStringLiteral("error") : QStringLiteral("good")); + + if (isDisconnected) { + updateArmAlert(deviceId, QStringLiteral("disconnected"), + QStringLiteral("ERROR"), QStringLiteral("机械臂已断开"), + QStringLiteral("请检查机械臂电源、网线以及控制器地址。")); + } else if (isEmergency) { + updateArmAlert(deviceId, QStringLiteral("emergency-stop"), + QStringLiteral("ERROR"), QStringLiteral("机械臂处于急停状态"), + QStringLiteral("请确认现场安全后释放急停并清除故障。")); + } else if (isFault) { + updateArmAlert(deviceId, QStringLiteral("fault"), + QStringLiteral("ERROR"), QStringLiteral("机械臂发生故障"), + QStringLiteral("请检查控制器告警信息,排除原因后清除故障。")); + } else if (isProtective) { + updateArmAlert(deviceId, QStringLiteral("protective-stop"), + QStringLiteral("WARN"), QStringLiteral("机械臂处于保护停止状态"), + QStringLiteral("请检查碰撞、限位或安全输入。")); + } else if (freedrive) { + updateArmAlert(deviceId, QStringLiteral("freedrive"), + QStringLiteral("WARN"), QStringLiteral("机械臂处于拖动示教状态"), + QStringLiteral("上位机运动控制暂不可用,请退出拖动示教后再操作。")); + } else { + updateArmAlert(deviceId, QString(), QString(), QString()); + } + } + if (m_armAlertStates.value(deviceId).isEmpty() + && m_bottomLogLevel && m_bottomLogMessage) { + m_bottomLogLevel->setText(QStringLiteral("[OK]")); + m_bottomLogLevel->setProperty("level", QStringLiteral("ok")); + m_bottomLogLevel->style()->unpolish(m_bottomLogLevel); + m_bottomLogLevel->style()->polish(m_bottomLogLevel); + m_bottomLogMessage->setText(QStringLiteral("Arm Telemetry · 已接收 %1 个关节状态 · %2") + .arg(joints.size()).arg(QDateTime::currentDateTime().toString("HH:mm:ss.zzz"))); + } +} + +void MainWindow::updateArmTelemetryHealth(const QString &deviceId, bool available, + const QString &detail) +{ + if (!m_armIdEdit || deviceId != m_armIdEdit->text().trimmed()) + return; + if (available) { + if (m_armAlertStates.value(deviceId) == QStringLiteral("communication")) + updateArmAlert(deviceId, QString(), QString(), QString()); + return; + } + + const auto markError = [](QLabel *label, const QString &text) { + if (!label) + return; + label->setText(text); + label->setProperty("state", QStringLiteral("error")); + label->style()->unpolish(label); + label->style()->polish(label); + }; + markError(m_servoStatusValue, QStringLiteral("遥测中断")); + markError(m_faultStatusValue, QStringLiteral("通信异常")); + updateArmAlert(deviceId, QStringLiteral("communication"), + QStringLiteral("ERROR"), QStringLiteral("机械臂遥测通信异常"), detail); +} + +void MainWindow::updateArmAlert(const QString &deviceId, const QString &alertKey, + const QString &level, const QString &summary, + const QString &detail) +{ + const QString previous = m_armAlertStates.value(deviceId); + if (previous == alertKey) + return; + if (alertKey.isEmpty()) { + m_armAlertStates.remove(deviceId); + if (!previous.isEmpty()) + appendLog(QStringLiteral("OK"), + QStringLiteral("机械臂 %1 状态已恢复正常").arg(deviceId)); + return; + } + + m_armAlertStates.insert(deviceId, alertKey); + const QString message = detail.isEmpty() + ? QStringLiteral("机械臂 %1:%2").arg(deviceId, summary) + : QStringLiteral("机械臂 %1:%2。%3").arg(deviceId, summary, detail); + appendLog(level, message); + + const QString popupKey = deviceId + QLatin1Char('/') + alertKey; + const qint64 nowMs = QDateTime::currentMSecsSinceEpoch(); + const qint64 lastPopupMs = m_armLastAlertPopupMs.value(popupKey, 0); + if (lastPopupMs > 0 && nowMs - lastPopupMs < 30000) + return; + m_armLastAlertPopupMs.insert(popupKey, nowMs); + + QMessageBox *popup = new QMessageBox( + level == QStringLiteral("ERROR") ? QMessageBox::Critical : QMessageBox::Warning, + QStringLiteral("机械臂状态提醒"), message, QMessageBox::Ok, this); + popup->setAttribute(Qt::WA_DeleteOnClose); + popup->setWindowModality(Qt::NonModal); + popup->open(); +} + +void MainWindow::updateSystemStatus(double cpu, double memory, double disk, + const QVariantList &devices) +{ + m_cpuValue->setText(QString::number(cpu, 'f', 0)); + m_memoryValue->setText(QString::number(memory, 'f', 0)); + m_diskValue->setText(QString::number(disk, 'f', 0)); + m_deviceValue->setText(QString::number(devices.size())); + if (!m_armSideCombo) + return; + + const QString previousId = m_armIdEdit && !m_armIdEdit->text().trimmed().isEmpty() + ? m_armIdEdit->text().trimmed() : m_armSideCombo->currentData().toString(); + QString firstArmId; + { + const QSignalBlocker blocker(m_armSideCombo); + m_armSideCombo->clear(); + for (const QVariant &value : devices) { + const QVariantMap device = value.toMap(); + if (device.value(QStringLiteral("type")).toInt() != 6) + continue; + const QString deviceId = device.value(QStringLiteral("deviceId")).toString(); + if (deviceId.isEmpty()) + continue; + if (firstArmId.isEmpty()) + firstArmId = deviceId; + const QString vendor = device.value(QStringLiteral("vendor")).toString(); + const QString driver = device.value(QStringLiteral("driverType")).toString(); + const QString detail = !vendor.isEmpty() ? vendor : driver; + m_armSideCombo->addItem( + detail.isEmpty() ? deviceId : QStringLiteral("%1 · %2").arg(deviceId, detail), + deviceId); + } + int index = m_armSideCombo->findData(previousId); + if (index < 0 && m_armSideCombo->count() > 0) + index = 0; + if (index >= 0) + m_armSideCombo->setCurrentIndex(index); + } + const QString selectedId = m_armSideCombo->currentData().toString(); + if (m_armIdEdit && !selectedId.isEmpty() + && (selectedId != previousId || m_activeArmJointNames.isEmpty())) { + m_armIdEdit->setText(selectedId); + m_client->requestArmInfo(selectedId); + m_client->requestArmFrames(selectedId); + } else if (m_armIdEdit && m_armIdEdit->text().trimmed().isEmpty() + && !firstArmId.isEmpty()) { + m_armIdEdit->setText(firstArmId); + m_client->requestArmInfo(firstArmId); + m_client->requestArmFrames(firstArmId); + } +} + +void MainWindow::updateSystemInfo(const QVariantMap &info) +{ + m_systemNameValue->setText(info.value(QStringLiteral("name"), QStringLiteral("--")).toString()); + m_systemVersionValue->setText(info.value(QStringLiteral("version"), QStringLiteral("--")).toString()); + const QString platform = QStringLiteral("%1 · %2") + .arg(info.value(QStringLiteral("os"), QStringLiteral("--")).toString(), + info.value(QStringLiteral("architecture"), QStringLiteral("--")).toString()); + m_systemOsValue->setText(platform); +} + +void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &navigation) +{ + const bool controllerConnected = state.value(QStringLiteral("connected")).toBool(); + const bool localized = state.value(QStringLiteral("localized")).toBool(); + const bool fault = state.value(QStringLiteral("fault")).toBool(); + const bool emergency = state.value(QStringLiteral("emergency")).toBool(); + m_agvConnectionValue->setText(QStringLiteral("%1 · %2%3") + .arg(controllerConnected ? QStringLiteral("在线") : QStringLiteral("离线"), + localized ? QStringLiteral("已定位") : QStringLiteral("未定位"), + (fault || emergency) ? QStringLiteral(" · 异常") : QString())); + m_agvMapValue->setText(QStringLiteral("%1 / %2") + .arg(state.value(QStringLiteral("map"), QStringLiteral("--")).toString(), + state.value(QStringLiteral("station"), QStringLiteral("--")).toString())); + m_agvPoseValue->setText(QStringLiteral("%1, %2, %3") + .arg(state.value(QStringLiteral("x")).toDouble(), 0, 'f', 2) + .arg(state.value(QStringLiteral("y")).toDouble(), 0, 'f', 2) + .arg(state.value(QStringLiteral("theta")).toDouble(), 0, 'f', 2)); + m_agvMotionValue->setText(QStringLiteral("%1 / %2 / %3") + .arg(state.value(QStringLiteral("vx")).toDouble(), 0, 'f', 2) + .arg(state.value(QStringLiteral("vy")).toDouble(), 0, 'f', 2) + .arg(state.value(QStringLiteral("wz")).toDouble(), 0, 'f', 2)); + m_agvBatteryValue->setText(QStringLiteral("%1%").arg( + state.value(QStringLiteral("battery")).toDouble() * 100.0, 0, 'f', 0)); + m_agvNavigationValue->setText(navigation.value(QStringLiteral("message"), QStringLiteral("--")).toString()); + m_agvErrorValue->setText(state.value(QStringLiteral("error"), QStringLiteral("无")).toString()); + m_agvModeValue->setText(QStringLiteral("模式 %1").arg( + state.value(QStringLiteral("mode")).toInt())); + m_agvMotionStateValue->setText(QStringLiteral("%1 / %2") + .arg(localized ? QStringLiteral("已定位") : QStringLiteral("未定位"), + state.value(QStringLiteral("moving")).toBool() + ? QStringLiteral("运动中") : QStringLiteral("静止"))); + m_agvSafetyValue->setText(QStringLiteral("%1 / %2") + .arg(fault ? QStringLiteral("有故障") : QStringLiteral("正常"), + emergency ? QStringLiteral("已急停") : QStringLiteral("未急停"))); + m_agvPowerValue->setText(QStringLiteral("%1 V / %2 A / %3 °C") + .arg(state.value(QStringLiteral("voltage")).toDouble(), 0, 'f', 2) + .arg(state.value(QStringLiteral("current")).toDouble(), 0, 'f', 2) + .arg(state.value(QStringLiteral("temperature")).toDouble(), 0, 'f', 1)); + const double timestamp = state.value(QStringLiteral("timestamp")).toDouble(); + m_agvTimestampValue->setText(timestamp > 0.0 + ? QDateTime::fromMSecsSinceEpoch(qRound64(timestamp * 1000.0)) + .toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")) + : QStringLiteral("--")); + m_agvProgress->setValue(qBound(0, qRound(navigation.value(QStringLiteral("progress")).toDouble() * 100.0), 100)); +} + +void MainWindow::updateAgvInventory(const QStringList &maps, const QVariantList &stations) +{ + const QString selectedMap = m_agvMapCombo->currentText(); + m_agvMapCombo->clear(); + m_agvMapCombo->addItems(maps); + const int mapIndex = m_agvMapCombo->findText(selectedMap); + if (mapIndex >= 0) + m_agvMapCombo->setCurrentIndex(mapIndex); + + const QString selectedStation = m_agvStationCombo->currentText(); + m_agvStationCombo->clear(); + m_agvStationTable->setRowCount(stations.size()); + for (int row = 0; row < stations.size(); ++row) { + const QVariantMap station = stations.at(row).toMap(); + const QString stationId = station.value(QStringLiteral("id")).toString(); + m_agvStationCombo->addItem(stationId); + m_agvStationTable->setItem(row, 0, new QTableWidgetItem(stationId)); + m_agvStationTable->setItem(row, 1, new QTableWidgetItem(station.value(QStringLiteral("type")).toString())); + m_agvStationTable->setItem(row, 2, new QTableWidgetItem(QString::number( + station.value(QStringLiteral("x")).toDouble(), 'f', 3))); + m_agvStationTable->setItem(row, 3, new QTableWidgetItem(QString::number( + station.value(QStringLiteral("y")).toDouble(), 'f', 3))); + } + const int stationIndex = m_agvStationCombo->findText(selectedStation); + if (stationIndex >= 0) + m_agvStationCombo->setCurrentIndex(stationIndex); + + QPixmap preview(960, 280); + preview.fill(QColor(QStringLiteral("#eef2f6"))); + QPainter painter(&preview); + painter.setRenderHint(QPainter::Antialiasing); + painter.setPen(QPen(QColor(QStringLiteral("#d5dee6")), 1)); + for (int x = 60; x < preview.width(); x += 100) + painter.drawLine(x, 24, x, preview.height() - 24); + for (int y = 40; y < preview.height(); y += 60) + painter.drawLine(36, y, preview.width() - 36, y); + if (stations.isEmpty()) { + painter.setPen(QColor(QStringLiteral("#71808e"))); + painter.drawText(preview.rect(), Qt::AlignCenter, + QStringLiteral("当前地图没有可显示的站点")); + } else { + double minX = stations.first().toMap().value(QStringLiteral("x")).toDouble(); + double maxX = minX; + double minY = stations.first().toMap().value(QStringLiteral("y")).toDouble(); + double maxY = minY; + for (const QVariant &entry : stations) { + const QVariantMap station = entry.toMap(); + minX = qMin(minX, station.value(QStringLiteral("x")).toDouble()); + maxX = qMax(maxX, station.value(QStringLiteral("x")).toDouble()); + minY = qMin(minY, station.value(QStringLiteral("y")).toDouble()); + maxY = qMax(maxY, station.value(QStringLiteral("y")).toDouble()); + } + if (qFuzzyCompare(minX, maxX)) { minX -= 1.0; maxX += 1.0; } + if (qFuzzyCompare(minY, maxY)) { minY -= 1.0; maxY += 1.0; } + QPointF previous; + for (int i = 0; i < stations.size(); ++i) { + const QVariantMap station = stations.at(i).toMap(); + const QPointF point( + 60.0 + (station.value(QStringLiteral("x")).toDouble() - minX) / + (maxX - minX) * (preview.width() - 120.0), + 40.0 + (maxY - station.value(QStringLiteral("y")).toDouble()) / + (maxY - minY) * (preview.height() - 80.0)); + if (i > 0) { + painter.setPen(QPen(QColor(QStringLiteral("#9db7ce")), 2)); + painter.drawLine(previous, point); + } + painter.setPen(Qt::NoPen); + painter.setBrush(QColor(QStringLiteral("#218c74"))); + painter.drawEllipse(point, 7, 7); + painter.setPen(QColor(QStringLiteral("#26323d"))); + painter.drawText(point + QPointF(10, -8), + station.value(QStringLiteral("id")).toString()); + previous = point; + } + } + painter.end(); + m_agvMapOverview->setPixmap(preview.scaled( + m_agvMapOverview->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); +} + +void MainWindow::updateImage(const QImage &image, const QString &detail) +{ + m_lastImage = image; + if (m_videoRender) + m_videoRender->setImage(image); + m_imageMetaLabel->setText(detail); + m_saveImageButton->setEnabled(true); +} + +void MainWindow::updateVideoFrame(const QString &cameraId, const VideoFrame &frame, + const QString &detail) +{ + const QString resolvedId = cameraId.isEmpty() && !m_cameraPreviewTiles.isEmpty() + ? m_cameraPreviewTiles.constBegin().key() : cameraId; + const auto it = m_cameraPreviewTiles.find(resolvedId); + if (it == m_cameraPreviewTiles.end()) + return; + it->render->setFrame(frame); + it->meta->setText(detail); + m_imageMetaLabel->setText(QStringLiteral("%1 | %2").arg(resolvedId, detail)); + m_saveImageButton->setEnabled(true); +} + +void MainWindow::updateCameraStreamState(const QString &cameraId, bool running, + const QString &detail) +{ + const QString resolvedId = cameraId.isEmpty() && !m_cameraPreviewTiles.isEmpty() + ? m_cameraPreviewTiles.constBegin().key() : cameraId; + if (running) + m_runningCameraIds.insert(resolvedId); + else + m_runningCameraIds.remove(resolvedId); + + const auto it = m_cameraPreviewTiles.find(resolvedId); + if (it != m_cameraPreviewTiles.end()) { + it->status->setText(running ? QStringLiteral("播放中") + : QStringLiteral("已停止")); + it->status->setToolTip(detail); + if (!running && !detail.isEmpty()) + it->meta->setText(detail); + } + refreshCameraStreamControls(); + m_cameraStreamStateLabel->setToolTip(detail); + if (!detail.isEmpty()) { + const bool failed = detail.contains(QStringLiteral("失败")); + appendLog(failed ? QStringLiteral("ERROR") : QStringLiteral("INFO"), + QStringLiteral("%1: %2").arg(resolvedId, detail)); + } +} + +void MainWindow::updateCameraRecordingState(bool recording, const QString &detail) +{ + m_cameraRecording = recording; + if (!m_cameraRecordButton || !m_cameraRecordPathEdit || !m_cameraRecordStateLabel) + return; + m_cameraRecordButton->setEnabled(m_connected); + m_cameraRecordButton->setText(recording ? QStringLiteral("停止录像") + : QStringLiteral("开始录像")); + m_cameraRecordButton->setIcon(style()->standardIcon( + recording ? QStyle::SP_MediaStop : QStyle::SP_DialogSaveButton)); + m_cameraRecordButton->setObjectName(recording ? QStringLiteral("dangerButton") + : QStringLiteral("primaryButton")); + m_cameraRecordButton->style()->unpolish(m_cameraRecordButton); + m_cameraRecordButton->style()->polish(m_cameraRecordButton); + m_cameraRecordPathEdit->setEnabled(!recording); + m_cameraIdEdit->setEnabled(!m_cameraStreaming && !recording); + m_cameraRecordStateLabel->setText(recording ? QStringLiteral("录像中") + : QStringLiteral("未录像")); + m_cameraRecordStateLabel->setToolTip(detail); + if (!detail.isEmpty()) + appendLog(QStringLiteral("INFO"), detail); +} + +void MainWindow::handleCommand(const QString &command, bool success, const QString &detail) +{ + QLabel *stateLabel = nullptr; + QString stateText; + if (command == QStringLiteral("Torque On")) { + stateLabel = m_servoStatusValue; + stateText = success ? QStringLiteral("已使能") : QStringLiteral("使能失败"); + } else if (command == QStringLiteral("Torque Off")) { + stateLabel = m_servoStatusValue; + stateText = success ? QStringLiteral("已去使能") : QStringLiteral("操作失败"); + } else if (command == QStringLiteral("Clear Fault")) { + stateLabel = m_faultStatusValue; + stateText = success ? QStringLiteral("正常") : QStringLiteral("清除失败"); + } + if (stateLabel) { + stateLabel->setText(stateText); + stateLabel->setProperty("state", success ? QStringLiteral("good") + : QStringLiteral("error")); + stateLabel->style()->unpolish(stateLabel); + stateLabel->style()->polish(stateLabel); + } + if (!success && (command == QStringLiteral("Camera Start Recording") + || command == QStringLiteral("Camera Stop Recording"))) { + updateCameraRecordingState(m_cameraRecording, detail); + } + if (success && m_agvStatusSwitch + && (command == QStringLiteral("AGV NavigateToPose") + || command == QStringLiteral("AGV NavigateToStation") + || command == QStringLiteral("AGV FollowPath"))) { + m_agvStatusSwitch->setChecked(true); + } + appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"), + QStringLiteral("%1 · %2").arg(command, detail)); + if (!success) + m_connectionText->setToolTip(detail); +} + +void MainWindow::appendLog(const QString &level, const QString &message) +{ + if (m_bottomLogLevel && m_bottomLogMessage) { + const QString normalizedLevel = level.toLower(); + m_bottomLogLevel->setText(QStringLiteral("[%1]").arg(level)); + m_bottomLogLevel->setProperty("level", normalizedLevel); + m_bottomLogLevel->style()->unpolish(m_bottomLogLevel); + m_bottomLogLevel->style()->polish(m_bottomLogLevel); + m_bottomLogMessage->setText(QStringLiteral("%1 · %2") + .arg(message, QDateTime::currentDateTime().toString("HH:mm:ss.zzz"))); + m_bottomLogMessage->setToolTip(message); + } + if (!m_logView) + return; + QString color = QStringLiteral("#aeb6c0"); + if (level == QStringLiteral("ERROR")) + color = QStringLiteral("#ff7b72"); + else if (level == QStringLiteral("WARN")) + color = QStringLiteral("#e3b341"); + else if (level == QStringLiteral("OK")) + color = QStringLiteral("#56d39b"); + const QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz"); + m_logView->append(QStringLiteral("%1 " + "[%3] %4") + .arg(timestamp, color, level, message.toHtmlEscaped())); +} + +void MainWindow::sendMoveJ() +{ + QVariantList positions; + for (QDoubleSpinBox *spin : m_targetSpins) + positions.append(qDegreesToRadians(spin->value())); + m_client->requestMoveJ(m_armIdEdit->text().trimmed(), positions, + m_velocitySpin->value(), m_accelerationSpin->value()); +} + +void MainWindow::sendMoveJPose() +{ + if (m_moveJPoseSpins.size() != 6 || !m_moveJPoseBaseLinkCombo) + return; + QVariantMap pose; + static const QStringList keys = { + QStringLiteral("x"), QStringLiteral("y"), QStringLiteral("z"), + QStringLiteral("rx"), QStringLiteral("ry"), QStringLiteral("rz") + }; + for (int i = 0; i < keys.size(); ++i) + pose.insert(keys.at(i), m_moveJPoseSpins.at(i)->value()); + m_client->requestMoveJPose(m_armIdEdit->text().trimmed(), pose, + m_armDefaultBaseFrame, + m_armDefaultTcpFrame, + m_velocitySpin->value(), m_accelerationSpin->value()); +} + +void MainWindow::saveSnapshot() +{ + QImage image = m_cameraStreaming && m_videoRender + ? m_videoRender->grabFramebuffer() : m_lastImage; + if (image.isNull()) + return; + const QString defaultName = QStringLiteral("cmvr_rgb_%1.png") + .arg(QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss")); + const QString path = QFileDialog::getSaveFileName(this, QStringLiteral("保存 RGB 图像"), + defaultName, QStringLiteral("PNG 图像 (*.png);;JPEG 图像 (*.jpg)")); + if (path.isEmpty()) + return; + const bool saved = image.save(path); + appendLog(saved ? QStringLiteral("OK") : QStringLiteral("ERROR"), + saved ? QStringLiteral("图像已保存:%1").arg(path) + : QStringLiteral("图像保存失败:%1").arg(path)); +} + +void MainWindow::loadSettings() +{ + QSettings settings; + m_hostEdit->setText(settings.value(QStringLiteral("connection/host"), QStringLiteral("192.168.0.28")).toString()); + m_hostEdit->setCursorPosition(0); + m_portSpin->setValue(settings.value(QStringLiteral("connection/port"), 50052).toInt()); + m_demoCheck->setChecked(settings.value(QStringLiteral("connection/demo"), true).toBool()); + m_systemTargetEdit->setText(settings.value(QStringLiteral("system/target"), QStringLiteral("*")).toString()); + QString armDeviceId = settings.value(QStringLiteral("arm/device"), + QStringLiteral("demo_arm")).toString().trimmed(); + m_armIdEdit->setText(armDeviceId); + if (m_armSideCombo && !armDeviceId.isEmpty()) + m_armSideCombo->addItem(armDeviceId, armDeviceId); + m_cameraIdEdit->setText(settings.value(QStringLiteral("camera/device"), QStringLiteral("camera")).toString()); + rebuildCameraPreviewGrid(configuredCameraIds()); + m_cameraRecordPathEdit->setText(settings.value( + QStringLiteral("camera/recordPath"), + QStringLiteral("/mnt/data/cmvr/record/camera.mp4")).toString()); + const QString cameraCodec = settings.value(QStringLiteral("camera/codec"), + QStringLiteral("h264")).toString().toLower(); + m_cameraCodecCombo->setCurrentIndex( + cameraCodec == QStringLiteral("h265") || cameraCodec == QStringLiteral("hevc") ? 1 : 0); + if (m_cameraStreamModeCombo) { + const QString cameraMode = settings.value(QStringLiteral("camera/streamMode"), + QStringLiteral("rgb")).toString().toLower(); + const int modeIndex = m_cameraStreamModeCombo->findData(cameraMode); + if (modeIndex >= 0) + m_cameraStreamModeCombo->setCurrentIndex(modeIndex); + } + m_agvIdEdit->setText(settings.value(QStringLiteral("agv/device"), QStringLiteral("agv")).toString()); + m_velocitySpin->setValue(settings.value( + QStringLiteral("motion/speedJVelocity"), + settings.value(QStringLiteral("motion/velocity"), 1.0)).toDouble()); + m_accelerationSpin->setValue(settings.value( + QStringLiteral("motion/speedJAcceleration"), + settings.value(QStringLiteral("motion/acceleration"), 0.5)).toDouble()); + if (m_cartesianVelocitySpin) + m_cartesianVelocitySpin->setValue(settings.value( + QStringLiteral("motion/speedLVelocity"), 0.25).toDouble()); + if (m_cartesianAccelerationSpin) + m_cartesianAccelerationSpin->setValue(settings.value( + QStringLiteral("motion/speedLAcceleration"), 0.5).toDouble()); + const QDir applicationDirectory(QCoreApplication::applicationDirPath()); + const QString defaultUrdf = applicationDirectory.filePath(QStringLiteral("models/demo_arm.urdf")); + QString configuredUrdf = settings.value(QStringLiteral("arm/urdf"), defaultUrdf) + .toString().trimmed(); + if (!configuredUrdf.isEmpty() && QFileInfo(configuredUrdf).isRelative()) + configuredUrdf = applicationDirectory.absoluteFilePath(configuredUrdf); + m_pendingUrdfPath = QFileInfo::exists(configuredUrdf) + ? QFileInfo(configuredUrdf).absoluteFilePath() + : (QFileInfo::exists(defaultUrdf) ? QFileInfo(defaultUrdf).absoluteFilePath() + : QString()); + m_quicBindEdit->setText(settings.value(QStringLiteral("quic/bindAddress"), + QStringLiteral("127.0.0.1")).toString()); + m_quicPortSpin->setValue(settings.value(QStringLiteral("quic/port"), 4433).toInt()); + m_quicAlpnEdit->setText(settings.value(QStringLiteral("quic/alpn"), + QStringLiteral("cmvr-quic-edge/1")).toString()); + const QDir applicationDir(QCoreApplication::applicationDirPath()); + const QString defaultCertificate = applicationDir.filePath( + QStringLiteral("quic-test-server.pfx")); + QString certificatePath = settings.value( + QStringLiteral("quic/certificate"), + QStringLiteral("quic-test-server.pfx")).toString().trimmed(); + if (QFileInfo(certificatePath).isRelative()) + certificatePath = applicationDir.filePath(certificatePath); + if (!QFileInfo(certificatePath).isFile()) { + certificatePath = defaultCertificate; + settings.setValue(QStringLiteral("quic/certificate"), + QStringLiteral("quic-test-server.pfx")); + } + m_quicCertificateEdit->setText(QDir::toNativeSeparators(certificatePath)); + m_quicPasswordEdit->setText(QStringLiteral("cmvr-test")); + m_endpointValue->setText(endpoint()); + if (m_sidebarEndpointValue) + m_sidebarEndpointValue->setText(endpoint()); +} + +void MainWindow::saveSettings() +{ + QSettings settings; + settings.setValue(QStringLiteral("connection/host"), m_hostEdit->text().trimmed()); + settings.setValue(QStringLiteral("connection/port"), m_portSpin->value()); + settings.setValue(QStringLiteral("connection/demo"), m_demoCheck->isChecked()); + settings.setValue(QStringLiteral("system/target"), m_systemTargetEdit->text().trimmed()); + settings.setValue(QStringLiteral("arm/device"), m_armIdEdit->text().trimmed()); + settings.setValue(QStringLiteral("camera/device"), m_cameraIdEdit->text().trimmed()); + settings.setValue(QStringLiteral("camera/recordPath"), + m_cameraRecordPathEdit->text().trimmed()); + settings.setValue(QStringLiteral("camera/codec"), + m_cameraCodecCombo->currentIndex() == 1 + ? QStringLiteral("h265") : QStringLiteral("h264")); + if (m_cameraStreamModeCombo) + settings.setValue(QStringLiteral("camera/streamMode"), + m_cameraStreamModeCombo->currentData().toString()); + settings.setValue(QStringLiteral("agv/device"), m_agvIdEdit->text().trimmed()); + settings.setValue(QStringLiteral("motion/speedJVelocity"), m_velocitySpin->value()); + settings.setValue(QStringLiteral("motion/speedJAcceleration"), + m_accelerationSpin->value()); + if (m_cartesianVelocitySpin) + settings.setValue(QStringLiteral("motion/speedLVelocity"), + m_cartesianVelocitySpin->value()); + if (m_cartesianAccelerationSpin) + settings.setValue(QStringLiteral("motion/speedLAcceleration"), + m_cartesianAccelerationSpin->value()); + if (m_urdfViewer && !m_urdfViewer->currentFile().isEmpty()) + settings.setValue(QStringLiteral("arm/urdf"), m_urdfViewer->currentFile()); + else if (!m_pendingUrdfPath.isEmpty()) + settings.setValue(QStringLiteral("arm/urdf"), m_pendingUrdfPath); + settings.setValue(QStringLiteral("quic/bindAddress"), m_quicBindEdit->text().trimmed()); + settings.setValue(QStringLiteral("quic/port"), m_quicPortSpin->value()); + settings.setValue(QStringLiteral("quic/alpn"), m_quicAlpnEdit->text().trimmed()); + const QString certificatePath = QDir::fromNativeSeparators( + m_quicCertificateEdit->text().trimmed()); + const QString bundledCertificate = QDir(QCoreApplication::applicationDirPath()) + .filePath(QStringLiteral("quic-test-server.pfx")); + settings.setValue( + QStringLiteral("quic/certificate"), + QFileInfo(certificatePath).absoluteFilePath() == + QFileInfo(bundledCertificate).absoluteFilePath() + ? QStringLiteral("quic-test-server.pfx") + : certificatePath); +} + +void MainWindow::setControlsEnabled(bool enabled) +{ + for (QPushButton *button : m_serviceButtons) { + if (button) + button->setEnabled(enabled); + } + for (QDoubleSpinBox *spin : m_targetSpins) + spin->setEnabled(enabled); + for (QDoubleSpinBox *spin : m_moveJPoseSpins) + spin->setEnabled(enabled); + if (m_moveJPoseBaseLinkCombo) + m_moveJPoseBaseLinkCombo->setEnabled(enabled); + if (m_velocitySpin) + m_velocitySpin->setEnabled(enabled); + if (m_accelerationSpin) + m_accelerationSpin->setEnabled(enabled); + if (m_cartesianVelocitySpin) + m_cartesianVelocitySpin->setEnabled(enabled); + if (m_cartesianAccelerationSpin) + m_cartesianAccelerationSpin->setEnabled(enabled); + if (m_calibrateZeroButton) + m_calibrateZeroButton->setEnabled(enabled && m_zeroJointCombo + && m_zeroJointCombo->count() > 0); + if (m_teachSendButton) + m_teachSendButton->setEnabled(enabled && m_teachModeButton + && m_teachModeButton->isChecked()); + if (m_speakerStreamStartButton) + m_speakerStreamStartButton->setEnabled(enabled); + if (m_speakerStreamStopButton) + m_speakerStreamStopButton->setEnabled(false); + if (m_microphoneStreamStartButton) + m_microphoneStreamStartButton->setEnabled(enabled); + if (m_microphoneStreamStopButton) + m_microphoneStreamStopButton->setEnabled(false); +} + +QString MainWindow::endpoint() const +{ + return QStringLiteral("%1:%2").arg(m_hostEdit->text().trimmed()).arg(m_portSpin->value()); +} diff --git a/src/robotclient.cpp b/src/robotclient.cpp index e31b306..1c3684f 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -1,3649 +1,4024 @@ -#include "robotclient.h" -#include "videodecoder.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef CMVR_WITH_GRPC -#include -#include -#include -#include -#include "cmvr/api/agv_command.pb.h" -#include "cmvr/api/agv_service.grpc.pb.h" -#include "cmvr/api/arm_command.pb.h" -#include "cmvr/api/arm_service.grpc.pb.h" -#include "cmvr/api/camera_command.pb.h" -#include "cmvr/api/camera_service.grpc.pb.h" -#include "cmvr/api/configuration_service.grpc.pb.h" -#include "cmvr/api/microphone_command.pb.h" -#include "cmvr/api/microphone_service.grpc.pb.h" -#include "cmvr/api/speaker_command.pb.h" -#include "cmvr/api/speaker_service.grpc.pb.h" -#include "cmvr/api/system_command.pb.h" -#include "cmvr/api/system_service.grpc.pb.h" -#endif - -namespace { -#ifdef CMVR_WITH_GRPC -constexpr int kGrpcMaxMessageBytes = 64 * 1024 * 1024; -constexpr int kArmMotionTimeoutMs = 120000; - -std::shared_ptr createGrpcChannel(const std::string &endpoint) -{ - grpc::ChannelArguments arguments; - arguments.SetMaxReceiveMessageSize(kGrpcMaxMessageBytes); - arguments.SetMaxSendMessageSize(kGrpcMaxMessageBytes); - return grpc::CreateCustomChannel(endpoint, grpc::InsecureChannelCredentials(), arguments); -} - -cmvr::api::DeviceType deviceTypeFromKind(cmvr::api::DeviceKind kind, - cmvr::api::DeviceType fallback) -{ - switch (kind) { - case cmvr::api::DEVICE_KIND_AGV: return cmvr::api::AGV; - case cmvr::api::DEVICE_KIND_ARM: - case cmvr::api::DEVICE_KIND_ROBOT: return cmvr::api::Robot; - case cmvr::api::DEVICE_KIND_BATTERY: return cmvr::api::Battery; - case cmvr::api::DEVICE_KIND_BIO_HEAD: return cmvr::api::BioHead; - case cmvr::api::DEVICE_KIND_CAMERA: return cmvr::api::Camera; - case cmvr::api::DEVICE_KIND_CAN_BUS: return cmvr::api::CanBus; - case cmvr::api::DEVICE_KIND_DEX_HAND: return cmvr::api::DexHand; - case cmvr::api::DEVICE_KIND_GRIPPER: return cmvr::api::Gripper; - case cmvr::api::DEVICE_KIND_MICROPHONE: return cmvr::api::Microphone; - case cmvr::api::DEVICE_KIND_MOTOR: return cmvr::api::Motor; - case cmvr::api::DEVICE_KIND_MOTOR_SYSTEM: return cmvr::api::MotorSystem; - case cmvr::api::DEVICE_KIND_MUJOCO_VIEWER: return cmvr::api::MujocoViewer; - case cmvr::api::DEVICE_KIND_MUJOCO_WORLD: return cmvr::api::MujocoWorld; - case cmvr::api::DEVICE_KIND_SPEAKER: return cmvr::api::Speaker; - case cmvr::api::DEVICE_KIND_UNKNOWN: - default: return fallback; - } -} - -QVariantList deviceListFromStatus(const cmvr::api::GetSystemStatusCommand::Feedback &response) -{ - QVariantList devices; - devices.reserve(response.device_list_size()); - for (const auto &device : response.device_list()) { - QVariantMap item; - const auto deviceType = deviceTypeFromKind(device.device_kind(), device.device_type()); - item.insert(QStringLiteral("deviceId"), QString::fromStdString(device.device_id())); - item.insert(QStringLiteral("type"), static_cast(deviceType)); - item.insert(QStringLiteral("typeName"), - QString::fromStdString(cmvr::api::DeviceType_Name(deviceType))); - item.insert(QStringLiteral("deviceKind"), static_cast(device.device_kind())); - item.insert(QStringLiteral("deviceKindName"), - QString::fromStdString(cmvr::api::DeviceKind_Name(device.device_kind()))); - item.insert(QStringLiteral("driverType"), - QString::fromStdString(device.driver_type())); - item.insert(QStringLiteral("vendor"), QString::fromStdString(device.vendor())); - item.insert(QStringLiteral("online"), true); - devices.append(item); - } - return devices; -} -#endif - -QVariantList demoDeviceList() -{ - QVariantList devices; - const QList definitions = { - {{QStringLiteral("deviceId"), QStringLiteral("right_arm")}, - {QStringLiteral("type"), 6}, {QStringLiteral("deviceKind"), 2}, - {QStringLiteral("driverType"), QStringLiteral("AuboARM")}, - {QStringLiteral("vendor"), QStringLiteral("AUBO")}}, - {{QStringLiteral("deviceId"), QStringLiteral("hikvision_camera")}, - {QStringLiteral("type"), 2}, {QStringLiteral("deviceKind"), 5}, - {QStringLiteral("driverType"), QStringLiteral("HikvisionCamera")}, - {QStringLiteral("vendor"), QStringLiteral("HIKVISION")}}, - {{QStringLiteral("deviceId"), QStringLiteral("src1100_agv")}, - {QStringLiteral("type"), 0}, {QStringLiteral("deviceKind"), 1}, - {QStringLiteral("driverType"), QStringLiteral("SeerRobokitAgv")}, - {QStringLiteral("vendor"), QStringLiteral("SEER")}}, - {{QStringLiteral("deviceId"), QStringLiteral("dexterous_hand")}, - {QStringLiteral("type"), 3}, {QStringLiteral("deviceKind"), 7}, - {QStringLiteral("driverType"), QStringLiteral("RH56DFTPDexhand")}, - {QStringLiteral("vendor"), QStringLiteral("Inspire Robots")}}, - {{QStringLiteral("deviceId"), QStringLiteral("meeting_microphone")}, - {QStringLiteral("type"), 5}, {QStringLiteral("deviceKind"), 9}, - {QStringLiteral("driverType"), QStringLiteral("FFMpegMicroPhone")}, - {QStringLiteral("vendor"), QStringLiteral("FFmpeg")}}, - {{QStringLiteral("deviceId"), QStringLiteral("speaker")}, - {QStringLiteral("type"), 7}, {QStringLiteral("deviceKind"), 15}, - {QStringLiteral("driverType"), QStringLiteral("FFMpegSpeaker")}, - {QStringLiteral("vendor"), QStringLiteral("FFmpeg")}}, - }; - for (const auto &definition : definitions) { - QVariantMap device = definition; - device.insert(QStringLiteral("online"), true); - devices.append(device); - } - return devices; -} - -QStringList armJointNamesForDevice(const QString &deviceId) -{ - const QString prefix = deviceId.contains(QStringLiteral("left"), Qt::CaseInsensitive) - ? 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") - }; -} - -VideoFrame videoFrameFromImage(const QImage &image) -{ - const QImage rgba = image.convertToFormat(QImage::Format_RGBA8888); - VideoFrame frame; - frame.width = rgba.width(); - frame.height = rgba.height(); - frame.format = VideoPixelFormat::RGBA; - frame.stride0 = frame.width * 4; - frame.plane0.resize(frame.width * frame.height * 4); - for (int row = 0; row < frame.height; ++row) { - std::memcpy(frame.plane0.data() + row * frame.width * 4, - rgba.constScanLine(row), static_cast(frame.width * 4)); - } - return frame; -} - -#ifdef CMVR_WITH_GRPC -VideoFrame videoFrameFromDepth(const cmvr::api::FrameData &frame) -{ - if (frame.width() <= 0 || frame.height() <= 0 || - frame.type() != cmvr::api::FrameData::U16C1 || - frame.data().size() < frame.width() * frame.height() * 2) { - return {}; - } - QImage gray(frame.width(), frame.height(), QImage::Format_Grayscale8); - const auto *source = reinterpret_cast(frame.data().data()); - for (int y = 0; y < frame.height(); ++y) { - uchar *destination = gray.scanLine(y); - for (int x = 0; x < frame.width(); ++x) { - quint16 millimeters = 0; - std::memcpy(&millimeters, - source + (y * frame.width() + x) * sizeof(quint16), - sizeof(quint16)); - const int clamped = std::min(millimeters, 5000); - destination[x] = static_cast(255 - (clamped * 255 / 5000)); - } - } - return videoFrameFromImage(gray); -} -#endif -} - -class BackendWorker : public QObject -{ -public: - struct CameraStreamSession { - QString cameraId; - QString codec; - QString mode = QStringLiteral("rgb"); - std::atomic stop{false}; - std::atomic running{false}; - std::thread thread; -#ifdef CMVR_WITH_GRPC - grpc::ClientContext *context = nullptr; - std::mutex contextMutex; -#endif - }; - - struct ArmMotionSession { - std::atomic stop{false}; - std::atomic running{false}; - std::thread thread; -#ifdef CMVR_WITH_GRPC - grpc::ClientContext *context = nullptr; - std::mutex contextMutex; -#endif - }; - - explicit BackendWorker(QObject *parent = nullptr) - : QObject(parent) - { - m_pollTimer = new QTimer(this); - m_pollTimer->setInterval(100); - connect(m_pollTimer, &QTimer::timeout, this, &BackendWorker::poll); - } - - ~BackendWorker() override - { - stopArmMotionInternal(); - stopCameraStreamInternal(); - stopSpeakerStreamInternal(true); - stopMicrophoneStreamInternal(); - stopAgvMapStreamInternal(); - } - -public: - void connectToServer(const QString &host, int port, bool demoMode) - { - m_host = host.trimmed(); - m_port = port; - m_demoMode = demoMode; - m_tick = 0; - - if (m_host.isEmpty()) { - emit connectionChanged(false, 0, QStringLiteral("主机地址不能为空")); - return; - } - - if (m_demoMode) { - m_connected = true; - m_pollTimer->start(); - emit connectionChanged(true, 8, QStringLiteral("演示数据源")); - emit logMessage(QStringLiteral("INFO"), - QStringLiteral("已启动演示模式,界面数据由本地模拟器生成")); - return; - } - -#ifdef CMVR_WITH_GRPC - const std::string endpoint = QStringLiteral("%1:%2").arg(m_host).arg(m_port).toStdString(); - m_channel = createGrpcChannel(endpoint); - QElapsedTimer elapsed; - elapsed.start(); - const auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(1200); - if (!m_channel->WaitForConnected(deadline)) { - m_connected = false; - emit connectionChanged(false, 0, QStringLiteral("连接超时,请检查地址和服务状态")); - emit logMessage(QStringLiteral("ERROR"), QStringLiteral("gRPC 通道连接超时:%1").arg(QString::fromStdString(endpoint))); - return; - } - m_arm = cmvr::api::ArmService::NewStub(m_channel); - m_camera = cmvr::api::CameraService::NewStub(m_channel); - m_system = cmvr::api::SystemService::NewStub(m_channel); - m_agv = cmvr::api::AgvService::NewStub(m_channel); - m_microphone = cmvr::api::MicPhoneService::NewStub(m_channel); - m_generic = std::make_unique(m_channel); - m_connected = true; - m_pollTimer->start(); - emit connectionChanged(true, static_cast(elapsed.elapsed()), QString::fromStdString(endpoint)); - emit logMessage(QStringLiteral("INFO"), QStringLiteral("gRPC 通道已连接:%1").arg(QString::fromStdString(endpoint))); -#else - m_connected = false; - emit connectionChanged(false, 0, QStringLiteral("当前程序未编译 gRPC 支持")); - emit logMessage(QStringLiteral("ERROR"), - QStringLiteral("请使用 CMake 和 gRPC C++ 依赖重新构建,或启用演示模式")); -#endif - } - - void disconnectFromServer() - { - m_pollTimer->stop(); - stopArmMotionInternal(); - stopCameraStreamInternal(); - stopSpeakerStreamInternal(true); - stopMicrophoneStreamInternal(); - stopAgvMapStreamInternal(); - if (m_cameraRecording) { - m_cameraRecording = false; - emit cameraRecordingStateChanged(false, QStringLiteral("连接已断开,录像状态未知")); - } - m_connected = false; - m_armPollingEnabled = false; -#ifdef CMVR_WITH_GRPC - m_arm.reset(); - m_camera.reset(); - m_system.reset(); - m_agv.reset(); - m_microphone.reset(); - m_generic.reset(); - m_channel.reset(); -#endif - emit connectionChanged(false, 0, QStringLiteral("已断开")); - emit logMessage(QStringLiteral("INFO"), QStringLiteral("连接已断开")); - } - - void connectConfigurationServer(const QString &host, int port) - { - const QString trimmedHost = host.trimmed(); - if (trimmedHost.isEmpty()) { - emit configurationConnectionChanged(false, QStringLiteral("主机地址不能为空")); - return; - } -#ifdef CMVR_WITH_GRPC - const std::string endpoint = QStringLiteral("%1:%2").arg(trimmedHost).arg(port).toStdString(); - m_configChannel = createGrpcChannel(endpoint); - const auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(1500); - if (!m_configChannel->WaitForConnected(deadline)) { - m_configuration.reset(); - m_configChannel.reset(); - m_configConnected = false; - emit configurationConnectionChanged( - false, QStringLiteral("配置服务连接超时:%1").arg(QString::fromStdString(endpoint))); - return; - } - m_configuration = cmvr::api::ConfigurationService::NewStub(m_configChannel); - m_configConnected = true; - emit configurationConnectionChanged( - true, QStringLiteral("已连接配置服务:%1").arg(QString::fromStdString(endpoint))); -#else - Q_UNUSED(port) - emit configurationConnectionChanged(false, QStringLiteral("当前程序未编译 gRPC 支持")); -#endif - } - - void disconnectConfigurationServer() - { -#ifdef CMVR_WITH_GRPC - m_configuration.reset(); - m_configChannel.reset(); -#endif - m_configConnected = false; - emit configurationConnectionChanged(false, QStringLiteral("配置服务已断开")); - } - - void listConfigurationFiles() - { -#ifdef CMVR_WITH_GRPC - if (!ensureConfigurationConnected(QStringLiteral("读取配置列表"))) - return; - cmvr::api::ListConfigFilesCommand::Request request; - cmvr::api::ListConfigFilesCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 3000); - const grpc::Status status = m_configuration->ListConfigFiles(&context, request, &response); - const bool success = status.ok() && response.header().success(); - QVariantList files; - if (success) { - for (const auto &file : response.files()) { - QVariantMap item; - item.insert(QStringLiteral("relativePath"), QString::fromStdString(file.relative_path())); - item.insert(QStringLiteral("sizeBytes"), QVariant::fromValue(file.size_bytes())); - item.insert(QStringLiteral("modifiedUnixMs"), QVariant::fromValue(file.modified_unix_ms())); - item.insert(QStringLiteral("messageType"), QString::fromStdString(file.message_type())); - files.append(item); - } - } - emit configurationFilesReceived( - QString::fromStdString(response.config_root()), files, success, - configurationError(status, response.header().error_message())); -#endif - } - - void readConfigurationFile(const QString &relativePath) - { -#ifdef CMVR_WITH_GRPC - if (!ensureConfigurationConnected(QStringLiteral("读取配置文件"))) - return; - cmvr::api::ReadConfigFileCommand::Request request; - request.set_relative_path(relativePath.toStdString()); - cmvr::api::ReadConfigFileCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 3000); - const grpc::Status status = m_configuration->ReadConfigFile(&context, request, &response); - const bool success = status.ok() && response.header().success(); - emit configurationFileReceived( - relativePath, - success ? QString::fromStdString(response.content()) : QString(), - success ? QString::fromStdString(response.revision()) : QString(), - success ? QString::fromStdString(response.file().message_type()) : QString(), - success, configurationError(status, response.header().error_message())); -#else - Q_UNUSED(relativePath) -#endif - } - - void validateConfigurationFile(const QString &relativePath, const QString &content) - { -#ifdef CMVR_WITH_GRPC - if (!ensureConfigurationConnected(QStringLiteral("校验配置文件"))) - return; - cmvr::api::ValidateConfigFileCommand::Request request; - request.set_relative_path(relativePath.toStdString()); - request.set_content(content.toStdString()); - cmvr::api::ValidateConfigFileCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 3000); - const grpc::Status status = m_configuration->ValidateConfigFile(&context, request, &response); - const bool success = status.ok() && response.header().success(); - QString detail = configurationError(status, response.header().error_message()); - if (success) - detail = QStringLiteral("配置有效:%1").arg(QString::fromStdString(response.message_type())); - emit configurationValidationFinished(relativePath, success, detail); -#else - Q_UNUSED(relativePath) - Q_UNUSED(content) -#endif - } - - void saveConfigurationFile(const QString &relativePath, const QString &content, - const QString &expectedRevision) - { -#ifdef CMVR_WITH_GRPC - if (!ensureConfigurationConnected(QStringLiteral("保存配置文件"))) - return; - cmvr::api::SaveConfigFileCommand::Request request; - request.set_relative_path(relativePath.toStdString()); - request.set_content(content.toStdString()); - request.set_expected_revision(expectedRevision.toStdString()); - cmvr::api::SaveConfigFileCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 5000); - const grpc::Status status = m_configuration->SaveConfigFile(&context, request, &response); - const bool success = status.ok() && response.header().success(); - emit configurationSaveFinished( - relativePath, success ? QString::fromStdString(response.revision()) : QString(), - success, configurationError(status, response.header().error_message())); -#else - Q_UNUSED(relativePath) - Q_UNUSED(content) - Q_UNUSED(expectedRevision) -#endif - } - - void setArmTelemetry(const QString &deviceId, bool enabled) - { - if (enabled && !ensureConnected(QStringLiteral("Arm Telemetry"))) - return; - if (enabled && !ensureDeviceId(QStringLiteral("Arm Telemetry"), deviceId)) - return; - const QString nextDeviceId = enabled ? deviceId.trimmed() : QString(); - if (m_armDeviceId != nextDeviceId) { - m_demoTargets.clear(); - m_armBaseFrame.clear(); - m_armTcpFrame.clear(); - } - m_armDeviceId = nextDeviceId; - m_armPollingEnabled = enabled; - m_consecutivePollErrors = 0; - emit commandFinished(QStringLiteral("Arm Telemetry"), true, - enabled ? QStringLiteral("机械臂遥测已启动") - : QStringLiteral("机械臂遥测已停止")); - } - - void getArmInfo(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("GetArmInfo")) - || !ensureDeviceId(QStringLiteral("GetArmInfo"), deviceId)) { - return; - } - QVariantMap info; - info.insert(QStringLiteral("deviceId"), deviceId.trimmed()); - if (m_demoMode) { - const QStringList jointNames = armJointNamesForDevice(deviceId); - info.insert(QStringLiteral("manufacturer"), QStringLiteral("CMVR")); - info.insert(QStringLiteral("model"), QStringLiteral("demo_arm")); - info.insert(QStringLiteral("descriptionId"), QStringLiteral("demo_arm")); - info.insert(QStringLiteral("dof"), jointNames.size()); - info.insert(QStringLiteral("jointNames"), jointNames); - info.insert(QStringLiteral("detectedFromSdk"), false); - emit armInfoReceived(deviceId.trimmed(), info); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::GetArmInfo::Request request; - fillHeader(request.mutable_header(), deviceId); - cmvr::api::GetArmInfo::Response response; - grpc::ClientContext context; - setDeadline(context, 1200); - const grpc::Status status = m_arm->GetArmInfo(&context, request, &response); - if (!status.ok() || !response.header().success()) { - const QString detail = status.ok() - ? QString::fromStdString(response.header().error_message()) - : QString::fromStdString(status.error_message()); - emit commandFinished(QStringLiteral("GetArmInfo"), false, detail); - return; - } - QStringList jointNames; - jointNames.reserve(response.joint_names_size()); - for (const auto &name : response.joint_names()) - jointNames.append(QString::fromStdString(name)); - info.insert(QStringLiteral("manufacturer"), QString::fromStdString(response.manufacturer())); - info.insert(QStringLiteral("model"), QString::fromStdString(response.model())); - info.insert(QStringLiteral("subtype"), QString::fromStdString(response.subtype())); - info.insert(QStringLiteral("dof"), static_cast(response.dof())); - info.insert(QStringLiteral("jointNames"), jointNames); - info.insert(QStringLiteral("defaultBaseFrame"), QString::fromStdString(response.default_base_frame())); - info.insert(QStringLiteral("defaultTcpFrame"), QString::fromStdString(response.default_tcp_frame())); - info.insert(QStringLiteral("descriptionId"), QString::fromStdString(response.description_id())); - info.insert(QStringLiteral("detectedFromSdk"), response.detected_from_sdk()); - info.insert(QStringLiteral("driverType"), QString::fromStdString(response.driver_type())); - emit armInfoReceived(deviceId.trimmed(), info); -#endif - } - - void getArmFrames(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("List Arm Frames")) - || !ensureDeviceId(QStringLiteral("List Arm Frames"), deviceId)) { - return; - } - QStringList baseFrames; - QStringList tcpFrames; - if (m_demoMode) { - baseFrames << QStringLiteral("base0") << QStringLiteral("world"); - tcpFrames << QStringLiteral("tool0") << QStringLiteral("flange"); - emit armFramesReceived(deviceId.trimmed(), baseFrames, tcpFrames); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::ListFrame::Request baseRequest; - fillHeader(baseRequest.mutable_header(), deviceId); - cmvr::api::ListFrame::Response baseResponse; - grpc::ClientContext baseContext; - setDeadline(baseContext, 1500); - const grpc::Status baseStatus = - m_arm->ListBaseFrame(&baseContext, baseRequest, &baseResponse); - if (baseStatus.ok() && baseResponse.header().success()) { - for (const auto &name : baseResponse.frame_names()) - baseFrames.append(QString::fromStdString(name)); - } - - cmvr::api::ListFrame::Request tcpRequest; - fillHeader(tcpRequest.mutable_header(), deviceId); - cmvr::api::ListFrame::Response tcpResponse; - grpc::ClientContext tcpContext; - setDeadline(tcpContext, 1500); - const grpc::Status tcpStatus = - m_arm->ListTCPFrame(&tcpContext, tcpRequest, &tcpResponse); - if (tcpStatus.ok() && tcpResponse.header().success()) { - for (const auto &name : tcpResponse.frame_names()) - tcpFrames.append(QString::fromStdString(name)); - } - emit armFramesReceived(deviceId.trimmed(), baseFrames, tcpFrames); - if (!baseStatus.ok() || !baseResponse.header().success() - || !tcpStatus.ok() || !tcpResponse.header().success()) { - emit logMessage(QStringLiteral("WARN"), - QStringLiteral("机械臂坐标系列表未完整返回,将使用 SDK 默认坐标系")); - } -#endif - } - - void setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame, - const QString &tcpFrame) - { - if (deviceId.trimmed() != m_armDeviceId) - return; - m_armBaseFrame = baseFrame.trimmed(); - m_armTcpFrame = tcpFrame.trimmed(); - } - - void speedJ(const QString &deviceId, const QVariantList &velocities, - double acceleration, double duration) - { - if (!ensureConnected(QStringLiteral("SpeedJ")) - || !ensureDeviceId(QStringLiteral("SpeedJ"), deviceId)) { - return; - } - if (velocities.isEmpty()) { - emit commandFinished(QStringLiteral("SpeedJ"), false, - QStringLiteral("关节速度不能为空")); - return; - } - if (m_demoMode) { - emit commandFinished(QStringLiteral("SpeedJ"), true, - QStringLiteral("演示点动:%1 个关节").arg(velocities.size())); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::SpeedJ::Request request; - fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs); - for (const QVariant &value : velocities) - request.mutable_velocity()->add_velocity(value.toDouble()); - request.set_acceleration(acceleration); - request.set_duration(duration); - startArmMotion( - QStringLiteral("SpeedJ"), std::move(request), - [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, - const cmvr::api::SpeedJ::Request &motionRequest, - cmvr::api::SpeedJ::Response *response) { - return stub.speedJ(context, motionRequest, response); - }); -#endif - } - - void speedL(const QString &deviceId, const QVariantMap &velocity, - double acceleration, double duration, bool toolFrame) - { - if (!ensureConnected(QStringLiteral("SpeedL")) - || !ensureDeviceId(QStringLiteral("SpeedL"), deviceId)) { - return; - } - if (m_demoMode) { - emit commandFinished(QStringLiteral("SpeedL"), true, - QStringLiteral("演示笛卡尔点动")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::SpeedL::Request request; - fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs); - auto *target = request.mutable_velocity(); - target->set_vx(velocity.value(QStringLiteral("vx")).toDouble()); - target->set_vy(velocity.value(QStringLiteral("vy")).toDouble()); - target->set_vz(velocity.value(QStringLiteral("vz")).toDouble()); - target->set_wx(velocity.value(QStringLiteral("wx")).toDouble()); - target->set_wy(velocity.value(QStringLiteral("wy")).toDouble()); - target->set_wz(velocity.value(QStringLiteral("wz")).toDouble()); - request.set_acceleration(acceleration); - request.set_duration(duration); - request.set_frame(toolFrame ? cmvr::api::ARM_FRAME_TOOL - : cmvr::api::ARM_FRAME_BASE); - startArmMotion( - QStringLiteral("SpeedL"), std::move(request), - [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, - const cmvr::api::SpeedL::Request &motionRequest, - cmvr::api::SpeedL::Response *response) { - return stub.speedL(context, motionRequest, response); - }); -#endif - } - - void moveJ(const QString &deviceId, const QVariantList &positions, - double velocity, double acceleration) - { - if (!ensureConnected(QStringLiteral("MoveJ"))) - return; - if (!ensureDeviceId(QStringLiteral("MoveJ"), deviceId)) - return; - if (positions.isEmpty()) { - emit commandFinished(QStringLiteral("MoveJ"), false, QStringLiteral("没有可发送的目标关节")); - return; - } - if (m_demoMode) { - m_demoTargets.clear(); - for (const QVariant &value : positions) - m_demoTargets.append(value.toDouble()); - emit commandFinished(QStringLiteral("MoveJ"), true, - QStringLiteral("已发送 %1 个目标,v=%2,a=%3") - .arg(positions.size()).arg(velocity, 0, 'f', 2).arg(acceleration, 0, 'f', 2)); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::MoveJ::Request request; - fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs); - for (const QVariant &value : positions) - request.mutable_target()->add_position(value.toDouble()); - request.mutable_options()->set_velocity(velocity); - request.mutable_options()->set_acceleration(acceleration); - startArmMotion( - QStringLiteral("MoveJ"), std::move(request), - [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, - const cmvr::api::MoveJ::Request &motionRequest, - cmvr::api::MoveJ::Response *response) { - return stub.moveJ(context, motionRequest, response); - }); -#endif - } - - void moveJPose(const QString &deviceId, const QVariantMap &pose, - const QString &baseLink, const QString &eeLink, - double velocity, double acceleration) - { - if (!ensureConnected(QStringLiteral("MoveL"))) - return; - if (!ensureDeviceId(QStringLiteral("MoveL"), deviceId)) - return; - if (m_demoMode) { - emit commandFinished(QStringLiteral("MoveL"), true, - QStringLiteral("已发送末端位姿 MoveL,%1 → %2,v=%3,a=%4") - .arg(baseLink, eeLink) - .arg(velocity, 0, 'f', 2) - .arg(acceleration, 0, 'f', 2)); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::MoveL::Request request; - fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs); - auto *target = request.mutable_target(); - target->set_x(pose.value(QStringLiteral("x")).toDouble()); - target->set_y(pose.value(QStringLiteral("y")).toDouble()); - target->set_z(pose.value(QStringLiteral("z")).toDouble()); - target->set_rx(pose.value(QStringLiteral("rx")).toDouble()); - target->set_ry(pose.value(QStringLiteral("ry")).toDouble()); - target->set_rz(pose.value(QStringLiteral("rz")).toDouble()); - request.mutable_options()->set_velocity(velocity); - request.mutable_options()->set_acceleration(acceleration); - request.set_frame(cmvr::api::ARM_FRAME_BASE); - if (!baseLink.trimmed().isEmpty()) - request.set_base_frame(baseLink.trimmed().toStdString()); - if (!eeLink.trimmed().isEmpty()) - request.set_tcp_frame(eeLink.trimmed().toStdString()); - startArmMotion( - QStringLiteral("MoveL"), std::move(request), - [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, - const cmvr::api::MoveL::Request &motionRequest, - cmvr::api::MoveL::Response *response) { - return stub.moveL(context, motionRequest, response); - }); -#endif - } - - void torque(const QString &deviceId, bool enabled) - { - const QString command = enabled ? QStringLiteral("Torque On") : QStringLiteral("Torque Off"); - if (!ensureConnected(command)) - return; - if (!ensureDeviceId(command, deviceId)) - return; - if (m_demoMode) { - emit commandFinished(command, true, enabled ? QStringLiteral("关节已使能") : QStringLiteral("关节已去使能")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::CommandHeader::Request request; - fillHeader(&request, deviceId); - cmvr::api::CommandHeader::Feedback response; - grpc::ClientContext context; - setDeadline(context, 2000); - const grpc::Status status = enabled - ? m_arm->torqueOn(&context, request, &response) - : m_arm->torqueOff(&context, request, &response); - finish(command, status, response.success(), QString::fromStdString(response.error_message())); -#endif - } - - void armStop(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("Stop Motion"))) - return; - if (!ensureDeviceId(QStringLiteral("Stop Motion"), deviceId)) - return; - if (m_demoMode) { - m_demoTargets.clear(); - emit commandFinished(QStringLiteral("Stop Motion"), true, QStringLiteral("运动已停止")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::CommandHeader::Request request; - fillHeader(&request, deviceId); - cmvr::api::CommandHeader::Feedback response; - grpc::ClientContext context; - setDeadline(context, 1500); - const grpc::Status status = m_arm->stopMotion(&context, request, &response); - finish(QStringLiteral("Stop Motion"), status, response.success(), QString::fromStdString(response.error_message())); -#endif - } - - void armClearFault(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("Clear Fault"))) - return; - if (!ensureDeviceId(QStringLiteral("Clear Fault"), deviceId)) - return; - if (m_demoMode) { - emit commandFinished(QStringLiteral("Clear Fault"), true, QStringLiteral("故障状态已清除")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::CommandHeader::Request request; - fillHeader(&request, deviceId); - cmvr::api::CommandHeader::Feedback response; - grpc::ClientContext context; - setDeadline(context, 2000); - const grpc::Status status = m_arm->clearFault(&context, request, &response); - finish(QStringLiteral("Clear Fault"), status, response.success(), QString::fromStdString(response.error_message())); -#endif - } - - void armCalibrateZero(const QString &deviceId, const QString &jointName) - { - const QString command = QStringLiteral("Calibrate Zero Q"); - if (!ensureConnected(command)) - return; - if (!ensureDeviceId(command, deviceId)) - return; - if (jointName.trimmed().isEmpty()) { - emit commandFinished(command, false, QStringLiteral("关节名称不能为空")); - return; - } - if (m_demoMode) { - emit commandFinished(command, true, - QStringLiteral("已将 %1 的当前位置设置为零位(演示)") - .arg(jointName)); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::CalibrateZeroQ::Request request; - fillHeader(request.mutable_header(), deviceId); - request.set_joint_name(jointName.toStdString()); - cmvr::api::CalibrateZeroQ::Response response; - grpc::ClientContext context; - setDeadline(context, 2500); - const grpc::Status status = m_arm->calibrateZeroQ(&context, request, &response); - finish(command, status, response.header().success(), - QString::fromStdString(response.header().error_message())); -#endif - } - - void snapshot(const QString &cameraId) - { - if (!ensureConnected(QStringLiteral("Snapshot"))) - return; - if (!ensureDeviceId(QStringLiteral("Snapshot"), cameraId)) - return; - if (m_demoMode) { - QImage image(1280, 720, QImage::Format_RGB32); - image.fill(QColor("#20252b")); - QPainter painter(&image); - painter.setRenderHint(QPainter::Antialiasing); - painter.setPen(QPen(QColor("#3b424b"), 1)); - for (int x = 0; x < image.width(); x += 64) - painter.drawLine(x, 0, x, image.height()); - for (int y = 0; y < image.height(); y += 64) - painter.drawLine(0, y, image.width(), y); - painter.setPen(QColor("#e9edf2")); - painter.setFont(QFont("Microsoft YaHei UI", 28, QFont::DemiBold)); - painter.drawText(image.rect().adjusted(0, -40, 0, 0), Qt::AlignCenter, QStringLiteral("相机预览")); - painter.setPen(QColor("#9ca4ad")); - painter.setFont(QFont("Microsoft YaHei UI", 14)); - painter.drawText(image.rect().adjusted(0, 48, 0, 0), Qt::AlignCenter, - QStringLiteral("%1 · DEMO · %2") - .arg(cameraId, QDateTime::currentDateTime().toString("HH:mm:ss"))); - emit imageReceived(image, QStringLiteral("1280 x 720 · 演示帧")); - emit commandFinished(QStringLiteral("Snapshot"), true, QStringLiteral("已获取演示图像")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::GetRGBImageCommand::Request request; - fillHeader(request.mutable_header(), cameraId); - cmvr::api::GetRGBImageCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 3000); - const grpc::Status status = m_camera->GetRGBImage(&context, request, &response); - if (!status.ok() || !response.header().success()) { - finish(QStringLiteral("Snapshot"), status, response.header().success(), - QString::fromStdString(response.header().error_message())); - return; - } - const auto &frame = response.color_frame(); - const QByteArray bytes(frame.data().data(), static_cast(frame.data().size())); - QImage image; - if (frame.type() == cmvr::api::FrameData::U8C3 && - frame.width() > 0 && frame.height() > 0 && bytes.size() == frame.width() * frame.height() * 3) { - image = QImage(reinterpret_cast(bytes.constData()), frame.width(), frame.height(), - frame.width() * 3, QImage::Format_RGB888).rgbSwapped(); - } else if (frame.type() == cmvr::api::FrameData::U8C1 && - frame.width() > 0 && frame.height() > 0 && bytes.size() == frame.width() * frame.height()) { - image = QImage(reinterpret_cast(bytes.constData()), frame.width(), frame.height(), - frame.width(), QImage::Format_Grayscale8).copy(); - } else { - image = QImage::fromData(bytes); - } - if (image.isNull()) { - emit commandFinished(QStringLiteral("Snapshot"), false, - QStringLiteral("暂不支持图像编码:%1").arg(QString::fromStdString(frame.codec()))); - return; - } - emit imageReceived(image, QStringLiteral("%1 x %2 · %3") - .arg(image.width()).arg(image.height()).arg(QString::fromStdString(frame.codec()))); - emit commandFinished(QStringLiteral("Snapshot"), true, QStringLiteral("图像获取成功")); -#endif - } - - void startCameraStream(const QString &cameraId, const QString &codec, - const QString &mode) - { - if (!ensureConnected(QStringLiteral("Camera Stream")) || - !ensureDeviceId(QStringLiteral("Camera Stream"), cameraId)) - return; - - const QString normalizedCameraId = cameraId.trimmed(); - std::shared_ptr existing; - { - std::lock_guard lock(m_cameraSessionsMutex); - const auto it = m_cameraSessions.find(normalizedCameraId); - if (it != m_cameraSessions.end()) - existing = it.value(); - } - if (existing && existing->running.load()) { - emit commandFinished(QStringLiteral("Camera Stream"), false, - QStringLiteral("摄像头 %1 的视频预览已经在运行") - .arg(normalizedCameraId)); - return; - } - if (existing) - stopCameraStreamInternal(normalizedCameraId); - - auto session = std::make_shared(); - session->cameraId = normalizedCameraId; - session->codec = codec.trimmed().toLower(); - session->mode = mode.trimmed().toLower(); - if (session->mode != QStringLiteral("depth") && - session->mode != QStringLiteral("rgbd")) - session->mode = QStringLiteral("rgb"); - if (session->codec.isEmpty()) - session->codec = m_defaultCameraCodec; - session->running.store(true); - { - std::lock_guard lock(m_cameraSessionsMutex); - m_cameraSessions[normalizedCameraId] = session; - } - emit cameraStreamStateChangedForCamera(normalizedCameraId, true, - QStringLiteral("正在建立视频流...")); - - if (m_demoMode) { - session->thread = std::thread([this, session]() { - int frameNumber = 0; - QElapsedTimer elapsed; - elapsed.start(); - while (!session->stop.load()) { - QImage image(1280, 720, QImage::Format_RGB32); - image.fill(QColor("#20252b")); - QPainter painter(&image); - painter.setPen(QPen(QColor("#3b424b"), 1)); - const int offset = frameNumber % 64; - for (int x = offset; x < image.width(); x += 64) - painter.drawLine(x, 0, x, image.height()); - for (int y = offset; y < image.height(); y += 64) - painter.drawLine(0, y, image.width(), y); - painter.setPen(QColor("#e9edf2")); - painter.setFont(QFont("Microsoft YaHei UI", 28, QFont::DemiBold)); - painter.drawText(image.rect().adjusted(0, -40, 0, 0), Qt::AlignCenter, - QStringLiteral("摄像头实时预览")); - painter.setPen(QColor("#9ca4ad")); - painter.setFont(QFont("Microsoft YaHei UI", 14)); - painter.drawText(image.rect().adjusted(0, 48, 0, 0), Qt::AlignCenter, - QStringLiteral("%1 | DEMO | frame %2") - .arg(session->cameraId).arg(frameNumber)); - const QString decodeCodec = session->codec == QStringLiteral("h265") - ? QStringLiteral("H.265") : QStringLiteral("H.264"); - if (videoFrameReceivedForCamera) - videoFrameReceivedForCamera( - session->cameraId, videoFrameFromImage(image), - QStringLiteral("1280 x 720 | DEMO / %1 | 30.0 FPS | #%2") - .arg(decodeCodec).arg(frameNumber)); - ++frameNumber; - std::this_thread::sleep_for(std::chrono::milliseconds(33)); - } - session->running.store(false); - if (cameraStreamStateChangedForCamera) - cameraStreamStateChangedForCamera( - session->cameraId, false, - QStringLiteral("视频预览已停止,%1 帧,%2 秒") - .arg(frameNumber) - .arg(elapsed.elapsed() / 1000.0, 0, 'f', 1)); - }); - return; - } - -#ifdef CMVR_WITH_GRPC - const std::shared_ptr channel = m_channel; - session->thread = std::thread([this, channel, session]() { - if (session->mode == QStringLiteral("depth")) - runDepthCameraStream(channel, session, false); - else if (session->mode == QStringLiteral("rgbd")) - runDepthCameraStream(channel, session, true); - else - runCameraStream(channel, session); - }); -#else - session->running.store(false); - emit cameraStreamStateChangedForCamera(session->cameraId, false, - QStringLiteral("当前程序未编译 gRPC 支持")); -#endif - } - - void stopCameraStream(const QString &cameraId) - { - stopCameraStreamInternal(cameraId.trimmed()); - } - - void startCameraRecording(const QString &cameraId, const QString &videoPath) - { - const QString command = QStringLiteral("Camera Start Recording"); - if (!ensureConnected(command) || !ensureDeviceId(command, cameraId)) - return; - const QString path = videoPath.trimmed(); - if (path.isEmpty()) { - emit commandFinished(command, false, QStringLiteral("服务端录像路径不能为空")); - return; - } - if (m_cameraRecording) { - emit commandFinished(command, false, QStringLiteral("相机已经在录像")); - return; - } - if (m_demoMode) { - m_cameraRecording = true; - emit cameraRecordingStateChanged(true, - QStringLiteral("演示录像中:%1").arg(path)); - emit commandFinished(command, true, QStringLiteral("录像已开始(演示)")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::StartCameraRecordingCommand::Request request; - fillHeader(request.mutable_header(), cameraId); - request.set_video_path(path.toStdString()); - cmvr::api::StartCameraRecordingCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 3000); - const grpc::Status status = m_camera->StartRecording(&context, request, &response); - const bool success = status.ok() && response.header().success(); - const QString error = status.ok() - ? QString::fromStdString(response.header().error_message()) - : QString::fromStdString(status.error_message()); - if (success) { - m_cameraRecording = true; - emit cameraRecordingStateChanged(true, QStringLiteral("录像中:%1").arg(path)); - } - finish(command, status, response.header().success(), error); -#endif - } - - void stopCameraRecording(const QString &cameraId) - { - const QString command = QStringLiteral("Camera Stop Recording"); - if (!ensureConnected(command) || !ensureDeviceId(command, cameraId)) - return; - if (!m_cameraRecording) { - emit commandFinished(command, false, QStringLiteral("当前没有正在进行的录像")); - return; - } - if (m_demoMode) { - m_cameraRecording = false; - emit cameraRecordingStateChanged(false, QStringLiteral("录像已停止")); - emit commandFinished(command, true, QStringLiteral("录像已停止(演示)")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::StopCameraRecordingCommand::Request request; - fillHeader(request.mutable_header(), cameraId); - cmvr::api::StopCameraRecordingCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 3000); - const grpc::Status status = m_camera->StopRecording(&context, request, &response); - const bool success = status.ok() && response.header().success(); - const QString error = status.ok() - ? QString::fromStdString(response.header().error_message()) - : QString::fromStdString(status.error_message()); - if (success) { - m_cameraRecording = false; - emit cameraRecordingStateChanged(false, QStringLiteral("录像已停止")); - } - finish(command, status, response.header().success(), error); -#endif - } - - void setCameraStreamCodec(const QString &codec) - { - const QString normalized = codec.trimmed().toLower(); - const bool hevc = normalized == QStringLiteral("h265") || - normalized == QStringLiteral("hevc") || - normalized == QStringLiteral("h.265"); - m_defaultCameraCodec = hevc ? QStringLiteral("h265") : QStringLiteral("h264"); - } - - void startSpeakerAudioStream(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("Speaker Stream")) || - !ensureDeviceId(QStringLiteral("Speaker Stream"), deviceId)) - return; - if (m_speakerStreamRunning.load()) { - emit commandFinished(QStringLiteral("Speaker Stream"), false, - QStringLiteral("扬声器音频流已经在运行")); - return; - } - if (m_speakerStreamThread.joinable()) - m_speakerStreamThread.join(); - { - std::lock_guard lock(m_speakerQueueMutex); - m_speakerQueue.clear(); - m_speakerQueueBytes = 0; - } - m_speakerStreamStop.store(false); - m_speakerStreamRunning.store(true); - m_speakerFrames.store(0); - m_speakerBytes.store(0); - emit audioStreamStateChanged(QStringLiteral("SpeakerService"), true, - QStringLiteral("正在建立扬声器客户端音频流...")); - - if (m_demoMode) { - emit audioStreamStateChanged(QStringLiteral("SpeakerService"), true, - QStringLiteral("演示模式:音频帧将在本地计数,不发送到设备")); - return; - } -#ifdef CMVR_WITH_GRPC - const std::shared_ptr channel = m_channel; - m_speakerStreamThread = std::thread([this, channel, deviceId]() { - runSpeakerAudioStream(channel, deviceId); - }); -#else - m_speakerStreamRunning.store(false); - emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false, - QStringLiteral("当前程序未编译 gRPC 支持")); -#endif - } - - void enqueueSpeakerAudioFrame(const QByteArray &data, int sampleRate, int channels, - qint64 pts, int samples) - { - if (!m_speakerStreamRunning.load() || data.isEmpty() || - sampleRate <= 0 || channels <= 0 || samples <= 0) - return; - if (m_demoMode) { - const quint64 frames = ++m_speakerFrames; - const quint64 bytes = m_speakerBytes.fetch_add(data.size()) + data.size(); - emit audioStreamStatistics(QStringLiteral("SpeakerService"), frames, bytes, - pts / 1000 + samples * 1000LL / sampleRate); - return; - } - - SpeakerAudioFrame frame; - frame.data = data; - frame.sampleRate = sampleRate; - frame.channels = channels; - frame.pts = pts; - frame.samples = samples; - { - std::lock_guard lock(m_speakerQueueMutex); - static const int kMaximumQueueBytes = 2 * 1024 * 1024; - while (!m_speakerQueue.empty() && - m_speakerQueueBytes + data.size() > kMaximumQueueBytes) { - m_speakerQueueBytes -= m_speakerQueue.front().data.size(); - m_speakerQueue.pop_front(); - } - m_speakerQueue.push_back(std::move(frame)); - m_speakerQueueBytes += data.size(); - } - m_speakerQueueCondition.notify_one(); - } - - void stopSpeakerAudioStream() - { - stopSpeakerStreamInternal(); - } - - void startMicrophoneAudioStream(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("MicPhone Stream")) || - !ensureDeviceId(QStringLiteral("MicPhone Stream"), deviceId)) - return; - if (m_microphoneStreamRunning.load()) { - emit commandFinished(QStringLiteral("MicPhone Stream"), false, - QStringLiteral("麦克风音频流已经在运行")); - return; - } - if (m_microphoneStreamThread.joinable()) - m_microphoneStreamThread.join(); - m_microphoneStreamStop.store(false); - m_microphoneStreamRunning.store(true); - m_microphoneFrames.store(0); - m_microphoneBytes.store(0); - emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), true, - QStringLiteral("正在建立麦克风服务端音频流...")); - - if (m_demoMode) { - m_microphoneStreamThread = std::thread([this]() { - const int sampleRate = 48000; - const int samples = sampleRate / 50; - const double pi = 3.14159265358979323846; - qint64 sampleIndex = 0; - while (!m_microphoneStreamStop.load()) { - QByteArray pcm(samples * 2, Qt::Uninitialized); - qint16 *output = reinterpret_cast(pcm.data()); - for (int i = 0; i < samples; ++i) { - output[i] = static_cast( - 1800.0 * qSin((sampleIndex + i) * 2.0 * pi * 440.0 / sampleRate)); - } - const qint64 pts = sampleIndex * 1000000LL / sampleRate; - sampleIndex += samples; - const quint64 frames = ++m_microphoneFrames; - const quint64 bytes = m_microphoneBytes.fetch_add(pcm.size()) + pcm.size(); - emit audioFrameReceived(pcm, sampleRate, 1, 0, - QStringLiteral("pcm_s16le"), pts, samples); - emit audioStreamStatistics(QStringLiteral("MicPhoneService"), frames, bytes, - sampleIndex * 1000LL / sampleRate); - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - } - m_microphoneStreamRunning.store(false); - emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, - QStringLiteral("麦克风音频拉流已停止")); - }); - emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), true, - QStringLiteral("演示模式:正在播放本地测试音")); - return; - } -#ifdef CMVR_WITH_GRPC - const std::shared_ptr channel = m_channel; - m_microphoneStreamThread = std::thread([this, channel, deviceId]() { - runMicrophoneAudioStream(channel, deviceId); - }); -#else - m_microphoneStreamRunning.store(false); - emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, - QStringLiteral("当前程序未编译 gRPC 支持")); -#endif - } - - void stopMicrophoneAudioStream() - { - stopMicrophoneStreamInternal(); - } - - void systemRefresh() - { - if (!ensureConnected(QStringLiteral("System Refresh"))) - return; - if (m_demoMode) { - QVariantMap info; - info.insert(QStringLiteral("name"), QStringLiteral("CMVR Demo Controller")); - info.insert(QStringLiteral("version"), QStringLiteral("demo-1.0")); - QString platform = QSysInfo::prettyProductName(); - if (platform.isEmpty()) - platform = QSysInfo::productType(); - info.insert(QStringLiteral("os"), platform + QStringLiteral(" / simulator")); - info.insert(QStringLiteral("architecture"), QSysInfo::currentCpuArchitecture()); - emit systemInfoReceived(info); - emit systemStatusReceived(34.0, 48.0, 62.0, demoDeviceList()); - emit commandFinished(QStringLiteral("System Refresh"), true, QStringLiteral("系统信息已刷新")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::GetSystemInfoCommand::Request request; - cmvr::api::GetSystemInfoCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 1200); - const grpc::Status infoStatus = m_system->GetSystemInfo(&context, request, &response); - if (infoStatus.ok() && response.header().success()) { - QVariantMap info; - info.insert(QStringLiteral("name"), QString::fromStdString(response.system_name())); - info.insert(QStringLiteral("version"), QString::fromStdString(response.version())); - info.insert(QStringLiteral("description"), QString::fromStdString(response.description())); - info.insert(QStringLiteral("os"), QString::fromStdString(response.os())); - info.insert(QStringLiteral("kernel"), QString::fromStdString(response.kernel_version())); - info.insert(QStringLiteral("architecture"), QString::fromStdString(response.architecture())); - emit systemInfoReceived(info); - } - - cmvr::api::GetSystemStatusCommand::Request statusRequest; - cmvr::api::GetSystemStatusCommand::Feedback statusResponse; - grpc::ClientContext statusContext; - setDeadline(statusContext, 1200); - const grpc::Status status = m_system->GetSystemStatus( - &statusContext, statusRequest, &statusResponse); - if (status.ok() && statusResponse.header().success()) { - const double memory = statusResponse.mem_total_mb() > 0 - ? statusResponse.mem_used_mb() * 100.0 / statusResponse.mem_total_mb() : 0.0; - const double disk = statusResponse.disk_total_gb() > 0 - ? statusResponse.disk_used_gb() * 100.0 / statusResponse.disk_total_gb() : 0.0; - emit systemStatusReceived(statusResponse.cpu_usage(), memory, disk, - deviceListFromStatus(statusResponse)); - } - - if (!infoStatus.ok() || !response.header().success()) { - finish(QStringLiteral("System Refresh"), infoStatus, response.header().success(), - QString::fromStdString(response.header().error_message())); - } else { - finish(QStringLiteral("System Refresh"), status, statusResponse.header().success(), - QString::fromStdString(statusResponse.header().error_message())); - } -#endif - } - - void systemStopAll(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("System StopAll")) || - !ensureDeviceId(QStringLiteral("System StopAll"), deviceId)) - return; - if (m_demoMode) { - emit commandFinished(QStringLiteral("System StopAll"), true, QStringLiteral("全局停止命令已执行")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::StopAllCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - cmvr::api::StopAllCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 1800); - const grpc::Status status = m_system->StopAll(&context, request, &response); - finish(QStringLiteral("System StopAll"), status, response.header().success(), - QString::fromStdString(response.header().error_message())); -#endif - } - - void agvRefresh(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("AGV Refresh")) || - !ensureDeviceId(QStringLiteral("AGV Refresh"), deviceId)) - return; - if (m_demoMode) { - QVariantMap state; - state.insert(QStringLiteral("connected"), true); - state.insert(QStringLiteral("timestamp"), QDateTime::currentMSecsSinceEpoch() / 1000.0); - state.insert(QStringLiteral("mode"), 1); - state.insert(QStringLiteral("localized"), true); - state.insert(QStringLiteral("moving"), false); - state.insert(QStringLiteral("fault"), false); - state.insert(QStringLiteral("emergency"), false); - state.insert(QStringLiteral("map"), QStringLiteral("demo_map")); - state.insert(QStringLiteral("station"), QStringLiteral("HOME")); - state.insert(QStringLiteral("battery"), 0.82); - state.insert(QStringLiteral("voltage"), 49.2); - state.insert(QStringLiteral("current"), -2.9); - state.insert(QStringLiteral("temperature"), 28.0); - state.insert(QStringLiteral("charging"), false); - state.insert(QStringLiteral("x"), 1.24); - state.insert(QStringLiteral("y"), -0.36); - state.insert(QStringLiteral("theta"), 0.12); - QVariantMap navigation; - navigation.insert(QStringLiteral("state"), 0); - navigation.insert(QStringLiteral("type"), 0); - navigation.insert(QStringLiteral("progress"), 0.0); - navigation.insert(QStringLiteral("message"), QStringLiteral("空闲")); - emit agvStateReceived(state, navigation); - emit commandFinished(QStringLiteral("AGV Refresh"), true, QStringLiteral("AGV 状态已刷新")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::AgvRuntimeStateCommand::Request stateRequest; - fillHeader(stateRequest.mutable_header(), deviceId); - cmvr::api::AgvRuntimeStateCommand::Feedback stateResponse; - grpc::ClientContext stateContext; - setDeadline(stateContext, 1000); - const grpc::Status stateStatus = m_agv->getRuntimeState(&stateContext, stateRequest, &stateResponse); - - cmvr::api::AgvNavigationStatusCommand::Request navRequest; - fillHeader(navRequest.mutable_header(), deviceId); - cmvr::api::AgvNavigationStatusCommand::Feedback navResponse; - grpc::ClientContext navContext; - setDeadline(navContext, 1000); - const grpc::Status navStatus = m_agv->getNavigationStatus(&navContext, navRequest, &navResponse); - - if (stateStatus.ok() && stateResponse.header().success()) { - const auto &source = stateResponse.state(); - QVariantMap state; - state.insert(QStringLiteral("connected"), source.connected()); - state.insert(QStringLiteral("timestamp"), source.timestamp()); - state.insert(QStringLiteral("mode"), source.mode()); - state.insert(QStringLiteral("localized"), source.localized()); - state.insert(QStringLiteral("moving"), source.moving()); - state.insert(QStringLiteral("fault"), source.fault()); - state.insert(QStringLiteral("emergency"), source.emergency_stopped()); - state.insert(QStringLiteral("map"), QString::fromStdString(source.current_map())); - state.insert(QStringLiteral("station"), QString::fromStdString(source.current_station())); - state.insert(QStringLiteral("battery"), source.battery().percentage()); - state.insert(QStringLiteral("voltage"), source.battery().voltage()); - state.insert(QStringLiteral("current"), source.battery().current()); - state.insert(QStringLiteral("temperature"), source.battery().temperature()); - state.insert(QStringLiteral("charging"), source.battery().charging()); - state.insert(QStringLiteral("x"), source.pose().x()); - state.insert(QStringLiteral("y"), source.pose().y()); - state.insert(QStringLiteral("theta"), source.pose().theta()); - state.insert(QStringLiteral("vx"), source.velocity().vx()); - state.insert(QStringLiteral("vy"), source.velocity().vy()); - state.insert(QStringLiteral("wz"), source.velocity().wz()); - state.insert(QStringLiteral("error"), QString::fromStdString(source.last_error())); - QVariantMap navigation; - if (navStatus.ok() && navResponse.header().success()) { - navigation.insert(QStringLiteral("state"), navResponse.status().state()); - navigation.insert(QStringLiteral("type"), navResponse.status().type()); - navigation.insert(QStringLiteral("progress"), navResponse.status().progress()); - navigation.insert(QStringLiteral("message"), QString::fromStdString(navResponse.status().message())); - } - emit agvStateReceived(state, navigation); - } - finish(QStringLiteral("AGV Refresh"), stateStatus, stateResponse.header().success(), - QString::fromStdString(stateResponse.header().error_message())); -#endif - } - - void agvRelocalize(const QString &deviceId, double x, double y, double theta) - { - const QString command = QStringLiteral("AGV Relocalize"); - if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) - return; - if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(theta)) { - emit commandFinished(command, false, - QStringLiteral("重新定位位姿必须是有效数值")); - return; - } - if (m_demoMode) { - emit commandFinished(command, true, - QStringLiteral("重新定位位姿已下发")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::AgvRelocalizeCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - request.mutable_pose()->set_x(x); - request.mutable_pose()->set_y(y); - request.mutable_pose()->set_theta(theta); - cmvr::api::AgvRelocalizeCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 2500); - const grpc::Status status = m_agv->relocalize(&context, request, &response); - finish(command, status, response.header().success(), - QString::fromStdString(response.header().error_message())); -#endif - } - - void agvNavigatePose(const QString &deviceId, double x, double y, double theta, double maxSpeed) - { - if (!ensureConnected(QStringLiteral("AGV NavigateToPose")) || - !ensureDeviceId(QStringLiteral("AGV NavigateToPose"), deviceId)) - return; - if (m_demoMode) { - emit commandFinished(QStringLiteral("AGV NavigateToPose"), true, - QStringLiteral("目标位姿 (%1, %2, %3) 已下发").arg(x).arg(y).arg(theta)); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::AgvNavigateToPoseCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - request.mutable_pose()->set_x(x); - request.mutable_pose()->set_y(y); - request.mutable_pose()->set_theta(theta); - request.mutable_options()->set_max_speed(maxSpeed); - request.mutable_options()->set_asynchronous(true); - cmvr::api::AgvNavigateToPoseCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 2500); - const grpc::Status status = m_agv->navigateToPose(&context, request, &response); - finish(QStringLiteral("AGV NavigateToPose"), status, response.header().success(), - QString::fromStdString(response.header().error_message())); -#endif - } - - void agvNavigateStation(const QString &deviceId, const QString &stationId, double maxSpeed) - { - if (!ensureConnected(QStringLiteral("AGV NavigateToStation")) || - !ensureDeviceId(QStringLiteral("AGV NavigateToStation"), deviceId)) - return; - if (stationId.trimmed().isEmpty()) { - emit commandFinished(QStringLiteral("AGV NavigateToStation"), false, QStringLiteral("站点 ID 不能为空")); - return; - } - if (m_demoMode) { - emit commandFinished(QStringLiteral("AGV NavigateToStation"), true, - QStringLiteral("目标站点 %1 已下发").arg(stationId)); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::AgvNavigateToStationCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - request.set_station_id(stationId.toStdString()); - request.mutable_options()->set_max_speed(maxSpeed); - request.mutable_options()->set_asynchronous(true); - cmvr::api::AgvNavigateToStationCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 2500); - const grpc::Status status = m_agv->navigateToStation(&context, request, &response); - finish(QStringLiteral("AGV NavigateToStation"), status, response.header().success(), - QString::fromStdString(response.header().error_message())); -#endif - } - - void agvFollowPath(const QString &deviceId, const QVariantList &path, double maxSpeed) - { - const QString command = QStringLiteral("AGV FollowPath"); - if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) - return; - if (path.isEmpty()) { - emit commandFinished(command, false, QStringLiteral("路径至少需要包含一个有效路径段")); - return; - } - if (m_demoMode) { - emit commandFinished(command, true, - QStringLiteral("包含 %1 个路径段的导航任务已下发").arg(path.size())); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::AgvFollowPathCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - for (const QVariant &entry : path) { - const QVariantMap segmentValue = entry.toMap(); - const QString source = segmentValue.value(QStringLiteral("sourceStation")).toString().trimmed(); - const QString target = segmentValue.value(QStringLiteral("targetStation")).toString().trimmed(); - if (source.isEmpty() || target.isEmpty()) { - emit commandFinished(command, false, QStringLiteral("路径段的起点和终点不能为空")); - return; - } - cmvr::msgs::AgvPathSegment *segment = request.add_path(); - segment->set_source_station(source.toStdString()); - segment->set_target_station(target.toStdString()); - } - request.mutable_options()->set_max_speed(maxSpeed); - request.mutable_options()->set_asynchronous(true); - cmvr::api::AgvFollowPathCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 2500); - const grpc::Status status = m_agv->followPath(&context, request, &response); - finish(command, status, response.header().success(), - QString::fromStdString(response.header().error_message())); -#endif - } - - void agvVelocity(const QString &deviceId, double vx, double vy, double wz) - { - if (!ensureConnected(QStringLiteral("AGV SetVelocity")) || - !ensureDeviceId(QStringLiteral("AGV SetVelocity"), deviceId)) - return; - if (m_demoMode) { - emit commandFinished(QStringLiteral("AGV SetVelocity"), true, QStringLiteral("底盘速度已下发")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::AgvSetVelocityCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - request.mutable_velocity()->set_vx(vx); - request.mutable_velocity()->set_vy(vy); - request.mutable_velocity()->set_wz(wz); - cmvr::api::AgvSetVelocityCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 1200); - const grpc::Status status = m_agv->setVelocity(&context, request, &response); - finish(QStringLiteral("AGV SetVelocity"), status, response.header().success(), - QString::fromStdString(response.header().error_message())); -#endif - } - - void agvAction(const QString &deviceId, const QString &action) - { - const QString command = QStringLiteral("AGV %1").arg(action); - if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) - return; - if (m_demoMode) { - emit commandFinished(command, true, QStringLiteral("AGV 操作已执行")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::CommandHeader::Request request; - fillHeader(&request, deviceId); - cmvr::api::CommandHeader::Feedback response; - grpc::ClientContext context; - setDeadline(context, 1500); - grpc::Status status; - if (action == QStringLiteral("EmergencyStop")) - status = m_agv->emergencyStop(&context, request, &response); - else if (action == QStringLiteral("ClearFault")) - status = m_agv->clearFault(&context, request, &response); - else if (action == QStringLiteral("Pause")) - status = m_agv->pauseNavigation(&context, request, &response); - else if (action == QStringLiteral("Resume")) - status = m_agv->resumeNavigation(&context, request, &response); - else if (action == QStringLiteral("Cancel")) - status = m_agv->cancelNavigation(&context, request, &response); - else if (action == QStringLiteral("StopVelocity")) - status = m_agv->stopVelocityControl(&context, request, &response); - else if (action == QStringLiteral("StopMapping")) - status = m_agv->stopMapping(&context, request, &response); - else { - emit commandFinished(command, false, QStringLiteral("未知 AGV 操作")); - return; - } - finish(command, status, response.success(), QString::fromStdString(response.error_message())); -#endif - } - - void agvInventory(const QString &deviceId) - { - if (!ensureConnected(QStringLiteral("AGV Inventory")) || - !ensureDeviceId(QStringLiteral("AGV Inventory"), deviceId)) - return; - if (m_demoMode) { - QVariantList stations; - QVariantMap home; - home.insert(QStringLiteral("id"), QStringLiteral("HOME")); - home.insert(QStringLiteral("type"), QStringLiteral("charge")); - home.insert(QStringLiteral("x"), 0.0); - home.insert(QStringLiteral("y"), 0.0); - stations.append(home); - const QStringList maps = {QStringLiteral("demo_map"), QStringLiteral("warehouse")}; - emit agvInventoryReceived(maps, stations); - emit commandFinished(QStringLiteral("AGV Inventory"), true, QStringLiteral("地图与站点已刷新")); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::AgvListMapsCommand::Request mapsRequest; - fillHeader(mapsRequest.mutable_header(), deviceId); - cmvr::api::AgvListMapsCommand::Feedback mapsResponse; - grpc::ClientContext mapsContext; - setDeadline(mapsContext, 1200); - const grpc::Status mapsStatus = m_agv->listMaps(&mapsContext, mapsRequest, &mapsResponse); - - cmvr::api::AgvListStationsCommand::Request stationsRequest; - fillHeader(stationsRequest.mutable_header(), deviceId); - cmvr::api::AgvListStationsCommand::Feedback stationsResponse; - grpc::ClientContext stationsContext; - setDeadline(stationsContext, 1200); - const grpc::Status stationsStatus = m_agv->listStations(&stationsContext, stationsRequest, &stationsResponse); - - if (mapsStatus.ok() && mapsResponse.header().success()) { - QStringList maps; - for (const auto &mapName : mapsResponse.maps()) - maps.append(QString::fromStdString(mapName)); - QVariantList stations; - if (stationsStatus.ok() && stationsResponse.header().success()) { - for (const auto &source : stationsResponse.stations()) { - QVariantMap station; - station.insert(QStringLiteral("id"), QString::fromStdString(source.id())); - station.insert(QStringLiteral("type"), QString::fromStdString(source.type())); - station.insert(QStringLiteral("description"), QString::fromStdString(source.description())); - station.insert(QStringLiteral("x"), source.pose().x()); - station.insert(QStringLiteral("y"), source.pose().y()); - station.insert(QStringLiteral("theta"), source.pose().theta()); - stations.append(station); - } - } - emit agvInventoryReceived(maps, stations); - } - finish(QStringLiteral("AGV Inventory"), mapsStatus, mapsResponse.header().success(), - QString::fromStdString(mapsResponse.header().error_message())); -#endif - } - - void agvSwitchMap(const QString &deviceId, const QString &mapName) - { - if (!ensureConnected(QStringLiteral("AGV SwitchMap")) || - !ensureDeviceId(QStringLiteral("AGV SwitchMap"), deviceId)) - return; - if (mapName.trimmed().isEmpty()) { - emit commandFinished(QStringLiteral("AGV SwitchMap"), false, QStringLiteral("地图名称不能为空")); - return; - } - if (m_demoMode) { - emit commandFinished(QStringLiteral("AGV SwitchMap"), true, - QStringLiteral("已切换到地图 %1").arg(mapName)); - return; - } -#ifdef CMVR_WITH_GRPC - cmvr::api::AgvMapCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - request.set_map_name(mapName.toStdString()); - cmvr::api::AgvMapCommand::Feedback response; - grpc::ClientContext context; - setDeadline(context, 2500); - const grpc::Status status = m_agv->switchMap(&context, request, &response); - finish(QStringLiteral("AGV SwitchMap"), status, response.header().success(), - QString::fromStdString(response.header().error_message())); -#endif - } - - void startAgvMapStream(const QString &deviceId, const QString &mapName, - int dimension, bool snapshot, bool incremental) - { - if (!ensureConnected(QStringLiteral("AGV StreamMap")) || - !ensureDeviceId(QStringLiteral("AGV StreamMap"), deviceId)) - return; - stopAgvMapStreamInternal(); - m_agvMapStreamStop.store(false); - m_agvMapStreamRunning.store(true); - emit agvMapStreamStateChanged(true, QStringLiteral("正在等待地图数据")); - - if (m_demoMode) { - QImage image(1280, 720, QImage::Format_RGB32); - image.fill(QColor(QStringLiteral("#eef2f6"))); - QPainter painter(&image); - painter.setRenderHint(QPainter::Antialiasing); - painter.setPen(QPen(QColor(QStringLiteral("#d3dde6")), 1)); - for (int x = 60; x < image.width(); x += 80) - painter.drawLine(x, 30, x, image.height() - 30); - for (int y = 40; y < image.height(); y += 60) - painter.drawLine(30, y, image.width() - 30, y); - const QVector stations = { - QPointF(180, 160), QPointF(460, 220), QPointF(760, 150), - QPointF(1050, 260), QPointF(850, 500), QPointF(400, 540) - }; - for (int i = 1; i < stations.size(); ++i) { - painter.setPen(QPen(QColor(QStringLiteral("#9db7ce")), 4)); - painter.drawLine(stations.at(i - 1), stations.at(i)); - } - for (int i = 0; i < stations.size(); ++i) { - painter.setPen(Qt::NoPen); - painter.setBrush(QColor(QStringLiteral("#218c74"))); - painter.drawEllipse(stations.at(i), 11, 11); - painter.setPen(QColor(QStringLiteral("#26323d"))); - painter.drawText(stations.at(i) + QPointF(15, -10), - QStringLiteral("STATION_%1").arg(i + 1)); - } - painter.setBrush(QColor(QStringLiteral("#237ddd"))); - painter.setPen(Qt::NoPen); - QPolygonF robot; - robot << QPointF(290, 320) << QPointF(260, 338) - << QPointF(260, 302); - painter.drawPolygon(robot); - painter.end(); - QVariantMap metadata; - metadata.insert(QStringLiteral("mapId"), QStringLiteral("demo_map")); - metadata.insert(QStringLiteral("dimension"), 2); - metadata.insert(QStringLiteral("originX"), 0.0); - metadata.insert(QStringLiteral("originY"), 0.0); - metadata.insert(QStringLiteral("originTheta"), 0.0); - metadata.insert(QStringLiteral("resolution"), 0.01); - metadata.insert(QStringLiteral("sourceWidth"), image.width()); - metadata.insert(QStringLiteral("sourceHeight"), image.height()); - metadata.insert(QStringLiteral("renderScale"), 1.0); - metadata.insert(QStringLiteral("timestamp"), - QDateTime::currentMSecsSinceEpoch() / 1000.0); - emit agvMapFrameReceived(image, metadata, - QStringLiteral("演示 2D 地图 · 6 个站点")); - return; - } - -#ifdef CMVR_WITH_GRPC - m_agvMapStreamThread = std::thread( - [this, deviceId, mapName, dimension, snapshot, incremental]() { - cmvr::api::AgvMapStreamCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - request.set_map_name(mapName.toStdString()); - request.set_dimension(static_cast(dimension)); - request.set_snapshot(snapshot); - request.set_incremental(incremental); - request.set_max_chunk_bytes(1024 * 1024); - - grpc::ClientContext context; - { - std::lock_guard lock(m_agvMapStreamContextMutex); - m_agvMapStreamContext = &context; - } - std::unique_ptr> - reader = m_agv->streamMap(&context, request); - cmvr::api::AgvMapStreamCommand::Feedback response; - while (!m_agvMapStreamStop.load() && reader->Read(&response)) { - if (!response.header().success()) - continue; - const auto &update = response.update(); - QImage image; - QVariantMap metadata; - QString detail; - if (update.has_map_2d()) { - const auto &map = update.map_2d(); - const int sourceWidth = static_cast(map.width()); - const int sourceHeight = static_cast(map.height()); - if (sourceWidth <= 0 || sourceHeight <= 0) - continue; - const double scale = qMin( - 1.0, qMin(1600.0 / sourceWidth, 1000.0 / sourceHeight)); - const int width = qMax(1, qRound(sourceWidth * scale)); - const int height = qMax(1, qRound(sourceHeight * scale)); - image = QImage(width, height, QImage::Format_RGB32); - for (int y = 0; y < height; ++y) { - QRgb *line = reinterpret_cast( - image.scanLine(height - 1 - y)); - const int sourceY = qMin(sourceHeight - 1, - qFloor(y / scale)); - for (int x = 0; x < width; ++x) { - const int sourceX = qMin(sourceWidth - 1, - qFloor(x / scale)); - const int index = sourceY * sourceWidth + sourceX; - const int value = index < map.data_size() - ? map.data(index) : -1; - if (value < 0) - line[x] = qRgb(205, 212, 219); - else if (value == 0) - line[x] = qRgb(248, 250, 252); - else { - const int shade = qBound(35, 235 - value * 2, 210); - line[x] = qRgb(shade, shade, shade); - } - } - } - QPainter painter(&image); - painter.setRenderHint(QPainter::Antialiasing); - const double resolution = map.resolution() > 0.0 - ? map.resolution() : 1.0; - for (const auto &object : map.objects()) { - QPolygonF geometry; - for (const auto &point : object.points()) { - geometry.append(QPointF( - (point.x() - map.origin().x()) / resolution * scale, - height - (point.y() - map.origin().y()) / - resolution * scale)); - } - painter.setPen(QPen(QColor(QStringLiteral("#218c74")), 2)); - painter.setBrush(QColor(33, 140, 116, 70)); - if (geometry.size() == 1) - painter.drawEllipse(geometry.first(), 6, 6); - else if (geometry.size() > 1) - painter.drawPolyline(geometry); - if (!geometry.isEmpty()) { - painter.setPen(QColor(QStringLiteral("#145da8"))); - painter.drawText(geometry.first() + QPointF(8, -6), - QString::fromStdString(object.id())); - } - } - painter.end(); - metadata.insert(QStringLiteral("mapId"), - QString::fromStdString(update.map_id())); - metadata.insert(QStringLiteral("dimension"), 2); - metadata.insert(QStringLiteral("originX"), map.origin().x()); - metadata.insert(QStringLiteral("originY"), map.origin().y()); - metadata.insert(QStringLiteral("originTheta"), map.origin().theta()); - metadata.insert(QStringLiteral("resolution"), resolution); - metadata.insert(QStringLiteral("sourceWidth"), sourceWidth); - metadata.insert(QStringLiteral("sourceHeight"), sourceHeight); - metadata.insert(QStringLiteral("renderScale"), scale); - metadata.insert(QStringLiteral("timestamp"), map.timestamp()); - metadata.insert(QStringLiteral("sequence"), - static_cast(update.sequence())); - metadata.insert(QStringLiteral("updateType"), - static_cast(update.update_type())); - detail = QStringLiteral("%1 · 2D · %2×%3 · seq %4") - .arg(QString::fromStdString(update.map_id())) - .arg(sourceWidth).arg(sourceHeight) - .arg(static_cast(update.sequence())); - } else if (update.has_map_3d()) { - const auto &map = update.map_3d(); - image = QImage(1280, 720, QImage::Format_RGB32); - image.fill(QColor(QStringLiteral("#eef2f6"))); - if (map.points_size() > 0) { - double minX = map.points(0).x(), maxX = minX; - double minY = map.points(0).y(), maxY = minY; - const int step = qMax(1, map.points_size() / 80000); - for (int i = 0; i < map.points_size(); i += step) { - minX = qMin(minX, map.points(i).x()); - maxX = qMax(maxX, map.points(i).x()); - minY = qMin(minY, map.points(i).y()); - maxY = qMax(maxY, map.points(i).y()); - } - if (qFuzzyCompare(minX, maxX)) { minX -= 1.0; maxX += 1.0; } - if (qFuzzyCompare(minY, maxY)) { minY -= 1.0; maxY += 1.0; } - QPainter painter(&image); - painter.setPen(QColor(QStringLiteral("#456b87"))); - for (int i = 0; i < map.points_size(); i += step) { - const auto &point = map.points(i); - painter.drawPoint(QPointF( - 30.0 + (point.x() - minX) / (maxX - minX) * 1220.0, - 690.0 - (point.y() - minY) / (maxY - minY) * 660.0)); - } - painter.end(); - } - metadata.insert(QStringLiteral("mapId"), - QString::fromStdString(update.map_id())); - metadata.insert(QStringLiteral("dimension"), 3); - metadata.insert(QStringLiteral("timestamp"), map.timestamp()); - metadata.insert(QStringLiteral("sequence"), - static_cast(update.sequence())); - detail = QStringLiteral("%1 · 3D · %2 points · seq %3") - .arg(QString::fromStdString(update.map_id())) - .arg(map.points_size()) - .arg(static_cast(update.sequence())); - } - if (!image.isNull()) - emit agvMapFrameReceived(image, metadata, detail); - } - const grpc::Status status = reader->Finish(); - { - std::lock_guard lock(m_agvMapStreamContextMutex); - m_agvMapStreamContext = nullptr; - } - m_agvMapStreamRunning.store(false); - const QString detail = m_agvMapStreamStop.load() - ? QStringLiteral("地图流已停止") - : status.ok() ? QStringLiteral("地图流已结束") - : QString::fromStdString(status.error_message()); - emit agvMapStreamStateChanged(false, detail); - }); -#endif - } - - void stopAgvMapStream() - { - stopAgvMapStreamInternal(); - emit agvMapStreamStateChanged(false, QStringLiteral("地图流已停止")); - } - - void invokeRpc(const QString &serviceName, const QString &methodName, - const QString &requestJson, const QString &deviceId) - { - const QString command = QStringLiteral("%1.%2").arg(serviceName, methodName); - if (!ensureConnected(command)) { - emit rpcFinished(serviceName, methodName, false, - QStringLiteral("{\"error\":\"设备尚未连接\"}")); - return; - } - if (m_demoMode) { - QJsonObject result; - result.insert(QStringLiteral("demo"), true); - result.insert(QStringLiteral("service"), serviceName); - result.insert(QStringLiteral("method"), methodName); - result.insert(QStringLiteral("deviceId"), deviceId); - result.insert(QStringLiteral("message"), QStringLiteral("演示模式调用成功")); - emit rpcFinished(serviceName, methodName, true, - QString::fromUtf8(QJsonDocument(result).toJson(QJsonDocument::Indented))); - emit commandFinished(command, true, QStringLiteral("演示模式 RPC 调用完成")); - return; - } -#ifdef CMVR_WITH_GRPC - const google::protobuf::ServiceDescriptor *service = - google::protobuf::DescriptorPool::generated_pool()->FindServiceByName( - serviceName.toStdString()); - const google::protobuf::MethodDescriptor *method = - service ? service->FindMethodByName(methodName.toStdString()) : nullptr; - if (!method || !m_generic) { - const QString error = QStringLiteral("找不到 RPC 描述符:%1").arg(command); - emit rpcFinished(serviceName, methodName, false, - QStringLiteral("{\"error\":\"%1\"}").arg(error)); - emit commandFinished(command, false, error); - return; - } - - google::protobuf::DynamicMessageFactory factory; - const google::protobuf::Message *requestPrototype = - factory.GetPrototype(method->input_type()); - const google::protobuf::Message *responsePrototype = - factory.GetPrototype(method->output_type()); - if (!requestPrototype || !responsePrototype) { - const QString error = QStringLiteral("无法创建 protobuf 动态消息"); - emit rpcFinished(serviceName, methodName, false, - QStringLiteral("{\"error\":\"%1\"}").arg(error)); - return; - } - - QStringList requestDocuments; - QJsonParseError parseError; - const QJsonDocument jsonDocument = QJsonDocument::fromJson(requestJson.toUtf8(), &parseError); - if (parseError.error != QJsonParseError::NoError) { - const QString error = QStringLiteral("请求 JSON 无效:%1").arg(parseError.errorString()); - emit rpcFinished(serviceName, methodName, false, - QStringLiteral("{\"error\":\"%1\"}").arg(error)); - return; - } - if (jsonDocument.isArray()) { - for (const QJsonValue &value : jsonDocument.array()) - requestDocuments.append(QString::fromUtf8( - QJsonDocument(value.toObject()).toJson(QJsonDocument::Compact))); - } else { - requestDocuments.append(QString::fromUtf8( - QJsonDocument(jsonDocument.object()).toJson(QJsonDocument::Compact))); - } - if (requestDocuments.isEmpty()) - requestDocuments.append(QStringLiteral("{}")); - - std::vector> requests; - std::vector requestBuffers; - google::protobuf::util::JsonParseOptions jsonOptions; - jsonOptions.ignore_unknown_fields = false; - for (const QString &document : requestDocuments) { - std::unique_ptr request(requestPrototype->New()); - const auto jsonStatus = google::protobuf::util::JsonStringToMessage( - document.toStdString(), request.get(), jsonOptions); - if (!jsonStatus.ok()) { - const QString error = QStringLiteral("protobuf JSON 转换失败:%1") - .arg(QString::fromStdString(jsonStatus.ToString())); - emit rpcFinished(serviceName, methodName, false, - QStringLiteral("{\"error\":\"%1\"}").arg(error)); - return; - } - setDynamicDeviceId(request.get(), deviceId); - std::string serialized; - request->SerializeToString(&serialized); - grpc::Slice slice(serialized); - requestBuffers.emplace_back(&slice, 1); - requests.emplace_back(std::move(request)); - } - - const std::string path = QStringLiteral("/%1/%2").arg(serviceName, methodName).toStdString(); - grpc::Status grpcStatus; - QJsonArray streamResponses; - QString unaryResponse; - bool transportOk = false; - if (!method->client_streaming() && !method->server_streaming()) { - grpc::ClientContext context; - setDeadline(context, 4000); - grpc::CompletionQueue queue; - grpc::ByteBuffer responseBuffer; - std::unique_ptr call = - m_generic->PrepareUnaryCall(&context, path, requestBuffers.front(), &queue); - call->StartCall(); - call->Finish(&responseBuffer, &grpcStatus, reinterpret_cast(1)); - void *tag = nullptr; - bool eventOk = false; - transportOk = queue.Next(&tag, &eventOk) && eventOk && - tag == reinterpret_cast(1) && grpcStatus.ok(); - if (transportOk) - unaryResponse = byteBufferToJson(responseBuffer, responsePrototype, factory); - queue.Shutdown(); - } else { - grpc::ClientContext context; - setDeadline(context, 5000); - grpc::CompletionQueue queue; - std::unique_ptr call = - m_generic->PrepareCall(&context, path, &queue); - void *tag = nullptr; - bool eventOk = false; - call->StartCall(reinterpret_cast(1)); - bool started = queue.Next(&tag, &eventOk) && eventOk; - for (int index = 0; started && index < static_cast(requestBuffers.size()); ++index) { - call->Write(requestBuffers.at(index), reinterpret_cast(2)); - started = queue.Next(&tag, &eventOk) && eventOk; - } - if (started) { - call->WritesDone(reinterpret_cast(3)); - queue.Next(&tag, &eventOk); - } - while (started && streamResponses.size() < 100) { - grpc::ByteBuffer responseBuffer; - call->Read(&responseBuffer, reinterpret_cast(4)); - if (!queue.Next(&tag, &eventOk) || !eventOk) - break; - const QString response = byteBufferToJson(responseBuffer, responsePrototype, factory); - QJsonParseError responseError; - const QJsonDocument parsed = QJsonDocument::fromJson(response.toUtf8(), &responseError); - streamResponses.append(responseError.error == QJsonParseError::NoError - ? QJsonValue(parsed.object()) : QJsonValue(response)); - } - if (streamResponses.size() >= 100) - context.TryCancel(); - call->Finish(&grpcStatus, reinterpret_cast(5)); - queue.Next(&tag, &eventOk); - transportOk = grpcStatus.ok() || - (grpcStatus.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED && - !streamResponses.isEmpty()); - queue.Shutdown(); - } - - QString result; - if (transportOk) { - result = method->client_streaming() || method->server_streaming() - ? QString::fromUtf8(QJsonDocument(streamResponses).toJson(QJsonDocument::Indented)) - : unaryResponse; - } else { - QJsonObject error; - error.insert(QStringLiteral("grpcCode"), grpcStatus.error_code()); - error.insert(QStringLiteral("error"), QString::fromStdString(grpcStatus.error_message())); - result = QString::fromUtf8(QJsonDocument(error).toJson(QJsonDocument::Indented)); - } - emit rpcFinished(serviceName, methodName, transportOk, result); - emit commandFinished(command, transportOk, - transportOk ? QStringLiteral("RPC 调用完成") - : QString::fromStdString(grpcStatus.error_message())); -#else - Q_UNUSED(requestJson) - Q_UNUSED(deviceId) -#endif - } - - std::function connectionChanged; - std::function armInfoReceived; - std::function - armFramesReceived; - std::function telemetryReceived; - std::function - armTelemetryHealthChanged; - std::function systemStatusReceived; - std::function systemInfoReceived; - std::function imageReceived; - std::function - videoFrameReceivedForCamera; - std::function - cameraStreamStateChangedForCamera; - std::function cameraRecordingStateChanged; - std::function agvStateReceived; - std::function agvInventoryReceived; - std::function - agvMapFrameReceived; - std::function agvMapStreamStateChanged; - std::function rpcFinished; - std::function audioStreamStateChanged; - std::function audioStreamStatistics; - std::function - audioFrameReceived; - std::function configurationConnectionChanged; - std::function - configurationFilesReceived; - std::function configurationFileReceived; - std::function - configurationValidationFinished; - std::function - configurationSaveFinished; - std::function commandFinished; - std::function logMessage; - -private: -#ifdef CMVR_WITH_GRPC - bool ensureConfigurationConnected(const QString &operation) - { - if (m_configConnected && m_configuration) - return true; - emit configurationConnectionChanged( - false, QStringLiteral("%1失败:配置服务未连接").arg(operation)); - return false; - } - - static QString configurationError(const grpc::Status &status, - const std::string &applicationError) - { - if (!status.ok()) - return QString::fromStdString(status.error_message()); - return QString::fromStdString(applicationError); - } - - std::shared_ptr prepareArmMotionSession(const QString &command) - { - std::shared_ptr previous; - { - std::lock_guard lock(m_armMotionSessionMutex); - previous = m_armMotionSession; - if (previous && previous->running.load()) { - emit commandFinished(command, false, - QStringLiteral("已有机械臂运动命令正在执行")); - return {}; - } - m_armMotionSession.reset(); - } - if (previous && previous->thread.joinable() && - previous->thread.get_id() != std::this_thread::get_id()) { - previous->thread.join(); - } - - auto session = std::make_shared(); - session->running.store(true); - { - std::lock_guard lock(m_armMotionSessionMutex); - m_armMotionSession = session; - } - return session; - } - - template - void startArmMotion(const QString &command, Request request, Call call) - { - const auto session = prepareArmMotionSession(command); - if (!session) - return; - const auto channel = m_channel; - session->thread = std::thread( - [this, channel, session, command, request = std::move(request), call]() mutable { - grpc::ClientContext context; - setDeadline(context, kArmMotionTimeoutMs); - { - std::lock_guard lock(session->contextMutex); - session->context = &context; - if (session->stop.load()) - context.TryCancel(); - } - try { - auto stub = cmvr::api::ArmService::NewStub(channel); - Response response; - const grpc::Status status = call(*stub, &context, request, &response); - finish(command, status, response.header().success(), - QString::fromStdString(response.header().error_message())); - } catch (const std::exception &error) { - emit commandFinished(command, false, - QStringLiteral("机械臂运动调用异常:%1") - .arg(QString::fromLocal8Bit(error.what()))); - } catch (...) { - emit commandFinished(command, false, - QStringLiteral("机械臂运动调用发生未知异常")); - } - { - std::lock_guard lock(session->contextMutex); - session->context = nullptr; - } - session->running.store(false); - }); - } - - static void setDynamicDeviceId(google::protobuf::Message *request, - const QString &deviceId) - { - if (!request || deviceId.trimmed().isEmpty()) - return; - const google::protobuf::FieldDescriptor *headerField = - request->GetDescriptor()->FindFieldByName("header"); - if (!headerField || headerField->cpp_type() != - google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) - return; - google::protobuf::Message *header = - request->GetReflection()->MutableMessage(request, headerField); - const google::protobuf::FieldDescriptor *deviceField = - header->GetDescriptor()->FindFieldByName("device_id"); - if (deviceField) - header->GetReflection()->SetString(header, deviceField, deviceId.toStdString()); - } - - static QString byteBufferToJson(const grpc::ByteBuffer &buffer, - const google::protobuf::Message *prototype, - google::protobuf::DynamicMessageFactory &factory) - { - Q_UNUSED(factory) - std::vector slices; - buffer.Dump(&slices); - std::string serialized; - for (const grpc::Slice &slice : slices) - serialized.append(reinterpret_cast(slice.begin()), slice.size()); - std::unique_ptr response(prototype->New()); - if (!response->ParseFromString(serialized)) - return QStringLiteral("{\"error\":\"无法解析 protobuf 反馈\"}"); - std::string json; - google::protobuf::util::JsonPrintOptions options; - options.add_whitespace = true; - options.always_print_primitive_fields = true; - const auto status = google::protobuf::util::MessageToJsonString(*response, &json, options); - return status.ok() ? QString::fromStdString(json) - : QStringLiteral("{\"error\":\"%1\"}") - .arg(QString::fromStdString(status.ToString())); - } -#endif - - void stopArmMotionInternal() - { - std::shared_ptr session; - { - std::lock_guard lock(m_armMotionSessionMutex); - session = m_armMotionSession; - } - if (!session) - return; - - session->stop.store(true); -#ifdef CMVR_WITH_GRPC - { - std::lock_guard lock(session->contextMutex); - if (session->context) - session->context->TryCancel(); - } -#endif - if (session->thread.joinable() && - session->thread.get_id() != std::this_thread::get_id()) { - session->thread.join(); - } - session->running.store(false); - { - std::lock_guard lock(m_armMotionSessionMutex); - if (m_armMotionSession == session) - m_armMotionSession.reset(); - } - } - - void stopAgvMapStreamInternal() - { - m_agvMapStreamStop.store(true); -#ifdef CMVR_WITH_GRPC - { - std::lock_guard lock(m_agvMapStreamContextMutex); - if (m_agvMapStreamContext) - m_agvMapStreamContext->TryCancel(); - } -#endif - if (m_agvMapStreamThread.joinable() && - m_agvMapStreamThread.get_id() != std::this_thread::get_id()) - m_agvMapStreamThread.join(); - m_agvMapStreamRunning.store(false); - } - - void stopCameraStreamInternal(const QString &cameraId = QString()) - { - QVector> sessions; - { - std::lock_guard lock(m_cameraSessionsMutex); - if (cameraId.isEmpty()) { - sessions.reserve(m_cameraSessions.size()); - for (auto it = m_cameraSessions.cbegin(); - it != m_cameraSessions.cend(); ++it) { - sessions.append(it.value()); - } - } else { - const auto it = m_cameraSessions.find(cameraId); - if (it != m_cameraSessions.end()) - sessions.append(it.value()); - } - } - - for (const auto &session : sessions) { - session->stop.store(true); -#ifdef CMVR_WITH_GRPC - std::lock_guard lock(session->contextMutex); - if (session->context) - session->context->TryCancel(); -#endif - } - for (const auto &session : sessions) { - if (session->thread.joinable() && - session->thread.get_id() != std::this_thread::get_id()) { - session->thread.join(); - } - session->running.store(false); - } - { - std::lock_guard lock(m_cameraSessionsMutex); - for (const auto &session : sessions) { - const auto it = m_cameraSessions.find(session->cameraId); - if (it != m_cameraSessions.end() && it.value() == session) - m_cameraSessions.erase(it); - } - } - } - - void stopSpeakerStreamInternal(bool cancel = false) - { - const bool wasRunning = m_speakerStreamRunning.load(); - m_speakerStreamStop.store(true); - m_speakerQueueCondition.notify_all(); -#ifdef CMVR_WITH_GRPC - { - std::lock_guard lock(m_speakerContextMutex); - if (cancel && m_speakerStreamContext) - m_speakerStreamContext->TryCancel(); - } -#endif - const bool hadThread = m_speakerStreamThread.joinable(); - if (hadThread && m_speakerStreamThread.get_id() != std::this_thread::get_id()) - m_speakerStreamThread.join(); - m_speakerStreamRunning.store(false); - { - std::lock_guard lock(m_speakerQueueMutex); - m_speakerQueue.clear(); - m_speakerQueueBytes = 0; - } - if (wasRunning && !hadThread) - emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false, - QStringLiteral("扬声器音频流已停止")); - } - - void stopMicrophoneStreamInternal() - { - const bool wasRunning = m_microphoneStreamRunning.load(); - m_microphoneStreamStop.store(true); -#ifdef CMVR_WITH_GRPC - { - std::lock_guard lock(m_microphoneContextMutex); - if (m_microphoneStreamContext) - m_microphoneStreamContext->TryCancel(); - } -#endif - const bool hadThread = m_microphoneStreamThread.joinable(); - if (hadThread && m_microphoneStreamThread.get_id() != std::this_thread::get_id()) - m_microphoneStreamThread.join(); - m_microphoneStreamRunning.store(false); - if (wasRunning && !hadThread) - emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, - QStringLiteral("麦克风音频拉流已停止")); - } - - void poll() - { - if (!m_connected) - return; - if (m_demoMode) { - pollDemo(); - return; - } -#ifdef CMVR_WITH_GRPC - pollGrpc(); -#endif - } - -private: - bool ensureConnected(const QString &command) - { - if (m_connected) - return true; - emit commandFinished(command, false, QStringLiteral("设备尚未连接")); - return false; - } - - bool ensureDeviceId(const QString &command, const QString &deviceId) - { - if (!deviceId.trimmed().isEmpty()) - return true; - emit commandFinished(command, false, QStringLiteral("请在对应服务页填写设备 ID")); - return false; - } - - void pollDemo() - { - ++m_tick; - if (m_armPollingEnabled) { - QVariantList joints; - const QStringList jointNames = armJointNamesForDevice(m_armDeviceId); - for (int i = 0; i < jointNames.size(); ++i) { - const double phase = m_tick * 0.035 + i * 0.46; - double position = 0.36 * qSin(phase); - if (i < m_demoTargets.size()) - position = m_demoTargets.at(i) + 0.025 * qSin(phase * 1.7); - QVariantMap joint; - joint.insert(QStringLiteral("name"), jointNames.at(i)); - joint.insert(QStringLiteral("position"), position); - joint.insert(QStringLiteral("velocity"), 0.22 * qCos(phase)); - joint.insert(QStringLiteral("effort"), 0.4 + 0.3 * qAbs(qSin(phase * 0.7))); - joints.append(joint); - } - QVariantMap pose; - pose.insert(QStringLiteral("x"), 0.421 + 0.004 * qSin(m_tick * 0.02)); - pose.insert(QStringLiteral("y"), -0.182 + 0.003 * qCos(m_tick * 0.025)); - pose.insert(QStringLiteral("z"), 0.736 + 0.002 * qSin(m_tick * 0.017)); - pose.insert(QStringLiteral("rx"), 1.571); - pose.insert(QStringLiteral("ry"), 0.014); - pose.insert(QStringLiteral("rz"), -0.021); - QVariantMap state; - state.insert(QStringLiteral("connected"), true); - state.insert(QStringLiteral("poweredOn"), true); - state.insert(QStringLiteral("fault"), false); - state.insert(QStringLiteral("moving"), !m_demoTargets.isEmpty()); - emit telemetryReceived(m_armDeviceId, joints, pose, state); - } - if (m_tick % 10 == 0) { - emit systemStatusReceived(31.0 + 8.0 * qSin(m_tick * 0.04), - 47.0 + 3.0 * qCos(m_tick * 0.025), 62.0, - demoDeviceList()); - } - } - -#ifdef CMVR_WITH_GRPC - static void fillHeader(cmvr::api::CommandHeader::Request *header, - const QString &deviceId, int validForMs = 5000) - { - header->set_device_id(deviceId.toStdString()); - const qint64 now = QDateTime::currentMSecsSinceEpoch(); - header->mutable_timestamp()->set_seconds(now / 1000); - header->mutable_timestamp()->set_nanos(static_cast((now % 1000) * 1000000)); - header->set_command_id( - QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString()); - header->set_valid_for_ms(static_cast(qMax(1, validForMs))); - } - - static void setDeadline(grpc::ClientContext &context, int milliseconds) - { - context.set_deadline(std::chrono::system_clock::now() + std::chrono::milliseconds(milliseconds)); - } - - void runSpeakerAudioStream(const std::shared_ptr &channel, - const QString &deviceId) - { - std::unique_ptr speaker = - cmvr::api::SpeakerService::NewStub(channel); - grpc::ClientContext context; - { - std::lock_guard lock(m_speakerContextMutex); - m_speakerStreamContext = &context; - } - if (m_speakerStreamStop.load()) - context.TryCancel(); - - cmvr::api::StreamSpeakerAudioCommand::Feedback feedback; - std::unique_ptr> writer = - speaker->StreamAudio(&context, &feedback); - bool writeOk = static_cast(writer); - while (writeOk) { - SpeakerAudioFrame frame; - { - std::unique_lock lock(m_speakerQueueMutex); - m_speakerQueueCondition.wait(lock, [this]() { - return m_speakerStreamStop.load() || !m_speakerQueue.empty(); - }); - if (m_speakerQueue.empty()) { - if (m_speakerStreamStop.load()) - break; - continue; - } - frame = std::move(m_speakerQueue.front()); - m_speakerQueue.pop_front(); - m_speakerQueueBytes -= frame.data.size(); - } - - cmvr::api::StreamSpeakerAudioCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - cmvr::api::AudioData *audio = request.mutable_audio(); - audio->set_data(frame.data.constData(), frame.data.size()); - audio->set_sample_rate(frame.sampleRate); - audio->set_channels(frame.channels); - audio->set_format(cmvr::api::AudioData::PCM); - audio->set_codec("pcm_s16le"); - audio->set_pts(frame.pts); - audio->set_nb_samples(frame.samples); - writeOk = writer->Write(request); - if (writeOk) { - const quint64 frames = ++m_speakerFrames; - const quint64 bytes = m_speakerBytes.fetch_add(frame.data.size()) + frame.data.size(); - emit audioStreamStatistics(QStringLiteral("SpeakerService"), frames, bytes, - frame.pts / 1000 + frame.samples * 1000LL / frame.sampleRate); - } - } - - if (writer) - writer->WritesDone(); - const grpc::Status status = writer ? writer->Finish() - : grpc::Status(grpc::StatusCode::UNKNOWN, - "failed to create client writer"); - { - std::lock_guard lock(m_speakerContextMutex); - m_speakerStreamContext = nullptr; - } - const bool stopped = m_speakerStreamStop.load(); - const bool success = !stopped && status.ok() && feedback.header().success(); - QString detail; - if (stopped) - detail = QStringLiteral("扬声器音频流已停止"); - else if (!status.ok()) - detail = QStringLiteral("扬声器音频流失败:%1") - .arg(QString::fromStdString(status.error_message())); - else if (!feedback.header().success()) - detail = QStringLiteral("扬声器拒绝音频流:%1") - .arg(QString::fromStdString(feedback.header().error_message())); - else - detail = QStringLiteral("扬声器音频流发送完成"); - m_speakerStreamRunning.store(false); - emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false, detail); - if (!stopped) - emit commandFinished(QStringLiteral("Speaker Stream"), success, detail); - } - - void runMicrophoneAudioStream(const std::shared_ptr &channel, - const QString &deviceId) - { - std::unique_ptr microphone = - cmvr::api::MicPhoneService::NewStub(channel); - cmvr::api::StreamMicAudioCommand::Request request; - fillHeader(request.mutable_header(), deviceId); - grpc::ClientContext context; - { - std::lock_guard lock(m_microphoneContextMutex); - m_microphoneStreamContext = &context; - } - if (m_microphoneStreamStop.load()) - context.TryCancel(); - - std::unique_ptr> reader = - microphone->StreamAudio(&context, request); - cmvr::api::StreamMicAudioCommand::Feedback feedback; - while (reader && !m_microphoneStreamStop.load() && reader->Read(&feedback)) { - if (!feedback.header().success()) { - emit logMessage(QStringLiteral("WARN"), - QStringLiteral("麦克风音频帧反馈失败:%1") - .arg(QString::fromStdString(feedback.header().error_message()))); - continue; - } - const cmvr::api::AudioData &audio = feedback.audio(); - const QByteArray data(audio.data().data(), static_cast(audio.data().size())); - const quint64 frames = ++m_microphoneFrames; - const quint64 bytes = m_microphoneBytes.fetch_add(data.size()) + data.size(); - emit audioFrameReceived(data, audio.sample_rate(), audio.channels(), - static_cast(audio.format()), - QString::fromStdString(audio.codec()), audio.pts(), - audio.nb_samples()); - const qint64 durationMs = audio.sample_rate() > 0 - ? audio.pts() / 1000 + audio.nb_samples() * 1000LL / audio.sample_rate() - : 0; - emit audioStreamStatistics(QStringLiteral("MicPhoneService"), frames, bytes, - durationMs); - } - const grpc::Status status = reader ? reader->Finish() - : grpc::Status(grpc::StatusCode::UNKNOWN, - "failed to create client reader"); - { - std::lock_guard lock(m_microphoneContextMutex); - m_microphoneStreamContext = nullptr; - } - const bool stopped = m_microphoneStreamStop.load(); - QString detail; - if (stopped) - detail = QStringLiteral("麦克风音频拉流已停止"); - else if (!status.ok()) - detail = QStringLiteral("麦克风音频拉流失败:%1") - .arg(QString::fromStdString(status.error_message())); - else - detail = QStringLiteral("麦克风音频拉流已结束"); - m_microphoneStreamRunning.store(false); - emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, detail); - if (!stopped) - emit commandFinished(QStringLiteral("MicPhone Stream"), status.ok(), detail); - } - - void runDepthCameraStream(const std::shared_ptr &channel, - const std::shared_ptr &session, - bool rgbd) - { - const QString cameraId = session->cameraId; - auto camera = cmvr::api::CameraService::NewStub(channel); - cmvr::api::StartCameraCommand::Request startRequest; - fillHeader(startRequest.mutable_header(), cameraId); - cmvr::api::StartCameraCommand::Feedback startResponse; - grpc::ClientContext startContext; - setDeadline(startContext, 3000); - const grpc::Status startStatus = camera->StartCamera(&startContext, startRequest, &startResponse); - if (!startStatus.ok() || !startResponse.header().success()) { - const QString error = !startStatus.ok() - ? QString::fromStdString(startStatus.error_message()) - : QString::fromStdString(startResponse.header().error_message()); - session->running.store(false); - emit cameraStreamStateChangedForCamera(cameraId, false, - QStringLiteral("鍚姩鐩告満澶辫触锛?1").arg(error)); - emit commandFinished(QStringLiteral("Camera Stream"), false, error); - return; - } - - grpc::ClientContext context; - { - std::lock_guard lock(session->contextMutex); - session->context = &context; - } - if (session->stop.load()) - context.TryCancel(); - - QString terminalError; - if (rgbd) { - auto stream = camera->GetRGBDImagesStream(&context); - cmvr::api::GetRGBDImagesStreamCommand::Request request; - fillHeader(request.mutable_header(), cameraId); - request.set_eof(false); - if (!stream || !stream->Write(request)) { - terminalError = QStringLiteral("鍙戦€佽棰戞祦璁㈤槄璇锋眰澶辫触"); - } else { - cmvr::api::GetRGBDImagesStreamCommand::Feedback response; - while (!session->stop.load() && stream->Read(&response)) { - if (!response.header().success()) { - terminalError = QString::fromStdString(response.header().error_message()); - break; - } - const auto &depth = response.depth_frame(); - VideoFrame frame = videoFrameFromDepth(depth); - if (!frame.isValid()) - continue; - if (videoFrameReceivedForCamera) - videoFrameReceivedForCamera(cameraId, frame, - QStringLiteral("%1 x %2 | DEPTH | #%3") - .arg(depth.width()).arg(depth.height()).arg(response.seq_no())); - } - stream->WritesDone(); - stream->Finish(); - } - } else { - auto stream = camera->GetDepthImageStream(&context); - cmvr::api::GetDepthImageStreamCommand::Request request; - fillHeader(request.mutable_header(), cameraId); - request.set_eof(false); - if (!stream || !stream->Write(request)) { - terminalError = QStringLiteral("鍙戦€佽棰戞祦璁㈤槄璇锋眰澶辫触"); - } else { - cmvr::api::GetDepthImageStreamCommand::Feedback response; - while (!session->stop.load() && stream->Read(&response)) { - if (!response.header().success()) { - terminalError = QString::fromStdString(response.header().error_message()); - break; - } - const auto &depth = response.depth_frame(); - VideoFrame frame = videoFrameFromDepth(depth); - if (!frame.isValid()) - continue; - if (videoFrameReceivedForCamera) - videoFrameReceivedForCamera(cameraId, frame, - QStringLiteral("%1 x %2 | DEPTH | #%3") - .arg(depth.width()).arg(depth.height()).arg(response.seq_no())); - } - stream->WritesDone(); - stream->Finish(); - } - } - if (session->stop.load()) - terminalError = QStringLiteral("瑙嗛棰勮宸插仠姝?"); - { - std::lock_guard lock(session->contextMutex); - if (session->context == &context) - session->context = nullptr; - } - session->running.store(false); - emit cameraStreamStateChangedForCamera( - cameraId, false, - terminalError.isEmpty() ? QStringLiteral("Depth stream ended") : terminalError); - } - - void runCameraStream(const std::shared_ptr &channel, - const std::shared_ptr &session) - { - const QString cameraId = session->cameraId; - std::unique_ptr camera = - cmvr::api::CameraService::NewStub(channel); - - cmvr::api::StartCameraCommand::Request startRequest; - fillHeader(startRequest.mutable_header(), cameraId); - cmvr::api::StartCameraCommand::Feedback startResponse; - grpc::ClientContext startContext; - setDeadline(startContext, 3000); - const grpc::Status startStatus = camera->StartCamera(&startContext, startRequest, &startResponse); - if (!startStatus.ok() || !startResponse.header().success()) { - const QString error = !startStatus.ok() - ? QString::fromStdString(startStatus.error_message()) - : QString::fromStdString(startResponse.header().error_message()); - session->running.store(false); - emit cameraStreamStateChangedForCamera( - cameraId, false, QStringLiteral("启动相机失败:%1").arg(error)); - emit commandFinished(QStringLiteral("Camera Stream"), false, error); - return; - } - if (session->stop.load()) { - session->running.store(false); - emit cameraStreamStateChangedForCamera( - cameraId, false, QStringLiteral("视频预览已停止")); - return; - } - - grpc::ClientContext context; - { - std::lock_guard lock(session->contextMutex); - session->context = &context; - } - if (session->stop.load()) - context.TryCancel(); - std::unique_ptr> stream = - camera->GetRGBImageStream(&context); - - cmvr::api::GetRGBImageStreamCommand::Request request; - fillHeader(request.mutable_header(), cameraId); - request.set_eof(false); - if (!stream || !stream->Write(request)) { - context.TryCancel(); - if (stream) - stream->Finish(); - { - std::lock_guard lock(session->contextMutex); - session->context = nullptr; - } - session->running.store(false); - emit cameraStreamStateChangedForCamera( - cameraId, false, QStringLiteral("发送视频流订阅请求失败")); - return; - } - if (session->stop.load()) - context.TryCancel(); - - emit logMessage(QStringLiteral("INFO"), - QStringLiteral("CameraService.GetRGBImageStream 已启动:%1,解码格式=%2") - .arg(cameraId, session->codec == QStringLiteral("h265") - ? QStringLiteral("H.265") - : QStringLiteral("H.264"))); - struct CompressedVideoFrame { - QByteArray data; - QString codec; - qint64 pts = 0; - qint64 dts = 0; - int width = 0; - int height = 0; - int seqNo = 0; - quint32 sourceFps = 0; - quint64 generation = 0; - bool keyFrame = false; - }; - // Frame-threaded HEVC needs several packets before its first output. - // Keep enough startup headroom so the low-latency recovery logic does - // not repeatedly reset a decoder that is still warming up. - constexpr std::size_t kMaxCompressedFrames = 45; - std::deque compressedFrames; - std::mutex compressedFramesMutex; - std::condition_variable compressedFramesReady; - bool readerFinished = false; - quint64 queueGeneration = 0; - std::atomic decodedFrames{0}; - std::atomic displayedFrames{0}; - std::atomic receivedFrames{0}; - std::atomic receivedBytes{0}; - std::atomic droppedFrames{0}; - std::atomic sourceSequence{0}; - std::atomic sourceSequenceGaps{0}; - std::atomic compressedQueueDepth{0}; - QElapsedTimer totalTimer; - totalTimer.start(); - QString terminalError; - - std::thread decoderThread([&] { - VideoDecoder decoder; - QElapsedTimer rateTimer; - rateTimer.start(); - quint64 rateFrames = 0; - quint64 previousReceivedFrames = 0; - quint64 previousDecodedFrames = 0; - quint64 previousRateBytes = 0; - quint64 previousSourceSequence = 0; - qint64 decodeNanoseconds = 0; - quint64 timedDecodePackets = 0; - double receiveFps = 0.0; - double sourceSequenceFps = 0.0; - double displayFps = 0.0; - double decodeFps = 0.0; - double decodeMilliseconds = 0.0; - double bitrateKbps = 0.0; - int decodeErrors = 0; - QString activeCodec; - quint64 activeGeneration = std::numeric_limits::max(); - while (!session->stop.load()) { - CompressedVideoFrame packet; - { - std::unique_lock lock(compressedFramesMutex); - compressedFramesReady.wait(lock, [&] { - return session->stop.load() || readerFinished || - !compressedFrames.empty(); - }); - if ((session->stop.load() || readerFinished) && - compressedFrames.empty()) - break; - packet = std::move(compressedFrames.front()); - compressedFrames.pop_front(); - compressedQueueDepth.store(compressedFrames.size()); - } - - const QString codec = packet.codec.isEmpty() - ? session->codec : packet.codec; - if (codec != activeCodec || - packet.generation != activeGeneration) { - decoder.reset(); - activeCodec = codec; - activeGeneration = packet.generation; - decodeErrors = 0; - emit logMessage(QStringLiteral("INFO"), - QStringLiteral("视频解码器已切换为 %1,等待参数集和关键帧") - .arg(codec.toUpper())); - } - - QVector frames; - int decodedCount = 0; - QElapsedTimer decodeTimer; - decodeTimer.start(); - if (!decoder.decode(packet.data, codec, packet.pts, packet.dts, - &frames, true, &decodedCount)) { - ++decodeErrors; - if (decodeErrors == 1 || decodeErrors % 60 == 0) { - emit logMessage(QStringLiteral("WARN"), - QStringLiteral("视频解码失败(%1 次):%2") - .arg(decodeErrors).arg(decoder.lastError())); - } - continue; - } - decodeNanoseconds += decodeTimer.nsecsElapsed(); - ++timedDecodePackets; - decodedFrames.fetch_add(static_cast(decodedCount)); - - if (!frames.isEmpty()) { - if (displayedFrames.load() == 0) { - emit logMessage(QStringLiteral("INFO"), - QStringLiteral("视频预览解码后端:%1") - .arg(decoder.backendName())); - } - } - - for (const VideoFrame &frame : frames) { - displayedFrames.fetch_add(1); - ++rateFrames; - if (rateTimer.elapsed() >= 1000) { - const double seconds = rateTimer.elapsed() / 1000.0; - const quint64 currentBytes = receivedBytes.load(); - const quint64 currentReceivedFrames = receivedFrames.load(); - const quint64 currentSourceSequence = sourceSequence.load(); - receiveFps = (currentReceivedFrames - previousReceivedFrames) / seconds; - sourceSequenceFps = previousSourceSequence > 0 && - currentSourceSequence >= previousSourceSequence - ? (currentSourceSequence - previousSourceSequence) / seconds : 0.0; - displayFps = rateFrames / seconds; - const quint64 currentDecodedFrames = decodedFrames.load(); - decodeFps = (currentDecodedFrames - previousDecodedFrames) / seconds; - bitrateKbps = (currentBytes - previousRateBytes) * 8.0 / - seconds / 1000.0; - decodeMilliseconds = timedDecodePackets > 0 - ? decodeNanoseconds / 1000000.0 / timedDecodePackets : 0.0; - rateFrames = 0; - previousReceivedFrames = currentReceivedFrames; - previousSourceSequence = currentSourceSequence; - previousDecodedFrames = currentDecodedFrames; - previousRateBytes = currentBytes; - decodeNanoseconds = 0; - timedDecodePackets = 0; - rateTimer.restart(); - } - const QString sourceRate = packet.sourceFps > 0 - ? QStringLiteral("/%1").arg(packet.sourceFps) : QString(); - const QString dropDetail = droppedFrames.load() > 0 - ? QStringLiteral(" | 低延迟丢帧 %1").arg(droppedFrames.load()) - : QString(); - const QString detail = QStringLiteral("%1 x %2 | %3 | FPS 源/收/解/显 %4/%5/%6/%7%8 | %9 %10 ms | Q%11 缺%12 | %13 kbps | #%14%15") - .arg(packet.width).arg(packet.height).arg(codec.toUpper()) - .arg(sourceSequenceFps, 0, 'f', 1).arg(receiveFps, 0, 'f', 1) - .arg(decodeFps, 0, 'f', 1).arg(displayFps, 0, 'f', 1) - .arg(sourceRate).arg(decoder.backendName()) - .arg(decodeMilliseconds, 0, 'f', 1).arg(compressedQueueDepth.load()) - .arg(sourceSequenceGaps.load()).arg(bitrateKbps, 0, 'f', 0) - .arg(packet.seqNo).arg(dropDetail); - if (videoFrameReceivedForCamera) - videoFrameReceivedForCamera(cameraId, frame, detail); - } - } - }); - - cmvr::api::GetRGBImageStreamCommand::Feedback response; - while (!session->stop.load() && stream->Read(&response)) { - if (!response.header().success()) { - terminalError = QString::fromStdString(response.header().error_message()); - break; - } - const auto &frame = response.color_frame(); - if (frame.data().empty()) - continue; - - receivedBytes.fetch_add(static_cast(frame.data().size())); - receivedFrames.fetch_add(1); - const quint64 currentSourceSequence = frame.source_sequence(); - const quint64 previousSequence = sourceSequence.exchange(currentSourceSequence); - if (previousSequence > 0 && currentSourceSequence > previousSequence + 1) - sourceSequenceGaps.fetch_add(currentSourceSequence - previousSequence - 1); - CompressedVideoFrame packet; - packet.data = QByteArray(frame.data().data(), static_cast(frame.data().size())); - packet.codec = QString::fromStdString(frame.codec()).trimmed().toLower(); - packet.pts = frame.pts(); - packet.dts = frame.dts(); - packet.width = frame.width(); - packet.height = frame.height(); - packet.seqNo = response.seq_no(); - packet.sourceFps = frame.source_fps(); - packet.keyFrame = frame.is_key_frame(); - { - std::lock_guard lock(compressedFramesMutex); - // Resynchronize only at a keyframe already in hand. Clearing a - // full queue at an arbitrary P-frame makes the decoder wait for - // a future keyframe and can cause a reset loop during startup. - if (compressedFrames.size() >= kMaxCompressedFrames) { - if (packet.keyFrame) { - droppedFrames.fetch_add( - static_cast(compressedFrames.size())); - compressedFrames.clear(); - compressedQueueDepth.store(0); - ++queueGeneration; - } else { - droppedFrames.fetch_add(1); - continue; - } - } - packet.generation = queueGeneration; - compressedFrames.push_back(std::move(packet)); - compressedQueueDepth.store(compressedFrames.size()); - } - compressedFramesReady.notify_one(); - } - - { - std::lock_guard lock(compressedFramesMutex); - readerFinished = true; - } - compressedFramesReady.notify_all(); - - stream->WritesDone(); - const grpc::Status status = stream->Finish(); - if (decoderThread.joinable()) - decoderThread.join(); - { - std::lock_guard lock(session->contextMutex); - if (session->context == &context) - session->context = nullptr; - } - - const bool stoppedByUser = session->stop.load(); - if (terminalError.isEmpty() && !status.ok() && !stoppedByUser) - terminalError = QString::fromStdString(status.error_message()); - session->running.store(false); - const QString summary = terminalError.isEmpty() - ? QStringLiteral("视频预览已停止,解码 %1 帧,显示 %2 帧,%3 MB,%4 秒") - .arg(decodedFrames.load()).arg(displayedFrames.load()) - .arg(receivedBytes.load() / 1048576.0, 0, 'f', 1) - .arg(totalTimer.elapsed() / 1000.0, 0, 'f', 1) - : QStringLiteral("视频流失败:%1").arg(terminalError); - emit cameraStreamStateChangedForCamera(cameraId, false, summary); - emit logMessage(terminalError.isEmpty() ? QStringLiteral("INFO") : QStringLiteral("ERROR"), summary); - } - - void finish(const QString &command, const grpc::Status &status, bool responseSuccess, - const QString &responseError) - { - const bool success = status.ok() && responseSuccess; - QString detail; - if (!status.ok()) { - const QString message = QString::fromStdString(status.error_message()); - detail = QStringLiteral("gRPC code %1:%2") - .arg(static_cast(status.error_code())) - .arg(message.isEmpty() ? QStringLiteral("服务端未返回错误详情") - : message); - } - else if (!responseSuccess) - detail = responseError.isEmpty() ? QStringLiteral("设备拒绝了命令") : responseError; - else - detail = QStringLiteral("命令执行成功"); - emit commandFinished(command, success, detail); - } - - void pollGrpc() - { - ++m_tick; - const bool armPollDue = m_consecutivePollErrors < 3 || m_tick % 10 == 0; - if (m_armPollingEnabled && !m_armDeviceId.isEmpty() && armPollDue) { - const QString polledDeviceId = m_armDeviceId; - cmvr::api::GetRobotState::Request request; - fillHeader(request.mutable_header(), polledDeviceId); - cmvr::api::GetRobotState::Response response; - grpc::ClientContext context; - setDeadline(context, 350); - const grpc::Status status = m_arm->getRobotState(&context, request, &response); - if (status.ok() && response.header().success()) { - const bool recovered = m_consecutivePollErrors >= 3; - m_consecutivePollErrors = 0; - QVariantList joints; - const auto &robotState = response.state(); - const auto &jointState = robotState.actual_joint_state(); - for (int i = 0; i < jointState.name_size(); ++i) { - QVariantMap joint; - joint.insert(QStringLiteral("name"), QString::fromStdString(jointState.name(i))); - joint.insert(QStringLiteral("position"), i < jointState.position_size() ? jointState.position(i) : 0.0); - joint.insert(QStringLiteral("velocity"), i < jointState.velocity_size() ? jointState.velocity(i) : 0.0); - joint.insert(QStringLiteral("effort"), i < jointState.effort_size() ? jointState.effort(i) : 0.0); - joints.append(joint); - } - const auto &tcp = robotState.actual_tcp_pose(); - QVariantMap pose; - pose.insert(QStringLiteral("x"), tcp.x()); - pose.insert(QStringLiteral("y"), tcp.y()); - pose.insert(QStringLiteral("z"), tcp.z()); - pose.insert(QStringLiteral("rx"), tcp.rx()); - pose.insert(QStringLiteral("ry"), tcp.ry()); - pose.insert(QStringLiteral("rz"), tcp.rz()); - if (robotState.connected() - && !m_armBaseFrame.isEmpty() && !m_armTcpFrame.isEmpty()) { - cmvr::api::GetPose::Request poseRequest; - fillHeader(poseRequest.mutable_header(), polledDeviceId); - poseRequest.set_base_link(m_armBaseFrame.toStdString()); - poseRequest.set_ee_link(m_armTcpFrame.toStdString()); - cmvr::api::GetPose::Response poseResponse; - grpc::ClientContext poseContext; - setDeadline(poseContext, 250); - const grpc::Status poseStatus = - m_arm->getPose(&poseContext, poseRequest, &poseResponse); - if (poseStatus.ok() && poseResponse.header().success()) { - const auto &selectedPose = poseResponse.pose(); - pose.insert(QStringLiteral("x"), selectedPose.x()); - pose.insert(QStringLiteral("y"), selectedPose.y()); - pose.insert(QStringLiteral("z"), selectedPose.z()); - pose.insert(QStringLiteral("rx"), selectedPose.rx()); - pose.insert(QStringLiteral("ry"), selectedPose.ry()); - pose.insert(QStringLiteral("rz"), selectedPose.rz()); - } - } - QVariantMap state; - state.insert(QStringLiteral("robotMode"), static_cast(robotState.robot_mode())); - state.insert(QStringLiteral("safetyMode"), static_cast(robotState.safety_mode())); - state.insert(QStringLiteral("controlMode"), static_cast(robotState.control_mode())); - state.insert(QStringLiteral("freedrive"), - robotState.control_mode() - == cmvr::api::ARM_CONTROL_MODE_FREEDRIVE); - state.insert(QStringLiteral("connected"), robotState.connected()); - state.insert(QStringLiteral("poweredOn"), robotState.powered_on()); - state.insert(QStringLiteral("brakeReleased"), robotState.brake_released()); - state.insert(QStringLiteral("moving"), robotState.moving()); - state.insert(QStringLiteral("fault"), robotState.fault()); - state.insert(QStringLiteral("protectiveStopped"), robotState.protective_stopped()); - state.insert(QStringLiteral("emergencyStopped"), robotState.emergency_stopped()); - state.insert(QStringLiteral("speedScaling"), robotState.speed_scaling()); - emit telemetryReceived(polledDeviceId, joints, pose, state); - if (recovered) { - emit armTelemetryHealthChanged( - polledDeviceId, true, QStringLiteral("机械臂遥测通信已恢复")); - } - } else { - ++m_consecutivePollErrors; - QString detail; - if (!status.ok()) { - const QString message = QString::fromStdString(status.error_message()); - detail = QStringLiteral("gRPC code %1:%2") - .arg(static_cast(status.error_code())) - .arg(message.isEmpty() - ? QStringLiteral("服务端未返回错误详情") - : message); - } else { - detail = QString::fromStdString(response.header().error_message()); - if (detail.isEmpty()) - detail = QStringLiteral("边缘端未返回机械臂状态"); - } - if (m_consecutivePollErrors == 3) - emit armTelemetryHealthChanged(polledDeviceId, false, detail); - } - } - - if (m_tick % 10 != 0) - return; - cmvr::api::GetSystemStatusCommand::Request statusRequest; - cmvr::api::GetSystemStatusCommand::Feedback statusResponse; - grpc::ClientContext statusContext; - setDeadline(statusContext, 500); - const grpc::Status rpcStatus = m_system->GetSystemStatus(&statusContext, statusRequest, &statusResponse); - if (rpcStatus.ok() && statusResponse.header().success()) { - const double memory = statusResponse.mem_total_mb() > 0 - ? statusResponse.mem_used_mb() * 100.0 / statusResponse.mem_total_mb() : 0.0; - const double disk = statusResponse.disk_total_gb() > 0 - ? statusResponse.disk_used_gb() * 100.0 / statusResponse.disk_total_gb() : 0.0; - emit systemStatusReceived(statusResponse.cpu_usage(), memory, disk, - deviceListFromStatus(statusResponse)); - } - } - - std::shared_ptr m_channel; - std::shared_ptr m_configChannel; - std::unique_ptr m_arm; - std::unique_ptr m_camera; - std::unique_ptr m_system; - std::unique_ptr m_agv; - std::unique_ptr m_microphone; - std::unique_ptr m_generic; - std::unique_ptr m_configuration; - grpc::ClientContext *m_speakerStreamContext = nullptr; - std::mutex m_speakerContextMutex; - grpc::ClientContext *m_microphoneStreamContext = nullptr; - std::mutex m_microphoneContextMutex; - grpc::ClientContext *m_agvMapStreamContext = nullptr; - std::mutex m_agvMapStreamContextMutex; -#endif - - struct SpeakerAudioFrame { - QByteArray data; - int sampleRate = 0; - int channels = 0; - qint64 pts = 0; - int samples = 0; - }; - - QTimer *m_pollTimer = nullptr; - QString m_host; - QString m_armDeviceId; - QString m_armBaseFrame; - QString m_armTcpFrame; - int m_port = 50052; - int m_tick = 0; - int m_consecutivePollErrors = 0; - bool m_connected = false; - bool m_configConnected = false; - bool m_demoMode = true; - bool m_armPollingEnabled = false; - std::shared_ptr m_armMotionSession; - std::mutex m_armMotionSessionMutex; - QHash> m_cameraSessions; - std::mutex m_cameraSessionsMutex; - QString m_defaultCameraCodec = QStringLiteral("h264"); - bool m_cameraRecording = false; - std::atomic m_speakerStreamRunning{false}; - std::atomic m_speakerStreamStop{false}; - std::atomic m_speakerFrames{0}; - std::atomic m_speakerBytes{0}; - std::thread m_speakerStreamThread; - std::deque m_speakerQueue; - int m_speakerQueueBytes = 0; - std::mutex m_speakerQueueMutex; - std::condition_variable m_speakerQueueCondition; - std::atomic m_microphoneStreamRunning{false}; - std::atomic m_microphoneStreamStop{false}; - std::atomic m_microphoneFrames{0}; - std::atomic m_microphoneBytes{0}; - std::thread m_microphoneStreamThread; - std::atomic m_agvMapStreamRunning{false}; - std::atomic m_agvMapStreamStop{false}; - std::thread m_agvMapStreamThread; - QVector m_demoTargets; -}; - -RobotClient::RobotClient(QObject *parent) - : QObject(parent), m_worker(new BackendWorker) -{ - qRegisterMetaType("QImage"); - qRegisterMetaType("VideoFrame"); - - m_worker->connectionChanged = [this](bool connected, int latencyMs, const QString &detail) { - QMetaObject::invokeMethod(this, [this, connected, latencyMs, detail]() { - emit connectionChanged(connected, latencyMs, detail); - }, Qt::QueuedConnection); - }; - m_worker->armInfoReceived = [this](const QString &deviceId, const QVariantMap &info) { - QMetaObject::invokeMethod(this, [this, deviceId, info]() { - emit armInfoReceived(deviceId, info); - }, Qt::QueuedConnection); - }; - m_worker->armFramesReceived = - [this](const QString &deviceId, const QStringList &baseFrames, - const QStringList &tcpFrames) { - QMetaObject::invokeMethod(this, - [this, deviceId, baseFrames, tcpFrames]() { - emit armFramesReceived(deviceId, baseFrames, tcpFrames); - }, Qt::QueuedConnection); - }; - m_worker->telemetryReceived = [this](const QString &deviceId, - const QVariantList &joints, - const QVariantMap &pose, - const QVariantMap &state) { - QMetaObject::invokeMethod(this, [this, deviceId, joints, pose, state]() { - emit telemetryReceived(deviceId, joints, pose, state); - }, Qt::QueuedConnection); - }; - m_worker->armTelemetryHealthChanged = - [this](const QString &deviceId, bool available, const QString &detail) { - QMetaObject::invokeMethod(this, [this, deviceId, available, detail]() { - emit armTelemetryHealthChanged(deviceId, available, detail); - }, Qt::QueuedConnection); - }; - m_worker->systemStatusReceived = [this](double cpu, double memory, double disk, - const QVariantList &devices) { - QMetaObject::invokeMethod(this, [this, cpu, memory, disk, devices]() { - emit systemStatusReceived(cpu, memory, disk, devices); - }, Qt::QueuedConnection); - }; - m_worker->systemInfoReceived = [this](const QVariantMap &info) { - QMetaObject::invokeMethod(this, [this, info]() { - emit systemInfoReceived(info); - }, Qt::QueuedConnection); - }; - m_worker->imageReceived = [this](const QImage &image, const QString &detail) { - QMetaObject::invokeMethod(this, [this, image, detail]() { - emit imageReceived(image, detail); - }, Qt::QueuedConnection); - }; - const auto queueVideoFrame = [this](const QString &cameraId, - const VideoFrame &frame, - const QString &detail) { - { - QMutexLocker locker(&m_videoFrameMutex); - PendingVideoFrame &pending = m_pendingVideoFrames[cameraId]; - pending.frame = frame; - pending.detail = detail; - if (m_videoFrameDeliveryScheduled.contains(cameraId)) - return; - m_videoFrameDeliveryScheduled.insert(cameraId); - } - QMetaObject::invokeMethod(this, [this, cameraId]() { - PendingVideoFrame pending; - { - QMutexLocker locker(&m_videoFrameMutex); - pending = m_pendingVideoFrames.take(cameraId); - m_videoFrameDeliveryScheduled.remove(cameraId); - } - emit videoFrameReceived(cameraId, pending.frame, pending.detail); - }, Qt::QueuedConnection); - }; - m_worker->videoFrameReceivedForCamera = queueVideoFrame; - const auto queueCameraState = [this](const QString &cameraId, bool running, - const QString &detail) { - QMetaObject::invokeMethod(this, [this, cameraId, running, detail]() { - emit cameraStreamStateChanged(cameraId, running, detail); - }, Qt::QueuedConnection); - }; - m_worker->cameraStreamStateChangedForCamera = queueCameraState; - m_worker->cameraRecordingStateChanged = [this](bool recording, const QString &detail) { - QMetaObject::invokeMethod(this, [this, recording, detail]() { - emit cameraRecordingStateChanged(recording, detail); - }, Qt::QueuedConnection); - }; - m_worker->agvStateReceived = [this](const QVariantMap &state, const QVariantMap &navigation) { - QMetaObject::invokeMethod(this, [this, state, navigation]() { - emit agvStateReceived(state, navigation); - }, Qt::QueuedConnection); - }; - m_worker->agvInventoryReceived = [this](const QStringList &maps, const QVariantList &stations) { - QMetaObject::invokeMethod(this, [this, maps, stations]() { - emit agvInventoryReceived(maps, stations); - }, Qt::QueuedConnection); - }; - m_worker->agvMapFrameReceived = [this](const QImage &image, - const QVariantMap &metadata, - const QString &detail) { - QMetaObject::invokeMethod(this, [this, image, metadata, detail]() { - emit agvMapFrameReceived(image, metadata, detail); - }, Qt::QueuedConnection); - }; - m_worker->agvMapStreamStateChanged = [this](bool running, const QString &detail) { - QMetaObject::invokeMethod(this, [this, running, detail]() { - emit agvMapStreamStateChanged(running, detail); - }, Qt::QueuedConnection); - }; - m_worker->rpcFinished = [this](const QString &serviceName, const QString &methodName, - bool success, const QString &responseJson) { - QMetaObject::invokeMethod(this, [this, serviceName, methodName, success, responseJson]() { - emit rpcFinished(serviceName, methodName, success, responseJson); - }, Qt::QueuedConnection); - }; - m_worker->audioStreamStateChanged = [this](const QString &serviceName, bool running, - const QString &detail) { - QMetaObject::invokeMethod(this, [this, serviceName, running, detail]() { - emit audioStreamStateChanged(serviceName, running, detail); - }, Qt::QueuedConnection); - }; - m_worker->audioStreamStatistics = [this](const QString &serviceName, quint64 frames, - quint64 bytes, qint64 durationMs) { - QMetaObject::invokeMethod(this, [this, serviceName, frames, bytes, durationMs]() { - emit audioStreamStatistics(serviceName, frames, bytes, durationMs); - }, Qt::QueuedConnection); - }; - m_worker->audioFrameReceived = [this](const QByteArray &data, int sampleRate, int channels, - int format, const QString &codec, - qint64 pts, int samples) { - QMetaObject::invokeMethod(this, - [this, data, sampleRate, channels, format, codec, pts, samples]() { - emit audioFrameReceived(data, sampleRate, channels, format, codec, pts, samples); - }, Qt::QueuedConnection); - }; - m_worker->configurationConnectionChanged = [this](bool connected, const QString &detail) { - QMetaObject::invokeMethod(this, [this, connected, detail]() { - emit configurationConnectionChanged(connected, detail); - }, Qt::QueuedConnection); - }; - m_worker->configurationFilesReceived = - [this](const QString &root, const QVariantList &files, bool success, - const QString &detail) { - QMetaObject::invokeMethod(this, [this, root, files, success, detail]() { - emit configurationFilesReceived(root, files, success, detail); - }, Qt::QueuedConnection); - }; - m_worker->configurationFileReceived = - [this](const QString &path, const QString &content, const QString &revision, - const QString &messageType, bool success, const QString &detail) { - QMetaObject::invokeMethod( - this, [this, path, content, revision, messageType, success, detail]() { - emit configurationFileReceived(path, content, revision, messageType, - success, detail); - }, Qt::QueuedConnection); - }; - m_worker->configurationValidationFinished = - [this](const QString &path, bool success, const QString &detail) { - QMetaObject::invokeMethod(this, [this, path, success, detail]() { - emit configurationValidationFinished(path, success, detail); - }, Qt::QueuedConnection); - }; - m_worker->configurationSaveFinished = - [this](const QString &path, const QString &revision, bool success, - const QString &detail) { - QMetaObject::invokeMethod(this, [this, path, revision, success, detail]() { - emit configurationSaveFinished(path, revision, success, detail); - }, Qt::QueuedConnection); - }; - m_worker->commandFinished = [this](const QString &command, bool success, const QString &detail) { - QMetaObject::invokeMethod(this, [this, command, success, detail]() { - emit commandFinished(command, success, detail); - }, Qt::QueuedConnection); - }; - m_worker->logMessage = [this](const QString &level, const QString &message) { - QMetaObject::invokeMethod(this, [this, level, message]() { - emit logMessage(level, message); - }, Qt::QueuedConnection); - }; - - m_worker->moveToThread(&m_thread); - - connect(this, &RobotClient::connectRequested, m_worker, &BackendWorker::connectToServer); - connect(this, &RobotClient::disconnectRequested, m_worker, &BackendWorker::disconnectFromServer); - connect(this, &RobotClient::armTelemetryRequested, m_worker, &BackendWorker::setArmTelemetry); - connect(this, &RobotClient::armInfoRequested, m_worker, &BackendWorker::getArmInfo); - connect(this, &RobotClient::armFramesRequested, m_worker, &BackendWorker::getArmFrames); - connect(this, &RobotClient::armTelemetryFramesRequested, - m_worker, &BackendWorker::setArmTelemetryFrames); - connect(this, &RobotClient::speedJRequested, m_worker, &BackendWorker::speedJ); - connect(this, &RobotClient::speedLRequested, m_worker, &BackendWorker::speedL); - connect(this, &RobotClient::moveJRequested, m_worker, &BackendWorker::moveJ); - connect(this, &RobotClient::moveJPoseRequested, m_worker, &BackendWorker::moveJPose); - connect(this, &RobotClient::torqueRequested, m_worker, &BackendWorker::torque); - connect(this, &RobotClient::armStopRequested, m_worker, &BackendWorker::armStop); - connect(this, &RobotClient::armClearFaultRequested, m_worker, &BackendWorker::armClearFault); - connect(this, &RobotClient::armCalibrateZeroRequested, - m_worker, &BackendWorker::armCalibrateZero); - connect(this, &RobotClient::snapshotRequested, m_worker, &BackendWorker::snapshot); - connect(this, &RobotClient::cameraStreamStartRequested, m_worker, &BackendWorker::startCameraStream); - connect(this, &RobotClient::cameraStreamCodecRequested, - m_worker, &BackendWorker::setCameraStreamCodec); - connect(this, &RobotClient::cameraStreamStopRequested, m_worker, &BackendWorker::stopCameraStream); - connect(this, &RobotClient::cameraRecordingStartRequested, - m_worker, &BackendWorker::startCameraRecording); - connect(this, &RobotClient::cameraRecordingStopRequested, - m_worker, &BackendWorker::stopCameraRecording); - connect(this, &RobotClient::systemRefreshRequested, m_worker, &BackendWorker::systemRefresh); - connect(this, &RobotClient::systemStopAllRequested, m_worker, &BackendWorker::systemStopAll); - connect(this, &RobotClient::agvRefreshRequested, m_worker, &BackendWorker::agvRefresh); - connect(this, &RobotClient::agvRelocalizeRequested, - m_worker, &BackendWorker::agvRelocalize); - connect(this, &RobotClient::agvNavigatePoseRequested, m_worker, &BackendWorker::agvNavigatePose); - connect(this, &RobotClient::agvNavigateStationRequested, m_worker, &BackendWorker::agvNavigateStation); - connect(this, &RobotClient::agvFollowPathRequested, m_worker, &BackendWorker::agvFollowPath); - connect(this, &RobotClient::agvVelocityRequested, m_worker, &BackendWorker::agvVelocity); - connect(this, &RobotClient::agvActionRequested, m_worker, &BackendWorker::agvAction); - connect(this, &RobotClient::agvInventoryRequested, m_worker, &BackendWorker::agvInventory); - connect(this, &RobotClient::agvSwitchMapRequested, m_worker, &BackendWorker::agvSwitchMap); - connect(this, &RobotClient::agvMapStreamStartRequested, - m_worker, &BackendWorker::startAgvMapStream); - connect(this, &RobotClient::agvMapStreamStopRequested, - m_worker, &BackendWorker::stopAgvMapStream); - connect(this, &RobotClient::rpcRequested, m_worker, &BackendWorker::invokeRpc); - connect(this, &RobotClient::speakerAudioStreamStartRequested, - m_worker, &BackendWorker::startSpeakerAudioStream); - connect(this, &RobotClient::speakerAudioFrameRequested, - m_worker, &BackendWorker::enqueueSpeakerAudioFrame); - connect(this, &RobotClient::speakerAudioStreamStopRequested, - m_worker, &BackendWorker::stopSpeakerAudioStream); - connect(this, &RobotClient::microphoneAudioStreamStartRequested, - m_worker, &BackendWorker::startMicrophoneAudioStream); - connect(this, &RobotClient::microphoneAudioStreamStopRequested, - m_worker, &BackendWorker::stopMicrophoneAudioStream); - connect(this, &RobotClient::configurationConnectRequested, - m_worker, &BackendWorker::connectConfigurationServer); - connect(this, &RobotClient::configurationDisconnectRequested, - m_worker, &BackendWorker::disconnectConfigurationServer); - connect(this, &RobotClient::configurationFilesRequested, - m_worker, &BackendWorker::listConfigurationFiles); - connect(this, &RobotClient::configurationFileReadRequested, - m_worker, &BackendWorker::readConfigurationFile); - connect(this, &RobotClient::configurationFileValidateRequested, - m_worker, &BackendWorker::validateConfigurationFile); - connect(this, &RobotClient::configurationFileSaveRequested, - m_worker, &BackendWorker::saveConfigurationFile); - - connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater); - m_thread.start(); -} - -RobotClient::~RobotClient() -{ - if (m_thread.isRunning()) { - QMetaObject::invokeMethod(m_worker, [this]() { - m_worker->disconnectConfigurationServer(); - m_worker->disconnectFromServer(); - }, Qt::BlockingQueuedConnection); - } - m_thread.quit(); - m_thread.wait(2500); -} - -bool RobotClient::grpcAvailable() const -{ -#ifdef CMVR_WITH_GRPC - return true; -#else - return false; -#endif -} - -void RobotClient::connectToServer(const QString &host, int port, bool demoMode) -{ - emit connectRequested(host, port, demoMode); -} - -void RobotClient::disconnectFromServer() { emit disconnectRequested(); } -void RobotClient::setArmTelemetry(const QString &deviceId, bool enabled) -{ - emit armTelemetryRequested(deviceId, enabled); -} -void RobotClient::requestArmInfo(const QString &deviceId) -{ - emit armInfoRequested(deviceId); -} -void RobotClient::requestArmFrames(const QString &deviceId) -{ - emit armFramesRequested(deviceId); -} -void RobotClient::setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame, - const QString &tcpFrame) -{ - emit armTelemetryFramesRequested(deviceId, baseFrame, tcpFrame); -} -void RobotClient::requestSpeedJ(const QString &deviceId, const QVariantList &velocities, - double acceleration, double duration) -{ - emit speedJRequested(deviceId, velocities, acceleration, duration); -} -void RobotClient::requestSpeedL(const QString &deviceId, const QVariantMap &velocity, - double acceleration, double duration, bool toolFrame) -{ - emit speedLRequested(deviceId, velocity, acceleration, duration, toolFrame); -} -void RobotClient::requestMoveJ(const QString &deviceId, const QVariantList &positions, - double velocity, double acceleration) -{ - emit moveJRequested(deviceId, positions, velocity, acceleration); -} -void RobotClient::requestMoveJPose(const QString &deviceId, const QVariantMap &pose, - const QString &baseLink, const QString &eeLink, - double velocity, double acceleration) -{ - emit moveJPoseRequested(deviceId, pose, baseLink, eeLink, velocity, acceleration); -} -void RobotClient::requestTorque(const QString &deviceId, bool enabled) { emit torqueRequested(deviceId, enabled); } -void RobotClient::requestArmStop(const QString &deviceId) { emit armStopRequested(deviceId); } -void RobotClient::requestArmClearFault(const QString &deviceId) { emit armClearFaultRequested(deviceId); } -void RobotClient::requestArmCalibrateZero(const QString &deviceId, const QString &jointName) -{ - emit armCalibrateZeroRequested(deviceId, jointName); -} -void RobotClient::requestSnapshot(const QString &cameraId) { emit snapshotRequested(cameraId); } -void RobotClient::startCameraStream(const QString &cameraId, const QString &codec, - const QString &mode) -{ - emit cameraStreamStartRequested(cameraId, codec, mode); -} -void RobotClient::setCameraStreamCodec(const QString &codec) -{ - emit cameraStreamCodecRequested(codec); -} -void RobotClient::stopCameraStream(const QString &cameraId) -{ - emit cameraStreamStopRequested(cameraId); -} -void RobotClient::startCameraRecording(const QString &cameraId, const QString &videoPath) -{ - emit cameraRecordingStartRequested(cameraId, videoPath); -} -void RobotClient::stopCameraRecording(const QString &cameraId) -{ - emit cameraRecordingStopRequested(cameraId); -} -void RobotClient::requestSystemRefresh() { emit systemRefreshRequested(); } -void RobotClient::requestSystemStopAll(const QString &deviceId) { emit systemStopAllRequested(deviceId); } -void RobotClient::requestAgvRefresh(const QString &deviceId) { emit agvRefreshRequested(deviceId); } -void RobotClient::requestAgvRelocalize(const QString &deviceId, double x, double y, - double theta) -{ - emit agvRelocalizeRequested(deviceId, x, y, theta); -} -void RobotClient::requestAgvNavigatePose(const QString &deviceId, double x, double y, - double theta, double maxSpeed) -{ - emit agvNavigatePoseRequested(deviceId, x, y, theta, maxSpeed); -} -void RobotClient::requestAgvNavigateStation(const QString &deviceId, const QString &stationId, - double maxSpeed) -{ - emit agvNavigateStationRequested(deviceId, stationId, maxSpeed); -} -void RobotClient::requestAgvFollowPath(const QString &deviceId, const QVariantList &path, - double maxSpeed) -{ - emit agvFollowPathRequested(deviceId, path, maxSpeed); -} -void RobotClient::requestAgvVelocity(const QString &deviceId, double vx, double vy, double wz) -{ - emit agvVelocityRequested(deviceId, vx, vy, wz); -} -void RobotClient::requestAgvAction(const QString &deviceId, const QString &action) -{ - emit agvActionRequested(deviceId, action); -} -void RobotClient::requestAgvInventory(const QString &deviceId) { emit agvInventoryRequested(deviceId); } -void RobotClient::requestAgvSwitchMap(const QString &deviceId, const QString &mapName) -{ - emit agvSwitchMapRequested(deviceId, mapName); -} -void RobotClient::startAgvMapStream(const QString &deviceId, const QString &mapName, - int dimension, bool snapshot, bool incremental) -{ - emit agvMapStreamStartRequested(deviceId, mapName, dimension, snapshot, incremental); -} -void RobotClient::stopAgvMapStream() -{ - emit agvMapStreamStopRequested(); -} -void RobotClient::requestRpc(const QString &serviceName, const QString &methodName, - const QString &requestJson, const QString &deviceId) -{ - emit rpcRequested(serviceName, methodName, requestJson, deviceId); -} - -void RobotClient::startSpeakerAudioStream(const QString &deviceId) -{ - emit speakerAudioStreamStartRequested(deviceId); -} - -void RobotClient::sendSpeakerAudioFrame(const QByteArray &data, int sampleRate, int channels, - qint64 pts, int samples) -{ - emit speakerAudioFrameRequested(data, sampleRate, channels, pts, samples); -} - -void RobotClient::stopSpeakerAudioStream() -{ - emit speakerAudioStreamStopRequested(); -} - -void RobotClient::startMicrophoneAudioStream(const QString &deviceId) -{ - emit microphoneAudioStreamStartRequested(deviceId); -} - -void RobotClient::stopMicrophoneAudioStream() -{ - emit microphoneAudioStreamStopRequested(); -} - -void RobotClient::connectConfigurationServer(const QString &host, int port) -{ - emit configurationConnectRequested(host, port); -} - -void RobotClient::disconnectConfigurationServer() -{ - emit configurationDisconnectRequested(); -} - -void RobotClient::requestConfigurationFiles() -{ - emit configurationFilesRequested(); -} - -void RobotClient::readConfigurationFile(const QString &relativePath) -{ - emit configurationFileReadRequested(relativePath); -} - -void RobotClient::validateConfigurationFile(const QString &relativePath, - const QString &content) -{ - emit configurationFileValidateRequested(relativePath, content); -} - -void RobotClient::saveConfigurationFile(const QString &relativePath, const QString &content, - const QString &expectedRevision) -{ - emit configurationFileSaveRequested(relativePath, content, expectedRevision); -} +#include "robotclient.h" +#include "videodecoder.h" +#include "tcpjogcontroller.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef CMVR_WITH_GRPC +#include +#include +#include +#include +#include "cmvr/api/agv_command.pb.h" +#include "cmvr/api/agv_service.grpc.pb.h" +#include "cmvr/api/arm_command.pb.h" +#include "cmvr/api/arm_service.grpc.pb.h" +#include "cmvr/api/camera_command.pb.h" +#include "cmvr/api/camera_service.grpc.pb.h" +#include "cmvr/api/configuration_service.grpc.pb.h" +#include "cmvr/api/microphone_command.pb.h" +#include "cmvr/api/microphone_service.grpc.pb.h" +#include "cmvr/api/speaker_command.pb.h" +#include "cmvr/api/speaker_service.grpc.pb.h" +#include "cmvr/api/system_command.pb.h" +#include "cmvr/api/system_service.grpc.pb.h" +#endif + +namespace { +#ifdef CMVR_WITH_GRPC +constexpr int kGrpcMaxMessageBytes = 64 * 1024 * 1024; +constexpr int kArmMotionTimeoutMs = 120000; + +std::shared_ptr createGrpcChannel(const std::string &endpoint) +{ + grpc::ChannelArguments arguments; + arguments.SetMaxReceiveMessageSize(kGrpcMaxMessageBytes); + arguments.SetMaxSendMessageSize(kGrpcMaxMessageBytes); + return grpc::CreateCustomChannel(endpoint, grpc::InsecureChannelCredentials(), arguments); +} + +cmvr::api::DeviceType deviceTypeFromKind(cmvr::api::DeviceKind kind, + cmvr::api::DeviceType fallback) +{ + switch (kind) { + case cmvr::api::DEVICE_KIND_AGV: return cmvr::api::AGV; + case cmvr::api::DEVICE_KIND_ARM: + case cmvr::api::DEVICE_KIND_ROBOT: return cmvr::api::Robot; + case cmvr::api::DEVICE_KIND_BATTERY: return cmvr::api::Battery; + case cmvr::api::DEVICE_KIND_BIO_HEAD: return cmvr::api::BioHead; + case cmvr::api::DEVICE_KIND_CAMERA: return cmvr::api::Camera; + case cmvr::api::DEVICE_KIND_CAN_BUS: return cmvr::api::CanBus; + case cmvr::api::DEVICE_KIND_DEX_HAND: return cmvr::api::DexHand; + case cmvr::api::DEVICE_KIND_GRIPPER: return cmvr::api::Gripper; + case cmvr::api::DEVICE_KIND_MICROPHONE: return cmvr::api::Microphone; + case cmvr::api::DEVICE_KIND_MOTOR: return cmvr::api::Motor; + case cmvr::api::DEVICE_KIND_MOTOR_SYSTEM: return cmvr::api::MotorSystem; + case cmvr::api::DEVICE_KIND_MUJOCO_VIEWER: return cmvr::api::MujocoViewer; + case cmvr::api::DEVICE_KIND_MUJOCO_WORLD: return cmvr::api::MujocoWorld; + case cmvr::api::DEVICE_KIND_SPEAKER: return cmvr::api::Speaker; + case cmvr::api::DEVICE_KIND_UNKNOWN: + default: return fallback; + } +} + +QVariantList deviceListFromStatus(const cmvr::api::GetSystemStatusCommand::Feedback &response) +{ + QVariantList devices; + devices.reserve(response.device_list_size()); + for (const auto &device : response.device_list()) { + QVariantMap item; + const auto deviceType = deviceTypeFromKind(device.device_kind(), device.device_type()); + item.insert(QStringLiteral("deviceId"), QString::fromStdString(device.device_id())); + item.insert(QStringLiteral("type"), static_cast(deviceType)); + item.insert(QStringLiteral("typeName"), + QString::fromStdString(cmvr::api::DeviceType_Name(deviceType))); + item.insert(QStringLiteral("deviceKind"), static_cast(device.device_kind())); + item.insert(QStringLiteral("deviceKindName"), + QString::fromStdString(cmvr::api::DeviceKind_Name(device.device_kind()))); + item.insert(QStringLiteral("driverType"), + QString::fromStdString(device.driver_type())); + item.insert(QStringLiteral("vendor"), QString::fromStdString(device.vendor())); + item.insert(QStringLiteral("online"), true); + devices.append(item); + } + return devices; +} +#endif + +QVariantList demoDeviceList() +{ + QVariantList devices; + const QList definitions = { + {{QStringLiteral("deviceId"), QStringLiteral("right_arm")}, + {QStringLiteral("type"), 6}, {QStringLiteral("deviceKind"), 2}, + {QStringLiteral("driverType"), QStringLiteral("AuboARM")}, + {QStringLiteral("vendor"), QStringLiteral("AUBO")}}, + {{QStringLiteral("deviceId"), QStringLiteral("hikvision_camera")}, + {QStringLiteral("type"), 2}, {QStringLiteral("deviceKind"), 5}, + {QStringLiteral("driverType"), QStringLiteral("HikvisionCamera")}, + {QStringLiteral("vendor"), QStringLiteral("HIKVISION")}}, + {{QStringLiteral("deviceId"), QStringLiteral("src1100_agv")}, + {QStringLiteral("type"), 0}, {QStringLiteral("deviceKind"), 1}, + {QStringLiteral("driverType"), QStringLiteral("SeerRobokitAgv")}, + {QStringLiteral("vendor"), QStringLiteral("SEER")}}, + {{QStringLiteral("deviceId"), QStringLiteral("dexterous_hand")}, + {QStringLiteral("type"), 3}, {QStringLiteral("deviceKind"), 7}, + {QStringLiteral("driverType"), QStringLiteral("RH56DFTPDexhand")}, + {QStringLiteral("vendor"), QStringLiteral("Inspire Robots")}}, + {{QStringLiteral("deviceId"), QStringLiteral("meeting_microphone")}, + {QStringLiteral("type"), 5}, {QStringLiteral("deviceKind"), 9}, + {QStringLiteral("driverType"), QStringLiteral("FFMpegMicroPhone")}, + {QStringLiteral("vendor"), QStringLiteral("FFmpeg")}}, + {{QStringLiteral("deviceId"), QStringLiteral("speaker")}, + {QStringLiteral("type"), 7}, {QStringLiteral("deviceKind"), 15}, + {QStringLiteral("driverType"), QStringLiteral("FFMpegSpeaker")}, + {QStringLiteral("vendor"), QStringLiteral("FFmpeg")}}, + }; + for (const auto &definition : definitions) { + QVariantMap device = definition; + device.insert(QStringLiteral("online"), true); + devices.append(device); + } + return devices; +} + +QStringList armJointNamesForDevice(const QString &deviceId) +{ + const QString prefix = deviceId.contains(QStringLiteral("left"), Qt::CaseInsensitive) + ? 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") + }; +} + +VideoFrame videoFrameFromImage(const QImage &image) +{ + const QImage rgba = image.convertToFormat(QImage::Format_RGBA8888); + VideoFrame frame; + frame.width = rgba.width(); + frame.height = rgba.height(); + frame.format = VideoPixelFormat::RGBA; + frame.stride0 = frame.width * 4; + frame.plane0.resize(frame.width * frame.height * 4); + for (int row = 0; row < frame.height; ++row) { + std::memcpy(frame.plane0.data() + row * frame.width * 4, + rgba.constScanLine(row), static_cast(frame.width * 4)); + } + return frame; +} + +#ifdef CMVR_WITH_GRPC +VideoFrame videoFrameFromDepth(const cmvr::api::FrameData &frame) +{ + if (frame.width() <= 0 || frame.height() <= 0 || + frame.type() != cmvr::api::FrameData::U16C1 || + frame.data().size() < frame.width() * frame.height() * 2) { + return {}; + } + QImage gray(frame.width(), frame.height(), QImage::Format_Grayscale8); + const auto *source = reinterpret_cast(frame.data().data()); + for (int y = 0; y < frame.height(); ++y) { + uchar *destination = gray.scanLine(y); + for (int x = 0; x < frame.width(); ++x) { + quint16 millimeters = 0; + std::memcpy(&millimeters, + source + (y * frame.width() + x) * sizeof(quint16), + sizeof(quint16)); + const int clamped = std::min(millimeters, 5000); + destination[x] = static_cast(255 - (clamped * 255 / 5000)); + } + } + return videoFrameFromImage(gray); +} +#endif +} + +class BackendWorker : public QObject +{ +public: + struct CameraStreamSession { + QString cameraId; + QString codec; + QString mode = QStringLiteral("rgb"); + std::atomic stop{false}; + std::atomic running{false}; + std::thread thread; +#ifdef CMVR_WITH_GRPC + grpc::ClientContext *context = nullptr; + std::mutex contextMutex; +#endif + }; + + struct ArmMotionSession { + std::atomic stop{false}; + std::atomic running{false}; + std::thread thread; +#ifdef CMVR_WITH_GRPC + grpc::ClientContext *context = nullptr; + std::mutex contextMutex; +#endif + }; + + explicit BackendWorker(QObject *parent = nullptr) + : QObject(parent) + { + m_pollTimer = new QTimer(this); + m_pollTimer->setInterval(100); + connect(m_pollTimer, &QTimer::timeout, this, &BackendWorker::poll); + } + + ~BackendWorker() override + { + stopArmMotionInternal(); + stopCameraStreamInternal(); + stopSpeakerStreamInternal(true); + stopMicrophoneStreamInternal(); + stopAgvMapStreamInternal(); + } + +public: + void connectToServer(const QString &host, int port, bool demoMode) + { + m_host = host.trimmed(); + m_port = port; + m_demoMode = demoMode; + m_tick = 0; + + if (m_host.isEmpty()) { + emit connectionChanged(false, 0, QStringLiteral("主机地址不能为空")); + return; + } + + if (m_demoMode) { + m_connected = true; + m_pollTimer->start(); + emit connectionChanged(true, 8, QStringLiteral("演示数据源")); + emit logMessage(QStringLiteral("INFO"), + QStringLiteral("已启动演示模式,界面数据由本地模拟器生成")); + return; + } + +#ifdef CMVR_WITH_GRPC + const std::string endpoint = QStringLiteral("%1:%2").arg(m_host).arg(m_port).toStdString(); + m_channel = createGrpcChannel(endpoint); + QElapsedTimer elapsed; + elapsed.start(); + const auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(1200); + if (!m_channel->WaitForConnected(deadline)) { + m_connected = false; + emit connectionChanged(false, 0, QStringLiteral("连接超时,请检查地址和服务状态")); + emit logMessage(QStringLiteral("ERROR"), QStringLiteral("gRPC 通道连接超时:%1").arg(QString::fromStdString(endpoint))); + return; + } + m_arm = cmvr::api::ArmService::NewStub(m_channel); + m_camera = cmvr::api::CameraService::NewStub(m_channel); + m_system = cmvr::api::SystemService::NewStub(m_channel); + m_agv = cmvr::api::AgvService::NewStub(m_channel); + m_microphone = cmvr::api::MicPhoneService::NewStub(m_channel); + m_generic = std::make_unique(m_channel); + m_connected = true; + m_pollTimer->start(); + emit connectionChanged(true, static_cast(elapsed.elapsed()), QString::fromStdString(endpoint)); + emit logMessage(QStringLiteral("INFO"), QStringLiteral("gRPC 通道已连接:%1").arg(QString::fromStdString(endpoint))); +#else + m_connected = false; + emit connectionChanged(false, 0, QStringLiteral("当前程序未编译 gRPC 支持")); + emit logMessage(QStringLiteral("ERROR"), + QStringLiteral("请使用 CMake 和 gRPC C++ 依赖重新构建,或启用演示模式")); +#endif + } + + void disconnectFromServer() + { + m_pollTimer->stop(); + stopArmMotionInternal(); + stopCameraStreamInternal(); + stopSpeakerStreamInternal(true); + stopMicrophoneStreamInternal(); + stopAgvMapStreamInternal(); + if (m_cameraRecording) { + m_cameraRecording = false; + emit cameraRecordingStateChanged(false, QStringLiteral("连接已断开,录像状态未知")); + } + m_connected = false; + m_armPollingEnabled = false; +#ifdef CMVR_WITH_GRPC + m_arm.reset(); + m_camera.reset(); + m_system.reset(); + m_agv.reset(); + m_microphone.reset(); + m_generic.reset(); + m_channel.reset(); +#endif + emit connectionChanged(false, 0, QStringLiteral("已断开")); + emit logMessage(QStringLiteral("INFO"), QStringLiteral("连接已断开")); + } + + void connectConfigurationServer(const QString &host, int port) + { + const QString trimmedHost = host.trimmed(); + if (trimmedHost.isEmpty()) { + emit configurationConnectionChanged(false, QStringLiteral("主机地址不能为空")); + return; + } +#ifdef CMVR_WITH_GRPC + const std::string endpoint = QStringLiteral("%1:%2").arg(trimmedHost).arg(port).toStdString(); + m_configChannel = createGrpcChannel(endpoint); + const auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(1500); + if (!m_configChannel->WaitForConnected(deadline)) { + m_configuration.reset(); + m_configChannel.reset(); + m_configConnected = false; + emit configurationConnectionChanged( + false, QStringLiteral("配置服务连接超时:%1").arg(QString::fromStdString(endpoint))); + return; + } + m_configuration = cmvr::api::ConfigurationService::NewStub(m_configChannel); + m_configConnected = true; + emit configurationConnectionChanged( + true, QStringLiteral("已连接配置服务:%1").arg(QString::fromStdString(endpoint))); +#else + Q_UNUSED(port) + emit configurationConnectionChanged(false, QStringLiteral("当前程序未编译 gRPC 支持")); +#endif + } + + void disconnectConfigurationServer() + { +#ifdef CMVR_WITH_GRPC + m_configuration.reset(); + m_configChannel.reset(); +#endif + m_configConnected = false; + emit configurationConnectionChanged(false, QStringLiteral("配置服务已断开")); + } + + void listConfigurationFiles() + { +#ifdef CMVR_WITH_GRPC + if (!ensureConfigurationConnected(QStringLiteral("读取配置列表"))) + return; + cmvr::api::ListConfigFilesCommand::Request request; + cmvr::api::ListConfigFilesCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 3000); + const grpc::Status status = m_configuration->ListConfigFiles(&context, request, &response); + const bool success = status.ok() && response.header().success(); + QVariantList files; + if (success) { + for (const auto &file : response.files()) { + QVariantMap item; + item.insert(QStringLiteral("relativePath"), QString::fromStdString(file.relative_path())); + item.insert(QStringLiteral("sizeBytes"), QVariant::fromValue(file.size_bytes())); + item.insert(QStringLiteral("modifiedUnixMs"), QVariant::fromValue(file.modified_unix_ms())); + item.insert(QStringLiteral("messageType"), QString::fromStdString(file.message_type())); + files.append(item); + } + } + emit configurationFilesReceived( + QString::fromStdString(response.config_root()), files, success, + configurationError(status, response.header().error_message())); +#endif + } + + void readConfigurationFile(const QString &relativePath) + { +#ifdef CMVR_WITH_GRPC + if (!ensureConfigurationConnected(QStringLiteral("读取配置文件"))) + return; + cmvr::api::ReadConfigFileCommand::Request request; + request.set_relative_path(relativePath.toStdString()); + cmvr::api::ReadConfigFileCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 3000); + const grpc::Status status = m_configuration->ReadConfigFile(&context, request, &response); + const bool success = status.ok() && response.header().success(); + emit configurationFileReceived( + relativePath, + success ? QString::fromStdString(response.content()) : QString(), + success ? QString::fromStdString(response.revision()) : QString(), + success ? QString::fromStdString(response.file().message_type()) : QString(), + success, configurationError(status, response.header().error_message())); +#else + Q_UNUSED(relativePath) +#endif + } + + void validateConfigurationFile(const QString &relativePath, const QString &content) + { +#ifdef CMVR_WITH_GRPC + if (!ensureConfigurationConnected(QStringLiteral("校验配置文件"))) + return; + cmvr::api::ValidateConfigFileCommand::Request request; + request.set_relative_path(relativePath.toStdString()); + request.set_content(content.toStdString()); + cmvr::api::ValidateConfigFileCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 3000); + const grpc::Status status = m_configuration->ValidateConfigFile(&context, request, &response); + const bool success = status.ok() && response.header().success(); + QString detail = configurationError(status, response.header().error_message()); + if (success) + detail = QStringLiteral("配置有效:%1").arg(QString::fromStdString(response.message_type())); + emit configurationValidationFinished(relativePath, success, detail); +#else + Q_UNUSED(relativePath) + Q_UNUSED(content) +#endif + } + + void saveConfigurationFile(const QString &relativePath, const QString &content, + const QString &expectedRevision) + { +#ifdef CMVR_WITH_GRPC + if (!ensureConfigurationConnected(QStringLiteral("保存配置文件"))) + return; + cmvr::api::SaveConfigFileCommand::Request request; + request.set_relative_path(relativePath.toStdString()); + request.set_content(content.toStdString()); + request.set_expected_revision(expectedRevision.toStdString()); + cmvr::api::SaveConfigFileCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 5000); + const grpc::Status status = m_configuration->SaveConfigFile(&context, request, &response); + const bool success = status.ok() && response.header().success(); + emit configurationSaveFinished( + relativePath, success ? QString::fromStdString(response.revision()) : QString(), + success, configurationError(status, response.header().error_message())); +#else + Q_UNUSED(relativePath) + Q_UNUSED(content) + Q_UNUSED(expectedRevision) +#endif + } + + void setArmTelemetry(const QString &deviceId, bool enabled) + { + if (enabled && !ensureConnected(QStringLiteral("Arm Telemetry"))) + return; + if (enabled && !ensureDeviceId(QStringLiteral("Arm Telemetry"), deviceId)) + return; + const QString nextDeviceId = enabled ? deviceId.trimmed() : QString(); + if (m_armDeviceId != nextDeviceId) { + m_demoTargets.clear(); + m_armBaseFrame.clear(); + m_armTcpFrame.clear(); + } + m_armDeviceId = nextDeviceId; + m_armPollingEnabled = enabled; + m_consecutivePollErrors = 0; + emit commandFinished(QStringLiteral("Arm Telemetry"), true, + enabled ? QStringLiteral("机械臂遥测已启动") + : QStringLiteral("机械臂遥测已停止")); + } + + void getArmInfo(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("GetArmInfo")) + || !ensureDeviceId(QStringLiteral("GetArmInfo"), deviceId)) { + return; + } + QVariantMap info; + info.insert(QStringLiteral("deviceId"), deviceId.trimmed()); + if (m_demoMode) { + const QStringList jointNames = armJointNamesForDevice(deviceId); + info.insert(QStringLiteral("manufacturer"), QStringLiteral("CMVR")); + info.insert(QStringLiteral("model"), QStringLiteral("demo_arm")); + info.insert(QStringLiteral("descriptionId"), QStringLiteral("demo_arm")); + info.insert(QStringLiteral("dof"), jointNames.size()); + info.insert(QStringLiteral("jointNames"), jointNames); + info.insert(QStringLiteral("detectedFromSdk"), false); + emit armInfoReceived(deviceId.trimmed(), info); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::GetArmInfo::Request request; + fillHeader(request.mutable_header(), deviceId); + cmvr::api::GetArmInfo::Response response; + grpc::ClientContext context; + setDeadline(context, 1200); + const grpc::Status status = m_arm->GetArmInfo(&context, request, &response); + if (!status.ok() || !response.header().success()) { + const QString detail = status.ok() + ? QString::fromStdString(response.header().error_message()) + : QString::fromStdString(status.error_message()); + emit commandFinished(QStringLiteral("GetArmInfo"), false, detail); + return; + } + QStringList jointNames; + jointNames.reserve(response.joint_names_size()); + for (const auto &name : response.joint_names()) + jointNames.append(QString::fromStdString(name)); + info.insert(QStringLiteral("manufacturer"), QString::fromStdString(response.manufacturer())); + info.insert(QStringLiteral("model"), QString::fromStdString(response.model())); + info.insert(QStringLiteral("subtype"), QString::fromStdString(response.subtype())); + info.insert(QStringLiteral("dof"), static_cast(response.dof())); + info.insert(QStringLiteral("jointNames"), jointNames); + info.insert(QStringLiteral("defaultBaseFrame"), QString::fromStdString(response.default_base_frame())); + info.insert(QStringLiteral("defaultTcpFrame"), QString::fromStdString(response.default_tcp_frame())); + info.insert(QStringLiteral("descriptionId"), QString::fromStdString(response.description_id())); + info.insert(QStringLiteral("detectedFromSdk"), response.detected_from_sdk()); + info.insert(QStringLiteral("driverType"), QString::fromStdString(response.driver_type())); + emit armInfoReceived(deviceId.trimmed(), info); +#endif + } + + void getTcpCalibrationPose(const QString &deviceId, quint64 requestId) + { + const QString selectedDevice = deviceId.trimmed(); + const auto reject = [this, requestId, selectedDevice](const QString &detail) { + emit tcpCalibrationPoseReceived(requestId, selectedDevice, {}, {}, false, detail); + }; + if (m_demoMode) { + reject(QStringLiteral("TCP 标定不接受演示数据,请连接真实机械臂")); + return; + } + if (!m_connected || selectedDevice.isEmpty()) { + reject(QStringLiteral("TCP 标定采样失败:服务未连接或设备 ID 为空")); + return; + } +#ifdef CMVR_WITH_GRPC + if (!m_arm) { + reject(QStringLiteral("TCP 标定采样失败:机械臂服务不可用")); + return; + } + cmvr::api::GetArmInfo::Request infoRequest; + fillHeader(infoRequest.mutable_header(), selectedDevice); + cmvr::api::GetArmInfo::Response info; + grpc::ClientContext infoContext; + setDeadline(infoContext, 1500); + const grpc::Status infoStatus = m_arm->GetArmInfo(&infoContext, infoRequest, &info); + if (!infoStatus.ok() || !info.header().success() + || QString::fromStdString(info.device_id()).trimmed() != selectedDevice) { + reject(QStringLiteral("TCP 标定采样失败:无法确认机械臂驱动身份")); + return; + } + const QString driver = QString::fromStdString(info.driver_type()).trimmed().toLower(); + const QString manufacturer = QString::fromStdString(info.manufacturer()).trimmed().toLower(); + const bool auboDriver = driver == QStringLiteral("auboarm") + || driver == QStringLiteral("aubo_arm"); + const bool auboManufacturer = manufacturer == QStringLiteral("aubo") + || manufacturer == QStringLiteral("auboarm"); + if (!auboDriver && !(driver.isEmpty() && auboManufacturer)) { + reject(QStringLiteral("当前驱动尚未适配 TCP 标定所需的姿态及运动约定:%1") + .arg(QString::fromStdString(info.driver_type()))); + return; + } + // A fresh state request deliberately bypasses display telemetry and named + // getPose: some drivers silently ignore its requested base/flange names. + cmvr::api::GetRobotState::Request request; + fillHeader(request.mutable_header(), selectedDevice); + cmvr::api::GetRobotState::Response response; + grpc::ClientContext context; + setDeadline(context, 1500); + const qint64 requestedAtMs = QDateTime::currentMSecsSinceEpoch(); + const grpc::Status status = m_arm->getRobotState(&context, request, &response); + const qint64 receivedAtMs = QDateTime::currentMSecsSinceEpoch(); + if (!status.ok() || !response.header().success()) { + const QString error = status.ok() + ? QString::fromStdString(response.header().error_message()) + : QString::fromStdString(status.error_message()); + reject(QStringLiteral("TCP 标定实时采样失败:%1").arg(error)); + return; + } + if (!response.has_state()) { + reject(QStringLiteral("TCP 标定采样失败:服务未返回机械臂状态")); + return; + } + const auto &robotState = response.state(); + if (!robotState.connected() || robotState.moving() || robotState.fault() + || robotState.protective_stopped() || robotState.emergency_stopped()) { + reject(QStringLiteral("TCP 标定采样失败:机械臂未连接、正在运动或存在故障/停止状态")); + return; + } + if ((robotState.safety_mode() != cmvr::api::ARM_SAFETY_MODE_NORMAL + && robotState.safety_mode() != cmvr::api::ARM_SAFETY_MODE_REDUCED) + || (robotState.robot_mode() != cmvr::api::ARM_ROBOT_MODE_IDLE + && robotState.robot_mode() != cmvr::api::ARM_ROBOT_MODE_PAUSED)) { + reject(QStringLiteral("TCP 标定采样失败:机械臂未处于可确认的静止安全状态")); + return; + } + if (!robotState.has_actual_tcp_pose() || !robotState.has_actual_joint_state() + || !std::isfinite(robotState.timestamp()) || robotState.timestamp() < 0.0) { + reject(QStringLiteral("TCP 标定采样失败:缺少有效 TCP 位姿、关节状态或时间戳")); + return; + } + const auto &joints = robotState.actual_joint_state(); + if (info.dof() == 0 || joints.position_size() != static_cast(info.dof()) + || joints.velocity_size() != joints.position_size() + || (joints.name_size() != 0 && joints.name_size() != joints.position_size())) { + reject(QStringLiteral("TCP 标定采样失败:关节速度缺失或维度不一致")); + return; + } + bool allJointsZero = true; + for (int i = 0; i < joints.position_size(); ++i) { + if (!std::isfinite(joints.position(i)) || !std::isfinite(joints.velocity(i)) + || std::abs(joints.velocity(i)) > 0.01) { + reject(QStringLiteral("TCP 标定采样失败:关节数据无效或机械臂尚未静止")); + return; + } + allJointsZero = allJointsZero && joints.position(i) == 0.0 && joints.velocity(i) == 0.0; + } + // This backend also zero-fills joint arrays when an SDK read fails. + if (allJointsZero) { + reject(QStringLiteral("TCP 标定采样失败:关节反馈全零,无法排除 SDK 读取失败,请更换姿态后重试")); + return; + } + const auto &tcp = robotState.actual_tcp_pose(); + const double values[] = {tcp.x(), tcp.y(), tcp.z(), tcp.rx(), tcp.ry(), tcp.rz()}; + bool allZero = true; + for (double value : values) { + if (!std::isfinite(value)) { + reject(QStringLiteral("TCP 标定采样失败:TCP 位姿包含非有限数值")); + return; + } + allZero = allZero && value == 0.0; + } + // Existing AUBO backend returns a zero pose on SDK read failure. + if (allZero) { + reject(QStringLiteral("TCP 标定采样失败:服务返回全零位姿,无法排除 SDK 读取失败")); + return; + } + const QVariantMap pose = { + {QStringLiteral("x"), tcp.x()}, {QStringLiteral("y"), tcp.y()}, + {QStringLiteral("z"), tcp.z()}, {QStringLiteral("rx"), tcp.rx()}, + {QStringLiteral("ry"), tcp.ry()}, {QStringLiteral("rz"), tcp.rz()}}; + const QVariantMap state = { + {QStringLiteral("connected"), robotState.connected()}, + {QStringLiteral("moving"), robotState.moving()}, + {QStringLiteral("fault"), robotState.fault()}, + {QStringLiteral("protectiveStopped"), robotState.protective_stopped()}, + {QStringLiteral("emergencyStopped"), robotState.emergency_stopped()}, + {QStringLiteral("timestamp"), robotState.timestamp()}, + {QStringLiteral("serverTimestampAvailable"), robotState.timestamp() > 0.0}, + {QStringLiteral("requestedAtMs"), requestedAtMs}, + {QStringLiteral("receivedAtMs"), receivedAtMs}, + {QStringLiteral("driverType"), QString::fromStdString(info.driver_type())}, + {QStringLiteral("manufacturer"), QString::fromStdString(info.manufacturer())}, + {QStringLiteral("source"), QStringLiteral("getRobotState.actual_tcp_pose")}}; + emit tcpCalibrationPoseReceived(requestId, selectedDevice, pose, state, true, + QStringLiteral("已实时读取当前 TCP 位姿;需用已确认的当前 TCP 偏置换算为法兰位姿")); +#else + reject(QStringLiteral("当前构建未启用 gRPC,无法采集真实 TCP 位姿")); +#endif + } + + void getArmFrames(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("List Arm Frames")) + || !ensureDeviceId(QStringLiteral("List Arm Frames"), deviceId)) { + return; + } + QStringList baseFrames; + QStringList tcpFrames; + if (m_demoMode) { + baseFrames << QStringLiteral("base0") << QStringLiteral("world"); + tcpFrames << QStringLiteral("tool0") << QStringLiteral("flange"); + emit armFramesReceived(deviceId.trimmed(), baseFrames, tcpFrames); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::ListFrame::Request baseRequest; + fillHeader(baseRequest.mutable_header(), deviceId); + cmvr::api::ListFrame::Response baseResponse; + grpc::ClientContext baseContext; + setDeadline(baseContext, 1500); + const grpc::Status baseStatus = + m_arm->ListBaseFrame(&baseContext, baseRequest, &baseResponse); + if (baseStatus.ok() && baseResponse.header().success()) { + for (const auto &name : baseResponse.frame_names()) + baseFrames.append(QString::fromStdString(name)); + } + + cmvr::api::ListFrame::Request tcpRequest; + fillHeader(tcpRequest.mutable_header(), deviceId); + cmvr::api::ListFrame::Response tcpResponse; + grpc::ClientContext tcpContext; + setDeadline(tcpContext, 1500); + const grpc::Status tcpStatus = + m_arm->ListTCPFrame(&tcpContext, tcpRequest, &tcpResponse); + if (tcpStatus.ok() && tcpResponse.header().success()) { + for (const auto &name : tcpResponse.frame_names()) + tcpFrames.append(QString::fromStdString(name)); + } + emit armFramesReceived(deviceId.trimmed(), baseFrames, tcpFrames); + if (!baseStatus.ok() || !baseResponse.header().success() + || !tcpStatus.ok() || !tcpResponse.header().success()) { + emit logMessage(QStringLiteral("WARN"), + QStringLiteral("机械臂坐标系列表未完整返回,将使用 SDK 默认坐标系")); + } +#endif + } + + void setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame, + const QString &tcpFrame) + { + if (deviceId.trimmed() != m_armDeviceId) + return; + m_armBaseFrame = baseFrame.trimmed(); + m_armTcpFrame = tcpFrame.trimmed(); + } + + void speedJ(const QString &deviceId, const QVariantList &velocities, + double acceleration, double duration) + { + if (!ensureConnected(QStringLiteral("SpeedJ")) + || !ensureDeviceId(QStringLiteral("SpeedJ"), deviceId)) { + return; + } + if (velocities.isEmpty()) { + emit commandFinished(QStringLiteral("SpeedJ"), false, + QStringLiteral("关节速度不能为空")); + return; + } + if (m_demoMode) { + emit commandFinished(QStringLiteral("SpeedJ"), true, + QStringLiteral("演示点动:%1 个关节").arg(velocities.size())); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::SpeedJ::Request request; + fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs); + for (const QVariant &value : velocities) + request.mutable_velocity()->add_velocity(value.toDouble()); + request.set_acceleration(acceleration); + request.set_duration(duration); + startArmMotion( + QStringLiteral("SpeedJ"), std::move(request), + [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, + const cmvr::api::SpeedJ::Request &motionRequest, + cmvr::api::SpeedJ::Response *response) { + return stub.speedJ(context, motionRequest, response); + }); +#endif + } + + void speedL(const QString &deviceId, const QVariantMap &velocity, + double acceleration, double duration, bool toolFrame) + { + if (!ensureConnected(QStringLiteral("SpeedL")) + || !ensureDeviceId(QStringLiteral("SpeedL"), deviceId)) { + return; + } + if (m_demoMode) { + emit commandFinished(QStringLiteral("SpeedL"), true, + QStringLiteral("演示笛卡尔点动")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::SpeedL::Request request; + fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs); + auto *target = request.mutable_velocity(); + target->set_vx(velocity.value(QStringLiteral("vx")).toDouble()); + target->set_vy(velocity.value(QStringLiteral("vy")).toDouble()); + target->set_vz(velocity.value(QStringLiteral("vz")).toDouble()); + target->set_wx(velocity.value(QStringLiteral("wx")).toDouble()); + target->set_wy(velocity.value(QStringLiteral("wy")).toDouble()); + target->set_wz(velocity.value(QStringLiteral("wz")).toDouble()); + request.set_acceleration(acceleration); + request.set_duration(duration); + request.set_frame(toolFrame ? cmvr::api::ARM_FRAME_TOOL + : cmvr::api::ARM_FRAME_BASE); + startArmMotion( + QStringLiteral("SpeedL"), std::move(request), + [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, + const cmvr::api::SpeedL::Request &motionRequest, + cmvr::api::SpeedL::Response *response) { + return stub.speedL(context, motionRequest, response); + }); +#endif + } + + void moveJ(const QString &deviceId, const QVariantList &positions, + double velocity, double acceleration) + { + if (!ensureConnected(QStringLiteral("MoveJ"))) + return; + if (!ensureDeviceId(QStringLiteral("MoveJ"), deviceId)) + return; + if (positions.isEmpty()) { + emit commandFinished(QStringLiteral("MoveJ"), false, QStringLiteral("没有可发送的目标关节")); + return; + } + if (m_demoMode) { + m_demoTargets.clear(); + for (const QVariant &value : positions) + m_demoTargets.append(value.toDouble()); + emit commandFinished(QStringLiteral("MoveJ"), true, + QStringLiteral("已发送 %1 个目标,v=%2,a=%3") + .arg(positions.size()).arg(velocity, 0, 'f', 2).arg(acceleration, 0, 'f', 2)); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::MoveJ::Request request; + fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs); + for (const QVariant &value : positions) + request.mutable_target()->add_position(value.toDouble()); + request.mutable_options()->set_velocity(velocity); + request.mutable_options()->set_acceleration(acceleration); + startArmMotion( + QStringLiteral("MoveJ"), std::move(request), + [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, + const cmvr::api::MoveJ::Request &motionRequest, + cmvr::api::MoveJ::Response *response) { + return stub.moveJ(context, motionRequest, response); + }); +#endif + } + + void moveJPose(const QString &deviceId, const QVariantMap &pose, + const QString &baseLink, const QString &eeLink, + double velocity, double acceleration) + { + movePoseImpl(deviceId, pose, baseLink, eeLink, velocity, acceleration, QStringLiteral("MoveL")); + } + + void tcpJogMove(const QString &deviceId, const QVariantMap &pose, + double velocity, double acceleration, quint64 token) + { + // The verified driver resolves "tcp" to its current active offset. + // Never pass a local profile name as a controller frame identifier. + movePoseImpl(deviceId, pose, QStringLiteral("base"), QStringLiteral("tcp"), + velocity, acceleration, TcpJogController::commandName(token)); + } + + void movePoseImpl(const QString &deviceId, const QVariantMap &pose, + const QString &baseLink, const QString &eeLink, + double velocity, double acceleration, const QString &command) + { + if (!ensureConnected(command)) + return; + if (!ensureDeviceId(command, deviceId)) + return; + if (m_demoMode) { + emit commandFinished(command, true, + QStringLiteral("已发送末端位姿 MoveL,%1 → %2,v=%3,a=%4") + .arg(baseLink, eeLink) + .arg(velocity, 0, 'f', 2) + .arg(acceleration, 0, 'f', 2)); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::MoveL::Request request; + fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs); + auto *target = request.mutable_target(); + target->set_x(pose.value(QStringLiteral("x")).toDouble()); + target->set_y(pose.value(QStringLiteral("y")).toDouble()); + target->set_z(pose.value(QStringLiteral("z")).toDouble()); + target->set_rx(pose.value(QStringLiteral("rx")).toDouble()); + target->set_ry(pose.value(QStringLiteral("ry")).toDouble()); + target->set_rz(pose.value(QStringLiteral("rz")).toDouble()); + request.mutable_options()->set_velocity(velocity); + request.mutable_options()->set_acceleration(acceleration); + request.set_frame(cmvr::api::ARM_FRAME_BASE); + if (!baseLink.trimmed().isEmpty()) + request.set_base_frame(baseLink.trimmed().toStdString()); + if (!eeLink.trimmed().isEmpty()) + request.set_tcp_frame(eeLink.trimmed().toStdString()); + startArmMotion( + command, std::move(request), + [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, + const cmvr::api::MoveL::Request &motionRequest, + cmvr::api::MoveL::Response *response) { + return stub.moveL(context, motionRequest, response); + }); +#endif + } + + void torque(const QString &deviceId, bool enabled) + { + const QString command = enabled ? QStringLiteral("Torque On") : QStringLiteral("Torque Off"); + if (!ensureConnected(command)) + return; + if (!ensureDeviceId(command, deviceId)) + return; + if (m_demoMode) { + emit commandFinished(command, true, enabled ? QStringLiteral("关节已使能") : QStringLiteral("关节已去使能")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::CommandHeader::Request request; + fillHeader(&request, deviceId); + cmvr::api::CommandHeader::Feedback response; + grpc::ClientContext context; + setDeadline(context, 2000); + const grpc::Status status = enabled + ? m_arm->torqueOn(&context, request, &response) + : m_arm->torqueOff(&context, request, &response); + finish(command, status, response.success(), QString::fromStdString(response.error_message())); +#endif + } + + void armStop(const QString &deviceId) + { + stopArmMotionInternal(); + if (!ensureConnected(QStringLiteral("Stop Motion"))) + return; + if (!ensureDeviceId(QStringLiteral("Stop Motion"), deviceId)) + return; + if (m_demoMode) { + m_demoTargets.clear(); + emit commandFinished(QStringLiteral("Stop Motion"), true, QStringLiteral("运动已停止")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::CommandHeader::Request request; + fillHeader(&request, deviceId); + cmvr::api::CommandHeader::Feedback response; + grpc::ClientContext context; + setDeadline(context, 1500); + const grpc::Status status = m_arm->stopMotion(&context, request, &response); + finish(QStringLiteral("Stop Motion"), status, response.success(), QString::fromStdString(response.error_message())); +#endif + } + + void armClearFault(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("Clear Fault"))) + return; + if (!ensureDeviceId(QStringLiteral("Clear Fault"), deviceId)) + return; + if (m_demoMode) { + emit commandFinished(QStringLiteral("Clear Fault"), true, QStringLiteral("故障状态已清除")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::CommandHeader::Request request; + fillHeader(&request, deviceId); + cmvr::api::CommandHeader::Feedback response; + grpc::ClientContext context; + setDeadline(context, 2000); + const grpc::Status status = m_arm->clearFault(&context, request, &response); + finish(QStringLiteral("Clear Fault"), status, response.success(), QString::fromStdString(response.error_message())); +#endif + } + + void armCalibrateZero(const QString &deviceId, const QString &jointName) + { + const QString command = QStringLiteral("Calibrate Zero Q"); + if (!ensureConnected(command)) + return; + if (!ensureDeviceId(command, deviceId)) + return; + if (jointName.trimmed().isEmpty()) { + emit commandFinished(command, false, QStringLiteral("关节名称不能为空")); + return; + } + if (m_demoMode) { + emit commandFinished(command, true, + QStringLiteral("已将 %1 的当前位置设置为零位(演示)") + .arg(jointName)); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::CalibrateZeroQ::Request request; + fillHeader(request.mutable_header(), deviceId); + request.set_joint_name(jointName.toStdString()); + cmvr::api::CalibrateZeroQ::Response response; + grpc::ClientContext context; + setDeadline(context, 2500); + const grpc::Status status = m_arm->calibrateZeroQ(&context, request, &response); + finish(command, status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + + void snapshot(const QString &cameraId) + { + if (!ensureConnected(QStringLiteral("Snapshot"))) + return; + if (!ensureDeviceId(QStringLiteral("Snapshot"), cameraId)) + return; + if (m_demoMode) { + QImage image(1280, 720, QImage::Format_RGB32); + image.fill(QColor("#20252b")); + QPainter painter(&image); + painter.setRenderHint(QPainter::Antialiasing); + painter.setPen(QPen(QColor("#3b424b"), 1)); + for (int x = 0; x < image.width(); x += 64) + painter.drawLine(x, 0, x, image.height()); + for (int y = 0; y < image.height(); y += 64) + painter.drawLine(0, y, image.width(), y); + painter.setPen(QColor("#e9edf2")); + painter.setFont(QFont("Microsoft YaHei UI", 28, QFont::DemiBold)); + painter.drawText(image.rect().adjusted(0, -40, 0, 0), Qt::AlignCenter, QStringLiteral("相机预览")); + painter.setPen(QColor("#9ca4ad")); + painter.setFont(QFont("Microsoft YaHei UI", 14)); + painter.drawText(image.rect().adjusted(0, 48, 0, 0), Qt::AlignCenter, + QStringLiteral("%1 · DEMO · %2") + .arg(cameraId, QDateTime::currentDateTime().toString("HH:mm:ss"))); + emit imageReceived(image, QStringLiteral("1280 x 720 · 演示帧")); + emit commandFinished(QStringLiteral("Snapshot"), true, QStringLiteral("已获取演示图像")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::GetRGBImageCommand::Request request; + fillHeader(request.mutable_header(), cameraId); + cmvr::api::GetRGBImageCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 3000); + const grpc::Status status = m_camera->GetRGBImage(&context, request, &response); + if (!status.ok() || !response.header().success()) { + finish(QStringLiteral("Snapshot"), status, response.header().success(), + QString::fromStdString(response.header().error_message())); + return; + } + const auto &frame = response.color_frame(); + const QByteArray bytes(frame.data().data(), static_cast(frame.data().size())); + QImage image; + if (frame.type() == cmvr::api::FrameData::U8C3 && + frame.width() > 0 && frame.height() > 0 && bytes.size() == frame.width() * frame.height() * 3) { + image = QImage(reinterpret_cast(bytes.constData()), frame.width(), frame.height(), + frame.width() * 3, QImage::Format_RGB888).rgbSwapped(); + } else if (frame.type() == cmvr::api::FrameData::U8C1 && + frame.width() > 0 && frame.height() > 0 && bytes.size() == frame.width() * frame.height()) { + image = QImage(reinterpret_cast(bytes.constData()), frame.width(), frame.height(), + frame.width(), QImage::Format_Grayscale8).copy(); + } else { + image = QImage::fromData(bytes); + } + if (image.isNull()) { + emit commandFinished(QStringLiteral("Snapshot"), false, + QStringLiteral("暂不支持图像编码:%1").arg(QString::fromStdString(frame.codec()))); + return; + } + emit imageReceived(image, QStringLiteral("%1 x %2 · %3") + .arg(image.width()).arg(image.height()).arg(QString::fromStdString(frame.codec()))); + emit commandFinished(QStringLiteral("Snapshot"), true, QStringLiteral("图像获取成功")); +#endif + } + + void getHandEyeImage(const QString &cameraId, quint64 token) + { + const QString selectedCamera = cameraId.trimmed(); + const auto reject = [this, token, selectedCamera](const QString &detail) { + emit handEyeImageReceived(token, selectedCamera, {}, {}, {}, false, detail); + }; + if (m_demoMode) { + reject(QStringLiteral("手眼标定不接受演示图像,请连接真实相机")); + return; + } + if (!m_connected || selectedCamera.isEmpty()) { + reject(QStringLiteral("手眼图像采集失败:服务未连接或相机 ID 为空")); + return; + } +#ifdef CMVR_WITH_GRPC + if (!m_camera) { + reject(QStringLiteral("手眼图像采集失败:相机服务不可用")); + return; + } + cmvr::api::GetRGBImageCommand::Request request; + fillHeader(request.mutable_header(), selectedCamera); + cmvr::api::GetRGBImageCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 3000); + const qint64 requestedAtMs = QDateTime::currentMSecsSinceEpoch(); + const grpc::Status status = m_camera->GetRGBImage(&context, request, &response); + const qint64 receivedAtMs = QDateTime::currentMSecsSinceEpoch(); + if (!status.ok() || !response.header().success()) { + reject(QStringLiteral("手眼图像采集失败:%1").arg(status.ok() + ? QString::fromStdString(response.header().error_message()) + : QString::fromStdString(status.error_message()))); + return; + } + if (!response.has_color_frame() || !response.has_intrinsics()) { + reject(QStringLiteral("相机未返回完整的彩色图像和对应内参")); + return; + } + const auto &frame = response.color_frame(); + const QString codec = QString::fromStdString(frame.codec()).trimmed().toLower(); + const int channels = frame.type() == cmvr::api::FrameData::U8C3 ? 3 + : frame.type() == cmvr::api::FrameData::U8C1 ? 1 : 0; + // Unary GetRGBImage serializes tightly packed OpenCV BGR/gray bytes. + // Bound the multiplication before allocating or constructing a QImage. + const qint64 pixels = static_cast(frame.width()) * frame.height(); + if (frame.width() <= 0 || frame.height() <= 0 || channels == 0 + || (!codec.isEmpty() && codec != QStringLiteral("none")) + || pixels > kGrpcMaxMessageBytes / channels + || static_cast(pixels * channels) != frame.data().size()) { + reject(QStringLiteral("相机图像格式、尺寸或数据长度无效;需要原始 BGR8/灰度图像")); + return; + } + const auto &camera = response.intrinsics(); + bool validIntrinsics = std::isfinite(camera.fx()) && camera.fx() > 0.0f + && std::isfinite(camera.fy()) && camera.fy() > 0.0f + && std::isfinite(camera.cx()) && std::isfinite(camera.cy()) + && camera.coeffs_size() == 5; + QVariantList coefficients; + for (const float coefficient : camera.coeffs()) { + validIntrinsics = validIntrinsics && std::isfinite(coefficient); + coefficients.append(static_cast(coefficient)); + } + if (!validIntrinsics) { + reject(QStringLiteral("相机彩色内参无效:需要正焦距、有限主点和 5 个有限畸变系数")); + return; + } + const auto *data = reinterpret_cast(frame.data().data()); + const QImage borrowed(data, frame.width(), frame.height(), frame.width() * channels, + channels == 3 ? QImage::Format_RGB888 : QImage::Format_Grayscale8); + const QImage image = channels == 3 ? borrowed.rgbSwapped() : borrowed.copy(); + if (image.isNull()) { + reject(QStringLiteral("手眼图像解码失败")); + return; + } + const QVariantMap intrinsics = { + {QStringLiteral("fx"), camera.fx()}, {QStringLiteral("fy"), camera.fy()}, + {QStringLiteral("cx"), camera.cx()}, {QStringLiteral("cy"), camera.cy()}, + {QStringLiteral("coeffs"), coefficients}, + {QStringLiteral("width"), image.width()}, {QStringLiteral("height"), image.height()}, + {QStringLiteral("distortionModelAvailable"), false}, + {QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImage.intrinsics")}}; + // Older/current unary servers omit these fields. Preserve zero and + // advertise the absence; receipt time is not a camera capture time. + const bool captureTimestampAvailable = frame.capture_utc_ns() > 0; + const QVariantMap metadata = { + {QStringLiteral("captureUtcNs"), static_cast(frame.capture_utc_ns())}, + {QStringLiteral("sourceSequence"), static_cast(frame.source_sequence())}, + {QStringLiteral("sourceFrameNumber"), static_cast(frame.source_frame_number())}, + {QStringLiteral("sourceTimestamp"), static_cast(frame.source_timestamp())}, + {QStringLiteral("pts"), static_cast(frame.pts())}, + {QStringLiteral("dts"), static_cast(frame.dts())}, + {QStringLiteral("sourceFps"), frame.source_fps()}, + {QStringLiteral("requestedAtMs"), requestedAtMs}, + {QStringLiteral("receivedAtMs"), receivedAtMs}, + {QStringLiteral("captureTimestampAvailable"), captureTimestampAvailable}, + {QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImage.color_frame")}}; + emit handEyeImageReceived(token, selectedCamera, image, intrinsics, metadata, true, + captureTimestampAvailable + ? QStringLiteral("已获取原始图像、对应内参及采集时间戳") + : QStringLiteral("已获取图像和内参;服务未提供图像采集时间戳,不能确认与机械臂位姿同步")); +#else + reject(QStringLiteral("当前构建未启用 gRPC,无法采集真实相机图像")); +#endif + } + + void getTouchRgbdImage(const QString &cameraId, quint64 token) + { + const auto reject=[&](const QString &detail) { touchRgbdImageReceived(token,cameraId,{},{},{},false,detail); }; + if(m_demoMode||!m_connected||cameraId.trimmed().isEmpty()) { reject(QStringLiteral("请连接真实相机服务")); return; } +#ifdef CMVR_WITH_GRPC + if(!m_camera) { reject(QStringLiteral("相机服务不可用")); return; } + cmvr::api::GetRGBDImagesCommand::Request request; + fillHeader(request.mutable_header(),cameraId); request.set_require_metric_depth(true); + cmvr::api::GetRGBDImagesCommand::Feedback response; + grpc::ClientContext context; setDeadline(context,3000); + const auto status=m_camera->GetRGBDImages(&context,request,&response); + if(!status.ok()||!response.header().success()) { + reject(QStringLiteral("GetRGBDImages:%1").arg(QString::fromStdString(status.ok()?response.header().error_message():status.error_message()))); return; + } + if(!response.has_depth_geometry()) { + reject(QStringLiteral("相机服务尚未提供公制深度元数据,请安装随上位机提供的 RGBD 服务补丁。")); return; + } + const auto &rgb=response.color_frame(); const auto &d=response.depth_frame(); + const auto &g=response.depth_geometry(); const auto &k=response.intrinsics(); + const int bytes=d.type()==cmvr::api::FrameData::U16C1?2:d.type()==cmvr::api::FrameData::F32C1?4:0; + const qint64 pixels=qint64(rgb.width())*rgb.height(); + const auto raw=[](const cmvr::api::FrameData &f) { return f.codec().empty()||f.codec()=="none"; }; + if(rgb.width()<2||rgb.height()<2||rgb.width()>16384||rgb.height()>16384||pixels>kGrpcMaxMessageBytes/7 + ||rgb.type()!=cmvr::api::FrameData::U8C3||!bytes||!raw(rgb)||!raw(d) + ||d.width()!=rgb.width()||d.height()!=rgb.height() + ||rgb.data().size()!=quint64(pixels*3)||d.data().size()!=quint64(pixels*bytes) + ||!g.aligned_to_color()||!g.color_axial_z()||g.byte_order()!="little" + ||!std::isfinite(g.metres_per_unit())||g.metres_per_unit()<=0||g.metres_per_unit()>1 + ||rgb.capture_utc_ns()<=0||d.capture_utc_ns()<=0 + ||std::abs(rgb.capture_utc_ns()-d.capture_utc_ns())>33000000 + ||(g.distortion_model()!="none"&&g.distortion_model()!="brown_conrady")) { + reject(QStringLiteral("RGBD 格式、配准、时间戳或公制深度信息无效")); return; + } + QVariantList coeffs; + for(float value:k.coeffs()) { if(!std::isfinite(value)) { reject(QStringLiteral("RGB 内参无效")); return; } coeffs<(rgb.data().data()),rgb.width(),rgb.height(),rgb.width()*3,QImage::Format_RGB888); + const QImage image=borrowed.rgbSwapped(); // Owning RGB image; raw transport is OpenCV BGR. + const QVariantMap intrinsics{{"fx",double(k.fx())},{"fy",double(k.fy())},{"cx",double(k.cx())},{"cy",double(k.cy())}, + {"width",rgb.width()},{"height",rgb.height()},{"coeffs",coeffs},{"model",QString::fromStdString(g.distortion_model())}}; + const QVariantMap metadata{{"captureUtcNs",qint64(rgb.capture_utc_ns())},{"depthCaptureUtcNs",qint64(d.capture_utc_ns())}, + {"alignedToColor",true},{"colorAxialZ",true},{"byteOrder","little"},{"metresPerUnit",g.metres_per_unit()}, + {"depthWidth",d.width()},{"depthHeight",d.height()},{"depthFloat32",bytes==4}, + {"depthData",QByteArray(d.data().data(),int(d.data().size()))}}; + touchRgbdImageReceived(token,cameraId,image,intrinsics,metadata,true,QStringLiteral("已获取同步公制 RGBD")); +#else + reject(QStringLiteral("当前构建未启用 gRPC")); +#endif + } + + void startCameraStream(const QString &cameraId, const QString &codec, + const QString &mode) + { + if (!ensureConnected(QStringLiteral("Camera Stream")) || + !ensureDeviceId(QStringLiteral("Camera Stream"), cameraId)) + return; + + const QString normalizedCameraId = cameraId.trimmed(); + std::shared_ptr existing; + { + std::lock_guard lock(m_cameraSessionsMutex); + const auto it = m_cameraSessions.find(normalizedCameraId); + if (it != m_cameraSessions.end()) + existing = it.value(); + } + if (existing && existing->running.load()) { + emit commandFinished(QStringLiteral("Camera Stream"), false, + QStringLiteral("摄像头 %1 的视频预览已经在运行") + .arg(normalizedCameraId)); + return; + } + if (existing) + stopCameraStreamInternal(normalizedCameraId); + + auto session = std::make_shared(); + session->cameraId = normalizedCameraId; + session->codec = codec.trimmed().toLower(); + session->mode = mode.trimmed().toLower(); + if (session->mode != QStringLiteral("depth") && + session->mode != QStringLiteral("rgbd")) + session->mode = QStringLiteral("rgb"); + if (session->codec.isEmpty()) + session->codec = m_defaultCameraCodec; + session->running.store(true); + { + std::lock_guard lock(m_cameraSessionsMutex); + m_cameraSessions[normalizedCameraId] = session; + } + emit cameraStreamStateChangedForCamera(normalizedCameraId, true, + QStringLiteral("正在建立视频流...")); + + if (m_demoMode) { + session->thread = std::thread([this, session]() { + int frameNumber = 0; + QElapsedTimer elapsed; + elapsed.start(); + while (!session->stop.load()) { + QImage image(1280, 720, QImage::Format_RGB32); + image.fill(QColor("#20252b")); + QPainter painter(&image); + painter.setPen(QPen(QColor("#3b424b"), 1)); + const int offset = frameNumber % 64; + for (int x = offset; x < image.width(); x += 64) + painter.drawLine(x, 0, x, image.height()); + for (int y = offset; y < image.height(); y += 64) + painter.drawLine(0, y, image.width(), y); + painter.setPen(QColor("#e9edf2")); + painter.setFont(QFont("Microsoft YaHei UI", 28, QFont::DemiBold)); + painter.drawText(image.rect().adjusted(0, -40, 0, 0), Qt::AlignCenter, + QStringLiteral("摄像头实时预览")); + painter.setPen(QColor("#9ca4ad")); + painter.setFont(QFont("Microsoft YaHei UI", 14)); + painter.drawText(image.rect().adjusted(0, 48, 0, 0), Qt::AlignCenter, + QStringLiteral("%1 | DEMO | frame %2") + .arg(session->cameraId).arg(frameNumber)); + const QString decodeCodec = session->codec == QStringLiteral("h265") + ? QStringLiteral("H.265") : QStringLiteral("H.264"); + if (videoFrameReceivedForCamera) + videoFrameReceivedForCamera( + session->cameraId, videoFrameFromImage(image), + QStringLiteral("1280 x 720 | DEMO / %1 | 30.0 FPS | #%2") + .arg(decodeCodec).arg(frameNumber)); + ++frameNumber; + std::this_thread::sleep_for(std::chrono::milliseconds(33)); + } + session->running.store(false); + if (cameraStreamStateChangedForCamera) + cameraStreamStateChangedForCamera( + session->cameraId, false, + QStringLiteral("视频预览已停止,%1 帧,%2 秒") + .arg(frameNumber) + .arg(elapsed.elapsed() / 1000.0, 0, 'f', 1)); + }); + return; + } + +#ifdef CMVR_WITH_GRPC + const std::shared_ptr channel = m_channel; + session->thread = std::thread([this, channel, session]() { + if (session->mode == QStringLiteral("depth")) + runDepthCameraStream(channel, session, false); + else if (session->mode == QStringLiteral("rgbd")) + runDepthCameraStream(channel, session, true); + else + runCameraStream(channel, session); + }); +#else + session->running.store(false); + emit cameraStreamStateChangedForCamera(session->cameraId, false, + QStringLiteral("当前程序未编译 gRPC 支持")); +#endif + } + + void stopCameraStream(const QString &cameraId) + { + stopCameraStreamInternal(cameraId.trimmed()); + } + + void startCameraRecording(const QString &cameraId, const QString &videoPath) + { + const QString command = QStringLiteral("Camera Start Recording"); + if (!ensureConnected(command) || !ensureDeviceId(command, cameraId)) + return; + const QString path = videoPath.trimmed(); + if (path.isEmpty()) { + emit commandFinished(command, false, QStringLiteral("服务端录像路径不能为空")); + return; + } + if (m_cameraRecording) { + emit commandFinished(command, false, QStringLiteral("相机已经在录像")); + return; + } + if (m_demoMode) { + m_cameraRecording = true; + emit cameraRecordingStateChanged(true, + QStringLiteral("演示录像中:%1").arg(path)); + emit commandFinished(command, true, QStringLiteral("录像已开始(演示)")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::StartCameraRecordingCommand::Request request; + fillHeader(request.mutable_header(), cameraId); + request.set_video_path(path.toStdString()); + cmvr::api::StartCameraRecordingCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 3000); + const grpc::Status status = m_camera->StartRecording(&context, request, &response); + const bool success = status.ok() && response.header().success(); + const QString error = status.ok() + ? QString::fromStdString(response.header().error_message()) + : QString::fromStdString(status.error_message()); + if (success) { + m_cameraRecording = true; + emit cameraRecordingStateChanged(true, QStringLiteral("录像中:%1").arg(path)); + } + finish(command, status, response.header().success(), error); +#endif + } + + void stopCameraRecording(const QString &cameraId) + { + const QString command = QStringLiteral("Camera Stop Recording"); + if (!ensureConnected(command) || !ensureDeviceId(command, cameraId)) + return; + if (!m_cameraRecording) { + emit commandFinished(command, false, QStringLiteral("当前没有正在进行的录像")); + return; + } + if (m_demoMode) { + m_cameraRecording = false; + emit cameraRecordingStateChanged(false, QStringLiteral("录像已停止")); + emit commandFinished(command, true, QStringLiteral("录像已停止(演示)")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::StopCameraRecordingCommand::Request request; + fillHeader(request.mutable_header(), cameraId); + cmvr::api::StopCameraRecordingCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 3000); + const grpc::Status status = m_camera->StopRecording(&context, request, &response); + const bool success = status.ok() && response.header().success(); + const QString error = status.ok() + ? QString::fromStdString(response.header().error_message()) + : QString::fromStdString(status.error_message()); + if (success) { + m_cameraRecording = false; + emit cameraRecordingStateChanged(false, QStringLiteral("录像已停止")); + } + finish(command, status, response.header().success(), error); +#endif + } + + void setCameraStreamCodec(const QString &codec) + { + const QString normalized = codec.trimmed().toLower(); + const bool hevc = normalized == QStringLiteral("h265") || + normalized == QStringLiteral("hevc") || + normalized == QStringLiteral("h.265"); + m_defaultCameraCodec = hevc ? QStringLiteral("h265") : QStringLiteral("h264"); + } + + void startSpeakerAudioStream(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("Speaker Stream")) || + !ensureDeviceId(QStringLiteral("Speaker Stream"), deviceId)) + return; + if (m_speakerStreamRunning.load()) { + emit commandFinished(QStringLiteral("Speaker Stream"), false, + QStringLiteral("扬声器音频流已经在运行")); + return; + } + if (m_speakerStreamThread.joinable()) + m_speakerStreamThread.join(); + { + std::lock_guard lock(m_speakerQueueMutex); + m_speakerQueue.clear(); + m_speakerQueueBytes = 0; + } + m_speakerStreamStop.store(false); + m_speakerStreamRunning.store(true); + m_speakerFrames.store(0); + m_speakerBytes.store(0); + emit audioStreamStateChanged(QStringLiteral("SpeakerService"), true, + QStringLiteral("正在建立扬声器客户端音频流...")); + + if (m_demoMode) { + emit audioStreamStateChanged(QStringLiteral("SpeakerService"), true, + QStringLiteral("演示模式:音频帧将在本地计数,不发送到设备")); + return; + } +#ifdef CMVR_WITH_GRPC + const std::shared_ptr channel = m_channel; + m_speakerStreamThread = std::thread([this, channel, deviceId]() { + runSpeakerAudioStream(channel, deviceId); + }); +#else + m_speakerStreamRunning.store(false); + emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false, + QStringLiteral("当前程序未编译 gRPC 支持")); +#endif + } + + void enqueueSpeakerAudioFrame(const QByteArray &data, int sampleRate, int channels, + qint64 pts, int samples) + { + if (!m_speakerStreamRunning.load() || data.isEmpty() || + sampleRate <= 0 || channels <= 0 || samples <= 0) + return; + if (m_demoMode) { + const quint64 frames = ++m_speakerFrames; + const quint64 bytes = m_speakerBytes.fetch_add(data.size()) + data.size(); + emit audioStreamStatistics(QStringLiteral("SpeakerService"), frames, bytes, + pts / 1000 + samples * 1000LL / sampleRate); + return; + } + + SpeakerAudioFrame frame; + frame.data = data; + frame.sampleRate = sampleRate; + frame.channels = channels; + frame.pts = pts; + frame.samples = samples; + { + std::lock_guard lock(m_speakerQueueMutex); + static const int kMaximumQueueBytes = 2 * 1024 * 1024; + while (!m_speakerQueue.empty() && + m_speakerQueueBytes + data.size() > kMaximumQueueBytes) { + m_speakerQueueBytes -= m_speakerQueue.front().data.size(); + m_speakerQueue.pop_front(); + } + m_speakerQueue.push_back(std::move(frame)); + m_speakerQueueBytes += data.size(); + } + m_speakerQueueCondition.notify_one(); + } + + void stopSpeakerAudioStream() + { + stopSpeakerStreamInternal(); + } + + void startMicrophoneAudioStream(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("MicPhone Stream")) || + !ensureDeviceId(QStringLiteral("MicPhone Stream"), deviceId)) + return; + if (m_microphoneStreamRunning.load()) { + emit commandFinished(QStringLiteral("MicPhone Stream"), false, + QStringLiteral("麦克风音频流已经在运行")); + return; + } + if (m_microphoneStreamThread.joinable()) + m_microphoneStreamThread.join(); + m_microphoneStreamStop.store(false); + m_microphoneStreamRunning.store(true); + m_microphoneFrames.store(0); + m_microphoneBytes.store(0); + emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), true, + QStringLiteral("正在建立麦克风服务端音频流...")); + + if (m_demoMode) { + m_microphoneStreamThread = std::thread([this]() { + const int sampleRate = 48000; + const int samples = sampleRate / 50; + const double pi = 3.14159265358979323846; + qint64 sampleIndex = 0; + while (!m_microphoneStreamStop.load()) { + QByteArray pcm(samples * 2, Qt::Uninitialized); + qint16 *output = reinterpret_cast(pcm.data()); + for (int i = 0; i < samples; ++i) { + output[i] = static_cast( + 1800.0 * qSin((sampleIndex + i) * 2.0 * pi * 440.0 / sampleRate)); + } + const qint64 pts = sampleIndex * 1000000LL / sampleRate; + sampleIndex += samples; + const quint64 frames = ++m_microphoneFrames; + const quint64 bytes = m_microphoneBytes.fetch_add(pcm.size()) + pcm.size(); + emit audioFrameReceived(pcm, sampleRate, 1, 0, + QStringLiteral("pcm_s16le"), pts, samples); + emit audioStreamStatistics(QStringLiteral("MicPhoneService"), frames, bytes, + sampleIndex * 1000LL / sampleRate); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + m_microphoneStreamRunning.store(false); + emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, + QStringLiteral("麦克风音频拉流已停止")); + }); + emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), true, + QStringLiteral("演示模式:正在播放本地测试音")); + return; + } +#ifdef CMVR_WITH_GRPC + const std::shared_ptr channel = m_channel; + m_microphoneStreamThread = std::thread([this, channel, deviceId]() { + runMicrophoneAudioStream(channel, deviceId); + }); +#else + m_microphoneStreamRunning.store(false); + emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, + QStringLiteral("当前程序未编译 gRPC 支持")); +#endif + } + + void stopMicrophoneAudioStream() + { + stopMicrophoneStreamInternal(); + } + + void systemRefresh() + { + if (!ensureConnected(QStringLiteral("System Refresh"))) + return; + if (m_demoMode) { + QVariantMap info; + info.insert(QStringLiteral("name"), QStringLiteral("CMVR Demo Controller")); + info.insert(QStringLiteral("version"), QStringLiteral("demo-1.0")); + QString platform = QSysInfo::prettyProductName(); + if (platform.isEmpty()) + platform = QSysInfo::productType(); + info.insert(QStringLiteral("os"), platform + QStringLiteral(" / simulator")); + info.insert(QStringLiteral("architecture"), QSysInfo::currentCpuArchitecture()); + emit systemInfoReceived(info); + emit systemStatusReceived(34.0, 48.0, 62.0, demoDeviceList()); + emit commandFinished(QStringLiteral("System Refresh"), true, QStringLiteral("系统信息已刷新")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::GetSystemInfoCommand::Request request; + cmvr::api::GetSystemInfoCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 1200); + const grpc::Status infoStatus = m_system->GetSystemInfo(&context, request, &response); + if (infoStatus.ok() && response.header().success()) { + QVariantMap info; + info.insert(QStringLiteral("name"), QString::fromStdString(response.system_name())); + info.insert(QStringLiteral("version"), QString::fromStdString(response.version())); + info.insert(QStringLiteral("description"), QString::fromStdString(response.description())); + info.insert(QStringLiteral("os"), QString::fromStdString(response.os())); + info.insert(QStringLiteral("kernel"), QString::fromStdString(response.kernel_version())); + info.insert(QStringLiteral("architecture"), QString::fromStdString(response.architecture())); + emit systemInfoReceived(info); + } + + cmvr::api::GetSystemStatusCommand::Request statusRequest; + cmvr::api::GetSystemStatusCommand::Feedback statusResponse; + grpc::ClientContext statusContext; + setDeadline(statusContext, 1200); + const grpc::Status status = m_system->GetSystemStatus( + &statusContext, statusRequest, &statusResponse); + if (status.ok() && statusResponse.header().success()) { + const double memory = statusResponse.mem_total_mb() > 0 + ? statusResponse.mem_used_mb() * 100.0 / statusResponse.mem_total_mb() : 0.0; + const double disk = statusResponse.disk_total_gb() > 0 + ? statusResponse.disk_used_gb() * 100.0 / statusResponse.disk_total_gb() : 0.0; + emit systemStatusReceived(statusResponse.cpu_usage(), memory, disk, + deviceListFromStatus(statusResponse)); + } + + if (!infoStatus.ok() || !response.header().success()) { + finish(QStringLiteral("System Refresh"), infoStatus, response.header().success(), + QString::fromStdString(response.header().error_message())); + } else { + finish(QStringLiteral("System Refresh"), status, statusResponse.header().success(), + QString::fromStdString(statusResponse.header().error_message())); + } +#endif + } + + void systemStopAll(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("System StopAll")) || + !ensureDeviceId(QStringLiteral("System StopAll"), deviceId)) + return; + if (m_demoMode) { + emit commandFinished(QStringLiteral("System StopAll"), true, QStringLiteral("全局停止命令已执行")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::StopAllCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + cmvr::api::StopAllCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 1800); + const grpc::Status status = m_system->StopAll(&context, request, &response); + finish(QStringLiteral("System StopAll"), status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + + void agvRefresh(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("AGV Refresh")) || + !ensureDeviceId(QStringLiteral("AGV Refresh"), deviceId)) + return; + if (m_demoMode) { + QVariantMap state; + state.insert(QStringLiteral("connected"), true); + state.insert(QStringLiteral("timestamp"), QDateTime::currentMSecsSinceEpoch() / 1000.0); + state.insert(QStringLiteral("mode"), 1); + state.insert(QStringLiteral("localized"), true); + state.insert(QStringLiteral("moving"), false); + state.insert(QStringLiteral("fault"), false); + state.insert(QStringLiteral("emergency"), false); + state.insert(QStringLiteral("map"), QStringLiteral("demo_map")); + state.insert(QStringLiteral("station"), QStringLiteral("HOME")); + state.insert(QStringLiteral("battery"), 0.82); + state.insert(QStringLiteral("voltage"), 49.2); + state.insert(QStringLiteral("current"), -2.9); + state.insert(QStringLiteral("temperature"), 28.0); + state.insert(QStringLiteral("x"), 1.24); + state.insert(QStringLiteral("y"), -0.36); + state.insert(QStringLiteral("theta"), 0.12); + QVariantMap navigation; + navigation.insert(QStringLiteral("state"), 0); + navigation.insert(QStringLiteral("type"), 0); + navigation.insert(QStringLiteral("progress"), 0.0); + navigation.insert(QStringLiteral("message"), QStringLiteral("空闲")); + emit agvStateReceived(state, navigation); + emit commandFinished(QStringLiteral("AGV Refresh"), true, QStringLiteral("AGV 状态已刷新")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::AgvRuntimeStateCommand::Request stateRequest; + fillHeader(stateRequest.mutable_header(), deviceId); + cmvr::api::AgvRuntimeStateCommand::Feedback stateResponse; + grpc::ClientContext stateContext; + setDeadline(stateContext, 1000); + const grpc::Status stateStatus = m_agv->getRuntimeState(&stateContext, stateRequest, &stateResponse); + + cmvr::api::AgvNavigationStatusCommand::Request navRequest; + fillHeader(navRequest.mutable_header(), deviceId); + cmvr::api::AgvNavigationStatusCommand::Feedback navResponse; + grpc::ClientContext navContext; + setDeadline(navContext, 1000); + const grpc::Status navStatus = m_agv->getNavigationStatus(&navContext, navRequest, &navResponse); + + if (stateStatus.ok() && stateResponse.header().success()) { + const auto &source = stateResponse.state(); + QVariantMap state; + state.insert(QStringLiteral("connected"), source.connected()); + state.insert(QStringLiteral("timestamp"), source.timestamp()); + state.insert(QStringLiteral("mode"), source.mode()); + state.insert(QStringLiteral("localized"), source.localized()); + state.insert(QStringLiteral("moving"), source.moving()); + state.insert(QStringLiteral("fault"), source.fault()); + state.insert(QStringLiteral("emergency"), source.emergency_stopped()); + state.insert(QStringLiteral("map"), QString::fromStdString(source.current_map())); + state.insert(QStringLiteral("station"), QString::fromStdString(source.current_station())); + state.insert(QStringLiteral("battery"), source.battery().percentage()); + state.insert(QStringLiteral("voltage"), source.battery().voltage()); + state.insert(QStringLiteral("current"), source.battery().current()); + state.insert(QStringLiteral("temperature"), source.battery().temperature()); + state.insert(QStringLiteral("x"), source.pose().x()); + state.insert(QStringLiteral("y"), source.pose().y()); + state.insert(QStringLiteral("theta"), source.pose().theta()); + state.insert(QStringLiteral("vx"), source.velocity().vx()); + state.insert(QStringLiteral("vy"), source.velocity().vy()); + state.insert(QStringLiteral("wz"), source.velocity().wz()); + state.insert(QStringLiteral("error"), QString::fromStdString(source.last_error())); + QVariantMap navigation; + if (navStatus.ok() && navResponse.header().success()) { + navigation.insert(QStringLiteral("state"), navResponse.status().state()); + navigation.insert(QStringLiteral("type"), navResponse.status().type()); + navigation.insert(QStringLiteral("progress"), navResponse.status().progress()); + navigation.insert(QStringLiteral("message"), QString::fromStdString(navResponse.status().message())); + } + emit agvStateReceived(state, navigation); + } + finish(QStringLiteral("AGV Refresh"), stateStatus, stateResponse.header().success(), + QString::fromStdString(stateResponse.header().error_message())); +#endif + } + + void agvNavigatePose(const QString &deviceId, double x, double y, double theta, double maxSpeed) + { + if (!ensureConnected(QStringLiteral("AGV NavigateToPose")) || + !ensureDeviceId(QStringLiteral("AGV NavigateToPose"), deviceId)) + return; + if (m_demoMode) { + emit commandFinished(QStringLiteral("AGV NavigateToPose"), true, + QStringLiteral("目标位姿 (%1, %2, %3) 已下发").arg(x).arg(y).arg(theta)); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::AgvNavigateToPoseCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + request.mutable_pose()->set_x(x); + request.mutable_pose()->set_y(y); + request.mutable_pose()->set_theta(theta); + request.mutable_options()->set_max_speed(maxSpeed); + request.mutable_options()->set_asynchronous(true); + cmvr::api::AgvNavigateToPoseCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 2500); + const grpc::Status status = m_agv->navigateToPose(&context, request, &response); + finish(QStringLiteral("AGV NavigateToPose"), status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + + void agvNavigateStation(const QString &deviceId, const QString &stationId, double maxSpeed) + { + if (!ensureConnected(QStringLiteral("AGV NavigateToStation")) || + !ensureDeviceId(QStringLiteral("AGV NavigateToStation"), deviceId)) + return; + if (stationId.trimmed().isEmpty()) { + emit commandFinished(QStringLiteral("AGV NavigateToStation"), false, QStringLiteral("站点 ID 不能为空")); + return; + } + if (m_demoMode) { + emit commandFinished(QStringLiteral("AGV NavigateToStation"), true, + QStringLiteral("目标站点 %1 已下发").arg(stationId)); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::AgvNavigateToStationCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + request.set_station_id(stationId.toStdString()); + request.mutable_options()->set_max_speed(maxSpeed); + request.mutable_options()->set_asynchronous(true); + cmvr::api::AgvNavigateToStationCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 2500); + const grpc::Status status = m_agv->navigateToStation(&context, request, &response); + finish(QStringLiteral("AGV NavigateToStation"), status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + + void agvFollowPath(const QString &deviceId, const QVariantList &path, double maxSpeed) + { + const QString command = QStringLiteral("AGV FollowPath"); + if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) + return; + if (path.isEmpty()) { + emit commandFinished(command, false, QStringLiteral("路径至少需要包含一个有效路径段")); + return; + } + if (m_demoMode) { + emit commandFinished(command, true, + QStringLiteral("包含 %1 个路径段的导航任务已下发").arg(path.size())); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::AgvFollowPathCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + for (const QVariant &entry : path) { + const QVariantMap segmentValue = entry.toMap(); + const QString source = segmentValue.value(QStringLiteral("sourceStation")).toString().trimmed(); + const QString target = segmentValue.value(QStringLiteral("targetStation")).toString().trimmed(); + if (source.isEmpty() || target.isEmpty()) { + emit commandFinished(command, false, QStringLiteral("路径段的起点和终点不能为空")); + return; + } + cmvr::msgs::AgvPathSegment *segment = request.add_path(); + segment->set_source_station(source.toStdString()); + segment->set_target_station(target.toStdString()); + } + request.mutable_options()->set_max_speed(maxSpeed); + request.mutable_options()->set_asynchronous(true); + cmvr::api::AgvFollowPathCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 2500); + const grpc::Status status = m_agv->followPath(&context, request, &response); + finish(command, status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + + void agvVelocity(const QString &deviceId, double vx, double vy, double wz) + { + if (!ensureConnected(QStringLiteral("AGV SetVelocity")) || + !ensureDeviceId(QStringLiteral("AGV SetVelocity"), deviceId)) + return; + if (m_demoMode) { + emit commandFinished(QStringLiteral("AGV SetVelocity"), true, QStringLiteral("底盘速度已下发")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::AgvSetVelocityCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + request.mutable_velocity()->set_vx(vx); + request.mutable_velocity()->set_vy(vy); + request.mutable_velocity()->set_wz(wz); + cmvr::api::AgvSetVelocityCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 1200); + const grpc::Status status = m_agv->setVelocity(&context, request, &response); + finish(QStringLiteral("AGV SetVelocity"), status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + + void agvAction(const QString &deviceId, const QString &action) + { + const QString command = QStringLiteral("AGV %1").arg(action); + if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) + return; + if (m_demoMode) { + emit commandFinished(command, true, QStringLiteral("AGV 操作已执行")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::CommandHeader::Request request; + fillHeader(&request, deviceId); + cmvr::api::CommandHeader::Feedback response; + grpc::ClientContext context; + setDeadline(context, 1500); + grpc::Status status; + if (action == QStringLiteral("EmergencyStop")) + status = m_agv->emergencyStop(&context, request, &response); + else if (action == QStringLiteral("ClearFault")) + status = m_agv->clearFault(&context, request, &response); + else if (action == QStringLiteral("Pause")) + status = m_agv->pauseNavigation(&context, request, &response); + else if (action == QStringLiteral("Resume")) + status = m_agv->resumeNavigation(&context, request, &response); + else if (action == QStringLiteral("Cancel")) + status = m_agv->cancelNavigation(&context, request, &response); + else if (action == QStringLiteral("StopVelocity")) + status = m_agv->stopVelocityControl(&context, request, &response); + else if (action == QStringLiteral("StopMapping")) + status = m_agv->stopMapping(&context, request, &response); + else { + emit commandFinished(command, false, QStringLiteral("未知 AGV 操作")); + return; + } + finish(command, status, response.success(), QString::fromStdString(response.error_message())); +#endif + } + + void agvInventory(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("AGV Inventory")) || + !ensureDeviceId(QStringLiteral("AGV Inventory"), deviceId)) + return; + if (m_demoMode) { + QVariantList stations; + QVariantMap home; + home.insert(QStringLiteral("id"), QStringLiteral("HOME")); + home.insert(QStringLiteral("type"), QStringLiteral("charge")); + home.insert(QStringLiteral("x"), 0.0); + home.insert(QStringLiteral("y"), 0.0); + stations.append(home); + const QStringList maps = {QStringLiteral("demo_map"), QStringLiteral("warehouse")}; + emit agvInventoryReceived(maps, stations); + emit commandFinished(QStringLiteral("AGV Inventory"), true, QStringLiteral("地图与站点已刷新")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::AgvListMapsCommand::Request mapsRequest; + fillHeader(mapsRequest.mutable_header(), deviceId); + cmvr::api::AgvListMapsCommand::Feedback mapsResponse; + grpc::ClientContext mapsContext; + setDeadline(mapsContext, 1200); + const grpc::Status mapsStatus = m_agv->listMaps(&mapsContext, mapsRequest, &mapsResponse); + + cmvr::api::AgvListStationsCommand::Request stationsRequest; + fillHeader(stationsRequest.mutable_header(), deviceId); + cmvr::api::AgvListStationsCommand::Feedback stationsResponse; + grpc::ClientContext stationsContext; + setDeadline(stationsContext, 1200); + const grpc::Status stationsStatus = m_agv->listStations(&stationsContext, stationsRequest, &stationsResponse); + + if (mapsStatus.ok() && mapsResponse.header().success()) { + QStringList maps; + for (const auto &mapName : mapsResponse.maps()) + maps.append(QString::fromStdString(mapName)); + QVariantList stations; + if (stationsStatus.ok() && stationsResponse.header().success()) { + for (const auto &source : stationsResponse.stations()) { + QVariantMap station; + station.insert(QStringLiteral("id"), QString::fromStdString(source.id())); + station.insert(QStringLiteral("type"), QString::fromStdString(source.type())); + station.insert(QStringLiteral("description"), QString::fromStdString(source.description())); + station.insert(QStringLiteral("x"), source.pose().x()); + station.insert(QStringLiteral("y"), source.pose().y()); + station.insert(QStringLiteral("theta"), source.pose().theta()); + stations.append(station); + } + } + emit agvInventoryReceived(maps, stations); + } + finish(QStringLiteral("AGV Inventory"), mapsStatus, mapsResponse.header().success(), + QString::fromStdString(mapsResponse.header().error_message())); +#endif + } + + void agvSwitchMap(const QString &deviceId, const QString &mapName) + { + if (!ensureConnected(QStringLiteral("AGV SwitchMap")) || + !ensureDeviceId(QStringLiteral("AGV SwitchMap"), deviceId)) + return; + if (mapName.trimmed().isEmpty()) { + emit commandFinished(QStringLiteral("AGV SwitchMap"), false, QStringLiteral("地图名称不能为空")); + return; + } + if (m_demoMode) { + emit commandFinished(QStringLiteral("AGV SwitchMap"), true, + QStringLiteral("已切换到地图 %1").arg(mapName)); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::AgvMapCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + request.set_map_name(mapName.toStdString()); + cmvr::api::AgvMapCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 2500); + const grpc::Status status = m_agv->switchMap(&context, request, &response); + finish(QStringLiteral("AGV SwitchMap"), status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + + void startAgvMapStream(const QString &deviceId, const QString &mapName, + int dimension, bool snapshot, bool incremental) + { + if (!ensureConnected(QStringLiteral("AGV StreamMap")) || + !ensureDeviceId(QStringLiteral("AGV StreamMap"), deviceId)) + return; + stopAgvMapStreamInternal(); + m_agvMapStreamStop.store(false); + m_agvMapStreamRunning.store(true); + emit agvMapStreamStateChanged(true, QStringLiteral("正在等待地图数据")); + + if (m_demoMode) { + QImage image(1280, 720, QImage::Format_RGB32); + image.fill(QColor(QStringLiteral("#eef2f6"))); + QPainter painter(&image); + painter.setRenderHint(QPainter::Antialiasing); + painter.setPen(QPen(QColor(QStringLiteral("#d3dde6")), 1)); + for (int x = 60; x < image.width(); x += 80) + painter.drawLine(x, 30, x, image.height() - 30); + for (int y = 40; y < image.height(); y += 60) + painter.drawLine(30, y, image.width() - 30, y); + const QVector stations = { + QPointF(180, 160), QPointF(460, 220), QPointF(760, 150), + QPointF(1050, 260), QPointF(850, 500), QPointF(400, 540) + }; + for (int i = 1; i < stations.size(); ++i) { + painter.setPen(QPen(QColor(QStringLiteral("#9db7ce")), 4)); + painter.drawLine(stations.at(i - 1), stations.at(i)); + } + for (int i = 0; i < stations.size(); ++i) { + painter.setPen(Qt::NoPen); + painter.setBrush(QColor(QStringLiteral("#218c74"))); + painter.drawEllipse(stations.at(i), 11, 11); + painter.setPen(QColor(QStringLiteral("#26323d"))); + painter.drawText(stations.at(i) + QPointF(15, -10), + QStringLiteral("STATION_%1").arg(i + 1)); + } + painter.setBrush(QColor(QStringLiteral("#237ddd"))); + painter.setPen(Qt::NoPen); + QPolygonF robot; + robot << QPointF(290, 320) << QPointF(260, 338) + << QPointF(260, 302); + painter.drawPolygon(robot); + painter.end(); + emit agvMapFrameReceived(image, QStringLiteral("演示 2D 地图 · 6 个站点")); + return; + } + +#ifdef CMVR_WITH_GRPC + m_agvMapStreamThread = std::thread( + [this, deviceId, mapName, dimension, snapshot, incremental]() { + cmvr::api::AgvMapStreamCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + request.set_map_name(mapName.toStdString()); + request.set_dimension(static_cast(dimension)); + request.set_snapshot(snapshot); + request.set_incremental(incremental); + request.set_max_chunk_bytes(1024 * 1024); + + grpc::ClientContext context; + { + std::lock_guard lock(m_agvMapStreamContextMutex); + m_agvMapStreamContext = &context; + } + std::unique_ptr> + reader = m_agv->streamMap(&context, request); + cmvr::api::AgvMapStreamCommand::Feedback response; + while (!m_agvMapStreamStop.load() && reader->Read(&response)) { + if (!response.header().success()) + continue; + const auto &update = response.update(); + QImage image; + QString detail; + if (update.has_map_2d()) { + const auto &map = update.map_2d(); + const int sourceWidth = static_cast(map.width()); + const int sourceHeight = static_cast(map.height()); + if (sourceWidth <= 0 || sourceHeight <= 0) + continue; + const double scale = qMin( + 1.0, qMin(1600.0 / sourceWidth, 1000.0 / sourceHeight)); + const int width = qMax(1, qRound(sourceWidth * scale)); + const int height = qMax(1, qRound(sourceHeight * scale)); + image = QImage(width, height, QImage::Format_RGB32); + for (int y = 0; y < height; ++y) { + QRgb *line = reinterpret_cast( + image.scanLine(height - 1 - y)); + const int sourceY = qMin(sourceHeight - 1, + qFloor(y / scale)); + for (int x = 0; x < width; ++x) { + const int sourceX = qMin(sourceWidth - 1, + qFloor(x / scale)); + const int index = sourceY * sourceWidth + sourceX; + const int value = index < map.data_size() + ? map.data(index) : -1; + if (value < 0) + line[x] = qRgb(205, 212, 219); + else if (value == 0) + line[x] = qRgb(248, 250, 252); + else { + const int shade = qBound(35, 235 - value * 2, 210); + line[x] = qRgb(shade, shade, shade); + } + } + } + QPainter painter(&image); + painter.setRenderHint(QPainter::Antialiasing); + const double resolution = map.resolution() > 0.0 + ? map.resolution() : 1.0; + for (const auto &object : map.objects()) { + QPolygonF geometry; + for (const auto &point : object.points()) { + geometry.append(QPointF( + (point.x() - map.origin().x()) / resolution * scale, + height - (point.y() - map.origin().y()) / + resolution * scale)); + } + painter.setPen(QPen(QColor(QStringLiteral("#218c74")), 2)); + painter.setBrush(QColor(33, 140, 116, 70)); + if (geometry.size() == 1) + painter.drawEllipse(geometry.first(), 6, 6); + else if (geometry.size() > 1) + painter.drawPolyline(geometry); + if (!geometry.isEmpty()) { + painter.setPen(QColor(QStringLiteral("#145da8"))); + painter.drawText(geometry.first() + QPointF(8, -6), + QString::fromStdString(object.id())); + } + } + painter.end(); + detail = QStringLiteral("%1 · 2D · %2×%3 · seq %4") + .arg(QString::fromStdString(update.map_id())) + .arg(sourceWidth).arg(sourceHeight) + .arg(static_cast(update.sequence())); + } else if (update.has_map_3d()) { + const auto &map = update.map_3d(); + image = QImage(1280, 720, QImage::Format_RGB32); + image.fill(QColor(QStringLiteral("#eef2f6"))); + if (map.points_size() > 0) { + double minX = map.points(0).x(), maxX = minX; + double minY = map.points(0).y(), maxY = minY; + const int step = qMax(1, map.points_size() / 80000); + for (int i = 0; i < map.points_size(); i += step) { + minX = qMin(minX, map.points(i).x()); + maxX = qMax(maxX, map.points(i).x()); + minY = qMin(minY, map.points(i).y()); + maxY = qMax(maxY, map.points(i).y()); + } + if (qFuzzyCompare(minX, maxX)) { minX -= 1.0; maxX += 1.0; } + if (qFuzzyCompare(minY, maxY)) { minY -= 1.0; maxY += 1.0; } + QPainter painter(&image); + painter.setPen(QColor(QStringLiteral("#456b87"))); + for (int i = 0; i < map.points_size(); i += step) { + const auto &point = map.points(i); + painter.drawPoint(QPointF( + 30.0 + (point.x() - minX) / (maxX - minX) * 1220.0, + 690.0 - (point.y() - minY) / (maxY - minY) * 660.0)); + } + painter.end(); + } + detail = QStringLiteral("%1 · 3D · %2 points · seq %3") + .arg(QString::fromStdString(update.map_id())) + .arg(map.points_size()) + .arg(static_cast(update.sequence())); + } + if (!image.isNull()) + emit agvMapFrameReceived(image, detail); + } + const grpc::Status status = reader->Finish(); + { + std::lock_guard lock(m_agvMapStreamContextMutex); + m_agvMapStreamContext = nullptr; + } + m_agvMapStreamRunning.store(false); + const QString detail = m_agvMapStreamStop.load() + ? QStringLiteral("地图流已停止") + : status.ok() ? QStringLiteral("地图流已结束") + : QString::fromStdString(status.error_message()); + emit agvMapStreamStateChanged(false, detail); + }); +#endif + } + + void stopAgvMapStream() + { + stopAgvMapStreamInternal(); + emit agvMapStreamStateChanged(false, QStringLiteral("地图流已停止")); + } + + void invokeRpc(const QString &serviceName, const QString &methodName, + const QString &requestJson, const QString &deviceId) + { + const QString command = QStringLiteral("%1.%2").arg(serviceName, methodName); + if (!ensureConnected(command)) { + emit rpcFinished(serviceName, methodName, false, + QStringLiteral("{\"error\":\"设备尚未连接\"}")); + return; + } + if (m_demoMode) { + QJsonObject result; + result.insert(QStringLiteral("demo"), true); + result.insert(QStringLiteral("service"), serviceName); + result.insert(QStringLiteral("method"), methodName); + result.insert(QStringLiteral("deviceId"), deviceId); + result.insert(QStringLiteral("message"), QStringLiteral("演示模式调用成功")); + emit rpcFinished(serviceName, methodName, true, + QString::fromUtf8(QJsonDocument(result).toJson(QJsonDocument::Indented))); + emit commandFinished(command, true, QStringLiteral("演示模式 RPC 调用完成")); + return; + } +#ifdef CMVR_WITH_GRPC + const google::protobuf::ServiceDescriptor *service = + google::protobuf::DescriptorPool::generated_pool()->FindServiceByName( + serviceName.toStdString()); + const google::protobuf::MethodDescriptor *method = + service ? service->FindMethodByName(methodName.toStdString()) : nullptr; + if (!method || !m_generic) { + const QString error = QStringLiteral("找不到 RPC 描述符:%1").arg(command); + emit rpcFinished(serviceName, methodName, false, + QStringLiteral("{\"error\":\"%1\"}").arg(error)); + emit commandFinished(command, false, error); + return; + } + + google::protobuf::DynamicMessageFactory factory; + const google::protobuf::Message *requestPrototype = + factory.GetPrototype(method->input_type()); + const google::protobuf::Message *responsePrototype = + factory.GetPrototype(method->output_type()); + if (!requestPrototype || !responsePrototype) { + const QString error = QStringLiteral("无法创建 protobuf 动态消息"); + emit rpcFinished(serviceName, methodName, false, + QStringLiteral("{\"error\":\"%1\"}").arg(error)); + return; + } + + QStringList requestDocuments; + QJsonParseError parseError; + const QJsonDocument jsonDocument = QJsonDocument::fromJson(requestJson.toUtf8(), &parseError); + if (parseError.error != QJsonParseError::NoError) { + const QString error = QStringLiteral("请求 JSON 无效:%1").arg(parseError.errorString()); + emit rpcFinished(serviceName, methodName, false, + QStringLiteral("{\"error\":\"%1\"}").arg(error)); + return; + } + if (jsonDocument.isArray()) { + for (const QJsonValue &value : jsonDocument.array()) + requestDocuments.append(QString::fromUtf8( + QJsonDocument(value.toObject()).toJson(QJsonDocument::Compact))); + } else { + requestDocuments.append(QString::fromUtf8( + QJsonDocument(jsonDocument.object()).toJson(QJsonDocument::Compact))); + } + if (requestDocuments.isEmpty()) + requestDocuments.append(QStringLiteral("{}")); + + std::vector> requests; + std::vector requestBuffers; + google::protobuf::util::JsonParseOptions jsonOptions; + jsonOptions.ignore_unknown_fields = false; + for (const QString &document : requestDocuments) { + std::unique_ptr request(requestPrototype->New()); + const auto jsonStatus = google::protobuf::util::JsonStringToMessage( + document.toStdString(), request.get(), jsonOptions); + if (!jsonStatus.ok()) { + const QString error = QStringLiteral("protobuf JSON 转换失败:%1") + .arg(QString::fromStdString(jsonStatus.ToString())); + emit rpcFinished(serviceName, methodName, false, + QStringLiteral("{\"error\":\"%1\"}").arg(error)); + return; + } + setDynamicDeviceId(request.get(), deviceId); + std::string serialized; + request->SerializeToString(&serialized); + grpc::Slice slice(serialized); + requestBuffers.emplace_back(&slice, 1); + requests.emplace_back(std::move(request)); + } + + const std::string path = QStringLiteral("/%1/%2").arg(serviceName, methodName).toStdString(); + grpc::Status grpcStatus; + QJsonArray streamResponses; + QString unaryResponse; + bool transportOk = false; + if (!method->client_streaming() && !method->server_streaming()) { + grpc::ClientContext context; + setDeadline(context, 4000); + grpc::CompletionQueue queue; + grpc::ByteBuffer responseBuffer; + std::unique_ptr call = + m_generic->PrepareUnaryCall(&context, path, requestBuffers.front(), &queue); + call->StartCall(); + call->Finish(&responseBuffer, &grpcStatus, reinterpret_cast(1)); + void *tag = nullptr; + bool eventOk = false; + transportOk = queue.Next(&tag, &eventOk) && eventOk && + tag == reinterpret_cast(1) && grpcStatus.ok(); + if (transportOk) + unaryResponse = byteBufferToJson(responseBuffer, responsePrototype, factory); + queue.Shutdown(); + } else { + grpc::ClientContext context; + setDeadline(context, 5000); + grpc::CompletionQueue queue; + std::unique_ptr call = + m_generic->PrepareCall(&context, path, &queue); + void *tag = nullptr; + bool eventOk = false; + call->StartCall(reinterpret_cast(1)); + bool started = queue.Next(&tag, &eventOk) && eventOk; + for (int index = 0; started && index < static_cast(requestBuffers.size()); ++index) { + call->Write(requestBuffers.at(index), reinterpret_cast(2)); + started = queue.Next(&tag, &eventOk) && eventOk; + } + if (started) { + call->WritesDone(reinterpret_cast(3)); + queue.Next(&tag, &eventOk); + } + while (started && streamResponses.size() < 100) { + grpc::ByteBuffer responseBuffer; + call->Read(&responseBuffer, reinterpret_cast(4)); + if (!queue.Next(&tag, &eventOk) || !eventOk) + break; + const QString response = byteBufferToJson(responseBuffer, responsePrototype, factory); + QJsonParseError responseError; + const QJsonDocument parsed = QJsonDocument::fromJson(response.toUtf8(), &responseError); + streamResponses.append(responseError.error == QJsonParseError::NoError + ? QJsonValue(parsed.object()) : QJsonValue(response)); + } + if (streamResponses.size() >= 100) + context.TryCancel(); + call->Finish(&grpcStatus, reinterpret_cast(5)); + queue.Next(&tag, &eventOk); + transportOk = grpcStatus.ok() || + (grpcStatus.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED && + !streamResponses.isEmpty()); + queue.Shutdown(); + } + + QString result; + if (transportOk) { + result = method->client_streaming() || method->server_streaming() + ? QString::fromUtf8(QJsonDocument(streamResponses).toJson(QJsonDocument::Indented)) + : unaryResponse; + } else { + QJsonObject error; + error.insert(QStringLiteral("grpcCode"), grpcStatus.error_code()); + error.insert(QStringLiteral("error"), QString::fromStdString(grpcStatus.error_message())); + result = QString::fromUtf8(QJsonDocument(error).toJson(QJsonDocument::Indented)); + } + emit rpcFinished(serviceName, methodName, transportOk, result); + emit commandFinished(command, transportOk, + transportOk ? QStringLiteral("RPC 调用完成") + : QString::fromStdString(grpcStatus.error_message())); +#else + Q_UNUSED(requestJson) + Q_UNUSED(deviceId) +#endif + } + + std::function connectionChanged; + std::function armInfoReceived; + std::function tcpCalibrationPoseReceived; + std::function + armFramesReceived; + std::function telemetryReceived; + std::function + armTelemetryHealthChanged; + std::function systemStatusReceived; + std::function systemInfoReceived; + std::function imageReceived; + std::function handEyeImageReceived; + std::function touchRgbdImageReceived; + std::function + videoFrameReceivedForCamera; + std::function + cameraStreamStateChangedForCamera; + std::function cameraRecordingStateChanged; + std::function agvStateReceived; + std::function agvInventoryReceived; + std::function agvMapFrameReceived; + std::function agvMapStreamStateChanged; + std::function rpcFinished; + std::function audioStreamStateChanged; + std::function audioStreamStatistics; + std::function + audioFrameReceived; + std::function configurationConnectionChanged; + std::function + configurationFilesReceived; + std::function configurationFileReceived; + std::function + configurationValidationFinished; + std::function + configurationSaveFinished; + std::function commandFinished; + std::function logMessage; + +private: +#ifdef CMVR_WITH_GRPC + bool ensureConfigurationConnected(const QString &operation) + { + if (m_configConnected && m_configuration) + return true; + emit configurationConnectionChanged( + false, QStringLiteral("%1失败:配置服务未连接").arg(operation)); + return false; + } + + static QString configurationError(const grpc::Status &status, + const std::string &applicationError) + { + if (!status.ok()) + return QString::fromStdString(status.error_message()); + return QString::fromStdString(applicationError); + } + + std::shared_ptr prepareArmMotionSession(const QString &command) + { + std::shared_ptr previous; + { + std::lock_guard lock(m_armMotionSessionMutex); + previous = m_armMotionSession; + if (previous && previous->running.load()) { + emit commandFinished(command, false, + QStringLiteral("已有机械臂运动命令正在执行")); + return {}; + } + m_armMotionSession.reset(); + } + if (previous && previous->thread.joinable() && + previous->thread.get_id() != std::this_thread::get_id()) { + previous->thread.join(); + } + + auto session = std::make_shared(); + session->running.store(true); + { + std::lock_guard lock(m_armMotionSessionMutex); + m_armMotionSession = session; + } + return session; + } + + template + void startArmMotion(const QString &command, Request request, Call call) + { + const auto session = prepareArmMotionSession(command); + if (!session) + return; + const auto channel = m_channel; + session->thread = std::thread( + [this, channel, session, command, request = std::move(request), call]() mutable { + grpc::ClientContext context; + setDeadline(context, kArmMotionTimeoutMs); + { + std::lock_guard lock(session->contextMutex); + session->context = &context; + if (session->stop.load()) + context.TryCancel(); + } + try { + auto stub = cmvr::api::ArmService::NewStub(channel); + Response response; + const grpc::Status status = call(*stub, &context, request, &response); + finish(command, status, response.header().success(), + QString::fromStdString(response.header().error_message())); + } catch (const std::exception &error) { + emit commandFinished(command, false, + QStringLiteral("机械臂运动调用异常:%1") + .arg(QString::fromLocal8Bit(error.what()))); + } catch (...) { + emit commandFinished(command, false, + QStringLiteral("机械臂运动调用发生未知异常")); + } + { + std::lock_guard lock(session->contextMutex); + session->context = nullptr; + } + session->running.store(false); + }); + } + + static void setDynamicDeviceId(google::protobuf::Message *request, + const QString &deviceId) + { + if (!request || deviceId.trimmed().isEmpty()) + return; + const google::protobuf::FieldDescriptor *headerField = + request->GetDescriptor()->FindFieldByName("header"); + if (!headerField || headerField->cpp_type() != + google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) + return; + google::protobuf::Message *header = + request->GetReflection()->MutableMessage(request, headerField); + const google::protobuf::FieldDescriptor *deviceField = + header->GetDescriptor()->FindFieldByName("device_id"); + if (deviceField) + header->GetReflection()->SetString(header, deviceField, deviceId.toStdString()); + } + + static QString byteBufferToJson(const grpc::ByteBuffer &buffer, + const google::protobuf::Message *prototype, + google::protobuf::DynamicMessageFactory &factory) + { + Q_UNUSED(factory) + std::vector slices; + buffer.Dump(&slices); + std::string serialized; + for (const grpc::Slice &slice : slices) + serialized.append(reinterpret_cast(slice.begin()), slice.size()); + std::unique_ptr response(prototype->New()); + if (!response->ParseFromString(serialized)) + return QStringLiteral("{\"error\":\"无法解析 protobuf 反馈\"}"); + std::string json; + google::protobuf::util::JsonPrintOptions options; + options.add_whitespace = true; + options.always_print_primitive_fields = true; + const auto status = google::protobuf::util::MessageToJsonString(*response, &json, options); + return status.ok() ? QString::fromStdString(json) + : QStringLiteral("{\"error\":\"%1\"}") + .arg(QString::fromStdString(status.ToString())); + } +#endif + + void stopArmMotionInternal() + { + std::shared_ptr session; + { + std::lock_guard lock(m_armMotionSessionMutex); + session = m_armMotionSession; + } + if (!session) + return; + + session->stop.store(true); +#ifdef CMVR_WITH_GRPC + { + std::lock_guard lock(session->contextMutex); + if (session->context) + session->context->TryCancel(); + } +#endif + if (session->thread.joinable() && + session->thread.get_id() != std::this_thread::get_id()) { + session->thread.join(); + } + session->running.store(false); + { + std::lock_guard lock(m_armMotionSessionMutex); + if (m_armMotionSession == session) + m_armMotionSession.reset(); + } + } + + void stopAgvMapStreamInternal() + { + m_agvMapStreamStop.store(true); +#ifdef CMVR_WITH_GRPC + { + std::lock_guard lock(m_agvMapStreamContextMutex); + if (m_agvMapStreamContext) + m_agvMapStreamContext->TryCancel(); + } +#endif + if (m_agvMapStreamThread.joinable() && + m_agvMapStreamThread.get_id() != std::this_thread::get_id()) + m_agvMapStreamThread.join(); + m_agvMapStreamRunning.store(false); + } + + void stopCameraStreamInternal(const QString &cameraId = QString()) + { + QVector> sessions; + { + std::lock_guard lock(m_cameraSessionsMutex); + if (cameraId.isEmpty()) { + sessions.reserve(m_cameraSessions.size()); + for (auto it = m_cameraSessions.cbegin(); + it != m_cameraSessions.cend(); ++it) { + sessions.append(it.value()); + } + } else { + const auto it = m_cameraSessions.find(cameraId); + if (it != m_cameraSessions.end()) + sessions.append(it.value()); + } + } + + for (const auto &session : sessions) { + session->stop.store(true); +#ifdef CMVR_WITH_GRPC + std::lock_guard lock(session->contextMutex); + if (session->context) + session->context->TryCancel(); +#endif + } + for (const auto &session : sessions) { + if (session->thread.joinable() && + session->thread.get_id() != std::this_thread::get_id()) { + session->thread.join(); + } + session->running.store(false); + } + { + std::lock_guard lock(m_cameraSessionsMutex); + for (const auto &session : sessions) { + const auto it = m_cameraSessions.find(session->cameraId); + if (it != m_cameraSessions.end() && it.value() == session) + m_cameraSessions.erase(it); + } + } + } + + void stopSpeakerStreamInternal(bool cancel = false) + { + const bool wasRunning = m_speakerStreamRunning.load(); + m_speakerStreamStop.store(true); + m_speakerQueueCondition.notify_all(); +#ifdef CMVR_WITH_GRPC + { + std::lock_guard lock(m_speakerContextMutex); + if (cancel && m_speakerStreamContext) + m_speakerStreamContext->TryCancel(); + } +#endif + const bool hadThread = m_speakerStreamThread.joinable(); + if (hadThread && m_speakerStreamThread.get_id() != std::this_thread::get_id()) + m_speakerStreamThread.join(); + m_speakerStreamRunning.store(false); + { + std::lock_guard lock(m_speakerQueueMutex); + m_speakerQueue.clear(); + m_speakerQueueBytes = 0; + } + if (wasRunning && !hadThread) + emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false, + QStringLiteral("扬声器音频流已停止")); + } + + void stopMicrophoneStreamInternal() + { + const bool wasRunning = m_microphoneStreamRunning.load(); + m_microphoneStreamStop.store(true); +#ifdef CMVR_WITH_GRPC + { + std::lock_guard lock(m_microphoneContextMutex); + if (m_microphoneStreamContext) + m_microphoneStreamContext->TryCancel(); + } +#endif + const bool hadThread = m_microphoneStreamThread.joinable(); + if (hadThread && m_microphoneStreamThread.get_id() != std::this_thread::get_id()) + m_microphoneStreamThread.join(); + m_microphoneStreamRunning.store(false); + if (wasRunning && !hadThread) + emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, + QStringLiteral("麦克风音频拉流已停止")); + } + + void poll() + { + if (!m_connected) + return; + if (m_demoMode) { + pollDemo(); + return; + } +#ifdef CMVR_WITH_GRPC + pollGrpc(); +#endif + } + +private: + bool ensureConnected(const QString &command) + { + if (m_connected) + return true; + emit commandFinished(command, false, QStringLiteral("设备尚未连接")); + return false; + } + + bool ensureDeviceId(const QString &command, const QString &deviceId) + { + if (!deviceId.trimmed().isEmpty()) + return true; + emit commandFinished(command, false, QStringLiteral("请在对应服务页填写设备 ID")); + return false; + } + + void pollDemo() + { + ++m_tick; + if (m_armPollingEnabled) { + QVariantList joints; + const QStringList jointNames = armJointNamesForDevice(m_armDeviceId); + for (int i = 0; i < jointNames.size(); ++i) { + const double phase = m_tick * 0.035 + i * 0.46; + double position = 0.36 * qSin(phase); + if (i < m_demoTargets.size()) + position = m_demoTargets.at(i) + 0.025 * qSin(phase * 1.7); + QVariantMap joint; + joint.insert(QStringLiteral("name"), jointNames.at(i)); + joint.insert(QStringLiteral("position"), position); + joint.insert(QStringLiteral("velocity"), 0.22 * qCos(phase)); + joint.insert(QStringLiteral("effort"), 0.4 + 0.3 * qAbs(qSin(phase * 0.7))); + joints.append(joint); + } + QVariantMap pose; + pose.insert(QStringLiteral("x"), 0.421 + 0.004 * qSin(m_tick * 0.02)); + pose.insert(QStringLiteral("y"), -0.182 + 0.003 * qCos(m_tick * 0.025)); + pose.insert(QStringLiteral("z"), 0.736 + 0.002 * qSin(m_tick * 0.017)); + pose.insert(QStringLiteral("rx"), 1.571); + pose.insert(QStringLiteral("ry"), 0.014); + pose.insert(QStringLiteral("rz"), -0.021); + QVariantMap state; + state.insert(QStringLiteral("connected"), true); + state.insert(QStringLiteral("poweredOn"), true); + state.insert(QStringLiteral("fault"), false); + state.insert(QStringLiteral("moving"), !m_demoTargets.isEmpty()); + emit telemetryReceived(m_armDeviceId, joints, pose, state); + } + if (m_tick % 10 == 0) { + emit systemStatusReceived(31.0 + 8.0 * qSin(m_tick * 0.04), + 47.0 + 3.0 * qCos(m_tick * 0.025), 62.0, + demoDeviceList()); + } + } + +#ifdef CMVR_WITH_GRPC + static void fillHeader(cmvr::api::CommandHeader::Request *header, + const QString &deviceId, int validForMs = 5000) + { + header->set_device_id(deviceId.toStdString()); + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + header->mutable_timestamp()->set_seconds(now / 1000); + header->mutable_timestamp()->set_nanos(static_cast((now % 1000) * 1000000)); + header->set_command_id( + QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString()); + header->set_valid_for_ms(static_cast(qMax(1, validForMs))); + } + + static void setDeadline(grpc::ClientContext &context, int milliseconds) + { + context.set_deadline(std::chrono::system_clock::now() + std::chrono::milliseconds(milliseconds)); + } + + void runSpeakerAudioStream(const std::shared_ptr &channel, + const QString &deviceId) + { + std::unique_ptr speaker = + cmvr::api::SpeakerService::NewStub(channel); + grpc::ClientContext context; + { + std::lock_guard lock(m_speakerContextMutex); + m_speakerStreamContext = &context; + } + if (m_speakerStreamStop.load()) + context.TryCancel(); + + cmvr::api::StreamSpeakerAudioCommand::Feedback feedback; + std::unique_ptr> writer = + speaker->StreamAudio(&context, &feedback); + bool writeOk = static_cast(writer); + while (writeOk) { + SpeakerAudioFrame frame; + { + std::unique_lock lock(m_speakerQueueMutex); + m_speakerQueueCondition.wait(lock, [this]() { + return m_speakerStreamStop.load() || !m_speakerQueue.empty(); + }); + if (m_speakerQueue.empty()) { + if (m_speakerStreamStop.load()) + break; + continue; + } + frame = std::move(m_speakerQueue.front()); + m_speakerQueue.pop_front(); + m_speakerQueueBytes -= frame.data.size(); + } + + cmvr::api::StreamSpeakerAudioCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + cmvr::api::AudioData *audio = request.mutable_audio(); + audio->set_data(frame.data.constData(), frame.data.size()); + audio->set_sample_rate(frame.sampleRate); + audio->set_channels(frame.channels); + audio->set_format(cmvr::api::AudioData::PCM); + audio->set_codec("pcm_s16le"); + audio->set_pts(frame.pts); + audio->set_nb_samples(frame.samples); + writeOk = writer->Write(request); + if (writeOk) { + const quint64 frames = ++m_speakerFrames; + const quint64 bytes = m_speakerBytes.fetch_add(frame.data.size()) + frame.data.size(); + emit audioStreamStatistics(QStringLiteral("SpeakerService"), frames, bytes, + frame.pts / 1000 + frame.samples * 1000LL / frame.sampleRate); + } + } + + if (writer) + writer->WritesDone(); + const grpc::Status status = writer ? writer->Finish() + : grpc::Status(grpc::StatusCode::UNKNOWN, + "failed to create client writer"); + { + std::lock_guard lock(m_speakerContextMutex); + m_speakerStreamContext = nullptr; + } + const bool stopped = m_speakerStreamStop.load(); + const bool success = !stopped && status.ok() && feedback.header().success(); + QString detail; + if (stopped) + detail = QStringLiteral("扬声器音频流已停止"); + else if (!status.ok()) + detail = QStringLiteral("扬声器音频流失败:%1") + .arg(QString::fromStdString(status.error_message())); + else if (!feedback.header().success()) + detail = QStringLiteral("扬声器拒绝音频流:%1") + .arg(QString::fromStdString(feedback.header().error_message())); + else + detail = QStringLiteral("扬声器音频流发送完成"); + m_speakerStreamRunning.store(false); + emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false, detail); + if (!stopped) + emit commandFinished(QStringLiteral("Speaker Stream"), success, detail); + } + + void runMicrophoneAudioStream(const std::shared_ptr &channel, + const QString &deviceId) + { + std::unique_ptr microphone = + cmvr::api::MicPhoneService::NewStub(channel); + cmvr::api::StreamMicAudioCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + grpc::ClientContext context; + { + std::lock_guard lock(m_microphoneContextMutex); + m_microphoneStreamContext = &context; + } + if (m_microphoneStreamStop.load()) + context.TryCancel(); + + std::unique_ptr> reader = + microphone->StreamAudio(&context, request); + cmvr::api::StreamMicAudioCommand::Feedback feedback; + while (reader && !m_microphoneStreamStop.load() && reader->Read(&feedback)) { + if (!feedback.header().success()) { + emit logMessage(QStringLiteral("WARN"), + QStringLiteral("麦克风音频帧反馈失败:%1") + .arg(QString::fromStdString(feedback.header().error_message()))); + continue; + } + const cmvr::api::AudioData &audio = feedback.audio(); + const QByteArray data(audio.data().data(), static_cast(audio.data().size())); + const quint64 frames = ++m_microphoneFrames; + const quint64 bytes = m_microphoneBytes.fetch_add(data.size()) + data.size(); + emit audioFrameReceived(data, audio.sample_rate(), audio.channels(), + static_cast(audio.format()), + QString::fromStdString(audio.codec()), audio.pts(), + audio.nb_samples()); + const qint64 durationMs = audio.sample_rate() > 0 + ? audio.pts() / 1000 + audio.nb_samples() * 1000LL / audio.sample_rate() + : 0; + emit audioStreamStatistics(QStringLiteral("MicPhoneService"), frames, bytes, + durationMs); + } + const grpc::Status status = reader ? reader->Finish() + : grpc::Status(grpc::StatusCode::UNKNOWN, + "failed to create client reader"); + { + std::lock_guard lock(m_microphoneContextMutex); + m_microphoneStreamContext = nullptr; + } + const bool stopped = m_microphoneStreamStop.load(); + QString detail; + if (stopped) + detail = QStringLiteral("麦克风音频拉流已停止"); + else if (!status.ok()) + detail = QStringLiteral("麦克风音频拉流失败:%1") + .arg(QString::fromStdString(status.error_message())); + else + detail = QStringLiteral("麦克风音频拉流已结束"); + m_microphoneStreamRunning.store(false); + emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, detail); + if (!stopped) + emit commandFinished(QStringLiteral("MicPhone Stream"), status.ok(), detail); + } + + void runDepthCameraStream(const std::shared_ptr &channel, + const std::shared_ptr &session, + bool rgbd) + { + const QString cameraId = session->cameraId; + auto camera = cmvr::api::CameraService::NewStub(channel); + cmvr::api::StartCameraCommand::Request startRequest; + fillHeader(startRequest.mutable_header(), cameraId); + cmvr::api::StartCameraCommand::Feedback startResponse; + grpc::ClientContext startContext; + setDeadline(startContext, 3000); + const grpc::Status startStatus = camera->StartCamera(&startContext, startRequest, &startResponse); + if (!startStatus.ok() || !startResponse.header().success()) { + const QString error = !startStatus.ok() + ? QString::fromStdString(startStatus.error_message()) + : QString::fromStdString(startResponse.header().error_message()); + session->running.store(false); + emit cameraStreamStateChangedForCamera(cameraId, false, + QStringLiteral("鍚姩鐩告満澶辫触锛?1").arg(error)); + emit commandFinished(QStringLiteral("Camera Stream"), false, error); + return; + } + + grpc::ClientContext context; + { + std::lock_guard lock(session->contextMutex); + session->context = &context; + } + if (session->stop.load()) + context.TryCancel(); + + QString terminalError; + if (rgbd) { + auto stream = camera->GetRGBDImagesStream(&context); + cmvr::api::GetRGBDImagesStreamCommand::Request request; + fillHeader(request.mutable_header(), cameraId); + request.set_eof(false); + if (!stream || !stream->Write(request)) { + terminalError = QStringLiteral("鍙戦€佽棰戞祦璁㈤槄璇锋眰澶辫触"); + } else { + cmvr::api::GetRGBDImagesStreamCommand::Feedback response; + while (!session->stop.load() && stream->Read(&response)) { + if (!response.header().success()) { + terminalError = QString::fromStdString(response.header().error_message()); + break; + } + const auto &depth = response.depth_frame(); + VideoFrame frame = videoFrameFromDepth(depth); + if (!frame.isValid()) + continue; + if (videoFrameReceivedForCamera) + videoFrameReceivedForCamera(cameraId, frame, + QStringLiteral("%1 x %2 | DEPTH | #%3") + .arg(depth.width()).arg(depth.height()).arg(response.seq_no())); + } + stream->WritesDone(); + stream->Finish(); + } + } else { + auto stream = camera->GetDepthImageStream(&context); + cmvr::api::GetDepthImageStreamCommand::Request request; + fillHeader(request.mutable_header(), cameraId); + request.set_eof(false); + if (!stream || !stream->Write(request)) { + terminalError = QStringLiteral("鍙戦€佽棰戞祦璁㈤槄璇锋眰澶辫触"); + } else { + cmvr::api::GetDepthImageStreamCommand::Feedback response; + while (!session->stop.load() && stream->Read(&response)) { + if (!response.header().success()) { + terminalError = QString::fromStdString(response.header().error_message()); + break; + } + const auto &depth = response.depth_frame(); + VideoFrame frame = videoFrameFromDepth(depth); + if (!frame.isValid()) + continue; + if (videoFrameReceivedForCamera) + videoFrameReceivedForCamera(cameraId, frame, + QStringLiteral("%1 x %2 | DEPTH | #%3") + .arg(depth.width()).arg(depth.height()).arg(response.seq_no())); + } + stream->WritesDone(); + stream->Finish(); + } + } + if (session->stop.load()) + terminalError = QStringLiteral("瑙嗛棰勮宸插仠姝?"); + { + std::lock_guard lock(session->contextMutex); + if (session->context == &context) + session->context = nullptr; + } + session->running.store(false); + emit cameraStreamStateChangedForCamera( + cameraId, false, + terminalError.isEmpty() ? QStringLiteral("Depth stream ended") : terminalError); + } + + void runCameraStream(const std::shared_ptr &channel, + const std::shared_ptr &session) + { + const QString cameraId = session->cameraId; + std::unique_ptr camera = + cmvr::api::CameraService::NewStub(channel); + + cmvr::api::StartCameraCommand::Request startRequest; + fillHeader(startRequest.mutable_header(), cameraId); + cmvr::api::StartCameraCommand::Feedback startResponse; + grpc::ClientContext startContext; + setDeadline(startContext, 3000); + const grpc::Status startStatus = camera->StartCamera(&startContext, startRequest, &startResponse); + if (!startStatus.ok() || !startResponse.header().success()) { + const QString error = !startStatus.ok() + ? QString::fromStdString(startStatus.error_message()) + : QString::fromStdString(startResponse.header().error_message()); + session->running.store(false); + emit cameraStreamStateChangedForCamera( + cameraId, false, QStringLiteral("启动相机失败:%1").arg(error)); + emit commandFinished(QStringLiteral("Camera Stream"), false, error); + return; + } + if (session->stop.load()) { + session->running.store(false); + emit cameraStreamStateChangedForCamera( + cameraId, false, QStringLiteral("视频预览已停止")); + return; + } + + grpc::ClientContext context; + { + std::lock_guard lock(session->contextMutex); + session->context = &context; + } + if (session->stop.load()) + context.TryCancel(); + std::unique_ptr> stream = + camera->GetRGBImageStream(&context); + + cmvr::api::GetRGBImageStreamCommand::Request request; + fillHeader(request.mutable_header(), cameraId); + request.set_eof(false); + if (!stream || !stream->Write(request)) { + context.TryCancel(); + if (stream) + stream->Finish(); + { + std::lock_guard lock(session->contextMutex); + session->context = nullptr; + } + session->running.store(false); + emit cameraStreamStateChangedForCamera( + cameraId, false, QStringLiteral("发送视频流订阅请求失败")); + return; + } + if (session->stop.load()) + context.TryCancel(); + + emit logMessage(QStringLiteral("INFO"), + QStringLiteral("CameraService.GetRGBImageStream 已启动:%1,解码格式=%2") + .arg(cameraId, session->codec == QStringLiteral("h265") + ? QStringLiteral("H.265") + : QStringLiteral("H.264"))); + struct CompressedVideoFrame { + QByteArray data; + QString codec; + qint64 pts = 0; + qint64 dts = 0; + int width = 0; + int height = 0; + int seqNo = 0; + quint32 sourceFps = 0; + quint64 generation = 0; + bool keyFrame = false; + QVariantMap intrinsics; + QVariantMap metadata; + }; + // Frame-threaded HEVC needs several packets before its first output. + // Keep enough startup headroom so the low-latency recovery logic does + // not repeatedly reset a decoder that is still warming up. + constexpr std::size_t kMaxCompressedFrames = 45; + std::deque compressedFrames; + std::mutex compressedFramesMutex; + std::condition_variable compressedFramesReady; + bool readerFinished = false; + quint64 queueGeneration = 0; + std::atomic decodedFrames{0}; + std::atomic displayedFrames{0}; + std::atomic receivedFrames{0}; + std::atomic receivedBytes{0}; + std::atomic droppedFrames{0}; + std::atomic sourceSequence{0}; + std::atomic sourceSequenceGaps{0}; + std::atomic compressedQueueDepth{0}; + QElapsedTimer totalTimer; + totalTimer.start(); + QString terminalError; + + std::thread decoderThread([&] { + VideoDecoder decoder; + QElapsedTimer rateTimer; + rateTimer.start(); + quint64 rateFrames = 0; + quint64 previousReceivedFrames = 0; + quint64 previousDecodedFrames = 0; + quint64 previousRateBytes = 0; + quint64 previousSourceSequence = 0; + qint64 decodeNanoseconds = 0; + quint64 timedDecodePackets = 0; + double receiveFps = 0.0; + double sourceSequenceFps = 0.0; + double displayFps = 0.0; + double decodeFps = 0.0; + double decodeMilliseconds = 0.0; + double bitrateKbps = 0.0; + int decodeErrors = 0; + QString activeCodec; + quint64 activeGeneration = std::numeric_limits::max(); + struct FrameMetadata { + QVariantMap intrinsics; + QVariantMap metadata; + bool ambiguous = false; + bool delivered = false; + }; + QHash metadataByPts; + std::deque metadataOrder; + constexpr std::size_t kMaxFrameMetadata = 256; + while (!session->stop.load()) { + CompressedVideoFrame packet; + { + std::unique_lock lock(compressedFramesMutex); + compressedFramesReady.wait(lock, [&] { + return session->stop.load() || readerFinished || + !compressedFrames.empty(); + }); + if ((session->stop.load() || readerFinished) && + compressedFrames.empty()) + break; + packet = std::move(compressedFrames.front()); + compressedFrames.pop_front(); + compressedQueueDepth.store(compressedFrames.size()); + } + + const QString codec = packet.codec.isEmpty() + ? session->codec : packet.codec; + if (codec != activeCodec || + packet.generation != activeGeneration) { + decoder.reset(); + metadataByPts.clear(); + metadataOrder.clear(); + activeCodec = codec; + activeGeneration = packet.generation; + decodeErrors = 0; + emit logMessage(QStringLiteral("INFO"), + QStringLiteral("视频解码器已切换为 %1,等待参数集和关键帧") + .arg(codec.toUpper())); + } + + // FFmpeg may output an older frame after several input packets. + // Match by decoded PTS, never by the most recently read packet. + // Zero is also the protobuf missing-field default: omit it from + // calibration matching, while leaving video display unaffected. + if (packet.pts != 0 && packet.pts != std::numeric_limits::min()) { + auto existingMetadata = metadataByPts.find(packet.pts); + if (existingMetadata != metadataByPts.end()) { + existingMetadata->ambiguous = true; + } else { + FrameMetadata values; + values.intrinsics = packet.intrinsics; + values.metadata = packet.metadata; + metadataByPts.insert(packet.pts, values); + metadataOrder.push_back(packet.pts); + while (metadataOrder.size() > kMaxFrameMetadata) { + metadataByPts.remove(metadataOrder.front()); + metadataOrder.pop_front(); + } + } + } + QVector frames; + int decodedCount = 0; + QElapsedTimer decodeTimer; + decodeTimer.start(); + if (!decoder.decode(packet.data, codec, packet.pts, packet.dts, + &frames, true, &decodedCount)) { + metadataByPts.clear(); + metadataOrder.clear(); + ++decodeErrors; + if (decodeErrors == 1 || decodeErrors % 60 == 0) { + emit logMessage(QStringLiteral("WARN"), + QStringLiteral("视频解码失败(%1 次):%2") + .arg(decodeErrors).arg(decoder.lastError())); + } + continue; + } + decodeNanoseconds += decodeTimer.nsecsElapsed(); + ++timedDecodePackets; + decodedFrames.fetch_add(static_cast(decodedCount)); + + if (!frames.isEmpty()) { + if (displayedFrames.load() == 0) { + emit logMessage(QStringLiteral("INFO"), + QStringLiteral("视频预览解码后端:%1") + .arg(decoder.backendName())); + } + } + + for (VideoFrame &frame : frames) { + frame.metadata = {{QStringLiteral("kind"), QStringLiteral("rgb")}, + {QStringLiteral("ptsMatched"), false}, + {QStringLiteral("captureTimestampAvailable"), false}}; + auto matched = metadataByPts.find(frame.presentationTimestamp); + if (matched != metadataByPts.end() && !matched->ambiguous + && !matched->delivered) { + frame.intrinsics = matched->intrinsics; + frame.metadata = matched->metadata; + frame.metadata.insert(QStringLiteral("ptsMatched"), true); + matched->delivered = true; + } + displayedFrames.fetch_add(1); + ++rateFrames; + if (rateTimer.elapsed() >= 1000) { + const double seconds = rateTimer.elapsed() / 1000.0; + const quint64 currentBytes = receivedBytes.load(); + const quint64 currentReceivedFrames = receivedFrames.load(); + const quint64 currentSourceSequence = sourceSequence.load(); + receiveFps = (currentReceivedFrames - previousReceivedFrames) / seconds; + sourceSequenceFps = previousSourceSequence > 0 && + currentSourceSequence >= previousSourceSequence + ? (currentSourceSequence - previousSourceSequence) / seconds : 0.0; + displayFps = rateFrames / seconds; + const quint64 currentDecodedFrames = decodedFrames.load(); + decodeFps = (currentDecodedFrames - previousDecodedFrames) / seconds; + bitrateKbps = (currentBytes - previousRateBytes) * 8.0 / + seconds / 1000.0; + decodeMilliseconds = timedDecodePackets > 0 + ? decodeNanoseconds / 1000000.0 / timedDecodePackets : 0.0; + rateFrames = 0; + previousReceivedFrames = currentReceivedFrames; + previousSourceSequence = currentSourceSequence; + previousDecodedFrames = currentDecodedFrames; + previousRateBytes = currentBytes; + decodeNanoseconds = 0; + timedDecodePackets = 0; + rateTimer.restart(); + } + const QString sourceRate = packet.sourceFps > 0 + ? QStringLiteral("/%1").arg(packet.sourceFps) : QString(); + const QString dropDetail = droppedFrames.load() > 0 + ? QStringLiteral(" | 低延迟丢帧 %1").arg(droppedFrames.load()) + : QString(); + const QString detail = QStringLiteral("%1 x %2 | %3 | FPS 源/收/解/显 %4/%5/%6/%7%8 | %9 %10 ms | Q%11 缺%12 | %13 kbps | #%14%15") + .arg(packet.width).arg(packet.height).arg(codec.toUpper()) + .arg(sourceSequenceFps, 0, 'f', 1).arg(receiveFps, 0, 'f', 1) + .arg(decodeFps, 0, 'f', 1).arg(displayFps, 0, 'f', 1) + .arg(sourceRate).arg(decoder.backendName()) + .arg(decodeMilliseconds, 0, 'f', 1).arg(compressedQueueDepth.load()) + .arg(sourceSequenceGaps.load()).arg(bitrateKbps, 0, 'f', 0) + .arg(packet.seqNo).arg(dropDetail); + if (videoFrameReceivedForCamera) + videoFrameReceivedForCamera(cameraId, frame, detail); + } + } + }); + + cmvr::api::GetRGBImageStreamCommand::Feedback response; + while (!session->stop.load() && stream->Read(&response)) { + if (!response.header().success()) { + terminalError = QString::fromStdString(response.header().error_message()); + break; + } + const auto &frame = response.color_frame(); + if (frame.data().empty()) + continue; + + receivedBytes.fetch_add(static_cast(frame.data().size())); + receivedFrames.fetch_add(1); + const quint64 currentSourceSequence = frame.source_sequence(); + const quint64 previousSequence = sourceSequence.exchange(currentSourceSequence); + if (previousSequence > 0 && currentSourceSequence > previousSequence + 1) + sourceSequenceGaps.fetch_add(currentSourceSequence - previousSequence - 1); + CompressedVideoFrame packet; + packet.data = QByteArray(frame.data().data(), static_cast(frame.data().size())); + packet.codec = QString::fromStdString(frame.codec()).trimmed().toLower(); + packet.pts = frame.pts(); + packet.dts = frame.dts(); + packet.width = frame.width(); + packet.height = frame.height(); + packet.seqNo = response.seq_no(); + packet.sourceFps = frame.source_fps(); + packet.keyFrame = frame.is_key_frame(); + const auto &intrinsics = response.intrinsics(); + QVariantList coefficients; + for (const float coefficient : intrinsics.coeffs()) + coefficients.append(static_cast(coefficient)); + // Preserve the server values. Some drivers resize their encoded + // output without scaling K; consumers must confirm native dimensions. + packet.intrinsics = { + {QStringLiteral("fx"), intrinsics.fx()}, {QStringLiteral("fy"), intrinsics.fy()}, + {QStringLiteral("cx"), intrinsics.cx()}, {QStringLiteral("cy"), intrinsics.cy()}, + {QStringLiteral("coeffs"), coefficients}, + {QStringLiteral("width"), frame.width()}, + {QStringLiteral("height"), frame.height()}, + {QStringLiteral("distortionModelAvailable"), false}, + {QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImageStream.intrinsics")}}; + packet.metadata = { + {QStringLiteral("kind"), QStringLiteral("rgb")}, + {QStringLiteral("captureUtcNs"), static_cast(frame.capture_utc_ns())}, + {QStringLiteral("sourceSequence"), static_cast(frame.source_sequence())}, + {QStringLiteral("sourceFrameNumber"), static_cast(frame.source_frame_number())}, + {QStringLiteral("sourceTimestamp"), static_cast(frame.source_timestamp())}, + {QStringLiteral("pts"), static_cast(frame.pts())}, + {QStringLiteral("dts"), static_cast(frame.dts())}, + {QStringLiteral("sourceFps"), frame.source_fps()}, + {QStringLiteral("receivedAtMs"), QDateTime::currentMSecsSinceEpoch()}, + {QStringLiteral("captureTimestampAvailable"), frame.capture_utc_ns() > 0}, + {QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImageStream.color_frame")}}; + { + std::lock_guard lock(compressedFramesMutex); + // Resynchronize only at a keyframe already in hand. Clearing a + // full queue at an arbitrary P-frame makes the decoder wait for + // a future keyframe and can cause a reset loop during startup. + if (compressedFrames.size() >= kMaxCompressedFrames) { + if (packet.keyFrame) { + droppedFrames.fetch_add( + static_cast(compressedFrames.size())); + compressedFrames.clear(); + compressedQueueDepth.store(0); + ++queueGeneration; + } else { + droppedFrames.fetch_add(1); + continue; + } + } + packet.generation = queueGeneration; + compressedFrames.push_back(std::move(packet)); + compressedQueueDepth.store(compressedFrames.size()); + } + compressedFramesReady.notify_one(); + } + + { + std::lock_guard lock(compressedFramesMutex); + readerFinished = true; + } + compressedFramesReady.notify_all(); + + stream->WritesDone(); + const grpc::Status status = stream->Finish(); + if (decoderThread.joinable()) + decoderThread.join(); + { + std::lock_guard lock(session->contextMutex); + if (session->context == &context) + session->context = nullptr; + } + + const bool stoppedByUser = session->stop.load(); + if (terminalError.isEmpty() && !status.ok() && !stoppedByUser) + terminalError = QString::fromStdString(status.error_message()); + session->running.store(false); + const QString summary = terminalError.isEmpty() + ? QStringLiteral("视频预览已停止,解码 %1 帧,显示 %2 帧,%3 MB,%4 秒") + .arg(decodedFrames.load()).arg(displayedFrames.load()) + .arg(receivedBytes.load() / 1048576.0, 0, 'f', 1) + .arg(totalTimer.elapsed() / 1000.0, 0, 'f', 1) + : QStringLiteral("视频流失败:%1").arg(terminalError); + emit cameraStreamStateChangedForCamera(cameraId, false, summary); + emit logMessage(terminalError.isEmpty() ? QStringLiteral("INFO") : QStringLiteral("ERROR"), summary); + } + + void finish(const QString &command, const grpc::Status &status, bool responseSuccess, + const QString &responseError) + { + const bool success = status.ok() && responseSuccess; + QString detail; + if (!status.ok()) { + const QString message = QString::fromStdString(status.error_message()); + detail = QStringLiteral("gRPC code %1:%2") + .arg(static_cast(status.error_code())) + .arg(message.isEmpty() ? QStringLiteral("服务端未返回错误详情") + : message); + } + else if (!responseSuccess) + detail = responseError.isEmpty() ? QStringLiteral("设备拒绝了命令") : responseError; + else + detail = QStringLiteral("命令执行成功"); + emit commandFinished(command, success, detail); + } + + void pollGrpc() + { + ++m_tick; + const bool armPollDue = m_consecutivePollErrors < 3 || m_tick % 10 == 0; + if (m_armPollingEnabled && !m_armDeviceId.isEmpty() && armPollDue) { + const QString polledDeviceId = m_armDeviceId; + cmvr::api::GetRobotState::Request request; + fillHeader(request.mutable_header(), polledDeviceId); + cmvr::api::GetRobotState::Response response; + grpc::ClientContext context; + setDeadline(context, 350); + const grpc::Status status = m_arm->getRobotState(&context, request, &response); + if (status.ok() && response.header().success()) { + const bool recovered = m_consecutivePollErrors >= 3; + m_consecutivePollErrors = 0; + QVariantList joints; + const auto &robotState = response.state(); + const auto &jointState = robotState.actual_joint_state(); + for (int i = 0; i < jointState.name_size(); ++i) { + QVariantMap joint; + joint.insert(QStringLiteral("name"), QString::fromStdString(jointState.name(i))); + joint.insert(QStringLiteral("position"), i < jointState.position_size() ? jointState.position(i) : 0.0); + joint.insert(QStringLiteral("velocity"), i < jointState.velocity_size() ? jointState.velocity(i) : 0.0); + joint.insert(QStringLiteral("effort"), i < jointState.effort_size() ? jointState.effort(i) : 0.0); + joints.append(joint); + } + const auto &tcp = robotState.actual_tcp_pose(); + QVariantMap pose; + pose.insert(QStringLiteral("x"), tcp.x()); + pose.insert(QStringLiteral("y"), tcp.y()); + pose.insert(QStringLiteral("z"), tcp.z()); + pose.insert(QStringLiteral("rx"), tcp.rx()); + pose.insert(QStringLiteral("ry"), tcp.ry()); + pose.insert(QStringLiteral("rz"), tcp.rz()); + const QVariantMap activeTcpPose = pose; + if (robotState.connected() + && !m_armBaseFrame.isEmpty() && !m_armTcpFrame.isEmpty()) { + cmvr::api::GetPose::Request poseRequest; + fillHeader(poseRequest.mutable_header(), polledDeviceId); + poseRequest.set_base_link(m_armBaseFrame.toStdString()); + poseRequest.set_ee_link(m_armTcpFrame.toStdString()); + cmvr::api::GetPose::Response poseResponse; + grpc::ClientContext poseContext; + setDeadline(poseContext, 250); + const grpc::Status poseStatus = + m_arm->getPose(&poseContext, poseRequest, &poseResponse); + if (poseStatus.ok() && poseResponse.header().success()) { + const auto &selectedPose = poseResponse.pose(); + pose.insert(QStringLiteral("x"), selectedPose.x()); + pose.insert(QStringLiteral("y"), selectedPose.y()); + pose.insert(QStringLiteral("z"), selectedPose.z()); + pose.insert(QStringLiteral("rx"), selectedPose.rx()); + pose.insert(QStringLiteral("ry"), selectedPose.ry()); + pose.insert(QStringLiteral("rz"), selectedPose.rz()); + } + } + QVariantMap state; + state.insert(QStringLiteral("activeTcpPose"), activeTcpPose); + state.insert(QStringLiteral("robotMode"), static_cast(robotState.robot_mode())); + state.insert(QStringLiteral("safetyMode"), static_cast(robotState.safety_mode())); + state.insert(QStringLiteral("controlMode"), static_cast(robotState.control_mode())); + state.insert(QStringLiteral("freedrive"), + robotState.control_mode() + == cmvr::api::ARM_CONTROL_MODE_FREEDRIVE); + state.insert(QStringLiteral("connected"), robotState.connected()); + state.insert(QStringLiteral("poweredOn"), robotState.powered_on()); + state.insert(QStringLiteral("brakeReleased"), robotState.brake_released()); + state.insert(QStringLiteral("moving"), robotState.moving()); + state.insert(QStringLiteral("fault"), robotState.fault()); + state.insert(QStringLiteral("protectiveStopped"), robotState.protective_stopped()); + state.insert(QStringLiteral("emergencyStopped"), robotState.emergency_stopped()); + state.insert(QStringLiteral("speedScaling"), robotState.speed_scaling()); + emit telemetryReceived(polledDeviceId, joints, pose, state); + if (recovered) { + emit armTelemetryHealthChanged( + polledDeviceId, true, QStringLiteral("机械臂遥测通信已恢复")); + } + } else { + ++m_consecutivePollErrors; + QString detail; + if (!status.ok()) { + const QString message = QString::fromStdString(status.error_message()); + detail = QStringLiteral("gRPC code %1:%2") + .arg(static_cast(status.error_code())) + .arg(message.isEmpty() + ? QStringLiteral("服务端未返回错误详情") + : message); + } else { + detail = QString::fromStdString(response.header().error_message()); + if (detail.isEmpty()) + detail = QStringLiteral("边缘端未返回机械臂状态"); + } + if (m_consecutivePollErrors == 3) + emit armTelemetryHealthChanged(polledDeviceId, false, detail); + } + } + + if (m_tick % 10 != 0) + return; + cmvr::api::GetSystemStatusCommand::Request statusRequest; + cmvr::api::GetSystemStatusCommand::Feedback statusResponse; + grpc::ClientContext statusContext; + setDeadline(statusContext, 500); + const grpc::Status rpcStatus = m_system->GetSystemStatus(&statusContext, statusRequest, &statusResponse); + if (rpcStatus.ok() && statusResponse.header().success()) { + const double memory = statusResponse.mem_total_mb() > 0 + ? statusResponse.mem_used_mb() * 100.0 / statusResponse.mem_total_mb() : 0.0; + const double disk = statusResponse.disk_total_gb() > 0 + ? statusResponse.disk_used_gb() * 100.0 / statusResponse.disk_total_gb() : 0.0; + emit systemStatusReceived(statusResponse.cpu_usage(), memory, disk, + deviceListFromStatus(statusResponse)); + } + } + + std::shared_ptr m_channel; + std::shared_ptr m_configChannel; + std::unique_ptr m_arm; + std::unique_ptr m_camera; + std::unique_ptr m_system; + std::unique_ptr m_agv; + std::unique_ptr m_microphone; + std::unique_ptr m_generic; + std::unique_ptr m_configuration; + grpc::ClientContext *m_speakerStreamContext = nullptr; + std::mutex m_speakerContextMutex; + grpc::ClientContext *m_microphoneStreamContext = nullptr; + std::mutex m_microphoneContextMutex; + grpc::ClientContext *m_agvMapStreamContext = nullptr; + std::mutex m_agvMapStreamContextMutex; +#endif + + struct SpeakerAudioFrame { + QByteArray data; + int sampleRate = 0; + int channels = 0; + qint64 pts = 0; + int samples = 0; + }; + + QTimer *m_pollTimer = nullptr; + QString m_host; + QString m_armDeviceId; + QString m_armBaseFrame; + QString m_armTcpFrame; + int m_port = 50052; + int m_tick = 0; + int m_consecutivePollErrors = 0; + bool m_connected = false; + bool m_configConnected = false; + bool m_demoMode = true; + bool m_armPollingEnabled = false; + std::shared_ptr m_armMotionSession; + std::mutex m_armMotionSessionMutex; + QHash> m_cameraSessions; + std::mutex m_cameraSessionsMutex; + QString m_defaultCameraCodec = QStringLiteral("h264"); + bool m_cameraRecording = false; + std::atomic m_speakerStreamRunning{false}; + std::atomic m_speakerStreamStop{false}; + std::atomic m_speakerFrames{0}; + std::atomic m_speakerBytes{0}; + std::thread m_speakerStreamThread; + std::deque m_speakerQueue; + int m_speakerQueueBytes = 0; + std::mutex m_speakerQueueMutex; + std::condition_variable m_speakerQueueCondition; + std::atomic m_microphoneStreamRunning{false}; + std::atomic m_microphoneStreamStop{false}; + std::atomic m_microphoneFrames{0}; + std::atomic m_microphoneBytes{0}; + std::thread m_microphoneStreamThread; + std::atomic m_agvMapStreamRunning{false}; + std::atomic m_agvMapStreamStop{false}; + std::thread m_agvMapStreamThread; + QVector m_demoTargets; +}; + +RobotClient::RobotClient(QObject *parent) + : QObject(parent), m_worker(new BackendWorker) +{ + qRegisterMetaType("QImage"); + qRegisterMetaType("VideoFrame"); + + m_worker->connectionChanged = [this](bool connected, int latencyMs, const QString &detail) { + QMetaObject::invokeMethod(this, [this, connected, latencyMs, detail]() { + emit connectionChanged(connected, latencyMs, detail); + }, Qt::QueuedConnection); + }; + m_worker->armInfoReceived = [this](const QString &deviceId, const QVariantMap &info) { + QMetaObject::invokeMethod(this, [this, deviceId, info]() { + emit armInfoReceived(deviceId, info); + }, Qt::QueuedConnection); + }; + m_worker->armFramesReceived = + [this](const QString &deviceId, const QStringList &baseFrames, + const QStringList &tcpFrames) { + QMetaObject::invokeMethod(this, + [this, deviceId, baseFrames, tcpFrames]() { + emit armFramesReceived(deviceId, baseFrames, tcpFrames); + }, Qt::QueuedConnection); + }; + m_worker->tcpCalibrationPoseReceived = + [this](quint64 requestId, const QString &deviceId, const QVariantMap &pose, + const QVariantMap &state, bool success, const QString &detail) { + QMetaObject::invokeMethod(this, + [this, requestId, deviceId, pose, state, success, detail]() { + emit tcpCalibrationPoseReceived(requestId, deviceId, pose, state, + success, detail); + }, Qt::QueuedConnection); + }; + m_worker->telemetryReceived = [this](const QString &deviceId, + const QVariantList &joints, + const QVariantMap &pose, + const QVariantMap &state) { + QMetaObject::invokeMethod(this, [this, deviceId, joints, pose, state]() { + emit telemetryReceived(deviceId, joints, pose, state); + }, Qt::QueuedConnection); + }; + m_worker->armTelemetryHealthChanged = + [this](const QString &deviceId, bool available, const QString &detail) { + QMetaObject::invokeMethod(this, [this, deviceId, available, detail]() { + emit armTelemetryHealthChanged(deviceId, available, detail); + }, Qt::QueuedConnection); + }; + m_worker->systemStatusReceived = [this](double cpu, double memory, double disk, + const QVariantList &devices) { + QMetaObject::invokeMethod(this, [this, cpu, memory, disk, devices]() { + emit systemStatusReceived(cpu, memory, disk, devices); + }, Qt::QueuedConnection); + }; + m_worker->systemInfoReceived = [this](const QVariantMap &info) { + QMetaObject::invokeMethod(this, [this, info]() { + emit systemInfoReceived(info); + }, Qt::QueuedConnection); + }; + m_worker->imageReceived = [this](const QImage &image, const QString &detail) { + QMetaObject::invokeMethod(this, [this, image, detail]() { + emit imageReceived(image, detail); + }, Qt::QueuedConnection); + }; + m_worker->handEyeImageReceived = + [this](quint64 token, const QString &cameraId, const QImage &image, + const QVariantMap &intrinsics, const QVariantMap &metadata, + bool success, const QString &detail) { + QMetaObject::invokeMethod(this, + [this, token, cameraId, image, intrinsics, metadata, success, detail]() { + emit handEyeImageReceived(token, cameraId, image, intrinsics, + metadata, success, detail); + }, Qt::QueuedConnection); + }; + m_worker->touchRgbdImageReceived = + [this](quint64 token,const QString &camera,const QImage &image,const QVariantMap &intrinsics, + const QVariantMap &metadata,bool success,const QString &detail) { + QMetaObject::invokeMethod(this,[this,token,camera,image,intrinsics,metadata,success,detail] { + emit touchRgbdImageReceived(token,camera,image,intrinsics,metadata,success,detail); + },Qt::QueuedConnection); + }; + const auto queueVideoFrame = [this](const QString &cameraId, + const VideoFrame &frame, + const QString &detail) { + { + QMutexLocker locker(&m_videoFrameMutex); + PendingVideoFrame &pending = m_pendingVideoFrames[cameraId]; + pending.frame = frame; + pending.detail = detail; + if (m_videoFrameDeliveryScheduled.contains(cameraId)) + return; + m_videoFrameDeliveryScheduled.insert(cameraId); + } + QMetaObject::invokeMethod(this, [this, cameraId]() { + PendingVideoFrame pending; + { + QMutexLocker locker(&m_videoFrameMutex); + pending = m_pendingVideoFrames.take(cameraId); + m_videoFrameDeliveryScheduled.remove(cameraId); + } + emit videoFrameReceived(cameraId, pending.frame, pending.detail); + }, Qt::QueuedConnection); + }; + m_worker->videoFrameReceivedForCamera = queueVideoFrame; + const auto queueCameraState = [this](const QString &cameraId, bool running, + const QString &detail) { + QMetaObject::invokeMethod(this, [this, cameraId, running, detail]() { + emit cameraStreamStateChanged(cameraId, running, detail); + }, Qt::QueuedConnection); + }; + m_worker->cameraStreamStateChangedForCamera = queueCameraState; + m_worker->cameraRecordingStateChanged = [this](bool recording, const QString &detail) { + QMetaObject::invokeMethod(this, [this, recording, detail]() { + emit cameraRecordingStateChanged(recording, detail); + }, Qt::QueuedConnection); + }; + m_worker->agvStateReceived = [this](const QVariantMap &state, const QVariantMap &navigation) { + QMetaObject::invokeMethod(this, [this, state, navigation]() { + emit agvStateReceived(state, navigation); + }, Qt::QueuedConnection); + }; + m_worker->agvInventoryReceived = [this](const QStringList &maps, const QVariantList &stations) { + QMetaObject::invokeMethod(this, [this, maps, stations]() { + emit agvInventoryReceived(maps, stations); + }, Qt::QueuedConnection); + }; + m_worker->agvMapFrameReceived = [this](const QImage &image, const QString &detail) { + QMetaObject::invokeMethod(this, [this, image, detail]() { + emit agvMapFrameReceived(image, detail); + }, Qt::QueuedConnection); + }; + m_worker->agvMapStreamStateChanged = [this](bool running, const QString &detail) { + QMetaObject::invokeMethod(this, [this, running, detail]() { + emit agvMapStreamStateChanged(running, detail); + }, Qt::QueuedConnection); + }; + m_worker->rpcFinished = [this](const QString &serviceName, const QString &methodName, + bool success, const QString &responseJson) { + QMetaObject::invokeMethod(this, [this, serviceName, methodName, success, responseJson]() { + emit rpcFinished(serviceName, methodName, success, responseJson); + }, Qt::QueuedConnection); + }; + m_worker->audioStreamStateChanged = [this](const QString &serviceName, bool running, + const QString &detail) { + QMetaObject::invokeMethod(this, [this, serviceName, running, detail]() { + emit audioStreamStateChanged(serviceName, running, detail); + }, Qt::QueuedConnection); + }; + m_worker->audioStreamStatistics = [this](const QString &serviceName, quint64 frames, + quint64 bytes, qint64 durationMs) { + QMetaObject::invokeMethod(this, [this, serviceName, frames, bytes, durationMs]() { + emit audioStreamStatistics(serviceName, frames, bytes, durationMs); + }, Qt::QueuedConnection); + }; + m_worker->audioFrameReceived = [this](const QByteArray &data, int sampleRate, int channels, + int format, const QString &codec, + qint64 pts, int samples) { + QMetaObject::invokeMethod(this, + [this, data, sampleRate, channels, format, codec, pts, samples]() { + emit audioFrameReceived(data, sampleRate, channels, format, codec, pts, samples); + }, Qt::QueuedConnection); + }; + m_worker->configurationConnectionChanged = [this](bool connected, const QString &detail) { + QMetaObject::invokeMethod(this, [this, connected, detail]() { + emit configurationConnectionChanged(connected, detail); + }, Qt::QueuedConnection); + }; + m_worker->configurationFilesReceived = + [this](const QString &root, const QVariantList &files, bool success, + const QString &detail) { + QMetaObject::invokeMethod(this, [this, root, files, success, detail]() { + emit configurationFilesReceived(root, files, success, detail); + }, Qt::QueuedConnection); + }; + m_worker->configurationFileReceived = + [this](const QString &path, const QString &content, const QString &revision, + const QString &messageType, bool success, const QString &detail) { + QMetaObject::invokeMethod( + this, [this, path, content, revision, messageType, success, detail]() { + emit configurationFileReceived(path, content, revision, messageType, + success, detail); + }, Qt::QueuedConnection); + }; + m_worker->configurationValidationFinished = + [this](const QString &path, bool success, const QString &detail) { + QMetaObject::invokeMethod(this, [this, path, success, detail]() { + emit configurationValidationFinished(path, success, detail); + }, Qt::QueuedConnection); + }; + m_worker->configurationSaveFinished = + [this](const QString &path, const QString &revision, bool success, + const QString &detail) { + QMetaObject::invokeMethod(this, [this, path, revision, success, detail]() { + emit configurationSaveFinished(path, revision, success, detail); + }, Qt::QueuedConnection); + }; + m_worker->commandFinished = [this](const QString &command, bool success, const QString &detail) { + QMetaObject::invokeMethod(this, [this, command, success, detail]() { + emit commandFinished(command, success, detail); + }, Qt::QueuedConnection); + }; + m_worker->logMessage = [this](const QString &level, const QString &message) { + QMetaObject::invokeMethod(this, [this, level, message]() { + emit logMessage(level, message); + }, Qt::QueuedConnection); + }; + + m_worker->moveToThread(&m_thread); + + connect(this, &RobotClient::connectRequested, m_worker, &BackendWorker::connectToServer); + connect(this, &RobotClient::disconnectRequested, m_worker, &BackendWorker::disconnectFromServer); + connect(this, &RobotClient::armTelemetryRequested, m_worker, &BackendWorker::setArmTelemetry); + connect(this, &RobotClient::armInfoRequested, m_worker, &BackendWorker::getArmInfo); + connect(this, &RobotClient::tcpCalibrationPoseRequested, + m_worker, &BackendWorker::getTcpCalibrationPose); + connect(this, &RobotClient::tcpJogMoveRequested, m_worker, &BackendWorker::tcpJogMove); + connect(this, &RobotClient::armFramesRequested, m_worker, &BackendWorker::getArmFrames); + connect(this, &RobotClient::armTelemetryFramesRequested, + m_worker, &BackendWorker::setArmTelemetryFrames); + connect(this, &RobotClient::speedJRequested, m_worker, &BackendWorker::speedJ); + connect(this, &RobotClient::speedLRequested, m_worker, &BackendWorker::speedL); + connect(this, &RobotClient::moveJRequested, m_worker, &BackendWorker::moveJ); + connect(this, &RobotClient::moveJPoseRequested, m_worker, &BackendWorker::moveJPose); + connect(this, &RobotClient::torqueRequested, m_worker, &BackendWorker::torque); + connect(this, &RobotClient::armStopRequested, m_worker, &BackendWorker::armStop); + connect(this, &RobotClient::armClearFaultRequested, m_worker, &BackendWorker::armClearFault); + connect(this, &RobotClient::armCalibrateZeroRequested, + m_worker, &BackendWorker::armCalibrateZero); + connect(this, &RobotClient::snapshotRequested, m_worker, &BackendWorker::snapshot); + connect(this, &RobotClient::handEyeImageRequested, m_worker, &BackendWorker::getHandEyeImage); + connect(this, &RobotClient::touchRgbdImageRequested, m_worker, &BackendWorker::getTouchRgbdImage); + connect(this, &RobotClient::cameraStreamStartRequested, m_worker, &BackendWorker::startCameraStream); + connect(this, &RobotClient::cameraStreamCodecRequested, + m_worker, &BackendWorker::setCameraStreamCodec); + connect(this, &RobotClient::cameraStreamStopRequested, m_worker, &BackendWorker::stopCameraStream); + connect(this, &RobotClient::cameraRecordingStartRequested, + m_worker, &BackendWorker::startCameraRecording); + connect(this, &RobotClient::cameraRecordingStopRequested, + m_worker, &BackendWorker::stopCameraRecording); + connect(this, &RobotClient::systemRefreshRequested, m_worker, &BackendWorker::systemRefresh); + connect(this, &RobotClient::systemStopAllRequested, m_worker, &BackendWorker::systemStopAll); + connect(this, &RobotClient::agvRefreshRequested, m_worker, &BackendWorker::agvRefresh); + connect(this, &RobotClient::agvNavigatePoseRequested, m_worker, &BackendWorker::agvNavigatePose); + connect(this, &RobotClient::agvNavigateStationRequested, m_worker, &BackendWorker::agvNavigateStation); + connect(this, &RobotClient::agvFollowPathRequested, m_worker, &BackendWorker::agvFollowPath); + connect(this, &RobotClient::agvVelocityRequested, m_worker, &BackendWorker::agvVelocity); + connect(this, &RobotClient::agvActionRequested, m_worker, &BackendWorker::agvAction); + connect(this, &RobotClient::agvInventoryRequested, m_worker, &BackendWorker::agvInventory); + connect(this, &RobotClient::agvSwitchMapRequested, m_worker, &BackendWorker::agvSwitchMap); + connect(this, &RobotClient::agvMapStreamStartRequested, + m_worker, &BackendWorker::startAgvMapStream); + connect(this, &RobotClient::agvMapStreamStopRequested, + m_worker, &BackendWorker::stopAgvMapStream); + connect(this, &RobotClient::rpcRequested, m_worker, &BackendWorker::invokeRpc); + connect(this, &RobotClient::speakerAudioStreamStartRequested, + m_worker, &BackendWorker::startSpeakerAudioStream); + connect(this, &RobotClient::speakerAudioFrameRequested, + m_worker, &BackendWorker::enqueueSpeakerAudioFrame); + connect(this, &RobotClient::speakerAudioStreamStopRequested, + m_worker, &BackendWorker::stopSpeakerAudioStream); + connect(this, &RobotClient::microphoneAudioStreamStartRequested, + m_worker, &BackendWorker::startMicrophoneAudioStream); + connect(this, &RobotClient::microphoneAudioStreamStopRequested, + m_worker, &BackendWorker::stopMicrophoneAudioStream); + connect(this, &RobotClient::configurationConnectRequested, + m_worker, &BackendWorker::connectConfigurationServer); + connect(this, &RobotClient::configurationDisconnectRequested, + m_worker, &BackendWorker::disconnectConfigurationServer); + connect(this, &RobotClient::configurationFilesRequested, + m_worker, &BackendWorker::listConfigurationFiles); + connect(this, &RobotClient::configurationFileReadRequested, + m_worker, &BackendWorker::readConfigurationFile); + connect(this, &RobotClient::configurationFileValidateRequested, + m_worker, &BackendWorker::validateConfigurationFile); + connect(this, &RobotClient::configurationFileSaveRequested, + m_worker, &BackendWorker::saveConfigurationFile); + + connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater); + m_thread.start(); +} + +RobotClient::~RobotClient() +{ + if (m_thread.isRunning()) { + QMetaObject::invokeMethod(m_worker, [this]() { + m_worker->disconnectConfigurationServer(); + m_worker->disconnectFromServer(); + }, Qt::BlockingQueuedConnection); + } + m_thread.quit(); + m_thread.wait(2500); +} + +bool RobotClient::grpcAvailable() const +{ +#ifdef CMVR_WITH_GRPC + return true; +#else + return false; +#endif +} + +void RobotClient::connectToServer(const QString &host, int port, bool demoMode) +{ + emit connectRequested(host, port, demoMode); +} + +void RobotClient::disconnectFromServer() { emit disconnectRequested(); } +void RobotClient::setArmTelemetry(const QString &deviceId, bool enabled) +{ + emit armTelemetryRequested(deviceId, enabled); +} +void RobotClient::requestArmInfo(const QString &deviceId) +{ + emit armInfoRequested(deviceId); +} +void RobotClient::requestTcpCalibrationPose(const QString &deviceId, quint64 requestId) +{ + emit tcpCalibrationPoseRequested(deviceId, requestId); +} +void RobotClient::requestTcpJogMove(const QString &deviceId, const QVariantMap &pose, + double velocity, double acceleration, quint64 token) +{ + emit tcpJogMoveRequested(deviceId, pose, velocity, acceleration, token); +} +void RobotClient::requestArmFrames(const QString &deviceId) +{ + emit armFramesRequested(deviceId); +} +void RobotClient::setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame, + const QString &tcpFrame) +{ + emit armTelemetryFramesRequested(deviceId, baseFrame, tcpFrame); +} +void RobotClient::requestSpeedJ(const QString &deviceId, const QVariantList &velocities, + double acceleration, double duration) +{ + emit armCommandStarting(deviceId); + emit speedJRequested(deviceId, velocities, acceleration, duration); +} +void RobotClient::requestSpeedL(const QString &deviceId, const QVariantMap &velocity, + double acceleration, double duration, bool toolFrame) +{ + emit armCommandStarting(deviceId); + emit speedLRequested(deviceId, velocity, acceleration, duration, toolFrame); +} +void RobotClient::requestMoveJ(const QString &deviceId, const QVariantList &positions, + double velocity, double acceleration) +{ + emit armCommandStarting(deviceId); + emit moveJRequested(deviceId, positions, velocity, acceleration); +} +void RobotClient::requestMoveJPose(const QString &deviceId, const QVariantMap &pose, + const QString &baseLink, const QString &eeLink, + double velocity, double acceleration) +{ + emit tcpReferenceInvalidated(deviceId); + emit moveJPoseRequested(deviceId, pose, baseLink, eeLink, velocity, acceleration); +} +void RobotClient::requestTorque(const QString &deviceId, bool enabled) { emit armCommandStarting(deviceId); emit torqueRequested(deviceId, enabled); } +void RobotClient::requestArmStop(const QString &deviceId) { emit armStopRequested(deviceId); } +void RobotClient::requestArmClearFault(const QString &deviceId) { emit armClearFaultRequested(deviceId); } +void RobotClient::requestArmCalibrateZero(const QString &deviceId, const QString &jointName) +{ + emit armCommandStarting(deviceId); + emit armCalibrateZeroRequested(deviceId, jointName); +} +void RobotClient::requestSnapshot(const QString &cameraId) { emit snapshotRequested(cameraId); } +void RobotClient::requestTouchRgbdImage(const QString &cameraId, quint64 token) +{ + emit touchRgbdImageRequested(cameraId, token); +} + +void RobotClient::requestHandEyeImage(const QString &cameraId, quint64 token) +{ + emit handEyeImageRequested(cameraId, token); +} +void RobotClient::startCameraStream(const QString &cameraId, const QString &codec, + const QString &mode) +{ + emit cameraStreamStartRequested(cameraId, codec, mode); +} +void RobotClient::setCameraStreamCodec(const QString &codec) +{ + emit cameraStreamCodecRequested(codec); +} +void RobotClient::stopCameraStream(const QString &cameraId) +{ + emit cameraStreamStopRequested(cameraId); +} +void RobotClient::startCameraRecording(const QString &cameraId, const QString &videoPath) +{ + emit cameraRecordingStartRequested(cameraId, videoPath); +} +void RobotClient::stopCameraRecording(const QString &cameraId) +{ + emit cameraRecordingStopRequested(cameraId); +} +void RobotClient::requestSystemRefresh() { emit systemRefreshRequested(); } +void RobotClient::requestSystemStopAll(const QString &deviceId) { emit systemStopAllRequested(deviceId); } +void RobotClient::requestAgvRefresh(const QString &deviceId) { emit agvRefreshRequested(deviceId); } +void RobotClient::requestAgvNavigatePose(const QString &deviceId, double x, double y, + double theta, double maxSpeed) +{ + emit agvNavigatePoseRequested(deviceId, x, y, theta, maxSpeed); +} +void RobotClient::requestAgvNavigateStation(const QString &deviceId, const QString &stationId, + double maxSpeed) +{ + emit agvNavigateStationRequested(deviceId, stationId, maxSpeed); +} +void RobotClient::requestAgvFollowPath(const QString &deviceId, const QVariantList &path, + double maxSpeed) +{ + emit agvFollowPathRequested(deviceId, path, maxSpeed); +} +void RobotClient::requestAgvVelocity(const QString &deviceId, double vx, double vy, double wz) +{ + emit agvVelocityRequested(deviceId, vx, vy, wz); +} +void RobotClient::requestAgvAction(const QString &deviceId, const QString &action) +{ + emit agvActionRequested(deviceId, action); +} +void RobotClient::requestAgvInventory(const QString &deviceId) { emit agvInventoryRequested(deviceId); } +void RobotClient::requestAgvSwitchMap(const QString &deviceId, const QString &mapName) +{ + emit agvSwitchMapRequested(deviceId, mapName); +} +void RobotClient::startAgvMapStream(const QString &deviceId, const QString &mapName, + int dimension, bool snapshot, bool incremental) +{ + emit agvMapStreamStartRequested(deviceId, mapName, dimension, snapshot, incremental); +} +void RobotClient::stopAgvMapStream() +{ + emit agvMapStreamStopRequested(); +} +void RobotClient::requestRpc(const QString &serviceName, const QString &methodName, + const QString &requestJson, const QString &deviceId) +{ + const QString method = methodName.toLower(); + if (serviceName.contains(QStringLiteral("ArmService"), Qt::CaseInsensitive) + && !method.startsWith(QStringLiteral("get")) && !method.startsWith(QStringLiteral("list"))) + emit tcpReferenceInvalidated(deviceId); + emit rpcRequested(serviceName, methodName, requestJson, deviceId); +} + +void RobotClient::startSpeakerAudioStream(const QString &deviceId) +{ + emit speakerAudioStreamStartRequested(deviceId); +} + +void RobotClient::sendSpeakerAudioFrame(const QByteArray &data, int sampleRate, int channels, + qint64 pts, int samples) +{ + emit speakerAudioFrameRequested(data, sampleRate, channels, pts, samples); +} + +void RobotClient::stopSpeakerAudioStream() +{ + emit speakerAudioStreamStopRequested(); +} + +void RobotClient::startMicrophoneAudioStream(const QString &deviceId) +{ + emit microphoneAudioStreamStartRequested(deviceId); +} + +void RobotClient::stopMicrophoneAudioStream() +{ + emit microphoneAudioStreamStopRequested(); +} + +void RobotClient::connectConfigurationServer(const QString &host, int port) +{ + emit configurationConnectRequested(host, port); +} + +void RobotClient::disconnectConfigurationServer() +{ + emit configurationDisconnectRequested(); +} + +void RobotClient::requestConfigurationFiles() +{ + emit configurationFilesRequested(); +} + +void RobotClient::readConfigurationFile(const QString &relativePath) +{ + emit configurationFileReadRequested(relativePath); +} + +void RobotClient::validateConfigurationFile(const QString &relativePath, + const QString &content) +{ + emit configurationFileValidateRequested(relativePath, content); +} + +void RobotClient::saveConfigurationFile(const QString &relativePath, const QString &content, + const QString &expectedRevision) +{ + emit configurationFileSaveRequested(relativePath, content, expectedRevision); +} diff --git a/src/robotclient.h b/src/robotclient.h index f640b65..4d3a6c7 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -1,206 +1,228 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "videoframe.h" - -class BackendWorker; - -class RobotClient : public QObject -{ - Q_OBJECT - -public: - explicit RobotClient(QObject *parent = nullptr); - ~RobotClient() override; - - bool grpcAvailable() const; - -public slots: - void connectToServer(const QString &host, int port, bool demoMode); - void disconnectFromServer(); - void setArmTelemetry(const QString &deviceId, bool enabled); - void requestArmInfo(const QString &deviceId); - void requestArmFrames(const QString &deviceId); - void setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame, - const QString &tcpFrame); - void requestSpeedJ(const QString &deviceId, const QVariantList &velocities, - double acceleration, double duration); - void requestSpeedL(const QString &deviceId, const QVariantMap &velocity, - double acceleration, double duration, bool toolFrame); - void requestMoveJ(const QString &deviceId, const QVariantList &positions, - double velocity, double acceleration); - void requestMoveJPose(const QString &deviceId, const QVariantMap &pose, - const QString &baseLink, const QString &eeLink, - double velocity, double acceleration); - void requestTorque(const QString &deviceId, bool enabled); - void requestArmStop(const QString &deviceId); - void requestArmClearFault(const QString &deviceId); - void requestArmCalibrateZero(const QString &deviceId, const QString &jointName); - void requestSnapshot(const QString &cameraId); - void startCameraStream(const QString &cameraId, const QString &codec, - const QString &mode = QStringLiteral("rgb")); - void setCameraStreamCodec(const QString &codec); - void stopCameraStream(const QString &cameraId = QString()); - void startCameraRecording(const QString &cameraId, const QString &videoPath); - void stopCameraRecording(const QString &cameraId); - void requestSystemRefresh(); - void requestSystemStopAll(const QString &deviceId); - void requestAgvRefresh(const QString &deviceId); - void requestAgvRelocalize(const QString &deviceId, double x, double y, - double theta); - void requestAgvNavigatePose(const QString &deviceId, double x, double y, - double theta, double maxSpeed); - void requestAgvNavigateStation(const QString &deviceId, const QString &stationId, - double maxSpeed); - void requestAgvFollowPath(const QString &deviceId, const QVariantList &path, - double maxSpeed); - void requestAgvVelocity(const QString &deviceId, double vx, double vy, double wz); - void requestAgvAction(const QString &deviceId, const QString &action); - void requestAgvInventory(const QString &deviceId); - void requestAgvSwitchMap(const QString &deviceId, const QString &mapName); - void startAgvMapStream(const QString &deviceId, const QString &mapName, - int dimension, bool snapshot, bool incremental); - void stopAgvMapStream(); - void requestRpc(const QString &serviceName, const QString &methodName, - const QString &requestJson, const QString &deviceId = QString()); - void startSpeakerAudioStream(const QString &deviceId); - void sendSpeakerAudioFrame(const QByteArray &data, int sampleRate, int channels, - qint64 pts, int samples); - void stopSpeakerAudioStream(); - void startMicrophoneAudioStream(const QString &deviceId); - void stopMicrophoneAudioStream(); - void connectConfigurationServer(const QString &host, int port); - void disconnectConfigurationServer(); - void requestConfigurationFiles(); - void readConfigurationFile(const QString &relativePath); - void validateConfigurationFile(const QString &relativePath, const QString &content); - void saveConfigurationFile(const QString &relativePath, const QString &content, - const QString &expectedRevision); - -signals: - void connectRequested(const QString &host, int port, bool demoMode); - void disconnectRequested(); - void armTelemetryRequested(const QString &deviceId, bool enabled); - void armInfoRequested(const QString &deviceId); - void armFramesRequested(const QString &deviceId); - void armTelemetryFramesRequested(const QString &deviceId, const QString &baseFrame, - const QString &tcpFrame); - void speedJRequested(const QString &deviceId, const QVariantList &velocities, - double acceleration, double duration); - void speedLRequested(const QString &deviceId, const QVariantMap &velocity, - double acceleration, double duration, bool toolFrame); - void moveJRequested(const QString &deviceId, const QVariantList &positions, - double velocity, double acceleration); - void moveJPoseRequested(const QString &deviceId, const QVariantMap &pose, - const QString &baseLink, const QString &eeLink, - double velocity, double acceleration); - void torqueRequested(const QString &deviceId, bool enabled); - void armStopRequested(const QString &deviceId); - void armClearFaultRequested(const QString &deviceId); - void armCalibrateZeroRequested(const QString &deviceId, const QString &jointName); - void snapshotRequested(const QString &cameraId); - void cameraStreamStartRequested(const QString &cameraId, const QString &codec, - const QString &mode); - void cameraStreamCodecRequested(const QString &codec); - void cameraStreamStopRequested(const QString &cameraId); - void cameraRecordingStartRequested(const QString &cameraId, const QString &videoPath); - void cameraRecordingStopRequested(const QString &cameraId); - void systemRefreshRequested(); - void systemStopAllRequested(const QString &deviceId); - void agvRefreshRequested(const QString &deviceId); - void agvRelocalizeRequested(const QString &deviceId, double x, double y, - double theta); - void agvNavigatePoseRequested(const QString &deviceId, double x, double y, - double theta, double maxSpeed); - void agvNavigateStationRequested(const QString &deviceId, const QString &stationId, - double maxSpeed); - void agvFollowPathRequested(const QString &deviceId, const QVariantList &path, - double maxSpeed); - void agvVelocityRequested(const QString &deviceId, double vx, double vy, double wz); - void agvActionRequested(const QString &deviceId, const QString &action); - void agvInventoryRequested(const QString &deviceId); - void agvSwitchMapRequested(const QString &deviceId, const QString &mapName); - void agvMapStreamStartRequested(const QString &deviceId, const QString &mapName, - int dimension, bool snapshot, bool incremental); - void agvMapStreamStopRequested(); - void rpcRequested(const QString &serviceName, const QString &methodName, - const QString &requestJson, const QString &deviceId); - void speakerAudioStreamStartRequested(const QString &deviceId); - void speakerAudioFrameRequested(const QByteArray &data, int sampleRate, int channels, - qint64 pts, int samples); - void speakerAudioStreamStopRequested(); - void microphoneAudioStreamStartRequested(const QString &deviceId); - void microphoneAudioStreamStopRequested(); - void configurationConnectRequested(const QString &host, int port); - void configurationDisconnectRequested(); - void configurationFilesRequested(); - void configurationFileReadRequested(const QString &relativePath); - void configurationFileValidateRequested(const QString &relativePath, - const QString &content); - void configurationFileSaveRequested(const QString &relativePath, const QString &content, - const QString &expectedRevision); - - void connectionChanged(bool connected, int latencyMs, const QString &detail); - void armInfoReceived(const QString &deviceId, const QVariantMap &info); - void armFramesReceived(const QString &deviceId, const QStringList &baseFrames, - const QStringList &tcpFrames); - void telemetryReceived(const QString &deviceId, const QVariantList &joints, - const QVariantMap &pose, const QVariantMap &state); - void armTelemetryHealthChanged(const QString &deviceId, bool available, - const QString &detail); - void systemStatusReceived(double cpu, double memory, double disk, - const QVariantList &devices); - void systemInfoReceived(const QVariantMap &info); - void imageReceived(const QImage &image, const QString &detail); - void videoFrameReceived(const QString &cameraId, const VideoFrame &frame, - const QString &detail); - void cameraStreamStateChanged(const QString &cameraId, bool running, - const QString &detail); - void cameraRecordingStateChanged(bool recording, const QString &detail); - void agvStateReceived(const QVariantMap &state, const QVariantMap &navigation); - void agvInventoryReceived(const QStringList &maps, const QVariantList &stations); - void agvMapFrameReceived(const QImage &image, const QVariantMap &metadata, - const QString &detail); - void agvMapStreamStateChanged(bool running, const QString &detail); - void rpcFinished(const QString &serviceName, const QString &methodName, - bool success, const QString &responseJson); - void audioStreamStateChanged(const QString &serviceName, bool running, - const QString &detail); - void audioStreamStatistics(const QString &serviceName, quint64 frames, - quint64 bytes, qint64 durationMs); - void audioFrameReceived(const QByteArray &data, int sampleRate, int channels, - int format, const QString &codec, qint64 pts, int samples); - void configurationConnectionChanged(bool connected, const QString &detail); - void configurationFilesReceived(const QString &configRoot, const QVariantList &files, - bool success, const QString &detail); - void configurationFileReceived(const QString &relativePath, const QString &content, - const QString &revision, const QString &messageType, - bool success, const QString &detail); - void configurationValidationFinished(const QString &relativePath, bool success, - const QString &detail); - void configurationSaveFinished(const QString &relativePath, const QString &revision, - bool success, const QString &detail); - void commandFinished(const QString &command, bool success, const QString &detail); - void logMessage(const QString &level, const QString &message); - -private: - QThread m_thread; - BackendWorker *m_worker = nullptr; - QMutex m_videoFrameMutex; - struct PendingVideoFrame { - VideoFrame frame; - QString detail; - }; - QHash m_pendingVideoFrames; - QSet m_videoFrameDeliveryScheduled; -}; +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "videoframe.h" + +class BackendWorker; + +class RobotClient : public QObject +{ + Q_OBJECT + +public: + explicit RobotClient(QObject *parent = nullptr); + ~RobotClient() override; + + bool grpcAvailable() const; + +public slots: + void connectToServer(const QString &host, int port, bool demoMode); + void disconnectFromServer(); + void setArmTelemetry(const QString &deviceId, bool enabled); + void requestArmInfo(const QString &deviceId); + void requestTcpCalibrationPose(const QString &deviceId, quint64 requestId); + void requestTcpJogMove(const QString &deviceId, const QVariantMap &pose, + double velocity, double acceleration, quint64 token); + void requestArmFrames(const QString &deviceId); + void setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame, + const QString &tcpFrame); + void requestSpeedJ(const QString &deviceId, const QVariantList &velocities, + double acceleration, double duration); + void requestSpeedL(const QString &deviceId, const QVariantMap &velocity, + double acceleration, double duration, bool toolFrame); + void requestMoveJ(const QString &deviceId, const QVariantList &positions, + double velocity, double acceleration); + void requestMoveJPose(const QString &deviceId, const QVariantMap &pose, + const QString &baseLink, const QString &eeLink, + double velocity, double acceleration); + void requestTorque(const QString &deviceId, bool enabled); + void requestArmStop(const QString &deviceId); + void requestArmClearFault(const QString &deviceId); + void requestArmCalibrateZero(const QString &deviceId, const QString &jointName); + void requestSnapshot(const QString &cameraId); + void requestHandEyeImage(const QString &cameraId, quint64 token); + void requestTouchRgbdImage(const QString &cameraId, quint64 token); + void startCameraStream(const QString &cameraId, const QString &codec, + const QString &mode = QStringLiteral("rgb")); + void setCameraStreamCodec(const QString &codec); + void stopCameraStream(const QString &cameraId = QString()); + void startCameraRecording(const QString &cameraId, const QString &videoPath); + void stopCameraRecording(const QString &cameraId); + void requestSystemRefresh(); + void requestSystemStopAll(const QString &deviceId); + void requestAgvRefresh(const QString &deviceId); + void requestAgvNavigatePose(const QString &deviceId, double x, double y, + double theta, double maxSpeed); + void requestAgvNavigateStation(const QString &deviceId, const QString &stationId, + double maxSpeed); + void requestAgvFollowPath(const QString &deviceId, const QVariantList &path, + double maxSpeed); + void requestAgvVelocity(const QString &deviceId, double vx, double vy, double wz); + void requestAgvAction(const QString &deviceId, const QString &action); + void requestAgvInventory(const QString &deviceId); + void requestAgvSwitchMap(const QString &deviceId, const QString &mapName); + void startAgvMapStream(const QString &deviceId, const QString &mapName, + int dimension, bool snapshot, bool incremental); + void stopAgvMapStream(); + void requestRpc(const QString &serviceName, const QString &methodName, + const QString &requestJson, const QString &deviceId = QString()); + void startSpeakerAudioStream(const QString &deviceId); + void sendSpeakerAudioFrame(const QByteArray &data, int sampleRate, int channels, + qint64 pts, int samples); + void stopSpeakerAudioStream(); + void startMicrophoneAudioStream(const QString &deviceId); + void stopMicrophoneAudioStream(); + void connectConfigurationServer(const QString &host, int port); + void disconnectConfigurationServer(); + void requestConfigurationFiles(); + void readConfigurationFile(const QString &relativePath); + void validateConfigurationFile(const QString &relativePath, const QString &content); + void saveConfigurationFile(const QString &relativePath, const QString &content, + const QString &expectedRevision); + +signals: + // Synchronous arbitration before manual arm commands enter the worker queue. + void armCommandStarting(const QString &deviceId); + // Emitted synchronously before a command that may select another active TCP. + void tcpReferenceInvalidated(const QString &deviceId); + void connectRequested(const QString &host, int port, bool demoMode); + void disconnectRequested(); + void armTelemetryRequested(const QString &deviceId, bool enabled); + void armInfoRequested(const QString &deviceId); + void tcpCalibrationPoseRequested(const QString &deviceId, quint64 requestId); + void tcpJogMoveRequested(const QString &deviceId, const QVariantMap &pose, + double velocity, double acceleration, quint64 token); + void armFramesRequested(const QString &deviceId); + void armTelemetryFramesRequested(const QString &deviceId, const QString &baseFrame, + const QString &tcpFrame); + void speedJRequested(const QString &deviceId, const QVariantList &velocities, + double acceleration, double duration); + void speedLRequested(const QString &deviceId, const QVariantMap &velocity, + double acceleration, double duration, bool toolFrame); + void moveJRequested(const QString &deviceId, const QVariantList &positions, + double velocity, double acceleration); + void moveJPoseRequested(const QString &deviceId, const QVariantMap &pose, + const QString &baseLink, const QString &eeLink, + double velocity, double acceleration); + void torqueRequested(const QString &deviceId, bool enabled); + void armStopRequested(const QString &deviceId); + void armClearFaultRequested(const QString &deviceId); + void armCalibrateZeroRequested(const QString &deviceId, const QString &jointName); + void snapshotRequested(const QString &cameraId); + void handEyeImageRequested(const QString &cameraId, quint64 token); + void touchRgbdImageRequested(const QString &cameraId, quint64 token); + void cameraStreamStartRequested(const QString &cameraId, const QString &codec, + const QString &mode); + void cameraStreamCodecRequested(const QString &codec); + void cameraStreamStopRequested(const QString &cameraId); + void cameraRecordingStartRequested(const QString &cameraId, const QString &videoPath); + void cameraRecordingStopRequested(const QString &cameraId); + void systemRefreshRequested(); + void systemStopAllRequested(const QString &deviceId); + void agvRefreshRequested(const QString &deviceId); + void agvNavigatePoseRequested(const QString &deviceId, double x, double y, + double theta, double maxSpeed); + void agvNavigateStationRequested(const QString &deviceId, const QString &stationId, + double maxSpeed); + void agvFollowPathRequested(const QString &deviceId, const QVariantList &path, + double maxSpeed); + void agvVelocityRequested(const QString &deviceId, double vx, double vy, double wz); + void agvActionRequested(const QString &deviceId, const QString &action); + void agvInventoryRequested(const QString &deviceId); + void agvSwitchMapRequested(const QString &deviceId, const QString &mapName); + void agvMapStreamStartRequested(const QString &deviceId, const QString &mapName, + int dimension, bool snapshot, bool incremental); + void agvMapStreamStopRequested(); + void rpcRequested(const QString &serviceName, const QString &methodName, + const QString &requestJson, const QString &deviceId); + void speakerAudioStreamStartRequested(const QString &deviceId); + void speakerAudioFrameRequested(const QByteArray &data, int sampleRate, int channels, + qint64 pts, int samples); + void speakerAudioStreamStopRequested(); + void microphoneAudioStreamStartRequested(const QString &deviceId); + void microphoneAudioStreamStopRequested(); + void configurationConnectRequested(const QString &host, int port); + void configurationDisconnectRequested(); + void configurationFilesRequested(); + void configurationFileReadRequested(const QString &relativePath); + void configurationFileValidateRequested(const QString &relativePath, + const QString &content); + void configurationFileSaveRequested(const QString &relativePath, const QString &content, + const QString &expectedRevision); + + void connectionChanged(bool connected, int latencyMs, const QString &detail); + void armInfoReceived(const QString &deviceId, const QVariantMap &info); + // Raw active TCP in the driver's base frame; this is not a flange pose. + void tcpCalibrationPoseReceived(quint64 requestId, const QString &deviceId, + const QVariantMap &pose, const QVariantMap &state, + bool success, const QString &detail); + void armFramesReceived(const QString &deviceId, const QStringList &baseFrames, + const QStringList &tcpFrames); + void telemetryReceived(const QString &deviceId, const QVariantList &joints, + const QVariantMap &pose, const QVariantMap &state); + void armTelemetryHealthChanged(const QString &deviceId, bool available, + const QString &detail); + void systemStatusReceived(double cpu, double memory, double disk, + const QVariantList &devices); + void systemInfoReceived(const QVariantMap &info); + void imageReceived(const QImage &image, const QString &detail); + // success validates image/intrinsics only. Pairing must additionally check + // metadata.captureTimestampAvailable and its captureUtcNs against robot poses. + void handEyeImageReceived(quint64 token, const QString &cameraId, + const QImage &image, const QVariantMap &intrinsics, + const QVariantMap &metadata, bool success, + const QString &detail); + void touchRgbdImageReceived(quint64 token, const QString &cameraId, + const QImage &image, const QVariantMap &intrinsics, + const QVariantMap &metadata, bool success, const QString &detail); + void videoFrameReceived(const QString &cameraId, const VideoFrame &frame, + const QString &detail); + void cameraStreamStateChanged(const QString &cameraId, bool running, + const QString &detail); + void cameraRecordingStateChanged(bool recording, const QString &detail); + void agvStateReceived(const QVariantMap &state, const QVariantMap &navigation); + void agvInventoryReceived(const QStringList &maps, const QVariantList &stations); + void agvMapFrameReceived(const QImage &image, const QString &detail); + void agvMapStreamStateChanged(bool running, const QString &detail); + void rpcFinished(const QString &serviceName, const QString &methodName, + bool success, const QString &responseJson); + void audioStreamStateChanged(const QString &serviceName, bool running, + const QString &detail); + void audioStreamStatistics(const QString &serviceName, quint64 frames, + quint64 bytes, qint64 durationMs); + void audioFrameReceived(const QByteArray &data, int sampleRate, int channels, + int format, const QString &codec, qint64 pts, int samples); + void configurationConnectionChanged(bool connected, const QString &detail); + void configurationFilesReceived(const QString &configRoot, const QVariantList &files, + bool success, const QString &detail); + void configurationFileReceived(const QString &relativePath, const QString &content, + const QString &revision, const QString &messageType, + bool success, const QString &detail); + void configurationValidationFinished(const QString &relativePath, bool success, + const QString &detail); + void configurationSaveFinished(const QString &relativePath, const QString &revision, + bool success, const QString &detail); + void commandFinished(const QString &command, bool success, const QString &detail); + void logMessage(const QString &level, const QString &message); + +private: + QThread m_thread; + BackendWorker *m_worker = nullptr; + QMutex m_videoFrameMutex; + struct PendingVideoFrame { + VideoFrame frame; + QString detail; + }; + QHash m_pendingVideoFrames; + QSet m_videoFrameDeliveryScheduled; +}; diff --git a/src/touchplanner.cpp b/src/touchplanner.cpp new file mode 100644 index 0000000..a099800 --- /dev/null +++ b/src/touchplanner.cpp @@ -0,0 +1,369 @@ +#include "touchplanner.h" +#include +#include +#include +#include + +namespace TouchPlanner { +namespace { +bool fail(QString *error, const char *message) { + if (error) *error=QString::fromUtf8(message); + return false; +} +void clear(QString *error) { if (error) error->clear(); } +bool finite(const Point &p) { return std::all_of(p.begin(),p.end(),[](double v){return std::isfinite(v);}); } +double norm(const Point &p) { return std::hypot(std::hypot(p[0],p[1]),p[2]); } +Point subtract(const Point &a,const Point &b) { return {{a[0]-b[0],a[1]-b[1],a[2]-b[2]}}; } +double dot(const Point &a,const Point &b) { return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]; } +Point position(const Pose &p) { return {{p[0],p[1],p[2]}}; } +Point shifted(const Point &p,const Point &n,double distance) { + return {{p[0]+n[0]*distance,p[1]+n[1]*distance,p[2]+n[2]*distance}}; +} +bool within(double value,double minimum,double maximum) { + return std::isfinite(value) && value>=minimum && value<=maximum; +} +bool validParameters(const Parameters &p,QString *error) { + if (!within(p.approachM,.001,.05) || !within(p.contactOffsetM,0,.002) + || !within(p.doubleLiftM,.0005,.05) + || !within(p.contactVelocityMps,.005,.03) || !within(p.travelVelocityMps,.005,.1) + || !within(p.accelerationMps2,.01,.5) || p.contactDwellMs<0 || p.contactDwellMs>5000 + || p.doubleIntervalMs<0 || p.doubleIntervalMs>500 + || !within(p.maxTravelM,.01,1) || !within(p.maxReachM,.05,3) + || !within(p.maxCameraRangeM,.05,5)) + return fail(error,"触控参数超出允许范围,检查距离、速度、加速度和停留时间。"); + return true; +} +bool validPlane(const Plane &p,QString *error) { + if (!finite(p.origin) || !finite(p.normal) || !finite(p.orientationRad) + || norm(p.origin)>3 || std::abs(norm(p.normal)-1)>1e-6) + return fail(error,"目标位置、触控姿态或接近方向无效,请重新取点。"); + return true; +} +bool validCamera(const CameraModel &c,QString *error) { + if (c.width<2 || c.width>16384 || c.height<2 || c.height>16384 + || !within(c.fx,1,1e6) || !within(c.fy,1,1e6) + || !within(c.cx,-c.width,2.0*c.width) || !within(c.cy,-c.height,2.0*c.height)) + return fail(error,"RGB 图像尺寸、焦距或主点无效。"); + const auto size=c.distortion.size(); + if (size!=0 && size!=4 && size!=5 && size!=8) + return fail(error,"仅支持无畸变或 4、5、8 项标准 Brown 畸变系数。"); + for (double v:c.distortion) if (!within(v,-100,100)) + return fail(error,"RGB 畸变系数不是有效的有限数值。"); + return true; +} +bool number(const QVariant &v,double &out) { + if (v.type()!=QVariant::Double && v.type()!=QVariant::Int && v.type()!=QVariant::UInt + && v.type()!=QVariant::LongLong && v.type()!=QVariant::ULongLong) return false; + out=v.toDouble(); return std::isfinite(out); +} +// Brown forward projection and analytic Jacobian. A positive, non-singular +// Jacobian is required so an inverse on a folded distortion branch is rejected. +bool distort(double x,double y,const std::array &k, + double &dx,double &dy,std::array &j) { + if (!within(x,-5,5) || !within(y,-5,5)) return false; + const double r2=x*x+y*y,r4=r2*r2,r6=r4*r2; + const double a=1+k[0]*r2+k[1]*r4+k[4]*r6; + const double b=1+k[5]*r2+k[6]*r4+k[7]*r6; + if (!std::isfinite(a) || !std::isfinite(b) || a<=1e-9 || b<=1e-9) return false; + const double radial=a/b; + const double derivative=((k[0]+2*k[1]*r2+3*k[4]*r4)*b + -a*(k[5]+2*k[6]*r2+3*k[7]*r4))/(b*b); + dx=x*radial+2*k[2]*x*y+k[3]*(r2+2*x*x); + dy=y*radial+k[2]*(r2+2*y*y)+2*k[3]*x*y; + j={{radial+2*x*x*derivative+2*k[2]*y+6*k[3]*x, + 2*x*y*derivative+2*k[2]*x+2*k[3]*y, + 2*x*y*derivative+2*k[2]*x+2*k[3]*y, + radial+2*y*y*derivative+6*k[2]*y+2*k[3]*x}}; + const double det=j[0]*j[3]-j[1]*j[2]; + return std::isfinite(dx) && std::isfinite(dy) && std::isfinite(det) && det>1e-10; +} +bool ray(const QPointF &pixel,const CameraModel &c,Point &direction,QString *error) { + if (!within(pixel.x(),0,c.width-1.0) || !within(pixel.y(),0,c.height-1.0)) + return fail(error,"触控像素必须位于所锁定的 RGB 图像内。"); + const double wantedX=(pixel.x()-c.cx)/c.fx,wantedY=(pixel.y()-c.cy)/c.fy; + double x=wantedX,y=wantedY; + std::array k{}; + std::copy(c.distortion.begin(),c.distortion.end(),k.begin()); + bool converged=false; + for (int iteration=0;iteration<30;++iteration) { + double actualX=0,actualY=0; std::array j{}; + if (!distort(x,y,k,actualX,actualY,j)) + return fail(error,"畸变反解不稳定,不能生成触控射线。"); + const double ex=actualX-wantedX,ey=actualY-wantedY; + if (std::hypot(ex,ey)<1e-12) { converged=true; break; } + const double det=j[0]*j[3]-j[1]*j[2]; + const double sx=(j[3]*ex-j[1]*ey)/det,sy=(-j[2]*ex+j[0]*ey)/det; + bool improved=false; + for (int search=0;search<12;++search) { + const double scale=std::ldexp(1.0,-search); + const double tx=x-scale*sx,ty=y-scale*sy; + double px=0,py=0; std::array unused{}; + if (distort(tx,ty,k,px,py,unused) && std::hypot(px-wantedX,py-wantedY) &contacts,const Pose &observation,Plane &plane,QString *error) { + if (!TcpCalibration::validPose(observation) || norm(position(observation))>3) + return fail(error,"观察位必须是有限的米制 TCP 位姿。"); + for (const Pose &p:contacts) if (!TcpCalibration::validPose(p) || norm(position(p))>3) + return fail(error,"平面示教点必须是有限的米制 TCP 位姿。"); + const Point a=subtract(position(contacts[1]),position(contacts[0])); + const Point b=subtract(position(contacts[2]),position(contacts[0])); + const double la=norm(a),lb=norm(b); + if (!within(la,.01,1) || !within(lb,.01,1) + || !within(norm(subtract(position(contacts[2]),position(contacts[1]))),.01,1)) + return fail(error,"三个平面示教点之间至少间隔 10 mm,最大基线不超过 1 m。"); + Point n{{a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]}}; + const double length=norm(n); + if (length/(la*lb)<.08715574274765817) + return fail(error,"平面示教点共线或接近共线,请扩大点位三角形(夹角至少 5 度)。"); + for (double &v:n) v/=length; + const double side=dot(subtract(position(observation),position(contacts[0])),n); + if (std::abs(side)<.001) + return fail(error,"观察位必须离开触控平面至少 1 mm,以确定安全回撤方向。"); + if (side<0) for (double &v:n) v=-v; + Plane result; result.origin=position(contacts[0]); result.normal=n; + result.orientationRad={{contacts[0][3],contacts[0][4],contacts[0][5]}}; + plane=result; clear(error); return true; +} + +bool cameraTransform(const HandEyeStore::Record &record,const Pose &flange,Matrix &baseCamera,QString *error) { + QString detail; + if (!HandEyeStore::validateRecord(record,detail)) { if (error) *error=detail; return false; } + Matrix result=record.transform; + if (record.mode==QStringLiteral("eye_in_hand")) { + Matrix baseFlange{}; + if (!TcpCalibration::poseMatrix(flange,baseFlange,error)) return false; + result.fill(0); + for (int r=0;r<4;++r) for (int c=0;c<4;++c) for (int k=0;k<4;++k) + result[size_t(4*r+c)]+=baseFlange[size_t(4*r+k)]*record.transform[size_t(4*k+c)]; + } + Pose checked{}; + if (!TcpCalibration::matrixPose(result,checked,error)) return false; + baseCamera=result; clear(error); return true; +} + +bool cameraModel(const QVariantMap &data,int width,int height,CameraModel &camera,QString *error) { + CameraModel result; result.width=width; result.height=height; + for (const QString &key:{QStringLiteral("width"),QStringLiteral("height")}) if (data.contains(key)) { + double value=0; + if (!number(data.value(key),value) || value!=(key=="width"?width:height)) + return fail(error,"RGB 内参尺寸与图像不一致,禁止自动缩放或使用裁剪图。"); + } + for (const QString &key:{QStringLiteral("model"),QStringLiteral("distortion_model")}) if (data.contains(key)) { + const QString model=data.value(key).toString().trimmed().toLower(); + if (model!="none" && model!="0" && model!="4" && model!="brown_conrady" + && model!="brown-conrady" && model!="opencv" && model!="plumb_bob" + && model!="rational_polynomial") + return fail(error,"当前 RGB 畸变模型不是受支持的标准 Brown 模型。"); + } + if (data.contains("camera_matrix")) { + const auto values=data.value("camera_matrix").toList(); + std::array k{}; + if (values.size()!=9) return fail(error,"相机内参矩阵需要 9 个有限数值。"); + for (int i=0;i<9;++i) if (!number(values[i],k[size_t(i)])) + return fail(error,"相机内参矩阵需要 9 个有限数值。"); + if (std::abs(k[1])+std::abs(k[3])+std::abs(k[6])+std::abs(k[7])+std::abs(k[8]-1)>1e-9) + return fail(error,"相机内参必须为无斜切的标准针孔矩阵。"); + result.fx=k[0]; result.fy=k[4]; result.cx=k[2]; result.cy=k[5]; + } else if (!number(data.value("fx"),result.fx) || !number(data.value("fy"),result.fy) + || !number(data.value("cx"),result.cx) || !number(data.value("cy"),result.cy)) { + return fail(error,"缺少有效的 RGB 焦距与主点参数。"); + } + const QVariant coefficients=data.value(data.contains("coeffs")?"coeffs":"distortion"); + if (coefficients.type()!=QVariant::List) + return fail(error,"RGB 内参必须明确提供畸变系数列表(无畸变时为空列表)。"); + for (const QVariant &v:coefficients.toList()) { + double value=0; + if (!number(v,value)) return fail(error,"畸变系数必须为有限数值。"); + result.distortion.push_back(value); + } + if (!validCamera(result,error)) return false; + camera=result; clear(error); return true; +} + +bool resolvePixels(const QVector &pixels,const CameraModel &camera,const Matrix &baseCamera, + const Plane &plane,const Parameters ¶meters,QVector &points,QString *error) { + if (pixels.isEmpty() || pixels.size()>2) return fail(error,"请选择 1 至 2 个 RGB 图像点。"); + if (!validCamera(camera,error) || !validPlane(plane,error) || !validParameters(parameters,error)) return false; + Pose cameraPose{}; + if (!TcpCalibration::matrixPose(baseCamera,cameraPose,error)) return false; + const Point origin=position(cameraPose); + if (norm(origin)>parameters.maxReachM) return fail(error,"相机基座坐标超出配置的工作空间范围。"); + QVector result; + for (const QPointF &pixel:pixels) { + Point cameraRay{},baseRay{}; + if (!ray(pixel,camera,cameraRay,error)) return false; + for (int r=0;r<3;++r) for (int c=0;c<3;++c) + baseRay[size_t(r)]+=baseCamera[size_t(r*4+c)]*cameraRay[size_t(c)]; + const double cosine=dot(plane.normal,baseRay); + if (std::abs(cosine)<.02) return fail(error,"像素射线与示教平面接近平行,无法可靠求交。"); + const double distance=dot(plane.normal,subtract(plane.origin,origin))/cosine; + if (!within(distance,.005,parameters.maxCameraRangeM)) + return fail(error,"触控交点位于相机后方、过近或超出相机距离限制。"); + const Point point=shifted(origin,baseRay,distance); + if (!finite(point) || norm(point)>parameters.maxReachM) + return fail(error,"触控交点超出配置的基座工作空间范围。"); + if (norm(subtract(point,plane.origin))>parameters.maxTravelM) + return fail(error,"触控交点离平面示教原点过远,超过最大行程。"); + result.append(point); + } + points=result; clear(error); return true; +} + +bool resolveDepthPixels(const QVector &pixels,const CameraModel &camera, + const DepthImage &depth,const Matrix &baseCamera,const Parameters &p, + QVector &basePoints,QVector &cameraPoints,QString *error) { + if (pixels.isEmpty() || pixels.size()>2 || !validCamera(camera,error) || !validParameters(p,error)) + return fail(error,"请选择 1 至 2 个有效 RGB 点并核对相机参数。"); + Pose pose{}; + if (!TcpCalibration::matrixPose(baseCamera,pose,error)) return false; + const int bytes=depth.float32?4:2; + if (depth.width!=camera.width || depth.height!=camera.height + || !within(depth.metresPerUnit,1e-9,1) + || qint64(depth.width)*depth.height*bytes!=depth.data.size()) + return fail(error,"缺少与锁定 RGB 对齐的原始深度或有效深度单位。"); + if (norm(position(pose))>p.maxReachM) return fail(error,"相机位置超出工作空间。"); + QVector base,cameraResult; + for (const auto &pixel:pixels) { + Point direction{}; if (!ray(pixel,camera,direction,error)) return false; + const int x=qRound(pixel.x()),y=qRound(pixel.y()); + std::vector samples; + // Phone _depth_mm: local valid-depth median. Keep a small 5x5 patch; + // reject depth edges instead of expanding onto an unrelated surface. + for (int v=qMax(0,y-2);v<=qMin(depth.height-1,y+2);++v) + for (int u=qMax(0,x-2);u<=qMin(depth.width-1,x+2);++u) { + const auto *raw=reinterpret_cast(depth.data.constData())+(v*depth.width+u)*bytes; + double value=0; + if (depth.float32) { + const quint32 bits=qFromLittleEndian(raw); float f=0; + std::memcpy(&f,&bits,sizeof(f)); value=f; + } else value=qFromLittleEndian(raw); + value*=depth.metresPerUnit; + if (within(value,.05,p.maxCameraRangeM)) samples.push_back(value); + } + if (samples.size()<5) return fail(error,"目标点附近有效深度不足,请重新取图或选择可测量位置。"); + std::sort(samples.begin(),samples.end()); + const double z=samples[samples.size()/2]; + if (samples.back()-samples.front()>.005) + return fail(error,"目标点处深度跳变超过 5 mm,请避开遮挡边缘或重新取图。"); + Point cp{},bp{}; + for (int i=0;i<3;++i) cp[i]=direction[i]*z/direction[2]; // Z, not Euclidean range. + if (norm(cp)>p.maxCameraRangeM) return fail(error,"目标超出相机测量范围。"); + for (int r=0;r<3;++r) { + bp[r]=baseCamera[r*4+3]; + for (int c=0;c<3;++c) bp[r]+=baseCamera[r*4+c]*cp[c]; + } + if (!finite(bp) || norm(bp)>p.maxReachM) return fail(error,"深度目标超出基座工作空间。"); + base.append(bp); cameraResult.append(cp); + } + basePoints=base; cameraPoints=cameraResult; clear(error); return true; +} + +bool validateDepthSwipe(const QVector &pixels,const CameraModel &camera, + const DepthImage &depth,const Matrix &baseCamera,const Parameters &p,QString *error) { + if (pixels.size()!=2) return fail(error,"滑动需要 A/B 两点。"); + QVector ends,unused; + if (!resolveDepthPixels(pixels,camera,depth,baseCamera,p,ends,unused,error)) return false; + const Point segment=subtract(ends[1],ends[0]); const double length=norm(segment); + if (length<.0001) return fail(error,"滑动端点间距不足 0.1 mm。"); + const int count=qMax(2,int(std::ceil(std::hypot(pixels[1].x()-pixels[0].x(),pixels[1].y()-pixels[0].y())/2))); + for (int i=1;i current; + if (!resolveDepthPixels({pixels[0]*(1-t)+pixels[1]*t},camera,depth,baseCamera,p,current,unused,error)) return false; + const Point delta=subtract(current[0],ends[0]); + const double along=dot(delta,segment)/(length*length); + if (along<-.01 || along>1.01 || norm(subtract(delta,shifted(Point{},segment,along)))>.003) + return fail(error,"滑动路径深度偏离直线超过 3 mm,不能执行直线触控。"); + } + clear(error); return true; +} + +bool buildPlan(Action action,const QVector &points,const Plane &plane,const Pose &observationActive, + const Pose &flangeActive,const Pose &flangeSelected,const Parameters &p,Plan &plan,QString *error,bool depthTargets) { + if (action!=Action::SingleTap && action!=Action::DoubleTap && action!=Action::Swipe) + return fail(error,"未知触控动作。"); + if (points.isEmpty() || points.size()>2 || (action==Action::Swipe && points.size()!=2)) + return fail(error,"单击或双击需要 1 至 2 点,滑动必须恰好选择 2 点。"); + if (!validPlane(plane,error) || !validParameters(p,error)) return false; + if (action==Action::DoubleTap && (p.doubleLiftMp.approachM+p.contactOffsetM)) + return fail(error,"双击短抬必须越过接触偏移至少 0.5 mm,且不超过接近点。"); + Pose observationFlange{},observationSelected{}; + if (!TcpCalibration::flangePose(observationActive,flangeActive,observationFlange,error) + || !TcpCalibration::toolPose(observationFlange,flangeSelected,observationSelected,error)) return false; + if (dot(subtract(position(observationSelected),plane.origin),plane.normal)1e-5)) + return fail(error,"触控目标不在已示教平面上。"); + if (depthTargets && dot(subtract(position(observationSelected),point),plane.normal)p.maxTravelM) + return fail(error,"触控目标之间的距离超过最大行程。"); + } + if (action==Action::Swipe && norm(subtract(points[0],points[1]))<.0001) + return fail(error,"滑动起点和终点至少间隔 0.1 mm。"); + Plan result; result.contacts=points; + Pose previousActive=observationActive,previousSelected=observationSelected; + double totalTravel=0; + const auto append=[&](const QString &label,const Pose &active,const Pose &selected, + double speed,int pause)->bool { + Pose flange{}; + if (!TcpCalibration::flangePose(active,flangeActive,flange,error)) return false; + if (!TcpCalibration::validPose(active) || !TcpCalibration::validPose(selected) + || norm(position(active))>p.maxReachM || norm(position(selected))>p.maxReachM + || norm(position(flange))>p.maxReachM) + return fail(error,"规划路径超出配置的 TCP / 法兰工作空间半径。"); + const double activeTravel=norm(subtract(position(active),position(previousActive))); + const double tipTravel=norm(subtract(position(selected),position(previousSelected))); + if (activeTravel>p.maxTravelM || tipTravel>p.maxTravelM + || norm(subtract(position(active),position(observationActive)))>p.maxTravelM + || norm(subtract(position(selected),position(observationSelected)))>p.maxTravelM) + return fail(error,"规划路径超出单段行程或观察位距离限制。"); + totalTravel+=std::max(activeTravel,tipTravel); + if (totalTravel>12*p.maxTravelM || result.steps.size()>=12) + return fail(error,"触控路径总行程或步骤数量超出限制。"); + result.steps.append(Step{label,active,speed,p.accelerationMps2,pause}); + previousActive=active; previousSelected=selected; return true; + }; + // Check the starting poses too, including a potentially long saved tool offset. + if (norm(position(observationActive))>p.maxReachM || norm(position(observationSelected))>p.maxReachM + || norm(position(observationFlange))>p.maxReachM) + return fail(error,"观察位超出配置的 TCP / 法兰工作空间半径。"); + const auto target=[&](const QString &label,const Point &surface,double normalOffset,double speed,int pause)->bool { + const Point xyz=shifted(surface,plane.normal,normalOffset); + const Pose selected{{xyz[0],xyz[1],xyz[2],plane.orientationRad[0],plane.orientationRad[1],plane.orientationRad[2]}}; + Pose flange{},active{}; + if (!TcpCalibration::flangePose(selected,flangeSelected,flange,error) + || !TcpCalibration::toolPose(flange,flangeActive,active,error)) return false; + return append(label,active,selected,speed,pause); + }; + const int visits=action==Action::Swipe?1:points.size(); + for (int visit=0;visit