From 19264915b4d991f8e6133e5e8779a6994159b776 Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Wed, 23 Sep 2026 17:25:01 +0800 Subject: [PATCH 01/15] feat: improve arm control workflow and Windows stability --- src/main.cpp | 86 +++++++++ src/mainwindow.cpp | 354 ++++++++++++++++++++++++++++++++++-- src/mainwindow.h | 52 ++++++ src/mainwindow_ui.cpp | 378 +++++++++++++++++++++++++++++++++------ src/robotclient.cpp | 40 ----- src/urdfviewerwidget.cpp | 114 ++++++++++-- styles.qss | 48 ++++- 7 files changed, 948 insertions(+), 124 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 11f7af7..7ca6fb9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -11,8 +11,94 @@ #include #include +#ifdef Q_OS_WIN +#include +#include + +namespace { + +LONG WINAPI writeCrashDump(EXCEPTION_POINTERS *exceptionPointers) +{ + static LONG handlingCrash = 0; + if (InterlockedCompareExchange(&handlingCrash, 1, 0) != 0) + return EXCEPTION_EXECUTE_HANDLER; + + wchar_t executablePath[MAX_PATH] = {}; + GetModuleFileNameW(nullptr, executablePath, MAX_PATH); + wchar_t *lastSeparator = wcsrchr(executablePath, L'\\'); + if (lastSeparator) + *lastSeparator = L'\0'; + + wchar_t dumpDirectory[MAX_PATH] = {}; + _snwprintf(dumpDirectory, MAX_PATH - 1, L"%ls\\crash_dumps", executablePath); + CreateDirectoryW(dumpDirectory, nullptr); + + SYSTEMTIME time = {}; + GetLocalTime(&time); + wchar_t baseName[96] = {}; + _snwprintf(baseName, 95, + L"CmvrControlStation_%04u%02u%02u_%02u%02u%02u_%lu", + time.wYear, time.wMonth, time.wDay, + time.wHour, time.wMinute, time.wSecond, + GetCurrentProcessId()); + + wchar_t dumpPath[MAX_PATH] = {}; + _snwprintf(dumpPath, MAX_PATH - 1, L"%ls\\%ls.dmp", dumpDirectory, baseName); + HANDLE dumpFile = CreateFileW(dumpPath, GENERIC_WRITE, FILE_SHARE_READ, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (dumpFile != INVALID_HANDLE_VALUE) { + MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = {}; + exceptionInfo.ThreadId = GetCurrentThreadId(); + exceptionInfo.ExceptionPointers = exceptionPointers; + exceptionInfo.ClientPointers = FALSE; + const MINIDUMP_TYPE dumpType = static_cast( + MiniDumpWithDataSegs | MiniDumpWithHandleData | + MiniDumpWithThreadInfo | MiniDumpWithIndirectlyReferencedMemory); + MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, + dumpType, &exceptionInfo, nullptr, nullptr); + FlushFileBuffers(dumpFile); + CloseHandle(dumpFile); + } + + wchar_t summaryPath[MAX_PATH] = {}; + _snwprintf(summaryPath, MAX_PATH - 1, L"%ls\\%ls.txt", dumpDirectory, baseName); + HANDLE summaryFile = CreateFileW(summaryPath, GENERIC_WRITE, FILE_SHARE_READ, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (summaryFile != INVALID_HANDLE_VALUE) { + const DWORD exceptionCode = exceptionPointers && exceptionPointers->ExceptionRecord + ? exceptionPointers->ExceptionRecord->ExceptionCode : 0; + const void *exceptionAddress = exceptionPointers && exceptionPointers->ExceptionRecord + ? exceptionPointers->ExceptionRecord->ExceptionAddress : nullptr; + char summary[512] = {}; + const int length = _snprintf(summary, sizeof(summary) - 1, + "Application: CmvrControlStation.exe\r\n" + "Timestamp: %04u-%02u-%02u %02u:%02u:%02u\r\n" + "Exception code: 0x%08lX\r\n" + "Exception address: %p\r\n" + "Process ID: %lu\r\nThread ID: %lu\r\n" + "Dump: %ls\r\n", + time.wYear, time.wMonth, time.wDay, + time.wHour, time.wMinute, time.wSecond, + exceptionCode, exceptionAddress, + GetCurrentProcessId(), GetCurrentThreadId(), dumpPath); + DWORD written = 0; + if (length > 0) + WriteFile(summaryFile, summary, static_cast(length), &written, nullptr); + FlushFileBuffers(summaryFile); + CloseHandle(summaryFile); + } + + return EXCEPTION_EXECUTE_HANDLER; +} + +} // namespace +#endif + int main(int argc, char *argv[]) { +#ifdef Q_OS_WIN + SetUnhandledExceptionFilter(writeCrashDump); +#endif QApplication app(argc, argv); app.setApplicationName(QStringLiteral("CMVR Control Station")); app.setOrganizationName(QStringLiteral("CMVR")); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index e3e1bed..be2e381 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -659,6 +659,7 @@ void MainWindow::updateTelemetry(const QVariantList &joints, const QVariantMap & byName.insert(name, joint); jointPositions.insert(name, joint.value(QStringLiteral("position")).toDouble()); } + m_latestArmJointPositions = jointPositions; if (m_urdfViewer) m_urdfViewer->setJointPositions(jointPositions); @@ -689,10 +690,13 @@ void MainWindow::updateTelemetry(const QVariantList &joints, const QVariantMap & if (!nameItem) continue; const QVariantMap joint = byName.value(nameItem->text()); - if (!joint.isEmpty()) + if (!joint.isEmpty()) { + const double position = joint.value(QStringLiteral("position")).toDouble(); table->item(row, 1)->setText(QStringLiteral("%1°").arg( - qRadiansToDegrees(joint.value(QStringLiteral("position")).toDouble()), + qRadiansToDegrees(position), 0, 'f', 2)); + table->item(row, 2)->setText(QString::number(position, 'f', 6)); + } } } @@ -967,6 +971,19 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri } appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"), QStringLiteral("%1 · %2").arg(command, detail)); + if (command == QStringLiteral("MoveJ") && m_jointPointMovePending) { + m_jointPointMovePending = false; + if (!success) { + stopJointPointLoop(QStringLiteral("MoveJ 执行失败:%1").arg(detail)); + } else if (m_jointPointLoopActive) { + const int completedIndex = m_jointPointLoopCursor - 1; + const double waitSeconds = completedIndex >= 0 + && completedIndex < m_jointPointExecutionWaits.size() + ? m_jointPointExecutionWaits.at(completedIndex) : 0.0; + const int delayMs = qRound(waitSeconds * 1000.0); + QTimer::singleShot(delayMs, this, &MainWindow::advanceJointPointLoop); + } + } if (!success) m_connectionText->setToolTip(detail); } @@ -1003,13 +1020,260 @@ void MainWindow::sendMoveJ() QVariantList positions; const bool leftArm = m_armSideCombo && m_armSideCombo->currentData().toString() == QStringLiteral("left"); - const int offset = leftArm ? 0 : 7; - for (int i = 0; i < 7 && offset + i < m_targetSpins.size(); ++i) - positions.append(qDegreesToRadians(m_targetSpins.at(offset + i)->value())); + const QList &spins = leftArm + ? m_leftTargetSpins : m_rightTargetSpins; + for (QDoubleSpinBox *spin : spins) + positions.append(qDegreesToRadians(spin->value())); m_client->requestMoveJ(m_armIdEdit->text().trimmed(), positions, m_velocitySpin->value(), m_accelerationSpin->value()); } +void MainWindow::refreshRecordedJointPoints() +{ + if (!m_jointPointTable) + return; + m_jointPointTable->setRowCount(m_recordedJointPoints.size()); + for (int row = 0; row < m_recordedJointPoints.size(); ++row) { + const RecordedJointPoint &point = m_recordedJointPoints.at(row); + QStringList values; + for (double position : point.positions) + values.append(QString::number(position, 'f', 6)); + m_jointPointTable->setItem(row, 0, new QTableWidgetItem(point.name)); + m_jointPointTable->setItem(row, 1, new QTableWidgetItem( + point.side == QStringLiteral("left") ? QStringLiteral("左臂") + : QStringLiteral("右臂"))); + m_jointPointTable->setItem(row, 2, new QTableWidgetItem(point.deviceId)); + m_jointPointTable->setItem(row, 3, new QTableWidgetItem( + QString::number(point.positions.size()))); + QTableWidgetItem *positionsItem = new QTableWidgetItem(values.join(QStringLiteral(", "))); + positionsItem->setToolTip(QStringLiteral("关节顺序:%1\n角度(rad):%2") + .arg(point.jointNames.join(QStringLiteral(", ")), + values.join(QStringLiteral(", ")))); + m_jointPointTable->setItem(row, 4, positionsItem); + } +} + +void MainWindow::refreshJointFlowTable() +{ + if (!m_jointFlowTable) + return; + m_jointFlowTable->setRowCount(m_jointFlowSteps.size()); + for (int row = 0; row < m_jointFlowSteps.size(); ++row) { + const JointFlowStep &step = m_jointFlowSteps.at(row); + m_jointFlowTable->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1))); + m_jointFlowTable->setItem(row, 1, new QTableWidgetItem(step.pointName)); + m_jointFlowTable->setItem(row, 2, new QTableWidgetItem( + QStringLiteral("%1 s").arg(step.waitSeconds, 0, 'f', 1))); + m_jointFlowTable->setItem(row, 3, new QTableWidgetItem( + step.loopGroup.isEmpty() ? QStringLiteral("—") : step.loopGroup)); + m_jointFlowTable->setItem(row, 4, new QTableWidgetItem( + step.loopGroup.isEmpty() ? QStringLiteral("1") + : QString::number(step.loopCount))); + } +} + +void MainWindow::recordCurrentJointPoint() +{ + const QString name = m_jointPointNameEdit + ? m_jointPointNameEdit->text().trimmed() : QString(); + if (name.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("记录关节点位"), + QStringLiteral("请输入动作名称。")); + return; + } + for (const RecordedJointPoint &point : m_recordedJointPoints) { + if (point.name.compare(name, Qt::CaseInsensitive) == 0) { + QMessageBox::warning(this, QStringLiteral("记录关节点位"), + QStringLiteral("动作名称“%1”已存在,请使用其他名称。") + .arg(name)); + return; + } + } + + const bool leftArm = m_armSideCombo + && m_armSideCombo->currentData().toString() == QStringLiteral("left"); + const QStringList jointNames = leftArm ? m_leftArmJointNames : m_rightArmJointNames; + if (jointNames.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("记录关节点位"), + QStringLiteral("当前 URDF 中没有该机械臂的可运动关节。")); + return; + } + + RecordedJointPoint point; + point.name = name; + point.side = leftArm ? QStringLiteral("left") : QStringLiteral("right"); + point.deviceId = m_armIdEdit->text().trimmed(); + point.jointNames = jointNames; + QStringList missing; + for (const QString &jointName : jointNames) { + if (!m_latestArmJointPositions.contains(jointName)) { + missing.append(jointName); + continue; + } + point.positions.append(m_latestArmJointPositions.value(jointName)); + } + if (!missing.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("记录关节点位"), + QStringLiteral("尚未收到以下关节的实时角度:\n%1\n\n请先启动遥测。") + .arg(missing.join(QStringLiteral(", ")))); + return; + } + if (point.deviceId.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("记录关节点位"), + QStringLiteral("当前 Device ID 为空。")); + return; + } + + m_recordedJointPoints.append(point); + refreshRecordedJointPoints(); + QSettings settings; + saveJointPrograms(settings); + m_jointPointNameEdit->clear(); + m_jointPointTable->selectRow(m_recordedJointPoints.size() - 1); + appendLog(QStringLiteral("OK"), + QStringLiteral("已记录动作“%1”,%2 个关节(rad)") + .arg(point.name).arg(point.positions.size())); +} + +void MainWindow::executeSelectedJointPoint() +{ + if (m_jointPointLoopActive || m_jointPointMovePending) + return; + const QModelIndexList selected = m_jointPointTable + ? m_jointPointTable->selectionModel()->selectedRows() : QModelIndexList(); + if (selected.isEmpty()) { + QMessageBox::information(this, QStringLiteral("执行关节点位"), + QStringLiteral("请先选择一个已记录动作。")); + return; + } + const int row = selected.first().row(); + if (row < 0 || row >= m_recordedJointPoints.size()) + return; + const RecordedJointPoint &point = m_recordedJointPoints.at(row); + QVariantList positions; + for (double position : point.positions) + positions.append(position); + m_jointPointMovePending = true; + m_client->requestMoveJ(point.deviceId, positions, + m_velocitySpin->value(), m_accelerationSpin->value()); + if (m_jointPointLoopStatus) + m_jointPointLoopStatus->setText(QStringLiteral("执行:%1").arg(point.name)); +} + +void MainWindow::startJointPointLoop() +{ + if (m_jointPointLoopActive || m_jointPointMovePending) + return; + if (m_jointFlowSteps.isEmpty()) { + QMessageBox::information(this, QStringLiteral("执行自定义流程"), + QStringLiteral("请先向自定义流程中添加步骤。")); + return; + } + m_jointPointLoopRows.clear(); + m_jointPointExecutionWaits.clear(); + const auto pointRow = [this](const QString &name) { + for (int row = 0; row < m_recordedJointPoints.size(); ++row) { + if (m_recordedJointPoints.at(row).name == name) + return row; + } + return -1; + }; + for (int i = 0; i < m_jointFlowSteps.size();) { + const JointFlowStep &step = m_jointFlowSteps.at(i); + if (step.loopGroup.isEmpty()) { + const int row = pointRow(step.pointName); + if (row >= 0) { + m_jointPointLoopRows.append(row); + m_jointPointExecutionWaits.append(step.waitSeconds); + } + ++i; + continue; + } + int end = i + 1; + while (end < m_jointFlowSteps.size() + && m_jointFlowSteps.at(end).loopGroup == step.loopGroup) + ++end; + for (int repeat = 0; repeat < step.loopCount; ++repeat) { + for (int index = i; index < end; ++index) { + const JointFlowStep &groupStep = m_jointFlowSteps.at(index); + const int row = pointRow(groupStep.pointName); + if (row >= 0) { + m_jointPointLoopRows.append(row); + m_jointPointExecutionWaits.append(groupStep.waitSeconds); + } + } + } + i = end; + } + if (m_jointPointLoopRows.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("执行自定义流程"), + QStringLiteral("流程引用的点位已不存在。")); + return; + } + m_jointPointLoopCursor = 0; + m_jointPointLoopTarget = m_jointPointLoopRows.size(); + m_jointPointLoopActive = true; + m_startJointPointLoopButton->setEnabled(false); + m_runJointPointButton->setEnabled(false); + m_deleteJointPointButton->setEnabled(false); + m_recordJointPointButton->setEnabled(false); + m_stopJointPointLoopButton->setEnabled(true); + m_jointPointTable->setEnabled(false); + advanceJointPointLoop(); +} + +void MainWindow::advanceJointPointLoop() +{ + if (!m_jointPointLoopActive || m_jointPointMovePending) + return; + if (m_jointPointLoopCursor >= m_jointPointLoopRows.size()) { + stopJointPointLoop(QStringLiteral("循环执行完成")); + return; + } + const int executionIndex = m_jointPointLoopCursor; + const int row = m_jointPointLoopRows.at(m_jointPointLoopCursor++); + if (row < 0 || row >= m_recordedJointPoints.size()) { + stopJointPointLoop(QStringLiteral("点位列表已发生变化")); + return; + } + const RecordedJointPoint &point = m_recordedJointPoints.at(row); + QVariantList positions; + for (double position : point.positions) + positions.append(position); + m_jointPointMovePending = true; + m_jointPointLoopStatus->setText(QStringLiteral("步骤 %1/%2 · %3") + .arg(executionIndex + 1).arg(m_jointPointLoopRows.size()).arg(point.name)); + m_client->requestMoveJ(point.deviceId, positions, + m_velocitySpin->value(), m_accelerationSpin->value()); +} + +void MainWindow::stopJointPointLoop(const QString &reason) +{ + const bool wasActive = m_jointPointLoopActive; + m_jointPointLoopActive = false; + m_jointPointMovePending = false; + m_jointPointLoopRows.clear(); + m_jointPointExecutionWaits.clear(); + if (m_startJointPointLoopButton) + m_startJointPointLoopButton->setEnabled(true); + if (m_runJointPointButton) + m_runJointPointButton->setEnabled(true); + if (m_deleteJointPointButton) + m_deleteJointPointButton->setEnabled(true); + if (m_recordJointPointButton) + m_recordJointPointButton->setEnabled(true); + if (m_stopJointPointLoopButton) + m_stopJointPointLoopButton->setEnabled(false); + if (m_jointPointTable) + m_jointPointTable->setEnabled(true); + if (m_jointPointLoopStatus) + m_jointPointLoopStatus->setText(reason.isEmpty() ? QStringLiteral("未运行") : reason); + if (wasActive && !reason.isEmpty()) + appendLog(reason == QStringLiteral("循环执行完成") ? QStringLiteral("OK") + : QStringLiteral("WARN"), + reason); +} + void MainWindow::sendMoveJPose() { if (m_moveJPoseSpins.size() != 6 || !m_moveJPoseBaseLinkCombo) @@ -1050,6 +1314,7 @@ void MainWindow::saveSnapshot() void MainWindow::loadSettings() { QSettings settings; + loadJointPrograms(settings); m_hostEdit->setText(settings.value(QStringLiteral("connection/host"), QStringLiteral("192.168.0.28")).toString()); m_hostEdit->setCursorPosition(0); m_portSpin->setValue(settings.value(QStringLiteral("connection/port"), 50052).toInt()); @@ -1063,14 +1328,16 @@ void MainWindow::loadSettings() m_armSideCombo->setCurrentIndex(sideIndex); } const QString defaultArmDeviceId = armSide == QStringLiteral("left") - ? QStringLiteral("eyou_left_arm") : QStringLiteral("eyou_right_arm"); + ? QStringLiteral("left_ethercat_arm") : QStringLiteral("right_ethercat_arm"); QString armDeviceId = settings.value(QStringLiteral("arm/device"), defaultArmDeviceId).toString().trimmed(); - if (armDeviceId == QStringLiteral("left_arm")) { - armDeviceId = QStringLiteral("eyou_left_arm"); + if (armDeviceId == QStringLiteral("left_arm") || + armDeviceId == QStringLiteral("eyou_left_arm")) { + armDeviceId = QStringLiteral("left_ethercat_arm"); } else if (armDeviceId == QStringLiteral("right_arm") || - armDeviceId == QStringLiteral("eyou_arm")) { - armDeviceId = QStringLiteral("eyou_right_arm"); + armDeviceId == QStringLiteral("eyou_arm") || + armDeviceId == QStringLiteral("eyou_right_arm")) { + armDeviceId = QStringLiteral("right_ethercat_arm"); } m_armIdEdit->setText(armDeviceId); m_cameraIdEdit->setText(settings.value(QStringLiteral("camera/device"), QStringLiteral("camera")).toString()); @@ -1130,6 +1397,7 @@ void MainWindow::loadSettings() void MainWindow::saveSettings() { QSettings settings; + saveJointPrograms(settings); settings.setValue(QStringLiteral("connection/host"), m_hostEdit->text().trimmed()); settings.setValue(QStringLiteral("connection/port"), m_portSpin->value()); settings.setValue(QStringLiteral("connection/demo"), m_demoCheck->isChecked()); @@ -1168,6 +1436,72 @@ void MainWindow::saveSettings() : certificatePath); } +void MainWindow::loadJointPrograms(QSettings &settings) +{ + m_recordedJointPoints.clear(); + const int pointCount = settings.beginReadArray(QStringLiteral("arm/jointPoints")); + for (int i = 0; i < pointCount; ++i) { + settings.setArrayIndex(i); + RecordedJointPoint point; + point.name = settings.value(QStringLiteral("name")).toString(); + point.side = settings.value(QStringLiteral("side")).toString(); + point.deviceId = settings.value(QStringLiteral("deviceId")).toString(); + point.jointNames = settings.value(QStringLiteral("jointNames")).toStringList(); + const QVariantList storedPositions = settings.value(QStringLiteral("positions")).toList(); + for (const QVariant &value : storedPositions) + point.positions.append(value.toDouble()); + if (!point.name.isEmpty() && point.jointNames.size() == point.positions.size()) + m_recordedJointPoints.append(point); + } + settings.endArray(); + + m_jointFlowSteps.clear(); + const int flowCount = settings.beginReadArray(QStringLiteral("arm/jointFlow")); + for (int i = 0; i < flowCount; ++i) { + settings.setArrayIndex(i); + JointFlowStep step; + step.pointName = settings.value(QStringLiteral("pointName")).toString(); + step.waitSeconds = settings.value(QStringLiteral("waitSeconds"), 1.0).toDouble(); + step.loopGroup = settings.value(QStringLiteral("loopGroup")).toString(); + step.loopCount = settings.value(QStringLiteral("loopCount"), 1).toInt(); + if (!step.pointName.isEmpty()) + m_jointFlowSteps.append(step); + } + settings.endArray(); + refreshRecordedJointPoints(); + refreshJointFlowTable(); +} + +void MainWindow::saveJointPrograms(QSettings &settings) const +{ + settings.remove(QStringLiteral("arm/jointPoints")); + settings.beginWriteArray(QStringLiteral("arm/jointPoints")); + for (int i = 0; i < m_recordedJointPoints.size(); ++i) { + settings.setArrayIndex(i); + const RecordedJointPoint &point = m_recordedJointPoints.at(i); + QVariantList positions; + for (double value : point.positions) + positions.append(value); + settings.setValue(QStringLiteral("name"), point.name); + settings.setValue(QStringLiteral("side"), point.side); + settings.setValue(QStringLiteral("deviceId"), point.deviceId); + settings.setValue(QStringLiteral("jointNames"), point.jointNames); + settings.setValue(QStringLiteral("positions"), positions); + } + settings.endArray(); + settings.remove(QStringLiteral("arm/jointFlow")); + settings.beginWriteArray(QStringLiteral("arm/jointFlow")); + for (int i = 0; i < m_jointFlowSteps.size(); ++i) { + settings.setArrayIndex(i); + const JointFlowStep &step = m_jointFlowSteps.at(i); + settings.setValue(QStringLiteral("pointName"), step.pointName); + settings.setValue(QStringLiteral("waitSeconds"), step.waitSeconds); + settings.setValue(QStringLiteral("loopGroup"), step.loopGroup); + settings.setValue(QStringLiteral("loopCount"), step.loopCount); + } + settings.endArray(); +} + void MainWindow::setControlsEnabled(bool enabled) { for (QPushButton *button : m_serviceButtons) { diff --git a/src/mainwindow.h b/src/mainwindow.h index 884a5ec..dd98930 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -9,6 +9,7 @@ #include #include #include +#include #include "videoframe.h" @@ -25,6 +26,7 @@ class QLineEdit; class QProgressBar; class QPushButton; class QResizeEvent; +class QSettings; class QSpinBox; class QStackedWidget; class QTableWidget; @@ -73,6 +75,13 @@ private slots: void appendQuicLog(const QString &level, const QString &message); void sendMoveJ(); void sendMoveJPose(); + void recordCurrentJointPoint(); + void executeSelectedJointPoint(); + void startJointPointLoop(); + void stopJointPointLoop(const QString &reason = QString()); + void advanceJointPointLoop(); + void refreshRecordedJointPoints(); + void refreshJointFlowTable(); void saveSnapshot(); private: @@ -89,6 +98,8 @@ private: QWidget *createDiagnosticsPage(); void loadSettings(); void saveSettings(); + void loadJointPrograms(QSettings &settings); + void saveJointPrograms(QSettings &settings) const; void setControlsEnabled(bool enabled); void updateWindowChrome(); void ensureArmModelLoaded(); @@ -155,6 +166,10 @@ private: QTableWidget *m_motionTable = nullptr; QTableWidget *m_leftMotionTable = nullptr; QList m_targetSpins; + QList m_leftTargetSpins; + QList m_rightTargetSpins; + QStringList m_leftArmJointNames; + QStringList m_rightArmJointNames; QStringList m_activeArmJointNames; QTabWidget *m_motionCommandTabs = nullptr; QList m_moveJPoseSpins; @@ -180,6 +195,43 @@ private: QString m_teachSelectedJoint; QString m_pendingUrdfPath; bool m_armModelLoadScheduled = false; + struct RecordedJointPoint { + QString name; + QString side; + QString deviceId; + QStringList jointNames; + QVector positions; + }; + struct JointFlowStep { + QString pointName; + double waitSeconds = 1.0; + QString loopGroup; + int loopCount = 1; + }; + QList m_recordedJointPoints; + QList m_jointFlowSteps; + QHash m_latestArmJointPositions; + QLineEdit *m_jointPointNameEdit = nullptr; + QTableWidget *m_jointPointTable = nullptr; + QLabel *m_jointPointDetailLabel = nullptr; + QSpinBox *m_jointPointLoopCount = nullptr; + QDoubleSpinBox *m_jointPointInterval = nullptr; + QLineEdit *m_jointFlowGroupEdit = nullptr; + QSpinBox *m_jointFlowGroupCount = nullptr; + QTableWidget *m_jointFlowTable = nullptr; + QPushButton *m_recordJointPointButton = nullptr; + QPushButton *m_runJointPointButton = nullptr; + QPushButton *m_deleteJointPointButton = nullptr; + QPushButton *m_startJointPointLoopButton = nullptr; + QPushButton *m_stopJointPointLoopButton = nullptr; + QLabel *m_jointPointLoopStatus = nullptr; + QVector m_jointPointLoopRows; + QVector m_jointPointExecutionWaits; + int m_jointPointLoopCursor = 0; + int m_jointPointLoopsCompleted = 0; + int m_jointPointLoopTarget = 0; + bool m_jointPointLoopActive = false; + bool m_jointPointMovePending = false; QLineEdit *m_cameraIdEdit = nullptr; VideoRenderWidget *m_videoRender = nullptr; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 2279488..07f17c6 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -143,11 +144,16 @@ QStringList armJointNames(bool leftArm) bool isArmJointForSide(const QString &jointName, bool leftArm) { - const QString upper = jointName.toUpper(); - return leftArm ? (upper.startsWith(QStringLiteral("L_")) - || upper.contains(QStringLiteral("LEFT"))) - : (upper.startsWith(QStringLiteral("R_")) - || upper.contains(QStringLiteral("RIGHT"))); + const QString lower = jointName.toLower(); + const QString sideWord = leftArm ? QStringLiteral("left") : QStringLiteral("right"); + const QString sidePrefix = leftArm ? QStringLiteral("l_") : QStringLiteral("r_"); + return lower.contains(sideWord + QStringLiteral("_arm")) + || lower.contains(sideWord + QStringLiteral("arm")) + || (lower.startsWith(sidePrefix) + && (lower.contains(QStringLiteral("shoulder")) + || lower.contains(QStringLiteral("elbow")) + || lower.contains(QStringLiteral("wrist")) + || lower.contains(QStringLiteral("arm")))); } QWidget *withRpcExplorer(QWidget *commonPage, RobotClient *client, @@ -247,19 +253,15 @@ QWidget *MainWindow::createArmPage() ui.commandPanel->setParent(ui.urdfTab); ui.urdfTabLayout->insertWidget(0, ui.commandPanel); - QSplitter *modelMotionWorkspace = new QSplitter(Qt::Vertical, ui.urdfTab); - modelMotionWorkspace->setObjectName(QStringLiteral("armModelMotionSplitter")); - modelMotionWorkspace->setChildrenCollapsible(false); - modelMotionWorkspace->setHandleWidth(8); + // Qt3D preview is disabled in release builds. Keep the viewer alive and + // hidden so it can still parse the URDF and provide the joint list, while + // giving the complete workspace height to the command/point-flow tables. ui.urdfTabLayout->removeWidget(ui.urdfViewer); - modelMotionWorkspace->addWidget(ui.urdfViewer); - modelMotionWorkspace->addWidget(ui.targetsPanel); - modelMotionWorkspace->setStretchFactor(0, 5); - modelMotionWorkspace->setStretchFactor(1, 4); - modelMotionWorkspace->setSizes({500, 350}); - ui.targetsPanel->setMinimumHeight(360); - ui.targetsPanel->setMaximumHeight(440); - ui.urdfTabLayout->insertWidget(1, modelMotionWorkspace, 1); + ui.urdfViewer->hide(); + ui.targetsPanel->setMinimumHeight(0); + ui.targetsPanel->setMaximumHeight(QWIDGETSIZE_MAX); + ui.targetsPanel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); + ui.urdfTabLayout->insertWidget(1, ui.targetsPanel, 1); ui.urdfTabLayout->setStretch(0, 0); ui.urdfTabLayout->setStretch(1, 1); @@ -309,32 +311,251 @@ QWidget *MainWindow::createArmPage() m_motionCommandTabs->setObjectName(QStringLiteral("armMotionCommandTabs")); m_motionCommandTabs->setDocumentMode(true); QWidget *moveJPage = new QWidget(m_motionCommandTabs); - QVBoxLayout *moveJLayout = new QVBoxLayout(moveJPage); + QGridLayout *moveJLayout = new QGridLayout(moveJPage); moveJLayout->setContentsMargins(0, 0, 0, 0); - QSplitter *armTargetTables = new QSplitter(Qt::Horizontal, moveJPage); + moveJLayout->setHorizontalSpacing(12); + moveJLayout->setVerticalSpacing(10); + moveJLayout->setColumnStretch(0, 4); + moveJLayout->setColumnStretch(1, 6); + moveJLayout->setRowStretch(0, 1); + moveJLayout->setRowStretch(1, 1); + QSplitter *armTargetTables = new QSplitter(Qt::Vertical, moveJPage); armTargetTables->setObjectName(QStringLiteral("armTargetTables")); armTargetTables->setChildrenCollapsible(false); QWidget *leftTargets = new QWidget(armTargetTables); + leftTargets->setObjectName(QStringLiteral("armTargetGroup")); QVBoxLayout *leftTargetsLayout = new QVBoxLayout(leftTargets); leftTargetsLayout->setContentsMargins(0, 4, 6, 0); - QLabel *leftTargetsTitle = new QLabel(QStringLiteral("左臂 · eyou_left_arm"), leftTargets); + QLabel *leftTargetsTitle = new QLabel(QStringLiteral("左臂 · left_ethercat_arm"), leftTargets); leftTargetsTitle->setObjectName(QStringLiteral("eyebrow")); m_leftMotionTable = new QTableWidget(7, 4, leftTargets); m_leftMotionTable->setObjectName(QStringLiteral("leftMotionTable")); leftTargetsLayout->addWidget(leftTargetsTitle); leftTargetsLayout->addWidget(m_leftMotionTable); QWidget *rightTargets = new QWidget(armTargetTables); + rightTargets->setObjectName(QStringLiteral("armTargetGroup")); QVBoxLayout *rightTargetsLayout = new QVBoxLayout(rightTargets); rightTargetsLayout->setContentsMargins(6, 4, 0, 0); - QLabel *rightTargetsTitle = new QLabel(QStringLiteral("右臂 · eyou_right_arm"), rightTargets); + QLabel *rightTargetsTitle = new QLabel(QStringLiteral("右臂 · right_ethercat_arm"), rightTargets); rightTargetsTitle->setObjectName(QStringLiteral("eyebrow")); m_motionTable->setParent(rightTargets); rightTargetsLayout->addWidget(rightTargetsTitle); rightTargetsLayout->addWidget(m_motionTable); armTargetTables->addWidget(leftTargets); armTargetTables->addWidget(rightTargets); - armTargetTables->setSizes({500, 500}); - moveJLayout->addWidget(armTargetTables); + armTargetTables->setSizes({340, 340}); + moveJLayout->addWidget(armTargetTables, 0, 0, 2, 1); + + QFrame *pointPanel = new QFrame(moveJPage); + pointPanel->setObjectName(QStringLiteral("panelCard")); + QVBoxLayout *pointLayout = new QVBoxLayout(pointPanel); + pointLayout->setContentsMargins(12, 10, 12, 10); + pointLayout->setSpacing(8); + QHBoxLayout *pointHeader = new QHBoxLayout; + QLabel *pointTitle = new QLabel(QStringLiteral("关节点位记录与循环"), pointPanel); + pointTitle->setObjectName(QStringLiteral("panelTitle")); + m_jointPointNameEdit = new QLineEdit(pointPanel); + m_jointPointNameEdit->setPlaceholderText(QStringLiteral("动作名称,例如:抓取准备")); + m_jointPointNameEdit->setMinimumWidth(220); + m_recordJointPointButton = new QPushButton(QStringLiteral("记录当前角度"), pointPanel); + pointHeader->addWidget(pointTitle); + pointHeader->addStretch(1); + pointHeader->addWidget(m_jointPointNameEdit); + pointHeader->addWidget(m_recordJointPointButton); + pointLayout->addLayout(pointHeader); + + m_jointPointTable = new QTableWidget(0, 5, pointPanel); + m_jointPointTable->setHorizontalHeaderLabels({ + QStringLiteral("动作名称"), QStringLiteral("机械臂"), QStringLiteral("Device ID"), + QStringLiteral("关节数"), QStringLiteral("关节角度(rad)")}); + m_jointPointTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_jointPointTable->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_jointPointTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_jointPointTable->verticalHeader()->setVisible(false); + m_jointPointTable->verticalHeader()->setDefaultSectionSize(28); + m_jointPointTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + m_jointPointTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + m_jointPointTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); + m_jointPointTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); + m_jointPointTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch); + m_jointPointTable->setMinimumHeight(132); + pointLayout->addWidget(m_jointPointTable); + m_jointPointDetailLabel = new QLabel(QStringLiteral("选择点位后查看详细关节角度"), pointPanel); + m_jointPointDetailLabel->setObjectName(QStringLiteral("mutedLabel")); + m_jointPointDetailLabel->setWordWrap(true); + m_jointPointDetailLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); + pointLayout->addWidget(m_jointPointDetailLabel); + + QHBoxLayout *pointActions = new QHBoxLayout; + m_runJointPointButton = new QPushButton(QStringLiteral("执行选中点位"), pointPanel); + m_deleteJointPointButton = new QPushButton(QStringLiteral("删除选中"), pointPanel); + QLabel *loopCountLabel = new QLabel(QStringLiteral("循环次数"), pointPanel); + m_jointPointLoopCount = new QSpinBox(pointPanel); + m_jointPointLoopCount->setRange(1, 10000); + m_jointPointLoopCount->setValue(1); + m_startJointPointLoopButton = new QPushButton(QStringLiteral("执行自定义流程"), pointPanel); + m_stopJointPointLoopButton = new QPushButton(QStringLiteral("停止循环"), pointPanel); + m_stopJointPointLoopButton->setEnabled(false); + m_jointPointLoopStatus = new QLabel(QStringLiteral("未运行"), pointPanel); + m_jointPointLoopStatus->setObjectName(QStringLiteral("mutedLabel")); + pointActions->addWidget(m_runJointPointButton); + pointActions->addWidget(m_deleteJointPointButton); + pointActions->addStretch(1); + pointActions->addWidget(m_jointPointLoopStatus); + pointLayout->addLayout(pointActions); + moveJLayout->addWidget(pointPanel, 0, 1); + + connect(m_recordJointPointButton, &QPushButton::clicked, + this, &MainWindow::recordCurrentJointPoint); + connect(m_runJointPointButton, &QPushButton::clicked, + this, &MainWindow::executeSelectedJointPoint); + connect(m_startJointPointLoopButton, &QPushButton::clicked, + this, &MainWindow::startJointPointLoop); + connect(m_stopJointPointLoopButton, &QPushButton::clicked, this, [this]() { + stopJointPointLoop(QStringLiteral("用户停止")); + m_client->requestArmStop(m_armIdEdit->text().trimmed()); + }); + connect(m_deleteJointPointButton, &QPushButton::clicked, this, [this]() { + if (m_jointPointLoopActive) + return; + QList rows; + for (const QModelIndex &index : m_jointPointTable->selectionModel()->selectedRows()) + rows.append(index.row()); + std::sort(rows.begin(), rows.end(), std::greater()); + QStringList removedNames; + for (int row : rows) { + if (row >= 0 && row < m_recordedJointPoints.size()) { + removedNames.append(m_recordedJointPoints.at(row).name); + m_recordedJointPoints.removeAt(row); + } + } + for (int i = m_jointFlowSteps.size() - 1; i >= 0; --i) { + if (removedNames.contains(m_jointFlowSteps.at(i).pointName)) + m_jointFlowSteps.removeAt(i); + } + refreshRecordedJointPoints(); + refreshJointFlowTable(); + QSettings settings; + saveJointPrograms(settings); + }); + connect(m_jointPointTable, &QTableWidget::cellClicked, this, + [this](int row, int) { + if (row < 0 || row >= m_recordedJointPoints.size()) + return; + const RecordedJointPoint &point = m_recordedJointPoints.at(row); + QStringList details; + for (int i = 0; i < point.jointNames.size() && i < point.positions.size(); ++i) { + details.append(QStringLiteral("%1 = %2 rad") + .arg(point.jointNames.at(i)) + .arg(point.positions.at(i), 0, 'f', 6)); + } + m_jointPointDetailLabel->setText( + QStringLiteral("%1 · %2 · %3\n%4") + .arg(point.name, + point.side == QStringLiteral("left") ? QStringLiteral("左臂") + : QStringLiteral("右臂"), + point.deviceId, details.join(QStringLiteral(" ")))); + }); + + QFrame *flowPanel = new QFrame(moveJPage); + flowPanel->setObjectName(QStringLiteral("panelCard")); + QVBoxLayout *flowLayout = new QVBoxLayout(flowPanel); + flowLayout->setContentsMargins(12, 10, 12, 10); + flowLayout->setSpacing(8); + QHBoxLayout *flowBuilder = new QHBoxLayout; + QLabel *flowTitle = new QLabel(QStringLiteral("自定义执行流程"), flowPanel); + flowTitle->setObjectName(QStringLiteral("panelTitle")); + QLabel *intervalLabel = new QLabel(QStringLiteral("完成后等待"), flowPanel); + m_jointPointInterval = new QDoubleSpinBox(flowPanel); + m_jointPointInterval->setRange(0.0, 3600.0); + m_jointPointInterval->setDecimals(1); + m_jointPointInterval->setValue(1.0); + m_jointPointInterval->setSuffix(QStringLiteral(" s")); + m_jointFlowGroupEdit = new QLineEdit(flowPanel); + m_jointFlowGroupEdit->setPlaceholderText(QStringLiteral("循环组名(留空=执行一次)")); + m_jointFlowGroupEdit->setMaximumWidth(190); + m_jointFlowGroupCount = new QSpinBox(flowPanel); + m_jointFlowGroupCount->setRange(1, 10000); + m_jointFlowGroupCount->setValue(1); + QPushButton *addFlowStepButton = new QPushButton(QStringLiteral("添加选中点位到流程"), flowPanel); + flowBuilder->addWidget(flowTitle); + flowBuilder->addStretch(1); + flowBuilder->addWidget(intervalLabel); + flowBuilder->addWidget(m_jointPointInterval); + flowBuilder->addWidget(m_jointFlowGroupEdit); + flowBuilder->addWidget(new QLabel(QStringLiteral("组循环次数"), flowPanel)); + flowBuilder->addWidget(m_jointFlowGroupCount); + flowBuilder->addWidget(addFlowStepButton); + flowLayout->addLayout(flowBuilder); + m_jointFlowTable = new QTableWidget(0, 5, flowPanel); + m_jointFlowTable->setHorizontalHeaderLabels({QStringLiteral("顺序"), QStringLiteral("动作点位"), + QStringLiteral("完成后等待"), QStringLiteral("循环组"), QStringLiteral("组循环次数")}); + m_jointFlowTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_jointFlowTable->setSelectionMode(QAbstractItemView::SingleSelection); + m_jointFlowTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_jointFlowTable->verticalHeader()->setVisible(false); + m_jointFlowTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); + m_jointFlowTable->setMinimumHeight(120); + flowLayout->addWidget(m_jointFlowTable); + QHBoxLayout *flowActions = new QHBoxLayout; + QPushButton *flowUpButton = new QPushButton(QStringLiteral("上移"), flowPanel); + QPushButton *flowDownButton = new QPushButton(QStringLiteral("下移"), flowPanel); + QPushButton *flowDeleteButton = new QPushButton(QStringLiteral("删除步骤"), flowPanel); + flowActions->addWidget(flowUpButton); + flowActions->addWidget(flowDownButton); + flowActions->addWidget(flowDeleteButton); + flowActions->addStretch(1); + flowActions->addWidget(loopCountLabel); + loopCountLabel->setVisible(false); + m_jointPointLoopCount->setVisible(false); + flowActions->addWidget(m_startJointPointLoopButton); + flowActions->addWidget(m_stopJointPointLoopButton); + flowLayout->addLayout(flowActions); + moveJLayout->addWidget(flowPanel, 1, 1); + + connect(addFlowStepButton, &QPushButton::clicked, this, [this]() { + const QModelIndexList rows = m_jointPointTable->selectionModel()->selectedRows(); + if (rows.isEmpty()) + return; + QList sortedRows; + for (const QModelIndex &index : rows) + sortedRows.append(index.row()); + std::sort(sortedRows.begin(), sortedRows.end()); + for (int row : sortedRows) { + if (row < 0 || row >= m_recordedJointPoints.size()) + continue; + JointFlowStep step; + step.pointName = m_recordedJointPoints.at(row).name; + step.waitSeconds = m_jointPointInterval->value(); + step.loopGroup = m_jointFlowGroupEdit->text().trimmed(); + step.loopCount = step.loopGroup.isEmpty() ? 1 : m_jointFlowGroupCount->value(); + m_jointFlowSteps.append(step); + } + refreshJointFlowTable(); + QSettings settings; + saveJointPrograms(settings); + }); + connect(flowDeleteButton, &QPushButton::clicked, this, [this]() { + const int row = m_jointFlowTable->currentRow(); + if (row >= 0 && row < m_jointFlowSteps.size()) + m_jointFlowSteps.removeAt(row); + refreshJointFlowTable(); + QSettings settings; + saveJointPrograms(settings); + }); + const auto moveFlowStep = [this](int delta) { + const int row = m_jointFlowTable->currentRow(); + const int target = row + delta; + if (row < 0 || target < 0 || target >= m_jointFlowSteps.size()) + return; + m_jointFlowSteps.swap(row, target); + refreshJointFlowTable(); + m_jointFlowTable->selectRow(target); + QSettings settings; + saveJointPrograms(settings); + }; + connect(flowUpButton, &QPushButton::clicked, this, [moveFlowStep]() { moveFlowStep(-1); }); + connect(flowDownButton, &QPushButton::clicked, this, [moveFlowStep]() { moveFlowStep(1); }); m_motionCommandTabs->addTab(moveJPage, QStringLiteral("MoveJ 关节角")); QWidget *moveLPage = new QWidget(m_motionCommandTabs); @@ -480,9 +701,10 @@ QWidget *MainWindow::createArmPage() }); connect(ui.zeroButton, &QPushButton::clicked, this, [this]() { const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left"); - const int offset = leftArm ? 0 : 7; - for (int i = 0; i < 7 && offset + i < m_targetSpins.size(); ++i) - m_targetSpins.at(offset + i)->setValue(0.0); + const QList &spins = leftArm + ? m_leftTargetSpins : m_rightTargetSpins; + for (QDoubleSpinBox *spin : spins) + spin->setValue(0.0); }); connect(m_sendMoveButton, &QPushButton::clicked, this, [this]() { if (m_motionCommandTabs && m_motionCommandTabs->currentIndex() == 1) @@ -528,18 +750,28 @@ QWidget *MainWindow::createArmPage() this, &MainWindow::appendLog); const auto configureMotionTable = [](QTableWidget *table) { - table->setHorizontalHeaderLabels({QStringLiteral("关节"), QStringLiteral("当前"), - QStringLiteral("目标角度"), QStringLiteral("目标弧度")}); + table->setColumnCount(5); + table->setHorizontalHeaderLabels({QStringLiteral("关节"), QStringLiteral("当前角度"), + QStringLiteral("当前弧度"), QStringLiteral("目标角度"), + QStringLiteral("目标弧度")}); table->setAlternatingRowColors(true); table->setSelectionBehavior(QAbstractItemView::SelectRows); table->setSelectionMode(QAbstractItemView::SingleSelection); table->setShowGrid(false); table->verticalHeader()->setVisible(false); - table->verticalHeader()->setDefaultSectionSize(32); - table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); - table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); - table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); - table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); + table->verticalHeader()->setDefaultSectionSize(29); + table->horizontalHeader()->setFixedHeight(32); + table->horizontalHeader()->setHighlightSections(false); + for (int column = 0; column < 5; ++column) + table->horizontalHeader()->setSectionResizeMode(column, QHeaderView::Fixed); + table->setColumnWidth(0, 112); + table->setColumnWidth(1, 76); + table->setColumnWidth(2, 92); + table->setColumnWidth(3, 118); + table->setColumnWidth(4, 96); + table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + table->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + table->setMinimumHeight(32 + 7 * 29 + 2); }; configureMotionTable(m_leftMotionTable); configureMotionTable(m_motionTable); @@ -554,14 +786,21 @@ QWidget *MainWindow::createArmPage() m_jointTable->horizontalHeader()->setStretchLastSection(true); m_targetSpins.clear(); - const auto populateMotionTable = [this](QTableWidget *table, bool leftArm) { - const QStringList jointNames = armJointNames(leftArm); + m_leftArmJointNames = armJointNames(true); + m_rightArmJointNames = armJointNames(false); + const auto populateMotionTable = [this](QTableWidget *table, bool leftArm, + const QStringList &jointNames) { + QList &sideSpins = leftArm + ? m_leftTargetSpins : m_rightTargetSpins; + sideSpins.clear(); table->clearContents(); table->setRowCount(jointNames.size()); + table->setMinimumHeight(32 + qMin(jointNames.size(), 10) * 29 + 2); for (int row = 0; row < jointNames.size(); ++row) { const QString jointName = jointNames.at(row); table->setItem(row, 0, new QTableWidgetItem(jointName)); table->setItem(row, 1, new QTableWidgetItem(QStringLiteral("--"))); + table->setItem(row, 2, new QTableWidgetItem(QStringLiteral("--"))); QDoubleSpinBox *target = new QDoubleSpinBox(table); target->setRange(-180.0, 180.0); target->setDecimals(3); @@ -570,14 +809,15 @@ QWidget *MainWindow::createArmPage() target->setFrame(false); target->setEnabled(m_connected); m_targetSpins.append(target); - table->setCellWidget(row, 2, target); + sideSpins.append(target); + table->setCellWidget(row, 3, target); QTableWidgetItem *radians = new QTableWidgetItem(QStringLiteral("0.000000")); radians->setFlags(radians->flags() & ~Qt::ItemIsEditable); - table->setItem(row, 3, radians); + table->setItem(row, 4, radians); connect(target, QOverload::of(&QDoubleSpinBox::valueChanged), this, [this, table, row, jointName](double degrees) { - if (row < table->rowCount() && table->item(row, 3)) - table->item(row, 3)->setText( + if (row < table->rowCount() && table->item(row, 4)) + table->item(row, 4)->setText( QString::number(qDegreesToRadians(degrees), 'f', 6)); if (m_teachModeButton->isChecked()) m_urdfViewer->setTeachingJointPosition( @@ -586,8 +826,8 @@ QWidget *MainWindow::createArmPage() } }; - populateMotionTable(m_leftMotionTable, true); - populateMotionTable(m_motionTable, false); + populateMotionTable(m_leftMotionTable, true, m_leftArmJointNames); + populateMotionTable(m_motionTable, false, m_rightArmJointNames); const QStringList allJointNames = armJointNames(true) + armJointNames(false); m_jointTable->clearContents(); @@ -600,7 +840,7 @@ QWidget *MainWindow::createArmPage() const auto refreshActiveArmControls = [this]() { const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left"); - m_activeArmJointNames = armJointNames(leftArm); + m_activeArmJointNames = leftArm ? m_leftArmJointNames : m_rightArmJointNames; QStringList zeroJointNames; const QStringList urdfNames = m_urdfViewer->jointNames(); for (const QString &name : urdfNames) { @@ -628,8 +868,8 @@ QWidget *MainWindow::createArmPage() if (telemetryRunning) m_client->setArmTelemetry(oldDeviceId, false); const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left"); - m_armIdEdit->setText(leftArm ? QStringLiteral("eyou_left_arm") - : QStringLiteral("eyou_right_arm")); + m_armIdEdit->setText(leftArm ? QStringLiteral("left_ethercat_arm") + : QStringLiteral("right_ethercat_arm")); m_latestArmPose.clear(); m_poseValue->setText(QStringLiteral("X --\nY --\nZ --\n\nRX --\nRY --\nRZ --")); poseSubtitle->setText(leftArm ? QStringLiteral("PELVIS_S → L_FINGER_TIP") @@ -641,9 +881,40 @@ QWidget *MainWindow::createArmPage() m_client->setArmTelemetry(m_armIdEdit->text().trimmed(), true); }); connect(m_urdfViewer, &UrdfViewerWidget::modelLoaded, this, - [this, refreshActiveArmControls](const QString &, int, int) { + [this, refreshActiveArmControls, populateMotionTable](const QString &, int, int) { + const QStringList urdfNames = m_urdfViewer->jointNames(); + QStringList leftNames; + QStringList rightNames; + for (const QString &name : urdfNames) { + if (isArmJointForSide(name, true)) + leftNames.append(name); + else if (isArmJointForSide(name, false)) + rightNames.append(name); + } + // A single-arm URDF often uses neutral names such as joint1..joint6. + // In that case bind all movable joints to the currently selected arm. + if (leftNames.isEmpty() && rightNames.isEmpty() && !urdfNames.isEmpty()) { + if (m_armSideCombo->currentData().toString() == QStringLiteral("left")) + leftNames = urdfNames; + else + rightNames = urdfNames; + } + m_leftArmJointNames = leftNames; + m_rightArmJointNames = rightNames; + m_targetSpins.clear(); + populateMotionTable(m_leftMotionTable, true, m_leftArmJointNames); + populateMotionTable(m_motionTable, false, m_rightArmJointNames); + + m_jointTable->clearContents(); + m_jointTable->setRowCount(urdfNames.size()); + for (int row = 0; row < urdfNames.size(); ++row) { + m_jointTable->setItem(row, 0, new QTableWidgetItem(urdfNames.at(row))); + for (int column = 1; column < 4; ++column) + m_jointTable->setItem(row, column, + new QTableWidgetItem(QStringLiteral("--"))); + } refreshActiveArmControls(); - m_teachModeButton->setEnabled(!m_urdfViewer->jointNames().isEmpty()); + m_teachModeButton->setEnabled(!urdfNames.isEmpty()); }); connect(m_teachModeButton, &QPushButton::toggled, this, [this](bool enabled) { m_urdfViewer->setTeachingEnabled(enabled); @@ -683,15 +954,16 @@ QWidget *MainWindow::createArmPage() for (int side = 0; side < 2; ++side) { const bool leftArm = side == 0; QTableWidget *table = leftArm ? m_leftMotionTable : m_motionTable; - const QStringList names = armJointNames(leftArm); - const int offset = leftArm ? 0 : 7; - for (int row = 0; row < names.size() && offset + row < m_targetSpins.size(); ++row) { + const QStringList &names = leftArm ? m_leftArmJointNames : m_rightArmJointNames; + const QList &spins = leftArm + ? m_leftTargetSpins : m_rightTargetSpins; + for (int row = 0; row < names.size() && row < spins.size(); ++row) { if (!positions.contains(names.at(row))) continue; const double radians = positions.value(names.at(row)); - const QSignalBlocker blocker(m_targetSpins.at(offset + row)); - m_targetSpins.at(offset + row)->setValue(qRadiansToDegrees(radians)); - table->item(row, 3)->setText(QString::number(radians, 'f', 6)); + const QSignalBlocker blocker(spins.at(row)); + spins.at(row)->setValue(qRadiansToDegrees(radians)); + table->item(row, 4)->setText(QString::number(radians, 'f', 6)); } } }); @@ -705,7 +977,7 @@ QWidget *MainWindow::createArmPage() leftArm ? QStringLiteral("left") : QStringLiteral("right")); if (sideIndex >= 0 && sideIndex != m_armSideCombo->currentIndex()) m_armSideCombo->setCurrentIndex(sideIndex); - const QStringList names = armJointNames(leftArm); + const QStringList &names = leftArm ? m_leftArmJointNames : m_rightArmJointNames; if (m_teachModeButton->isChecked() && row >= 0 && row < names.size()) m_urdfViewer->selectTeachingJoint(names.at(row)); }); diff --git a/src/robotclient.cpp b/src/robotclient.cpp index a27ae31..ac86655 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -2648,7 +2648,6 @@ private: void pollGrpc() { - ++m_tick; if (m_armPollingEnabled && !m_armDeviceId.isEmpty()) { cmvr::api::JointRequest request; fillHeader(request.mutable_header(), m_armDeviceId); @@ -2675,45 +2674,6 @@ private: emit logMessage(QStringLiteral("WARN"), QStringLiteral("ArmService 连续 10 次遥测请求失败")); } - if (m_tick % 5 == 0) { - cmvr::api::GetPose::Request poseRequest; - fillHeader(poseRequest.mutable_header(), m_armDeviceId); - poseRequest.set_base_link("PELVIS_S"); - poseRequest.set_ee_link( - m_armDeviceId.contains(QStringLiteral("left"), Qt::CaseInsensitive) - ? "L_FINGER_TIP" : "R_FINGER_TIP"); - cmvr::api::GetPose::Response poseResponse; - grpc::ClientContext poseContext; - setDeadline(poseContext, 400); - const grpc::Status poseStatus = m_arm->getPose(&poseContext, poseRequest, &poseResponse); - if (poseStatus.ok() && poseResponse.header().success()) { - const auto &source = poseResponse.pose(); - QVariantMap pose; - pose.insert(QStringLiteral("x"), source.x()); - pose.insert(QStringLiteral("y"), source.y()); - pose.insert(QStringLiteral("z"), source.z()); - pose.insert(QStringLiteral("rx"), source.rx()); - pose.insert(QStringLiteral("ry"), source.ry()); - pose.insert(QStringLiteral("rz"), source.rz()); - emit telemetryReceived(QVariantList(), pose); - } - } - } - - 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, - statusResponse.device_list_size()); } } diff --git a/src/urdfviewerwidget.cpp b/src/urdfviewerwidget.cpp index c1ec512..346262d 100644 --- a/src/urdfviewerwidget.cpp +++ b/src/urdfviewerwidget.cpp @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -406,7 +407,29 @@ void UrdfViewerWidget::setLoading(bool loading, const QString &message) UrdfViewerWidget::~UrdfViewerWidget() { - // Qt3DWindow's aspect engine owns and synchronously tears down the scene. + if (m_demoTimer) + m_demoTimer->stop(); + + // Qt 5.12/MinGW has a reproducible access violation in Qt53DRender.dll + // when an embedded Qt3DWindow is destroyed while its render aspect is + // winding down. Detach this process-lifetime viewer so normal QWidget + // destruction cannot enter the faulty Qt3D teardown path; the OS reclaims + // it immediately when the process exits. + if (m_viewContainer) + m_viewContainer->removeEventFilter(this); + if (m_view) + m_view->removeEventFilter(this); + if (m_viewContainer) { + m_layout->removeWidget(m_viewContainer); + m_viewContainer->hide(); + m_viewContainer->setParent(nullptr); + } + m_viewContainer = nullptr; + m_view = nullptr; + m_camera = nullptr; + m_teachingRayCaster = nullptr; + m_modelRoot = nullptr; + m_rootEntity = nullptr; } void UrdfViewerWidget::showEvent(QShowEvent *event) @@ -624,8 +647,7 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath) return false; } - setLoading(true, QStringLiteral("正在初始化 Qt3D 场景…")); - ensureSceneInitialized(); + setLoading(true, QStringLiteral("正在解析 URDF 关节数据…")); m_statusLabel->setText(QStringLiteral("正在解析 %1…").arg(fileInfo.fileName())); QFile file(fileInfo.absoluteFilePath()); @@ -647,6 +669,60 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath) return false; } + { + // Qt 5.12.4/MinGW's Qt3D renderer crashes in its backend entity + // synchronization code while a URDF component tree is being published. + // Parse the complete URDF for control tables without creating a 3D scene. + clearModel(); + m_currentFile = fileInfo.absoluteFilePath(); + m_urdfDirectory = fileInfo.absolutePath(); + m_pathEdit->setText(fileInfo.fileName()); + m_pathEdit->setToolTip(QDir::toNativeSeparators(m_currentFile)); + m_reloadButton->setEnabled(true); + + std::function collectJoints; + collectJoints = [this, &collectJoints](const urdf::LinkConstSharedPtr &link) { + if (!link) + return; + for (const urdf::JointSharedPtr &joint : link->child_joints) { + if (!joint) + continue; + if (joint->type == urdf::Joint::REVOLUTE + || joint->type == urdf::Joint::CONTINUOUS + || joint->type == urdf::Joint::PRISMATIC) { + const QString jointName = QString::fromStdString(joint->name); + m_jointOrder.append(jointName); + m_jointPositions.insert(jointName, + m_latestTelemetryPositions.value(jointName, 0.0)); + } + urdf::LinkConstSharedPtr childLink; + for (const urdf::LinkSharedPtr &candidate : link->child_links) { + if (candidate && candidate->name == joint->child_link_name) { + childLink = candidate; + break; + } + } + collectJoints(childLink); + } + }; + collectJoints(model->getRoot()); + + const int linkCount = static_cast(model->links_.size()); + const int jointCount = static_cast(model->joints_.size()); + m_modelSummary = QStringLiteral("%1 个 Link · %2 个 Joint · 仅关节数据") + .arg(linkCount).arg(jointCount); + m_statusLabel->setText(m_modelSummary); + m_loadingTitle->setText(QStringLiteral("3D 模型预览暂时关闭")); + m_loadingDetail->setText(QStringLiteral("URDF 已解析,关节表和控制功能可正常使用")); + m_loadingProgress->setVisible(false); + m_viewportPlaceholder->show(); + emit logMessage(QStringLiteral("OK"), + QStringLiteral("URDF 已加载(关节数据模式):%1(%2 Link,%3 Joint)") + .arg(fileInfo.fileName()).arg(linkCount).arg(jointCount)); + emit modelLoaded(m_currentFile, linkCount, jointCount); + return true; + } + clearModel(); m_currentFile = fileInfo.absoluteFilePath(); m_urdfDirectory = fileInfo.absolutePath(); @@ -740,20 +816,24 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath) break; } Qt3DRender::QSceneLoader *loader = new Qt3DRender::QSceneLoader(geometryEntity); + const QPointer guardedLoader(loader); + const QPointer guardedGeometry(geometryEntity); connect(loader, &Qt3DRender::QSceneLoader::statusChanged, this, - [this, loader, source, geometryEntity, teachingJointName] + [this, guardedLoader, source, guardedGeometry, teachingJointName] (Qt3DRender::QSceneLoader::Status status) { + if (!guardedLoader || !guardedGeometry) + return; if (status == Qt3DRender::QSceneLoader::Error) { emit logMessage(QStringLiteral("ERROR"), QStringLiteral("Qt3D 无法加载网格:%1").arg(source)); } else if (status == Qt3DRender::QSceneLoader::Ready && !teachingJointName.isEmpty()) { - const QStringList entityNames = loader->entityNames(); + const QStringList entityNames = guardedLoader->entityNames(); for (const QString &entityName : entityNames) { - Qt3DCore::QEntity *loadedEntity = loader->entity(entityName); + Qt3DCore::QEntity *loadedEntity = guardedLoader->entity(entityName); if (!loadedEntity) continue; - if (loader->component( + if (guardedLoader->component( entityName, Qt3DRender::QSceneLoader::GeometryRendererComponent)) { attachTeachingPicker(loadedEntity, teachingJointName); @@ -761,7 +841,7 @@ bool UrdfViewerWidget::loadUrdf(const QString &filePath) attachTeachingPickersRecursively(loadedEntity, teachingJointName); } - attachTeachingPickersRecursively(geometryEntity, + attachTeachingPickersRecursively(guardedGeometry.data(), teachingJointName); } if (m_view) @@ -1181,18 +1261,16 @@ QString UrdfViewerWidget::resolveMeshPath(const QString &uri) const void UrdfViewerWidget::scheduleViewAll() { + // QCamera::viewEntity() starts a backend bounding-volume query. In Qt + // 5.12 on Windows that query can race the first scene synchronization and + // crash inside Qt53DRender.dll. The viewer already has a deterministic + // camera in resetView(), so only request frames after the scene settles. QTimer::singleShot(120, this, [this]() { - if (m_camera && m_modelRoot) { - m_camera->viewEntity(m_modelRoot); - if (m_view) - m_view->requestUpdate(); - } + if (m_view && m_modelRoot) + m_view->requestUpdate(); }); QTimer::singleShot(700, this, [this]() { - if (m_camera && m_modelRoot) { - m_camera->viewEntity(m_modelRoot); - if (m_view) - m_view->requestUpdate(); - } + if (m_view && m_modelRoot) + m_view->requestUpdate(); }); } diff --git a/styles.qss b/styles.qss index a1717cf..295233f 100644 --- a/styles.qss +++ b/styles.qss @@ -337,9 +337,51 @@ QTabWidget#armMotionCommandTabs QTabBar::tab:selected { font-weight: 600; } QSplitter#armTargetTables::handle { - background: #dfe5ec; - width: 1px; - margin: 26px 5px 4px 5px; + background: transparent; + width: 12px; +} +QWidget#armTargetGroup { + background: transparent; +} +QTableWidget#leftMotionTable, +QTableWidget#motionTable { + background: #ffffff; + alternate-background-color: #f8fafc; + border: 1px solid #dce3ea; + border-radius: 6px; + color: #26323d; +} +QTableWidget#leftMotionTable QHeaderView::section, +QTableWidget#motionTable QHeaderView::section { + background: #eef3f7; + color: #526171; + border: none; + border-bottom: 1px solid #d7e0e8; + padding: 6px 8px; + font-size: 11px; + font-weight: 600; +} +QTableWidget#leftMotionTable::item, +QTableWidget#motionTable::item { + padding: 3px 8px; + border-bottom: 1px solid #edf1f4; +} +QTableWidget#leftMotionTable QDoubleSpinBox, +QTableWidget#motionTable QDoubleSpinBox { + min-height: 24px; + padding: 1px 7px; + background: #f5f8fb; + border: 1px solid transparent; + border-radius: 4px; + color: #1d5fa7; + font-weight: 600; +} +QTableWidget#leftMotionTable QDoubleSpinBox:hover, +QTableWidget#motionTable QDoubleSpinBox:hover, +QTableWidget#leftMotionTable QDoubleSpinBox:focus, +QTableWidget#motionTable QDoubleSpinBox:focus { + background: #ffffff; + border-color: #6aa7ea; } QFrame#urdfToolbar, QFrame#urdfStatusBar { From d7a19c48980f8afc8932cd40735865dd92790dfd Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Mon, 28 Sep 2026 11:01:33 +0800 Subject: [PATCH 02/15] feat: discover cameras and show active codec --- protos/cmvr/api/camera_command.proto | 1 + src/main.cpp | 10 ++-- src/mainwindow.cpp | 79 +++++++++++++++++++++++++--- src/mainwindow.h | 2 +- src/mainwindow_ui.cpp | 37 ++++++------- src/robotclient.cpp | 53 +++++++++++++++++++ src/robotclient.h | 3 ++ ui/cameraservicepage.ui | 4 +- 8 files changed, 155 insertions(+), 34 deletions(-) diff --git a/protos/cmvr/api/camera_command.proto b/protos/cmvr/api/camera_command.proto index 7305955..280d4d0 100644 --- a/protos/cmvr/api/camera_command.proto +++ b/protos/cmvr/api/camera_command.proto @@ -48,6 +48,7 @@ message CameraState { int32 fps = 7; int32 width = 8; int32 height = 9; + string codec = 10; } message GetCameraStateCommand { diff --git a/src/main.cpp b/src/main.cpp index 7ca6fb9..044b1c9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -203,16 +204,17 @@ int main(int argc, char *argv[]) QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 2)); QCheckBox *demoCheck = window.findChild(QStringLiteral("demoCheck")); - QLineEdit *cameraIdEdit = - window.findChild(QStringLiteral("cameraIdEdit")); + QComboBox *cameraDeviceCombo = + window.findChild(QStringLiteral("cameraDeviceCombo")); QPushButton *connectButton = window.findChild(QStringLiteral("connectButton")); - if (!demoCheck || !cameraIdEdit || !connectButton) { + if (!demoCheck || !cameraDeviceCombo || !connectButton) { finishSmoke(3, QStringLiteral("未找到相机自检所需控件")); return; } demoCheck->setChecked(true); - cameraIdEdit->setText(QStringLiteral("demo_camera_1,demo_camera_2")); + cameraDeviceCombo->addItem(QStringLiteral("demo_camera_1"), + QStringLiteral("demo_camera_1")); appendCameraSmokeLog(QStringLiteral("STEP 等待应用自动连接 Demo")); QTimer::singleShot(1500, &window, diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 9028354..43a7589 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -433,7 +433,14 @@ MainWindow::MainWindow(QWidget *parent) break; case 2: pageIndex = 2; - if (m_cameraIdEdit) m_cameraIdEdit->setText(deviceId); + if (m_cameraDeviceCombo) { + int index = m_cameraDeviceCombo->findData(deviceId); + if (index < 0) { + m_cameraDeviceCombo->addItem(deviceId, deviceId); + index = m_cameraDeviceCombo->count() - 1; + } + m_cameraDeviceCombo->setCurrentIndex(index); + } break; case 0: pageIndex = 3; @@ -507,6 +514,26 @@ MainWindow::MainWindow(QWidget *parent) connect(m_client, &RobotClient::systemStatusReceived, this, &MainWindow::updateSystemStatus); connect(m_client, &RobotClient::systemInfoReceived, this, &MainWindow::updateSystemInfo); connect(m_client, &RobotClient::imageReceived, this, &MainWindow::updateImage); + connect(m_client, &RobotClient::cameraStatusReceived, this, + [this](const QString &cameraId, const QVariantMap &state) { + if (!m_cameraDeviceCombo || !m_cameraCodecCombo + || m_cameraDeviceCombo->currentData().toString() != cameraId) { + return; + } + const QString codec = state.value(QStringLiteral("codec")).toString().toLower(); + if (codec.isEmpty()) + return; + const bool isH265 = codec.contains(QStringLiteral("265")) + || codec.contains(QStringLiteral("hevc")); + { + const QSignalBlocker blocker(m_cameraCodecCombo); + m_cameraCodecCombo->setCurrentIndex(isH265 ? 1 : 0); + } + m_cameraCodecCombo->setToolTip( + QStringLiteral("服务端当前编码器:%1").arg(codec.toUpper())); + m_client->setCameraStreamCodec(isH265 ? QStringLiteral("h265") + : QStringLiteral("h264")); + }); connect(m_client, &RobotClient::videoFrameReceived, this, &MainWindow::updateVideoFrame); connect(m_client, &RobotClient::cameraStreamStateChanged, this, &MainWindow::updateCameraStreamState); @@ -1372,9 +1399,6 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk, 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; @@ -1415,6 +1439,43 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk, m_client->requestArmInfo(firstArmId); m_client->requestArmFrames(firstArmId); } + + if (m_cameraDeviceCombo) { + const QString previousCameraId = m_cameraDeviceCombo->currentData().toString(); + { + const QSignalBlocker blocker(m_cameraDeviceCombo); + m_cameraDeviceCombo->clear(); + for (const QVariant &value : devices) { + const QVariantMap device = value.toMap(); + if (device.value(QStringLiteral("type")).toInt() != 2) + continue; + const QString deviceId = device.value(QStringLiteral("deviceId")).toString(); + if (deviceId.isEmpty()) + continue; + const QString vendor = device.value(QStringLiteral("vendor")).toString(); + const QString driver = device.value(QStringLiteral("driverType")).toString(); + const QString detail = !vendor.isEmpty() ? vendor : driver; + m_cameraDeviceCombo->addItem( + detail.isEmpty() ? deviceId + : QStringLiteral("%1 · %2").arg(deviceId, detail), + deviceId); + } + int index = m_cameraDeviceCombo->findData(previousCameraId); + if (index < 0 && m_cameraDeviceCombo->count() > 0) + index = 0; + if (index >= 0) + m_cameraDeviceCombo->setCurrentIndex(index); + } + m_cameraDeviceCombo->setEnabled(!m_cameraStreaming && !m_cameraRecording + && m_cameraDeviceCombo->count() > 0); + if (!m_cameraStreaming + && previousCameraId != m_cameraDeviceCombo->currentData().toString()) + rebuildCameraPreviewGrid(configuredCameraIds()); + const QString cameraId = m_cameraDeviceCombo->currentData().toString(); + if (!cameraId.isEmpty() + && (previousCameraId != cameraId || m_cameraCodecCombo->toolTip().isEmpty())) + m_client->requestCameraStatus(cameraId); + } } void MainWindow::updateSystemInfo(const QVariantMap &info) @@ -1618,7 +1679,8 @@ void MainWindow::updateCameraRecordingState(bool recording, const QString &detai m_cameraRecordButton->style()->unpolish(m_cameraRecordButton); m_cameraRecordButton->style()->polish(m_cameraRecordButton); m_cameraRecordPathEdit->setEnabled(!recording); - m_cameraIdEdit->setEnabled(!m_cameraStreaming && !recording); + m_cameraDeviceCombo->setEnabled(!m_cameraStreaming && !recording + && m_cameraDeviceCombo->count() > 0); m_cameraRecordStateLabel->setText(recording ? QStringLiteral("录像中") : QStringLiteral("未录像")); m_cameraRecordStateLabel->setToolTip(detail); @@ -2028,7 +2090,9 @@ void MainWindow::loadSettings() 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()); + const QString cameraDeviceId = settings.value(QStringLiteral("camera/device"), QString()).toString().trimmed(); + if (m_cameraDeviceCombo && !cameraDeviceId.isEmpty()) + m_cameraDeviceCombo->addItem(cameraDeviceId, cameraDeviceId); rebuildCameraPreviewGrid(configuredCameraIds()); m_cameraRecordPathEdit->setText(settings.value( QStringLiteral("camera/recordPath"), @@ -2101,7 +2165,8 @@ void MainWindow::saveSettings() 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/device"), + configuredCameraIds().value(0)); settings.setValue(QStringLiteral("camera/recordPath"), m_cameraRecordPathEdit->text().trimmed()); settings.setValue(QStringLiteral("camera/codec"), diff --git a/src/mainwindow.h b/src/mainwindow.h index 23dfca5..392871f 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -269,7 +269,7 @@ private: bool m_jointPointLoopActive = false; bool m_jointPointMovePending = false; - QLineEdit *m_cameraIdEdit = nullptr; + QComboBox *m_cameraDeviceCombo = nullptr; VideoRenderWidget *m_videoRender = nullptr; QLabel *m_imageMetaLabel = nullptr; QPushButton *m_snapshotButton = nullptr; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index bdb8e01..f662840 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -1365,20 +1365,10 @@ QWidget *MainWindow::createArmPage() QStringList MainWindow::configuredCameraIds() const { - if (!m_cameraIdEdit) + if (!m_cameraDeviceCombo) return {}; - const QStringList values = m_cameraIdEdit->text().split( - QRegularExpression(QStringLiteral("[,;\\s]+")), QString::SkipEmptyParts); - QStringList result; - QSet seen; - for (const QString &value : values) { - const QString cameraId = value.trimmed(); - if (!cameraId.isEmpty() && !seen.contains(cameraId)) { - seen.insert(cameraId); - result.append(cameraId); - } - } - return result; + const QString cameraId = m_cameraDeviceCombo->currentData().toString().trimmed(); + return cameraId.isEmpty() ? QStringList() : QStringList{cameraId}; } void MainWindow::rebuildCameraPreviewGrid(const QStringList &cameraIds) @@ -1463,8 +1453,9 @@ void MainWindow::refreshCameraStreamControls() ? QStringLiteral("dangerButton") : QStringLiteral("primaryButton")); m_cameraStreamButton->style()->unpolish(m_cameraStreamButton); m_cameraStreamButton->style()->polish(m_cameraStreamButton); - m_cameraIdEdit->setEnabled(!m_cameraStreaming && !m_cameraRecording); - m_cameraCodecCombo->setEnabled(!m_cameraStreaming); + m_cameraDeviceCombo->setEnabled(!m_cameraStreaming && !m_cameraRecording + && m_cameraDeviceCombo->count() > 0); + m_cameraCodecCombo->setEnabled(false); m_cameraStreamModeCombo->setEnabled(!m_cameraStreaming); m_snapshotButton->setEnabled(m_connected && !m_cameraStreaming); m_cameraStreamStateLabel->setText(m_cameraStreaming @@ -1489,7 +1480,7 @@ QWidget *MainWindow::createCameraPage() m_cameraPreviewGrid->setContentsMargins(0, 0, 0, 0); m_cameraPreviewGrid->setSpacing(10); ui.viewerLayout->addWidget(m_cameraPreviewContainer, 1); - m_cameraIdEdit = ui.cameraIdEdit; + m_cameraDeviceCombo = ui.cameraDeviceCombo; m_snapshotButton = ui.snapshotButton; m_cameraStreamButton = ui.cameraStreamButton; m_cameraCodecCombo = ui.codecCombo; @@ -1524,9 +1515,15 @@ QWidget *MainWindow::createCameraPage() .arg(index == 1 ? QStringLiteral("H.265") : QStringLiteral("H.264"))); } }); - connect(m_cameraIdEdit, &QLineEdit::editingFinished, this, [this]() { - if (!m_cameraStreaming) + connect(m_cameraDeviceCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, [this](int) { + if (!m_cameraStreaming) { rebuildCameraPreviewGrid(configuredCameraIds()); + saveSettings(); + } + const QStringList cameraIds = configuredCameraIds(); + if (m_connected && !cameraIds.isEmpty()) + m_client->requestCameraStatus(cameraIds.first()); }); connect(m_cameraStreamButton, &QPushButton::clicked, this, [this]() { if (m_cameraStreaming) { @@ -1537,7 +1534,7 @@ QWidget *MainWindow::createCameraPage() const QStringList cameraIds = configuredCameraIds(); if (cameraIds.isEmpty()) { appendLog(QStringLiteral("WARN"), - QStringLiteral("请至少填写一个摄像头设备 ID")); + QStringLiteral("服务端未返回可用的摄像头设备")); return; } saveSettings(); @@ -1570,7 +1567,7 @@ QWidget *MainWindow::createCameraPage() if (cameraIds.isEmpty()) { m_cameraRecordButton->setEnabled(m_connected); appendLog(QStringLiteral("WARN"), - QStringLiteral("请先填写摄像头设备 ID")); + QStringLiteral("服务端未返回可用的摄像头设备")); return; } m_client->startCameraRecording(cameraIds.first(), path); diff --git a/src/robotclient.cpp b/src/robotclient.cpp index 51c524e..80585e4 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -576,6 +576,47 @@ public: #endif } + void getCameraStatus(const QString &cameraId) + { + if (!ensureConnected(QStringLiteral("Get Camera Status")) + || !ensureDeviceId(QStringLiteral("Get Camera Status"), cameraId)) { + return; + } + QVariantMap state; + if (m_demoMode) { + state.insert(QStringLiteral("codec"), QStringLiteral("h264")); + state.insert(QStringLiteral("fps"), 30); + state.insert(QStringLiteral("width"), 1280); + state.insert(QStringLiteral("height"), 720); + if (cameraStatusReceived) + cameraStatusReceived(cameraId.trimmed(), state); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::GetCameraStateCommand::Request request; + fillHeader(request.mutable_header(), cameraId); + cmvr::api::GetCameraStateCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 1200); + const grpc::Status status = m_camera->GetStatus(&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("Get Camera Status"), false, detail); + return; + } + const auto &cameraState = response.state(); + state.insert(QStringLiteral("codec"), QString::fromStdString(cameraState.codec())); + state.insert(QStringLiteral("fps"), cameraState.fps()); + state.insert(QStringLiteral("width"), cameraState.width()); + state.insert(QStringLiteral("height"), cameraState.height()); + state.insert(QStringLiteral("streaming"), cameraState.is_streaming()); + if (cameraStatusReceived) + cameraStatusReceived(cameraId.trimmed(), state); +#endif + } + void setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame, const QString &tcpFrame) { @@ -2014,6 +2055,7 @@ public: std::function systemStatusReceived; std::function systemInfoReceived; std::function imageReceived; + std::function cameraStatusReceived; std::function videoFrameReceivedForCamera; std::function @@ -3142,6 +3184,12 @@ RobotClient::RobotClient(QObject *parent) emit imageReceived(image, detail); }, Qt::QueuedConnection); }; + m_worker->cameraStatusReceived = [this](const QString &cameraId, + const QVariantMap &state) { + QMetaObject::invokeMethod(this, [this, cameraId, state]() { + emit cameraStatusReceived(cameraId, state); + }, Qt::QueuedConnection); + }; const auto queueVideoFrame = [this](const QString &cameraId, const VideoFrame &frame, const QString &detail) { @@ -3287,6 +3335,7 @@ RobotClient::RobotClient(QObject *parent) connect(this, &RobotClient::armCalibrateZeroRequested, m_worker, &BackendWorker::armCalibrateZero); connect(this, &RobotClient::snapshotRequested, m_worker, &BackendWorker::snapshot); + connect(this, &RobotClient::cameraStatusRequested, m_worker, &BackendWorker::getCameraStatus); connect(this, &RobotClient::cameraStreamStartRequested, m_worker, &BackendWorker::startCameraStream); connect(this, &RobotClient::cameraStreamCodecRequested, m_worker, &BackendWorker::setCameraStreamCodec); @@ -3410,6 +3459,10 @@ void RobotClient::requestArmCalibrateZero(const QString &deviceId, const QString emit armCalibrateZeroRequested(deviceId, jointName); } void RobotClient::requestSnapshot(const QString &cameraId) { emit snapshotRequested(cameraId); } +void RobotClient::requestCameraStatus(const QString &cameraId) +{ + emit cameraStatusRequested(cameraId); +} void RobotClient::startCameraStream(const QString &cameraId, const QString &codec, const QString &mode) { diff --git a/src/robotclient.h b/src/robotclient.h index 90a7c77..c32732f 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -47,6 +47,7 @@ public slots: void requestArmClearFault(const QString &deviceId); void requestArmCalibrateZero(const QString &deviceId, const QString &jointName); void requestSnapshot(const QString &cameraId); + void requestCameraStatus(const QString &cameraId); void startCameraStream(const QString &cameraId, const QString &codec, const QString &mode = QStringLiteral("rgb")); void setCameraStreamCodec(const QString &codec); @@ -107,6 +108,7 @@ signals: void armClearFaultRequested(const QString &deviceId); void armCalibrateZeroRequested(const QString &deviceId, const QString &jointName); void snapshotRequested(const QString &cameraId); + void cameraStatusRequested(const QString &cameraId); void cameraStreamStartRequested(const QString &cameraId, const QString &codec, const QString &mode); void cameraStreamCodecRequested(const QString &codec); @@ -158,6 +160,7 @@ signals: const QVariantList &devices); void systemInfoReceived(const QVariantMap &info); void imageReceived(const QImage &image, const QString &detail); + void cameraStatusReceived(const QString &cameraId, const QVariantMap &state); void videoFrameReceived(const QString &cameraId, const VideoFrame &frame, const QString &detail); void cameraStreamStateChanged(const QString &cameraId, bool running, diff --git a/ui/cameraservicepage.ui b/ui/cameraservicepage.ui index f31c85d..0367945 100644 --- a/ui/cameraservicepage.ui +++ b/ui/cameraservicepage.ui @@ -20,12 +20,12 @@ 1218161818 CameraServicesectionTitle - 设备 IDcamera + 摄像头由服务端设备列表自动加载 单帧抓图eyebrow 获取 RGB 图像primaryButton Qt::VerticalQSizePolicy::Fixed2010 实时视频eyebrow - 解码格式H.264 / AVCH.265 / HEVC流模式RGBrgbDepthdepthRGBDrgbd + 当前编码器falseH.264 / AVCH.265 / HEVC流模式RGBrgbDepthdepthRGBDrgbd 开始预览primaryButton 流状态mutedLabelQt::Horizontal4020已停止panelSubtitle Qt::VerticalQSizePolicy::Fixed208 From 6c3477a8733391f4cc48bf3adbe4d0f1b82a6230 Mon Sep 17 00:00:00 2001 From: xtkuang <87661715@qq.com> Date: Thu, 8 Oct 2026 15:24:48 +0800 Subject: [PATCH 03/15] Integrate AGV control workspace and arm telemetry --- CMakeLists.txt | 2 + CmvrControlStation.pro | 2 + protos/cmvr/api/agv_command.proto | 40 +++- protos/cmvr/api/agv_service.proto | 7 + protos/cmvr/msgs/agv.proto | 39 +++- src/agvmapviewwidget.cpp | 286 +++++++++++++++++++++++++ src/agvmapviewwidget.h | 57 +++++ src/mainwindow.cpp | 269 +++++++++++++++++++++--- src/mainwindow.h | 17 +- src/mainwindow_ui.cpp | 338 +++++++++++++++++++++++------- src/robotclient.cpp | 89 +++++++- src/robotclient.h | 7 +- ui/agvservicepage.ui | 2 - ui/agvstatusdialog.ui | 10 - 14 files changed, 1038 insertions(+), 127 deletions(-) create mode 100644 src/agvmapviewwidget.cpp create mode 100644 src/agvmapviewwidget.h diff --git a/CMakeLists.txt b/CMakeLists.txt index d51ab7a..55df4c3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -152,6 +152,8 @@ if(CMVR_WITH_MSQUIC) endif() set(CMVR_SOURCES + src/agvmapviewwidget.cpp + src/agvmapviewwidget.h src/audiostreammanager.cpp src/audiostreammanager.h src/configeditorwidget.cpp diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index d2633e4..dbb8f81 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -237,6 +237,7 @@ CONFIG(debug, debug|release) { !exists($$ASSIMP_SCENE_PARSER): error("Qt3D Assimp scene parser not found in the selected Qt Kit.") SOURCES += \ + src/agvmapviewwidget.cpp \ src/audiostreammanager.cpp \ src/configeditorwidget.cpp \ src/main.cpp \ @@ -252,6 +253,7 @@ SOURCES += \ ui/handeyecalibrationwidget.cpp HEADERS += \ + src/agvmapviewwidget.h \ src/audiostreammanager.h \ src/configeditorwidget.h \ src/mainwindow.h \ diff --git a/protos/cmvr/api/agv_command.proto b/protos/cmvr/api/agv_command.proto index d6c6649..7ddb71b 100644 --- a/protos/cmvr/api/agv_command.proto +++ b/protos/cmvr/api/agv_command.proto @@ -37,6 +37,23 @@ message AgvNavigationStatusCommand { } } + +// 在当前活动地图中重新设置 AGV 定位位姿。 +message AgvRelocalizeCommand { + message Request { + // header.device_id 指定目标 AGV 设备。 + CommandHeader.Request header = 1; + // x/y 单位:米,theta 单位:弧度,逆时针为正。 + cmvr.msgs.AgvPose2d pose = 2; + } + + message Feedback { + // 成功仅表示控制器接受命令,不表示定位已经收敛。 + CommandHeader.Feedback header = 1; + } +} + + // 导航到指定地图位姿命令。 message AgvNavigateToPoseCommand { // 请求体。 @@ -45,7 +62,7 @@ message AgvNavigateToPoseCommand { CommandHeader.Request header = 1; // 目标位姿。x/y 单位:米,theta 单位:弧度。 cmvr.msgs.AgvPose2d pose = 2; - // 通用运动约束和执行选项。 + // 通用运动约束和执行选项;默认同步阻塞至任务终态并确认停车。 cmvr.msgs.AgvMotionOptions options = 3; // AGV 适配器扩展参数,用于传递厂商特有选项。 cmvr.msgs.AgvAdapterParams adapter_params = 4; @@ -65,7 +82,7 @@ message AgvNavigateToStationCommand { CommandHeader.Request header = 1; // 目标站点 id。 string station_id = 2; - // 通用运动约束和执行选项。 + // 通用运动约束和执行选项;默认同步阻塞至任务终态并确认停车。 cmvr.msgs.AgvMotionOptions options = 3; // AGV 适配器扩展参数,用于传递厂商特有选项。 cmvr.msgs.AgvAdapterParams adapter_params = 4; @@ -85,7 +102,7 @@ message AgvFollowPathCommand { CommandHeader.Request header = 1; // 路径段列表。每段包含起点站点 id 和终点站点 id。 repeated cmvr.msgs.AgvPathSegment path = 2; - // 通用执行选项。上位机使用异步模式提交任务,并通过导航状态接口跟踪进度。 + // 通用执行选项;默认同步阻塞至整条路径终态并确认停车。 cmvr.msgs.AgvMotionOptions options = 3; } // 反馈体。 @@ -95,6 +112,23 @@ message AgvFollowPathCommand { } } + +// 按指定速度执行固定距离平移命令。 +message AgvTranslateCommand { + message Request { + // 通用请求头。header.device_id 指定目标 AGV 设备。 + CommandHeader.Request header = 1; + // 固定距离平移参数。 + cmvr.msgs.AgvTranslation translation = 2; + } + + message Feedback { + // 仅表示控制器是否接受命令,不表示平移已经完成。 + CommandHeader.Feedback header = 1; + } +} + + // 下发底盘速度命令。 message AgvSetVelocityCommand { // 请求体。 diff --git a/protos/cmvr/api/agv_service.proto b/protos/cmvr/api/agv_service.proto index f0bdc5b..b8de93d 100644 --- a/protos/cmvr/api/agv_service.proto +++ b/protos/cmvr/api/agv_service.proto @@ -20,6 +20,9 @@ service AgvService { // 清除可恢复故障或告警。 rpc clearFault(CommandHeader.Request) returns (CommandHeader.Feedback); + // 在当前活动地图中重新设置定位位姿。调用前 AGV 必须已经停止。 + rpc relocalize(AgvRelocalizeCommand.Request)returns (AgvRelocalizeCommand.Feedback); + // 导航到指定地图位姿。目标位姿 x/y 单位为米,theta 单位为弧度。 rpc navigateToPose(AgvNavigateToPoseCommand.Request) returns (AgvNavigateToPoseCommand.Feedback); @@ -69,4 +72,8 @@ service AgvService { // 停止当前建图/扫图会话。 rpc stopMapping(CommandHeader.Request) returns (CommandHeader.Feedback); + + + // 按指定速度平移固定距离。成功返回仅表示控制器已接受命令。 + rpc translate(AgvTranslateCommand.Request) returns (AgvTranslateCommand.Feedback); } diff --git a/protos/cmvr/msgs/agv.proto b/protos/cmvr/msgs/agv.proto index 54439ee..39109f4 100644 --- a/protos/cmvr/msgs/agv.proto +++ b/protos/cmvr/msgs/agv.proto @@ -1,5 +1,7 @@ syntax = "proto3"; +// 文件随 AGV API 定义统一放在 cmvr/api 下,但保留 cmvr.msgs package, +// 以兼容既有生成代码、消息完整名称和 Any type URL。 package cmvr.msgs; // AGV 在地图平面坐标系中的二维位姿。 @@ -12,6 +14,29 @@ message AgvPose2d { double theta = 3; } +// 固定距离平移使用的距离参考模式。 +enum AgvTranslationMode { + // 根据底盘里程计算运动距离。 + AGV_TRANSLATION_MODE_ODOMETRY = 0; + // 根据定位结果计算运动距离。 + AGV_TRANSLATION_MODE_LOCALIZATION = 1; +} + + + +// AGV 车体坐标系下的固定距离平移参数。 +message AgvTranslation { + // 平移距离的绝对值,单位:米,必须大于 0。 + double distance = 1; + // 车体 X 方向速度,单位:米/秒;正为向前,负为向后。 + double vx = 2; + // 车体 Y 方向速度,单位:米/秒;正为向左,负为向右。 + double vy = 3; + // 距离参考模式;默认使用里程模式。 + AgvTranslationMode mode = 4; +} + + // AGV 车体坐标系下的平面速度。 message AgvVelocity { // 车体 X 方向线速度,单位:米/秒。 @@ -22,6 +47,9 @@ message AgvVelocity { double wz = 3; } + + + // AGV 电池状态。 message AgvBatteryState { // 电量比例,范围:[0, 1],例如 0.8 表示 80%。 @@ -52,8 +80,17 @@ message AgvMotionOptions { double reach_angle = 6; // 速度比例,范围通常为 [0, 1];1 表示不降速。 double speed_ratio = 7; - // 是否异步执行;true 表示下发任务后立即返回。 + // 是否异步执行;false(默认)表示到达、失败、取消或遇障停止后才返回, + // true 表示任务被控制器接受后立即返回。 bool asynchronous = 8; + // 同步导航的最大等待时间,单位:毫秒;0 表示使用适配器默认值。 + // gRPC deadline 应大于该值或预计行程时间,否则服务端会安全取消导航。 + int32 wait_timeout_ms = 9; + // 同步导航的状态轮询周期,单位:毫秒;0 表示使用适配器默认值。 + int32 poll_interval_ms = 10; + // 连续遇障且底盘停止时的最大等待时间,单位:毫秒; + // 0 或未传表示使用适配器默认值 60000 毫秒。 + int32 blocked_timeout_ms = 11; } // AGV 适配器扩展参数。用于传递厂商或控制器特有的参数。 diff --git a/src/agvmapviewwidget.cpp b/src/agvmapviewwidget.cpp new file mode 100644 index 0000000..ef13cc6 --- /dev/null +++ b/src/agvmapviewwidget.cpp @@ -0,0 +1,286 @@ +#include "agvmapviewwidget.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr double kMinimumZoom = 0.5; +constexpr double kMaximumZoom = 8.0; +constexpr int kMaximumTrajectoryPoints = 600; +constexpr double kTrajectoryMinimumDistance = 0.03; +} + +AgvMapViewWidget::AgvMapViewWidget(QWidget *parent) + : QWidget(parent) +{ + setMinimumSize(420, 320); + setMouseTracking(true); + setCursor(Qt::OpenHandCursor); + setFocusPolicy(Qt::StrongFocus); + setAutoFillBackground(false); +} + +void AgvMapViewWidget::setMapFrame(const QImage &image, + const QVariantMap &metadata) +{ + const QString nextMapId = metadata.value(QStringLiteral("mapId")).toString(); + if (!nextMapId.isEmpty() && nextMapId != m_mapId) { + m_mapId = nextMapId; + clearTrajectory(); + resetView(); + } + m_image = image; + m_metadata = metadata; + update(); +} + +void AgvMapViewWidget::updateRobotPose(double x, double y, double theta, + bool localized) +{ + m_robotX = x; + m_robotY = y; + m_robotTheta = theta; + m_localized = localized; + m_hasPose = qIsFinite(x) && qIsFinite(y) && qIsFinite(theta); + + if (m_hasPose && localized && canProjectPose()) { + const QPointF next(x, y); + if (m_trajectory.isEmpty() + || QLineF(m_trajectory.constLast(), next).length() + >= kTrajectoryMinimumDistance) { + m_trajectory.append(next); + if (m_trajectory.size() > kMaximumTrajectoryPoints) + m_trajectory.remove(0, m_trajectory.size() + - kMaximumTrajectoryPoints); + } + } + update(); +} + +void AgvMapViewWidget::setStreamMessage(const QString &message) +{ + m_streamMessage = message; + update(); +} + +void AgvMapViewWidget::zoomIn() +{ + changeZoom(1.25, rect().center()); +} + +void AgvMapViewWidget::zoomOut() +{ + changeZoom(0.8, rect().center()); +} + +void AgvMapViewWidget::resetView() +{ + m_zoom = 1.0; + m_pan = QPointF(); + update(); +} + +void AgvMapViewWidget::clearTrajectory() +{ + m_trajectory.clear(); + update(); +} + +bool AgvMapViewWidget::canProjectPose() const +{ + return !m_image.isNull() + && m_metadata.value(QStringLiteral("dimension")).toInt() == 2 + && m_metadata.value(QStringLiteral("resolution")).toDouble() > 0.0 + && m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble() > 0.0; +} + +QPointF AgvMapViewWidget::worldToImage(double x, double y) const +{ + const double originX = m_metadata.value(QStringLiteral("originX")).toDouble(); + const double originY = m_metadata.value(QStringLiteral("originY")).toDouble(); + const double originTheta = m_metadata.value(QStringLiteral("originTheta")).toDouble(); + const double resolution = m_metadata.value(QStringLiteral("resolution")).toDouble(); + const double renderScale = m_metadata.value(QStringLiteral("renderScale"), 1.0).toDouble(); + + const double dx = x - originX; + const double dy = y - originY; + const double cosine = qCos(originTheta); + const double sine = qSin(originTheta); + const double gridX = (cosine * dx + sine * dy) / resolution; + const double gridY = (-sine * dx + cosine * dy) / resolution; + return QPointF(gridX * renderScale, + m_image.height() - gridY * renderScale); +} + +double AgvMapViewWidget::viewScale() const +{ + if (m_image.isNull()) + return 1.0; + const double horizontal = qMax(1, width() - 24) + / static_cast(m_image.width()); + const double vertical = qMax(1, height() - 24) + / static_cast(m_image.height()); + return qMin(horizontal, vertical) * m_zoom; +} + +QPointF AgvMapViewWidget::imageTopLeft() const +{ + if (m_image.isNull()) + return QPointF(); + const double scale = viewScale(); + return QPointF((width() - m_image.width() * scale) * 0.5, + (height() - m_image.height() * scale) * 0.5) + m_pan; +} + +QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const +{ + return imageTopLeft() + point * viewScale(); +} + +void AgvMapViewWidget::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event) + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.fillRect(rect(), QColor(QStringLiteral("#eef2f6"))); + + if (m_image.isNull()) { + painter.setPen(QColor(QStringLiteral("#71808e"))); + painter.drawText(rect(), Qt::AlignCenter, + m_streamMessage.isEmpty() + ? QStringLiteral("等待 AGV 返回地图数据") + : m_streamMessage); + return; + } + + const double scale = viewScale(); + const QPointF topLeft = imageTopLeft(); + const QRectF target(topLeft, + QSizeF(m_image.width() * scale, + m_image.height() * scale)); + painter.setRenderHint(QPainter::SmoothPixmapTransform, true); + painter.drawImage(target, m_image); + painter.setPen(QPen(QColor(QStringLiteral("#c9d4de")), 1)); + painter.setBrush(Qt::NoBrush); + painter.drawRect(target); + + if (canProjectPose() && m_trajectory.size() > 1) { + QPainterPath path; + path.moveTo(imageToWidget(worldToImage( + m_trajectory.first().x(), m_trajectory.first().y()))); + for (int index = 1; index < m_trajectory.size(); ++index) { + path.lineTo(imageToWidget(worldToImage( + m_trajectory.at(index).x(), m_trajectory.at(index).y()))); + } + painter.setPen(QPen(QColor(QStringLiteral("#2f6fed")), 2, + Qt::DashLine, Qt::RoundCap, Qt::RoundJoin)); + painter.drawPath(path); + } + + if (canProjectPose() && m_hasPose) { + const QPointF center = imageToWidget(worldToImage(m_robotX, m_robotY)); + const double originTheta = m_metadata.value( + QStringLiteral("originTheta")).toDouble(); + const double angle = m_robotTheta - originTheta; + const QPointF forward(qCos(angle), -qSin(angle)); + const QPointF lateral(-forward.y(), forward.x()); + const double size = 13.0; + QPolygonF robot; + robot << center + forward * size + << center - forward * size * 0.7 + lateral * size * 0.65 + << center - forward * size * 0.7 - lateral * size * 0.65; + + painter.setPen(Qt::NoPen); + painter.setBrush(QColor(47, 111, 237, m_localized ? 48 : 24)); + painter.drawEllipse(center, 25, 25); + painter.setBrush(m_localized + ? QColor(QStringLiteral("#2f6fed")) + : QColor(QStringLiteral("#df8b24"))); + painter.drawPolygon(robot); + painter.setPen(QColor(QStringLiteral("#ffffff"))); + painter.drawLine(center - forward * 2, center + forward * 7); + + const QString poseText = QStringLiteral("(%1, %2, %3°)") + .arg(m_robotX, 0, 'f', 2) + .arg(m_robotY, 0, 'f', 2) + .arg(qRadiansToDegrees(m_robotTheta), 0, 'f', 1); + const QFontMetrics metrics(painter.font()); + QRectF labelRect = metrics.boundingRect(poseText); + labelRect.adjust(-7, -4, 7, 4); + labelRect.moveBottomLeft(center + QPointF(16, -14)); + painter.setPen(QPen(QColor(QStringLiteral("#b9c9dc")), 1)); + painter.setBrush(QColor(255, 255, 255, 238)); + painter.drawRoundedRect(labelRect, 6, 6); + painter.setPen(QColor(QStringLiteral("#145da8"))); + painter.drawText(labelRect, Qt::AlignCenter, poseText); + } + + if (!m_streamMessage.isEmpty()) { + const QRect messageRect(12, height() - 36, width() - 24, 24); + painter.setPen(QColor(QStringLiteral("#5c6975"))); + painter.drawText(messageRect, Qt::AlignLeft | Qt::AlignVCenter, + m_streamMessage); + } +} + +void AgvMapViewWidget::changeZoom(double factor, const QPointF &anchor) +{ + if (m_image.isNull()) + return; + const double oldScale = viewScale(); + const QPointF imagePoint = (anchor - imageTopLeft()) / oldScale; + m_zoom = qBound(kMinimumZoom, m_zoom * factor, kMaximumZoom); + const double newScale = viewScale(); + const QPointF centeredTopLeft( + (width() - m_image.width() * newScale) * 0.5, + (height() - m_image.height() * newScale) * 0.5); + m_pan = anchor - imagePoint * newScale - centeredTopLeft; + update(); +} + +void AgvMapViewWidget::wheelEvent(QWheelEvent *event) +{ + changeZoom(event->angleDelta().y() > 0 ? 1.15 : 0.87, event->pos()); + event->accept(); +} + +void AgvMapViewWidget::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + m_dragging = true; + m_lastMousePosition = event->pos(); + setCursor(Qt::ClosedHandCursor); + event->accept(); + return; + } + QWidget::mousePressEvent(event); +} + +void AgvMapViewWidget::mouseMoveEvent(QMouseEvent *event) +{ + if (m_dragging) { + m_pan += event->pos() - m_lastMousePosition; + m_lastMousePosition = event->pos(); + update(); + event->accept(); + return; + } + QWidget::mouseMoveEvent(event); +} + +void AgvMapViewWidget::mouseReleaseEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton && m_dragging) { + m_dragging = false; + setCursor(Qt::OpenHandCursor); + event->accept(); + return; + } + QWidget::mouseReleaseEvent(event); +} diff --git a/src/agvmapviewwidget.h b/src/agvmapviewwidget.h new file mode 100644 index 0000000..5a1d5cf --- /dev/null +++ b/src/agvmapviewwidget.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +class QMouseEvent; +class QPaintEvent; +class QWheelEvent; + +class AgvMapViewWidget final : public QWidget +{ +public: + explicit AgvMapViewWidget(QWidget *parent = nullptr); + + void setMapFrame(const QImage &image, const QVariantMap &metadata); + void updateRobotPose(double x, double y, double theta, bool localized); + void setStreamMessage(const QString &message); + void zoomIn(); + void zoomOut(); + void resetView(); + void clearTrajectory(); + +protected: + void paintEvent(QPaintEvent *event) override; + void wheelEvent(QWheelEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + +private: + bool canProjectPose() const; + QPointF worldToImage(double x, double y) const; + QPointF imageToWidget(const QPointF &point) const; + double viewScale() const; + QPointF imageTopLeft() const; + void changeZoom(double factor, const QPointF &anchor); + + QImage m_image; + QVariantMap m_metadata; + QVector m_trajectory; + QString m_streamMessage; + QString m_mapId; + QPointF m_pan; + QPoint m_lastMousePosition; + double m_zoom = 1.0; + double m_robotX = 0.0; + double m_robotY = 0.0; + double m_robotTheta = 0.0; + bool m_localized = false; + bool m_hasPose = false; + bool m_dragging = false; +}; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 18ccab8..afe4b03 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,6 +1,7 @@ #include "mainwindow.h" #include "videorenderwidget.h" +#include "agvmapviewwidget.h" #include "audiostreammanager.h" #include "configeditorwidget.h" #include "robotclient.h" @@ -11,6 +12,8 @@ #include "urdfviewerwidget.h" #include "ui_mainwindow.h" +#include +#include #include #include #include @@ -26,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -33,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -515,15 +520,22 @@ MainWindow::MainWindow(QWidget *parent) 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); + [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); @@ -581,6 +593,7 @@ MainWindow::MainWindow(QWidget *parent) } selectPage(initialPage); setControlsEnabled(false); + qApp->installEventFilter(this); appendLog(QStringLiteral("INFO"), QStringLiteral("CMVR 控制台已启动")); appendLog(QStringLiteral("INFO"), m_client->grpcAvailable() ? QStringLiteral("原生 gRPC 后端可用") @@ -595,6 +608,10 @@ MainWindow::MainWindow(QWidget *parent) MainWindow::~MainWindow() { + qApp->removeEventFilter(this); + stopAgvManualMotion(false); + if (m_client) + m_client->stopAgvMapStream(); m_audioManager->stopSource(); m_audioManager->stopPlayback(); m_client->stopSpeakerAudioStream(); @@ -672,6 +689,74 @@ bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *r 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); @@ -794,10 +879,38 @@ void MainWindow::appendQuicLog(const QString &level, const QString &message) .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)); @@ -807,12 +920,67 @@ void MainWindow::selectPage(int index) m_armHeaderControls->setVisible(index == 1); if (index == 1) ensureArmModelLoaded(); - if (index != 3 && m_agvStatusSwitch && m_agvStatusSwitch->isChecked()) - m_agvStatusSwitch->setChecked(false); + 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() @@ -878,16 +1046,24 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString & state->style()->polish(state); } setControlsEnabled(connected); - if (m_agvStatusRefreshTimer && m_agvStatusSwitch - && m_agvStatusSwitch->isChecked()) { - if (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(); @@ -897,15 +1073,8 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString & } 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_armTelemetryButton) + setArmTelemetryEnabled(false); if (!connected) { m_armAlertStates.clear(); const QList armStates = {m_servoStatusValue, m_faultStatusValue}; @@ -1396,6 +1565,13 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk, 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) @@ -1410,6 +1586,7 @@ void MainWindow::updateSystemInfo(const QVariantMap &info) 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(); @@ -1429,12 +1606,22 @@ void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &nav .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)); + 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()); - m_agvModeValue->setText(QStringLiteral("模式 %1").arg( - state.value(QStringLiteral("mode")).toInt())); + 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() @@ -1442,9 +1629,12 @@ void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &nav 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) + 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 @@ -1452,11 +1642,19 @@ void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &nav .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) { - const QString selectedMap = m_agvMapCombo->currentText(); + 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); @@ -1632,12 +1830,15 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri || 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); + 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) @@ -1872,6 +2073,8 @@ void MainWindow::setControlsEnabled(bool enabled) m_microphoneStreamStartButton->setEnabled(enabled); if (m_microphoneStreamStopButton) m_microphoneStreamStopButton->setEnabled(false); + if (m_agvDeleteMapButton) + m_agvDeleteMapButton->setEnabled(false); } QString MainWindow::endpoint() const diff --git a/src/mainwindow.h b/src/mainwindow.h index cb9d409..5a9b7c1 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -39,6 +39,7 @@ class QuicTestServer; class UrdfViewerWidget; class AudioStreamManager; class VideoRenderWidget; +class AgvMapViewWidget; class MainWindow : public QMainWindow { @@ -50,6 +51,7 @@ public: protected: bool nativeEvent(const QByteArray &eventType, void *message, long *result) override; + bool eventFilter(QObject *watched, QEvent *event) override; void changeEvent(QEvent *event) override; void resizeEvent(QResizeEvent *event) override; @@ -101,9 +103,13 @@ private: void ensureArmModelLoaded(); void rebuildArmJointTables(const QStringList &jointNames); void rebuildArmJogControls(); + void setArmTelemetryEnabled(bool enabled); void startJointJog(int jointIndex, int direction); void startCartesianJog(int axisIndex, int direction); void stopArmJog(); + void startAgvManualMotion(double vx, double vy, double wz); + void stopAgvManualMotion(bool sendStop = true); + void restartAgvMapStream(const QString &mapName = QString()); void updateArmAlert(const QString &deviceId, const QString &alertKey, const QString &level, const QString &summary, const QString &detail = QString()); @@ -244,8 +250,8 @@ private: QLineEdit *m_agvIdEdit = nullptr; QDialog *m_agvStatusDialog = nullptr; - QCheckBox *m_agvStatusSwitch = nullptr; QTimer *m_agvStatusRefreshTimer = nullptr; + QTimer *m_agvManualVelocityTimer = nullptr; QLabel *m_agvConnectionValue = nullptr; QLabel *m_agvPoseValue = nullptr; QLabel *m_agvMotionValue = nullptr; @@ -261,6 +267,9 @@ private: QLabel *m_agvMapOverview = nullptr; QLabel *m_agvMappingPreview = nullptr; QLabel *m_agvMappingStateLabel = nullptr; + AgvMapViewWidget *m_agvMapView = nullptr; + QWidget *m_agvControlWorkspace = nullptr; + QPushButton *m_agvDeleteMapButton = nullptr; QProgressBar *m_agvProgress = nullptr; QDoubleSpinBox *m_agvXSpin = nullptr; QDoubleSpinBox *m_agvYSpin = nullptr; @@ -273,6 +282,12 @@ private: QComboBox *m_agvStationCombo = nullptr; QTableWidget *m_agvStationTable = nullptr; QString m_agvDownloadPath; + QVariantMap m_latestAgvState; + double m_agvManualVx = 0.0; + double m_agvManualVy = 0.0; + double m_agvManualWz = 0.0; + bool m_agvManualMotionActive = false; + bool m_agvMapStreamActive = false; QList m_serviceButtons; QPushButton *m_speakerStreamStartButton = nullptr; QPushButton *m_speakerStreamStopButton = nullptr; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 3222c2a..4dc4cae 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -1,5 +1,6 @@ #include "mainwindow.h" +#include "agvmapviewwidget.h" #include "audiostreammanager.h" #include "robotclient.h" #include "rpcservicewidget.h" @@ -14,6 +15,7 @@ #include "ui_quicserverpage.h" #include "ui_systemservicepage.h" +#include #include #include #include @@ -31,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -44,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -692,26 +696,13 @@ QWidget *MainWindow::createArmPage() m_client->requestSystemStopAll(target.isEmpty() ? QStringLiteral("*") : target); }); connect(m_armTelemetryButton, &QPushButton::clicked, this, [this](bool enabled) { - const QString deviceId = m_armIdEdit->text().trimmed(); - if (enabled && deviceId.isEmpty()) { + if (enabled && m_armIdEdit->text().trimmed().isEmpty()) { QMessageBox::warning(this, QStringLiteral("ArmService"), - QStringLiteral("请先填写机械臂设备 ID。")); - m_armTelemetryButton->setChecked(false); + QStringLiteral("请先选择机械臂设备。")); + setArmTelemetryEnabled(false); return; } - m_armTelemetryButton->setText(enabled ? QStringLiteral("遥测 10 Hz") - : QStringLiteral("遥测 未启动")); - m_armTelemetryButton->setProperty("active", enabled); - m_armTelemetryButton->style()->unpolish(m_armTelemetryButton); - m_armTelemetryButton->style()->polish(m_armTelemetryButton); - // Keep device selection available while telemetry is running. The - // selection handler transfers polling to the newly selected arm. - m_armSideCombo->setEnabled(true); - if (enabled) { - m_client->requestArmInfo(deviceId); - m_client->requestArmFrames(deviceId); - } - m_client->setArmTelemetry(deviceId, enabled); + setArmTelemetryEnabled(enabled); }); connect(m_torqueOnButton, &QPushButton::clicked, this, [this]() { m_client->requestTorque(m_armIdEdit->text().trimmed(), true); @@ -1094,7 +1085,6 @@ QWidget *MainWindow::createAgvPage() statusUi.statusLayout->setColumnStretch(3, 1); m_agvIdEdit = ui.agvIdEdit; - m_agvStatusSwitch = ui.agvStatusSwitch; m_agvStatusRefreshTimer = new QTimer(page); m_agvStatusRefreshTimer->setInterval(1000); m_agvConnectionValue = statusUi.agvConnectionValue; @@ -1136,41 +1126,251 @@ QWidget *MainWindow::createAgvPage() m_agvStationTable->setSelectionBehavior(QAbstractItemView::SelectRows); m_agvStationTable->verticalHeader()->setVisible(false); m_agvStationTable->horizontalHeader()->setStretchLastSection(true); + m_agvStatusRefreshTimer->setInterval(500); + m_agvManualVelocityTimer = new QTimer(page); + m_agvManualVelocityTimer->setInterval(150); + connect(m_agvManualVelocityTimer, &QTimer::timeout, this, [this]() { + if (!m_agvManualMotionActive || !m_connected) + return; + m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), + m_agvManualVx, m_agvManualVy, + m_agvManualWz); + }); + + m_agvControlWorkspace = new QWidget(ui.agvTabs); + m_agvControlWorkspace->setObjectName(QStringLiteral("agvControlWorkspace")); + QHBoxLayout *workspaceLayout = new QHBoxLayout(m_agvControlWorkspace); + workspaceLayout->setContentsMargins(0, 0, 0, 0); + workspaceLayout->setSpacing(12); + + QWidget *leftColumn = new QWidget(m_agvControlWorkspace); + QVBoxLayout *leftLayout = new QVBoxLayout(leftColumn); + leftLayout->setContentsMargins(0, 0, 0, 0); + leftLayout->setSpacing(12); + QWidget *rightColumn = new QWidget(m_agvControlWorkspace); + QVBoxLayout *rightLayout = new QVBoxLayout(rightColumn); + rightLayout->setContentsMargins(0, 0, 0, 0); + rightLayout->setSpacing(12); + workspaceLayout->addWidget(leftColumn, 7); + workspaceLayout->addWidget(rightColumn, 4); + + ui.mappingPreviewPanel->setParent(leftColumn); + ui.mappingPreviewPanel->setMinimumSize(0, 0); + ui.mappingPreviewTitle->setText(QStringLiteral("实时地图")); + ui.mappingPreviewLayout->removeWidget(ui.mappingPreview); + ui.mappingPreview->hide(); + m_agvMappingPreview = nullptr; + + QHBoxLayout *mapToolbar = new QHBoxLayout; + QLabel *mapLegend = new QLabel( + QStringLiteral("蓝色箭头:AGV 当前位姿 · 虚线:运动轨迹"), + ui.mappingPreviewPanel); + mapLegend->setObjectName(QStringLiteral("panelSubtitle")); + QPushButton *zoomOutButton = new QPushButton(QStringLiteral("−"), + ui.mappingPreviewPanel); + QPushButton *zoomInButton = new QPushButton(QStringLiteral("+"), + ui.mappingPreviewPanel); + QPushButton *resetViewButton = new QPushButton(QStringLiteral("适应窗口"), + ui.mappingPreviewPanel); + QPushButton *clearTrackButton = new QPushButton(QStringLiteral("清除轨迹"), + ui.mappingPreviewPanel); + for (QPushButton *button : {zoomOutButton, zoomInButton, + resetViewButton, clearTrackButton}) { + button->setObjectName(QStringLiteral("agvMapToolButton")); + button->setMinimumHeight(30); + } + zoomOutButton->setMaximumWidth(42); + zoomInButton->setMaximumWidth(42); + mapToolbar->addWidget(mapLegend); + mapToolbar->addStretch(); + mapToolbar->addWidget(zoomOutButton); + mapToolbar->addWidget(zoomInButton); + mapToolbar->addWidget(resetViewButton); + mapToolbar->addWidget(clearTrackButton); + ui.mappingPreviewLayout->insertLayout(1, mapToolbar); + + m_agvMapView = new AgvMapViewWidget(ui.mappingPreviewPanel); + m_agvMapView->setObjectName(QStringLiteral("agvLiveMap")); + m_agvMapView->setStreamMessage(QStringLiteral("连接设备后自动加载实时地图")); + ui.mappingPreviewLayout->insertWidget(2, m_agvMapView, 1); + leftLayout->addWidget(ui.mappingPreviewPanel, 1); + + QFrame *mapActionsPanel = new QFrame(leftColumn); + mapActionsPanel->setObjectName(QStringLiteral("panel")); + QVBoxLayout *mapActionsLayout = new QVBoxLayout(mapActionsPanel); + mapActionsLayout->setContentsMargins(18, 14, 18, 14); + mapActionsLayout->setSpacing(9); + QLabel *mapActionsTitle = new QLabel(QStringLiteral("地图与建图"), + mapActionsPanel); + mapActionsTitle->setObjectName(QStringLiteral("sectionTitle")); + QLabel *mapActionsSubtitle = new QLabel( + QStringLiteral("加载已有地图、重新定位,或创建新的建图会话"), + mapActionsPanel); + mapActionsSubtitle->setObjectName(QStringLiteral("panelSubtitle")); + mapActionsLayout->addWidget(mapActionsTitle); + mapActionsLayout->addWidget(mapActionsSubtitle); + + QHBoxLayout *mapSelectionRow = new QHBoxLayout; + ui.agvMapCombo->setParent(mapActionsPanel); + ui.inventoryButton->setParent(mapActionsPanel); + ui.switchMapButton->setParent(mapActionsPanel); + ui.inventoryButton->setText(QStringLiteral("刷新列表")); + ui.switchMapButton->setText(QStringLiteral("加载地图")); + mapSelectionRow->addWidget(ui.agvMapCombo, 1); + mapSelectionRow->addWidget(ui.inventoryButton); + mapSelectionRow->addWidget(ui.switchMapButton); + mapActionsLayout->addLayout(mapSelectionRow); + + QPushButton *addMapButton = new QPushButton(QStringLiteral("新增地图"), + mapActionsPanel); + QPushButton *relocalizeButton = new QPushButton(QStringLiteral("重新定位"), + mapActionsPanel); + m_agvDeleteMapButton = new QPushButton(QStringLiteral("删除地图"), + mapActionsPanel); + m_agvDeleteMapButton->setObjectName(QStringLiteral("dangerOutlineButton")); + m_agvDeleteMapButton->setEnabled(false); + m_agvDeleteMapButton->setToolTip( + QStringLiteral("当前边缘系统未提供删除地图接口")); + QHBoxLayout *mapOperationRow = new QHBoxLayout; + mapOperationRow->addWidget(addMapButton); + mapOperationRow->addWidget(relocalizeButton); + mapOperationRow->addWidget(m_agvDeleteMapButton); + mapActionsLayout->addLayout(mapOperationRow); + + QGridLayout *mappingForm = new QGridLayout; + QLabel *mappingNameLabel = new QLabel(QStringLiteral("新地图"), + mapActionsPanel); + QLabel *mappingDimensionLabel = new QLabel(QStringLiteral("类型"), + mapActionsPanel); + ui.mappingNameEdit->setParent(mapActionsPanel); + ui.mappingDimensionCombo->setParent(mapActionsPanel); + ui.mappingRealtimeCheck->setParent(mapActionsPanel); + mappingForm->addWidget(mappingNameLabel, 0, 0); + mappingForm->addWidget(ui.mappingNameEdit, 0, 1); + mappingForm->addWidget(mappingDimensionLabel, 0, 2); + mappingForm->addWidget(ui.mappingDimensionCombo, 0, 3); + mappingForm->addWidget(ui.mappingRealtimeCheck, 1, 1, 1, 3); + mappingForm->setColumnStretch(1, 1); + mappingForm->setColumnStretch(3, 1); + mapActionsLayout->addLayout(mappingForm); + + ui.startMappingButton->setParent(mapActionsPanel); + ui.stopMappingButton->setParent(mapActionsPanel); + QHBoxLayout *mappingButtonRow = new QHBoxLayout; + mappingButtonRow->addWidget(ui.startMappingButton); + mappingButtonRow->addWidget(ui.stopMappingButton); + mapActionsLayout->addLayout(mappingButtonRow); + + ui.uploadMapButton->setParent(mapActionsPanel); + ui.downloadMapButton->setParent(mapActionsPanel); + QHBoxLayout *transferRow = new QHBoxLayout; + transferRow->addWidget(ui.uploadMapButton); + transferRow->addWidget(ui.downloadMapButton); + mapActionsLayout->addLayout(transferRow); + leftLayout->addWidget(mapActionsPanel); + + statusUi.agvDialogSurface->setGraphicsEffect(nullptr); + statusUi.agvDialogSurface->setParent(rightColumn); + statusUi.agvDialogSurface->setMinimumSize(0, 0); + statusUi.agvDialogTitleBar->hide(); + statusUi.agvDialogContentLayout->setContentsMargins(0, 0, 0, 0); + statusUi.navigationStatusPanel->setMaximumHeight(150); + rightLayout->addWidget(statusUi.agvDialogSurface, 3); + + ui.velocityPanel->setParent(rightColumn); + ui.velocityPanel->setMinimumSize(0, 0); + ui.velocityTitle->setText(QStringLiteral("手动速度控制")); + ui.velocitySubtitle->setText( + QStringLiteral("按住方向按钮或 Q/W/E/A/S/D 键运动,松开即停止")); + m_agvVxSpin->setMinimum(0.0); + m_agvVySpin->setMinimum(0.0); + m_agvWzSpin->setMinimum(0.0); + if (qFuzzyIsNull(m_agvVySpin->value())) + m_agvVySpin->setValue(0.2); + ui.rotateLeftButton->setText(QStringLiteral("左旋 (Q)")); + ui.forwardButton->setText(QStringLiteral("前进 (W)")); + ui.rotateRightButton->setText(QStringLiteral("右旋 (E)")); + ui.leftButton->setText(QStringLiteral("左移 (A)")); + ui.rightButton->setText(QStringLiteral("右移 (D)")); + ui.backwardButton->setText(QStringLiteral("后退 (S)")); + ui.velocityButton->hide(); + rightLayout->addWidget(ui.velocityPanel, 4); + + const auto removeOriginalTab = [tabs = ui.agvTabs](QWidget *tab) { + const int index = tabs->indexOf(tab); + if (index >= 0) + tabs->removeTab(index); + }; + removeOriginalTab(ui.manualTab); + removeOriginalTab(ui.mapTab); + removeOriginalTab(ui.mappingTab); + ui.agvTabs->insertTab(0, m_agvControlWorkspace, + QStringLiteral("控制与建图")); + ui.agvTabs->setCurrentWidget(m_agvControlWorkspace); + + connect(zoomOutButton, &QPushButton::clicked, + m_agvMapView, &AgvMapViewWidget::zoomOut); + connect(zoomInButton, &QPushButton::clicked, + m_agvMapView, &AgvMapViewWidget::zoomIn); + connect(resetViewButton, &QPushButton::clicked, + m_agvMapView, &AgvMapViewWidget::resetView); + connect(clearTrackButton, &QPushButton::clicked, + m_agvMapView, &AgvMapViewWidget::clearTrajectory); + connect(addMapButton, &QPushButton::clicked, this, + [this, nameEdit = ui.mappingNameEdit]() { + bool accepted = false; + const QString name = QInputDialog::getText( + this, QStringLiteral("新增地图"), QStringLiteral("地图名称"), + QLineEdit::Normal, nameEdit->text(), &accepted).trimmed(); + if (!accepted || name.isEmpty()) + return; + nameEdit->setText(name); + nameEdit->setFocus(); + }); + connect(relocalizeButton, &QPushButton::clicked, this, [this]() { + QDialog dialog(this); + dialog.setWindowTitle(QStringLiteral("AGV 重新定位")); + QFormLayout *form = new QFormLayout(&dialog); + QDoubleSpinBox *xSpin = new QDoubleSpinBox(&dialog); + QDoubleSpinBox *ySpin = new QDoubleSpinBox(&dialog); + QDoubleSpinBox *thetaSpin = new QDoubleSpinBox(&dialog); + for (QDoubleSpinBox *spin : {xSpin, ySpin}) { + spin->setRange(-10000.0, 10000.0); + spin->setDecimals(3); + spin->setSuffix(QStringLiteral(" m")); + } + thetaSpin->setRange(-6.283, 6.283); + thetaSpin->setDecimals(3); + thetaSpin->setSuffix(QStringLiteral(" rad")); + xSpin->setValue(m_latestAgvState.value(QStringLiteral("x")).toDouble()); + ySpin->setValue(m_latestAgvState.value(QStringLiteral("y")).toDouble()); + thetaSpin->setValue( + m_latestAgvState.value(QStringLiteral("theta")).toDouble()); + form->addRow(QStringLiteral("X"), xSpin); + form->addRow(QStringLiteral("Y"), ySpin); + form->addRow(QStringLiteral("航向"), thetaSpin); + QDialogButtonBox *buttons = new QDialogButtonBox( + QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); + connect(buttons, &QDialogButtonBox::accepted, + &dialog, &QDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, + &dialog, &QDialog::reject); + form->addRow(buttons); + if (dialog.exec() == QDialog::Accepted) { + m_client->requestAgvRelocalize( + m_agvIdEdit->text().trimmed(), xSpin->value(), + ySpin->value(), thetaSpin->value()); + } + }); + connect(ui.refreshButton, &QPushButton::clicked, this, [this]() { m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); }); - connect(statusUi.refreshDialogButton, &QPushButton::clicked, this, [this]() { - m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); - }); connect(m_agvStatusRefreshTimer, &QTimer::timeout, this, [this]() { - if (m_connected && m_agvStatusSwitch && m_agvStatusSwitch->isChecked()) + if (m_connected && m_pages && m_pages->currentIndex() == 3) m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); }); - connect(m_agvStatusSwitch, &QCheckBox::toggled, this, [this](bool checked) { - if (!m_agvStatusDialog) - return; - if (!checked) { - m_agvStatusRefreshTimer->stop(); - m_agvStatusDialog->hide(); - return; - } - const QRect owner = frameGeometry(); - const int x = qMax(owner.left() + 24, - owner.right() - m_agvStatusDialog->width() - 24); - m_agvStatusDialog->move(x, owner.top() + 88); - m_agvStatusDialog->show(); - m_agvStatusDialog->raise(); - m_agvStatusDialog->activateWindow(); - if (m_connected) { - m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); - m_agvStatusRefreshTimer->start(); - } - }); - connect(m_agvStatusDialog, &QDialog::finished, this, [this](int) { - if (m_agvStatusSwitch) - m_agvStatusSwitch->setChecked(false); - }); connect(ui.navigatePoseButton, &QPushButton::clicked, this, [this]() { m_client->requestAgvNavigatePose(m_agvIdEdit->text().trimmed(), m_agvXSpin->value(), m_agvYSpin->value(), m_agvThetaSpin->value(), @@ -1190,36 +1390,34 @@ QWidget *MainWindow::createAgvPage() connect(ui.cancelButton, &QPushButton::clicked, this, [this]() { m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("Cancel")); }); - connect(ui.velocityButton, &QPushButton::clicked, this, [this]() { - m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), m_agvVxSpin->value(), - m_agvVySpin->value(), m_agvWzSpin->value()); + connect(ui.forwardButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(qAbs(m_agvVxSpin->value()), 0.0, 0.0); }); - const auto sendManualVelocity = [this](double vx, double vy, double wz) { - m_client->requestAgvVelocity(m_agvIdEdit->text().trimmed(), vx, vy, wz); - }; - connect(ui.forwardButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(qAbs(m_agvVxSpin->value()), 0.0, 0.0); + connect(ui.backwardButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(-qAbs(m_agvVxSpin->value()), 0.0, 0.0); }); - connect(ui.backwardButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(-qAbs(m_agvVxSpin->value()), 0.0, 0.0); + connect(ui.leftButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(0.0, qAbs(m_agvVySpin->value()), 0.0); }); - connect(ui.leftButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(0.0, qAbs(m_agvVySpin->value()), 0.0); + connect(ui.rightButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(0.0, -qAbs(m_agvVySpin->value()), 0.0); }); - connect(ui.rightButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(0.0, -qAbs(m_agvVySpin->value()), 0.0); + connect(ui.rotateLeftButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(0.0, 0.0, qAbs(m_agvWzSpin->value())); }); - connect(ui.rotateLeftButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(0.0, 0.0, qAbs(m_agvWzSpin->value())); - }); - connect(ui.rotateRightButton, &QPushButton::clicked, this, [this, sendManualVelocity]() { - sendManualVelocity(0.0, 0.0, -qAbs(m_agvWzSpin->value())); - }); - connect(ui.manualStopButton, &QPushButton::clicked, this, [this]() { - m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), - QStringLiteral("StopVelocity")); + connect(ui.rotateRightButton, &QPushButton::pressed, this, [this]() { + startAgvManualMotion(0.0, 0.0, -qAbs(m_agvWzSpin->value())); }); + for (QPushButton *button : { + ui.forwardButton, ui.backwardButton, ui.leftButton, + ui.rightButton, ui.rotateLeftButton, ui.rotateRightButton}) { + connect(button, &QPushButton::released, this, + [this]() { stopAgvManualMotion(); }); + } + connect(ui.manualStopButton, &QPushButton::clicked, this, + [this]() { stopAgvManualMotion(); }); connect(ui.zeroVelocityButton, &QPushButton::clicked, this, [this]() { + stopAgvManualMotion(); m_agvVxSpin->setValue(0.0); m_agvVySpin->setValue(0.0); m_agvWzSpin->setValue(0.0); @@ -1376,7 +1574,7 @@ QWidget *MainWindow::createAgvPage() << ui.pauseButton << ui.resumeButton << ui.cancelButton << ui.velocityButton << statusUi.stopVelocityButton << statusUi.clearFaultButton - << ui.emergencyButton << ui.inventoryButton << ui.switchMapButton + << ui.emergencyButton << ui.inventoryButton << ui.switchMapButton << relocalizeButton << ui.forwardButton << ui.backwardButton << ui.leftButton << ui.rightButton << ui.rotateLeftButton << ui.rotateRightButton << ui.manualStopButton << ui.followPathButton << ui.startMappingButton << ui.stopMappingButton diff --git a/src/robotclient.cpp b/src/robotclient.cpp index fa9e78c..e31b306 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -1337,6 +1337,7 @@ public: 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); @@ -1380,6 +1381,7 @@ public: 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()); @@ -1401,6 +1403,36 @@ public: #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")) || @@ -1687,7 +1719,20 @@ public: << QPointF(260, 302); painter.drawPolygon(robot); painter.end(); - emit agvMapFrameReceived(image, QStringLiteral("演示 2D 地图 · 6 个站点")); + 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; } @@ -1715,6 +1760,7 @@ public: continue; const auto &update = response.update(); QImage image; + QVariantMap metadata; QString detail; if (update.has_map_2d()) { const auto &map = update.map_2d(); @@ -1773,6 +1819,21 @@ public: } } 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) @@ -1803,13 +1864,19 @@ public: } 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, detail); + emit agvMapFrameReceived(image, metadata, detail); } const grpc::Status status = reader->Finish(); { @@ -2021,7 +2088,8 @@ public: std::function cameraRecordingStateChanged; std::function agvStateReceived; std::function agvInventoryReceived; - std::function agvMapFrameReceived; + std::function + agvMapFrameReceived; std::function agvMapStreamStateChanged; std::function rpcFinished; std::function audioStreamStateChanged; @@ -3223,9 +3291,11 @@ RobotClient::RobotClient(QObject *parent) 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); + 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) { @@ -3334,6 +3404,8 @@ RobotClient::RobotClient(QObject *parent) 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); @@ -3470,6 +3542,11 @@ void RobotClient::stopCameraRecording(const QString &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) { diff --git a/src/robotclient.h b/src/robotclient.h index 90a7c77..f640b65 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -56,6 +56,8 @@ public slots: 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, @@ -116,6 +118,8 @@ signals: 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, @@ -165,7 +169,8 @@ signals: 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 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); diff --git a/ui/agvservicepage.ui b/ui/agvservicepage.ui index 2e655a2..31cb25f 100644 --- a/ui/agvservicepage.ui +++ b/ui/agvservicepage.ui @@ -23,8 +23,6 @@ 设备 IDeyebrow 220028016777215AGV 设备 ID 1080刷新状态primaryButton - 状态监测eyebrow - 44244424开启或关闭 AGV 实时状态监测agvStatusSwitch 1080AGV 急停dangerButton diff --git a/ui/agvstatusdialog.ui b/ui/agvstatusdialog.ui index f54c54b..2d4979e 100644 --- a/ui/agvstatusdialog.ui +++ b/ui/agvstatusdialog.ui @@ -47,16 +47,6 @@ 14 16 16 - - - 10 - AGV 实时状态pageTitle - 控制器、定位、运动、安全与能源状态panelSubtitle - Qt::Horizontal4020 - ● 实时监测agvLiveIndicator - 刷新880 - - panel From 141d1b98d959d9e8caac16cfd51a134a15c25cfb Mon Sep 17 00:00:00 2001 From: Gao Date: Thu, 8 Oct 2026 16:29:02 +0800 Subject: [PATCH 04/15] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E8=87=B3=20src?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/tcpcalibrationwidget.cpp | 599 +++++++++++++++++++++++++++++++++++ src/touchoperationwidget.cpp | 446 ++++++++++++++++++++++++++ src/videorenderwidget.cpp | 550 +++++++++++++++++--------------- src/videorenderwidget.h | 96 +++--- 4 files changed, 1392 insertions(+), 299 deletions(-) create mode 100644 src/tcpcalibrationwidget.cpp create mode 100644 src/touchoperationwidget.cpp diff --git a/src/tcpcalibrationwidget.cpp b/src/tcpcalibrationwidget.cpp new file mode 100644 index 0000000..86b405d --- /dev/null +++ b/src/tcpcalibrationwidget.cpp @@ -0,0 +1,599 @@ +#include "tcpcalibrationwidget.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +QVBoxLayout *panel(QBoxLayout *parent, const QString &title) +{ + auto *frame = new QFrame; + frame->setObjectName(QStringLiteral("panel")); + auto *layout = new QVBoxLayout(frame); + layout->setContentsMargins(14, 12, 14, 12); + layout->setSpacing(8); + auto *label = new QLabel(title); + label->setObjectName(QStringLiteral("sectionTitle")); + layout->addWidget(label); + parent->addWidget(frame); + return layout; +} +QLabel *hint(const QString &text) +{ + auto *label = new QLabel(text); + label->setObjectName(QStringLiteral("mutedLabel")); + label->setWordWrap(true); + return label; +} +const char *keys[] = {"x", "y", "z", "rx", "ry", "rz"}; +QString axis(int i) { return QString::fromLatin1(keys[i]).toUpper(); } +double fromDisplay(double value, int axisIndex) +{ + return axisIndex < 3 ? value / 1000.0 : qDegreesToRadians(value); +} +double toDisplay(double value, int axisIndex) +{ + return axisIndex < 3 ? value * 1000.0 : qRadiansToDegrees(value); +} +} + +TcpCalibrationWidget::TcpCalibrationWidget(QWidget *parent) : QWidget(parent) +{ + setObjectName(QStringLiteral("tcpCalibrationPage")); + buildUi(); + m_captureTimer = new QTimer(this); + m_captureTimer->setSingleShot(true); + m_captureTimer->setInterval(6000); + connect(m_captureTimer, &QTimer::timeout, this, [this] { + if (m_pendingRow < 0) return; + ++m_serial; + m_pendingRow = -1; + refresh(); + reportError(QStringLiteral("读取实时位姿超时,请检查机械臂连接后重试")); + }); + resizeSamples(4); +} + +void TcpCalibrationWidget::buildUi() +{ + auto *outer = new QVBoxLayout(this); + outer->setContentsMargins(12, 10, 12, 10); + auto *scroll = new QScrollArea(this); + scroll->setWidgetResizable(true); + scroll->setFrameShape(QFrame::NoFrame); + auto *content = new QWidget; + auto *layout = new QVBoxLayout(content); + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(10); + scroll->setWidget(content); + outer->addWidget(scroll); + + auto *configuration = new QHBoxLayout; + configuration->setSpacing(10); + layout->addLayout(configuration); + auto *toolPanel = panel(configuration, QStringLiteral("工具信息")); + auto *toolGrid = new QGridLayout; + toolGrid->setHorizontalSpacing(12); + m_toolCombo = new QComboBox; + m_toolCombo->setObjectName(QStringLiteral("tcpLocalTools")); + m_toolCombo->addItem(QStringLiteral("新建工具")); + m_name = new QLineEdit; + m_name->setObjectName(QStringLiteral("tcpToolName")); + m_name->setMaxLength(80); + m_name->setPlaceholderText(QStringLiteral("输入工具名称")); + m_name->setToolTip(QStringLiteral("保存至当前机械臂,并同步至工具坐标列表。")); + m_reload = new QPushButton(QStringLiteral("刷新")); + m_delete = new QPushButton(QStringLiteral("删除")); + m_delete->setObjectName(QStringLiteral("tcpDelete")); + toolGrid->addWidget(new QLabel(QStringLiteral("工具")), 0, 0); + toolGrid->addWidget(m_toolCombo, 0, 1); + toolGrid->addWidget(new QLabel(QStringLiteral("名称")), 1, 0); + toolGrid->addWidget(m_name, 1, 1, 1, 3); + toolGrid->addWidget(m_reload, 0, 2); + toolGrid->addWidget(m_delete, 0, 3); + toolGrid->setColumnStretch(1, 1); + toolPanel->addLayout(toolGrid); + m_currentTool = hint(QStringLiteral("正在标定:新工具")); + toolPanel->addWidget(m_currentTool); + toolPanel->addStretch(); + auto *sourcePanel = panel(configuration, QStringLiteral("控制器 TCP 偏移")); + sourcePanel->parentWidget()->setToolTip(QStringLiteral("与示教器当前活动 TCP 一致,用于还原法兰位姿。仅零偏移工具可填全零;采样期间不得切换。")); + configuration->setStretch(0,1); configuration->setStretch(1,1); + auto *sourceGrid = new QGridLayout; + for (int i = 0; i < 6; ++i) { + auto *spin = new QDoubleSpinBox; + spin->setObjectName(QStringLiteral("tcpSource%1").arg(i)); + spin->setRange(i < 3 ? -10000 : -360, i < 3 ? 10000 : 360); + spin->setDecimals(4); + spin->setSuffix(i < 3 ? QStringLiteral(" mm") : QStringLiteral(" °")); + m_source.append(spin); + sourceGrid->addWidget(new QLabel(axis(i)), i/3, (i%3)*2); + sourceGrid->addWidget(spin, i/3, (i%3)*2+1); + sourceGrid->setColumnStretch((i%3)*2+1,1); + connect(spin, QOverload::of(&QDoubleSpinBox::valueChanged), this, + [this](double) { updateSource(); }); + } + sourcePanel->addLayout(sourceGrid); + m_sourceConfirmed = new QCheckBox(QStringLiteral( + "已确认控制器 TCP 偏移")); + m_sourceConfirmed->setToolTip(QStringLiteral("RX/RY/RZ 为 ZYX 欧拉角,非旋转向量。偏移必须与控制器当前活动工具一致。")); + m_sourceConfirmed->setObjectName(QStringLiteral("tcpSourceConfirmed")); + sourcePanel->addWidget(m_sourceConfirmed); + connect(m_sourceConfirmed, &QCheckBox::toggled, this, [this](bool) { + resetCalibration(); + refresh(); + emit referenceChanged(); + }); + + auto *pointsPanel = panel(layout, QStringLiteral("TCP 采样")); + m_instructions = hint(QString()); + pointsPanel->addWidget(m_instructions); + auto *pointActions = new QHBoxLayout; + m_method = new QComboBox; + m_method->setObjectName(QStringLiteral("tcpCalibrationMethod")); + m_method->addItem(QStringLiteral("四点法"),QStringLiteral("four_point")); + m_method->addItem(QStringLiteral("六点法 · XZ"),QStringLiteral("six_point_xz")); + m_method->addItem(QStringLiteral("六点法 · XY"),QStringLiteral("six_point_xy")); + pointActions->addWidget(new QLabel(QStringLiteral("标定方式"))); + pointActions->addWidget(m_method); + pointActions->addStretch(); + auto *restart = new QPushButton(QStringLiteral("重新标定")); + restart->setObjectName(QStringLiteral("tcpClear")); + pointActions->addWidget(restart); + pointsPanel->addLayout(pointActions); + m_table = new QTableWidget(0, 10); + m_table->setObjectName(QStringLiteral("tcpSamples")); + m_table->setHorizontalHeaderLabels({QStringLiteral("点位"), QStringLiteral("状态"), + QStringLiteral("X mm"), QStringLiteral("Y mm"), QStringLiteral("Z mm"), + QStringLiteral("RX °"), QStringLiteral("RY °"), QStringLiteral("RZ °"), + QStringLiteral("残差 mm"), QStringLiteral("操作")}); + m_table->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_table->setSelectionMode(QAbstractItemView::NoSelection); + m_table->setAlternatingRowColors(true); + m_table->verticalHeader()->hide(); + m_table->verticalHeader()->setDefaultSectionSize(36); + m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + m_table->setMinimumHeight(180); + pointsPanel->addWidget(m_table); + connect(m_method, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { + resizeSamples(m_method->currentIndex()==0 ? 4 : 6); + for (auto *spin : m_orientation) spin->setValue(0); + }); + connect(restart, &QPushButton::clicked, this, &TcpCalibrationWidget::resetCalibration); + + auto *resultPanel = panel(layout, QStringLiteral("TCP 参数(相对法兰)")); + auto *resultGrid = new QGridLayout; + for (int i = 0; i < 6; ++i) { + auto *axisLabel = new QLabel(axis(i) + (i < 3 ? QStringLiteral(" mm") : QStringLiteral(" °(手动)"))); + resultGrid->addWidget(axisLabel, 0, i); + if (i>=3) m_orientationLabels.append(axisLabel); + if (i < 3) { + auto *value = new QLabel(QStringLiteral("--")); + value->setObjectName(QStringLiteral("tcpResult%1").arg(i)); + value->setTextInteractionFlags(Qt::TextSelectableByMouse); + m_results.append(value); + resultGrid->addWidget(value, 1, i); + } else { + auto *spin = new QDoubleSpinBox; + spin->setObjectName(QStringLiteral("tcpOrientation%1").arg(i)); + spin->setRange(-360, 360); + spin->setDecimals(4); + spin->setSuffix(QStringLiteral(" °")); + m_orientation.append(spin); + resultGrid->addWidget(spin, 1, i); + connect(spin, QOverload::of(&QDoubleSpinBox::valueChanged), this, + [this](double) { refresh(); }); + } + } + resultPanel->addLayout(resultGrid); + for (auto *spin : m_orientation) spin->setToolTip(QStringLiteral("固定点法仅求解平移;工具姿态需手动设置,采用 ZYX 欧拉角。")); + m_rms = new QLabel(QStringLiteral("固定点 RMS:--(合格上限 2.000 mm)")); + m_rms->setObjectName(QStringLiteral("tcpRms")); + resultPanel->addWidget(m_rms); + m_preview = hint(QStringLiteral("基座下工具位姿:--")); + m_preview->setObjectName(QStringLiteral("tcpToolPreview")); + resultPanel->addWidget(m_preview); + auto *actions = new QHBoxLayout; + m_status = hint(QStringLiteral("等待采样")); + m_status->setObjectName(QStringLiteral("tcpStatus")); + actions->addWidget(m_status, 1); + m_calculate = new QPushButton(QStringLiteral("TCP 标定")); + m_calculate->setObjectName(QStringLiteral("primaryButton")); + m_calculate->setProperty("tcpAction", QStringLiteral("calculate")); + m_save = new QPushButton(QStringLiteral("保存工具")); + m_save->setObjectName(QStringLiteral("tcpSave")); + actions->addWidget(m_calculate); + actions->addWidget(m_save); + outer->addLayout(actions); + layout->addStretch(); + connect(m_calculate, &QPushButton::clicked, this, &TcpCalibrationWidget::calculate); + connect(m_save, &QPushButton::clicked, this, &TcpCalibrationWidget::saveTool); + connect(m_name, &QLineEdit::textChanged, this, [this](const QString &) { refresh(); }); + connect(m_toolCombo, QOverload::of(&QComboBox::currentIndexChanged), this, &TcpCalibrationWidget::selectTool); + connect(m_reload, &QPushButton::clicked, this, [this] { reloadTools(); }); + connect(m_delete, &QPushButton::clicked, this, &TcpCalibrationWidget::deleteTool); +} + +void TcpCalibrationWidget::setContext(const QString &endpoint, const QString &deviceId, + bool connected, bool demoMode) +{ + const bool identityChanged = endpoint != m_endpoint || deviceId != m_device; + const bool sessionChanged = connected != m_connected || demoMode != m_demo; + m_endpoint = endpoint; + m_device = deviceId; + m_connected = connected; + m_demo = demoMode; + if (identityChanged || sessionChanged) { + const QSignalBlocker blocker(m_sourceConfirmed); + m_sourceConfirmed->setChecked(false); + resetCalibration(); + if (identityChanged) { + m_loading = true; + for (auto *spin : m_source) spin->setValue(0); + m_loading = false; + } + reloadTools(); + } + refresh(); + emit referenceChanged(); +} + +bool TcpCalibrationWidget::referenceConfirmed() const +{ + return m_connected && !m_demo && !m_device.trimmed().isEmpty() && m_sourceConfirmed->isChecked(); +} + +void TcpCalibrationWidget::invalidateReference() +{ + const QSignalBlocker blocker(m_sourceConfirmed); + m_sourceConfirmed->setChecked(false); + resetCalibration(); + emit referenceChanged(); +} + +bool TcpCalibrationWidget::hasSamples() const +{ + for (const auto &sample : m_samples) if (sample.captured) return true; + return false; +} +void TcpCalibrationWidget::invalidateResult() +{ + m_resultValid = false; + m_loadedResult = false; + m_result = TcpCalibration::Result{}; + for (auto *label : m_results) label->setText(QStringLiteral("--")); + m_rms->setText(QStringLiteral("固定点 RMS:--(合格上限 2.000 mm)")); + m_preview->setText(QStringLiteral("基座下工具位姿:--")); +} +void TcpCalibrationWidget::resetCalibration() +{ + ++m_serial; + m_pendingRow = -1; + if (m_captureTimer) m_captureTimer->stop(); + for (auto &sample : m_samples) sample = Sample{}; + invalidateResult(); + refresh(); + emit logMessage(QStringLiteral("INFO"), QStringLiteral("TCP 标定临时采样已重置,已保存工具保持不变")); +} +void TcpCalibrationWidget::resizeSamples(int count) +{ + ++m_serial; + m_pendingRow = -1; + if (m_captureTimer) m_captureTimer->stop(); + m_samples.assign(size_t(count),Sample{}); + invalidateResult(); + m_table->setRowCount(count); + m_table->setMinimumHeight(count*36+40); + for (int row = 0; row < count; ++row) { + for (int col = 0; col < 9; ++col) + if (!m_table->item(row, col)) m_table->setItem(row, col, new QTableWidgetItem); + if (!m_table->cellWidget(row, 9)) { + auto *button = new QPushButton(QStringLiteral("采集")); + button->setObjectName(QStringLiteral("tcpCapture%1").arg(row)); + m_table->setCellWidget(row, 9, button); + connect(button, &QPushButton::clicked, this, [this, row] { capture(row); }); + } + } + refresh(); +} +TcpCalibration::Pose TcpCalibrationWidget::serverOffset() const +{ + TcpCalibration::Pose pose{}; + for (int i = 0; i < 6; ++i) pose[size_t(i)] = fromDisplay(m_source.at(i)->value(), i); + return pose; +} +void TcpCalibrationWidget::updateSource() +{ + if (m_loading) return; + const QSignalBlocker blocker(m_sourceConfirmed); + m_sourceConfirmed->setChecked(false); + resetCalibration(); + emit referenceChanged(); +} +void TcpCalibrationWidget::refresh() +{ + if (!m_table) return; + int captured = 0; + const bool busy = m_pendingRow >= 0; + const bool six = m_method->currentIndex()>0; + const bool xz = m_method->currentData().toString()=="six_point_xz"; + m_instructions->setText(six + ? QStringLiteral("1–3:固定尖端位置并改变姿态;4:方向原点;5:+X;6:+%1。后三点保持相同姿态。").arg(xz?"Z":"Y") + : QStringLiteral("保持尖端位置不变,以四个不同姿态采样;工具方向手动设置。")); + m_instructions->setToolTip(six ? QStringLiteral("方向点从原点沿所需工具正轴平移,返回原点姿态后采下一轴。程序不会自动移动机器人。最小方向基线 10 mm;建议在安全行程内增加基线。") : QString()); + const bool ready = m_connected && !m_demo && !m_device.trimmed().isEmpty() + && m_sourceConfirmed->isChecked() && !busy; + for (int row = 0; row < int(m_samples.size()); ++row) { + const auto &sample = m_samples[size_t(row)]; + captured += sample.captured; + const QString purpose=!six ? QStringLiteral("固定点") : row<3 ? QStringLiteral("接近点") + : row==3 ? QStringLiteral("方向原点") : row==4 ? QStringLiteral("+X") : xz?QStringLiteral("+Z"):QStringLiteral("+Y"); + m_table->item(row, 0)->setText(QStringLiteral("%1 · %2").arg(row+1).arg(purpose)); + m_table->item(row, 1)->setText(row == m_pendingRow ? QStringLiteral("读取中") + : sample.captured ? QStringLiteral("已采集") : QStringLiteral("未采集")); + for (int i = 0; i < 6; ++i) m_table->item(row, 2 + i)->setText(sample.captured + ? QString::number(toDisplay(sample.flange[size_t(i)], i), 'f', 3) : QStringLiteral("--")); + m_table->item(row, 8)->setText(m_resultValid && !m_loadedResult + && row < int(m_result.residualsMm.size()) + ? QString::number(m_result.residualsMm[size_t(row)], 'f', 3) : QStringLiteral("--")); + auto *button = qobject_cast(m_table->cellWidget(row, 9)); + button->setText(sample.captured ? QStringLiteral("重新采集") : QStringLiteral("采集")); + button->setEnabled(ready); + } + m_method->setEnabled(!busy); + for (int i=0;isetReadOnly(six); m_orientation[i]->setButtonSymbols(six?QAbstractSpinBox::NoButtons:QAbstractSpinBox::UpDownArrows); + m_orientationLabels[i]->setText(axis(i+3)+(six?QStringLiteral(" °(计算)"):QStringLiteral(" °(手动)"))); + m_orientation[i]->setToolTip(six?QStringLiteral("由方向原点、+X 与第二方向点计算,ZYX 欧拉角。"):QStringLiteral("四点法仅求平移;工具方向手动设置,ZYX 欧拉角。")); + } + m_toolCombo->setEnabled(!busy); + m_name->setEnabled(!busy); + m_reload->setEnabled(!busy && !m_device.isEmpty()); + m_delete->setEnabled(!busy && m_toolCombo->currentIndex() > 0); + for (auto *spin : m_source) spin->setEnabled(!busy); + m_sourceConfirmed->setEnabled(!busy && m_connected && !m_demo); + m_calculate->setEnabled(!busy && captured >= 4 && captured == int(m_samples.size())); + m_save->setEnabled(!busy && m_resultValid && m_result.rmsMm <= 2.0 + && !m_name->text().trimmed().isEmpty()); + m_status->setText(busy ? QStringLiteral("正在读取真实位姿…") : m_resultValid + ? (m_result.rmsMm > 2.0 ? QStringLiteral("误差超限,禁止保存,请重新采样") + : m_loadedResult ? (six ? QStringLiteral("已加载六点标定结果") : QStringLiteral("已加载标定结果,可修改名称或手动方向")) + : QStringLiteral("已计算,尚未保存")) + : QStringLiteral("已采集 %1 / %2 点%3").arg(captured).arg(m_samples.size()) + .arg(!m_sourceConfirmed->isChecked() ? QStringLiteral(" · 请先核对活动 TCP 偏移") : QString())); +} + +void TcpCalibrationWidget::capture(int index) +{ + if (index < 0 || index >= int(m_samples.size()) || m_pendingRow >= 0) return; + if (!m_connected || m_demo || !m_sourceConfirmed->isChecked() || m_device.isEmpty()) { + reportError(QStringLiteral("请连接真实机械臂并核对服务端活动 TCP 偏移")); + return; + } + invalidateResult(); + // A failed replacement must not silently reuse the previous observation. + m_samples[size_t(index)] = Sample{}; + m_pendingRow = index; + ++m_serial; + m_captureTimer->start(); + refresh(); + emit captureRequested(m_device, m_serial); +} +bool TcpCalibrationWidget::readPose(const QVariantMap &map, TcpCalibration::Pose &pose) const +{ + for (int i = 0; i < 6; ++i) { + const QString name = QString::fromLatin1(keys[i]); + bool ok = false; + pose[size_t(i)] = map.value(name).toDouble(&ok); + if (!map.contains(name) || !ok || !std::isfinite(pose[size_t(i)])) return false; + } + return TcpCalibration::validPose(pose); +} +void TcpCalibrationWidget::acceptPose(quint64 requestId, const QString &deviceId, + const QVariantMap &pose, const QVariantMap &state, + bool success, const QString &detail) +{ + if (requestId != m_serial || deviceId != m_device || m_pendingRow < 0) return; + const int row = m_pendingRow; + m_pendingRow = -1; + m_captureTimer->stop(); + if (!success) { refresh(); reportError(detail); return; } + if (!m_connected || m_demo || !m_sourceConfirmed->isChecked() + || !state.value(QStringLiteral("connected")).toBool() + || state.value(QStringLiteral("moving"), true).toBool() + || state.value(QStringLiteral("fault"), true).toBool()) { + refresh(); reportError(QStringLiteral("机械臂状态不可用于采点,请停稳并重新核对")); return; + } + TcpCalibration::Pose tcp{}, flange{}; + QString error; + if (!readPose(pose, tcp) || !TcpCalibration::flangePose(tcp, serverOffset(), flange, &error)) { + refresh(); reportError(QStringLiteral("位姿数据无效:%1").arg(error)); return; + } + for (int i = 0; i < int(m_samples.size()); ++i) { + // Direction origin may legitimately repeat one of the position poses. + if (m_method->currentIndex()>0 && ((i<3)!=(row<3))) continue; + if (i != row && m_samples[size_t(i)].captured + && TcpCalibration::tooSimilar(m_samples[size_t(i)].flange, flange)) { + refresh(); reportError(QStringLiteral("与点位 %1 姿态过于接近,请改变腕部姿态后采集").arg(i + 1)); return; + } + } + m_samples[size_t(row)].flange = flange; + m_samples[size_t(row)].captured = true; + if (m_toolCombo->currentIndex() > 0 && m_toolCombo->currentIndex() <= m_tools.tools.size()) { + TcpCalibration::Pose preview{}; + if (TcpCalibration::toolPose(flange, m_tools.tools.at(m_toolCombo->currentIndex() - 1).offset, preview)) { + QStringList values; + for (int i = 0; i < 6; ++i) values << QString::number(toDisplay(preview[size_t(i)], i), 'f', 3); + m_preview->setText(QStringLiteral("基座下工具位姿(mm / °):%1").arg(values.join(QStringLiteral(", ")))); + } + } + refresh(); + emit logMessage(QStringLiteral("OK"), QStringLiteral("TCP 点位 %1 已采集 · %2 · 法兰位姿 m/rad,活动 TCP 偏移已换算") + .arg(row + 1).arg(m_device)); +} +void TcpCalibrationWidget::calculate() +{ + std::vector poses; + for (const auto &sample : m_samples) { + if (!sample.captured) { reportError(QStringLiteral("请先完成所有点位采集")); return; } + poses.push_back(sample.flange); + } + invalidateResult(); + QString error; + const bool solved=m_method->currentIndex()==0 ? TcpCalibration::solve(poses,m_result,&error) + : TcpCalibration::solveSixPoint(poses,m_method->currentData().toString()=="six_point_xz" + ? TcpCalibration::DirectionMethod::XZ : TcpCalibration::DirectionMethod::XY,m_result,&error); + if (!solved) { + refresh(); reportError(error); return; + } + m_resultValid = true; + showResult(m_result.offset, m_result.rmsMm, false); + refresh(); + emit logMessage(m_result.rmsMm <= 2.0 ? QStringLiteral("OK") : QStringLiteral("WARN"), + QStringLiteral("TCP 计算完成,%1 点,RMS %2 mm%3").arg(poses.size()) + .arg(m_result.rmsMm, 0, 'f', 3) + .arg(m_result.rmsMm > 2.0 ? QStringLiteral(",超过 2 mm,禁止保存") : QString())); +} +void TcpCalibrationWidget::showResult(const TcpCalibration::Pose &offset, double rmsMm, bool loaded) +{ + for (int i = 0; i < 3; ++i) m_results.at(i)->setText(QString::number(offset[size_t(i)] * 1000, 'f', 3)); + if (m_method->currentIndex()>0) + for (int i=0;i<3;++i) m_orientation[i]->setValue(qRadiansToDegrees(offset[size_t(i+3)])); + m_rms->setText(QStringLiteral("固定点 RMS:%1 mm · %2%3").arg(rmsMm, 0, 'f', 3) + .arg(rmsMm <= 2.0 ? QStringLiteral("合格(≤ 2.000 mm)") : QStringLiteral("超限,禁止保存")) + .arg(loaded ? QStringLiteral(" · 已保存结果") : QString())); +} +void TcpCalibrationWidget::reportError(const QString &message) +{ + emit logMessage(QStringLiteral("ERROR"), QStringLiteral("TCP 标定:%1").arg(message)); + QMessageBox::warning(this, QStringLiteral("工具坐标标定"), message); +} +void TcpCalibrationWidget::saveTool() +{ + if (!m_resultValid || !std::isfinite(m_result.rmsMm) || m_result.rmsMm > 2.0) { + reportError(QStringLiteral("请先得到 RMS 不超过 2 mm 的有效标定结果")); return; + } + TcpToolStore::Tool tool; + tool.name = m_name->text().trimmed(); + tool.offset = m_result.offset; + if (m_method->currentIndex()==0) + for (int i = 0; i < 3; ++i) tool.offset[size_t(i + 3)] = qDegreesToRadians(m_orientation.at(i)->value()); + tool.rmsMm = m_result.rmsMm; + tool.sampleCount = m_loadedResult ? m_loadedSampleCount : int(m_samples.size()); + tool.method = m_loadedResult ? m_loadedMethod : m_method->currentData().toString(); + bool replace = false; + for (const auto &saved : m_tools.tools) if (saved.name == tool.name) replace = true; + if (replace && QMessageBox::question(this, QStringLiteral("覆盖工具"), + QStringLiteral("当前机械臂的工具“%1”已存在,是否覆盖?").arg(tool.name), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return; + QSettings settings; + QString error; + // TODO(controller TCP): ArmService currently has only ListTCPFrame; + // there is no Get/Set/Create/Delete TCP-offset RPC to call or verify. + // Keep local records distinct until actual persistent controller APIs exist. + if (!TcpToolStore::save(settings, m_endpoint, m_device, tool, replace, error)) { + reportError(error); return; + } + reloadTools(tool.name); + emit toolsChanged(m_endpoint, m_device, tool.name); + emit logMessage(QStringLiteral("OK"), QStringLiteral("TCP 本机工具“%1”已保存 · %2 / %3") + .arg(tool.name, m_endpoint, m_device)); + QMessageBox::information(this, QStringLiteral("保存成功"), + QStringLiteral("已保存到当前机器人的工具配置,并同步到机械臂的工具坐标列表。选择该工具后可进行 TCP 点动。")); +} +void TcpCalibrationWidget::reloadTools(const QString &preferred) +{ + if (m_device.trimmed().isEmpty() || m_endpoint.trimmed().isEmpty()) { + m_tools = TcpToolStore::Snapshot{}; + const QSignalBlocker blocker(m_toolCombo); + m_toolCombo->clear(); + m_toolCombo->addItem(QStringLiteral("新建工具")); + selectTool(0); + m_currentTool->setText(QStringLiteral("请先选择机械臂")); + return; + } + QSettings settings; + QString error; + TcpToolStore::Snapshot snapshot; + if (!TcpToolStore::load(settings, m_endpoint, m_device, snapshot, error)) { + emit logMessage(QStringLiteral("ERROR"), error); + m_currentTool->setText(error); + m_tools = TcpToolStore::Snapshot{}; + const QSignalBlocker blocker(m_toolCombo); + m_toolCombo->clear(); m_toolCombo->addItem(QStringLiteral("配置读取失败")); + resetCalibration(); + return; + } + m_tools = snapshot; + const QString wanted = preferred.isEmpty() ? snapshot.current : preferred; + int selected = 0; + { + const QSignalBlocker blocker(m_toolCombo); + m_toolCombo->clear(); + m_toolCombo->addItem(QStringLiteral("新建工具")); + for (const auto &tool : snapshot.tools) { + m_toolCombo->addItem(tool.name); + if (tool.name == wanted) selected = m_toolCombo->count() - 1; + } + m_toolCombo->setCurrentIndex(selected); + } + selectTool(selected); +} +void TcpCalibrationWidget::selectTool(int index) +{ + resetCalibration(); + m_loading = true; + if (index <= 0 || index > m_tools.tools.size()) { + m_name->clear(); + for (auto *spin : m_orientation) spin->setValue(0); + m_currentTool->setText(QStringLiteral("新工具 · 未保存")); + } else { + const auto &tool = m_tools.tools.at(index - 1); + { const QSignalBlocker blocker(m_method); + m_method->setCurrentIndex(qMax(0,m_method->findData(tool.method))); } + resizeSamples(m_method->currentIndex()==0 ? 4 : 6); + m_name->setText(tool.name); + m_result.offset = tool.offset; + m_result.rmsMm = tool.rmsMm; + m_loadedSampleCount = tool.sampleCount; + m_loadedMethod = tool.method; + m_resultValid = true; + m_loadedResult = true; + for (int i = 0; i < 3; ++i) m_orientation.at(i)->setValue(qRadiansToDegrees(tool.offset[size_t(i + 3)])); + showResult(tool.offset, tool.rmsMm, true); + m_currentTool->setText(QStringLiteral("%1 · %2 点标定").arg(tool.name).arg(tool.sampleCount)); + emit logMessage(QStringLiteral("INFO"), QStringLiteral("已加载工具标定结果:%1").arg(tool.name)); + } + m_loading = false; + refresh(); +} +void TcpCalibrationWidget::deleteTool() +{ + const int index = m_toolCombo->currentIndex() - 1; + if (index < 0 || index >= m_tools.tools.size()) return; + const QString name = m_tools.tools.at(index).name; + if (QMessageBox::question(this, QStringLiteral("删除工具"), + QStringLiteral("删除当前机械臂的工具“%1”?对应的工具坐标选项也将移除。").arg(name), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return; + QSettings settings; + QString error; + if (!TcpToolStore::remove(settings, m_endpoint, m_device, name, error)) { reportError(error); return; } + reloadTools(); + emit toolsChanged(m_endpoint, m_device, QString()); + emit logMessage(QStringLiteral("INFO"), QStringLiteral("已删除本机 TCP 工具:%1").arg(name)); +} diff --git a/src/touchoperationwidget.cpp b/src/touchoperationwidget.cpp new file mode 100644 index 0000000..0c52750 --- /dev/null +++ b/src/touchoperationwidget.cpp @@ -0,0 +1,446 @@ +#include "touchoperationwidget.h" +#include "touchvideowidget.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using Pose=TcpCalibration::Pose; +constexpr quint64 kPosePrefix=quint64(1)<<58; +constexpr quint64 kImagePrefix=quint64(1)<<57; +QVariantList values(const Pose &pose) { QVariantList result; for(double v:pose) result<setObjectName("panel"); parent->addWidget(frame); + auto *layout=new QVBoxLayout(frame); layout->setContentsMargins(12,12,12,12); layout->setSpacing(8); + auto *label=new QLabel(title); label->setObjectName("sectionTitle"); layout->addWidget(label); return layout; +} +} + +TouchOperationWidget::TouchOperationWidget(QWidget *parent):QWidget(parent), + m_sequence(new TouchSequenceController(this)),m_video(new TouchVideoWidget(this)) +{ + setObjectName("touchOperationPage"); + m_video->setMaxPoints(2); + auto *outer=new QVBoxLayout(this); outer->setContentsMargins(12,10,12,10); outer->setSpacing(8); + auto *scroll=new QScrollArea; scroll->setWidgetResizable(true); scroll->setFrameShape(QFrame::NoFrame); + auto *content=new QWidget; scroll->setWidget(content); outer->addWidget(scroll); + auto *root=new QVBoxLayout(content); root->setContentsMargins(0,0,0,0); root->setSpacing(10); + auto *top=new QHBoxLayout; top->setSpacing(10); root->addLayout(top); + auto *vision=panel(top,QStringLiteral("视觉取点")); + m_video->setMinimumWidth(320); m_video->setMaximumWidth(640); m_video->setFrameAspectLayoutEnabled(true); + vision->setAlignment(Qt::AlignTop); + vision->addWidget(m_video,0,Qt::AlignTop|Qt::AlignHCenter); + auto *videoActions=new QHBoxLayout; + m_previewButton=new QPushButton(QStringLiteral("开始视频")); m_stopPreviewButton=new QPushButton(QStringLiteral("停止视频")); + m_lockButton=new QPushButton(QStringLiteral("锁定观察画面")); m_liveButton=new QPushButton(QStringLiteral("恢复实时")); + for(auto *b:{m_previewButton,m_stopPreviewButton,m_lockButton,m_liveButton}) videoActions->addWidget(b); + vision->addLayout(videoActions); + auto *hint=new QLabel(QStringLiteral("在锁定画面中选择 A / B 点;滑动按 A → B 执行。")); hint->setObjectName("mutedLabel"); vision->addWidget(hint); + auto *config=panel(top,QStringLiteral("任务配置")); top->setStretch(0,1); top->setStretch(1,1); + auto *grid=new QGridLayout; config->addLayout(grid); + m_handEyeChoice=new QComboBox; m_handEyeChoice->setObjectName("touchHandEye"); + m_toolChoice=new QComboBox; m_toolChoice->setObjectName("touchTcp"); + for(auto *c:{m_handEyeChoice,m_toolChoice}) { c->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed); c->setMinimumWidth(130); } + m_cameraName=new QLabel; m_cameraName->setWordWrap(true); + grid->setColumnStretch(1,1); + grid->addWidget(new QLabel(QStringLiteral("手眼标定")),0,0); grid->addWidget(m_handEyeChoice,0,1,1,2); + grid->addWidget(new QLabel(QStringLiteral("工具 TCP")),1,0); grid->addWidget(m_toolChoice,1,1,1,2); + grid->addWidget(new QLabel(QStringLiteral("相机")),2,0); grid->addWidget(m_cameraName,2,1); + m_reloadButton=new QPushButton(QStringLiteral("刷新标定")); grid->addWidget(m_reloadButton,2,2); + m_cameraConfirmed=new QCheckBox(QStringLiteral("已核对相机内参与时钟")); + m_cameraConfirmed->setToolTip(QStringLiteral("使用该相机 RGB 光学坐标系及标准 Brown 畸变模型;服务与上位机时钟同步,目标保持静止;深度单位及配准由服务提供。")); config->addWidget(m_cameraConfirmed); + m_teachObservation=new QPushButton(QStringLiteral("录入当前观察位")); m_teachObservation->setObjectName("touchTeachObservation"); + m_returnButton=new QPushButton(QStringLiteral("回观察位")); + auto *teachRow=new QHBoxLayout; teachRow->addWidget(m_teachObservation,1); teachRow->addWidget(m_returnButton); config->addLayout(teachRow); + m_observationText=new QLabel; m_observationText->setWordWrap(true); m_observationText->setObjectName("mutedLabel"); config->addWidget(m_observationText); + config->addSpacing(8); + auto *actionTitle=new QLabel(QStringLiteral("动作参数")); actionTitle->setObjectName("sectionTitle"); config->addWidget(actionTitle); + auto *params=new QGridLayout; params->setHorizontalSpacing(8); params->setVerticalSpacing(8); + params->setColumnStretch(1,1); params->setColumnStretch(3,1); config->addLayout(params); + m_action=new QComboBox; m_action->setObjectName("touchAction"); m_action->addItems({QStringLiteral("单击"),QStringLiteral("双击"),QStringLiteral("滑动")}); + params->addWidget(new QLabel(QStringLiteral("动作")),0,0); params->addWidget(m_action,0,1,1,3); + auto addSpin=[params](const QString &label,int row,int col,double value,double min,double max,const QString &suffix) { + auto *spin=new QDoubleSpinBox; spin->setRange(min,max); spin->setDecimals(2); spin->setValue(value); spin->setSuffix(suffix); spin->setKeyboardTracking(false); + params->addWidget(new QLabel(label),row,col); params->addWidget(spin,row,col+1); return spin; + }; + m_approach=addSpin(QStringLiteral("接近高度"),1,0,10,1,50," mm"); + m_press=addSpin(QStringLiteral("接触偏移"),1,2,0,0,2," mm"); + m_lift=addSpin(QStringLiteral("双击抬笔"),4,0,1,1,20," mm"); + m_speed=addSpin(QStringLiteral("移动速度"),2,0,30,5,50," mm/s"); + m_contactSpeed=addSpin(QStringLiteral("接触速度"),2,2,10,5,30," mm/s"); + m_travel=addSpin(QStringLiteral("运动范围"),3,0,300,10,1000," mm"); + m_dwell=new QSpinBox; m_dwell->setRange(0,2000); m_dwell->setValue(50); m_dwell->setSuffix(" ms"); + params->addWidget(new QLabel(QStringLiteral("接触停留")),3,2); params->addWidget(m_dwell,3,3); + m_gap=new QSpinBox; m_gap->setRange(20,500); m_gap->setValue(50); m_gap->setSuffix(" ms"); + params->addWidget(new QLabel(QStringLiteral("双击间隔")),4,2); params->addWidget(m_gap,4,3); + config->addStretch(); + m_press->setToolTip(QStringLiteral("沿相机 +Z 方向的几何位移,不是力控。首次验证建议为 0。")); + m_travel->setToolTip(QStringLiteral("相对观察位的最大位移与每段最大行程;不代替碰撞检查。")); + m_gap->setToolTip(QStringLiteral("抬笔到位后的停留;实际两次触点间隔还包含机械臂运动时间。")); + auto *bottom=new QHBoxLayout; root->addLayout(bottom); + auto *targetPanel=panel(bottom,QStringLiteral("目标点坐标换算结果")); + m_conversionStatus=new QLabel; m_conversionStatus->setObjectName("touchConversionStatus"); m_conversionStatus->setWordWrap(true); + m_conversionStatus->setToolTip(QStringLiteral("显示深度测量目标点,尚未叠加接触偏移;控制器 TCP 的实际运动目标见执行路径。")); + targetPanel->addWidget(m_conversionStatus); + m_targets=new QTableWidget(0,4); m_targets->setObjectName("touchTargets"); + m_targets->setHorizontalHeaderLabels({QStringLiteral("点"),QStringLiteral("像素 · px"),QStringLiteral("相机 XYZ · mm"),QStringLiteral("基座 XYZ · mm")}); targetPanel->addWidget(m_targets); + auto *pathPanel=panel(bottom,QStringLiteral("执行路径")); + m_steps=new QTableWidget(0,3); m_steps->setObjectName("touchSteps"); m_steps->setHorizontalHeaderLabels({QStringLiteral("步骤"),QStringLiteral("控制器 TCP · XYZ mm / RxRyRz °"),QStringLiteral("速度 mm/s")}); pathPanel->addWidget(m_steps); + for(auto *table:{m_targets,m_steps}) { table->verticalHeader()->hide(); table->setEditTriggers(QAbstractItemView::NoEditTriggers); table->setMinimumHeight(150); table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); table->horizontalHeader()->setStretchLastSection(true); } + m_targets->setMinimumHeight(188); m_targets->setMaximumHeight(230); m_targets->setWordWrap(false); + m_steps->setMinimumHeight(188); m_steps->setMaximumHeight(260); + for(auto *table:{m_targets,m_steps}) { table->setAlternatingRowColors(true); table->setShowGrid(false); } + m_targets->horizontalHeader()->setSectionResizeMode(2,QHeaderView::Stretch); + m_targets->horizontalHeader()->setSectionResizeMode(3,QHeaderView::Stretch); + bottom->setStretch(0,1); bottom->setStretch(1,1); + root->addStretch(1); + auto *footer=new QHBoxLayout; outer->addLayout(footer); + m_status=new QLabel; m_status->setWordWrap(true); m_status->setObjectName("mutedLabel"); outer->insertWidget(1,m_status); + m_pathConfirmed=new QCheckBox(QStringLiteral("已核对目标、笔姿及路径净空")); footer->addWidget(m_pathConfirmed); + footer->addStretch(1); + m_calculateButton=new QPushButton(QStringLiteral("转换 / 预览")); m_executeButton=new QPushButton(QStringLiteral("执行动作")); m_executeButton->setObjectName("primaryButton"); + auto *stopButton=new QPushButton(QStringLiteral("停止")); stopButton->setObjectName("dangerOutlineButton"); + footer->addWidget(m_calculateButton); footer->addWidget(m_executeButton); footer->addWidget(stopButton); + m_timeout.setSingleShot(true); m_timeout.setInterval(12000); + connect(&m_timeout,&QTimer::timeout,this,[this] { fail(QStringLiteral("读取超时,请检查连接后重试。")); }); + connect(m_previewButton,&QPushButton::clicked,this,&TouchOperationWidget::startPreview); + connect(m_stopPreviewButton,&QPushButton::clicked,this,&TouchOperationWidget::stopPreview); + connect(m_lockButton,&QPushButton::clicked,this,&TouchOperationWidget::lockFrame); + connect(m_liveButton,&QPushButton::clicked,this,[this] { invalidateFrame(); refresh(); }); + connect(m_teachObservation,&QPushButton::clicked,this,[this] { teach(Phase::Observation); }); + connect(m_returnButton,&QPushButton::clicked,this,[this] { teach(Phase::Return); }); + connect(m_calculateButton,&QPushButton::clicked,this,&TouchOperationWidget::calculate); + connect(m_executeButton,&QPushButton::clicked,this,&TouchOperationWidget::execute); + connect(stopButton,&QPushButton::clicked,this,[this] { + const bool active=running(); stop(); + if(!active&&!m_device.isEmpty()) emit stopRequested(m_device); + }); + connect(m_reloadButton,&QPushButton::clicked,this,&TouchOperationWidget::reloadCalibrations); + connect(m_video,&TouchVideoWidget::pointsChanged,this,[this] { invalidatePlan(); refresh(); }); + connect(m_cameraConfirmed,&QCheckBox::toggled,this,[this] { invalidateFrame(); refresh(); }); + connect(m_pathConfirmed,&QCheckBox::toggled,this,[this] { refresh(); }); + connect(m_handEyeChoice,QOverload::of(&QComboBox::currentIndexChanged),this,[this] { if(m_loading) return; stopPreview(); invalidateFrame(); m_cameraConfirmed->setChecked(false); saveTeaching(); refresh(); }); + connect(m_toolChoice,QOverload::of(&QComboBox::currentIndexChanged),this,[this] { if(m_loading) return; stop(); saveTeaching(); refresh(); }); + connect(m_action,QOverload::of(&QComboBox::currentIndexChanged),this,[this] { invalidatePlan(); refresh(); }); + for(auto *spin:{m_approach,m_press,m_lift,m_speed,m_contactSpeed,m_travel}) connect(spin,QOverload::of(&QDoubleSpinBox::valueChanged),this,[this] { invalidatePlan(); refresh(); }); + for(auto *spin:{m_dwell,m_gap}) connect(spin,QOverload::of(&QSpinBox::valueChanged),this,[this] { invalidatePlan(); refresh(); }); + connect(m_sequence,&TouchSequenceController::captureRequested,this,&TouchOperationWidget::captureRequested); + connect(m_sequence,&TouchSequenceController::moveRequested,this,&TouchOperationWidget::moveRequested); + connect(m_sequence,&TouchSequenceController::stopRequested,this,&TouchOperationWidget::stopRequested); + connect(m_sequence,&TouchSequenceController::progressChanged,this,[this](int step,int count,const QString &label) { m_status->setText(QStringLiteral("执行 %1 / %2 · %3").arg(step).arg(count).arg(label)); refresh(); }); + connect(m_sequence,&TouchSequenceController::errorOccurred,this,[this](const QString &error) { emit logMessage("ERROR",error); }); + connect(m_sequence,&TouchSequenceController::finished,this,[this](bool success,const QString &detail) { invalidateFrame(); refresh(); m_status->setText(detail); emit logMessage(success?"OK":"WARN",QStringLiteral("末端操作:%1").arg(detail)); }); + refresh(); +} + +bool TouchOperationWidget::running() const { return m_sequence->running(); } +bool TouchOperationWidget::ready() const { return m_connected&&!m_demo&&m_reference&&!m_device.isEmpty()&&TcpCalibration::validPose(m_activeOffset); } +const HandEyeStore::Record *TouchOperationWidget::handEye() const { + int i=m_handEyeChoice->currentIndex(); return i>=0&&icameraId:QString(); } +bool TouchOperationWidget::selectedTool(Pose &offset) const { + int i=m_toolChoice->currentIndex(); if(i<0||i>=m_tools.tools.size()) return false; + offset=m_tools.tools[i].offset; return true; +} +void TouchOperationWidget::setContext(const QString &endpoint,const QString &device,bool connected,bool demo,bool reference,const Pose &offset) { + bool scope=endpoint!=m_endpoint||device!=m_device; + if(!scope&&offset!=m_activeOffset) { m_observed=false; } + if(scope||connected!=m_connected||demo!=m_demo||reference!=m_reference||offset!=m_activeOffset) { + stopPreview(); stop(); m_cameraConfirmed->setChecked(false); + } + m_endpoint=endpoint; m_device=device; m_connected=connected; m_demo=demo; m_reference=reference; m_activeOffset=offset; + if(scope) { m_observed=false; reloadCalibrations(); loadTeaching(); } + if(m_observed&&m_reference&&m_teachingOffset!=m_activeOffset) { m_observed=false; } + m_sequence->setContext(endpoint,device,ready(),offset); refresh(); +} +void TouchOperationWidget::reloadCalibrations() { + stopPreview(); stop(); + const QString oldHand=m_handEyeChoice->currentText(),oldTool=m_toolChoice->currentText(); + m_loading=true; m_handEyeChoice->clear(); m_toolChoice->clear(); m_handEyes={}; m_tools={}; + QSettings settings; QString error; + bool ok=m_endpoint.isEmpty()||m_device.isEmpty()|| + (HandEyeStore::load(settings,m_endpoint,m_device,m_handEyes,error)&&TcpToolStore::load(settings,m_endpoint,m_device,m_tools,error)); + if(ok) { + for(const auto &r:m_handEyes.records) m_handEyeChoice->addItem(r.name); + for(const auto &t:m_tools.tools) m_toolChoice->addItem(t.name); + int h=m_handEyeChoice->findText(oldHand),t=m_toolChoice->findText(oldTool); + if(h>=0) m_handEyeChoice->setCurrentIndex(h); + if(t>=0) m_toolChoice->setCurrentIndex(t); + } + m_loading=false; + m_cameraConfirmed->setChecked(false); refresh(); if(!ok) fail(error); +} +void TouchOperationWidget::invalidatePlan() { m_planValid=false; m_plan={}; m_pathConfirmed->setChecked(false); m_steps->setRowCount(0); } +void TouchOperationWidget::invalidateFrame() { + invalidatePlan(); m_lockedAt=0; m_pendingImage={}; m_depth={}; m_video->unlock(); m_video->clearSelection(); +} +void TouchOperationWidget::stop() { + m_sequence->stop(); ++m_serial; m_poseToken=0; m_imageToken=0; m_phase=Phase::Idle; m_timeout.stop(); invalidateFrame(); refresh(); +} +void TouchOperationWidget::fail(const QString &message) { + stop(); m_status->setText(message); emit logMessage("ERROR",QStringLiteral("末端操作:%1").arg(message)); + QMessageBox::warning(this,QStringLiteral("末端操作"),message); +} +void TouchOperationWidget::hideEvent(QHideEvent *event) { stopPreview(); stop(); QWidget::hideEvent(event); } +void TouchOperationWidget::startPreview() { + if(!m_connected||m_demo||!handEye()) { fail(QStringLiteral("请连接机器人服务并选择手眼标定。")); return; } + stopPreview(); m_previewCamera=cameraId(); m_preview=true; emit previewRequested(m_previewCamera,true); refresh(); +} +void TouchOperationWidget::stopPreview() { + const QString camera=m_previewCamera; bool active=m_preview; m_preview=false; m_previewCamera.clear(); + if(active) emit previewRequested(camera,false); + stop(); m_video->clearFrame(); +} +void TouchOperationWidget::acceptFrame(const QString &camera,const VideoFrame &frame,const QString &) { + if(!m_preview||camera!=m_previewCamera||!frame.isValid()) return; + if(frame.metadata.value("kind").toString()!="rgb") { m_status->setText(QStringLiteral("当前流不是 RGB,请在相机页面切换为彩色视频。")); return; } + m_video->present(frame); + +} +void TouchOperationWidget::acceptStreamState(const QString &camera,bool active,const QString &detail) { + if(m_preview&&camera==m_previewCamera&&!active) { stopPreview(); m_status->setText(QStringLiteral("视频已停止:%1").arg(detail)); } +} +void TouchOperationWidget::teach(Phase phase) { + Pose offset{}; + if(!ready()||running()||m_phase!=Phase::Idle||(phase!=Phase::Observation&&!selectedTool(offset))) { fail(QStringLiteral("请先连接机械臂、选择 TCP 标定并核对控制器偏移。")); return; } + if(phase==Phase::Return&&!m_observed) return; + invalidateFrame(); m_phase=phase; readPose(); +} +void TouchOperationWidget::readPose() { + m_poseToken=kPosePrefix|++m_serial; m_requestAt=QDateTime::currentMSecsSinceEpoch(); m_timeout.start(); + emit captureRequested(m_device,m_poseToken); refresh(); +} +void TouchOperationWidget::lockFrame() { + if(!ready()||!m_preview||!m_observed||!m_cameraConfirmed->isChecked()||running()||m_phase!=Phase::Idle) return; + invalidateFrame(); m_phase=Phase::LockBefore; readPose(); +} +void TouchOperationWidget::acceptPose(quint64 token,const QString &device,const QVariantMap &map,const QVariantMap &state,bool success,const QString &detail) { + m_sequence->acceptPose(token,device,map,state,success,detail); + if(!m_poseToken||token!=m_poseToken||device!=m_device) return; + m_poseToken=0; Pose pose{},tool{},flange{},selected{}; + const qint64 requested=state.value("requestedAtMs").toLongLong(),received=state.value("receivedAtMs").toLongLong(); + const qint64 now=QDateTime::currentMSecsSinceEpoch(); + if(!success||!ready()||!decodePose(map,pose)||(m_phase!=Phase::Observation&&!selectedTool(tool))||requestednow||now-received>1500 + ||!state.value("connected").toBool()||state.value("moving",true).toBool()||state.value("fault",true).toBool() + ||state.value("protectiveStopped",true).toBool()||state.value("emergencyStopped",true).toBool() + ||state.value("source").toString()!=QStringLiteral("getRobotState.actual_tcp_pose")) { fail(QStringLiteral("实时位姿不可用:%1").arg(detail)); return; } + if(!TcpCalibration::flangePose(pose,m_activeOffset,flange)||!TcpCalibration::toolPose(flange,tool,selected)) { fail(QStringLiteral("TCP 位姿转换失败。")); return; } + const auto phase=m_phase; + if(phase==Phase::LockBefore) { + if(!nearPose(pose,m_observation)) { fail(QStringLiteral("机械臂不在观察位,请先回观察位并停稳。")); return; } + m_before=pose; m_beforeAt=received; m_phase=Phase::LockImage; m_imageToken=kImagePrefix|++m_serial; + emit imageRequested(cameraId(),m_imageToken); refresh(); return; + } + if(phase==Phase::LockAfter) { + if(requested10000) { fail(QStringLiteral("取图期间位姿变化或时间窗无效,请停稳后重试。")); return; } + TcpCalibration::flangePose(m_before,m_activeOffset,m_lockedFlange); + if(!(m_video->lockImage(m_pendingImage))) { fail(QStringLiteral("观察图像无效。")); return; } + m_pendingImage={}; m_lockedAt=QDateTime::currentMSecsSinceEpoch(); + } else if(phase==Phase::Observation) { + m_observation=pose; m_observed=true; m_teachingOffset=m_activeOffset; saveTeaching(); + } else if(phase==Phase::Return) { + m_phase=Phase::Idle; m_timeout.stop(); returnObservation(pose); return; + } + m_phase=Phase::Idle; m_timeout.stop(); refresh(); emit logMessage("OK",QStringLiteral("末端操作:已录入位姿 / 锁定观察图像")); +} +void TouchOperationWidget::acceptImage(quint64 token,const QString &camera,const QImage &image,const QVariantMap &intrinsics,const QVariantMap &metadata,bool success,const QString &detail) { + if(!m_imageToken||token!=m_imageToken||camera!=cameraId()||m_phase!=Phase::LockImage) return; + m_imageToken=0; QString error; + if(!success) { fail(QStringLiteral("读取 RGBD 失败:%1").arg(detail)); return; } + const qint64 colorAt=metadata.value("captureUtcNs").toLongLong()/1000000; + const qint64 depthAt=metadata.value("depthCaptureUtcNs").toLongLong()/1000000; + const qint64 now=QDateTime::currentMSecsSinceEpoch(); + if(!metadata.value("alignedToColor").toBool()||!metadata.value("colorAxialZ").toBool() + ||metadata.value("byteOrder").toString()!="little"||colorAt<=0||depthAt<=0 + ||std::abs(colorAt-depthAt)>33||colorAt>now||depthAt>now) { + fail(QStringLiteral("RGBD 缺少有效配准、深度单位或同步时间戳,请更新相机服务。")); return; + } + if(colorAt1500) { + // The server snapshots its acquisition thread. Wait for a new pair; + // never combine a live color frame with an older depth image. + const quint64 generation=m_serial; + QTimer::singleShot(80,this,[this,generation] { + if(m_serial!=generation||m_phase!=Phase::LockImage||m_imageToken) return; + m_imageToken=kImagePrefix|++m_serial; emit imageRequested(cameraId(),m_imageToken); + }); + return; + } + TouchPlanner::DepthImage depth; + depth.width=metadata.value("depthWidth").toInt(); depth.height=metadata.value("depthHeight").toInt(); + depth.data=metadata.value("depthData").toByteArray(); depth.float32=metadata.value("depthFloat32").toBool(); + depth.metresPerUnit=metadata.value("metresPerUnit").toDouble(); + if(image.isNull()||!TouchPlanner::cameraModel(intrinsics,image.width(),image.height(),m_cameraModel,&error) + ||depth.width!=image.width()||depth.height!=image.height() + ||!std::isfinite(depth.metresPerUnit)||depth.metresPerUnit<=0||depth.metresPerUnit>1 + ||qint64(depth.width)*depth.height*(depth.float32?4:2)!=depth.data.size()) { + fail(QStringLiteral("RGBD 尺寸、单位或内参无效:%1").arg(error)); return; + } + m_depth=depth; m_pendingImage=image; m_captureAt=qMax(colorAt,depthAt); m_phase=Phase::LockAfter; readPose(); +} +void TouchOperationWidget::acceptCommand(const QString &command,bool success,const QString &detail) { m_sequence->acceptCommand(command,success,detail); } +TouchPlanner::Parameters TouchOperationWidget::parameters() const { + TouchPlanner::Parameters p; p.approachM=m_approach->value()/1000; p.contactOffsetM=m_press->value()/1000; + p.doubleLiftM=m_lift->value()/1000; p.travelVelocityMps=m_speed->value()/1000; p.contactVelocityMps=m_contactSpeed->value()/1000; + p.maxTravelM=m_travel->value()/1000; p.contactDwellMs=m_dwell->value(); p.doubleIntervalMs=m_gap->value(); return p; +} +bool TouchOperationWidget::buildPlane(TouchPlanner::Plane &plane,QString &error) const { + QVector points,cameraPoints; + TouchPlanner::Matrix baseCamera{}; Pose offset{},tip{}; + if(!resolveTargets(points,cameraPoints,error)||!selectedTool(offset) + ||!TcpCalibration::toolPose(m_lockedFlange,offset,tip,&error) + ||!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error)) return false; + plane.origin=points.first(); + // Same free-pixel approach direction as phone: negative camera Z. + // Preserve the selected stylus orientation taught at the observation pose. + for(int i=0;i<3;++i) { plane.normal[i]=-baseCamera[i*4+2]; plane.orientationRad[i]=tip[i+3]; } + return true; +} +void TouchOperationWidget::calculate() { + invalidatePlan(); QString error; Pose tool{}; TouchPlanner::Plane plane; QVector points,cameraPoints; + TouchPlanner::Matrix baseCamera{}; + if(!ready()||!handEye()||!selectedTool(tool)||!m_video->locked()||!m_lockedAt||QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { fail(QStringLiteral("请在观察位重新锁定画面后取点。")); return; } + if(!buildPlane(plane,error)||!resolveTargets(points,cameraPoints,error) + ||!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error) + ||(m_action->currentIndex()==2&&!TouchPlanner::validateDepthSwipe(m_video->selectedPoints(),m_cameraModel,m_depth,baseCamera,parameters(),&error)) + ||!TouchPlanner::buildPlan(static_cast(m_action->currentIndex()),points,plane,m_observation,m_activeOffset,tool,parameters(),m_plan,&error,true)) { fail(error); return; } + m_planValid=true; m_steps->setRowCount(m_plan.steps.size()); + for(int i=0;isetItem(i,0,new QTableWidgetItem(QString::number(i+1)+" · "+step.label)); + m_steps->setItem(i,1,new QTableWidgetItem(poseText(step.target))); m_steps->setItem(i,2,new QTableWidgetItem(QString::number(step.velocityMps*1000,'f',1))); } + refresh(); emit logMessage("INFO",QStringLiteral("末端操作:已转换 %1 个目标,规划 %2 个动作步骤").arg(points.size()).arg(m_plan.steps.size())); +} +void TouchOperationWidget::execute() { + if(!m_planValid||!m_pathConfirmed->isChecked()||running()||!ready()||QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { fail(QStringLiteral("请重新预览路径并确认后执行。")); return; } + QVector steps; + for(const auto &s:m_plan.steps) steps.append({s.target,s.velocityMps,s.accelerationMps2,s.pauseMs,s.label}); + m_sequence->setContext(m_endpoint,m_device,ready(),m_activeOffset); + m_sequence->start(steps,m_observation); refresh(); +} +void TouchOperationWidget::returnObservation(const Pose ¤t) { + // Explicit straight return; automatic touch sequences retract before return. + auto p=parameters(); double distance=0; for(int i=0;i<3;++i) distance+=std::pow(current[i]-m_observation[i],2); + if(std::sqrt(distance)>p.maxTravelM) { fail(QStringLiteral("当前位置超出所设回程范围,请手动接近观察位。")); return; } + QVector steps; Pose tool{}; + steps.append({m_observation,p.travelVelocityMps,p.accelerationMps2,0,QStringLiteral("返回观察位")}); + if(!selectedTool(tool)) { fail(QStringLiteral("请选择有效 TCP。")); return; } + Pose previous=current,previousFlange{},previousTip{},obsFlange{},obsTip{}; + if(!TcpCalibration::flangePose(current,m_activeOffset,previousFlange)||!TcpCalibration::toolPose(previousFlange,tool,previousTip) + ||!TcpCalibration::flangePose(m_observation,m_activeOffset,obsFlange)||!TcpCalibration::toolPose(obsFlange,tool,obsTip)) { fail(QStringLiteral("回程位姿转换失败。")); return; } + for(const auto &step:steps) { + Pose nextFlange{},nextTip{}; + if(!TcpCalibration::flangePose(step.target,m_activeOffset,nextFlange)||!TcpCalibration::toolPose(nextFlange,tool,nextTip)) { fail(QStringLiteral("回程位姿转换失败。")); return; } + auto norm=[](const Pose &a,const Pose &b) { double sum=0; for(int i=0;i<3;++i) sum+=std::pow(a[i]-b[i],2); return std::sqrt(sum); }; + const Pose origin{}; + if(norm(step.target,previous)>p.maxTravelM||norm(nextTip,previousTip)>p.maxTravelM||norm(nextFlange,previousFlange)>p.maxTravelM + ||norm(step.target,m_observation)>p.maxTravelM||norm(nextTip,obsTip)>p.maxTravelM||norm(nextFlange,obsFlange)>p.maxTravelM + ||norm(step.target,origin)>p.maxReachM||norm(nextTip,origin)>p.maxReachM||norm(nextFlange,origin)>p.maxReachM) { fail(QStringLiteral("回程路径超出所设运动范围。")); return; } + previous=step.target; previousTip=nextTip; previousFlange=nextFlange; + } + m_sequence->setContext(m_endpoint,m_device,ready(),m_activeOffset); m_sequence->start(steps,current); refresh(); +} +QString TouchOperationWidget::settingsKey() const { + QByteArray identity=m_endpoint.toUtf8(); identity.append('\0'); identity.append(m_device.toUtf8()); + return QStringLiteral("touchOperation/v1/")+QString::fromLatin1(QCryptographicHash::hash(identity,QCryptographicHash::Sha256).toHex()); +} +void TouchOperationWidget::saveTeaching() { + if(m_loading||m_endpoint.isEmpty()||m_device.isEmpty()) return; + Pose tool{}; QVariantMap data{{"endpoint",m_endpoint},{"device",m_device},{"handEye",m_handEyeChoice->currentText()},{"tool",m_toolChoice->currentText()}, + {"observed",m_observed},{"observation",values(m_observation)},{"activeOffset",values(m_teachingOffset)}}; + if(selectedTool(tool)) data.insert("toolOffset",values(tool)); + QSettings settings; settings.setValue(settingsKey(),QJsonDocument::fromVariant(data).toJson(QJsonDocument::Compact)); settings.sync(); + if(settings.status()!=QSettings::NoError) { m_status->setText(QStringLiteral("示教配置写入失败")); emit logMessage("ERROR",m_status->text()); } +} +void TouchOperationWidget::loadTeaching() { + QSettings settings; auto bytes=settings.value(settingsKey()).toByteArray(); if(bytes.isEmpty()) return; + const auto data=QJsonDocument::fromJson(bytes).toVariant().toMap(); + if(data.value("endpoint").toString()!=m_endpoint||data.value("device").toString()!=m_device) return; + m_loading=true; const int h=m_handEyeChoice->findText(data.value("handEye").toString()),t=m_toolChoice->findText(data.value("tool").toString()); + if(h>=0) m_handEyeChoice->setCurrentIndex(h); + if(t>=0) m_toolChoice->setCurrentIndex(t); + m_loading=false; + m_observed=data.value("observed").toBool()&&poseFrom(data.value("observation"),m_observation)&&poseFrom(data.value("activeOffset"),m_teachingOffset); + +} +void TouchOperationWidget::refresh() { + bool busy=running()||m_phase!=Phase::Idle; Pose offset{}; bool selected=selectedTool(offset); + m_cameraName->setText(cameraId().isEmpty()?QStringLiteral("请先选择手眼标定"):cameraId()); + for(auto *w:QList{m_handEyeChoice,m_toolChoice,m_action,m_reloadButton,m_cameraConfirmed,m_approach,m_press,m_lift,m_speed,m_contactSpeed,m_travel,m_dwell,m_gap}) w->setEnabled(!busy); + m_teachObservation->setEnabled(ready()&&!busy); m_returnButton->setEnabled(ready()&&selected&&m_observed&&!busy); + + m_previewButton->setEnabled(m_connected&&!m_demo&&handEye()&&!m_preview&&!busy); m_stopPreviewButton->setEnabled(m_preview); + m_lockButton->setEnabled(ready()&&m_observed&&m_preview&&m_cameraConfirmed->isChecked()&&!busy); + m_liveButton->setEnabled(m_video->locked()&&!busy); m_video->setEnabled(!busy); + m_calculateButton->setEnabled(ready()&&m_video->locked()&&!m_video->selectedPoints().isEmpty()&&!busy); + m_executeButton->setEnabled(ready()&&m_planValid&&m_pathConfirmed->isChecked()&&!busy); + m_pathConfirmed->setEnabled(m_planValid&&!busy); + m_observationText->setText(m_observed?QStringLiteral("观察位 · %1").arg(poseText(m_observation)):QStringLiteral("尚未录入观察位")); + refreshTargetResults(); + if(!running()) m_status->setText(!ready()?QStringLiteral("请连接机械臂并在 TCP 标定页核对控制器工具偏移"): + busy?QStringLiteral("正在读取真实位姿 / 图像…"):m_planValid?QStringLiteral("路径已就绪,核对后执行"):m_video->locked()?QStringLiteral("画面已锁定,请选择 1–2 个目标点"):QStringLiteral("录入示教位、选择标定后,在观察位锁定画面")); +} + +bool TouchOperationWidget::resolveTargets(QVector &basePoints, + QVector &cameraPoints,QString &error) const { + if(!m_video->locked()||!m_lockedAt) { error=QStringLiteral("请锁定观察画面后选择目标点"); return false; } + if(m_video->selectedPoints().isEmpty()) { error=QStringLiteral("请选择 A / B 目标点"); return false; } + if(QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { error=QStringLiteral("观察画面已过期,请重新锁定"); return false; } + if(!ready()||!handEye()) { error=QStringLiteral("请核对连接、手眼标定与 TCP 偏移"); return false; } + TouchPlanner::Matrix baseCamera{}; + if(!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error)) return false; + return TouchPlanner::resolveDepthPixels(m_video->selectedPoints(),m_cameraModel,m_depth,baseCamera, + parameters(),basePoints,cameraPoints,&error); + +} + +void TouchOperationWidget::refreshTargetResults() { + const auto pixels=m_video->selectedPoints(); QVector base,camera; QString error; + const bool valid=resolveTargets(base,camera,error); + m_conversionStatus->setText(valid?QStringLiteral("%1 个深度目标点 · 换算完成").arg(base.size()):error); + m_targets->setRowCount(pixels.size()); + auto xyz=[](const TouchPlanner::Point &point) { + return QStringLiteral("X %1\nY %2\nZ %3").arg(point[0]*1000,0,'f',3).arg(point[1]*1000,0,'f',3).arg(point[2]*1000,0,'f',3); + }; + for(int i=0;isetTextAlignment(Qt::AlignLeft|Qt::AlignVCenter); m_targets->setItem(i,col,item); } + m_targets->setRowHeight(i,74); + } +} diff --git a/src/videorenderwidget.cpp b/src/videorenderwidget.cpp index c750e41..bdc2fd0 100644 --- a/src/videorenderwidget.cpp +++ b/src/videorenderwidget.cpp @@ -1,267 +1,307 @@ -#include "videorenderwidget.h" - -#include -#include - -#include -#include - -namespace { -const char *vertexShaderSource = R"( -attribute vec2 position; -attribute vec2 texCoord; -varying vec2 textureCoordinate; -uniform vec2 contentScale; -void main() +#include "videorenderwidget.h" + +#include +#include + +#include +#include + +namespace { +const char *vertexShaderSource = R"( +attribute vec2 position; +attribute vec2 texCoord; +varying vec2 textureCoordinate; +uniform vec2 contentScale; +void main() +{ + gl_Position = vec4(position * contentScale, 0.0, 1.0); + textureCoordinate = texCoord; +} +)"; + +const char *fragmentShaderSource = R"( +#ifdef GL_ES +precision mediump float; +#endif +varying vec2 textureCoordinate; +uniform sampler2D textureY; +uniform sampler2D textureU; +uniform sampler2D textureV; +uniform float pixelFormat; +uniform float scaleY; +uniform float scaleU; +uniform float scaleV; +void main() +{ + if (pixelFormat > 1.5) { + gl_FragColor = texture2D(textureY, textureCoordinate); + return; + } + + float y = texture2D(textureY, + vec2(textureCoordinate.x * scaleY, textureCoordinate.y)).r; + float u; + float v; + if (pixelFormat > 0.5) { + vec4 uv = texture2D(textureU, + vec2(textureCoordinate.x * scaleU, textureCoordinate.y)); + u = uv.r - 0.5; + v = uv.a - 0.5; + } else { + u = texture2D(textureU, + vec2(textureCoordinate.x * scaleU, textureCoordinate.y)).r - 0.5; + v = texture2D(textureV, + vec2(textureCoordinate.x * scaleV, textureCoordinate.y)).r - 0.5; + } + y = 1.16438356 * (y - 0.0625); + gl_FragColor = vec4(y + 1.59602678 * v, + y - 0.39176229 * u - 0.81296764 * v, + y + 2.01723214 * u, 1.0); +} +)"; +} + +VideoRenderWidget::VideoRenderWidget(QWidget *parent) + : QOpenGLWidget(parent) +{ + setAutoFillBackground(false); + setUpdateBehavior(QOpenGLWidget::NoPartialUpdate); +} + +VideoRenderWidget::~VideoRenderWidget() +{ + if (context()) { + makeCurrent(); + releaseTextures(); + doneCurrent(); + } +} + +void VideoRenderWidget::setFrameAspectLayoutEnabled(bool enabled) { - gl_Position = vec4(position * contentScale, 0.0, 1.0); - textureCoordinate = texCoord; -} -)"; - -const char *fragmentShaderSource = R"( -#ifdef GL_ES -precision mediump float; -#endif -varying vec2 textureCoordinate; -uniform sampler2D textureY; -uniform sampler2D textureU; -uniform sampler2D textureV; -uniform float pixelFormat; -uniform float scaleY; -uniform float scaleU; -uniform float scaleV; -void main() -{ - if (pixelFormat > 1.5) { - gl_FragColor = texture2D(textureY, textureCoordinate); - return; - } - - float y = texture2D(textureY, - vec2(textureCoordinate.x * scaleY, textureCoordinate.y)).r; - float u; - float v; - if (pixelFormat > 0.5) { - vec4 uv = texture2D(textureU, - vec2(textureCoordinate.x * scaleU, textureCoordinate.y)); - u = uv.r - 0.5; - v = uv.a - 0.5; - } else { - u = texture2D(textureU, - vec2(textureCoordinate.x * scaleU, textureCoordinate.y)).r - 0.5; - v = texture2D(textureV, - vec2(textureCoordinate.x * scaleV, textureCoordinate.y)).r - 0.5; - } - y = 1.16438356 * (y - 0.0625); - gl_FragColor = vec4(y + 1.59602678 * v, - y - 0.39176229 * u - 0.81296764 * v, - y + 2.01723214 * u, 1.0); -} -)"; + m_frameAspectLayout = enabled; + QSizePolicy policy(QSizePolicy::Expanding, enabled ? QSizePolicy::Fixed : QSizePolicy::Expanding); + policy.setHeightForWidth(enabled); + setSizePolicy(policy); + if (enabled) updateAspectHeight(); + else { setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); } + updateGeometry(); } -VideoRenderWidget::VideoRenderWidget(QWidget *parent) - : QOpenGLWidget(parent) +int VideoRenderWidget::heightForWidth(int width) const { - setAutoFillBackground(false); - setUpdateBehavior(QOpenGLWidget::NoPartialUpdate); + return m_frameAspectLayout ? qMax(1, qRound(double(width) * m_layoutFrameSize.height() + / m_layoutFrameSize.width())) : -1; } -VideoRenderWidget::~VideoRenderWidget() +QSize VideoRenderWidget::sizeHint() const { - if (context()) { - makeCurrent(); - releaseTextures(); - doneCurrent(); - } + return m_frameAspectLayout ? QSize(640,heightForWidth(640)) : QOpenGLWidget::sizeHint(); +} + +void VideoRenderWidget::updateAspectHeight() +{ + if (!m_frameAspectLayout) return; + const int wanted = heightForWidth(width()); + if (minimumHeight() != wanted || maximumHeight() != wanted) setFixedHeight(wanted); +} + +void VideoRenderWidget::resizeEvent(QResizeEvent *event) +{ + QOpenGLWidget::resizeEvent(event); + updateAspectHeight(); } void VideoRenderWidget::setFrame(const VideoFrame &frame) -{ - if (!frame.isValid()) - return; +{ + if (!frame.isValid()) + return; m_frame = frame; - m_message.clear(); - m_frameDirty = true; - update(); -} - -void VideoRenderWidget::setImage(const QImage &image) -{ - if (image.isNull()) - return; - const QImage converted = image.convertToFormat(QImage::Format_RGBA8888); - VideoFrame frame; - frame.width = converted.width(); - frame.height = converted.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, - converted.constScanLine(row), static_cast(frame.width * 4)); + if (m_layoutFrameSize != QSize(frame.width, frame.height)) { + m_layoutFrameSize = QSize(frame.width, frame.height); + updateAspectHeight(); + if (m_frameAspectLayout) updateGeometry(); } - setFrame(frame); -} - -void VideoRenderWidget::clearFrame(const QString &message) -{ - m_frame = VideoFrame(); - m_message = message; - m_frameDirty = false; - update(); -} - -void VideoRenderWidget::initializeGL() -{ - initializeOpenGLFunctions(); - glClearColor(0.055f, 0.067f, 0.078f, 1.0f); - glGenTextures(3, m_textures); - - m_program.reset(new QOpenGLShaderProgram); - if (!m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource) || - !m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource) || - !m_program->link()) { - m_message = QStringLiteral("OpenGL 视频着色器初始化失败:%1").arg(m_program->log()); - m_program.reset(); - return; - } - m_glReady = true; -} - -void VideoRenderWidget::uploadPlane(unsigned int texture, int unit, int width, - int height, unsigned int format, - const QByteArray &data, int textureIndex) -{ - glActiveTexture(GL_TEXTURE0 + unit); - glBindTexture(GL_TEXTURE_2D, texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - if (m_textureWidths[textureIndex] != width || - m_textureHeights[textureIndex] != height || - m_textureFormats[textureIndex] != format) { - glTexImage2D(GL_TEXTURE_2D, 0, static_cast(format), width, height, 0, - format, GL_UNSIGNED_BYTE, data.constData()); - m_textureWidths[textureIndex] = width; - m_textureHeights[textureIndex] = height; - m_textureFormats[textureIndex] = format; - } else { - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, - GL_UNSIGNED_BYTE, data.constData()); - } -} - -void VideoRenderWidget::paintGL() -{ - glClear(GL_COLOR_BUFFER_BIT); - if (!m_glReady || !m_program || !m_frame.isValid()) { - drawMessage(m_message); - return; - } - - // Qt 5.12's ANGLE backend can upload RGBA QImage data with an incorrect - // channel layout. Draw still RGBA frames with the CPU painter instead. - if (m_frame.format == VideoPixelFormat::RGBA) { - const QImage image(reinterpret_cast(m_frame.plane0.constData()), - m_frame.width, m_frame.height, m_frame.stride0, - QImage::Format_RGBA8888); - QPainter painter(this); - painter.fillRect(rect(), QColor(QStringLiteral("#0e1115"))); - QSize target = image.size(); - target.scale(size(), Qt::KeepAspectRatio); - const QRect destination((width() - target.width()) / 2, - (height() - target.height()) / 2, - target.width(), target.height()); - painter.drawImage(destination, image); - m_frameDirty = false; - return; - } - - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - if (m_frameDirty) { - if (m_frame.format == VideoPixelFormat::I420) { - uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, - GL_LUMINANCE, m_frame.plane0, 0); - uploadPlane(m_textures[1], 1, m_frame.stride1, - (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane1, 1); - uploadPlane(m_textures[2], 2, m_frame.stride2, - (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane2, 2); - } else if (m_frame.format == VideoPixelFormat::NV12) { - uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, - GL_LUMINANCE, m_frame.plane0, 0); - uploadPlane(m_textures[1], 1, m_frame.stride1 / 2, - (m_frame.height + 1) / 2, GL_LUMINANCE_ALPHA, - m_frame.plane1, 1); - } else { - uploadPlane(m_textures[0], 0, m_frame.width, m_frame.height, - GL_RGBA, m_frame.plane0, 0); - } - m_frameDirty = false; - } - - const GLfloat vertices[] = { - -1.0f, -1.0f, 0.0f, 1.0f, - 1.0f, -1.0f, 1.0f, 1.0f, - -1.0f, 1.0f, 0.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 0.0f - }; - float scaleX = 1.0f; - float scaleY = 1.0f; - const float frameAspect = static_cast(m_frame.width) / m_frame.height; - const float widgetAspect = width() > 0 && height() > 0 - ? static_cast(width()) / height() : frameAspect; - if (frameAspect > widgetAspect) - scaleY = widgetAspect / frameAspect; - else - scaleX = frameAspect / widgetAspect; - - m_program->bind(); - m_program->setUniformValue("contentScale", scaleX, scaleY); - m_program->setUniformValue("textureY", 0); - m_program->setUniformValue("textureU", 1); - m_program->setUniformValue("textureV", 2); - m_program->setUniformValue("pixelFormat", - m_frame.format == VideoPixelFormat::NV12 ? 1.0f : - m_frame.format == VideoPixelFormat::RGBA ? 2.0f : 0.0f); - m_program->setUniformValue("scaleY", m_frame.format == VideoPixelFormat::RGBA - ? 1.0f : static_cast(m_frame.width) / m_frame.stride0); - m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::NV12 - ? static_cast((m_frame.width + 1) / 2) / (m_frame.stride1 / 2) - : static_cast((m_frame.width + 1) / 2) / m_frame.stride1); - m_program->setUniformValue("scaleV", m_frame.format == VideoPixelFormat::I420 - ? static_cast((m_frame.width + 1) / 2) / m_frame.stride2 : 1.0f); - const int position = m_program->attributeLocation("position"); - const int texCoord = m_program->attributeLocation("texCoord"); - m_program->enableAttributeArray(position); - m_program->enableAttributeArray(texCoord); - m_program->setAttributeArray(position, GL_FLOAT, vertices, 2, 4 * sizeof(GLfloat)); - m_program->setAttributeArray(texCoord, GL_FLOAT, vertices + 2, 2, - 4 * sizeof(GLfloat)); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - m_program->disableAttributeArray(position); - m_program->disableAttributeArray(texCoord); - m_program->release(); -} - -void VideoRenderWidget::drawMessage(const QString &message) -{ - if (message.isEmpty()) - return; - QPainter painter(this); - painter.setPen(QColor(QStringLiteral("#8d98a5"))); - painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, message); -} - -void VideoRenderWidget::releaseTextures() -{ - if (m_textures[0]) { - glDeleteTextures(3, m_textures); - m_textures[0] = m_textures[1] = m_textures[2] = 0; - std::fill(m_textureWidths, m_textureWidths + 3, 0); - std::fill(m_textureHeights, m_textureHeights + 3, 0); - std::fill(m_textureFormats, m_textureFormats + 3, 0); - } -} + m_message.clear(); + m_frameDirty = true; + update(); +} + +void VideoRenderWidget::setImage(const QImage &image) +{ + if (image.isNull()) + return; + const QImage converted = image.convertToFormat(QImage::Format_RGBA8888); + VideoFrame frame; + frame.width = converted.width(); + frame.height = converted.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, + converted.constScanLine(row), static_cast(frame.width * 4)); + } + setFrame(frame); +} + +void VideoRenderWidget::clearFrame(const QString &message) +{ + m_frame = VideoFrame(); + m_message = message; + m_frameDirty = false; + update(); +} + +void VideoRenderWidget::initializeGL() +{ + initializeOpenGLFunctions(); + glClearColor(0.055f, 0.067f, 0.078f, 1.0f); + glGenTextures(3, m_textures); + + m_program.reset(new QOpenGLShaderProgram); + if (!m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource) || + !m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource) || + !m_program->link()) { + m_message = QStringLiteral("OpenGL 视频着色器初始化失败:%1").arg(m_program->log()); + m_program.reset(); + return; + } + m_glReady = true; +} + +void VideoRenderWidget::uploadPlane(unsigned int texture, int unit, int width, + int height, unsigned int format, + const QByteArray &data, int textureIndex) +{ + glActiveTexture(GL_TEXTURE0 + unit); + glBindTexture(GL_TEXTURE_2D, texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + if (m_textureWidths[textureIndex] != width || + m_textureHeights[textureIndex] != height || + m_textureFormats[textureIndex] != format) { + glTexImage2D(GL_TEXTURE_2D, 0, static_cast(format), width, height, 0, + format, GL_UNSIGNED_BYTE, data.constData()); + m_textureWidths[textureIndex] = width; + m_textureHeights[textureIndex] = height; + m_textureFormats[textureIndex] = format; + } else { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, + GL_UNSIGNED_BYTE, data.constData()); + } +} + +void VideoRenderWidget::paintGL() +{ + glClear(GL_COLOR_BUFFER_BIT); + if (!m_glReady || !m_program || !m_frame.isValid()) { + drawMessage(m_message); + return; + } + + // Qt 5.12's ANGLE backend can upload RGBA QImage data with an incorrect + // channel layout. Draw still RGBA frames with the CPU painter instead. + if (m_frame.format == VideoPixelFormat::RGBA) { + const QImage image(reinterpret_cast(m_frame.plane0.constData()), + m_frame.width, m_frame.height, m_frame.stride0, + QImage::Format_RGBA8888); + QPainter painter(this); + painter.fillRect(rect(), QColor(QStringLiteral("#0e1115"))); + QSize target = image.size(); + target.scale(size(), Qt::KeepAspectRatio); + const QRect destination((width() - target.width()) / 2, + (height() - target.height()) / 2, + target.width(), target.height()); + painter.drawImage(destination, image); + m_frameDirty = false; + return; + } + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + if (m_frameDirty) { + if (m_frame.format == VideoPixelFormat::I420) { + uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, + GL_LUMINANCE, m_frame.plane0, 0); + uploadPlane(m_textures[1], 1, m_frame.stride1, + (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane1, 1); + uploadPlane(m_textures[2], 2, m_frame.stride2, + (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane2, 2); + } else if (m_frame.format == VideoPixelFormat::NV12) { + uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, + GL_LUMINANCE, m_frame.plane0, 0); + uploadPlane(m_textures[1], 1, m_frame.stride1 / 2, + (m_frame.height + 1) / 2, GL_LUMINANCE_ALPHA, + m_frame.plane1, 1); + } else { + uploadPlane(m_textures[0], 0, m_frame.width, m_frame.height, + GL_RGBA, m_frame.plane0, 0); + } + m_frameDirty = false; + } + + const GLfloat vertices[] = { + -1.0f, -1.0f, 0.0f, 1.0f, + 1.0f, -1.0f, 1.0f, 1.0f, + -1.0f, 1.0f, 0.0f, 0.0f, + 1.0f, 1.0f, 1.0f, 0.0f + }; + float scaleX = 1.0f; + float scaleY = 1.0f; + const float frameAspect = static_cast(m_frame.width) / m_frame.height; + const float widgetAspect = width() > 0 && height() > 0 + ? static_cast(width()) / height() : frameAspect; + if (frameAspect > widgetAspect) + scaleY = widgetAspect / frameAspect; + else + scaleX = frameAspect / widgetAspect; + + m_program->bind(); + m_program->setUniformValue("contentScale", scaleX, scaleY); + m_program->setUniformValue("textureY", 0); + m_program->setUniformValue("textureU", 1); + m_program->setUniformValue("textureV", 2); + m_program->setUniformValue("pixelFormat", + m_frame.format == VideoPixelFormat::NV12 ? 1.0f : + m_frame.format == VideoPixelFormat::RGBA ? 2.0f : 0.0f); + m_program->setUniformValue("scaleY", m_frame.format == VideoPixelFormat::RGBA + ? 1.0f : static_cast(m_frame.width) / m_frame.stride0); + m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::NV12 + ? static_cast((m_frame.width + 1) / 2) / (m_frame.stride1 / 2) + : static_cast((m_frame.width + 1) / 2) / m_frame.stride1); + m_program->setUniformValue("scaleV", m_frame.format == VideoPixelFormat::I420 + ? static_cast((m_frame.width + 1) / 2) / m_frame.stride2 : 1.0f); + const int position = m_program->attributeLocation("position"); + const int texCoord = m_program->attributeLocation("texCoord"); + m_program->enableAttributeArray(position); + m_program->enableAttributeArray(texCoord); + m_program->setAttributeArray(position, GL_FLOAT, vertices, 2, 4 * sizeof(GLfloat)); + m_program->setAttributeArray(texCoord, GL_FLOAT, vertices + 2, 2, + 4 * sizeof(GLfloat)); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + m_program->disableAttributeArray(position); + m_program->disableAttributeArray(texCoord); + m_program->release(); +} + +void VideoRenderWidget::drawMessage(const QString &message) +{ + if (message.isEmpty()) + return; + QPainter painter(this); + painter.setPen(QColor(QStringLiteral("#8d98a5"))); + painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, message); +} + +void VideoRenderWidget::releaseTextures() +{ + if (m_textures[0]) { + glDeleteTextures(3, m_textures); + m_textures[0] = m_textures[1] = m_textures[2] = 0; + std::fill(m_textureWidths, m_textureWidths + 3, 0); + std::fill(m_textureHeights, m_textureHeights + 3, 0); + std::fill(m_textureFormats, m_textureFormats + 3, 0); + } +} diff --git a/src/videorenderwidget.h b/src/videorenderwidget.h index 15bad3a..2b6bce1 100644 --- a/src/videorenderwidget.h +++ b/src/videorenderwidget.h @@ -1,47 +1,55 @@ -#pragma once - -#include "videoframe.h" - -#include -#include -#include -#include - -#include - -class QOpenGLShaderProgram; - -class VideoRenderWidget : public QOpenGLWidget, protected QOpenGLFunctions -{ - Q_OBJECT - -public: - explicit VideoRenderWidget(QWidget *parent = nullptr); - ~VideoRenderWidget() override; - - void setFrame(const VideoFrame &frame); - void setImage(const QImage &image); - void clearFrame(const QString &message = QStringLiteral("暂无画面")); +#pragma once + +#include "videoframe.h" + +#include +#include +#include +#include + +#include + +class QOpenGLShaderProgram; + +class VideoRenderWidget : public QOpenGLWidget, protected QOpenGLFunctions +{ + Q_OBJECT + +public: + explicit VideoRenderWidget(QWidget *parent = nullptr); + ~VideoRenderWidget() override; + + void setFrame(const VideoFrame &frame); + void setImage(const QImage &image); + void clearFrame(const QString &message = QStringLiteral("暂无画面")); bool hasFrame() const { return m_frame.isValid(); } - -protected: - void initializeGL() override; + // Opt-in for calibration panels; other video pages keep their layout. + void setFrameAspectLayoutEnabled(bool enabled); + int heightForWidth(int width) const override; + QSize sizeHint() const override; + +protected: + void initializeGL() override; void paintGL() override; - -private: - void releaseTextures(); - void uploadPlane(unsigned int texture, int unit, int width, int height, - unsigned int format, const QByteArray &data, - int textureIndex); + void resizeEvent(QResizeEvent *event) override; + +private: + void releaseTextures(); + void uploadPlane(unsigned int texture, int unit, int width, int height, + unsigned int format, const QByteArray &data, + int textureIndex); void drawMessage(const QString &message); - - std::unique_ptr m_program; - VideoFrame m_frame; - QString m_message = QStringLiteral("暂无画面"); - unsigned int m_textures[3] = {0, 0, 0}; - int m_textureWidths[3] = {0, 0, 0}; - int m_textureHeights[3] = {0, 0, 0}; - unsigned int m_textureFormats[3] = {0, 0, 0}; - bool m_frameDirty = false; - bool m_glReady = false; -}; + void updateAspectHeight(); + bool m_frameAspectLayout = false; + QSize m_layoutFrameSize{640, 480}; // Placeholder until the first camera frame. + + std::unique_ptr m_program; + VideoFrame m_frame; + QString m_message = QStringLiteral("暂无画面"); + unsigned int m_textures[3] = {0, 0, 0}; + int m_textureWidths[3] = {0, 0, 0}; + int m_textureHeights[3] = {0, 0, 0}; + unsigned int m_textureFormats[3] = {0, 0, 0}; + bool m_frameDirty = false; + bool m_glReady = false; +}; From 3fb913e859915ee477bfb0ed0c1abb70589baa2d Mon Sep 17 00:00:00 2001 From: Gao Date: Thu, 8 Oct 2026 16:32:34 +0800 Subject: [PATCH 05/15] =?UTF-8?q?=E5=88=A0=E9=99=A4=20src/videorenderwidge?= =?UTF-8?q?t.cpp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/videorenderwidget.cpp | 307 -------------------------------------- 1 file changed, 307 deletions(-) delete mode 100644 src/videorenderwidget.cpp diff --git a/src/videorenderwidget.cpp b/src/videorenderwidget.cpp deleted file mode 100644 index bdc2fd0..0000000 --- a/src/videorenderwidget.cpp +++ /dev/null @@ -1,307 +0,0 @@ -#include "videorenderwidget.h" - -#include -#include - -#include -#include - -namespace { -const char *vertexShaderSource = R"( -attribute vec2 position; -attribute vec2 texCoord; -varying vec2 textureCoordinate; -uniform vec2 contentScale; -void main() -{ - gl_Position = vec4(position * contentScale, 0.0, 1.0); - textureCoordinate = texCoord; -} -)"; - -const char *fragmentShaderSource = R"( -#ifdef GL_ES -precision mediump float; -#endif -varying vec2 textureCoordinate; -uniform sampler2D textureY; -uniform sampler2D textureU; -uniform sampler2D textureV; -uniform float pixelFormat; -uniform float scaleY; -uniform float scaleU; -uniform float scaleV; -void main() -{ - if (pixelFormat > 1.5) { - gl_FragColor = texture2D(textureY, textureCoordinate); - return; - } - - float y = texture2D(textureY, - vec2(textureCoordinate.x * scaleY, textureCoordinate.y)).r; - float u; - float v; - if (pixelFormat > 0.5) { - vec4 uv = texture2D(textureU, - vec2(textureCoordinate.x * scaleU, textureCoordinate.y)); - u = uv.r - 0.5; - v = uv.a - 0.5; - } else { - u = texture2D(textureU, - vec2(textureCoordinate.x * scaleU, textureCoordinate.y)).r - 0.5; - v = texture2D(textureV, - vec2(textureCoordinate.x * scaleV, textureCoordinate.y)).r - 0.5; - } - y = 1.16438356 * (y - 0.0625); - gl_FragColor = vec4(y + 1.59602678 * v, - y - 0.39176229 * u - 0.81296764 * v, - y + 2.01723214 * u, 1.0); -} -)"; -} - -VideoRenderWidget::VideoRenderWidget(QWidget *parent) - : QOpenGLWidget(parent) -{ - setAutoFillBackground(false); - setUpdateBehavior(QOpenGLWidget::NoPartialUpdate); -} - -VideoRenderWidget::~VideoRenderWidget() -{ - if (context()) { - makeCurrent(); - releaseTextures(); - doneCurrent(); - } -} - -void VideoRenderWidget::setFrameAspectLayoutEnabled(bool enabled) -{ - m_frameAspectLayout = enabled; - QSizePolicy policy(QSizePolicy::Expanding, enabled ? QSizePolicy::Fixed : QSizePolicy::Expanding); - policy.setHeightForWidth(enabled); - setSizePolicy(policy); - if (enabled) updateAspectHeight(); - else { setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); } - updateGeometry(); -} - -int VideoRenderWidget::heightForWidth(int width) const -{ - return m_frameAspectLayout ? qMax(1, qRound(double(width) * m_layoutFrameSize.height() - / m_layoutFrameSize.width())) : -1; -} - -QSize VideoRenderWidget::sizeHint() const -{ - return m_frameAspectLayout ? QSize(640,heightForWidth(640)) : QOpenGLWidget::sizeHint(); -} - -void VideoRenderWidget::updateAspectHeight() -{ - if (!m_frameAspectLayout) return; - const int wanted = heightForWidth(width()); - if (minimumHeight() != wanted || maximumHeight() != wanted) setFixedHeight(wanted); -} - -void VideoRenderWidget::resizeEvent(QResizeEvent *event) -{ - QOpenGLWidget::resizeEvent(event); - updateAspectHeight(); -} - -void VideoRenderWidget::setFrame(const VideoFrame &frame) -{ - if (!frame.isValid()) - return; - m_frame = frame; - if (m_layoutFrameSize != QSize(frame.width, frame.height)) { - m_layoutFrameSize = QSize(frame.width, frame.height); - updateAspectHeight(); - if (m_frameAspectLayout) updateGeometry(); - } - m_message.clear(); - m_frameDirty = true; - update(); -} - -void VideoRenderWidget::setImage(const QImage &image) -{ - if (image.isNull()) - return; - const QImage converted = image.convertToFormat(QImage::Format_RGBA8888); - VideoFrame frame; - frame.width = converted.width(); - frame.height = converted.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, - converted.constScanLine(row), static_cast(frame.width * 4)); - } - setFrame(frame); -} - -void VideoRenderWidget::clearFrame(const QString &message) -{ - m_frame = VideoFrame(); - m_message = message; - m_frameDirty = false; - update(); -} - -void VideoRenderWidget::initializeGL() -{ - initializeOpenGLFunctions(); - glClearColor(0.055f, 0.067f, 0.078f, 1.0f); - glGenTextures(3, m_textures); - - m_program.reset(new QOpenGLShaderProgram); - if (!m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource) || - !m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource) || - !m_program->link()) { - m_message = QStringLiteral("OpenGL 视频着色器初始化失败:%1").arg(m_program->log()); - m_program.reset(); - return; - } - m_glReady = true; -} - -void VideoRenderWidget::uploadPlane(unsigned int texture, int unit, int width, - int height, unsigned int format, - const QByteArray &data, int textureIndex) -{ - glActiveTexture(GL_TEXTURE0 + unit); - glBindTexture(GL_TEXTURE_2D, texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - if (m_textureWidths[textureIndex] != width || - m_textureHeights[textureIndex] != height || - m_textureFormats[textureIndex] != format) { - glTexImage2D(GL_TEXTURE_2D, 0, static_cast(format), width, height, 0, - format, GL_UNSIGNED_BYTE, data.constData()); - m_textureWidths[textureIndex] = width; - m_textureHeights[textureIndex] = height; - m_textureFormats[textureIndex] = format; - } else { - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, - GL_UNSIGNED_BYTE, data.constData()); - } -} - -void VideoRenderWidget::paintGL() -{ - glClear(GL_COLOR_BUFFER_BIT); - if (!m_glReady || !m_program || !m_frame.isValid()) { - drawMessage(m_message); - return; - } - - // Qt 5.12's ANGLE backend can upload RGBA QImage data with an incorrect - // channel layout. Draw still RGBA frames with the CPU painter instead. - if (m_frame.format == VideoPixelFormat::RGBA) { - const QImage image(reinterpret_cast(m_frame.plane0.constData()), - m_frame.width, m_frame.height, m_frame.stride0, - QImage::Format_RGBA8888); - QPainter painter(this); - painter.fillRect(rect(), QColor(QStringLiteral("#0e1115"))); - QSize target = image.size(); - target.scale(size(), Qt::KeepAspectRatio); - const QRect destination((width() - target.width()) / 2, - (height() - target.height()) / 2, - target.width(), target.height()); - painter.drawImage(destination, image); - m_frameDirty = false; - return; - } - - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - if (m_frameDirty) { - if (m_frame.format == VideoPixelFormat::I420) { - uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, - GL_LUMINANCE, m_frame.plane0, 0); - uploadPlane(m_textures[1], 1, m_frame.stride1, - (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane1, 1); - uploadPlane(m_textures[2], 2, m_frame.stride2, - (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane2, 2); - } else if (m_frame.format == VideoPixelFormat::NV12) { - uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, - GL_LUMINANCE, m_frame.plane0, 0); - uploadPlane(m_textures[1], 1, m_frame.stride1 / 2, - (m_frame.height + 1) / 2, GL_LUMINANCE_ALPHA, - m_frame.plane1, 1); - } else { - uploadPlane(m_textures[0], 0, m_frame.width, m_frame.height, - GL_RGBA, m_frame.plane0, 0); - } - m_frameDirty = false; - } - - const GLfloat vertices[] = { - -1.0f, -1.0f, 0.0f, 1.0f, - 1.0f, -1.0f, 1.0f, 1.0f, - -1.0f, 1.0f, 0.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 0.0f - }; - float scaleX = 1.0f; - float scaleY = 1.0f; - const float frameAspect = static_cast(m_frame.width) / m_frame.height; - const float widgetAspect = width() > 0 && height() > 0 - ? static_cast(width()) / height() : frameAspect; - if (frameAspect > widgetAspect) - scaleY = widgetAspect / frameAspect; - else - scaleX = frameAspect / widgetAspect; - - m_program->bind(); - m_program->setUniformValue("contentScale", scaleX, scaleY); - m_program->setUniformValue("textureY", 0); - m_program->setUniformValue("textureU", 1); - m_program->setUniformValue("textureV", 2); - m_program->setUniformValue("pixelFormat", - m_frame.format == VideoPixelFormat::NV12 ? 1.0f : - m_frame.format == VideoPixelFormat::RGBA ? 2.0f : 0.0f); - m_program->setUniformValue("scaleY", m_frame.format == VideoPixelFormat::RGBA - ? 1.0f : static_cast(m_frame.width) / m_frame.stride0); - m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::NV12 - ? static_cast((m_frame.width + 1) / 2) / (m_frame.stride1 / 2) - : static_cast((m_frame.width + 1) / 2) / m_frame.stride1); - m_program->setUniformValue("scaleV", m_frame.format == VideoPixelFormat::I420 - ? static_cast((m_frame.width + 1) / 2) / m_frame.stride2 : 1.0f); - const int position = m_program->attributeLocation("position"); - const int texCoord = m_program->attributeLocation("texCoord"); - m_program->enableAttributeArray(position); - m_program->enableAttributeArray(texCoord); - m_program->setAttributeArray(position, GL_FLOAT, vertices, 2, 4 * sizeof(GLfloat)); - m_program->setAttributeArray(texCoord, GL_FLOAT, vertices + 2, 2, - 4 * sizeof(GLfloat)); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - m_program->disableAttributeArray(position); - m_program->disableAttributeArray(texCoord); - m_program->release(); -} - -void VideoRenderWidget::drawMessage(const QString &message) -{ - if (message.isEmpty()) - return; - QPainter painter(this); - painter.setPen(QColor(QStringLiteral("#8d98a5"))); - painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, message); -} - -void VideoRenderWidget::releaseTextures() -{ - if (m_textures[0]) { - glDeleteTextures(3, m_textures); - m_textures[0] = m_textures[1] = m_textures[2] = 0; - std::fill(m_textureWidths, m_textureWidths + 3, 0); - std::fill(m_textureHeights, m_textureHeights + 3, 0); - std::fill(m_textureFormats, m_textureFormats + 3, 0); - } -} From 3c877f77c7cdee0d0d4731c04158e1213309a9f5 Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Fri, 9 Oct 2026 10:36:15 +0800 Subject: [PATCH 06/15] update arm config --- CmvrControlStation.pro | 4 + protos/cmvr/api/dexhand_command.proto | 4 +- .../dexhand_config/dexhand_config.proto | 13 +- src/jointfloweditor.cpp | 658 ++++++++++++++++++ src/jointfloweditor.h | 78 +++ src/mainwindow.cpp | 283 ++++++-- src/mainwindow.h | 39 +- src/mainwindow_ui.cpp | 371 +++++++--- src/robotclient.cpp | 279 ++++++++ src/robotclient.h | 17 + src/tactileheatmapwidget.cpp | 87 +++ src/tactileheatmapwidget.h | 20 + 12 files changed, 1685 insertions(+), 168 deletions(-) create mode 100644 src/jointfloweditor.cpp create mode 100644 src/jointfloweditor.h create mode 100644 src/tactileheatmapwidget.cpp create mode 100644 src/tactileheatmapwidget.h diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index d2633e4..85e1624 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -245,6 +245,8 @@ SOURCES += \ src/quictestserver.cpp \ src/rpcservicewidget.cpp \ src/robotclient.cpp \ + src/tactileheatmapwidget.cpp \ + src/jointfloweditor.cpp \ src/trendwidget.cpp \ src/urdfviewerwidget.cpp \ src/videodecoder.cpp \ @@ -258,6 +260,8 @@ HEADERS += \ src/quictestserver.h \ src/rpcservicewidget.h \ src/robotclient.h \ + src/tactileheatmapwidget.h \ + src/jointfloweditor.h \ src/trendwidget.h \ src/uiicons.h \ src/urdfviewerwidget.h \ diff --git a/protos/cmvr/api/dexhand_command.proto b/protos/cmvr/api/dexhand_command.proto index 9d65a7f..8ff1bb3 100644 --- a/protos/cmvr/api/dexhand_command.proto +++ b/protos/cmvr/api/dexhand_command.proto @@ -58,6 +58,8 @@ message SensorData { message DexHandState { bool is_initialized = 1; // 是否初始化 repeated FreedomState hands = 2; // 包含多个自由度状态 + bool has_tactile_feedback = 3; // 是否具备真实触觉传感器反馈能力 + string model = 4; // 设备型号,仅作为描述信息 } message GetDexHandStateCommand { @@ -146,4 +148,4 @@ message GetSensorDataStreamCommand { CommandHeader.Feedback header = 1; repeated SensorData sensor = 2;//所有传感器的数据 } -} \ No newline at end of file +} diff --git a/protos/cmvr/config/dexhand_config/dexhand_config.proto b/protos/cmvr/config/dexhand_config/dexhand_config.proto index 0cbc267..9d894d0 100644 --- a/protos/cmvr/config/dexhand_config/dexhand_config.proto +++ b/protos/cmvr/config/dexhand_config/dexhand_config.proto @@ -43,14 +43,25 @@ message ZeroSimTouchDexHand { string id = 1; } +message OYMotionAP001Config { + string id = 1; + string can_interface = 2; + uint32 hand_id = 3; + uint32 master_id = 4; + uint32 command_timeout_ms = 5; +} + message DexHandDeviceConfig { string id = 1; - reserved 2; + string model = 2; + optional bool has_tactile_feedback = 3; oneof backend { RH56DFTPDexHandConfig rh56dftp = 10; PX6AXGen3 px_6ax_gen3 = 11; ZeroSimTouchDexHand zero_sim_touch = 12; + // Shared OYMotion backend for AP001, LiteS001 and compatible hands. + OYMotionAP001Config oymotion_ap001 = 13; } } diff --git a/src/jointfloweditor.cpp b/src/jointfloweditor.cpp new file mode 100644 index 0000000..f2849f6 --- /dev/null +++ b/src/jointfloweditor.cpp @@ -0,0 +1,658 @@ +#include "jointfloweditor.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr qreal kNodeWidth = 190.0; +constexpr qreal kNodeHeight = 76.0; + +class FlowGraphicsView final : public QGraphicsView +{ +public: + explicit FlowGraphicsView(QGraphicsScene *scene, QWidget *parent = nullptr) + : QGraphicsView(scene, parent) + { + } + +protected: + void mousePressEvent(QMouseEvent *event) override + { + if (event->button() == Qt::RightButton) { + m_panning = true; + m_lastPosition = event->pos(); + viewport()->setCursor(Qt::ClosedHandCursor); + event->accept(); + return; + } + QGraphicsView::mousePressEvent(event); + } + + void mouseMoveEvent(QMouseEvent *event) override + { + if (m_panning) { + const QPoint delta = event->pos() - m_lastPosition; + m_lastPosition = event->pos(); + horizontalScrollBar()->setValue(horizontalScrollBar()->value() - delta.x()); + verticalScrollBar()->setValue(verticalScrollBar()->value() - delta.y()); + event->accept(); + return; + } + QGraphicsView::mouseMoveEvent(event); + } + + void mouseReleaseEvent(QMouseEvent *event) override + { + if (event->button() == Qt::RightButton && m_panning) { + m_panning = false; + viewport()->unsetCursor(); + event->accept(); + return; + } + QGraphicsView::mouseReleaseEvent(event); + } + +private: + bool m_panning = false; + QPoint m_lastPosition; +}; + +class FlowCardItem final : public QGraphicsItem +{ +public: + FlowCardItem(QString id, QString title, QString subtitle, bool loop, bool active, + bool collapsed, + std::function moved, + std::function edit, + std::function toggleCollapsed) + : m_id(std::move(id)), m_title(std::move(title)), m_subtitle(std::move(subtitle)), + m_loop(loop), m_active(active), m_collapsed(collapsed), + m_moved(std::move(moved)), m_edit(std::move(edit)), + m_toggleCollapsed(std::move(toggleCollapsed)) + { + setFlags(ItemIsMovable | ItemIsSelectable | ItemSendsGeometryChanges); + setAcceptHoverEvents(true); + setCursor(Qt::OpenHandCursor); + setZValue(2.0); + } + + QRectF boundingRect() const override { return QRectF(0, 0, kNodeWidth, kNodeHeight); } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override + { + painter->setRenderHint(QPainter::Antialiasing); + const QColor fill = m_loop ? QColor("#262044") : QColor("#163447"); + const QColor border = m_active ? QColor("#56d39b") + : (isSelected() ? QColor("#64b5f6") : QColor("#52606d")); + painter->setPen(QPen(border, m_active ? 3.0 : 1.5)); + painter->setBrush(fill); + painter->drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), 10, 10); + painter->setPen(QColor("#f2f5f7")); + QFont titleFont = painter->font(); + titleFont.setBold(true); + painter->setFont(titleFont); + painter->drawText(QRectF(14, 10, kNodeWidth - (m_loop ? 58 : 28), 25), + Qt::AlignLeft | Qt::AlignVCenter, + m_title); + if (m_loop) { + const QColor buttonFill = m_collapsePressed ? QColor("#2563a8") + : m_collapseHovered ? QColor("#244d78") : QColor("#17263a"); + const QColor buttonBorder = m_collapseHovered || m_collapsePressed + ? QColor("#64b5f6") : QColor("#71869b"); + painter->setPen(QPen(buttonBorder, 1.4)); + painter->setBrush(buttonFill); + painter->drawRoundedRect(collapseButtonRect(), 5, 5); + painter->setPen(QPen(QColor("#f4f8fc"), 1.8, + Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + const QPointF center = collapseButtonRect().center(); + QPolygonF arrow; + if (m_collapsed) { + arrow << QPointF(center.x() - 3.5, center.y() - 5) + << QPointF(center.x() + 2.0, center.y()) + << QPointF(center.x() - 3.5, center.y() + 5); + } else { + arrow << QPointF(center.x() - 5, center.y() - 3.0) + << QPointF(center.x(), center.y() + 2.5) + << QPointF(center.x() + 5, center.y() - 3.0); + } + painter->drawPolyline(arrow); + } + painter->setFont(QFont()); + painter->setPen(QColor("#aeb8c2")); + painter->drawText(QRectF(14, 38, kNodeWidth - 28, 26), Qt::AlignLeft | Qt::AlignVCenter, + m_subtitle); + } + +protected: + void mousePressEvent(QGraphicsSceneMouseEvent *event) override + { + if (m_loop && event->button() == Qt::LeftButton + && collapseButtonRect().contains(event->pos())) { + m_collapsePressed = true; + update(collapseButtonRect().adjusted(-2, -2, 2, 2)); + event->accept(); + return; + } + setCursor(Qt::ClosedHandCursor); + QGraphicsItem::mousePressEvent(event); + } + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override + { + if (m_collapsePressed) { + const bool activate = collapseButtonRect().contains(event->pos()); + m_collapsePressed = false; + update(collapseButtonRect().adjusted(-2, -2, 2, 2)); + if (activate && m_toggleCollapsed) + m_toggleCollapsed(m_id); + event->accept(); + return; + } + setCursor(Qt::OpenHandCursor); + QGraphicsItem::mouseReleaseEvent(event); + if (m_moved) + m_moved(m_id, pos()); + } + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override + { + if (m_edit) + m_edit(m_id); + event->accept(); + } + void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override + { + const bool overButton = m_loop && collapseButtonRect().contains(event->pos()); + if (m_collapseHovered != overButton) { + m_collapseHovered = overButton; + update(collapseButtonRect().adjusted(-2, -2, 2, 2)); + } + setCursor(overButton ? Qt::PointingHandCursor : Qt::OpenHandCursor); + QGraphicsItem::hoverMoveEvent(event); + } + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override + { + if (m_collapseHovered) { + m_collapseHovered = false; + update(collapseButtonRect().adjusted(-2, -2, 2, 2)); + } + setCursor(Qt::OpenHandCursor); + QGraphicsItem::hoverLeaveEvent(event); + } + +private: + QRectF collapseButtonRect() const { return QRectF(kNodeWidth - 34, 9, 22, 22); } + + QString m_id; + QString m_title; + QString m_subtitle; + bool m_loop = false; + bool m_active = false; + bool m_collapsed = false; + bool m_collapseHovered = false; + bool m_collapsePressed = false; + std::function m_moved; + std::function m_edit; + std::function m_toggleCollapsed; +}; +} + +JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent) +{ + QVBoxLayout *layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + m_scene = new QGraphicsScene(this); + m_scene->setBackgroundBrush(QColor("#10161d")); + m_view = new FlowGraphicsView(m_scene, this); + m_view->setRenderHint(QPainter::Antialiasing); + m_view->setDragMode(QGraphicsView::RubberBandDrag); + m_view->setMinimumHeight(230); + layout->addWidget(m_view); + connect(m_scene, &QGraphicsScene::selectionChanged, this, [this]() { + for (QGraphicsItem *item : m_scene->selectedItems()) { + const QString id = item->data(0).toString(); + if (!id.isEmpty()) { m_selectedNodeId = id; return; } + } + }); +} + +void JointFlowEditor::addSingleNode(const QString &nodeName, const QString &pointName, + double intervalSeconds) +{ + if (nodeName.trimmed().isEmpty() || pointName.isEmpty()) + return; + Node node; + node.id = QUuid::createUuid().toString(QUuid::WithoutBraces); + node.type = SingleNode; + node.nodeName = nodeName.trimmed(); + node.pointName = pointName; + node.intervalSeconds = qMax(0.0, intervalSeconds); + const Node *insertionParent = nodeById(m_insertionParentId); + node.parentId = insertionParent && insertionParent->type == LoopNode + ? insertionParent->id : QString(); + node.order = childrenOf(node.parentId).size(); + node.position = QPointF(40 + node.order * 220, 40 + (node.parentId.isEmpty() ? 0 : 100)); + m_nodes.append(node); + m_selectedNodeId = node.id; + rebuildScene(); + emit changed(); +} + +void JointFlowEditor::addLoopNode(const QString &nodeName, int loopCount, + double intervalSeconds) +{ + if (nodeName.trimmed().isEmpty()) + return; + Node node; + node.id = QUuid::createUuid().toString(QUuid::WithoutBraces); + node.type = LoopNode; + node.nodeName = nodeName.trimmed(); + node.loopCount = qMax(1, loopCount); + node.intervalSeconds = qMax(0.0, intervalSeconds); + const Node *insertionParent = nodeById(m_insertionParentId); + node.parentId = insertionParent && insertionParent->type == LoopNode + ? insertionParent->id : QString(); + node.order = childrenOf(node.parentId).size(); + node.position = QPointF(40 + node.order * 220, 40 + (node.parentId.isEmpty() ? 0 : 100)); + m_nodes.append(node); + m_selectedNodeId = node.id; + rebuildScene(); + emit changed(); +} + +void JointFlowEditor::removeSelectedNode() +{ + const QString id = selectedNodeId(); + if (id.isEmpty()) + return; + QStringList removing{id}; + for (int i = 0; i < removing.size(); ++i) { + for (const Node &node : m_nodes) + if (node.parentId == removing.at(i)) + removing.append(node.id); + } + QString parentId; + if (const Node *node = nodeById(id)) + parentId = node->parentId; + for (int i = m_nodes.size() - 1; i >= 0; --i) + if (removing.contains(m_nodes.at(i).id)) + m_nodes.removeAt(i); + if (removing.contains(m_insertionParentId)) + setInsertionAtRoot(); + m_selectedNodeId.clear(); + normalizeOrders(parentId); + rebuildScene(); + emit changed(); +} + +void JointFlowEditor::removePointReferences(const QStringList &pointNames) +{ + for (int i = m_nodes.size() - 1; i >= 0; --i) + if (m_nodes.at(i).type == SingleNode && pointNames.contains(m_nodes.at(i).pointName)) + m_nodes.removeAt(i); + rebuildScene(); + emit changed(); +} + +bool JointFlowEditor::isEmpty() const { return m_nodes.isEmpty(); } + +QList JointFlowEditor::expandedSteps( + QString *error, int maximumSteps) const +{ + QList result; + for (const Node *node : childrenOf(QString())) { + if (!appendExecution(*node, result, error, maximumSteps)) + return {}; + } + return result; +} + +bool JointFlowEditor::appendExecution(const Node &node, QList &steps, + QString *error, int maximumSteps) const +{ + if (node.type == SingleNode) { + if (steps.size() >= maximumSteps) { + if (error) *error = QStringLiteral("展开后的流程超过 %1 步").arg(maximumSteps); + return false; + } + steps.append({node.pointName, node.intervalSeconds, node.id}); + return true; + } + const QList children = childrenOf(node.id); + if (children.isEmpty()) { + if (error) *error = QStringLiteral("存在没有子节点的循环节点"); + return false; + } + for (int repeat = 0; repeat < node.loopCount; ++repeat) + for (const Node *child : children) + if (!appendExecution(*child, steps, error, maximumSteps)) return false; + if (!steps.isEmpty()) + steps.last().intervalSeconds += node.intervalSeconds; + return true; +} + +QJsonArray JointFlowEditor::toJson() const +{ + QJsonArray array; + for (const Node &node : m_nodes) + appendJsonNode(array, node); + return array; +} + +void JointFlowEditor::appendJsonNode(QJsonArray &target, const Node &node) const +{ + QJsonObject object; + object.insert(QStringLiteral("id"), node.id); + object.insert(QStringLiteral("type"), node.type == LoopNode ? QStringLiteral("loop") + : QStringLiteral("single")); + object.insert(QStringLiteral("nodeName"), node.nodeName); + object.insert(QStringLiteral("pointName"), node.pointName); + object.insert(QStringLiteral("loopCount"), node.loopCount); + object.insert(QStringLiteral("intervalSeconds"), node.intervalSeconds); + object.insert(QStringLiteral("parentId"), node.parentId); + object.insert(QStringLiteral("order"), node.order); + object.insert(QStringLiteral("x"), node.position.x()); + object.insert(QStringLiteral("y"), node.position.y()); + object.insert(QStringLiteral("collapsed"), node.collapsed); + target.append(object); +} + +bool JointFlowEditor::fromJson(const QJsonArray &array) +{ + QList loaded; + for (const QJsonValue &value : array) { + const QJsonObject object = value.toObject(); + Node node; + node.id = object.value(QStringLiteral("id")).toString(); + if (node.id.isEmpty()) return false; + node.type = object.value(QStringLiteral("type")).toString() == QStringLiteral("loop") + ? LoopNode : SingleNode; + node.nodeName = object.value(QStringLiteral("nodeName")).toString().trimmed(); + node.pointName = object.value(QStringLiteral("pointName")).toString(); + if (node.nodeName.isEmpty()) + node.nodeName = node.type == LoopNode ? QStringLiteral("循环节点") : node.pointName; + node.loopCount = qMax(1, object.value(QStringLiteral("loopCount")).toInt(1)); + node.intervalSeconds = qMax(0.0, object.value(QStringLiteral("intervalSeconds")).toDouble()); + node.parentId = object.value(QStringLiteral("parentId")).toString(); + node.order = object.value(QStringLiteral("order")).toInt(); + node.position = QPointF(object.value(QStringLiteral("x")).toDouble(), + object.value(QStringLiteral("y")).toDouble()); + node.collapsed = object.value(QStringLiteral("collapsed")).toBool(false); + loaded.append(node); + } + m_nodes = loaded; + m_selectedNodeId.clear(); + m_insertionParentId.clear(); + rebuildScene(); + emit insertionContextChanged(QStringLiteral("根流程")); + return true; +} + +void JointFlowEditor::clear() +{ + m_nodes.clear(); + m_selectedNodeId.clear(); + m_insertionParentId.clear(); + rebuildScene(); + emit insertionContextChanged(QStringLiteral("根流程")); +} +void JointFlowEditor::setActiveNode(const QString &nodeId) { m_activeNodeId = nodeId; rebuildScene(); } + +void JointFlowEditor::setAvailablePointNames(const QStringList &pointNames) +{ + m_availablePointNames = pointNames; + m_availablePointNames.removeDuplicates(); +} + +void JointFlowEditor::setInsertionAtRoot() +{ + m_insertionParentId.clear(); + emit insertionContextChanged(QStringLiteral("根流程")); +} + +bool JointFlowEditor::useSelectedLoopAsInsertionParent() +{ + const Node *selected = nodeById(selectedNodeId()); + if (!selected || selected->type != LoopNode) + return false; + m_insertionParentId = selected->id; + emit insertionContextChanged(selected->nodeName); + return true; +} + +JointFlowEditor::Node *JointFlowEditor::nodeById(const QString &id) +{ for (Node &node : m_nodes) if (node.id == id) return &node; return nullptr; } +const JointFlowEditor::Node *JointFlowEditor::nodeById(const QString &id) const +{ for (const Node &node : m_nodes) if (node.id == id) return &node; return nullptr; } + +QList JointFlowEditor::childrenOf(const QString &parentId) const +{ + QList result; + for (const Node &node : m_nodes) if (node.parentId == parentId) result.append(&node); + std::sort(result.begin(), result.end(), [](const Node *a, const Node *b) { + return a->order < b->order; + }); + return result; +} + +QString JointFlowEditor::selectedNodeId() const +{ + for (QGraphicsItem *item : m_scene->selectedItems()) + if (!item->data(0).toString().isEmpty()) return item->data(0).toString(); + return m_selectedNodeId; +} + +void JointFlowEditor::editNode(const QString &id) +{ + Node *node = nodeById(id); + if (!node) return; + + QDialog dialog(this); + dialog.setWindowTitle(node->type == SingleNode + ? QStringLiteral("编辑单步节点") : QStringLiteral("编辑循环节点")); + dialog.setMinimumWidth(420); + QVBoxLayout *dialogLayout = new QVBoxLayout(&dialog); + QFormLayout *form = new QFormLayout; + QLineEdit *nameEdit = new QLineEdit(node->nodeName, &dialog); + form->addRow(QStringLiteral("节点名称"), nameEdit); + + QComboBox *pointCombo = nullptr; + QSpinBox *loopCountSpin = nullptr; + if (node->type == SingleNode) { + QStringList pointNames = m_availablePointNames; + if (!pointNames.contains(node->pointName)) + pointNames.prepend(node->pointName); + pointCombo = new QComboBox(&dialog); + pointCombo->addItems(pointNames); + pointCombo->setCurrentText(node->pointName); + form->addRow(QStringLiteral("执行点位"), pointCombo); + } else { + loopCountSpin = new QSpinBox(&dialog); + loopCountSpin->setRange(1, 10000); + loopCountSpin->setValue(node->loopCount); + form->addRow(QStringLiteral("循环次数"), loopCountSpin); + } + QDoubleSpinBox *intervalSpin = new QDoubleSpinBox(&dialog); + intervalSpin->setRange(0.0, 3600.0); + intervalSpin->setDecimals(1); + intervalSpin->setSingleStep(0.1); + intervalSpin->setSuffix(QStringLiteral(" s")); + intervalSpin->setValue(node->intervalSeconds); + form->addRow(node->type == LoopNode ? QStringLiteral("循环结束后等待") + : QStringLiteral("执行结束后等待"), + intervalSpin); + dialogLayout->addLayout(form); + + QDialogButtonBox *buttons = new QDialogButtonBox( + QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); + buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("保存")); + buttons->button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消")); + connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + dialogLayout->addWidget(buttons); + + if (dialog.exec() != QDialog::Accepted || nameEdit->text().trimmed().isEmpty()) + return; + node->nodeName = nameEdit->text().trimmed(); + if (pointCombo) + node->pointName = pointCombo->currentText(); + if (loopCountSpin) + node->loopCount = loopCountSpin->value(); + node->intervalSeconds = intervalSpin->value(); + rebuildScene(); + emit changed(); +} + +void JointFlowEditor::toggleLoopCollapsed(const QString &id) +{ + Node *node = nodeById(id); + if (!node || node->type != LoopNode) + return; + node->collapsed = !node->collapsed; + QTimer::singleShot(0, this, [this]() { + rebuildScene(); + emit changed(); + }); +} + +void JointFlowEditor::moveNode(const QString &id, const QPointF &position) +{ + Node *node = nodeById(id); + if (!node) return; + const QString originalParent = node->parentId; + const QPointF center = position + QPointF(kNodeWidth / 2.0, kNodeHeight / 2.0); + if (!originalParent.isEmpty()) { + for (const Node &candidate : m_nodes) { + if (candidate.id == id || candidate.parentId != originalParent) + continue; + if (QRectF(candidate.position, QSizeF(kNodeWidth, kNodeHeight)).contains(center)) { + rebuildScene(); + return; + } + } + } + node->position = position; + QString newParent = originalParent; + // Once a node belongs to a loop, dragging only changes its order inside that loop. + // This prevents an existing child from accidentally becoming a child of a sibling loop. + if (originalParent.isEmpty()) { + for (const Node &candidate : m_nodes) { + if (candidate.id == id || candidate.type != LoopNode) + continue; + if (!QRectF(candidate.position, QSizeF(kNodeWidth, kNodeHeight)).contains(center)) + continue; + bool createsCycle = false; + const Node *ancestor = &candidate; + while (ancestor && !ancestor->parentId.isEmpty()) { + if (ancestor->parentId == id) { createsCycle = true; break; } + ancestor = nodeById(ancestor->parentId); + } + if (!createsCycle) { + newParent = candidate.id; + break; + } + } + } + node = nodeById(id); + if (node) + node->parentId = newParent; + QStringList parents{newParent}; + for (const Node &candidate : m_nodes) + if (!parents.contains(candidate.parentId)) parents.append(candidate.parentId); + for (const QString &parent : parents) { + QList siblings; + for (Node &candidate : m_nodes) + if (candidate.parentId == parent) siblings.append(&candidate); + std::sort(siblings.begin(), siblings.end(), [](const Node *a, const Node *b) { + return a->position.x() == b->position.x() + ? a->position.y() < b->position.y() : a->position.x() < b->position.x(); + }); + for (int order = 0; order < siblings.size(); ++order) + siblings.at(order)->order = order; + } + rebuildScene(); + emit changed(); +} + +void JointFlowEditor::normalizeOrders(const QString &parentId) +{ + int order = 0; + for (const Node *child : childrenOf(parentId)) + if (Node *node = nodeById(child->id)) node->order = order++; +} + +void JointFlowEditor::rebuildScene() +{ + m_scene->clear(); + QHash cards; + for (const Node &node : m_nodes) { + bool hiddenByCollapsedAncestor = false; + const Node *ancestor = node.parentId.isEmpty() ? nullptr : nodeById(node.parentId); + while (ancestor) { + if (ancestor->collapsed) { + hiddenByCollapsedAncestor = true; + break; + } + ancestor = ancestor->parentId.isEmpty() ? nullptr : nodeById(ancestor->parentId); + } + if (hiddenByCollapsedAncestor) + continue; + const QString title = node.nodeName; + const QString executionUnit = node.type == LoopNode + ? QStringLiteral("循环 × %1").arg(node.loopCount) : node.pointName; + const QString subtitle = QStringLiteral("执行:%1 · 等待 %2 s") + .arg(executionUnit).arg(node.intervalSeconds, 0, 'f', 1); + auto *card = new FlowCardItem(node.id, title, subtitle, node.type == LoopNode, + node.id == m_activeNodeId, node.collapsed, + [this](const QString &id, const QPointF &pos) { moveNode(id, pos); }, + [this](const QString &id) { editNode(id); }, + [this](const QString &id) { toggleLoopCollapsed(id); }); + card->setData(0, node.id); + card->setPos(node.position); + m_scene->addItem(card); + if (node.id == m_selectedNodeId) + card->setSelected(true); + cards.insert(node.id, card); + } + for (const Node &node : m_nodes) { + if (node.parentId.isEmpty() || !cards.contains(node.parentId) || !cards.contains(node.id)) + continue; + const QPointF from = cards.value(node.parentId)->sceneBoundingRect().center(); + const QPointF to = cards.value(node.id)->sceneBoundingRect().center(); + m_scene->addLine(QLineF(from, to), QPen(QColor("#667788"), 2.0)); + } + QStringList parentIds{QString()}; + for (const Node &node : m_nodes) + if (!parentIds.contains(node.parentId)) parentIds.append(node.parentId); + for (const QString &parentId : parentIds) { + const QList siblings = childrenOf(parentId); + for (int i = 1; i < siblings.size(); ++i) { + const Node *previous = siblings.at(i - 1); + const Node *current = siblings.at(i); + if (!cards.contains(previous->id) || !cards.contains(current->id)) continue; + const QPointF from = cards.value(previous->id)->sceneBoundingRect().center(); + const QPointF to = cards.value(current->id)->sceneBoundingRect().center(); + m_scene->addLine(QLineF(from, to), QPen(QColor("#3f8db3"), 1.5, Qt::DashLine)); + } + } + m_scene->setSceneRect(m_scene->itemsBoundingRect().adjusted(-60, -60, 60, 60)); +} diff --git a/src/jointfloweditor.h b/src/jointfloweditor.h new file mode 100644 index 0000000..0cd1aeb --- /dev/null +++ b/src/jointfloweditor.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include + +class QGraphicsScene; +class QGraphicsView; + +class JointFlowEditor : public QWidget +{ + Q_OBJECT +public: + struct ExecutionStep { + QString pointName; + double intervalSeconds = 0.0; + QString nodeId; + }; + + explicit JointFlowEditor(QWidget *parent = nullptr); + + void addSingleNode(const QString &nodeName, const QString &pointName, + double intervalSeconds); + void addLoopNode(const QString &nodeName, int loopCount, double intervalSeconds); + void removeSelectedNode(); + void removePointReferences(const QStringList &pointNames); + bool isEmpty() const; + QList expandedSteps(QString *error = nullptr, + int maximumSteps = 100000) const; + QJsonArray toJson() const; + bool fromJson(const QJsonArray &array); + void clear(); + void setActiveNode(const QString &nodeId); + void setAvailablePointNames(const QStringList &pointNames); + void setInsertionAtRoot(); + bool useSelectedLoopAsInsertionParent(); + +signals: + void changed(); + void insertionContextChanged(const QString &description); + +private: + enum NodeType { SingleNode, LoopNode }; + struct Node { + QString id; + NodeType type = SingleNode; + QString nodeName; + QString pointName; + int loopCount = 1; + double intervalSeconds = 0.0; + QString parentId; + int order = 0; + QPointF position; + bool collapsed = false; + }; + + Node *nodeById(const QString &id); + const Node *nodeById(const QString &id) const; + QList childrenOf(const QString &parentId) const; + QString selectedNodeId() const; + void editNode(const QString &id); + void toggleLoopCollapsed(const QString &id); + void moveNode(const QString &id, const QPointF &position); + void normalizeOrders(const QString &parentId); + void rebuildScene(); + void appendJsonNode(QJsonArray &target, const Node &node) const; + bool appendExecution(const Node &node, QList &steps, + QString *error, int maximumSteps) const; + + QList m_nodes; + QGraphicsScene *m_scene = nullptr; + QGraphicsView *m_view = nullptr; + QString m_activeNodeId; + QString m_selectedNodeId; + QString m_insertionParentId; + QStringList m_availablePointNames; +}; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 43a7589..e0cabb8 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,4 +1,6 @@ #include "mainwindow.h" +#include "tactileheatmapwidget.h" +#include "jointfloweditor.h" #include "videorenderwidget.h" #include "audiostreammanager.h" @@ -26,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -407,7 +410,7 @@ MainWindow::MainWindow(QWidget *parent) 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(createDexHandPage()); m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.BioHeadService"))); m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.HlcService"))); m_pages->addWidget(createRpcPage(QStringLiteral("cmvr.api.TestService"))); @@ -442,6 +445,17 @@ MainWindow::MainWindow(QWidget *parent) m_cameraDeviceCombo->setCurrentIndex(index); } break; + case 3: + pageIndex = 6; + if (m_dexHandDeviceCombo) { + int index = m_dexHandDeviceCombo->findData(deviceId); + if (index < 0) { + m_dexHandDeviceCombo->addItem(deviceId, deviceId); + index = m_dexHandDeviceCombo->count() - 1; + } + m_dexHandDeviceCombo->setCurrentIndex(index); + } + break; case 0: pageIndex = 3; if (m_agvIdEdit) m_agvIdEdit->setText(deviceId); @@ -454,9 +468,6 @@ MainWindow::MainWindow(QWidget *parent) pageIndex = 5; if (m_microphoneIdEdit) m_microphoneIdEdit->setText(deviceId); break; - case 3: - pageIndex = 6; - break; case 8: pageIndex = 7; break; @@ -534,6 +545,16 @@ MainWindow::MainWindow(QWidget *parent) m_client->setCameraStreamCodec(isH265 ? QStringLiteral("h265") : QStringLiteral("h264")); }); + connect(m_client, &RobotClient::dexHandStatusReceived, + this, &MainWindow::updateDexHandStatus); + connect(m_client, &RobotClient::dexHandTactileReceived, + this, &MainWindow::updateDexHandTactile); + connect(m_client, &RobotClient::dexHandTactileStreamStateChanged, + this, [this](bool running, const QString &detail) { + if (m_dexHandTactileStateLabel) m_dexHandTactileStateLabel->setText(detail); + if (m_dexHandTactileStartButton) m_dexHandTactileStartButton->setEnabled(!running); + if (m_dexHandTactileStopButton) m_dexHandTactileStopButton->setEnabled(running); + }); connect(m_client, &RobotClient::videoFrameReceived, this, &MainWindow::updateVideoFrame); connect(m_client, &RobotClient::cameraStreamStateChanged, this, &MainWindow::updateCameraStreamState); @@ -1476,6 +1497,34 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk, && (previousCameraId != cameraId || m_cameraCodecCombo->toolTip().isEmpty())) m_client->requestCameraStatus(cameraId); } + + if (m_dexHandDeviceCombo) { + const QString previousHandId = m_dexHandDeviceCombo->currentData().toString(); + const QSignalBlocker blocker(m_dexHandDeviceCombo); + m_dexHandDeviceCombo->clear(); + for (const QVariant &value : devices) { + const QVariantMap device = value.toMap(); + if (device.value(QStringLiteral("type")).toInt() != 3) + continue; + const QString deviceId = device.value(QStringLiteral("deviceId")).toString(); + if (deviceId.isEmpty()) + continue; + const QString driver = device.value(QStringLiteral("driverType")).toString(); + m_dexHandDeviceCombo->addItem( + driver.isEmpty() ? deviceId : QStringLiteral("%1 · %2").arg(deviceId, driver), + deviceId); + m_dexHandDeviceCombo->setItemData(m_dexHandDeviceCombo->count() - 1, + driver, Qt::UserRole + 1); + } + int index = m_dexHandDeviceCombo->findData(previousHandId); + if (index < 0 && m_dexHandDeviceCombo->count() > 0) + index = 0; + if (index >= 0) + m_dexHandDeviceCombo->setCurrentIndex(index); + const QString selectedHandId = m_dexHandDeviceCombo->currentData().toString(); + if (!selectedHandId.isEmpty()) + m_client->requestDexHandStatus(selectedHandId); + } } void MainWindow::updateSystemInfo(const QVariantMap &info) @@ -1488,6 +1537,94 @@ void MainWindow::updateSystemInfo(const QVariantMap &info) m_systemOsValue->setText(platform); } +void MainWindow::updateDexHandStatus(const QString &deviceId, bool initialized, + bool hasTactileFeedback, + const QString &model, + const QVariantList &freedoms) +{ + if (!m_dexHandDeviceCombo + || m_dexHandDeviceCombo->currentData().toString() != deviceId) + return; + const QString modelText = model.isEmpty() ? QStringLiteral("未知型号") : model; + m_dexHandStateLabel->setText(initialized + ? QStringLiteral("%1 · 已初始化 · %2") + .arg(modelText, + hasTactileFeedback ? QStringLiteral("支持触觉") + : QStringLiteral("无触觉")) + : QStringLiteral("%1 · 未初始化").arg(modelText)); + m_dexHandStateLabel->setProperty("state", initialized ? QStringLiteral("ok") + : QStringLiteral("warn")); + if (m_dexHandHasTactileFeedback && !hasTactileFeedback) + m_client->stopDexHandTactileStream(); + m_dexHandHasTactileFeedback = hasTactileFeedback; + if (m_dexHandTactilePanel) + m_dexHandTactilePanel->setVisible(hasTactileFeedback); + m_dexHandStateTable->setRowCount(6); + const QString driver = m_dexHandDeviceCombo->currentData(Qt::UserRole + 1).toString(); + const bool oymotion = driver.contains(QStringLiteral("OYMotion"), + Qt::CaseInsensitive); + const QStringList names = {QStringLiteral("小拇指"), QStringLiteral("无名指"), + QStringLiteral("中指"), QStringLiteral("食指"), + QStringLiteral("大拇指弯曲"), QStringLiteral("大拇指旋转")}; + for (int row = 0; row < 6; ++row) { + QVariantMap freedom; + for (const QVariant &value : freedoms) { + if (value.toMap().value(QStringLiteral("id")).toInt() == row) { + freedom = value.toMap(); + break; + } + } + const QStringList values = { + names.at(row), oymotion + ? QStringLiteral("%1°").arg( + freedom.value(QStringLiteral("angle")).toInt() / 100.0, 0, 'f', 2) + : QString::number(freedom.value(QStringLiteral("angle")).toInt()), + QString::number(freedom.value(QStringLiteral("position")).toInt()), + QString::number(freedom.value(QStringLiteral("speed")).toInt()), + QString::number(freedom.value(QStringLiteral("force")).toInt()), + QString::number(freedom.value(QStringLiteral("current")).toInt()), + QString::number(freedom.value(QStringLiteral("temperature")).toInt()), + freedom.value(QStringLiteral("error")).toInt() == 0 + ? QStringLiteral("正常") + : freedom.value(QStringLiteral("errors")).toStringList().join(QStringLiteral(";"))}; + for (int column = 0; column < values.size(); ++column) + m_dexHandStateTable->setItem(row, column, new QTableWidgetItem(values.at(column))); + } +} + +void MainWindow::updateDexHandTactile(const QString &deviceId, int rows, int cols, + const QVariantList &values, quint64 frameCount) +{ + if (!m_dexHandDeviceCombo || !m_dexHandTactileHeatmap + || m_dexHandDeviceCombo->currentData().toString() != deviceId + || rows <= 0 || cols <= 0 || values.size() < rows * cols) + return; + + // Preserve the full-rate gRPC reception while limiting expensive table + // painting to about 30 FPS. + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + if (now - m_lastDexHandTactileUiUpdateMs < 33) + return; + m_lastDexHandTactileUiUpdateMs = now; + QVector forceValues; + forceValues.reserve(rows * cols); + int peak = 0; + qint64 totalMilliNewtons = 0; + for (int index = 0; index < rows * cols; ++index) { + const int value = values.at(index).toInt(); + forceValues.append(value); + peak = qMax(peak, value); + totalMilliNewtons += value; + } + m_dexHandTactileHeatmap->setTactileData(rows, cols, forceValues); + if (m_dexHandTactileStateLabel) + m_dexHandTactileStateLabel->setText( + QStringLiteral("帧 %1 · 合力 %2 N · 峰值 %3 mN") + .arg(frameCount) + .arg(totalMilliNewtons / 1000.0, 0, 'f', 3) + .arg(peak)); +} + void MainWindow::updateAgvState(const QVariantMap &state, const QVariantMap &navigation) { const bool controllerConnected = state.value(QStringLiteral("connected")).toBool(); @@ -1782,6 +1919,11 @@ void MainWindow::refreshRecordedJointPoints() { if (!m_jointPointTable) return; + QStringList pointNames; + for (const RecordedJointPoint &point : m_recordedJointPoints) + pointNames.append(point.name); + if (m_jointFlowEditor) + m_jointFlowEditor->setAvailablePointNames(pointNames); m_jointPointTable->setRowCount(m_recordedJointPoints.size()); for (int row = 0; row < m_recordedJointPoints.size(); ++row) { const RecordedJointPoint &point = m_recordedJointPoints.at(row); @@ -1805,21 +1947,8 @@ void MainWindow::refreshRecordedJointPoints() void MainWindow::refreshJointFlowTable() { - if (!m_jointFlowTable) - return; - m_jointFlowTable->setRowCount(m_jointFlowSteps.size()); - for (int row = 0; row < m_jointFlowSteps.size(); ++row) { - const JointFlowStep &step = m_jointFlowSteps.at(row); - m_jointFlowTable->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1))); - m_jointFlowTable->setItem(row, 1, new QTableWidgetItem(step.pointName)); - m_jointFlowTable->setItem(row, 2, new QTableWidgetItem( - QStringLiteral("%1 s").arg(step.waitSeconds, 0, 'f', 1))); - m_jointFlowTable->setItem(row, 3, new QTableWidgetItem( - step.loopGroup.isEmpty() ? QStringLiteral("—") : step.loopGroup)); - m_jointFlowTable->setItem(row, 4, new QTableWidgetItem( - step.loopGroup.isEmpty() ? QStringLiteral("1") - : QString::number(step.loopCount))); - } + if (m_jointFlowEditor) + m_jointFlowEditor->update(); } void MainWindow::recordCurrentJointPoint() @@ -1914,13 +2043,14 @@ void MainWindow::startJointPointLoop() { if (m_jointPointLoopActive || m_jointPointMovePending) return; - if (m_jointFlowSteps.isEmpty()) { + if (!m_jointFlowEditor || m_jointFlowEditor->isEmpty()) { QMessageBox::information(this, QStringLiteral("执行自定义流程"), QStringLiteral("请先向自定义流程中添加步骤。")); return; } m_jointPointLoopRows.clear(); m_jointPointExecutionWaits.clear(); + m_jointPointExecutionNodeIds.clear(); const auto pointRow = [this](const QString &name) { for (int row = 0; row < m_recordedJointPoints.size(); ++row) { if (m_recordedJointPoints.at(row).name == name) @@ -1928,32 +2058,26 @@ void MainWindow::startJointPointLoop() } return -1; }; - for (int i = 0; i < m_jointFlowSteps.size();) { - const JointFlowStep &step = m_jointFlowSteps.at(i); - if (step.loopGroup.isEmpty()) { - const int row = pointRow(step.pointName); - if (row >= 0) { - m_jointPointLoopRows.append(row); - m_jointPointExecutionWaits.append(step.waitSeconds); - } - ++i; - continue; + QString flowError; + const QList steps = + m_jointFlowEditor->expandedSteps(&flowError); + if (!flowError.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("执行自定义流程"), flowError); + return; + } + for (const JointFlowEditor::ExecutionStep &step : steps) { + const int row = pointRow(step.pointName); + if (row < 0) { + QMessageBox::warning(this, QStringLiteral("执行自定义流程"), + QStringLiteral("流程引用的点位“%1”已不存在。").arg(step.pointName)); + m_jointPointLoopRows.clear(); + m_jointPointExecutionWaits.clear(); + m_jointPointExecutionNodeIds.clear(); + return; } - int end = i + 1; - while (end < m_jointFlowSteps.size() - && m_jointFlowSteps.at(end).loopGroup == step.loopGroup) - ++end; - for (int repeat = 0; repeat < step.loopCount; ++repeat) { - for (int index = i; index < end; ++index) { - const JointFlowStep &groupStep = m_jointFlowSteps.at(index); - const int row = pointRow(groupStep.pointName); - if (row >= 0) { - m_jointPointLoopRows.append(row); - m_jointPointExecutionWaits.append(groupStep.waitSeconds); - } - } - } - i = end; + m_jointPointLoopRows.append(row); + m_jointPointExecutionWaits.append(step.intervalSeconds); + m_jointPointExecutionNodeIds.append(step.nodeId); } if (m_jointPointLoopRows.isEmpty()) { QMessageBox::warning(this, QStringLiteral("执行自定义流程"), @@ -1987,6 +2111,8 @@ void MainWindow::advanceJointPointLoop() return; } const RecordedJointPoint &point = m_recordedJointPoints.at(row); + if (m_jointFlowEditor && executionIndex < m_jointPointExecutionNodeIds.size()) + m_jointFlowEditor->setActiveNode(m_jointPointExecutionNodeIds.at(executionIndex)); QVariantList positions; for (double position : point.positions) positions.append(position); @@ -2004,6 +2130,9 @@ void MainWindow::stopJointPointLoop(const QString &reason) m_jointPointMovePending = false; m_jointPointLoopRows.clear(); m_jointPointExecutionWaits.clear(); + m_jointPointExecutionNodeIds.clear(); + if (m_jointFlowEditor) + m_jointFlowEditor->setActiveNode(QString()); if (m_startJointPointLoopButton) m_startJointPointLoopButton->setEnabled(true); if (m_runJointPointButton) @@ -2223,19 +2352,45 @@ void MainWindow::loadJointPrograms(QSettings &settings) } settings.endArray(); - m_jointFlowSteps.clear(); - const int flowCount = settings.beginReadArray(QStringLiteral("arm/jointFlow")); - for (int i = 0; i < flowCount; ++i) { - settings.setArrayIndex(i); - JointFlowStep step; - step.pointName = settings.value(QStringLiteral("pointName")).toString(); - step.waitSeconds = settings.value(QStringLiteral("waitSeconds"), 1.0).toDouble(); - step.loopGroup = settings.value(QStringLiteral("loopGroup")).toString(); - step.loopCount = settings.value(QStringLiteral("loopCount"), 1).toInt(); - if (!step.pointName.isEmpty()) - m_jointFlowSteps.append(step); + if (m_jointFlowEditor) { + m_jointFlowEditor->clear(); + const QByteArray flowJson = settings.value(QStringLiteral("arm/jointFlowGraph")).toByteArray(); + const QJsonDocument document = QJsonDocument::fromJson(flowJson); + if (document.isArray()) { + m_jointFlowEditor->fromJson(document.array()); + } else { + struct LegacyStep { QString point; double wait = 1.0; QString group; int count = 1; }; + QList legacy; + const int flowCount = settings.beginReadArray(QStringLiteral("arm/jointFlow")); + for (int i = 0; i < flowCount; ++i) { + settings.setArrayIndex(i); + LegacyStep step; + step.point = settings.value(QStringLiteral("pointName")).toString(); + step.wait = settings.value(QStringLiteral("waitSeconds"), 1.0).toDouble(); + step.group = settings.value(QStringLiteral("loopGroup")).toString(); + step.count = qMax(1, settings.value(QStringLiteral("loopCount"), 1).toInt()); + if (!step.point.isEmpty()) legacy.append(step); + } + settings.endArray(); + for (int i = 0; i < legacy.size();) { + if (legacy.at(i).group.isEmpty()) { + m_jointFlowEditor->addSingleNode(legacy.at(i).point, + legacy.at(i).point, + legacy.at(i).wait); + ++i; + continue; + } + int end = i + 1; + while (end < legacy.size() && legacy.at(end).group == legacy.at(i).group) ++end; + for (int repeat = 0; repeat < legacy.at(i).count; ++repeat) + for (int index = i; index < end; ++index) + m_jointFlowEditor->addSingleNode(legacy.at(index).point, + legacy.at(index).point, + legacy.at(index).wait); + i = end; + } + } } - settings.endArray(); refreshRecordedJointPoints(); refreshJointFlowTable(); } @@ -2257,17 +2412,11 @@ void MainWindow::saveJointPrograms(QSettings &settings) const settings.setValue(QStringLiteral("positions"), positions); } settings.endArray(); - settings.remove(QStringLiteral("arm/jointFlow")); - settings.beginWriteArray(QStringLiteral("arm/jointFlow")); - for (int i = 0; i < m_jointFlowSteps.size(); ++i) { - settings.setArrayIndex(i); - const JointFlowStep &step = m_jointFlowSteps.at(i); - settings.setValue(QStringLiteral("pointName"), step.pointName); - settings.setValue(QStringLiteral("waitSeconds"), step.waitSeconds); - settings.setValue(QStringLiteral("loopGroup"), step.loopGroup); - settings.setValue(QStringLiteral("loopCount"), step.loopCount); + if (m_jointFlowEditor) { + settings.setValue(QStringLiteral("arm/jointFlowGraph"), + QJsonDocument(m_jointFlowEditor->toJson()).toJson(QJsonDocument::Compact)); + settings.remove(QStringLiteral("arm/jointFlow")); } - settings.endArray(); } void MainWindow::setControlsEnabled(bool enabled) diff --git a/src/mainwindow.h b/src/mainwindow.h index 392871f..a069d31 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -41,6 +41,8 @@ class QuicTestServer; class UrdfViewerWidget; class AudioStreamManager; class VideoRenderWidget; +class TactileHeatmapWidget; +class JointFlowEditor; class MainWindow : public QMainWindow { @@ -73,6 +75,12 @@ private slots: void updateCameraStreamState(const QString &cameraId, bool running, const QString &detail); void updateCameraRecordingState(bool recording, const QString &detail); + void updateDexHandStatus(const QString &deviceId, bool initialized, + bool hasTactileFeedback, + const QString &model, + const QVariantList &freedoms); + void updateDexHandTactile(const QString &deviceId, int rows, int cols, + const QVariantList &values, quint64 frameCount); void updateAgvState(const QVariantMap &state, const QVariantMap &navigation); void updateAgvInventory(const QStringList &maps, const QVariantList &stations); void handleCommand(const QString &command, bool success, const QString &detail); @@ -95,6 +103,7 @@ private: QWidget *createSystemPage(); QWidget *createArmPage(); QWidget *createCameraPage(); + QWidget *createDexHandPage(); QStringList configuredCameraIds() const; void rebuildCameraPreviewGrid(const QStringList &cameraIds); void refreshCameraStreamControls(); @@ -185,7 +194,6 @@ private: QStringList m_leftArmJointNames; QStringList m_rightArmJointNames; QStringList m_activeArmJointNames; - QTabWidget *m_motionCommandTabs = nullptr; QList m_moveJPoseSpins; QComboBox *m_moveJPoseBaseLinkCombo = nullptr; QPushButton *m_copyCurrentPoseButton = nullptr; @@ -238,23 +246,16 @@ private: QStringList jointNames; QVector positions; }; - struct JointFlowStep { - QString pointName; - double waitSeconds = 1.0; - QString loopGroup; - int loopCount = 1; - }; QList m_recordedJointPoints; - QList m_jointFlowSteps; QHash m_latestArmJointPositions; QLineEdit *m_jointPointNameEdit = nullptr; QTableWidget *m_jointPointTable = nullptr; QLabel *m_jointPointDetailLabel = nullptr; QSpinBox *m_jointPointLoopCount = nullptr; QDoubleSpinBox *m_jointPointInterval = nullptr; - QLineEdit *m_jointFlowGroupEdit = nullptr; QSpinBox *m_jointFlowGroupCount = nullptr; - QTableWidget *m_jointFlowTable = nullptr; + JointFlowEditor *m_jointFlowEditor = nullptr; + QDialog *m_jointFlowDialog = nullptr; QPushButton *m_recordJointPointButton = nullptr; QPushButton *m_runJointPointButton = nullptr; QPushButton *m_deleteJointPointButton = nullptr; @@ -263,6 +264,7 @@ private: QLabel *m_jointPointLoopStatus = nullptr; QVector m_jointPointLoopRows; QVector m_jointPointExecutionWaits; + QStringList m_jointPointExecutionNodeIds; int m_jointPointLoopCursor = 0; int m_jointPointLoopsCompleted = 0; int m_jointPointLoopTarget = 0; @@ -295,6 +297,23 @@ private: bool m_cameraStreaming = false; bool m_cameraRecording = false; + QComboBox *m_dexHandDeviceCombo = nullptr; + QLabel *m_dexHandStateLabel = nullptr; + QTableWidget *m_dexHandStateTable = nullptr; + QTabWidget *m_dexHandCommandTabs = nullptr; + QList m_dexHandAngleSpins; + QList m_dexHandPositionSpins; + QList m_dexHandSpeedSpins; + QList m_dexHandForceSpins; + QTimer *m_dexHandRefreshTimer = nullptr; + QWidget *m_dexHandTactilePanel = nullptr; + TactileHeatmapWidget *m_dexHandTactileHeatmap = nullptr; + QLabel *m_dexHandTactileStateLabel = nullptr; + QPushButton *m_dexHandTactileStartButton = nullptr; + QPushButton *m_dexHandTactileStopButton = nullptr; + bool m_dexHandHasTactileFeedback = false; + qint64 m_lastDexHandTactileUiUpdateMs = 0; + QLineEdit *m_agvIdEdit = nullptr; QDialog *m_agvStatusDialog = nullptr; QCheckBox *m_agvStatusSwitch = nullptr; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index f662840..dc1a520 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -2,6 +2,8 @@ #include "audiostreammanager.h" #include "robotclient.h" +#include "tactileheatmapwidget.h" +#include "jointfloweditor.h" #include "rpcservicewidget.h" #include "uiicons.h" #include "urdfviewerwidget.h" @@ -31,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -373,19 +376,11 @@ QWidget *MainWindow::createArmPage() ui.poseValue->hide(); ui.updatedValue->hide(); - m_motionCommandTabs = new QTabWidget(ui.targetsPanel); - m_motionCommandTabs->setObjectName(QStringLiteral("armMotionCommandTabs")); - m_motionCommandTabs->setDocumentMode(true); - QWidget *moveJPage = new QWidget(m_motionCommandTabs); - QGridLayout *moveJLayout = new QGridLayout(moveJPage); - moveJLayout->setContentsMargins(0, 0, 0, 0); - moveJLayout->setHorizontalSpacing(12); - moveJLayout->setVerticalSpacing(10); - moveJLayout->setColumnStretch(0, 4); - moveJLayout->setColumnStretch(1, 6); - moveJLayout->setRowStretch(0, 1); - moveJLayout->setRowStretch(1, 1); - QSplitter *armTargetTables = new QSplitter(Qt::Vertical, moveJPage); + QWidget *directMovePage = new QWidget; + QVBoxLayout *directMoveLayout = new QVBoxLayout(directMovePage); + directMoveLayout->setContentsMargins(0, 8, 0, 0); + directMoveLayout->setSpacing(8); + QSplitter *armTargetTables = new QSplitter(Qt::Vertical, directMovePage); armTargetTables->setObjectName(QStringLiteral("armTargetTables")); armTargetTables->setChildrenCollapsible(false); QWidget *leftTargets = new QWidget(armTargetTables); @@ -410,7 +405,20 @@ QWidget *MainWindow::createArmPage() armTargetTables->addWidget(leftTargets); armTargetTables->addWidget(rightTargets); armTargetTables->setSizes({340, 340}); - moveJLayout->addWidget(armTargetTables, 0, 0, 2, 1); + directMoveLayout->addWidget(armTargetTables, 1); + QHBoxLayout *directMoveActions = new QHBoxLayout; + ui.zeroButton->setParent(directMovePage); + ui.safetyHint->setParent(directMovePage); + m_sendMoveButton->setParent(directMovePage); + directMoveActions->addWidget(ui.zeroButton); + directMoveActions->addWidget(ui.safetyHint, 1); + directMoveActions->addWidget(m_sendMoveButton); + directMoveLayout->addLayout(directMoveActions); + + QWidget *moveJPage = new QWidget; + QVBoxLayout *moveJLayout = new QVBoxLayout(moveJPage); + moveJLayout->setContentsMargins(0, 0, 0, 0); + moveJLayout->setSpacing(10); QFrame *pointPanel = new QFrame(moveJPage); pointPanel->setObjectName(QStringLiteral("panelCard")); @@ -469,7 +477,7 @@ QWidget *MainWindow::createArmPage() pointActions->addStretch(1); pointActions->addWidget(m_jointPointLoopStatus); pointLayout->addLayout(pointActions); - moveJLayout->addWidget(pointPanel, 0, 1); + moveJLayout->addWidget(pointPanel, 2); connect(m_recordJointPointButton, &QPushButton::clicked, this, &MainWindow::recordCurrentJointPoint); @@ -495,10 +503,8 @@ QWidget *MainWindow::createArmPage() m_recordedJointPoints.removeAt(row); } } - for (int i = m_jointFlowSteps.size() - 1; i >= 0; --i) { - if (removedNames.contains(m_jointFlowSteps.at(i).pointName)) - m_jointFlowSteps.removeAt(i); - } + if (m_jointFlowEditor) + m_jointFlowEditor->removePointReferences(removedNames); refreshRecordedJointPoints(); refreshJointFlowTable(); QSettings settings; @@ -537,38 +543,37 @@ QWidget *MainWindow::createArmPage() m_jointPointInterval->setDecimals(1); m_jointPointInterval->setValue(1.0); m_jointPointInterval->setSuffix(QStringLiteral(" s")); - m_jointFlowGroupEdit = new QLineEdit(flowPanel); - m_jointFlowGroupEdit->setPlaceholderText(QStringLiteral("循环组名(留空=执行一次)")); - m_jointFlowGroupEdit->setMaximumWidth(190); m_jointFlowGroupCount = new QSpinBox(flowPanel); m_jointFlowGroupCount->setRange(1, 10000); - m_jointFlowGroupCount->setValue(1); - QPushButton *addFlowStepButton = new QPushButton(QStringLiteral("添加选中点位到流程"), flowPanel); + m_jointFlowGroupCount->setValue(2); + QLabel *insertionContextLabel = new QLabel(QStringLiteral("添加到:根流程"), flowPanel); + insertionContextLabel->setObjectName(QStringLiteral("mutedLabel")); + QPushButton *insertAtRootButton = new QPushButton(QStringLiteral("返回根流程"), flowPanel); + QPushButton *enterSelectedLoopButton = new QPushButton(QStringLiteral("进入选中循环"), flowPanel); + QPushButton *addFlowStepButton = new QPushButton(QStringLiteral("+ 单步节点"), flowPanel); + QPushButton *addFlowLoopButton = new QPushButton(QStringLiteral("+ 循环节点"), flowPanel); flowBuilder->addWidget(flowTitle); + flowBuilder->addWidget(insertionContextLabel); + flowBuilder->addWidget(insertAtRootButton); + flowBuilder->addWidget(enterSelectedLoopButton); flowBuilder->addStretch(1); flowBuilder->addWidget(intervalLabel); flowBuilder->addWidget(m_jointPointInterval); - flowBuilder->addWidget(m_jointFlowGroupEdit); - flowBuilder->addWidget(new QLabel(QStringLiteral("组循环次数"), flowPanel)); - flowBuilder->addWidget(m_jointFlowGroupCount); flowBuilder->addWidget(addFlowStepButton); + flowBuilder->addWidget(new QLabel(QStringLiteral("循环次数"), flowPanel)); + flowBuilder->addWidget(m_jointFlowGroupCount); + flowBuilder->addWidget(addFlowLoopButton); flowLayout->addLayout(flowBuilder); - m_jointFlowTable = new QTableWidget(0, 5, flowPanel); - m_jointFlowTable->setHorizontalHeaderLabels({QStringLiteral("顺序"), QStringLiteral("动作点位"), - QStringLiteral("完成后等待"), QStringLiteral("循环组"), QStringLiteral("组循环次数")}); - m_jointFlowTable->setSelectionBehavior(QAbstractItemView::SelectRows); - m_jointFlowTable->setSelectionMode(QAbstractItemView::SingleSelection); - m_jointFlowTable->setEditTriggers(QAbstractItemView::NoEditTriggers); - m_jointFlowTable->verticalHeader()->setVisible(false); - m_jointFlowTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); - m_jointFlowTable->setMinimumHeight(120); - flowLayout->addWidget(m_jointFlowTable); + QLabel *flowHint = new QLabel(QStringLiteral( + "默认在根流程添加;选中循环后点击“进入选中循环”,可向循环内添加节点。" + "点击“返回根流程”退出循环;双击卡片编辑参数,左键拖动节点,右键拖动画布。" + "循环卡片右上角可展开或收起子节点;循环内子节点只能在当前循环内调整顺序。"), flowPanel); + flowHint->setObjectName(QStringLiteral("mutedLabel")); + flowLayout->addWidget(flowHint); + m_jointFlowEditor = new JointFlowEditor(flowPanel); + flowLayout->addWidget(m_jointFlowEditor); QHBoxLayout *flowActions = new QHBoxLayout; - QPushButton *flowUpButton = new QPushButton(QStringLiteral("上移"), flowPanel); - QPushButton *flowDownButton = new QPushButton(QStringLiteral("下移"), flowPanel); - QPushButton *flowDeleteButton = new QPushButton(QStringLiteral("删除步骤"), flowPanel); - flowActions->addWidget(flowUpButton); - flowActions->addWidget(flowDownButton); + QPushButton *flowDeleteButton = new QPushButton(QStringLiteral("删除选中节点"), flowPanel); flowActions->addWidget(flowDeleteButton); flowActions->addStretch(1); flowActions->addWidget(loopCountLabel); @@ -577,60 +582,63 @@ QWidget *MainWindow::createArmPage() flowActions->addWidget(m_startJointPointLoopButton); flowActions->addWidget(m_stopJointPointLoopButton); flowLayout->addLayout(flowActions); - moveJLayout->addWidget(flowPanel, 1, 1); + moveJLayout->addWidget(flowPanel, 3); connect(addFlowStepButton, &QPushButton::clicked, this, [this]() { const QModelIndexList rows = m_jointPointTable->selectionModel()->selectedRows(); - if (rows.isEmpty()) + if (rows.isEmpty()) { + QMessageBox::information(this, QStringLiteral("添加单步节点"), + QStringLiteral("请先选择一个已记录点位。")); return; - QList sortedRows; - for (const QModelIndex &index : rows) - sortedRows.append(index.row()); - std::sort(sortedRows.begin(), sortedRows.end()); - for (int row : sortedRows) { - if (row < 0 || row >= m_recordedJointPoints.size()) - continue; - JointFlowStep step; - step.pointName = m_recordedJointPoints.at(row).name; - step.waitSeconds = m_jointPointInterval->value(); - step.loopGroup = m_jointFlowGroupEdit->text().trimmed(); - step.loopCount = step.loopGroup.isEmpty() ? 1 : m_jointFlowGroupCount->value(); - m_jointFlowSteps.append(step); } - refreshJointFlowTable(); - QSettings settings; - saveJointPrograms(settings); + const int row = rows.first().row(); + if (row >= 0 && row < m_recordedJointPoints.size()) { + const QString executionUnit = m_recordedJointPoints.at(row).name; + bool ok = false; + const QString nodeName = QInputDialog::getText( + this, QStringLiteral("新增单步节点"), QStringLiteral("节点名称"), + QLineEdit::Normal, executionUnit, &ok).trimmed(); + if (ok && !nodeName.isEmpty()) + m_jointFlowEditor->addSingleNode(nodeName, executionUnit, + m_jointPointInterval->value()); + } + }); + connect(addFlowLoopButton, &QPushButton::clicked, this, [this]() { + bool ok = false; + const QString nodeName = QInputDialog::getText( + this, QStringLiteral("新增循环节点"), QStringLiteral("节点名称"), + QLineEdit::Normal, QStringLiteral("循环"), &ok).trimmed(); + if (ok && !nodeName.isEmpty()) + m_jointFlowEditor->addLoopNode(nodeName, m_jointFlowGroupCount->value(), + m_jointPointInterval->value()); + }); + connect(insertAtRootButton, &QPushButton::clicked, + m_jointFlowEditor, &JointFlowEditor::setInsertionAtRoot); + connect(enterSelectedLoopButton, &QPushButton::clicked, this, [this]() { + if (!m_jointFlowEditor->useSelectedLoopAsInsertionParent()) { + QMessageBox::information(this, QStringLiteral("进入循环"), + QStringLiteral("请先在画布中选择一个循环节点。")); + } + }); + connect(m_jointFlowEditor, &JointFlowEditor::insertionContextChanged, + insertionContextLabel, [insertionContextLabel](const QString &description) { + insertionContextLabel->setText(QStringLiteral("添加到:%1").arg(description)); }); connect(flowDeleteButton, &QPushButton::clicked, this, [this]() { - const int row = m_jointFlowTable->currentRow(); - if (row >= 0 && row < m_jointFlowSteps.size()) - m_jointFlowSteps.removeAt(row); - refreshJointFlowTable(); + m_jointFlowEditor->removeSelectedNode(); + }); + connect(m_jointFlowEditor, &JointFlowEditor::changed, this, [this]() { QSettings settings; saveJointPrograms(settings); }); - const auto moveFlowStep = [this](int delta) { - const int row = m_jointFlowTable->currentRow(); - const int target = row + delta; - if (row < 0 || target < 0 || target >= m_jointFlowSteps.size()) - return; - m_jointFlowSteps.swap(row, target); - refreshJointFlowTable(); - m_jointFlowTable->selectRow(target); - QSettings settings; - saveJointPrograms(settings); - }; - connect(flowUpButton, &QPushButton::clicked, this, [moveFlowStep]() { moveFlowStep(-1); }); - connect(flowDownButton, &QPushButton::clicked, this, [moveFlowStep]() { moveFlowStep(1); }); - m_motionCommandTabs->addTab(moveJPage, QStringLiteral("MoveJ 关节角")); - - QWidget *moveLPage = new QWidget(m_motionCommandTabs); - QVBoxLayout *moveLLayout = new QVBoxLayout(moveLPage); - moveLLayout->setContentsMargins(16, 10, 16, 8); - moveLLayout->setSpacing(10); - QGridLayout *poseGrid = new QGridLayout; - poseGrid->setHorizontalSpacing(12); - poseGrid->setVerticalSpacing(8); + m_jointFlowDialog = new QDialog(this); + m_jointFlowDialog->setWindowTitle(QStringLiteral("机械臂点位与流程编排")); + m_jointFlowDialog->setModal(false); + m_jointFlowDialog->resize(1120, 780); + m_jointFlowDialog->setMinimumSize(860, 620); + QVBoxLayout *jointFlowDialogLayout = new QVBoxLayout(m_jointFlowDialog); + jointFlowDialogLayout->setContentsMargins(12, 12, 12, 12); + jointFlowDialogLayout->addWidget(moveJPage); const QStringList poseLabels = { QStringLiteral("X"), QStringLiteral("Y"), QStringLiteral("Z"), QStringLiteral("RX"), QStringLiteral("RY"), QStringLiteral("RZ") @@ -704,10 +712,21 @@ QWidget *MainWindow::createArmPage() jogTitle->setObjectName(QStringLiteral("sectionTitle")); QLabel *jogHint = new QLabel(QStringLiteral("按住执行,松开即停"), jogPanel); jogHint->setObjectName(QStringLiteral("panelSubtitle")); + QPushButton *openJointFlowButton = new QPushButton( + QStringLiteral("点位与流程…"), jogPanel); + openJointFlowButton->setObjectName(QStringLiteral("secondaryButton")); jogHeader->addWidget(jogTitle); jogHeader->addStretch(1); jogHeader->addWidget(jogHint); + jogHeader->addWidget(openJointFlowButton); jogLayout->addLayout(jogHeader); + connect(openJointFlowButton, &QPushButton::clicked, this, [this]() { + if (!m_jointFlowDialog) + return; + m_jointFlowDialog->show(); + m_jointFlowDialog->raise(); + m_jointFlowDialog->activateWindow(); + }); m_jogModeTabs = new QTabWidget(jogPanel); m_jogModeTabs->setObjectName(QStringLiteral("armJogModeTabs")); @@ -939,9 +958,9 @@ QWidget *MainWindow::createArmPage() jogTabBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); } m_jogModeTabs->addTab(cartesianJogPage, QStringLiteral("笛卡尔速度")); - ui.targetsPanel->setParent(m_jogModeTabs); - ui.targetsPanel->show(); - m_jogModeTabs->addTab(ui.targetsPanel, QStringLiteral("点位与流程")); + m_jogModeTabs->addTab(directMovePage, QStringLiteral("MoveJ 目标")); + ui.urdfTabLayout->removeWidget(ui.targetsPanel); + ui.targetsPanel->hide(); jogLayout->addWidget(m_jogModeTabs, 1); QHBoxLayout *speedLayout = new QHBoxLayout; @@ -2128,6 +2147,180 @@ QWidget *MainWindow::createRpcPage(const QString &serviceName) return new RpcServiceWidget(serviceName, m_client); } +QWidget *MainWindow::createDexHandPage() +{ + QWidget *page = new QWidget; + QVBoxLayout *layout = new QVBoxLayout(page); + layout->setContentsMargins(16, 12, 16, 14); + layout->setSpacing(10); + + QFrame *header = new QFrame(page); + header->setObjectName(QStringLiteral("panel")); + QHBoxLayout *headerLayout = new QHBoxLayout(header); + QLabel *title = new QLabel(QStringLiteral("灵巧手控制"), header); + title->setObjectName(QStringLiteral("sectionTitle")); + m_dexHandDeviceCombo = new QComboBox(header); + m_dexHandDeviceCombo->setMinimumWidth(320); + m_dexHandDeviceCombo->setToolTip(QStringLiteral("从 cmvr-es 在线设备列表自动加载")); + QPushButton *refreshButton = new QPushButton(QStringLiteral("刷新状态"), header); + m_dexHandStateLabel = new QLabel(QStringLiteral("未获取"), header); + m_dexHandStateLabel->setObjectName(QStringLiteral("panelSubtitle")); + headerLayout->addWidget(title); + headerLayout->addStretch(1); + headerLayout->addWidget(new QLabel(QStringLiteral("设备"), header)); + headerLayout->addWidget(m_dexHandDeviceCombo); + headerLayout->addWidget(refreshButton); + headerLayout->addWidget(m_dexHandStateLabel); + layout->addWidget(header); + + QSplitter *splitter = new QSplitter(Qt::Vertical, page); + splitter->setChildrenCollapsible(false); + m_dexHandStateTable = new QTableWidget(6, 8, splitter); + m_dexHandStateTable->setHorizontalHeaderLabels({ + QStringLiteral("自由度"), QStringLiteral("角度"), QStringLiteral("位置"), + QStringLiteral("速度"), QStringLiteral("受力"), QStringLiteral("电流"), + QStringLiteral("温度"), QStringLiteral("状态")}); + m_dexHandStateTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_dexHandStateTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_dexHandStateTable->verticalHeader()->setVisible(false); + m_dexHandStateTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + m_dexHandStateTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + + QFrame *tactilePanel = new QFrame(splitter); + m_dexHandTactilePanel = tactilePanel; + tactilePanel->setObjectName(QStringLiteral("panel")); + QVBoxLayout *tactileLayout = new QVBoxLayout(tactilePanel); + QHBoxLayout *tactileHeader = new QHBoxLayout; + QLabel *tactileTitle = new QLabel(QStringLiteral("食指触觉(12 × 5)"), tactilePanel); + tactileTitle->setObjectName(QStringLiteral("sectionTitle")); + m_dexHandTactileStateLabel = new QLabel(QStringLiteral("未启动"), tactilePanel); + m_dexHandTactileStateLabel->setObjectName(QStringLiteral("panelSubtitle")); + m_dexHandTactileStartButton = new QPushButton(QStringLiteral("开始触觉流"), tactilePanel); + m_dexHandTactileStopButton = new QPushButton(QStringLiteral("停止"), tactilePanel); + m_dexHandTactileStopButton->setEnabled(false); + tactileHeader->addWidget(tactileTitle); + tactileHeader->addStretch(1); + tactileHeader->addWidget(m_dexHandTactileStateLabel); + tactileHeader->addWidget(m_dexHandTactileStartButton); + tactileHeader->addWidget(m_dexHandTactileStopButton); + tactileLayout->addLayout(tactileHeader); + m_dexHandTactileHeatmap = new TactileHeatmapWidget(tactilePanel); + m_dexHandTactileHeatmap->setToolTip( + QStringLiteral("颜色表示单点法向力;数值单位 mN")); + tactileLayout->addWidget(m_dexHandTactileHeatmap); + // Keep tactile controls hidden until GetStatus explicitly reports support. + tactilePanel->hide(); + + m_dexHandCommandTabs = new QTabWidget(splitter); + m_dexHandCommandTabs->setDocumentMode(true); + const QStringList freedomNames = { + QStringLiteral("小拇指"), QStringLiteral("无名指"), QStringLiteral("中指"), + QStringLiteral("食指"), QStringLiteral("大拇指弯曲"), QStringLiteral("大拇指旋转")}; + const auto addCommandPage = [this, &freedomNames, refreshButton](const QString &titleText, + const QString &command, + QList &spins) { + QWidget *commandPage = new QWidget(m_dexHandCommandTabs); + QVBoxLayout *commandLayout = new QVBoxLayout(commandPage); + commandLayout->setContentsMargins(12, 12, 12, 12); + QLabel *hint = new QLabel( + QStringLiteral("按服务端统一归一化范围设置;100% 对应设备该参数最大值。"), + commandPage); + hint->setObjectName(QStringLiteral("panelSubtitle")); + commandLayout->addWidget(hint); + QGridLayout *grid = new QGridLayout; + grid->setHorizontalSpacing(12); + grid->setVerticalSpacing(8); + for (int index = 0; index < freedomNames.size(); ++index) { + QLabel *label = new QLabel(freedomNames.at(index), commandPage); + QDoubleSpinBox *spin = new QDoubleSpinBox(commandPage); + spin->setRange(0.0, 100.0); + spin->setDecimals(1); + spin->setSingleStep(1.0); + spin->setSuffix(QStringLiteral(" %")); + spins.append(spin); + grid->addWidget(label, index / 2, (index % 2) * 2); + grid->addWidget(spin, index / 2, (index % 2) * 2 + 1); + } + commandLayout->addLayout(grid); + QHBoxLayout *actions = new QHBoxLayout; + QPushButton *copyButton = new QPushButton(QStringLiteral("复制当前状态"), commandPage); + QPushButton *sendButton = new QPushButton(QStringLiteral("发送%1").arg(titleText), commandPage); + sendButton->setObjectName(QStringLiteral("primaryButton")); + actions->addStretch(1); + actions->addWidget(copyButton); + actions->addWidget(sendButton); + commandLayout->addLayout(actions); + const QList commandSpins = spins; + connect(copyButton, &QPushButton::clicked, this, [this, command, commandSpins]() { + const QString key = command == QStringLiteral("angle") ? QStringLiteral("angle") + : command == QStringLiteral("position") ? QStringLiteral("position") + : command == QStringLiteral("speed") ? QStringLiteral("speed") + : QStringLiteral("force"); + const double maximum = command == QStringLiteral("position") ? 2000.0 + : command == QStringLiteral("force") ? 3000.0 : 1000.0; + for (int row = 0; row < commandSpins.size() && row < m_dexHandStateTable->rowCount(); ++row) { + const int column = key == QStringLiteral("angle") ? 1 + : key == QStringLiteral("position") ? 2 + : key == QStringLiteral("speed") ? 3 : 4; + const QTableWidgetItem *item = m_dexHandStateTable->item(row, column); + if (item) + commandSpins.at(row)->setValue(item->text().toDouble() * 100.0 / maximum); + } + }); + connect(sendButton, &QPushButton::clicked, this, [this, command, commandSpins]() { + const QString deviceId = m_dexHandDeviceCombo->currentData().toString(); + if (deviceId.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("灵巧手控制"), + QStringLiteral("服务端未返回可用灵巧手设备")); + return; + } + QVariantList values; + for (QDoubleSpinBox *spin : commandSpins) + values.append(spin->value() / 100.0); + m_client->requestDexHandCommand(deviceId, command, values); + }); + m_serviceButtons << refreshButton << copyButton << sendButton; + m_dexHandCommandTabs->addTab(commandPage, titleText); + }; + addCommandPage(QStringLiteral("角度"), QStringLiteral("angle"), m_dexHandAngleSpins); + addCommandPage(QStringLiteral("位置"), QStringLiteral("position"), m_dexHandPositionSpins); + addCommandPage(QStringLiteral("速度"), QStringLiteral("speed"), m_dexHandSpeedSpins); + addCommandPage(QStringLiteral("力"), QStringLiteral("force"), m_dexHandForceSpins); + + splitter->addWidget(m_dexHandStateTable); + splitter->addWidget(tactilePanel); + splitter->addWidget(m_dexHandCommandTabs); + splitter->setStretchFactor(0, 2); + splitter->setStretchFactor(1, 3); + splitter->setStretchFactor(2, 3); + layout->addWidget(splitter, 1); + + const auto refresh = [this]() { + const QString deviceId = m_dexHandDeviceCombo->currentData().toString(); + if (m_connected && !deviceId.isEmpty()) + m_client->requestDexHandStatus(deviceId); + }; + connect(refreshButton, &QPushButton::clicked, this, refresh); + connect(m_dexHandDeviceCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, [this, refresh](int) { + m_client->stopDexHandTactileStream(); + refresh(); + }); + connect(m_dexHandTactileStartButton, &QPushButton::clicked, this, [this]() { + const QString deviceId = m_dexHandDeviceCombo->currentData().toString(); + if (!deviceId.isEmpty()) m_client->startDexHandTactileStream(deviceId); + }); + connect(m_dexHandTactileStopButton, &QPushButton::clicked, + m_client, &RobotClient::stopDexHandTactileStream); + m_serviceButtons << m_dexHandTactileStartButton << m_dexHandTactileStopButton; + m_dexHandRefreshTimer = new QTimer(page); + m_dexHandRefreshTimer->setInterval(1000); + connect(m_dexHandRefreshTimer, &QTimer::timeout, this, refresh); + m_dexHandRefreshTimer->start(); + + return withRpcExplorer(page, m_client, QStringLiteral("cmvr.api.DexHandService")); +} + QWidget *MainWindow::createQuicPage() { QWidget *page = new QWidget; diff --git a/src/robotclient.cpp b/src/robotclient.cpp index 80585e4..a8a7d75 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -37,6 +37,8 @@ #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/dexhand_command.pb.h" +#include "cmvr/api/dexhand_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" @@ -238,6 +240,7 @@ public: stopCameraStreamInternal(); stopSpeakerStreamInternal(true); stopMicrophoneStreamInternal(); + stopDexHandTactileStreamInternal(); stopAgvMapStreamInternal(); } @@ -277,6 +280,7 @@ public: } m_arm = cmvr::api::ArmService::NewStub(m_channel); m_camera = cmvr::api::CameraService::NewStub(m_channel); + m_dexHand = cmvr::api::DexHandService::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); @@ -300,6 +304,7 @@ public: stopCameraStreamInternal(); stopSpeakerStreamInternal(true); stopMicrophoneStreamInternal(); + stopDexHandTactileStreamInternal(); stopAgvMapStreamInternal(); if (m_cameraRecording) { m_cameraRecording = false; @@ -617,6 +622,136 @@ public: #endif } + void getDexHandStatus(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("Get DexHand Status")) + || !ensureDeviceId(QStringLiteral("Get DexHand Status"), deviceId)) + return; + QVariantList freedoms; + if (m_demoMode) { + for (int id = 0; id < 6; ++id) { + QVariantMap freedom; + freedom.insert(QStringLiteral("id"), id); + freedom.insert(QStringLiteral("angle"), id == 4 ? 280 : 120 + id * 70); + freedom.insert(QStringLiteral("position"), 240 + id * 120); + freedom.insert(QStringLiteral("speed"), 500); + freedom.insert(QStringLiteral("force"), 0); + freedom.insert(QStringLiteral("current"), 0); + freedom.insert(QStringLiteral("temperature"), 0); + freedom.insert(QStringLiteral("error"), 0); + freedoms.append(freedom); + } + if (dexHandStatusReceived) + dexHandStatusReceived(deviceId.trimmed(), true, true, + QStringLiteral("Demo DexHand"), freedoms); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::GetDexHandStateCommand::Request request; + fillHeader(request.mutable_header(), deviceId); + cmvr::api::GetDexHandStateCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 1200); + const grpc::Status status = m_dexHand->GetStatus(&context, request, &response); + if (!status.ok() || !response.header().success()) { + emit commandFinished(QStringLiteral("Get DexHand Status"), false, + status.ok() ? QString::fromStdString(response.header().error_message()) + : QString::fromStdString(status.error_message())); + return; + } + for (const auto &item : response.state().hands()) { + QVariantMap freedom; + freedom.insert(QStringLiteral("id"), item.dof_id()); + freedom.insert(QStringLiteral("angle"), item.angle()); + freedom.insert(QStringLiteral("position"), item.position()); + freedom.insert(QStringLiteral("speed"), item.speed()); + freedom.insert(QStringLiteral("force"), item.force()); + freedom.insert(QStringLiteral("current"), item.current()); + freedom.insert(QStringLiteral("temperature"), item.temperature()); + freedom.insert(QStringLiteral("error"), item.error()); + QStringList errors; + for (const auto &message : item.error_message()) + errors.append(QString::fromStdString(message)); + freedom.insert(QStringLiteral("errors"), errors); + freedoms.append(freedom); + } + if (dexHandStatusReceived) + dexHandStatusReceived(deviceId.trimmed(), response.state().is_initialized(), + response.state().has_tactile_feedback(), + QString::fromStdString(response.state().model()), + freedoms); +#endif + } + + void setDexHandValues(const QString &deviceId, const QString &command, + const QVariantList &values) + { + const QString displayCommand = QStringLiteral("DexHand %1").arg(command); + if (!ensureConnected(displayCommand) || !ensureDeviceId(displayCommand, deviceId)) + return; + if (values.size() != 6) { + emit commandFinished(displayCommand, false, QStringLiteral("灵巧手命令必须包含 6 个自由度")); + return; + } + if (m_demoMode) { + emit commandFinished(displayCommand, true, QStringLiteral("演示命令已执行")); + getDexHandStatus(deviceId); + return; + } +#ifdef CMVR_WITH_GRPC + const auto fillValues = [&values](auto *request) { + for (int id = 0; id < values.size(); ++id) { + auto *value = request->add_values(); + value->set_id(id); + value->set_value(static_cast(values.at(id).toDouble())); + } + }; + grpc::Status status; + bool success = false; + QString error; + grpc::ClientContext context; + setDeadline(context, 2000); + if (command == QStringLiteral("angle")) { + cmvr::api::SetDexHandAnglesCommand::Request request; + fillHeader(request.mutable_header(), deviceId); fillValues(&request); + cmvr::api::SetDexHandAnglesCommand::Feedback response; + status = m_dexHand->SetDexHandAngle(&context, request, &response); + success = status.ok() && response.header().success(); + error = QString::fromStdString(response.header().error_message()); + } else if (command == QStringLiteral("position")) { + cmvr::api::SetDexHandPositionsCommand::Request request; + fillHeader(request.mutable_header(), deviceId); fillValues(&request); + cmvr::api::SetDexHandPositionsCommand::Feedback response; + status = m_dexHand->SetDexHandPos(&context, request, &response); + success = status.ok() && response.header().success(); + error = QString::fromStdString(response.header().error_message()); + } else if (command == QStringLiteral("speed")) { + cmvr::api::SetDexHandSpeedCommand::Request request; + fillHeader(request.mutable_header(), deviceId); fillValues(&request); + cmvr::api::SetDexHandSpeedCommand::Feedback response; + status = m_dexHand->SetDexHandSpeed(&context, request, &response); + success = status.ok() && response.header().success(); + error = QString::fromStdString(response.header().error_message()); + } else if (command == QStringLiteral("force")) { + cmvr::api::SetDexHandForceCommand::Request request; + fillHeader(request.mutable_header(), deviceId); fillValues(&request); + cmvr::api::SetDexHandForceCommand::Feedback response; + status = m_dexHand->SetDexHandForce(&context, request, &response); + success = status.ok() && response.header().success(); + error = QString::fromStdString(response.header().error_message()); + } else { + emit commandFinished(displayCommand, false, QStringLiteral("未知灵巧手命令")); + return; + } + if (!status.ok()) + error = QString::fromStdString(status.error_message()); + emit commandFinished(displayCommand, success, + success ? QStringLiteral("命令执行成功") : error); + if (success) + getDexHandStatus(deviceId); +#endif + } + void setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame, const QString &tcpFrame) { @@ -938,6 +1073,72 @@ public: #endif } + void startDexHandTactileStream(const QString &deviceId) + { + if (!ensureConnected(QStringLiteral("DexHand Tactile Stream")) + || !ensureDeviceId(QStringLiteral("DexHand Tactile Stream"), deviceId)) + return; + stopDexHandTactileStreamInternal(); + m_dexHandTactileStop.store(false); + m_dexHandTactileRunning.store(true); +#ifdef CMVR_WITH_GRPC + const auto channel = m_channel; + m_dexHandTactileThread = std::thread([this, channel, deviceId]() { + auto stub = cmvr::api::DexHandService::NewStub(channel); + grpc::ClientContext context; + { + std::lock_guard lock(m_dexHandTactileContextMutex); + m_dexHandTactileContext = &context; + } + auto stream = stub->GetSensorDataStream(&context); + cmvr::api::GetSensorDataStreamCommand::Request request; + request.mutable_header()->set_device_id(deviceId.toStdString()); + bool started = stream && stream->Write(request); + if (stream) stream->WritesDone(); + quint64 frameCount = 0; + cmvr::api::GetSensorDataStreamCommand::Feedback response; + while (started && !m_dexHandTactileStop.load() && stream->Read(&response)) { + for (const auto &sensor : response.sensor()) { + if (sensor.finger_type() != cmvr::api::SensorData::INDEX) + continue; + QVariantList values; + values.reserve(sensor.rows() * sensor.cols()); + for (const auto &row : sensor.data()) + for (const auto value : row.values()) values.append(value); + ++frameCount; + emit dexHandTactileReceived(deviceId, sensor.rows(), sensor.cols(), + values, frameCount); + break; + } + } + grpc::Status status = stream ? stream->Finish() + : grpc::Status(grpc::StatusCode::UNKNOWN, + "cannot create tactile stream"); + { + std::lock_guard lock(m_dexHandTactileContextMutex); + m_dexHandTactileContext = nullptr; + } + const bool stopped = m_dexHandTactileStop.load(); + emit dexHandTactileStreamStateChanged( + false, stopped ? QStringLiteral("食指触觉流已停止") + : QStringLiteral("食指触觉流结束:%1") + .arg(QString::fromStdString(status.error_message()))); + m_dexHandTactileRunning.store(false); + }); + emit dexHandTactileStreamStateChanged(true, QStringLiteral("正在接收食指触觉数据")); +#else + Q_UNUSED(deviceId) + m_dexHandTactileRunning.store(false); + emit dexHandTactileStreamStateChanged(false, QStringLiteral("当前程序未编译 gRPC 支持")); +#endif + } + + void stopDexHandTactileStream() + { + stopDexHandTactileStreamInternal(); + emit dexHandTactileStreamStateChanged(false, QStringLiteral("食指触觉流已停止")); + } + void startCameraStream(const QString &cameraId, const QString &codec, const QString &mode) { @@ -2056,6 +2257,12 @@ public: std::function systemInfoReceived; std::function imageReceived; std::function cameraStatusReceived; + std::function + dexHandStatusReceived; + std::function + dexHandTactileReceived; + std::function dexHandTactileStreamStateChanged; std::function videoFrameReceivedForCamera; std::function @@ -2239,6 +2446,22 @@ private: } } + void stopDexHandTactileStreamInternal() + { + m_dexHandTactileStop.store(true); +#ifdef CMVR_WITH_GRPC + { + std::lock_guard lock(m_dexHandTactileContextMutex); + if (m_dexHandTactileContext) + m_dexHandTactileContext->TryCancel(); + } +#endif + if (m_dexHandTactileThread.joinable() + && m_dexHandTactileThread.get_id() != std::this_thread::get_id()) + m_dexHandTactileThread.join(); + m_dexHandTactileRunning.store(false); + } + void stopAgvMapStreamInternal() { m_agvMapStreamStop.store(true); @@ -3071,6 +3294,7 @@ private: std::shared_ptr m_configChannel; std::unique_ptr m_arm; std::unique_ptr m_camera; + std::unique_ptr m_dexHand; std::unique_ptr m_system; std::unique_ptr m_agv; std::unique_ptr m_microphone; @@ -3082,6 +3306,8 @@ private: std::mutex m_microphoneContextMutex; grpc::ClientContext *m_agvMapStreamContext = nullptr; std::mutex m_agvMapStreamContextMutex; + grpc::ClientContext *m_dexHandTactileContext = nullptr; + std::mutex m_dexHandTactileContextMutex; #endif struct SpeakerAudioFrame { @@ -3124,6 +3350,9 @@ private: std::atomic m_microphoneFrames{0}; std::atomic m_microphoneBytes{0}; std::thread m_microphoneStreamThread; + std::atomic m_dexHandTactileRunning{false}; + std::atomic m_dexHandTactileStop{false}; + std::thread m_dexHandTactileThread; std::atomic m_agvMapStreamRunning{false}; std::atomic m_agvMapStreamStop{false}; std::thread m_agvMapStreamThread; @@ -3190,6 +3419,29 @@ RobotClient::RobotClient(QObject *parent) emit cameraStatusReceived(cameraId, state); }, Qt::QueuedConnection); }; + m_worker->dexHandStatusReceived = + [this](const QString &deviceId, bool initialized, bool hasTactileFeedback, + const QString &model, + const QVariantList &freedoms) { + QMetaObject::invokeMethod(this, [this, deviceId, initialized, + hasTactileFeedback, model, freedoms]() { + emit dexHandStatusReceived(deviceId, initialized, + hasTactileFeedback, model, freedoms); + }, Qt::QueuedConnection); + }; + m_worker->dexHandTactileReceived = + [this](const QString &deviceId, int rows, int cols, + const QVariantList &values, quint64 frameCount) { + QMetaObject::invokeMethod(this, [this, deviceId, rows, cols, values, frameCount]() { + emit dexHandTactileReceived(deviceId, rows, cols, values, frameCount); + }, Qt::QueuedConnection); + }; + m_worker->dexHandTactileStreamStateChanged = + [this](bool running, const QString &detail) { + QMetaObject::invokeMethod(this, [this, running, detail]() { + emit dexHandTactileStreamStateChanged(running, detail); + }, Qt::QueuedConnection); + }; const auto queueVideoFrame = [this](const QString &cameraId, const VideoFrame &frame, const QString &detail) { @@ -3336,6 +3588,14 @@ RobotClient::RobotClient(QObject *parent) m_worker, &BackendWorker::armCalibrateZero); connect(this, &RobotClient::snapshotRequested, m_worker, &BackendWorker::snapshot); connect(this, &RobotClient::cameraStatusRequested, m_worker, &BackendWorker::getCameraStatus); + connect(this, &RobotClient::dexHandStatusRequested, + m_worker, &BackendWorker::getDexHandStatus); + connect(this, &RobotClient::dexHandCommandRequested, + m_worker, &BackendWorker::setDexHandValues); + connect(this, &RobotClient::dexHandTactileStreamStartRequested, + m_worker, &BackendWorker::startDexHandTactileStream); + connect(this, &RobotClient::dexHandTactileStreamStopRequested, + m_worker, &BackendWorker::stopDexHandTactileStream); connect(this, &RobotClient::cameraStreamStartRequested, m_worker, &BackendWorker::startCameraStream); connect(this, &RobotClient::cameraStreamCodecRequested, m_worker, &BackendWorker::setCameraStreamCodec); @@ -3463,6 +3723,25 @@ void RobotClient::requestCameraStatus(const QString &cameraId) { emit cameraStatusRequested(cameraId); } +void RobotClient::requestDexHandStatus(const QString &deviceId) +{ + emit dexHandStatusRequested(deviceId); +} +void RobotClient::requestDexHandCommand(const QString &deviceId, const QString &command, + const QVariantList &values) +{ + emit dexHandCommandRequested(deviceId, command, values); +} + +void RobotClient::startDexHandTactileStream(const QString &deviceId) +{ + emit dexHandTactileStreamStartRequested(deviceId); +} + +void RobotClient::stopDexHandTactileStream() +{ + emit dexHandTactileStreamStopRequested(); +} void RobotClient::startCameraStream(const QString &cameraId, const QString &codec, const QString &mode) { diff --git a/src/robotclient.h b/src/robotclient.h index c32732f..bfda40f 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -48,6 +48,11 @@ public slots: void requestArmCalibrateZero(const QString &deviceId, const QString &jointName); void requestSnapshot(const QString &cameraId); void requestCameraStatus(const QString &cameraId); + void requestDexHandStatus(const QString &deviceId); + void requestDexHandCommand(const QString &deviceId, const QString &command, + const QVariantList &values); + void startDexHandTactileStream(const QString &deviceId); + void stopDexHandTactileStream(); void startCameraStream(const QString &cameraId, const QString &codec, const QString &mode = QStringLiteral("rgb")); void setCameraStreamCodec(const QString &codec); @@ -109,6 +114,11 @@ signals: void armCalibrateZeroRequested(const QString &deviceId, const QString &jointName); void snapshotRequested(const QString &cameraId); void cameraStatusRequested(const QString &cameraId); + void dexHandStatusRequested(const QString &deviceId); + void dexHandCommandRequested(const QString &deviceId, const QString &command, + const QVariantList &values); + void dexHandTactileStreamStartRequested(const QString &deviceId); + void dexHandTactileStreamStopRequested(); void cameraStreamStartRequested(const QString &cameraId, const QString &codec, const QString &mode); void cameraStreamCodecRequested(const QString &codec); @@ -161,6 +171,13 @@ signals: void systemInfoReceived(const QVariantMap &info); void imageReceived(const QImage &image, const QString &detail); void cameraStatusReceived(const QString &cameraId, const QVariantMap &state); + void dexHandStatusReceived(const QString &deviceId, bool initialized, + bool hasTactileFeedback, + const QString &model, + const QVariantList &freedoms); + void dexHandTactileReceived(const QString &deviceId, int rows, int cols, + const QVariantList &values, quint64 frameCount); + void dexHandTactileStreamStateChanged(bool running, const QString &detail); void videoFrameReceived(const QString &cameraId, const VideoFrame &frame, const QString &detail); void cameraStreamStateChanged(const QString &cameraId, bool running, diff --git a/src/tactileheatmapwidget.cpp b/src/tactileheatmapwidget.cpp new file mode 100644 index 0000000..109de46 --- /dev/null +++ b/src/tactileheatmapwidget.cpp @@ -0,0 +1,87 @@ +#include "tactileheatmapwidget.h" + +#include +#include +#include +#include + +#include + +namespace { +QColor forceColor(double normalized) +{ + normalized = qBound(0.0, normalized, 1.0); + if (normalized < 0.25) + return QColor::fromRgbF(0.10, 0.32 + normalized * 1.6, 0.88); + if (normalized < 0.55) { + const double t = (normalized - 0.25) / 0.30; + return QColor::fromRgbF(0.10 + t * 0.85, 0.72 + t * 0.20, 0.88 - t * 0.72); + } + const double t = (normalized - 0.55) / 0.45; + return QColor::fromRgbF(0.95, 0.92 - t * 0.78, 0.16 - t * 0.08); +} +} + +TactileHeatmapWidget::TactileHeatmapWidget(QWidget *parent) + : QWidget(parent) +{ + setMinimumSize(260, 360); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); +} + +void TactileHeatmapWidget::setTactileData(int rows, int cols, + const QVector &values) +{ + if (rows <= 0 || cols <= 0 || values.size() < rows * cols) + return; + m_rows = rows; + m_cols = cols; + m_values = values.mid(0, rows * cols); + update(); +} + +void TactileHeatmapWidget::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event) + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.fillRect(rect(), QColor(20, 25, 36)); + + const int legendWidth = 22; + const QRectF gridArea = rect().adjusted(18, 18, -50, -18); + const double cellWidth = gridArea.width() / m_cols; + const double cellHeight = gridArea.height() / m_rows; + const int peak = m_values.isEmpty() + ? 0 : *std::max_element(m_values.cbegin(), m_values.cend()); + const double scale = qMax(25, peak); + + for (int row = 0; row < m_rows; ++row) { + // AP001 reports matrix rows from the finger base towards the tip. + // Draw the tip at the top of the widget to match the physical finger. + const int sourceRow = m_rows - 1 - row; + for (int col = 0; col < m_cols; ++col) { + const int value = m_values.value(sourceRow * m_cols + col); + QRectF cell(gridArea.left() + col * cellWidth + 2, + gridArea.top() + row * cellHeight + 2, + cellWidth - 4, cellHeight - 4); + painter.setPen(QPen(QColor(255, 255, 255, 35), 1)); + painter.setBrush(forceColor(value / scale)); + painter.drawRoundedRect(cell, 5, 5); + painter.setPen(value / scale > 0.65 ? Qt::white : QColor(235, 242, 255)); + painter.drawText(cell, Qt::AlignCenter, QString::number(value)); + } + } + + const QRectF legend(gridArea.right() + 15, gridArea.top(), legendWidth, + gridArea.height()); + QLinearGradient gradient(legend.bottomLeft(), legend.topLeft()); + gradient.setColorAt(0.0, forceColor(0.0)); + gradient.setColorAt(0.5, forceColor(0.5)); + gradient.setColorAt(1.0, forceColor(1.0)); + painter.fillRect(legend, gradient); + painter.setPen(QColor(220, 228, 240)); + painter.drawText(QRectF(legend.right() + 3, legend.top() - 7, 30, 18), + Qt::AlignLeft, QString::number(peak)); + painter.drawText(QRectF(legend.right() + 3, legend.bottom() - 10, 30, 18), + Qt::AlignLeft, QStringLiteral("0")); +} diff --git a/src/tactileheatmapwidget.h b/src/tactileheatmapwidget.h new file mode 100644 index 0000000..60517cc --- /dev/null +++ b/src/tactileheatmapwidget.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +class TactileHeatmapWidget final : public QWidget +{ +public: + explicit TactileHeatmapWidget(QWidget *parent = nullptr); + + void setTactileData(int rows, int cols, const QVector &values); + +protected: + void paintEvent(QPaintEvent *event) override; + +private: + int m_rows = 12; + int m_cols = 5; + QVector m_values = QVector(60, 0); +}; From 722beb5a1390cb0add8edfa0daab99766361579b Mon Sep 17 00:00:00 2001 From: Gao Date: Fri, 9 Oct 2026 10:53:53 +0800 Subject: [PATCH 07/15] hand-eye calibration, TCP, end-effector operation function update version --- src/videorenderwidget.cpp | 307 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 src/videorenderwidget.cpp diff --git a/src/videorenderwidget.cpp b/src/videorenderwidget.cpp new file mode 100644 index 0000000..bdc2fd0 --- /dev/null +++ b/src/videorenderwidget.cpp @@ -0,0 +1,307 @@ +#include "videorenderwidget.h" + +#include +#include + +#include +#include + +namespace { +const char *vertexShaderSource = R"( +attribute vec2 position; +attribute vec2 texCoord; +varying vec2 textureCoordinate; +uniform vec2 contentScale; +void main() +{ + gl_Position = vec4(position * contentScale, 0.0, 1.0); + textureCoordinate = texCoord; +} +)"; + +const char *fragmentShaderSource = R"( +#ifdef GL_ES +precision mediump float; +#endif +varying vec2 textureCoordinate; +uniform sampler2D textureY; +uniform sampler2D textureU; +uniform sampler2D textureV; +uniform float pixelFormat; +uniform float scaleY; +uniform float scaleU; +uniform float scaleV; +void main() +{ + if (pixelFormat > 1.5) { + gl_FragColor = texture2D(textureY, textureCoordinate); + return; + } + + float y = texture2D(textureY, + vec2(textureCoordinate.x * scaleY, textureCoordinate.y)).r; + float u; + float v; + if (pixelFormat > 0.5) { + vec4 uv = texture2D(textureU, + vec2(textureCoordinate.x * scaleU, textureCoordinate.y)); + u = uv.r - 0.5; + v = uv.a - 0.5; + } else { + u = texture2D(textureU, + vec2(textureCoordinate.x * scaleU, textureCoordinate.y)).r - 0.5; + v = texture2D(textureV, + vec2(textureCoordinate.x * scaleV, textureCoordinate.y)).r - 0.5; + } + y = 1.16438356 * (y - 0.0625); + gl_FragColor = vec4(y + 1.59602678 * v, + y - 0.39176229 * u - 0.81296764 * v, + y + 2.01723214 * u, 1.0); +} +)"; +} + +VideoRenderWidget::VideoRenderWidget(QWidget *parent) + : QOpenGLWidget(parent) +{ + setAutoFillBackground(false); + setUpdateBehavior(QOpenGLWidget::NoPartialUpdate); +} + +VideoRenderWidget::~VideoRenderWidget() +{ + if (context()) { + makeCurrent(); + releaseTextures(); + doneCurrent(); + } +} + +void VideoRenderWidget::setFrameAspectLayoutEnabled(bool enabled) +{ + m_frameAspectLayout = enabled; + QSizePolicy policy(QSizePolicy::Expanding, enabled ? QSizePolicy::Fixed : QSizePolicy::Expanding); + policy.setHeightForWidth(enabled); + setSizePolicy(policy); + if (enabled) updateAspectHeight(); + else { setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); } + updateGeometry(); +} + +int VideoRenderWidget::heightForWidth(int width) const +{ + return m_frameAspectLayout ? qMax(1, qRound(double(width) * m_layoutFrameSize.height() + / m_layoutFrameSize.width())) : -1; +} + +QSize VideoRenderWidget::sizeHint() const +{ + return m_frameAspectLayout ? QSize(640,heightForWidth(640)) : QOpenGLWidget::sizeHint(); +} + +void VideoRenderWidget::updateAspectHeight() +{ + if (!m_frameAspectLayout) return; + const int wanted = heightForWidth(width()); + if (minimumHeight() != wanted || maximumHeight() != wanted) setFixedHeight(wanted); +} + +void VideoRenderWidget::resizeEvent(QResizeEvent *event) +{ + QOpenGLWidget::resizeEvent(event); + updateAspectHeight(); +} + +void VideoRenderWidget::setFrame(const VideoFrame &frame) +{ + if (!frame.isValid()) + return; + m_frame = frame; + if (m_layoutFrameSize != QSize(frame.width, frame.height)) { + m_layoutFrameSize = QSize(frame.width, frame.height); + updateAspectHeight(); + if (m_frameAspectLayout) updateGeometry(); + } + m_message.clear(); + m_frameDirty = true; + update(); +} + +void VideoRenderWidget::setImage(const QImage &image) +{ + if (image.isNull()) + return; + const QImage converted = image.convertToFormat(QImage::Format_RGBA8888); + VideoFrame frame; + frame.width = converted.width(); + frame.height = converted.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, + converted.constScanLine(row), static_cast(frame.width * 4)); + } + setFrame(frame); +} + +void VideoRenderWidget::clearFrame(const QString &message) +{ + m_frame = VideoFrame(); + m_message = message; + m_frameDirty = false; + update(); +} + +void VideoRenderWidget::initializeGL() +{ + initializeOpenGLFunctions(); + glClearColor(0.055f, 0.067f, 0.078f, 1.0f); + glGenTextures(3, m_textures); + + m_program.reset(new QOpenGLShaderProgram); + if (!m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource) || + !m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource) || + !m_program->link()) { + m_message = QStringLiteral("OpenGL 视频着色器初始化失败:%1").arg(m_program->log()); + m_program.reset(); + return; + } + m_glReady = true; +} + +void VideoRenderWidget::uploadPlane(unsigned int texture, int unit, int width, + int height, unsigned int format, + const QByteArray &data, int textureIndex) +{ + glActiveTexture(GL_TEXTURE0 + unit); + glBindTexture(GL_TEXTURE_2D, texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + if (m_textureWidths[textureIndex] != width || + m_textureHeights[textureIndex] != height || + m_textureFormats[textureIndex] != format) { + glTexImage2D(GL_TEXTURE_2D, 0, static_cast(format), width, height, 0, + format, GL_UNSIGNED_BYTE, data.constData()); + m_textureWidths[textureIndex] = width; + m_textureHeights[textureIndex] = height; + m_textureFormats[textureIndex] = format; + } else { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, + GL_UNSIGNED_BYTE, data.constData()); + } +} + +void VideoRenderWidget::paintGL() +{ + glClear(GL_COLOR_BUFFER_BIT); + if (!m_glReady || !m_program || !m_frame.isValid()) { + drawMessage(m_message); + return; + } + + // Qt 5.12's ANGLE backend can upload RGBA QImage data with an incorrect + // channel layout. Draw still RGBA frames with the CPU painter instead. + if (m_frame.format == VideoPixelFormat::RGBA) { + const QImage image(reinterpret_cast(m_frame.plane0.constData()), + m_frame.width, m_frame.height, m_frame.stride0, + QImage::Format_RGBA8888); + QPainter painter(this); + painter.fillRect(rect(), QColor(QStringLiteral("#0e1115"))); + QSize target = image.size(); + target.scale(size(), Qt::KeepAspectRatio); + const QRect destination((width() - target.width()) / 2, + (height() - target.height()) / 2, + target.width(), target.height()); + painter.drawImage(destination, image); + m_frameDirty = false; + return; + } + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + if (m_frameDirty) { + if (m_frame.format == VideoPixelFormat::I420) { + uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, + GL_LUMINANCE, m_frame.plane0, 0); + uploadPlane(m_textures[1], 1, m_frame.stride1, + (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane1, 1); + uploadPlane(m_textures[2], 2, m_frame.stride2, + (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane2, 2); + } else if (m_frame.format == VideoPixelFormat::NV12) { + uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, + GL_LUMINANCE, m_frame.plane0, 0); + uploadPlane(m_textures[1], 1, m_frame.stride1 / 2, + (m_frame.height + 1) / 2, GL_LUMINANCE_ALPHA, + m_frame.plane1, 1); + } else { + uploadPlane(m_textures[0], 0, m_frame.width, m_frame.height, + GL_RGBA, m_frame.plane0, 0); + } + m_frameDirty = false; + } + + const GLfloat vertices[] = { + -1.0f, -1.0f, 0.0f, 1.0f, + 1.0f, -1.0f, 1.0f, 1.0f, + -1.0f, 1.0f, 0.0f, 0.0f, + 1.0f, 1.0f, 1.0f, 0.0f + }; + float scaleX = 1.0f; + float scaleY = 1.0f; + const float frameAspect = static_cast(m_frame.width) / m_frame.height; + const float widgetAspect = width() > 0 && height() > 0 + ? static_cast(width()) / height() : frameAspect; + if (frameAspect > widgetAspect) + scaleY = widgetAspect / frameAspect; + else + scaleX = frameAspect / widgetAspect; + + m_program->bind(); + m_program->setUniformValue("contentScale", scaleX, scaleY); + m_program->setUniformValue("textureY", 0); + m_program->setUniformValue("textureU", 1); + m_program->setUniformValue("textureV", 2); + m_program->setUniformValue("pixelFormat", + m_frame.format == VideoPixelFormat::NV12 ? 1.0f : + m_frame.format == VideoPixelFormat::RGBA ? 2.0f : 0.0f); + m_program->setUniformValue("scaleY", m_frame.format == VideoPixelFormat::RGBA + ? 1.0f : static_cast(m_frame.width) / m_frame.stride0); + m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::NV12 + ? static_cast((m_frame.width + 1) / 2) / (m_frame.stride1 / 2) + : static_cast((m_frame.width + 1) / 2) / m_frame.stride1); + m_program->setUniformValue("scaleV", m_frame.format == VideoPixelFormat::I420 + ? static_cast((m_frame.width + 1) / 2) / m_frame.stride2 : 1.0f); + const int position = m_program->attributeLocation("position"); + const int texCoord = m_program->attributeLocation("texCoord"); + m_program->enableAttributeArray(position); + m_program->enableAttributeArray(texCoord); + m_program->setAttributeArray(position, GL_FLOAT, vertices, 2, 4 * sizeof(GLfloat)); + m_program->setAttributeArray(texCoord, GL_FLOAT, vertices + 2, 2, + 4 * sizeof(GLfloat)); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + m_program->disableAttributeArray(position); + m_program->disableAttributeArray(texCoord); + m_program->release(); +} + +void VideoRenderWidget::drawMessage(const QString &message) +{ + if (message.isEmpty()) + return; + QPainter painter(this); + painter.setPen(QColor(QStringLiteral("#8d98a5"))); + painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, message); +} + +void VideoRenderWidget::releaseTextures() +{ + if (m_textures[0]) { + glDeleteTextures(3, m_textures); + m_textures[0] = m_textures[1] = m_textures[2] = 0; + std::fill(m_textureWidths, m_textureWidths + 3, 0); + std::fill(m_textureHeights, m_textureHeights + 3, 0); + std::fill(m_textureFormats, m_textureFormats + 3, 0); + } +} From 96e5fe0c762e74eb9a8d6e9b06bea67d74aef346 Mon Sep 17 00:00:00 2001 From: xtkuang <87661715@qq.com> Date: Fri, 9 Oct 2026 12:05:14 +0800 Subject: [PATCH 08/15] feat: improve AGV live map controls --- src/agvmapviewwidget.cpp | 59 ++++++++ src/agvmapviewwidget.h | 2 + src/mainwindow.cpp | 101 ++++++++++++- src/mainwindow.h | 9 ++ src/mainwindow_ui.cpp | 36 +++++ src/robotclient.cpp | 7 +- src/videorenderwidget.cpp | 307 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 511 insertions(+), 10 deletions(-) create mode 100644 src/videorenderwidget.cpp diff --git a/src/agvmapviewwidget.cpp b/src/agvmapviewwidget.cpp index ef13cc6..b5e2063 100644 --- a/src/agvmapviewwidget.cpp +++ b/src/agvmapviewwidget.cpp @@ -143,6 +143,62 @@ QPointF AgvMapViewWidget::imageToWidget(const QPointF &point) const return imageTopLeft() + point * viewScale(); } +void AgvMapViewWidget::drawCoordinateAxes(QPainter &painter) const +{ + constexpr double panelSize = 92.0; + constexpr double panelMargin = 12.0; + constexpr double arrowLength = 27.0; + const QRectF panel(width() - panelMargin - panelSize, + panelMargin, panelSize, panelSize); + + painter.save(); + painter.setPen(QPen(QColor(QStringLiteral("#c9d4de")), 1)); + painter.setBrush(QColor(255, 255, 255, 232)); + painter.drawRoundedRect(panel, 8, 8); + + const QPointF center = panel.center(); + const double originTheta = m_metadata.value( + QStringLiteral("originTheta")).toDouble(); + const QPointF xDirection(qCos(originTheta), qSin(originTheta)); + const QPointF yDirection(qSin(originTheta), -qCos(originTheta)); + + const auto drawArrow = [&painter, center, arrowLength]( + const QPointF &direction, + const QColor &color, + const QString &label) { + const QPointF normal(-direction.y(), direction.x()); + const QPointF tip = center + direction * arrowLength; + painter.setPen(QPen(color, 2.4, Qt::SolidLine, Qt::RoundCap)); + painter.setBrush(color); + painter.drawLine(center, tip); + + QPolygonF arrowHead; + arrowHead << tip + << tip - direction * 8.0 + normal * 4.5 + << tip - direction * 8.0 - normal * 4.5; + painter.setPen(Qt::NoPen); + painter.drawPolygon(arrowHead); + + const QPointF labelCenter = tip + direction * 9.0; + const QRectF labelRect(labelCenter.x() - 9.0, + labelCenter.y() - 9.0, 18.0, 18.0); + QFont labelFont = painter.font(); + labelFont.setBold(true); + painter.setFont(labelFont); + painter.setPen(color); + painter.drawText(labelRect, Qt::AlignCenter, label); + }; + + drawArrow(xDirection, QColor(QStringLiteral("#d94a4a")), + QStringLiteral("X")); + drawArrow(yDirection, QColor(QStringLiteral("#2f9e69")), + QStringLiteral("Y")); + painter.setPen(Qt::NoPen); + painter.setBrush(QColor(QStringLiteral("#374151"))); + painter.drawEllipse(center, 3.2, 3.2); + painter.restore(); +} + void AgvMapViewWidget::paintEvent(QPaintEvent *event) { Q_UNUSED(event) @@ -221,6 +277,9 @@ void AgvMapViewWidget::paintEvent(QPaintEvent *event) painter.drawText(labelRect, Qt::AlignCenter, poseText); } + if (canProjectPose()) + drawCoordinateAxes(painter); + if (!m_streamMessage.isEmpty()) { const QRect messageRect(12, height() - 36, width() - 24, 24); painter.setPen(QColor(QStringLiteral("#5c6975"))); diff --git a/src/agvmapviewwidget.h b/src/agvmapviewwidget.h index 5a1d5cf..5e8c625 100644 --- a/src/agvmapviewwidget.h +++ b/src/agvmapviewwidget.h @@ -9,6 +9,7 @@ #include class QMouseEvent; +class QPainter; class QPaintEvent; class QWheelEvent; @@ -38,6 +39,7 @@ private: QPointF imageToWidget(const QPointF &point) const; double viewScale() const; QPointF imageTopLeft() const; + void drawCoordinateAxes(QPainter &painter) const; void changeZoom(double factor, const QPointF &anchor); QImage m_image; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index afe4b03..515edf0 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -522,16 +522,35 @@ MainWindow::MainWindow(QWidget *parent) 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); + m_pendingAgvMapImage = image; + m_pendingAgvMapMetadata = metadata; + m_pendingAgvMapDetail = detail; + m_agvMapFramePending = true; + + const int intervalMs = m_agvMapRefreshCombo + ? m_agvMapRefreshCombo->currentData().toInt() : 0; + if (intervalMs <= 0) { + presentPendingAgvMapFrame(); + } else if (m_agvMapRefreshTimer && !m_agvMapRefreshTimer->isActive()) { + presentPendingAgvMapFrame(); + m_agvMapRefreshTimer->setInterval(intervalMs); + m_agvMapRefreshTimer->start(); } - if (m_agvMappingStateLabel) - m_agvMappingStateLabel->setText(detail); }); connect(m_client, &RobotClient::agvMapStreamStateChanged, this, [this](bool running, const QString &detail) { m_agvMapStreamActive = running; + const int intervalMs = m_agvMapRefreshCombo + ? m_agvMapRefreshCombo->currentData().toInt() : 0; + if (m_agvMapRefreshTimer) { + if (running && intervalMs > 0) { + m_agvMapRefreshTimer->setInterval(intervalMs); + m_agvMapRefreshTimer->start(); + } else if (!running) { + presentPendingAgvMapFrame(); + m_agvMapRefreshTimer->stop(); + } + } if (m_agvMapView) m_agvMapView->setStreamMessage(detail); if (!m_agvMappingStateLabel) @@ -926,6 +945,12 @@ void MainWindow::selectPage(int index) stopAgvManualMotion(); if (m_agvStatusRefreshTimer) m_agvStatusRefreshTimer->stop(); + if (m_agvMapRefreshTimer) + m_agvMapRefreshTimer->stop(); + m_agvMapFramePending = false; + m_pendingAgvMapImage = QImage(); + m_pendingAgvMapMetadata.clear(); + m_pendingAgvMapDetail.clear(); if (m_agvMapStreamActive) { m_client->stopAgvMapStream(); m_agvMapStreamActive = false; @@ -981,6 +1006,25 @@ void MainWindow::restartAgvMapStream(const QString &mapName) 1, true, true); } +void MainWindow::presentPendingAgvMapFrame() +{ + if (!m_agvMapFramePending) + return; + + if (m_agvMapView) { + m_agvMapView->setMapFrame(m_pendingAgvMapImage, + m_pendingAgvMapMetadata); + m_agvMapView->setStreamMessage(m_pendingAgvMapDetail); + } + if (m_agvMappingStateLabel) + m_agvMappingStateLabel->setText(m_pendingAgvMapDetail); + + m_agvMapFramePending = false; + m_pendingAgvMapImage = QImage(); + m_pendingAgvMapMetadata.clear(); + m_pendingAgvMapDetail.clear(); +} + void MainWindow::ensureArmModelLoaded() { if (!m_urdfViewer || m_pendingUrdfPath.isEmpty() @@ -1834,9 +1878,41 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri 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(); + if (command == QStringLiteral("AGV StopMapping")) { + const bool asynchronousMappingFrame = + !success + && detail.contains(QStringLiteral("expected=16101")) + && detail.contains(QStringLiteral("actual=17002")); + if (asynchronousMappingFrame && !m_agvStopMappingRetryPending) { + m_agvStopMappingRetryPending = true; + if (m_agvMappingStateLabel) { + m_agvMappingStateLabel->setText( + QStringLiteral("正在重新确认停止建图")); + } + appendLog( + QStringLiteral("WARN"), + QStringLiteral("停止建图响应被异步地图帧打断,正在自动重试一次")); + QTimer::singleShot(350, this, [this]() { + if (!m_agvStopMappingRetryPending) + return; + m_client->requestAgvAction( + m_agvIdEdit->text().trimmed(), + QStringLiteral("StopMapping")); + }); + return; + } + + m_agvStopMappingRetryPending = false; + if (m_agvStopMappingButton) + m_agvStopMappingButton->setEnabled(true); + if (success) { + if (m_agvMappingStateLabel) + m_agvMappingStateLabel->setText(QStringLiteral("建图已停止")); + m_client->requestAgvInventory(m_agvIdEdit->text().trimmed()); + restartAgvMapStream(); + } else if (m_agvMappingStateLabel) { + m_agvMappingStateLabel->setText(QStringLiteral("停止建图失败")); + } } appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"), @@ -1946,6 +2022,12 @@ void MainWindow::loadSettings() m_cameraStreamModeCombo->setCurrentIndex(modeIndex); } m_agvIdEdit->setText(settings.value(QStringLiteral("agv/device"), QStringLiteral("agv")).toString()); + if (m_agvMapRefreshCombo) { + const int intervalMs = settings.value( + QStringLiteral("agv/mapRefreshIntervalMs"), 0).toInt(); + const int index = m_agvMapRefreshCombo->findData(intervalMs); + m_agvMapRefreshCombo->setCurrentIndex(index >= 0 ? index : 0); + } m_velocitySpin->setValue(settings.value( QStringLiteral("motion/speedJVelocity"), settings.value(QStringLiteral("motion/velocity"), 1.0)).toDouble()); @@ -2011,6 +2093,9 @@ void MainWindow::saveSettings() settings.setValue(QStringLiteral("camera/streamMode"), m_cameraStreamModeCombo->currentData().toString()); settings.setValue(QStringLiteral("agv/device"), m_agvIdEdit->text().trimmed()); + if (m_agvMapRefreshCombo) + settings.setValue(QStringLiteral("agv/mapRefreshIntervalMs"), + m_agvMapRefreshCombo->currentData().toInt()); settings.setValue(QStringLiteral("motion/speedJVelocity"), m_velocitySpin->value()); settings.setValue(QStringLiteral("motion/speedJAcceleration"), m_accelerationSpin->value()); diff --git a/src/mainwindow.h b/src/mainwindow.h index 5a9b7c1..48aa3bd 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -110,6 +110,7 @@ private: void startAgvManualMotion(double vx, double vy, double wz); void stopAgvManualMotion(bool sendStop = true); void restartAgvMapStream(const QString &mapName = QString()); + void presentPendingAgvMapFrame(); void updateArmAlert(const QString &deviceId, const QString &alertKey, const QString &level, const QString &summary, const QString &detail = QString()); @@ -252,6 +253,7 @@ private: QDialog *m_agvStatusDialog = nullptr; QTimer *m_agvStatusRefreshTimer = nullptr; QTimer *m_agvManualVelocityTimer = nullptr; + QTimer *m_agvMapRefreshTimer = nullptr; QLabel *m_agvConnectionValue = nullptr; QLabel *m_agvPoseValue = nullptr; QLabel *m_agvMotionValue = nullptr; @@ -270,6 +272,7 @@ private: AgvMapViewWidget *m_agvMapView = nullptr; QWidget *m_agvControlWorkspace = nullptr; QPushButton *m_agvDeleteMapButton = nullptr; + QPushButton *m_agvStopMappingButton = nullptr; QProgressBar *m_agvProgress = nullptr; QDoubleSpinBox *m_agvXSpin = nullptr; QDoubleSpinBox *m_agvYSpin = nullptr; @@ -279,15 +282,21 @@ private: QDoubleSpinBox *m_agvVySpin = nullptr; QDoubleSpinBox *m_agvWzSpin = nullptr; QComboBox *m_agvMapCombo = nullptr; + QComboBox *m_agvMapRefreshCombo = nullptr; QComboBox *m_agvStationCombo = nullptr; QTableWidget *m_agvStationTable = nullptr; QString m_agvDownloadPath; QVariantMap m_latestAgvState; + QImage m_pendingAgvMapImage; + QVariantMap m_pendingAgvMapMetadata; + QString m_pendingAgvMapDetail; double m_agvManualVx = 0.0; double m_agvManualVy = 0.0; double m_agvManualWz = 0.0; bool m_agvManualMotionActive = false; bool m_agvMapStreamActive = false; + bool m_agvMapFramePending = false; + bool m_agvStopMappingRetryPending = false; QList m_serviceButtons; QPushButton *m_speakerStreamStartButton = nullptr; QPushButton *m_speakerStreamStopButton = nullptr; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 4dc4cae..1be7a99 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -1087,6 +1087,10 @@ QWidget *MainWindow::createAgvPage() m_agvIdEdit = ui.agvIdEdit; m_agvStatusRefreshTimer = new QTimer(page); m_agvStatusRefreshTimer->setInterval(1000); + m_agvMapRefreshTimer = new QTimer(page); + m_agvMapRefreshTimer->setTimerType(Qt::PreciseTimer); + connect(m_agvMapRefreshTimer, &QTimer::timeout, + this, &MainWindow::presentPendingAgvMapFrame); m_agvConnectionValue = statusUi.agvConnectionValue; m_agvPoseValue = statusUi.agvPoseValue; m_agvMotionValue = statusUi.agvMotionValue; @@ -1166,6 +1170,19 @@ QWidget *MainWindow::createAgvPage() QStringLiteral("蓝色箭头:AGV 当前位姿 · 虚线:运动轨迹"), ui.mappingPreviewPanel); mapLegend->setObjectName(QStringLiteral("panelSubtitle")); + QLabel *mapRefreshLabel = new QLabel(QStringLiteral("刷新率"), + ui.mappingPreviewPanel); + mapRefreshLabel->setObjectName(QStringLiteral("panelSubtitle")); + m_agvMapRefreshCombo = new QComboBox(ui.mappingPreviewPanel); + m_agvMapRefreshCombo->setObjectName(QStringLiteral("agvMapRefreshCombo")); + m_agvMapRefreshCombo->addItem(QStringLiteral("自动"), 0); + m_agvMapRefreshCombo->addItem(QStringLiteral("1 Hz"), 1000); + m_agvMapRefreshCombo->addItem(QStringLiteral("2 Hz"), 500); + m_agvMapRefreshCombo->addItem(QStringLiteral("5 Hz"), 200); + m_agvMapRefreshCombo->addItem(QStringLiteral("10 Hz"), 100); + m_agvMapRefreshCombo->setMaximumWidth(96); + m_agvMapRefreshCombo->setToolTip( + QStringLiteral("控制上位机地图画面的刷新频率;自动模式跟随地图数据")); QPushButton *zoomOutButton = new QPushButton(QStringLiteral("−"), ui.mappingPreviewPanel); QPushButton *zoomInButton = new QPushButton(QStringLiteral("+"), @@ -1183,6 +1200,9 @@ QWidget *MainWindow::createAgvPage() zoomInButton->setMaximumWidth(42); mapToolbar->addWidget(mapLegend); mapToolbar->addStretch(); + mapToolbar->addWidget(mapRefreshLabel); + mapToolbar->addWidget(m_agvMapRefreshCombo); + mapToolbar->addSpacing(4); mapToolbar->addWidget(zoomOutButton); mapToolbar->addWidget(zoomInButton); mapToolbar->addWidget(resetViewButton); @@ -1316,6 +1336,19 @@ QWidget *MainWindow::createAgvPage() m_agvMapView, &AgvMapViewWidget::resetView); connect(clearTrackButton, &QPushButton::clicked, m_agvMapView, &AgvMapViewWidget::clearTrajectory); + connect(m_agvMapRefreshCombo, + QOverload::of(&QComboBox::currentIndexChanged), + this, [this](int) { + const int intervalMs = m_agvMapRefreshCombo->currentData().toInt(); + if (intervalMs <= 0) { + m_agvMapRefreshTimer->stop(); + presentPendingAgvMapFrame(); + return; + } + m_agvMapRefreshTimer->setInterval(intervalMs); + if (m_agvMapStreamActive) + m_agvMapRefreshTimer->start(); + }); connect(addMapButton, &QPushButton::clicked, this, [this, nameEdit = ui.mappingNameEdit]() { bool accepted = false; @@ -1551,7 +1584,10 @@ QWidget *MainWindow::createAgvPage() m_agvIdEdit->text().trimmed()); ui.mappingStateLabel->setText(QStringLiteral("建图启动请求已发送")); }); + m_agvStopMappingButton = ui.stopMappingButton; connect(ui.stopMappingButton, &QPushButton::clicked, this, [this, ui]() { + m_agvStopMappingRetryPending = false; + m_agvStopMappingButton->setEnabled(false); m_client->requestAgvAction(m_agvIdEdit->text().trimmed(), QStringLiteral("StopMapping")); ui.mappingStateLabel->setText(QStringLiteral("正在停止建图")); diff --git a/src/robotclient.cpp b/src/robotclient.cpp index e31b306..5a8f956 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -1812,10 +1812,13 @@ public: painter.drawEllipse(geometry.first(), 6, 6); else if (geometry.size() > 1) painter.drawPolyline(geometry); - if (!geometry.isEmpty()) { + const QString objectId = QString::fromStdString( + object.id()).trimmed(); + if (!geometry.isEmpty() && !objectId.isEmpty() + && objectId != QStringLiteral("0")) { painter.setPen(QColor(QStringLiteral("#145da8"))); painter.drawText(geometry.first() + QPointF(8, -6), - QString::fromStdString(object.id())); + objectId); } } painter.end(); diff --git a/src/videorenderwidget.cpp b/src/videorenderwidget.cpp new file mode 100644 index 0000000..4036004 --- /dev/null +++ b/src/videorenderwidget.cpp @@ -0,0 +1,307 @@ +#include "videorenderwidget.h" + +#include +#include + +#include +#include + +namespace { +const char *vertexShaderSource = R"( +attribute vec2 position; +attribute vec2 texCoord; +varying vec2 textureCoordinate; +uniform vec2 contentScale; +void main() +{ + gl_Position = vec4(position * contentScale, 0.0, 1.0); + textureCoordinate = texCoord; +} +)"; + +const char *fragmentShaderSource = R"( +#ifdef GL_ES +precision mediump float; +#endif +varying vec2 textureCoordinate; +uniform sampler2D textureY; +uniform sampler2D textureU; +uniform sampler2D textureV; +uniform float pixelFormat; +uniform float scaleY; +uniform float scaleU; +uniform float scaleV; +void main() +{ + if (pixelFormat > 1.5) { + gl_FragColor = texture2D(textureY, textureCoordinate); + return; + } + + float y = texture2D(textureY, + vec2(textureCoordinate.x * scaleY, textureCoordinate.y)).r; + float u; + float v; + if (pixelFormat > 0.5) { + vec4 uv = texture2D(textureU, + vec2(textureCoordinate.x * scaleU, textureCoordinate.y)); + u = uv.r - 0.5; + v = uv.a - 0.5; + } else { + u = texture2D(textureU, + vec2(textureCoordinate.x * scaleU, textureCoordinate.y)).r - 0.5; + v = texture2D(textureV, + vec2(textureCoordinate.x * scaleV, textureCoordinate.y)).r - 0.5; + } + y = 1.16438356 * (y - 0.0625); + gl_FragColor = vec4(y + 1.59602678 * v, + y - 0.39176229 * u - 0.81296764 * v, + y + 2.01723214 * u, 1.0); +} +)"; +} + +VideoRenderWidget::VideoRenderWidget(QWidget *parent) + : QOpenGLWidget(parent) +{ + setAutoFillBackground(false); + setUpdateBehavior(QOpenGLWidget::NoPartialUpdate); +} + +VideoRenderWidget::~VideoRenderWidget() +{ + if (context()) { + makeCurrent(); + releaseTextures(); + doneCurrent(); + } +} + +void VideoRenderWidget::setFrameAspectLayoutEnabled(bool enabled) +{ + m_frameAspectLayout = enabled; + QSizePolicy policy(QSizePolicy::Expanding, enabled ? QSizePolicy::Fixed : QSizePolicy::Expanding); + policy.setHeightForWidth(enabled); + setSizePolicy(policy); + if (enabled) updateAspectHeight(); + else { setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); } + updateGeometry(); +} + +int VideoRenderWidget::heightForWidth(int width) const +{ + return m_frameAspectLayout ? qMax(1, qRound(double(width) * m_layoutFrameSize.height() + / m_layoutFrameSize.width())) : -1; +} + +QSize VideoRenderWidget::sizeHint() const +{ + return m_frameAspectLayout ? QSize(640,heightForWidth(640)) : QOpenGLWidget::sizeHint(); +} + +void VideoRenderWidget::updateAspectHeight() +{ + if (!m_frameAspectLayout) return; + const int wanted = heightForWidth(width()); + if (minimumHeight() != wanted || maximumHeight() != wanted) setFixedHeight(wanted); +} + +void VideoRenderWidget::resizeEvent(QResizeEvent *event) +{ + QOpenGLWidget::resizeEvent(event); + updateAspectHeight(); +} + +void VideoRenderWidget::setFrame(const VideoFrame &frame) +{ + if (!frame.isValid()) + return; + m_frame = frame; + if (m_layoutFrameSize != QSize(frame.width, frame.height)) { + m_layoutFrameSize = QSize(frame.width, frame.height); + updateAspectHeight(); + if (m_frameAspectLayout) updateGeometry(); + } + m_message.clear(); + m_frameDirty = true; + update(); +} + +void VideoRenderWidget::setImage(const QImage &image) +{ + if (image.isNull()) + return; + const QImage converted = image.convertToFormat(QImage::Format_RGBA8888); + VideoFrame frame; + frame.width = converted.width(); + frame.height = converted.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, + converted.constScanLine(row), static_cast(frame.width * 4)); + } + setFrame(frame); +} + +void VideoRenderWidget::clearFrame(const QString &message) +{ + m_frame = VideoFrame(); + m_message = message; + m_frameDirty = false; + update(); +} + +void VideoRenderWidget::initializeGL() +{ + initializeOpenGLFunctions(); + glClearColor(0.055f, 0.067f, 0.078f, 1.0f); + glGenTextures(3, m_textures); + + m_program.reset(new QOpenGLShaderProgram); + if (!m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource) || + !m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource) || + !m_program->link()) { + m_message = QStringLiteral("OpenGL 视频着色器初始化失败:%1").arg(m_program->log()); + m_program.reset(); + return; + } + m_glReady = true; +} + +void VideoRenderWidget::uploadPlane(unsigned int texture, int unit, int width, + int height, unsigned int format, + const QByteArray &data, int textureIndex) +{ + glActiveTexture(GL_TEXTURE0 + unit); + glBindTexture(GL_TEXTURE_2D, texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + if (m_textureWidths[textureIndex] != width || + m_textureHeights[textureIndex] != height || + m_textureFormats[textureIndex] != format) { + glTexImage2D(GL_TEXTURE_2D, 0, static_cast(format), width, height, 0, + format, GL_UNSIGNED_BYTE, data.constData()); + m_textureWidths[textureIndex] = width; + m_textureHeights[textureIndex] = height; + m_textureFormats[textureIndex] = format; + } else { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, + GL_UNSIGNED_BYTE, data.constData()); + } +} + +void VideoRenderWidget::paintGL() +{ + glClear(GL_COLOR_BUFFER_BIT); + if (!m_glReady || !m_program || !m_frame.isValid()) { + drawMessage(m_message); + return; + } + + // Qt 5.12's ANGLE backend can upload RGBA QImage data with an incorrect + // channel layout. Draw still RGBA frames with the CPU painter instead. + if (m_frame.format == VideoPixelFormat::RGBA) { + const QImage image(reinterpret_cast(m_frame.plane0.constData()), + m_frame.width, m_frame.height, m_frame.stride0, + QImage::Format_RGBA8888); + QPainter painter(this); + painter.fillRect(rect(), QColor(QStringLiteral("#0e1115"))); + QSize target = image.size(); + target.scale(size(), Qt::KeepAspectRatio); + const QRect destination((width() - target.width()) / 2, + (height() - target.height()) / 2, + target.width(), target.height()); + painter.drawImage(destination, image); + m_frameDirty = false; + return; + } + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + if (m_frameDirty) { + if (m_frame.format == VideoPixelFormat::I420) { + uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, + GL_LUMINANCE, m_frame.plane0, 0); + uploadPlane(m_textures[1], 1, m_frame.stride1, + (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane1, 1); + uploadPlane(m_textures[2], 2, m_frame.stride2, + (m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane2, 2); + } else if (m_frame.format == VideoPixelFormat::NV12) { + uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height, + GL_LUMINANCE, m_frame.plane0, 0); + uploadPlane(m_textures[1], 1, m_frame.stride1 / 2, + (m_frame.height + 1) / 2, GL_LUMINANCE_ALPHA, + m_frame.plane1, 1); + } else { + uploadPlane(m_textures[0], 0, m_frame.width, m_frame.height, + GL_RGBA, m_frame.plane0, 0); + } + m_frameDirty = false; + } + + const GLfloat vertices[] = { + -1.0f, -1.0f, 0.0f, 1.0f, + 1.0f, -1.0f, 1.0f, 1.0f, + -1.0f, 1.0f, 0.0f, 0.0f, + 1.0f, 1.0f, 1.0f, 0.0f + }; + float scaleX = 1.0f; + float scaleY = 1.0f; + const float frameAspect = static_cast(m_frame.width) / m_frame.height; + const float widgetAspect = width() > 0 && height() > 0 + ? static_cast(width()) / height() : frameAspect; + if (frameAspect > widgetAspect) + scaleY = widgetAspect / frameAspect; + else + scaleX = frameAspect / widgetAspect; + + m_program->bind(); + m_program->setUniformValue("contentScale", scaleX, scaleY); + m_program->setUniformValue("textureY", 0); + m_program->setUniformValue("textureU", 1); + m_program->setUniformValue("textureV", 2); + m_program->setUniformValue("pixelFormat", + m_frame.format == VideoPixelFormat::NV12 ? 1.0f : + m_frame.format == VideoPixelFormat::RGBA ? 2.0f : 0.0f); + m_program->setUniformValue("scaleY", m_frame.format == VideoPixelFormat::RGBA + ? 1.0f : static_cast(m_frame.width) / m_frame.stride0); + m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::NV12 + ? static_cast((m_frame.width + 1) / 2) / (m_frame.stride1 / 2) + : static_cast((m_frame.width + 1) / 2) / m_frame.stride1); + m_program->setUniformValue("scaleV", m_frame.format == VideoPixelFormat::I420 + ? static_cast((m_frame.width + 1) / 2) / m_frame.stride2 : 1.0f); + const int position = m_program->attributeLocation("position"); + const int texCoord = m_program->attributeLocation("texCoord"); + m_program->enableAttributeArray(position); + m_program->enableAttributeArray(texCoord); + m_program->setAttributeArray(position, GL_FLOAT, vertices, 2, 4 * sizeof(GLfloat)); + m_program->setAttributeArray(texCoord, GL_FLOAT, vertices + 2, 2, + 4 * sizeof(GLfloat)); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + m_program->disableAttributeArray(position); + m_program->disableAttributeArray(texCoord); + m_program->release(); +} + +void VideoRenderWidget::drawMessage(const QString &message) +{ + if (message.isEmpty()) + return; + QPainter painter(this); + painter.setPen(QColor(QStringLiteral("#8d98a5"))); + painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, message); +} + +void VideoRenderWidget::releaseTextures() +{ + if (m_textures[0]) { + glDeleteTextures(3, m_textures); + m_textures[0] = m_textures[1] = m_textures[2] = 0; + std::fill(m_textureWidths, m_textureWidths + 3, 0); + std::fill(m_textureHeights, m_textureHeights + 3, 0); + std::fill(m_textureFormats, m_textureFormats + 3, 0); + } +} From daf547e1c23e5361556c55068b8b2dde69bbab49 Mon Sep 17 00:00:00 2001 From: xtkuang <87661715@qq.com> Date: Fri, 9 Oct 2026 12:41:35 +0800 Subject: [PATCH 09/15] fix: include merged widgets in CMake build --- CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 55df4c3..7865982 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -158,6 +158,8 @@ set(CMVR_SOURCES src/audiostreammanager.h src/configeditorwidget.cpp src/configeditorwidget.h + src/jointfloweditor.cpp + src/jointfloweditor.h src/main.cpp src/mainwindow.cpp src/mainwindow_ui.cpp @@ -168,6 +170,8 @@ set(CMVR_SOURCES src/rpcservicewidget.h src/robotclient.cpp src/robotclient.h + src/tactileheatmapwidget.cpp + src/tactileheatmapwidget.h src/trendwidget.cpp src/trendwidget.h src/uiicons.h From aeca58c0877b75e64338989c839c209898ed06ce Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Fri, 9 Oct 2026 16:55:09 +0800 Subject: [PATCH 10/15] fix: isolate camera snapshot rendering --- CMakeLists.txt | 2 +- CmvrControlStation.pro | 2 +- src/mainwindow.cpp | 4 ++ src/videorenderwidget.cpp | 71 ++++++++++++++++------------- src/videorenderwidget.h | 94 ++++++++++++++++++++------------------- 5 files changed, 94 insertions(+), 79 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7865982..0e1a03e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.16) project(CmvrControlStation VERSION 1.0.0 LANGUAGES CXX) -set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_AUTOMOC ON) diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index be7c991..d184279 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -1,6 +1,6 @@ QT += core gui widgets multimedia 3dcore 3drender 3dextras 3dinput 3danimation -CONFIG += c++14 warn_on debug_and_release +CONFIG += c++17 warn_on debug_and_release TEMPLATE = app DEFINES += QT_DEPRECATED_WARNINGS _WIN32_WINNT=0x0600 diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index b87b384..c41afa2 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2006,6 +2006,10 @@ void MainWindow::updateVideoFrame(const QString &cameraId, const VideoFrame &fra { const QString resolvedId = cameraId.isEmpty() && !m_cameraPreviewTiles.isEmpty() ? m_cameraPreviewTiles.constBegin().key() : cameraId; + // The decoder thread can already have queued frames when a stream is + // stopped. Do not let those stale frames overwrite a later snapshot. + if (!m_runningCameraIds.contains(resolvedId)) + return; const auto it = m_cameraPreviewTiles.find(resolvedId); if (it == m_cameraPreviewTiles.end()) return; diff --git a/src/videorenderwidget.cpp b/src/videorenderwidget.cpp index 4036004..ba2b02f 100644 --- a/src/videorenderwidget.cpp +++ b/src/videorenderwidget.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -66,6 +68,10 @@ VideoRenderWidget::VideoRenderWidget(QWidget *parent) { setAutoFillBackground(false); setUpdateBehavior(QOpenGLWidget::NoPartialUpdate); + m_stillImageOverlay = new QLabel(this); + m_stillImageOverlay->setAlignment(Qt::AlignCenter); + m_stillImageOverlay->setStyleSheet(QStringLiteral("background: #0e1115;")); + m_stillImageOverlay->hide(); } VideoRenderWidget::~VideoRenderWidget() @@ -109,6 +115,7 @@ void VideoRenderWidget::updateAspectHeight() void VideoRenderWidget::resizeEvent(QResizeEvent *event) { QOpenGLWidget::resizeEvent(event); + updateStillImageOverlay(); updateAspectHeight(); } @@ -116,6 +123,9 @@ void VideoRenderWidget::setFrame(const VideoFrame &frame) { if (!frame.isValid()) return; + m_stillImage = QImage(); + m_stillImageOverlay->clear(); + m_stillImageOverlay->hide(); m_frame = frame; if (m_layoutFrameSize != QSize(frame.width, frame.height)) { m_layoutFrameSize = QSize(frame.width, frame.height); @@ -131,28 +141,41 @@ void VideoRenderWidget::setImage(const QImage &image) { if (image.isNull()) return; - const QImage converted = image.convertToFormat(QImage::Format_RGBA8888); - VideoFrame frame; - frame.width = converted.width(); - frame.height = converted.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, - converted.constScanLine(row), static_cast(frame.width * 4)); + m_stillImage = image.copy(); + if (m_layoutFrameSize != m_stillImage.size()) { + m_layoutFrameSize = m_stillImage.size(); + updateAspectHeight(); + if (m_frameAspectLayout) + updateGeometry(); } - setFrame(frame); + m_message.clear(); + updateStillImageOverlay(); + m_stillImageOverlay->show(); + m_stillImageOverlay->raise(); } void VideoRenderWidget::clearFrame(const QString &message) { m_frame = VideoFrame(); + m_stillImage = QImage(); + m_stillImageOverlay->clear(); + m_stillImageOverlay->hide(); m_message = message; m_frameDirty = false; update(); } +void VideoRenderWidget::updateStillImageOverlay() +{ + if (!m_stillImageOverlay) + return; + m_stillImageOverlay->setGeometry(rect()); + if (m_stillImage.isNull()) + return; + m_stillImageOverlay->setPixmap(QPixmap::fromImage(m_stillImage).scaled( + size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); +} + void VideoRenderWidget::initializeGL() { initializeOpenGLFunctions(); @@ -202,24 +225,6 @@ void VideoRenderWidget::paintGL() return; } - // Qt 5.12's ANGLE backend can upload RGBA QImage data with an incorrect - // channel layout. Draw still RGBA frames with the CPU painter instead. - if (m_frame.format == VideoPixelFormat::RGBA) { - const QImage image(reinterpret_cast(m_frame.plane0.constData()), - m_frame.width, m_frame.height, m_frame.stride0, - QImage::Format_RGBA8888); - QPainter painter(this); - painter.fillRect(rect(), QColor(QStringLiteral("#0e1115"))); - QSize target = image.size(); - target.scale(size(), Qt::KeepAspectRatio); - const QRect destination((width() - target.width()) / 2, - (height() - target.height()) / 2, - target.width(), target.height()); - painter.drawImage(destination, image); - m_frameDirty = false; - return; - } - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); if (m_frameDirty) { if (m_frame.format == VideoPixelFormat::I420) { @@ -268,9 +273,11 @@ void VideoRenderWidget::paintGL() m_frame.format == VideoPixelFormat::RGBA ? 2.0f : 0.0f); m_program->setUniformValue("scaleY", m_frame.format == VideoPixelFormat::RGBA ? 1.0f : static_cast(m_frame.width) / m_frame.stride0); - m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::NV12 - ? static_cast((m_frame.width + 1) / 2) / (m_frame.stride1 / 2) - : static_cast((m_frame.width + 1) / 2) / m_frame.stride1); + m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::RGBA + ? 1.0f + : m_frame.format == VideoPixelFormat::NV12 + ? static_cast((m_frame.width + 1) / 2) / (m_frame.stride1 / 2) + : static_cast((m_frame.width + 1) / 2) / m_frame.stride1); m_program->setUniformValue("scaleV", m_frame.format == VideoPixelFormat::I420 ? static_cast((m_frame.width + 1) / 2) / m_frame.stride2 : 1.0f); const int position = m_program->attributeLocation("position"); diff --git a/src/videorenderwidget.h b/src/videorenderwidget.h index 2b6bce1..34a7cbf 100644 --- a/src/videorenderwidget.h +++ b/src/videorenderwidget.h @@ -1,55 +1,59 @@ -#pragma once - -#include "videoframe.h" - -#include -#include -#include -#include - -#include - -class QOpenGLShaderProgram; - -class VideoRenderWidget : public QOpenGLWidget, protected QOpenGLFunctions -{ - Q_OBJECT - -public: - explicit VideoRenderWidget(QWidget *parent = nullptr); - ~VideoRenderWidget() override; - - void setFrame(const VideoFrame &frame); - void setImage(const QImage &image); - void clearFrame(const QString &message = QStringLiteral("暂无画面")); - bool hasFrame() const { return m_frame.isValid(); } +#pragma once + +#include "videoframe.h" + +#include +#include +#include +#include + +#include + +class QOpenGLShaderProgram; +class QLabel; + +class VideoRenderWidget : public QOpenGLWidget, protected QOpenGLFunctions +{ + Q_OBJECT + +public: + explicit VideoRenderWidget(QWidget *parent = nullptr); + ~VideoRenderWidget() override; + + void setFrame(const VideoFrame &frame); + void setImage(const QImage &image); + void clearFrame(const QString &message = QStringLiteral("暂无画面")); + bool hasFrame() const { return m_frame.isValid() || !m_stillImage.isNull(); } // Opt-in for calibration panels; other video pages keep their layout. void setFrameAspectLayoutEnabled(bool enabled); int heightForWidth(int width) const override; QSize sizeHint() const override; - -protected: - void initializeGL() override; + +protected: + void initializeGL() override; void paintGL() override; void resizeEvent(QResizeEvent *event) override; - -private: - void releaseTextures(); - void uploadPlane(unsigned int texture, int unit, int width, int height, - unsigned int format, const QByteArray &data, - int textureIndex); + +private: + void releaseTextures(); + void uploadPlane(unsigned int texture, int unit, int width, int height, + unsigned int format, const QByteArray &data, + int textureIndex); void drawMessage(const QString &message); void updateAspectHeight(); + void updateStillImageOverlay(); bool m_frameAspectLayout = false; QSize m_layoutFrameSize{640, 480}; // Placeholder until the first camera frame. - - std::unique_ptr m_program; - VideoFrame m_frame; - QString m_message = QStringLiteral("暂无画面"); - unsigned int m_textures[3] = {0, 0, 0}; - int m_textureWidths[3] = {0, 0, 0}; - int m_textureHeights[3] = {0, 0, 0}; - unsigned int m_textureFormats[3] = {0, 0, 0}; - bool m_frameDirty = false; - bool m_glReady = false; -}; + + std::unique_ptr m_program; + VideoFrame m_frame; + QImage m_stillImage; + QLabel *m_stillImageOverlay = nullptr; + QString m_message = QStringLiteral("暂无画面"); + unsigned int m_textures[3] = {0, 0, 0}; + int m_textureWidths[3] = {0, 0, 0}; + int m_textureHeights[3] = {0, 0, 0}; + unsigned int m_textureFormats[3] = {0, 0, 0}; + bool m_frameDirty = false; + bool m_glReady = false; +}; From d527f8ff245e1eb2f1b93a2fe2f79e88f100b8a3 Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Sat, 10 Oct 2026 11:38:26 +0800 Subject: [PATCH 11/15] feat: refine arm point workflow editor --- src/jointfloweditor.cpp | 120 ++++++-- src/mainwindow.cpp | 52 +--- src/mainwindow.h | 5 - src/mainwindow_ui.cpp | 607 +++++++++++++++++----------------------- styles.qss | 142 ++++++++++ 5 files changed, 508 insertions(+), 418 deletions(-) diff --git a/src/jointfloweditor.cpp b/src/jointfloweditor.cpp index f2849f6..8741bf9 100644 --- a/src/jointfloweditor.cpp +++ b/src/jointfloweditor.cpp @@ -1,4 +1,5 @@ #include "jointfloweditor.h" +#include "uiicons.h" #include #include @@ -9,8 +10,12 @@ #include #include #include +#include #include +#include #include +#include +#include #include #include #include @@ -28,6 +33,88 @@ namespace { constexpr qreal kNodeWidth = 190.0; constexpr qreal kNodeHeight = 76.0; +class NodeEditDialog final : public QDialog +{ +public: + NodeEditDialog(const QString &title, QWidget *parent) + : QDialog(parent, Qt::Tool | Qt::FramelessWindowHint) + { + setObjectName(QStringLiteral("jointFlowChildDialog")); + setAttribute(Qt::WA_TranslucentBackground); + QVBoxLayout *outerLayout = new QVBoxLayout(this); + outerLayout->setContentsMargins(12, 12, 12, 12); + outerLayout->setSpacing(0); + QFrame *surface = new QFrame(this); + surface->setObjectName(QStringLiteral("jointFlowChildSurface")); + QVBoxLayout *surfaceLayout = new QVBoxLayout(surface); + surfaceLayout->setContentsMargins(0, 0, 0, 0); + surfaceLayout->setSpacing(0); + m_titleBar = new QWidget(surface); + m_titleBar->setObjectName(QStringLiteral("jointFlowChildTitleBar")); + m_titleBar->setFixedHeight(44); + QHBoxLayout *titleLayout = new QHBoxLayout(m_titleBar); + titleLayout->setContentsMargins(12, 0, 0, 0); + titleLayout->setSpacing(9); + QLabel *mark = new QLabel(QStringLiteral("C"), m_titleBar); + mark->setObjectName(QStringLiteral("jointFlowDialogMark")); + mark->setAlignment(Qt::AlignCenter); + mark->setFixedSize(24, 24); + QLabel *titleLabel = new QLabel(title, m_titleBar); + titleLabel->setObjectName(QStringLiteral("jointFlowDialogTitle")); + QPushButton *closeButton = new QPushButton(m_titleBar); + closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton")); + closeButton->setFixedSize(46, 43); + closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"), + QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#ffffff")))); + titleLayout->addWidget(mark); + titleLayout->addWidget(titleLabel); + titleLayout->addStretch(1); + titleLayout->addWidget(closeButton); + surfaceLayout->addWidget(m_titleBar); + QWidget *content = new QWidget(surface); + content->setObjectName(QStringLiteral("jointFlowChildContent")); + m_contentLayout = new QVBoxLayout(content); + m_contentLayout->setContentsMargins(18, 16, 18, 16); + m_contentLayout->setSpacing(12); + surfaceLayout->addWidget(content, 1); + outerLayout->addWidget(surface); + m_titleBar->installEventFilter(this); + titleLabel->installEventFilter(this); + mark->installEventFilter(this); + connect(closeButton, &QPushButton::clicked, this, &QDialog::reject); + } + + QVBoxLayout *contentLayout() const { return m_contentLayout; } + +protected: + bool eventFilter(QObject *watched, QEvent *event) override + { + if ((watched == m_titleBar || (watched && watched->parent() == m_titleBar)) && event) { + if (event->type() == QEvent::MouseButtonPress) { + QMouseEvent *mouseEvent = static_cast(event); + if (mouseEvent->button() == Qt::LeftButton) { + m_dragging = true; + m_dragOffset = mouseEvent->globalPos() - frameGeometry().topLeft(); + return true; + } + } else if (event->type() == QEvent::MouseMove && m_dragging) { + QMouseEvent *mouseEvent = static_cast(event); + move(mouseEvent->globalPos() - m_dragOffset); + return true; + } else if (event->type() == QEvent::MouseButtonRelease) { + m_dragging = false; + } + } + return QDialog::eventFilter(watched, event); + } + +private: + QWidget *m_titleBar = nullptr; + QVBoxLayout *m_contentLayout = nullptr; + QPoint m_dragOffset; + bool m_dragging = false; +}; + class FlowGraphicsView final : public QGraphicsView { public: @@ -102,13 +189,13 @@ public: void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override { painter->setRenderHint(QPainter::Antialiasing); - const QColor fill = m_loop ? QColor("#262044") : QColor("#163447"); - const QColor border = m_active ? QColor("#56d39b") - : (isSelected() ? QColor("#64b5f6") : QColor("#52606d")); + const QColor fill = m_loop ? QColor("#f4efff") : QColor("#ffffff"); + const QColor border = m_active ? QColor("#20a36a") + : (isSelected() ? QColor("#1b6ef3") : QColor("#cbd6e2")); painter->setPen(QPen(border, m_active ? 3.0 : 1.5)); painter->setBrush(fill); painter->drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), 10, 10); - painter->setPen(QColor("#f2f5f7")); + painter->setPen(QColor("#25313d")); QFont titleFont = painter->font(); titleFont.setBold(true); painter->setFont(titleFont); @@ -116,14 +203,14 @@ public: Qt::AlignLeft | Qt::AlignVCenter, m_title); if (m_loop) { - const QColor buttonFill = m_collapsePressed ? QColor("#2563a8") - : m_collapseHovered ? QColor("#244d78") : QColor("#17263a"); + const QColor buttonFill = m_collapsePressed ? QColor("#d8e9ff") + : m_collapseHovered ? QColor("#e8f2ff") : QColor("#ffffff"); const QColor buttonBorder = m_collapseHovered || m_collapsePressed - ? QColor("#64b5f6") : QColor("#71869b"); + ? QColor("#1b6ef3") : QColor("#b8c7d8"); painter->setPen(QPen(buttonBorder, 1.4)); painter->setBrush(buttonFill); painter->drawRoundedRect(collapseButtonRect(), 5, 5); - painter->setPen(QPen(QColor("#f4f8fc"), 1.8, + painter->setPen(QPen(QColor("#286fc2"), 1.8, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); const QPointF center = collapseButtonRect().center(); QPolygonF arrow; @@ -139,7 +226,7 @@ public: painter->drawPolyline(arrow); } painter->setFont(QFont()); - painter->setPen(QColor("#aeb8c2")); + painter->setPen(QColor("#687684")); painter->drawText(QRectF(14, 38, kNodeWidth - 28, 26), Qt::AlignLeft | Qt::AlignVCenter, m_subtitle); } @@ -218,11 +305,13 @@ private: JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent) { + setObjectName(QStringLiteral("jointFlowEditor")); QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); m_scene = new QGraphicsScene(this); - m_scene->setBackgroundBrush(QColor("#10161d")); + m_scene->setBackgroundBrush(QColor("#f4f7fa")); m_view = new FlowGraphicsView(m_scene, this); + m_view->setObjectName(QStringLiteral("jointFlowCanvas")); m_view->setRenderHint(QPainter::Antialiasing); m_view->setDragMode(QGraphicsView::RubberBandDrag); m_view->setMinimumHeight(230); @@ -466,11 +555,10 @@ void JointFlowEditor::editNode(const QString &id) Node *node = nodeById(id); if (!node) return; - QDialog dialog(this); - dialog.setWindowTitle(node->type == SingleNode - ? QStringLiteral("编辑单步节点") : QStringLiteral("编辑循环节点")); + NodeEditDialog dialog(node->type == SingleNode + ? QStringLiteral("编辑单步节点") : QStringLiteral("编辑循环节点"), this); dialog.setMinimumWidth(420); - QVBoxLayout *dialogLayout = new QVBoxLayout(&dialog); + QVBoxLayout *dialogLayout = dialog.contentLayout(); QFormLayout *form = new QFormLayout; QLineEdit *nameEdit = new QLineEdit(node->nodeName, &dialog); form->addRow(QStringLiteral("节点名称"), nameEdit); @@ -638,7 +726,7 @@ void JointFlowEditor::rebuildScene() continue; const QPointF from = cards.value(node.parentId)->sceneBoundingRect().center(); const QPointF to = cards.value(node.id)->sceneBoundingRect().center(); - m_scene->addLine(QLineF(from, to), QPen(QColor("#667788"), 2.0)); + m_scene->addLine(QLineF(from, to), QPen(QColor("#9aabc0"), 2.0)); } QStringList parentIds{QString()}; for (const Node &node : m_nodes) @@ -651,7 +739,7 @@ void JointFlowEditor::rebuildScene() if (!cards.contains(previous->id) || !cards.contains(current->id)) continue; const QPointF from = cards.value(previous->id)->sceneBoundingRect().center(); const QPointF to = cards.value(current->id)->sceneBoundingRect().center(); - m_scene->addLine(QLineF(from, to), QPen(QColor("#3f8db3"), 1.5, Qt::DashLine)); + m_scene->addLine(QLineF(from, to), QPen(QColor("#5a91cf"), 1.5, Qt::DashLine)); } } m_scene->setSceneRect(m_scene->itemsBoundingRect().adjusted(-60, -60, 60, 60)); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index c41afa2..ab2270e 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1447,25 +1447,7 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo if (row == 0 && m_trend) m_trend->appendSample(position, velocity); } - - const QList motionTables = {m_leftMotionTable, m_motionTable}; - for (QTableWidget *table : motionTables) { - if (!table) - continue; - for (int row = 0; row < table->rowCount(); ++row) { - const QTableWidgetItem *nameItem = table->item(row, 0); - if (!nameItem) - continue; - const QVariantMap joint = byName.value(nameItem->text()); - if (!joint.isEmpty()) { - const double position = joint.value(QStringLiteral("position")).toDouble(); - table->item(row, 1)->setText(QStringLiteral("%1°").arg( - qRadiansToDegrees(position), - 0, 'f', 2)); - table->item(row, 2)->setText(QString::number(position, 'f', 6)); - } - } - } + m_lastArmTelemetryMs = nowMs; if (!pose.isEmpty()) { m_latestArmPose = pose; @@ -2185,11 +2167,7 @@ void MainWindow::appendLog(const QString &level, const QString &message) void MainWindow::sendMoveJ() { QVariantList positions; - const bool leftArm = m_armSideCombo - && m_armSideCombo->currentData().toString() == QStringLiteral("left"); - const QList &spins = leftArm - ? m_leftTargetSpins : m_rightTargetSpins; - for (QDoubleSpinBox *spin : spins) + for (QDoubleSpinBox *spin : m_targetSpins) positions.append(qDegreesToRadians(spin->value())); m_client->requestMoveJ(m_armIdEdit->text().trimmed(), positions, m_velocitySpin->value(), m_accelerationSpin->value()); @@ -2249,9 +2227,7 @@ void MainWindow::recordCurrentJointPoint() } } - const bool leftArm = m_armSideCombo - && m_armSideCombo->currentData().toString() == QStringLiteral("left"); - const QStringList jointNames = leftArm ? m_leftArmJointNames : m_rightArmJointNames; + const QStringList jointNames = m_activeArmJointNames; if (jointNames.isEmpty()) { QMessageBox::warning(this, QStringLiteral("记录关节点位"), QStringLiteral("当前 URDF 中没有该机械臂的可运动关节。")); @@ -2260,8 +2236,9 @@ void MainWindow::recordCurrentJointPoint() RecordedJointPoint point; point.name = name; - point.side = leftArm ? QStringLiteral("left") : QStringLiteral("right"); point.deviceId = m_armIdEdit->text().trimmed(); + point.side = point.deviceId.contains(QStringLiteral("left"), Qt::CaseInsensitive) + ? QStringLiteral("left") : QStringLiteral("right"); point.jointNames = jointNames; QStringList missing; for (const QString &jointName : jointNames) { @@ -2477,25 +2454,8 @@ void MainWindow::loadSettings() m_portSpin->setValue(settings.value(QStringLiteral("connection/port"), 50052).toInt()); m_demoCheck->setChecked(settings.value(QStringLiteral("connection/demo"), true).toBool()); m_systemTargetEdit->setText(settings.value(QStringLiteral("system/target"), QStringLiteral("*")).toString()); - const QString armSide = settings.value(QStringLiteral("arm/side"), - QStringLiteral("right")).toString(); - if (m_armSideCombo) { - const int sideIndex = m_armSideCombo->findData(armSide); - if (sideIndex >= 0) - m_armSideCombo->setCurrentIndex(sideIndex); - } - const QString defaultArmDeviceId = armSide == QStringLiteral("left") - ? QStringLiteral("left_ethercat_arm") : QStringLiteral("right_ethercat_arm"); QString armDeviceId = settings.value(QStringLiteral("arm/device"), - defaultArmDeviceId).toString().trimmed(); - if (armDeviceId == QStringLiteral("left_arm") || - armDeviceId == QStringLiteral("eyou_left_arm")) { - armDeviceId = QStringLiteral("left_ethercat_arm"); - } else if (armDeviceId == QStringLiteral("right_arm") || - armDeviceId == QStringLiteral("eyou_arm") || - armDeviceId == QStringLiteral("eyou_right_arm")) { - armDeviceId = QStringLiteral("right_ethercat_arm"); - } + QStringLiteral("demo_arm")).toString().trimmed(); m_armIdEdit->setText(armDeviceId); if (m_armSideCombo && !armDeviceId.isEmpty()) m_armSideCombo->addItem(armDeviceId, armDeviceId); diff --git a/src/mainwindow.h b/src/mainwindow.h index 8a99e4a..21f3848 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -194,12 +194,7 @@ private: TrendWidget *m_trend = nullptr; QTableWidget *m_jointTable = nullptr; QTableWidget *m_motionTable = nullptr; - QTableWidget *m_leftMotionTable = nullptr; QList m_targetSpins; - QList m_leftTargetSpins; - QList m_rightTargetSpins; - QStringList m_leftArmJointNames; - QStringList m_rightArmJointNames; QStringList m_activeArmJointNames; QList m_moveJPoseSpins; QComboBox *m_moveJPoseBaseLinkCombo = nullptr; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index d820326..7b18d82 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -62,13 +63,16 @@ #include #include +#ifdef Q_OS_WIN +#include +#endif + namespace { class FramelessToolDialog final : public QDialog { public: explicit FramelessToolDialog(QWidget *parent = nullptr) - : QDialog(parent, Qt::Tool | Qt::FramelessWindowHint - | Qt::WindowStaysOnTopHint) + : QDialog(parent, Qt::Tool | Qt::FramelessWindowHint) { setAttribute(Qt::WA_TranslucentBackground); } @@ -87,6 +91,36 @@ public: } protected: + bool nativeEvent(const QByteArray &eventType, void *message, long *result) override + { +#ifdef Q_OS_WIN + Q_UNUSED(eventType) + MSG *nativeMessage = static_cast(message); + if (nativeMessage && nativeMessage->message == WM_NCHITTEST && result + && !isMaximized()) { + const QPoint position = mapFromGlobal(QCursor::pos()); + const int border = 8; + const bool left = position.x() >= 0 && position.x() < border; + const bool right = position.x() < width() && position.x() >= width() - border; + const bool top = position.y() >= 0 && position.y() < border; + const bool bottom = position.y() < height() && position.y() >= height() - border; + 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; } + } +#else + Q_UNUSED(eventType) + Q_UNUSED(message) + Q_UNUSED(result) +#endif + return QDialog::nativeEvent(eventType, message, result); + } + bool eventFilter(QObject *watched, QEvent *event) override { if (m_dragHandle && event) { @@ -116,6 +150,80 @@ private: bool m_dragging = false; }; +QString requestFlowNodeName(QWidget *parent, const QString &title, + const QString &initialValue, bool *accepted) +{ + FramelessToolDialog dialog(parent); + dialog.setObjectName(QStringLiteral("jointFlowChildDialog")); + dialog.setModal(true); + dialog.setMinimumSize(420, 210); + dialog.resize(460, 230); + QVBoxLayout *outerLayout = new QVBoxLayout(&dialog); + outerLayout->setContentsMargins(12, 12, 12, 12); + outerLayout->setSpacing(0); + QFrame *surface = new QFrame(&dialog); + surface->setObjectName(QStringLiteral("jointFlowChildSurface")); + QVBoxLayout *surfaceLayout = new QVBoxLayout(surface); + surfaceLayout->setContentsMargins(0, 0, 0, 0); + surfaceLayout->setSpacing(0); + QWidget *titleBar = new QWidget(surface); + titleBar->setObjectName(QStringLiteral("jointFlowChildTitleBar")); + titleBar->setFixedHeight(44); + QHBoxLayout *titleLayout = new QHBoxLayout(titleBar); + titleLayout->setContentsMargins(12, 0, 0, 0); + titleLayout->setSpacing(9); + QLabel *mark = new QLabel(QStringLiteral("C"), titleBar); + mark->setObjectName(QStringLiteral("jointFlowDialogMark")); + mark->setAlignment(Qt::AlignCenter); + mark->setFixedSize(24, 24); + QLabel *titleLabel = new QLabel(title, titleBar); + titleLabel->setObjectName(QStringLiteral("jointFlowDialogTitle")); + QPushButton *closeButton = new QPushButton(titleBar); + closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton")); + closeButton->setFixedSize(46, 43); + closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"), + QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#ffffff")))); + titleLayout->addWidget(mark); + titleLayout->addWidget(titleLabel); + titleLayout->addStretch(1); + titleLayout->addWidget(closeButton); + surfaceLayout->addWidget(titleBar); + QWidget *content = new QWidget(surface); + content->setObjectName(QStringLiteral("jointFlowChildContent")); + QVBoxLayout *contentLayout = new QVBoxLayout(content); + contentLayout->setContentsMargins(18, 16, 18, 16); + contentLayout->setSpacing(9); + QLabel *fieldLabel = new QLabel(QStringLiteral("节点名称"), content); + QLineEdit *nameEdit = new QLineEdit(initialValue, content); + QHBoxLayout *actions = new QHBoxLayout; + QPushButton *cancelButton = new QPushButton(QStringLiteral("取消"), content); + cancelButton->setObjectName(QStringLiteral("secondaryButton")); + QPushButton *okButton = new QPushButton(QStringLiteral("确定"), content); + okButton->setObjectName(QStringLiteral("primaryButton")); + actions->addStretch(1); + actions->addWidget(cancelButton); + actions->addWidget(okButton); + contentLayout->addWidget(fieldLabel); + contentLayout->addWidget(nameEdit); + contentLayout->addStretch(1); + contentLayout->addLayout(actions); + surfaceLayout->addWidget(content, 1); + outerLayout->addWidget(surface); + dialog.setDragHandle(titleBar); + QObject::connect(closeButton, &QPushButton::clicked, &dialog, &QDialog::reject); + QObject::connect(cancelButton, &QPushButton::clicked, &dialog, &QDialog::reject); + QObject::connect(okButton, &QPushButton::clicked, &dialog, &QDialog::accept); + QObject::connect(nameEdit, &QLineEdit::returnPressed, &dialog, &QDialog::accept); + QTimer::singleShot(0, nameEdit, [nameEdit]() { + nameEdit->setFocus(); + nameEdit->selectAll(); + }); + const bool ok = dialog.exec() == QDialog::Accepted; + if (accepted) + *accepted = ok; + return ok ? nameEdit->text().trimmed() : QString(); +} + class AccentRowDelegate final : public QStyledItemDelegate { public: @@ -140,31 +248,6 @@ public: } }; -QStringList armJointNames(bool leftArm) -{ - const QString prefix = leftArm ? QStringLiteral("L_") : QStringLiteral("R_"); - return { - prefix + QStringLiteral("SHOULDER_P"), prefix + QStringLiteral("SHOULDER_R"), - prefix + QStringLiteral("SHOULDER_Y"), prefix + QStringLiteral("ELBOW_R"), - prefix + QStringLiteral("WRIST_P"), prefix + QStringLiteral("WRIST_Y"), - prefix + QStringLiteral("WRIST_R") - }; -} - -bool isArmJointForSide(const QString &jointName, bool leftArm) -{ - const QString lower = jointName.toLower(); - const QString sideWord = leftArm ? QStringLiteral("left") : QStringLiteral("right"); - const QString sidePrefix = leftArm ? QStringLiteral("l_") : QStringLiteral("r_"); - return lower.contains(sideWord + QStringLiteral("_arm")) - || lower.contains(sideWord + QStringLiteral("arm")) - || (lower.startsWith(sidePrefix) - && (lower.contains(QStringLiteral("shoulder")) - || lower.contains(QStringLiteral("elbow")) - || lower.contains(QStringLiteral("wrist")) - || lower.contains(QStringLiteral("arm")))); -} - QWidget *withRpcExplorer(QWidget *commonPage, RobotClient *client, const QString &serviceName) { @@ -296,29 +379,6 @@ QWidget *MainWindow::createArmPage() ui.armTabs->insertTab(0, ui.urdfTab, QStringLiteral("模型与控制")); } - // Keep device safety controls, the model, MoveJ targets and teaching in one workspace. - ui.commandPanel->setParent(ui.urdfTab); - ui.urdfTabLayout->insertWidget(0, ui.commandPanel); - - // Qt3D preview is disabled in release builds. Keep the viewer alive and - // hidden so it can still parse the URDF and provide the joint list, while - // giving the complete workspace height to the command/point-flow tables. - ui.urdfTabLayout->removeWidget(ui.urdfViewer); - ui.urdfViewer->hide(); - ui.targetsPanel->setMinimumHeight(0); - ui.targetsPanel->setMaximumHeight(QWIDGETSIZE_MAX); - ui.targetsPanel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); - ui.urdfTabLayout->insertWidget(1, ui.targetsPanel, 1); - ui.urdfTabLayout->setStretch(0, 0); - ui.urdfTabLayout->setStretch(1, 1); - - const int legacyCommandTabIndex = ui.armTabs->indexOf(ui.jointControlTab); - if (legacyCommandTabIndex >= 0) { - ui.armTabs->removeTab(legacyCommandTabIndex); - ui.jointControlTab->hide(); - } - ui.armTabs->setCurrentWidget(ui.urdfTab); - m_armIdEdit = ui.armIdEdit; m_armTelemetryButton = ui.armTelemetryButton; m_armDeviceSummary = ui.commandSubtitle; @@ -379,69 +439,41 @@ QWidget *MainWindow::createArmPage() ui.poseValue->hide(); ui.updatedValue->hide(); - QWidget *directMovePage = new QWidget; - QVBoxLayout *directMoveLayout = new QVBoxLayout(directMovePage); - directMoveLayout->setContentsMargins(0, 8, 0, 0); - directMoveLayout->setSpacing(8); - QSplitter *armTargetTables = new QSplitter(Qt::Vertical, directMovePage); - armTargetTables->setObjectName(QStringLiteral("armTargetTables")); - armTargetTables->setChildrenCollapsible(false); - QWidget *leftTargets = new QWidget(armTargetTables); - leftTargets->setObjectName(QStringLiteral("armTargetGroup")); - QVBoxLayout *leftTargetsLayout = new QVBoxLayout(leftTargets); - leftTargetsLayout->setContentsMargins(0, 4, 6, 0); - QLabel *leftTargetsTitle = new QLabel(QStringLiteral("左臂 · left_ethercat_arm"), leftTargets); - leftTargetsTitle->setObjectName(QStringLiteral("eyebrow")); - m_leftMotionTable = new QTableWidget(7, 4, leftTargets); - m_leftMotionTable->setObjectName(QStringLiteral("leftMotionTable")); - leftTargetsLayout->addWidget(leftTargetsTitle); - leftTargetsLayout->addWidget(m_leftMotionTable); - QWidget *rightTargets = new QWidget(armTargetTables); - rightTargets->setObjectName(QStringLiteral("armTargetGroup")); - QVBoxLayout *rightTargetsLayout = new QVBoxLayout(rightTargets); - rightTargetsLayout->setContentsMargins(6, 4, 0, 0); - QLabel *rightTargetsTitle = new QLabel(QStringLiteral("右臂 · right_ethercat_arm"), rightTargets); - rightTargetsTitle->setObjectName(QStringLiteral("eyebrow")); - m_motionTable->setParent(rightTargets); - rightTargetsLayout->addWidget(rightTargetsTitle); - rightTargetsLayout->addWidget(m_motionTable); - armTargetTables->addWidget(leftTargets); - armTargetTables->addWidget(rightTargets); - armTargetTables->setSizes({340, 340}); - directMoveLayout->addWidget(armTargetTables, 1); - QHBoxLayout *directMoveActions = new QHBoxLayout; - ui.zeroButton->setParent(directMovePage); - ui.safetyHint->setParent(directMovePage); - m_sendMoveButton->setParent(directMovePage); - directMoveActions->addWidget(ui.zeroButton); - directMoveActions->addWidget(ui.safetyHint, 1); - directMoveActions->addWidget(m_sendMoveButton); - directMoveLayout->addLayout(directMoveActions); - QWidget *moveJPage = new QWidget; + moveJPage->setObjectName(QStringLiteral("jointFlowWorkspace")); QVBoxLayout *moveJLayout = new QVBoxLayout(moveJPage); - moveJLayout->setContentsMargins(0, 0, 0, 0); - moveJLayout->setSpacing(10); + moveJLayout->setContentsMargins(16, 14, 16, 16); + moveJLayout->setSpacing(12); QFrame *pointPanel = new QFrame(moveJPage); - pointPanel->setObjectName(QStringLiteral("panelCard")); + pointPanel->setObjectName(QStringLiteral("jointPointPanel")); QVBoxLayout *pointLayout = new QVBoxLayout(pointPanel); pointLayout->setContentsMargins(12, 10, 12, 10); pointLayout->setSpacing(8); QHBoxLayout *pointHeader = new QHBoxLayout; QLabel *pointTitle = new QLabel(QStringLiteral("关节点位记录与循环"), pointPanel); - pointTitle->setObjectName(QStringLiteral("panelTitle")); + pointTitle->setObjectName(QStringLiteral("jointFlowSectionTitle")); + QLabel *pointSubtitle = new QLabel( + QStringLiteral("记录当前关节角度,作为流程中的可执行点位"), pointPanel); + pointSubtitle->setObjectName(QStringLiteral("jointFlowSectionSubtitle")); + QVBoxLayout *pointHeading = new QVBoxLayout; + pointHeading->setSpacing(2); + pointHeading->addWidget(pointTitle); + pointHeading->addWidget(pointSubtitle); m_jointPointNameEdit = new QLineEdit(pointPanel); m_jointPointNameEdit->setPlaceholderText(QStringLiteral("动作名称,例如:抓取准备")); m_jointPointNameEdit->setMinimumWidth(220); m_recordJointPointButton = new QPushButton(QStringLiteral("记录当前角度"), pointPanel); - pointHeader->addWidget(pointTitle); + m_recordJointPointButton->setObjectName(QStringLiteral("primaryButton")); + pointHeader->addLayout(pointHeading); pointHeader->addStretch(1); pointHeader->addWidget(m_jointPointNameEdit); pointHeader->addWidget(m_recordJointPointButton); pointLayout->addLayout(pointHeader); m_jointPointTable = new QTableWidget(0, 5, pointPanel); + m_jointPointTable->setObjectName(QStringLiteral("jointPointTable")); + m_jointPointTable->setAlternatingRowColors(true); m_jointPointTable->setHorizontalHeaderLabels({ QStringLiteral("动作名称"), QStringLiteral("机械臂"), QStringLiteral("Device ID"), QStringLiteral("关节数"), QStringLiteral("关节角度(rad)")}); @@ -466,6 +498,8 @@ QWidget *MainWindow::createArmPage() QHBoxLayout *pointActions = new QHBoxLayout; m_runJointPointButton = new QPushButton(QStringLiteral("执行选中点位"), pointPanel); m_deleteJointPointButton = new QPushButton(QStringLiteral("删除选中"), pointPanel); + m_runJointPointButton->setObjectName(QStringLiteral("primaryButton")); + m_deleteJointPointButton->setObjectName(QStringLiteral("dangerOutlineButton")); QLabel *loopCountLabel = new QLabel(QStringLiteral("循环次数"), pointPanel); m_jointPointLoopCount = new QSpinBox(pointPanel); m_jointPointLoopCount->setRange(1, 10000); @@ -480,8 +514,6 @@ QWidget *MainWindow::createArmPage() pointActions->addStretch(1); pointActions->addWidget(m_jointPointLoopStatus); pointLayout->addLayout(pointActions); - moveJLayout->addWidget(pointPanel, 2); - connect(m_recordJointPointButton, &QPushButton::clicked, this, &MainWindow::recordCurrentJointPoint); connect(m_runJointPointButton, &QPushButton::clicked, @@ -533,13 +565,15 @@ QWidget *MainWindow::createArmPage() }); QFrame *flowPanel = new QFrame(moveJPage); - flowPanel->setObjectName(QStringLiteral("panelCard")); + flowPanel->setObjectName(QStringLiteral("jointFlowPanel")); QVBoxLayout *flowLayout = new QVBoxLayout(flowPanel); flowLayout->setContentsMargins(12, 10, 12, 10); flowLayout->setSpacing(8); - QHBoxLayout *flowBuilder = new QHBoxLayout; QLabel *flowTitle = new QLabel(QStringLiteral("自定义执行流程"), flowPanel); - flowTitle->setObjectName(QStringLiteral("panelTitle")); + flowTitle->setObjectName(QStringLiteral("jointFlowSectionTitle")); + QLabel *flowSubtitle = new QLabel( + QStringLiteral("组合单步与循环节点,拖动调整执行顺序"), flowPanel); + flowSubtitle->setObjectName(QStringLiteral("jointFlowSectionSubtitle")); QLabel *intervalLabel = new QLabel(QStringLiteral("完成后等待"), flowPanel); m_jointPointInterval = new QDoubleSpinBox(flowPanel); m_jointPointInterval->setRange(0.0, 3600.0); @@ -550,23 +584,41 @@ QWidget *MainWindow::createArmPage() m_jointFlowGroupCount->setRange(1, 10000); m_jointFlowGroupCount->setValue(2); QLabel *insertionContextLabel = new QLabel(QStringLiteral("添加到:根流程"), flowPanel); - insertionContextLabel->setObjectName(QStringLiteral("mutedLabel")); + insertionContextLabel->setObjectName(QStringLiteral("jointFlowContextChip")); QPushButton *insertAtRootButton = new QPushButton(QStringLiteral("返回根流程"), flowPanel); QPushButton *enterSelectedLoopButton = new QPushButton(QStringLiteral("进入选中循环"), flowPanel); QPushButton *addFlowStepButton = new QPushButton(QStringLiteral("+ 单步节点"), flowPanel); QPushButton *addFlowLoopButton = new QPushButton(QStringLiteral("+ 循环节点"), flowPanel); - flowBuilder->addWidget(flowTitle); - flowBuilder->addWidget(insertionContextLabel); + insertAtRootButton->setObjectName(QStringLiteral("secondaryButton")); + enterSelectedLoopButton->setObjectName(QStringLiteral("secondaryButton")); + addFlowStepButton->setObjectName(QStringLiteral("primaryButton")); + addFlowLoopButton->setObjectName(QStringLiteral("secondaryButton")); + QHBoxLayout *flowHeader = new QHBoxLayout; + QVBoxLayout *flowHeading = new QVBoxLayout; + flowHeading->setSpacing(2); + flowHeading->addWidget(flowTitle); + flowHeading->addWidget(flowSubtitle); + flowHeader->addLayout(flowHeading); + flowHeader->addStretch(1); + flowHeader->addWidget(insertionContextLabel); + flowLayout->addLayout(flowHeader); + + QFrame *flowToolbar = new QFrame(flowPanel); + flowToolbar->setObjectName(QStringLiteral("jointFlowToolbar")); + QHBoxLayout *flowBuilder = new QHBoxLayout(flowToolbar); + flowBuilder->setContentsMargins(10, 8, 10, 8); + flowBuilder->setSpacing(8); flowBuilder->addWidget(insertAtRootButton); flowBuilder->addWidget(enterSelectedLoopButton); - flowBuilder->addStretch(1); + flowBuilder->addSpacing(8); flowBuilder->addWidget(intervalLabel); flowBuilder->addWidget(m_jointPointInterval); flowBuilder->addWidget(addFlowStepButton); + flowBuilder->addStretch(1); flowBuilder->addWidget(new QLabel(QStringLiteral("循环次数"), flowPanel)); flowBuilder->addWidget(m_jointFlowGroupCount); flowBuilder->addWidget(addFlowLoopButton); - flowLayout->addLayout(flowBuilder); + flowLayout->addWidget(flowToolbar); QLabel *flowHint = new QLabel(QStringLiteral( "默认在根流程添加;选中循环后点击“进入选中循环”,可向循环内添加节点。" "点击“返回根流程”退出循环;双击卡片编辑参数,左键拖动节点,右键拖动画布。" @@ -577,6 +629,9 @@ QWidget *MainWindow::createArmPage() flowLayout->addWidget(m_jointFlowEditor); QHBoxLayout *flowActions = new QHBoxLayout; QPushButton *flowDeleteButton = new QPushButton(QStringLiteral("删除选中节点"), flowPanel); + flowDeleteButton->setObjectName(QStringLiteral("dangerOutlineButton")); + m_startJointPointLoopButton->setObjectName(QStringLiteral("primaryButton")); + m_stopJointPointLoopButton->setObjectName(QStringLiteral("dangerButton")); flowActions->addWidget(flowDeleteButton); flowActions->addStretch(1); flowActions->addWidget(loopCountLabel); @@ -585,12 +640,19 @@ QWidget *MainWindow::createArmPage() flowActions->addWidget(m_startJointPointLoopButton); flowActions->addWidget(m_stopJointPointLoopButton); flowLayout->addLayout(flowActions); - moveJLayout->addWidget(flowPanel, 3); + QSplitter *jointFlowSplitter = new QSplitter(Qt::Vertical, moveJPage); + jointFlowSplitter->setObjectName(QStringLiteral("jointFlowSplitter")); + jointFlowSplitter->addWidget(pointPanel); + jointFlowSplitter->addWidget(flowPanel); + jointFlowSplitter->setStretchFactor(0, 1); + jointFlowSplitter->setStretchFactor(1, 3); + jointFlowSplitter->setSizes({245, 510}); + moveJLayout->addWidget(jointFlowSplitter, 1); connect(addFlowStepButton, &QPushButton::clicked, this, [this]() { const QModelIndexList rows = m_jointPointTable->selectionModel()->selectedRows(); if (rows.isEmpty()) { - QMessageBox::information(this, QStringLiteral("添加单步节点"), + QMessageBox::information(m_jointFlowDialog, QStringLiteral("添加单步节点"), QStringLiteral("请先选择一个已记录点位。")); return; } @@ -598,9 +660,8 @@ QWidget *MainWindow::createArmPage() if (row >= 0 && row < m_recordedJointPoints.size()) { const QString executionUnit = m_recordedJointPoints.at(row).name; bool ok = false; - const QString nodeName = QInputDialog::getText( - this, QStringLiteral("新增单步节点"), QStringLiteral("节点名称"), - QLineEdit::Normal, executionUnit, &ok).trimmed(); + const QString nodeName = requestFlowNodeName( + m_jointFlowDialog, QStringLiteral("新增单步节点"), executionUnit, &ok); if (ok && !nodeName.isEmpty()) m_jointFlowEditor->addSingleNode(nodeName, executionUnit, m_jointPointInterval->value()); @@ -608,9 +669,8 @@ QWidget *MainWindow::createArmPage() }); connect(addFlowLoopButton, &QPushButton::clicked, this, [this]() { bool ok = false; - const QString nodeName = QInputDialog::getText( - this, QStringLiteral("新增循环节点"), QStringLiteral("节点名称"), - QLineEdit::Normal, QStringLiteral("循环"), &ok).trimmed(); + const QString nodeName = requestFlowNodeName( + m_jointFlowDialog, QStringLiteral("新增循环节点"), QStringLiteral("循环"), &ok); if (ok && !nodeName.isEmpty()) m_jointFlowEditor->addLoopNode(nodeName, m_jointFlowGroupCount->value(), m_jointPointInterval->value()); @@ -619,7 +679,7 @@ QWidget *MainWindow::createArmPage() m_jointFlowEditor, &JointFlowEditor::setInsertionAtRoot); connect(enterSelectedLoopButton, &QPushButton::clicked, this, [this]() { if (!m_jointFlowEditor->useSelectedLoopAsInsertionParent()) { - QMessageBox::information(this, QStringLiteral("进入循环"), + QMessageBox::information(m_jointFlowDialog, QStringLiteral("进入循环"), QStringLiteral("请先在画布中选择一个循环节点。")); } }); @@ -634,15 +694,73 @@ QWidget *MainWindow::createArmPage() QSettings settings; saveJointPrograms(settings); }); - m_jointFlowDialog = new QDialog(this); + FramelessToolDialog *jointFlowDialog = new FramelessToolDialog(this); + m_jointFlowDialog = jointFlowDialog; + m_jointFlowDialog->setObjectName(QStringLiteral("jointFlowDialog")); m_jointFlowDialog->setWindowTitle(QStringLiteral("机械臂点位与流程编排")); m_jointFlowDialog->setModal(false); - m_jointFlowDialog->resize(1120, 780); - m_jointFlowDialog->setMinimumSize(860, 620); + m_jointFlowDialog->resize(1240, 820); + m_jointFlowDialog->setMinimumSize(980, 680); QVBoxLayout *jointFlowDialogLayout = new QVBoxLayout(m_jointFlowDialog); - jointFlowDialogLayout->setContentsMargins(12, 12, 12, 12); - jointFlowDialogLayout->addWidget(moveJPage); - const QStringList poseLabels = { + jointFlowDialogLayout->setContentsMargins(14, 14, 14, 14); + jointFlowDialogLayout->setSpacing(0); + QFrame *jointFlowSurface = new QFrame(m_jointFlowDialog); + jointFlowSurface->setObjectName(QStringLiteral("jointFlowDialogSurface")); + QVBoxLayout *jointFlowSurfaceLayout = new QVBoxLayout(jointFlowSurface); + jointFlowSurfaceLayout->setContentsMargins(0, 0, 0, 0); + jointFlowSurfaceLayout->setSpacing(0); + QWidget *jointFlowTitleBar = new QWidget(jointFlowSurface); + jointFlowTitleBar->setObjectName(QStringLiteral("jointFlowDialogTitleBar")); + jointFlowTitleBar->setFixedHeight(46); + QHBoxLayout *jointFlowTitleLayout = new QHBoxLayout(jointFlowTitleBar); + jointFlowTitleLayout->setContentsMargins(12, 0, 0, 0); + jointFlowTitleLayout->setSpacing(9); + QLabel *jointFlowMark = new QLabel(QStringLiteral("C"), jointFlowTitleBar); + jointFlowMark->setObjectName(QStringLiteral("jointFlowDialogMark")); + jointFlowMark->setAlignment(Qt::AlignCenter); + jointFlowMark->setFixedSize(25, 25); + QLabel *jointFlowTitle = new QLabel(QStringLiteral("机械臂点位与流程编排"), jointFlowTitleBar); + jointFlowTitle->setObjectName(QStringLiteral("jointFlowDialogTitle")); + QLabel *jointFlowSubtitle = new QLabel(QStringLiteral("POINT & FLOW"), jointFlowTitleBar); + jointFlowSubtitle->setObjectName(QStringLiteral("jointFlowDialogSubtitle")); + QPushButton *jointFlowMinimize = new QPushButton(jointFlowTitleBar); + jointFlowMinimize->setObjectName(QStringLiteral("jointFlowDialogWindowButton")); + jointFlowMinimize->setToolTip(QStringLiteral("最小化")); + jointFlowMinimize->setFixedSize(46, 45); + jointFlowMinimize->setIcon(UiIcons::icon(QStringLiteral(":/icons/minus.svg"), + QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#202832")))); + QPushButton *jointFlowClose = new QPushButton(jointFlowTitleBar); + jointFlowClose->setObjectName(QStringLiteral("jointFlowDialogCloseButton")); + jointFlowClose->setToolTip(QStringLiteral("关闭")); + jointFlowClose->setFixedSize(48, 45); + jointFlowClose->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"), + QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#ffffff")))); + jointFlowTitleLayout->addWidget(jointFlowMark); + jointFlowTitleLayout->addWidget(jointFlowTitle); + jointFlowTitleLayout->addWidget(jointFlowSubtitle); + jointFlowTitleLayout->addStretch(1); + jointFlowTitleLayout->addWidget(jointFlowMinimize); + jointFlowTitleLayout->addWidget(jointFlowClose); + jointFlowSurfaceLayout->addWidget(jointFlowTitleBar); + jointFlowSurfaceLayout->addWidget(moveJPage, 1); + jointFlowDialogLayout->addWidget(jointFlowSurface); + jointFlowDialog->setDragHandle(jointFlowTitleBar); + QGraphicsDropShadowEffect *jointFlowShadow = new QGraphicsDropShadowEffect(jointFlowSurface); + jointFlowShadow->setBlurRadius(28.0); + jointFlowShadow->setOffset(0.0, 5.0); + jointFlowShadow->setColor(QColor(24, 34, 44, 78)); + jointFlowSurface->setGraphicsEffect(jointFlowShadow); + connect(jointFlowMinimize, &QPushButton::clicked, + m_jointFlowDialog, &QDialog::showMinimized); + connect(jointFlowClose, &QPushButton::clicked, + m_jointFlowDialog, &QDialog::hide); + QFrame *poseMetrics = new QFrame(ui.telemetryPanel); + poseMetrics->setObjectName(QStringLiteral("poseMetrics")); + QGridLayout *poseMetricsLayout = new QGridLayout(poseMetrics); + poseMetricsLayout->setContentsMargins(0, 0, 0, 0); + poseMetricsLayout->setHorizontalSpacing(8); + poseMetricsLayout->setVerticalSpacing(8); + const QStringList poseAxes = { QStringLiteral("X"), QStringLiteral("Y"), QStringLiteral("Z"), QStringLiteral("RX"), QStringLiteral("RY"), QStringLiteral("RZ") }; @@ -650,13 +768,6 @@ QWidget *MainWindow::createArmPage() QStringLiteral("m"), QStringLiteral("m"), QStringLiteral("m"), QStringLiteral("rad"), QStringLiteral("rad"), QStringLiteral("rad") }; - QFrame *poseMetrics = new QFrame(ui.telemetryPanel); - poseMetrics->setObjectName(QStringLiteral("poseMetrics")); - QGridLayout *poseMetricsLayout = new QGridLayout(poseMetrics); - poseMetricsLayout->setContentsMargins(0, 0, 0, 0); - poseMetricsLayout->setHorizontalSpacing(8); - poseMetricsLayout->setVerticalSpacing(8); - const QStringList poseAxes = poseLabels; m_poseMetricValues.clear(); for (int index = 0; index < poseAxes.size(); ++index) { QFrame *metricCard = new QFrame(poseMetrics); @@ -686,9 +797,9 @@ QWidget *MainWindow::createArmPage() ui.telemetryLayout->setStretch(0, 1); ui.telemetryLayout->setStretch(1, 1); - // Combine the new hold-to-jog controls with the point/flow editor retained - // from the arm workflow branch. The URDF viewer remains alive for parsing, - // but stays hidden to avoid the release-only Qt3D crash and free the space. + // Replace the old target/teaching workspace with hold-to-jog controls and + // a read-only telemetry panel. + ui.targetsPanel->hide(); ui.teachPanel->hide(); ui.urdfTabLayout->removeWidget(ui.urdfViewer); ui.urdfTabLayout->removeWidget(ui.teachPanel); @@ -961,9 +1072,6 @@ QWidget *MainWindow::createArmPage() jogTabBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); } m_jogModeTabs->addTab(cartesianJogPage, QStringLiteral("笛卡尔速度")); - m_jogModeTabs->addTab(directMovePage, QStringLiteral("MoveJ 目标")); - ui.urdfTabLayout->removeWidget(ui.targetsPanel); - ui.targetsPanel->hide(); jogLayout->addWidget(m_jogModeTabs, 1); QHBoxLayout *speedLayout = new QHBoxLayout; @@ -992,10 +1100,9 @@ QWidget *MainWindow::createArmPage() jogFooter->addWidget(m_jogStopButton); jogLayout->addLayout(jogFooter); modelJogWorkspace->addWidget(jogPanel); - ui.urdfViewer->hide(); - modelJogWorkspace->setStretchFactor(0, 0); - modelJogWorkspace->setStretchFactor(1, 1); - modelJogWorkspace->setSizes({0, 1300}); + modelJogWorkspace->setStretchFactor(0, 3); + modelJogWorkspace->setStretchFactor(1, 2); + modelJogWorkspace->setSizes({780, 520}); workspaceLayout->addWidget(modelJogWorkspace, 3); ui.telemetryPanel->setParent(workspace); @@ -1070,12 +1177,9 @@ QWidget *MainWindow::createArmPage() connect(m_stopButton, &QPushButton::clicked, this, [this]() { m_client->requestArmStop(m_armIdEdit->text().trimmed()); }); - connect(ui.zeroButton, &QPushButton::clicked, this, [this]() { - const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left"); - const QList &spins = leftArm - ? m_leftTargetSpins : m_rightTargetSpins; - for (QDoubleSpinBox *spin : spins) - spin->setValue(0.0); + connect(m_jogStopButton, &QPushButton::clicked, this, &MainWindow::stopArmJog); + connect(m_jogSpeedSlider, &QSlider::valueChanged, this, [this](int value) { + m_jogSpeedValue->setText(QStringLiteral("%1%").arg(value)); }); connect(m_jogModeTabs, &QTabWidget::currentChanged, this, [this](int index) { stopArmJog(); @@ -1125,33 +1229,6 @@ QWidget *MainWindow::createArmPage() connect(m_urdfViewer, &UrdfViewerWidget::logMessage, this, &MainWindow::appendLog); - const auto configureMotionTable = [](QTableWidget *table) { - table->setColumnCount(5); - table->setHorizontalHeaderLabels({QStringLiteral("关节"), QStringLiteral("当前角度"), - QStringLiteral("当前弧度"), QStringLiteral("目标角度"), - QStringLiteral("目标弧度")}); - table->setAlternatingRowColors(true); - table->setSelectionBehavior(QAbstractItemView::SelectRows); - table->setSelectionMode(QAbstractItemView::SingleSelection); - table->setShowGrid(false); - table->verticalHeader()->setVisible(false); - table->verticalHeader()->setDefaultSectionSize(29); - table->horizontalHeader()->setFixedHeight(32); - table->horizontalHeader()->setHighlightSections(false); - for (int column = 0; column < 5; ++column) - table->horizontalHeader()->setSectionResizeMode(column, QHeaderView::Fixed); - table->setColumnWidth(0, 112); - table->setColumnWidth(1, 76); - table->setColumnWidth(2, 92); - table->setColumnWidth(3, 118); - table->setColumnWidth(4, 96); - table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - table->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - table->setMinimumHeight(32 + 7 * 29 + 2); - }; - configureMotionTable(m_leftMotionTable); - configureMotionTable(m_motionTable); - m_jointTable->setHorizontalHeaderLabels({QStringLiteral("关节"), QStringLiteral("位置 rad"), QStringLiteral("速度 rad/s"), QStringLiteral("加速度 rad/s²")}); m_jointTable->setAlternatingRowColors(true); @@ -1161,81 +1238,9 @@ QWidget *MainWindow::createArmPage() m_jointTable->verticalHeader()->setDefaultSectionSize(28); m_jointTable->horizontalHeader()->setStretchLastSection(true); - m_targetSpins.clear(); - m_leftArmJointNames = armJointNames(true); - m_rightArmJointNames = armJointNames(false); - const auto populateMotionTable = [this](QTableWidget *table, bool leftArm, - const QStringList &jointNames) { - QList &sideSpins = leftArm - ? m_leftTargetSpins : m_rightTargetSpins; - sideSpins.clear(); - table->clearContents(); - table->setRowCount(jointNames.size()); - table->setMinimumHeight(32 + qMin(jointNames.size(), 10) * 29 + 2); - for (int row = 0; row < jointNames.size(); ++row) { - const QString jointName = jointNames.at(row); - table->setItem(row, 0, new QTableWidgetItem(jointName)); - table->setItem(row, 1, new QTableWidgetItem(QStringLiteral("--"))); - table->setItem(row, 2, new QTableWidgetItem(QStringLiteral("--"))); - QDoubleSpinBox *target = new QDoubleSpinBox(table); - target->setRange(-180.0, 180.0); - target->setDecimals(3); - target->setSingleStep(1.0); - target->setSuffix(QStringLiteral(" °")); - target->setFrame(false); - target->setEnabled(m_connected); - m_targetSpins.append(target); - sideSpins.append(target); - table->setCellWidget(row, 3, target); - QTableWidgetItem *radians = new QTableWidgetItem(QStringLiteral("0.000000")); - radians->setFlags(radians->flags() & ~Qt::ItemIsEditable); - table->setItem(row, 4, radians); - connect(target, QOverload::of(&QDoubleSpinBox::valueChanged), this, - [this, table, row, jointName](double degrees) { - if (row < table->rowCount() && table->item(row, 4)) - table->item(row, 4)->setText( - QString::number(qDegreesToRadians(degrees), 'f', 6)); - if (m_teachModeButton->isChecked()) - m_urdfViewer->setTeachingJointPosition( - jointName, qDegreesToRadians(degrees)); - }); - - } - }; - populateMotionTable(m_leftMotionTable, true, m_leftArmJointNames); - populateMotionTable(m_motionTable, false, m_rightArmJointNames); - - const QStringList allJointNames = armJointNames(true) + armJointNames(false); - m_jointTable->clearContents(); - m_jointTable->setRowCount(allJointNames.size()); - for (int row = 0; row < allJointNames.size(); ++row) { - m_jointTable->setItem(row, 0, new QTableWidgetItem(allJointNames.at(row))); - for (int column = 1; column < 4; ++column) - m_jointTable->setItem(row, column, new QTableWidgetItem(QStringLiteral("--"))); - } - - const auto refreshActiveArmControls = [this]() { - const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left"); - m_activeArmJointNames = leftArm ? m_leftArmJointNames : m_rightArmJointNames; - QStringList zeroJointNames; - const QStringList urdfNames = m_urdfViewer->jointNames(); - for (const QString &name : urdfNames) { - if (isArmJointForSide(name, leftArm)) - zeroJointNames.append(name); - } - if (zeroJointNames.isEmpty()) - zeroJointNames = m_activeArmJointNames; - const QString selectedJoint = m_zeroJointCombo->currentText(); - const QSignalBlocker blocker(m_zeroJointCombo); - m_zeroJointCombo->clear(); - m_zeroJointCombo->addItems(zeroJointNames); - const int selectedIndex = m_zeroJointCombo->findText(selectedJoint); - if (selectedIndex >= 0) - m_zeroJointCombo->setCurrentIndex(selectedIndex); - m_zeroJointCombo->setEnabled(!zeroJointNames.isEmpty()); - m_calibrateZeroButton->setEnabled(m_connected && !zeroJointNames.isEmpty()); - }; - refreshActiveArmControls(); + m_activeArmJointNames.clear(); + m_jointTable->setRowCount(0); + m_zeroJointCombo->clear(); connect(m_armSideCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this, poseSubtitle = ui.poseSubtitle](int) { @@ -1246,9 +1251,13 @@ QWidget *MainWindow::createArmPage() const bool telemetryRunning = m_armTelemetryButton->isChecked(); if (telemetryRunning) m_client->setArmTelemetry(oldDeviceId, false); - const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left"); - m_armIdEdit->setText(leftArm ? QStringLiteral("left_ethercat_arm") - : QStringLiteral("right_ethercat_arm")); + m_armIdEdit->setText(newDeviceId); + m_activeArmJointNames.clear(); + m_jointTable->setRowCount(0); + rebuildArmJogControls(); + m_zeroJointCombo->clear(); + m_armDefaultBaseFrame.clear(); + m_armDefaultTcpFrame.clear(); m_latestArmPose.clear(); for (QLabel *valueLabel : m_poseMetricValues) valueLabel->setText(QStringLiteral("--")); @@ -1260,110 +1269,6 @@ QWidget *MainWindow::createArmPage() if (telemetryRunning) m_client->setArmTelemetry(newDeviceId, true); }); - connect(m_urdfViewer, &UrdfViewerWidget::modelLoaded, this, - [this, refreshActiveArmControls, populateMotionTable](const QString &, int, int) { - const QStringList urdfNames = m_urdfViewer->jointNames(); - QStringList leftNames; - QStringList rightNames; - for (const QString &name : urdfNames) { - if (isArmJointForSide(name, true)) - leftNames.append(name); - else if (isArmJointForSide(name, false)) - rightNames.append(name); - } - // A single-arm URDF often uses neutral names such as joint1..joint6. - // In that case bind all movable joints to the currently selected arm. - if (leftNames.isEmpty() && rightNames.isEmpty() && !urdfNames.isEmpty()) { - if (m_armSideCombo->currentData().toString() == QStringLiteral("left")) - leftNames = urdfNames; - else - rightNames = urdfNames; - } - m_leftArmJointNames = leftNames; - m_rightArmJointNames = rightNames; - m_targetSpins.clear(); - populateMotionTable(m_leftMotionTable, true, m_leftArmJointNames); - populateMotionTable(m_motionTable, false, m_rightArmJointNames); - - m_jointTable->clearContents(); - m_jointTable->setRowCount(urdfNames.size()); - for (int row = 0; row < urdfNames.size(); ++row) { - m_jointTable->setItem(row, 0, new QTableWidgetItem(urdfNames.at(row))); - for (int column = 1; column < 4; ++column) - m_jointTable->setItem(row, column, - new QTableWidgetItem(QStringLiteral("--"))); - } - refreshActiveArmControls(); - m_teachModeButton->setEnabled(!urdfNames.isEmpty()); - }); - connect(m_teachModeButton, &QPushButton::toggled, this, [this](bool enabled) { - m_urdfViewer->setTeachingEnabled(enabled); - if (enabled && !m_activeArmJointNames.isEmpty()) - m_urdfViewer->selectTeachingJoint(m_activeArmJointNames.first()); - }); - connect(m_urdfViewer, &UrdfViewerWidget::teachingModeChanged, this, - [this](bool enabled) { - const QSignalBlocker blocker(m_teachModeButton); - m_teachModeButton->setChecked(enabled); - m_teachModeButton->setText(enabled ? QStringLiteral("退出示教") - : QStringLiteral("示教模式")); - m_teachRestoreButton->setEnabled(enabled); - if (!enabled) { - m_teachSelectedJoint.clear(); - m_leftMotionTable->clearSelection(); - m_motionTable->clearSelection(); - } - }); - connect(m_urdfViewer, &UrdfViewerWidget::teachingJointSelected, this, - [this](const QString &jointName, double, double, double) { - const int row = m_activeArmJointNames.indexOf(jointName); - if (row < 0) { - if (!m_activeArmJointNames.isEmpty()) - m_urdfViewer->selectTeachingJoint(m_activeArmJointNames.first()); - return; - } - m_teachSelectedJoint = jointName; - const int zeroIndex = m_zeroJointCombo->findText(jointName); - if (zeroIndex >= 0) - m_zeroJointCombo->setCurrentIndex(zeroIndex); - const bool leftArm = m_armSideCombo->currentData().toString() == QStringLiteral("left"); - (leftArm ? m_leftMotionTable : m_motionTable)->selectRow(row); - }); - connect(m_urdfViewer, &UrdfViewerWidget::teachingPositionsChanged, this, - [this](const QHash &positions) { - for (int side = 0; side < 2; ++side) { - const bool leftArm = side == 0; - QTableWidget *table = leftArm ? m_leftMotionTable : m_motionTable; - const QStringList &names = leftArm ? m_leftArmJointNames : m_rightArmJointNames; - const QList &spins = leftArm - ? m_leftTargetSpins : m_rightTargetSpins; - for (int row = 0; row < names.size() && row < spins.size(); ++row) { - if (!positions.contains(names.at(row))) - continue; - const double radians = positions.value(names.at(row)); - const QSignalBlocker blocker(spins.at(row)); - spins.at(row)->setValue(qRadiansToDegrees(radians)); - table->item(row, 4)->setText(QString::number(radians, 'f', 6)); - } - } - }); - connect(m_teachRestoreButton, &QPushButton::clicked, - m_urdfViewer, &UrdfViewerWidget::restoreTeachingFromTelemetry); - - const auto connectMotionTable = [this](QTableWidget *table, bool leftArm) { - connect(table, &QTableWidget::cellClicked, this, - [this, leftArm](int row, int) { - const int sideIndex = m_armSideCombo->findData( - leftArm ? QStringLiteral("left") : QStringLiteral("right")); - if (sideIndex >= 0 && sideIndex != m_armSideCombo->currentIndex()) - m_armSideCombo->setCurrentIndex(sideIndex); - const QStringList &names = leftArm ? m_leftArmJointNames : m_rightArmJointNames; - if (m_teachModeButton->isChecked() && row >= 0 && row < names.size()) - m_urdfViewer->selectTeachingJoint(names.at(row)); - }); - }; - connectMotionTable(m_leftMotionTable, true); - connectMotionTable(m_motionTable, false); m_serviceButtons << m_armTelemetryButton << m_armGlobalStopButton << m_torqueOnButton << m_torqueOffButton diff --git a/styles.qss b/styles.qss index 7c1e35d..0c8fdc2 100644 --- a/styles.qss +++ b/styles.qss @@ -1612,6 +1612,148 @@ QToolTip { border: none; padding: 5px; } + +/* Arm point and flow planner */ +QDialog#jointFlowDialog { + background: transparent; + border: none; +} +QDialog#jointFlowChildDialog { + background: transparent; + border: none; +} +QFrame#jointFlowChildSurface { + background: #f5f7fa; + border: 1px solid #cbd2da; + border-radius: 9px; +} +QWidget#jointFlowChildTitleBar { + background: #f8fafc; + border: none; + border-bottom: 1px solid #dce1e6; + border-top-left-radius: 8px; + border-top-right-radius: 8px; +} +QWidget#jointFlowChildContent { + background: #ffffff; + border: none; + border-bottom-left-radius: 8px; + border-bottom-right-radius: 8px; +} +QWidget#jointFlowChildContent QLabel { + color: #4f5d69; + font-weight: 600; +} +QWidget#jointFlowChildContent QLineEdit { + min-height: 34px; + padding: 0 10px; + background: #ffffff; + border: 1px solid #bfc9d4; + border-radius: 5px; + selection-background-color: #1b6ef3; +} +QWidget#jointFlowChildContent QLineEdit:focus { + border: 1px solid #1b6ef3; +} +QFrame#jointFlowDialogSurface { + background: #f3f6f9; + border: 1px solid #cbd2da; + border-radius: 9px; +} +QWidget#jointFlowDialogTitleBar { + background: #f8fafc; + border: none; + border-bottom: 1px solid #dce1e6; + border-top-left-radius: 8px; + border-top-right-radius: 8px; +} +QLabel#jointFlowDialogMark { + color: #ffffff; + background: #1b6ef3; + border-radius: 5px; + font-size: 12px; + font-weight: 700; +} +QLabel#jointFlowDialogTitle { + color: #202832; + font-size: 13px; + font-weight: 700; +} +QLabel#jointFlowDialogSubtitle { + color: #78838f; + font-size: 11px; +} +QPushButton#jointFlowDialogWindowButton, +QPushButton#jointFlowDialogCloseButton { + min-height: 45px; + padding: 0; + background: transparent; + border: none; + border-radius: 0; +} +QPushButton#jointFlowDialogWindowButton:hover { + background: #e9edf2; +} +QPushButton#jointFlowDialogCloseButton { + border-top-right-radius: 8px; +} +QPushButton#jointFlowDialogCloseButton:hover { + background: #d83b3b; +} +QWidget#jointFlowWorkspace { + background: #f3f6f9; +} +QFrame#jointPointPanel, +QFrame#jointFlowPanel { + background: #ffffff; + border: 1px solid #dce3ea; + border-radius: 8px; +} +QLabel#jointFlowSectionTitle { + color: #202a34; + font-size: 14px; + font-weight: 700; +} +QLabel#jointFlowSectionSubtitle { + color: #77838f; + font-size: 11px; +} +QLabel#jointFlowContextChip { + color: #155dcc; + background: #eaf3ff; + border: 1px solid #c9def8; + border-radius: 12px; + padding: 4px 10px; + font-weight: 600; +} +QFrame#jointFlowToolbar { + background: #f7f9fb; + border: 1px solid #e1e7ed; + border-radius: 6px; +} +QPushButton#secondaryButton { + color: #2866a8; + background: #ffffff; + border-color: #b9cde2; +} +QPushButton#secondaryButton:hover { + color: #155dcc; + background: #edf5ff; + border-color: #6fa7e5; +} +QTableWidget#jointPointTable { + border: 1px solid #e0e6ec; + border-radius: 6px; +} +QGraphicsView#jointFlowCanvas { + background: #f4f7fa; + border: 1px solid #dce3ea; + border-radius: 6px; +} +QSplitter#jointFlowSplitter::handle { + height: 10px; + background: transparent; +} QFrame#bottomStatusBar { background: #ffffff; border: none; From 798ac83a8e79891b7d0cfe14c6ccf72c7300a5b5 Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Sat, 10 Oct 2026 13:34:25 +0800 Subject: [PATCH 12/15] style: refine flow dialog text selection --- src/mainwindow_ui.cpp | 2 +- styles.qss | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 7b18d82..db06fc8 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -216,7 +216,7 @@ QString requestFlowNodeName(QWidget *parent, const QString &title, QObject::connect(nameEdit, &QLineEdit::returnPressed, &dialog, &QDialog::accept); QTimer::singleShot(0, nameEdit, [nameEdit]() { nameEdit->setFocus(); - nameEdit->selectAll(); + nameEdit->setCursorPosition(nameEdit->text().size()); }); const bool ok = dialog.exec() == QDialog::Accepted; if (accepted) diff --git a/styles.qss b/styles.qss index 0c8fdc2..fff8f53 100644 --- a/styles.qss +++ b/styles.qss @@ -1650,7 +1650,8 @@ QWidget#jointFlowChildContent QLineEdit { background: #ffffff; border: 1px solid #bfc9d4; border-radius: 5px; - selection-background-color: #1b6ef3; + selection-background-color: #dbeafe; + selection-color: #155dcc; } QWidget#jointFlowChildContent QLineEdit:focus { border: 1px solid #1b6ef3; From 165343b0a3610eca3fa3f43c614568488e39f120 Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Sat, 10 Oct 2026 15:47:22 +0800 Subject: [PATCH 13/15] feat: enhance arm position and point workflow controls --- resources/joint_programs.json | 181 ++++++++++++++++ src/jointfloweditor.cpp | 2 +- src/mainwindow.cpp | 391 +++++++++++++++++++++++++++------- src/mainwindow.h | 27 ++- src/mainwindow_ui.cpp | 241 +++++++++++++++++++-- src/robotclient.cpp | 96 +++++++++ src/robotclient.h | 2 + styles.qss | 5 +- 8 files changed, 844 insertions(+), 101 deletions(-) create mode 100644 resources/joint_programs.json diff --git a/resources/joint_programs.json b/resources/joint_programs.json new file mode 100644 index 0000000..94c2866 --- /dev/null +++ b/resources/joint_programs.json @@ -0,0 +1,181 @@ +{ + "activeGroup": "挥手", + "groups": [ + { + "flow": [ + ], + "moveJAcceleration": 0.1, + "moveJVelocity": 0.1, + "name": "默认组", + "points": [ + ] + }, + { + "flow": [ + { + "collapsed": false, + "id": "860308d9-f0fb-46f6-a0d3-30013b46827a", + "intervalSeconds": 0.5, + "loopCount": 1, + "nodeName": "初始位置", + "order": 0, + "parentId": "", + "pointName": "初始位置", + "type": "single", + "x": 40, + "y": 40 + }, + { + "collapsed": false, + "id": "0ddff873-9e76-4635-917d-1d7357dddcc1", + "intervalSeconds": 0.5, + "loopCount": 3, + "nodeName": "循环左右", + "order": 1, + "parentId": "", + "pointName": "", + "type": "loop", + "x": 260, + "y": 40 + }, + { + "collapsed": false, + "id": "c1a33717-b636-4eb4-80f4-91305edc64ff", + "intervalSeconds": 0.5, + "loopCount": 1, + "nodeName": "挥手-右", + "order": 0, + "parentId": "0ddff873-9e76-4635-917d-1d7357dddcc1", + "pointName": "挥手-右", + "type": "single", + "x": 40, + "y": 140 + }, + { + "collapsed": false, + "id": "9851e4a8-91bd-4182-a5f5-cdd19180d0a3", + "intervalSeconds": 0.5, + "loopCount": 1, + "nodeName": "挥手-左", + "order": 1, + "parentId": "0ddff873-9e76-4635-917d-1d7357dddcc1", + "pointName": "挥手-左", + "type": "single", + "x": 260, + "y": 140 + }, + { + "collapsed": false, + "id": "3b89feb6-c457-4a93-b81f-28e5b1423046", + "intervalSeconds": 0.5, + "loopCount": 1, + "nodeName": "初始位置", + "order": 2, + "parentId": "", + "pointName": "初始位置", + "type": "single", + "x": 480, + "y": 40 + } + ], + "moveJAcceleration": 1, + "moveJVelocity": 1, + "name": "挥手", + "points": [ + { + "deviceId": "right_ethercat_arm", + "jointNames": [ + "right_arm_J1", + "right_arm_J2", + "right_arm_J3", + "right_arm_J4", + "right_arm_J5", + "right_arm_J6", + "right_arm_J7" + ], + "name": "零位", + "positions": [ + -9.492455370579462e-07, + 0, + -9.492455370579462e-07, + 0, + 0, + -9.492455370579462e-07, + -9.492455370579462e-07 + ], + "side": "right" + }, + { + "deviceId": "right_ethercat_arm", + "jointNames": [ + "right_arm_J1", + "right_arm_J2", + "right_arm_J3", + "right_arm_J4", + "right_arm_J5", + "right_arm_J6", + "right_arm_J7" + ], + "name": "初始位置", + "positions": [ + 0.014501624069634246, + -1.4912457538072925, + -1.2003475604848106, + -0.02585080371069905, + -0.07927434253632026, + -0.06444807649301221, + -0.11000426830749717 + ], + "side": "right" + }, + { + "deviceId": "right_ethercat_arm", + "jointNames": [ + "right_arm_J1", + "right_arm_J2", + "right_arm_J3", + "right_arm_J4", + "right_arm_J5", + "right_arm_J6", + "right_arm_J7" + ], + "name": "挥手-右", + "positions": [ + 0.742245461282794, + -1.490991356003361, + -1.3799808874265822, + 1.543379267948052, + 0.14546428458983382, + -0.06442149761797458, + -0.4555106588858484 + ], + "side": "right" + }, + { + "deviceId": "right_ethercat_arm", + "jointNames": [ + "right_arm_J1", + "right_arm_J2", + "right_arm_J3", + "right_arm_J4", + "right_arm_J5", + "right_arm_J6", + "right_arm_J7" + ], + "name": "挥手-左", + "positions": [ + 0.9055916332997255, + -1.4894905988092724, + -1.8256241389547136, + 1.5302806287821893, + 0.019423462179279694, + -0.06441770063582634, + -0.4553255560061222 + ], + "side": "right" + } + ] + } + ], + "version": 1 +} diff --git a/src/jointfloweditor.cpp b/src/jointfloweditor.cpp index 8741bf9..00a15f2 100644 --- a/src/jointfloweditor.cpp +++ b/src/jointfloweditor.cpp @@ -65,7 +65,7 @@ public: closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton")); closeButton->setFixedSize(46, 43); closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"), - QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#ffffff")))); + QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#4f5964")))); titleLayout->addWidget(mark); titleLayout->addWidget(titleLabel); titleLayout->addStretch(1); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index ab2270e..4dd1d01 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -33,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -45,8 +47,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include @@ -1197,6 +1202,54 @@ void MainWindow::rebuildArmJointTables(const QStringList &jointNames) m_jointTable->setItem(row, column, new QTableWidgetItem(QStringLiteral("--"))); } + if (m_motionTable) { + m_motionTable->clearContents(); + m_motionTable->setColumnCount(5); + m_motionTable->setRowCount(jointNames.size()); + m_targetSpins.clear(); + m_targetRadianSpins.clear(); + for (int row = 0; row < jointNames.size(); ++row) { + m_motionTable->setItem(row, 0, new QTableWidgetItem(jointNames.at(row))); + QLineEdit *currentDegrees = new QLineEdit(QStringLiteral("--"), m_motionTable); + QLineEdit *currentRadians = new QLineEdit(QStringLiteral("--"), m_motionTable); + for (QLineEdit *current : {currentDegrees, currentRadians}) { + current->setReadOnly(true); + current->setFrame(false); + current->setAlignment(Qt::AlignCenter); + current->setToolTip(QStringLiteral("只读;可选中文本后复制")); + } + m_motionTable->setCellWidget(row, 1, currentDegrees); + m_motionTable->setCellWidget(row, 2, currentRadians); + + QDoubleSpinBox *targetDegrees = new QDoubleSpinBox(m_motionTable); + targetDegrees->setRange(-360.0, 360.0); + targetDegrees->setDecimals(3); + targetDegrees->setSingleStep(1.0); + targetDegrees->setSuffix(QStringLiteral(" °")); + targetDegrees->setKeyboardTracking(false); + QDoubleSpinBox *targetRadians = new QDoubleSpinBox(m_motionTable); + targetRadians->setRange(-2.0 * M_PI, 2.0 * M_PI); + targetRadians->setDecimals(6); + targetRadians->setSingleStep(0.01); + targetRadians->setSuffix(QStringLiteral(" rad")); + targetRadians->setKeyboardTracking(false); + m_motionTable->setCellWidget(row, 3, targetDegrees); + m_motionTable->setCellWidget(row, 4, targetRadians); + connect(targetDegrees, QOverload::of(&QDoubleSpinBox::valueChanged), + this, [targetRadians](double degrees) { + const QSignalBlocker blocker(targetRadians); + targetRadians->setValue(qDegreesToRadians(degrees)); + }); + connect(targetRadians, QOverload::of(&QDoubleSpinBox::valueChanged), + this, [targetDegrees](double radians) { + const QSignalBlocker blocker(targetDegrees); + targetDegrees->setValue(qRadiansToDegrees(radians)); + }); + m_targetSpins.append(targetDegrees); + m_targetRadianSpins.append(targetRadians); + } + } + if (m_zeroJointCombo) { const QSignalBlocker blocker(m_zeroJointCombo); m_zeroJointCombo->clear(); @@ -1204,6 +1257,10 @@ void MainWindow::rebuildArmJointTables(const QStringList &jointNames) } if (m_calibrateZeroButton) m_calibrateZeroButton->setEnabled(m_connected && !jointNames.isEmpty()); + if (m_sendMoveButton) + m_sendMoveButton->setEnabled(m_connected && !jointNames.isEmpty()); + if (m_syncCurrentToTargetButton) + m_syncCurrentToTargetButton->setEnabled(m_connected && !jointNames.isEmpty()); m_previousJointVelocities.clear(); m_lastArmTelemetryMs = 0; rebuildArmJogControls(); @@ -1413,6 +1470,20 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo 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)); + if (m_motionTable) { + for (int targetRow = 0; targetRow < m_motionTable->rowCount(); ++targetRow) { + QTableWidgetItem *targetName = m_motionTable->item(targetRow, 0); + if (!targetName || targetName->text() != nameItem->text()) + continue; + if (QLineEdit *degrees = qobject_cast( + m_motionTable->cellWidget(targetRow, 1))) + degrees->setText(QString::number(qRadiansToDegrees(position), 'f', 3)); + if (QLineEdit *radians = qobject_cast( + m_motionTable->cellWidget(targetRow, 2))) + radians->setText(QString::number(position, 'f', 6)); + break; + } + } m_previousJointVelocities.insert(nameItem->text(), velocity); if (row < m_jointJogPositionLabels.size()) m_jointJogPositionLabels.at(row)->setText( @@ -1977,6 +2048,7 @@ void MainWindow::updateAgvInventory(const QStringList &maps, const QVariantList void MainWindow::updateImage(const QImage &image, const QString &detail) { m_lastImage = image; + m_lastImageIsDepth = detail.startsWith(QStringLiteral("深度")); if (m_videoRender) m_videoRender->setImage(image); m_imageMetaLabel->setText(detail); @@ -2166,11 +2238,19 @@ void MainWindow::appendLog(const QString &level, const QString &message) void MainWindow::sendMoveJ() { + if (m_armIdEdit->text().trimmed().isEmpty() || m_targetSpins.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("MoveJ 关节位置控制"), + QStringLiteral("请先选择机械臂并等待关节信息加载完成。")); + return; + } QVariantList positions; - for (QDoubleSpinBox *spin : m_targetSpins) - positions.append(qDegreesToRadians(spin->value())); + for (QDoubleSpinBox *spin : m_targetRadianSpins) + positions.append(spin->value()); m_client->requestMoveJ(m_armIdEdit->text().trimmed(), positions, - m_velocitySpin->value(), m_accelerationSpin->value()); + m_moveJVelocitySpin ? m_moveJVelocitySpin->value() + : m_velocitySpin->value(), + m_moveJAccelerationSpin ? m_moveJAccelerationSpin->value() + : m_accelerationSpin->value()); } void MainWindow::refreshRecordedJointPoints() @@ -2262,8 +2342,7 @@ void MainWindow::recordCurrentJointPoint() m_recordedJointPoints.append(point); refreshRecordedJointPoints(); - QSettings settings; - saveJointPrograms(settings); + saveJointPrograms(); m_jointPointNameEdit->clear(); m_jointPointTable->selectRow(m_recordedJointPoints.size() - 1); appendLog(QStringLiteral("OK"), @@ -2291,7 +2370,8 @@ void MainWindow::executeSelectedJointPoint() positions.append(position); m_jointPointMovePending = true; m_client->requestMoveJ(point.deviceId, positions, - m_velocitySpin->value(), m_accelerationSpin->value()); + m_jointFlowVelocitySpin->value(), + m_jointFlowAccelerationSpin->value()); if (m_jointPointLoopStatus) m_jointPointLoopStatus->setText(QStringLiteral("执行:%1").arg(point.name)); } @@ -2350,6 +2430,8 @@ void MainWindow::startJointPointLoop() m_recordJointPointButton->setEnabled(false); m_stopJointPointLoopButton->setEnabled(true); m_jointPointTable->setEnabled(false); + m_jointFlowVelocitySpin->setEnabled(false); + m_jointFlowAccelerationSpin->setEnabled(false); advanceJointPointLoop(); } @@ -2377,7 +2459,8 @@ void MainWindow::advanceJointPointLoop() m_jointPointLoopStatus->setText(QStringLiteral("步骤 %1/%2 · %3") .arg(executionIndex + 1).arg(m_jointPointLoopRows.size()).arg(point.name)); m_client->requestMoveJ(point.deviceId, positions, - m_velocitySpin->value(), m_accelerationSpin->value()); + m_jointFlowVelocitySpin->value(), + m_jointFlowAccelerationSpin->value()); } void MainWindow::stopJointPointLoop(const QString &reason) @@ -2402,6 +2485,10 @@ void MainWindow::stopJointPointLoop(const QString &reason) m_stopJointPointLoopButton->setEnabled(false); if (m_jointPointTable) m_jointPointTable->setEnabled(true); + if (m_jointFlowVelocitySpin) + m_jointFlowVelocitySpin->setEnabled(m_connected); + if (m_jointFlowAccelerationSpin) + m_jointFlowAccelerationSpin->setEnabled(m_connected); if (m_jointPointLoopStatus) m_jointPointLoopStatus->setText(reason.isEmpty() ? QStringLiteral("未运行") : reason); if (wasActive && !reason.isEmpty()) @@ -2433,9 +2520,13 @@ void MainWindow::saveSnapshot() ? 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 图像"), + const QString defaultName = QStringLiteral("cmvr_%1_%2.png") + .arg(m_lastImageIsDepth ? QStringLiteral("depth") + : QStringLiteral("rgb"), + QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss")); + const QString path = QFileDialog::getSaveFileName( + this, m_lastImageIsDepth ? QStringLiteral("保存深度图像") + : QStringLiteral("保存 RGB 图像"), defaultName, QStringLiteral("PNG 图像 (*.png);;JPEG 图像 (*.jpg)")); if (path.isEmpty()) return; @@ -2534,7 +2625,7 @@ void MainWindow::loadSettings() void MainWindow::saveSettings() { QSettings settings; - saveJointPrograms(settings); + saveJointPrograms(); settings.setValue(QStringLiteral("connection/host"), m_hostEdit->text().trimmed()); settings.setValue(QStringLiteral("connection/port"), m_portSpin->value()); settings.setValue(QStringLiteral("connection/demo"), m_demoCheck->isChecked()); @@ -2582,89 +2673,217 @@ void MainWindow::saveSettings() : certificatePath); } -void MainWindow::loadJointPrograms(QSettings &settings) +QString MainWindow::jointProgramsFilePath() const { - m_recordedJointPoints.clear(); - const int pointCount = settings.beginReadArray(QStringLiteral("arm/jointPoints")); - for (int i = 0; i < pointCount; ++i) { - settings.setArrayIndex(i); - RecordedJointPoint point; - point.name = settings.value(QStringLiteral("name")).toString(); - point.side = settings.value(QStringLiteral("side")).toString(); - point.deviceId = settings.value(QStringLiteral("deviceId")).toString(); - point.jointNames = settings.value(QStringLiteral("jointNames")).toStringList(); - const QVariantList storedPositions = settings.value(QStringLiteral("positions")).toList(); - for (const QVariant &value : storedPositions) - point.positions.append(value.toDouble()); - if (!point.name.isEmpty() && point.jointNames.size() == point.positions.size()) - m_recordedJointPoints.append(point); - } - settings.endArray(); + return QDir(QCoreApplication::applicationDirPath()) + .filePath(QStringLiteral("joint_programs.json")); +} +void MainWindow::storeCurrentJointProgramGroup() +{ + if (m_activeJointProgramGroup < 0 + || m_activeJointProgramGroup >= m_jointProgramGroups.size()) + return; + JointProgramGroup &group = m_jointProgramGroups[m_activeJointProgramGroup]; + group.points = m_recordedJointPoints; + group.flow = m_jointFlowEditor ? m_jointFlowEditor->toJson() : QJsonArray(); + if (m_jointFlowVelocitySpin) + group.moveJVelocity = m_jointFlowVelocitySpin->value(); + if (m_jointFlowAccelerationSpin) + group.moveJAcceleration = m_jointFlowAccelerationSpin->value(); +} + +void MainWindow::activateJointProgramGroup(int index) +{ + if (m_updatingJointProgramGroup || index < 0 + || index >= m_jointProgramGroups.size() + || index == m_activeJointProgramGroup) + return; + if (m_jointPointLoopActive) + stopJointPointLoop(QStringLiteral("切换点位组")); + storeCurrentJointProgramGroup(); + m_activeJointProgramGroup = index; + const JointProgramGroup &group = m_jointProgramGroups.at(index); + m_recordedJointPoints = group.points; if (m_jointFlowEditor) { + const QSignalBlocker blocker(m_jointFlowEditor); m_jointFlowEditor->clear(); - const QByteArray flowJson = settings.value(QStringLiteral("arm/jointFlowGraph")).toByteArray(); - const QJsonDocument document = QJsonDocument::fromJson(flowJson); - if (document.isArray()) { - m_jointFlowEditor->fromJson(document.array()); - } else { - struct LegacyStep { QString point; double wait = 1.0; QString group; int count = 1; }; - QList legacy; - const int flowCount = settings.beginReadArray(QStringLiteral("arm/jointFlow")); - for (int i = 0; i < flowCount; ++i) { - settings.setArrayIndex(i); - LegacyStep step; - step.point = settings.value(QStringLiteral("pointName")).toString(); - step.wait = settings.value(QStringLiteral("waitSeconds"), 1.0).toDouble(); - step.group = settings.value(QStringLiteral("loopGroup")).toString(); - step.count = qMax(1, settings.value(QStringLiteral("loopCount"), 1).toInt()); - if (!step.point.isEmpty()) legacy.append(step); - } - settings.endArray(); - for (int i = 0; i < legacy.size();) { - if (legacy.at(i).group.isEmpty()) { - m_jointFlowEditor->addSingleNode(legacy.at(i).point, - legacy.at(i).point, - legacy.at(i).wait); - ++i; - continue; - } - int end = i + 1; - while (end < legacy.size() && legacy.at(end).group == legacy.at(i).group) ++end; - for (int repeat = 0; repeat < legacy.at(i).count; ++repeat) - for (int index = i; index < end; ++index) - m_jointFlowEditor->addSingleNode(legacy.at(index).point, - legacy.at(index).point, - legacy.at(index).wait); - i = end; - } - } + m_jointFlowEditor->fromJson(group.flow); + } + if (m_jointFlowVelocitySpin) { + const QSignalBlocker blocker(m_jointFlowVelocitySpin); + m_jointFlowVelocitySpin->setValue(group.moveJVelocity); + } + if (m_jointFlowAccelerationSpin) { + const QSignalBlocker blocker(m_jointFlowAccelerationSpin); + m_jointFlowAccelerationSpin->setValue(group.moveJAcceleration); } refreshRecordedJointPoints(); refreshJointFlowTable(); + saveJointPrograms(); } -void MainWindow::saveJointPrograms(QSettings &settings) const +void MainWindow::loadJointPrograms(QSettings &legacySettings) { - settings.remove(QStringLiteral("arm/jointPoints")); - settings.beginWriteArray(QStringLiteral("arm/jointPoints")); - for (int i = 0; i < m_recordedJointPoints.size(); ++i) { - settings.setArrayIndex(i); - const RecordedJointPoint &point = m_recordedJointPoints.at(i); - QVariantList positions; - for (double value : point.positions) - positions.append(value); - settings.setValue(QStringLiteral("name"), point.name); - settings.setValue(QStringLiteral("side"), point.side); - settings.setValue(QStringLiteral("deviceId"), point.deviceId); - settings.setValue(QStringLiteral("jointNames"), point.jointNames); - settings.setValue(QStringLiteral("positions"), positions); + m_jointProgramGroups.clear(); + m_activeJointProgramGroup = -1; + const QString filePath = jointProgramsFilePath(); + const QString legacyJsonPath = QDir( + QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)) + .filePath(QStringLiteral("joint_programs.json")); + const QString sourcePath = QFileInfo::exists(filePath) + ? filePath : legacyJsonPath; + QFile file(sourcePath); + QString activeGroupName; + if (file.open(QIODevice::ReadOnly)) { + QJsonParseError parseError; + const QJsonDocument document = QJsonDocument::fromJson(file.readAll(), &parseError); + const QJsonObject root = document.object(); + activeGroupName = root.value(QStringLiteral("activeGroup")).toString(); + const QJsonArray groups = root.value(QStringLiteral("groups")).toArray(); + for (const QJsonValue &groupValue : groups) { + const QJsonObject groupObject = groupValue.toObject(); + JointProgramGroup group; + group.name = groupObject.value(QStringLiteral("name")).toString().trimmed(); + group.flow = groupObject.value(QStringLiteral("flow")).toArray(); + group.moveJVelocity = groupObject.value( + QStringLiteral("moveJVelocity")).toDouble(0.1); + group.moveJAcceleration = groupObject.value( + QStringLiteral("moveJAcceleration")).toDouble(0.1); + for (const QJsonValue &pointValue : groupObject.value(QStringLiteral("points")).toArray()) { + const QJsonObject pointObject = pointValue.toObject(); + RecordedJointPoint point; + point.name = pointObject.value(QStringLiteral("name")).toString(); + point.side = pointObject.value(QStringLiteral("side")).toString(); + point.deviceId = pointObject.value(QStringLiteral("deviceId")).toString(); + for (const QJsonValue &name : pointObject.value(QStringLiteral("jointNames")).toArray()) + point.jointNames.append(name.toString()); + for (const QJsonValue &position : pointObject.value(QStringLiteral("positions")).toArray()) + point.positions.append(position.toDouble()); + if (!point.name.isEmpty() + && point.jointNames.size() == point.positions.size()) + group.points.append(point); + } + if (!group.name.isEmpty()) + m_jointProgramGroups.append(group); + } + if (document.isNull()) + appendLog(QStringLiteral("WARN"), + QStringLiteral("点位组 JSON 解析失败:%1").arg(parseError.errorString())); } - settings.endArray(); + + if (m_jointProgramGroups.isEmpty()) { + JointProgramGroup migrated; + migrated.name = QStringLiteral("默认组"); + const int pointCount = legacySettings.beginReadArray(QStringLiteral("arm/jointPoints")); + for (int i = 0; i < pointCount; ++i) { + legacySettings.setArrayIndex(i); + RecordedJointPoint point; + point.name = legacySettings.value(QStringLiteral("name")).toString(); + point.side = legacySettings.value(QStringLiteral("side")).toString(); + point.deviceId = legacySettings.value(QStringLiteral("deviceId")).toString(); + point.jointNames = legacySettings.value(QStringLiteral("jointNames")).toStringList(); + const QVariantList positions = + legacySettings.value(QStringLiteral("positions")).toList(); + for (const QVariant &position : positions) + point.positions.append(position.toDouble()); + if (!point.name.isEmpty() + && point.jointNames.size() == point.positions.size()) + migrated.points.append(point); + } + legacySettings.endArray(); + const QJsonDocument legacyFlow = QJsonDocument::fromJson( + legacySettings.value(QStringLiteral("arm/jointFlowGraph")).toByteArray()); + if (legacyFlow.isArray()) + migrated.flow = legacyFlow.array(); + m_jointProgramGroups.append(migrated); + activeGroupName = migrated.name; + } + + int activeIndex = 0; + for (int i = 0; i < m_jointProgramGroups.size(); ++i) { + if (m_jointProgramGroups.at(i).name == activeGroupName) { + activeIndex = i; + break; + } + } + m_activeJointProgramGroup = activeIndex; + m_updatingJointProgramGroup = true; + if (m_jointProgramGroupCombo) { + m_jointProgramGroupCombo->clear(); + for (const JointProgramGroup &group : m_jointProgramGroups) + m_jointProgramGroupCombo->addItem(group.name); + m_jointProgramGroupCombo->setCurrentIndex(activeIndex); + } + m_updatingJointProgramGroup = false; + m_recordedJointPoints = m_jointProgramGroups.at(activeIndex).points; if (m_jointFlowEditor) { - settings.setValue(QStringLiteral("arm/jointFlowGraph"), - QJsonDocument(m_jointFlowEditor->toJson()).toJson(QJsonDocument::Compact)); - settings.remove(QStringLiteral("arm/jointFlow")); + const QSignalBlocker blocker(m_jointFlowEditor); + m_jointFlowEditor->clear(); + m_jointFlowEditor->fromJson(m_jointProgramGroups.at(activeIndex).flow); + } + if (m_jointFlowVelocitySpin) + m_jointFlowVelocitySpin->setValue( + m_jointProgramGroups.at(activeIndex).moveJVelocity); + if (m_jointFlowAccelerationSpin) + m_jointFlowAccelerationSpin->setValue( + m_jointProgramGroups.at(activeIndex).moveJAcceleration); + refreshRecordedJointPoints(); + refreshJointFlowTable(); + if (!QFileInfo::exists(filePath)) { + saveJointPrograms(); + if (QFileInfo::exists(legacyJsonPath)) + appendLog(QStringLiteral("INFO"), + QStringLiteral("点位规划数据已迁移到程序目录:%1") + .arg(filePath)); + } +} + +void MainWindow::saveJointPrograms() +{ + storeCurrentJointProgramGroup(); + if (m_jointProgramGroups.isEmpty()) + return; + QJsonArray groups; + for (const JointProgramGroup &group : m_jointProgramGroups) { + QJsonObject groupObject; + groupObject.insert(QStringLiteral("name"), group.name); + QJsonArray points; + for (const RecordedJointPoint &point : group.points) { + QJsonObject pointObject; + pointObject.insert(QStringLiteral("name"), point.name); + pointObject.insert(QStringLiteral("side"), point.side); + pointObject.insert(QStringLiteral("deviceId"), point.deviceId); + QJsonArray names; + for (const QString &name : point.jointNames) + names.append(name); + QJsonArray positions; + for (double position : point.positions) + positions.append(position); + pointObject.insert(QStringLiteral("jointNames"), names); + pointObject.insert(QStringLiteral("positions"), positions); + points.append(pointObject); + } + groupObject.insert(QStringLiteral("points"), points); + groupObject.insert(QStringLiteral("flow"), group.flow); + groupObject.insert(QStringLiteral("moveJVelocity"), group.moveJVelocity); + groupObject.insert(QStringLiteral("moveJAcceleration"), group.moveJAcceleration); + groups.append(groupObject); + } + QJsonObject root; + root.insert(QStringLiteral("version"), 1); + root.insert(QStringLiteral("activeGroup"), + m_jointProgramGroups.at(m_activeJointProgramGroup).name); + root.insert(QStringLiteral("groups"), groups); + + const QString filePath = jointProgramsFilePath(); + QDir().mkpath(QFileInfo(filePath).absolutePath()); + QSaveFile file(filePath); + if (!file.open(QIODevice::WriteOnly) + || file.write(QJsonDocument(root).toJson(QJsonDocument::Indented)) < 0 + || !file.commit()) { + appendLog(QStringLiteral("ERROR"), + QStringLiteral("点位组保存失败:%1").arg(filePath)); } } @@ -2684,6 +2903,14 @@ void MainWindow::setControlsEnabled(bool enabled) m_velocitySpin->setEnabled(enabled); if (m_accelerationSpin) m_accelerationSpin->setEnabled(enabled); + if (m_moveJVelocitySpin) + m_moveJVelocitySpin->setEnabled(enabled); + if (m_moveJAccelerationSpin) + m_moveJAccelerationSpin->setEnabled(enabled); + if (m_jointFlowVelocitySpin) + m_jointFlowVelocitySpin->setEnabled(enabled && !m_jointPointLoopActive); + if (m_jointFlowAccelerationSpin) + m_jointFlowAccelerationSpin->setEnabled(enabled && !m_jointPointLoopActive); if (m_cartesianVelocitySpin) m_cartesianVelocitySpin->setEnabled(enabled); if (m_cartesianAccelerationSpin) diff --git a/src/mainwindow.h b/src/mainwindow.h index 21f3848..515fefd 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -116,8 +117,11 @@ private: QWidget *createDiagnosticsPage(); void loadSettings(); void saveSettings(); - void loadJointPrograms(QSettings &settings); - void saveJointPrograms(QSettings &settings) const; + void loadJointPrograms(QSettings &legacySettings); + void saveJointPrograms(); + void storeCurrentJointProgramGroup(); + void activateJointProgramGroup(int index); + QString jointProgramsFilePath() const; void setControlsEnabled(bool enabled); void updateWindowChrome(); void ensureArmModelLoaded(); @@ -195,6 +199,10 @@ private: QTableWidget *m_jointTable = nullptr; QTableWidget *m_motionTable = nullptr; QList m_targetSpins; + QList m_targetRadianSpins; + QPushButton *m_syncCurrentToTargetButton = nullptr; + QDoubleSpinBox *m_moveJVelocitySpin = nullptr; + QDoubleSpinBox *m_moveJAccelerationSpin = nullptr; QStringList m_activeArmJointNames; QList m_moveJPoseSpins; QComboBox *m_moveJPoseBaseLinkCombo = nullptr; @@ -248,13 +256,26 @@ private: QStringList jointNames; QVector positions; }; + struct JointProgramGroup { + QString name; + QList points; + QJsonArray flow; + double moveJVelocity = 0.1; + double moveJAcceleration = 0.1; + }; + QList m_jointProgramGroups; + int m_activeJointProgramGroup = -1; + bool m_updatingJointProgramGroup = false; QList m_recordedJointPoints; + QComboBox *m_jointProgramGroupCombo = nullptr; QHash m_latestArmJointPositions; QLineEdit *m_jointPointNameEdit = nullptr; QTableWidget *m_jointPointTable = nullptr; QLabel *m_jointPointDetailLabel = nullptr; QSpinBox *m_jointPointLoopCount = nullptr; QDoubleSpinBox *m_jointPointInterval = nullptr; + QDoubleSpinBox *m_jointFlowVelocitySpin = nullptr; + QDoubleSpinBox *m_jointFlowAccelerationSpin = nullptr; QSpinBox *m_jointFlowGroupCount = nullptr; JointFlowEditor *m_jointFlowEditor = nullptr; QDialog *m_jointFlowDialog = nullptr; @@ -277,6 +298,7 @@ private: VideoRenderWidget *m_videoRender = nullptr; QLabel *m_imageMetaLabel = nullptr; QPushButton *m_snapshotButton = nullptr; + QPushButton *m_depthSnapshotButton = nullptr; QPushButton *m_cameraStreamButton = nullptr; QPushButton *m_saveImageButton = nullptr; QComboBox *m_cameraCodecCombo = nullptr; @@ -296,6 +318,7 @@ private: QHash m_cameraPreviewTiles; QSet m_runningCameraIds; QImage m_lastImage; + bool m_lastImageIsDepth = false; bool m_cameraStreaming = false; bool m_cameraRecording = false; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index db06fc8..614442b 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -182,7 +182,7 @@ QString requestFlowNodeName(QWidget *parent, const QString &title, closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton")); closeButton->setFixedSize(46, 43); closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"), - QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#ffffff")))); + QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#4f5964")))); titleLayout->addWidget(mark); titleLayout->addWidget(titleLabel); titleLayout->addStretch(1); @@ -193,7 +193,10 @@ QString requestFlowNodeName(QWidget *parent, const QString &title, QVBoxLayout *contentLayout = new QVBoxLayout(content); contentLayout->setContentsMargins(18, 16, 18, 16); contentLayout->setSpacing(9); - QLabel *fieldLabel = new QLabel(QStringLiteral("节点名称"), content); + QLabel *fieldLabel = new QLabel( + title.contains(QStringLiteral("点位组")) ? QStringLiteral("组名称") + : QStringLiteral("节点名称"), + content); QLineEdit *nameEdit = new QLineEdit(initialValue, content); QHBoxLayout *actions = new QHBoxLayout; QPushButton *cancelButton = new QPushButton(QStringLiteral("取消"), content); @@ -445,6 +448,83 @@ QWidget *MainWindow::createArmPage() moveJLayout->setContentsMargins(16, 14, 16, 16); moveJLayout->setSpacing(12); + QFrame *groupPanel = new QFrame(moveJPage); + groupPanel->setObjectName(QStringLiteral("jointProgramGroupPanel")); + QHBoxLayout *groupLayout = new QHBoxLayout(groupPanel); + groupLayout->setContentsMargins(12, 8, 12, 8); + groupLayout->setSpacing(8); + QLabel *groupLabel = new QLabel(QStringLiteral("点位组"), groupPanel); + groupLabel->setObjectName(QStringLiteral("jointFlowSectionTitle")); + QLabel *groupHint = new QLabel( + QStringLiteral("每个组独立保存点位记录和执行流程"), groupPanel); + groupHint->setObjectName(QStringLiteral("jointFlowSectionSubtitle")); + m_jointProgramGroupCombo = new QComboBox(groupPanel); + m_jointProgramGroupCombo->setMinimumWidth(220); + m_jointProgramGroupCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents); + QPushButton *newGroupButton = new QPushButton(QStringLiteral("新建组"), groupPanel); + QPushButton *renameGroupButton = new QPushButton(QStringLiteral("重命名"), groupPanel); + newGroupButton->setObjectName(QStringLiteral("primaryButton")); + renameGroupButton->setObjectName(QStringLiteral("secondaryButton")); + groupLayout->addWidget(groupLabel); + groupLayout->addWidget(groupHint); + groupLayout->addStretch(1); + groupLayout->addWidget(m_jointProgramGroupCombo); + groupLayout->addWidget(newGroupButton); + groupLayout->addWidget(renameGroupButton); + moveJLayout->addWidget(groupPanel); + + connect(m_jointProgramGroupCombo, + QOverload::of(&QComboBox::currentIndexChanged), + this, [this](int index) { activateJointProgramGroup(index); }); + connect(newGroupButton, &QPushButton::clicked, this, [this]() { + bool ok = false; + const QString name = requestFlowNodeName( + m_jointFlowDialog, QStringLiteral("新建点位组"), QStringLiteral("新建组"), &ok); + if (!ok || name.isEmpty()) + return; + for (const JointProgramGroup &group : m_jointProgramGroups) { + if (group.name.compare(name, Qt::CaseInsensitive) == 0) { + QMessageBox::information(m_jointFlowDialog, QStringLiteral("新建点位组"), + QStringLiteral("已存在同名点位组。")); + return; + } + } + storeCurrentJointProgramGroup(); + JointProgramGroup group; + group.name = name; + m_jointProgramGroups.append(group); + const int newIndex = m_jointProgramGroups.size() - 1; + m_updatingJointProgramGroup = true; + m_jointProgramGroupCombo->addItem(name); + m_jointProgramGroupCombo->setCurrentIndex(newIndex); + m_updatingJointProgramGroup = false; + activateJointProgramGroup(newIndex); + }); + connect(renameGroupButton, &QPushButton::clicked, this, [this]() { + if (m_activeJointProgramGroup < 0 + || m_activeJointProgramGroup >= m_jointProgramGroups.size()) + return; + const QString oldName = m_jointProgramGroups.at(m_activeJointProgramGroup).name; + bool ok = false; + const QString name = requestFlowNodeName( + m_jointFlowDialog, QStringLiteral("重命名点位组"), oldName, &ok); + if (!ok || name.isEmpty() || name == oldName) + return; + for (int i = 0; i < m_jointProgramGroups.size(); ++i) { + if (i != m_activeJointProgramGroup + && m_jointProgramGroups.at(i).name.compare(name, Qt::CaseInsensitive) == 0) { + QMessageBox::information(m_jointFlowDialog, QStringLiteral("重命名点位组"), + QStringLiteral("已存在同名点位组。")); + return; + } + } + m_jointProgramGroups[m_activeJointProgramGroup].name = name; + m_updatingJointProgramGroup = true; + m_jointProgramGroupCombo->setItemText(m_activeJointProgramGroup, name); + m_updatingJointProgramGroup = false; + saveJointPrograms(); + }); + QFrame *pointPanel = new QFrame(moveJPage); pointPanel->setObjectName(QStringLiteral("jointPointPanel")); QVBoxLayout *pointLayout = new QVBoxLayout(pointPanel); @@ -542,8 +622,7 @@ QWidget *MainWindow::createArmPage() m_jointFlowEditor->removePointReferences(removedNames); refreshRecordedJointPoints(); refreshJointFlowTable(); - QSettings settings; - saveJointPrograms(settings); + saveJointPrograms(); }); connect(m_jointPointTable, &QTableWidget::cellClicked, this, [this](int row, int) { @@ -630,9 +709,30 @@ QWidget *MainWindow::createArmPage() QHBoxLayout *flowActions = new QHBoxLayout; QPushButton *flowDeleteButton = new QPushButton(QStringLiteral("删除选中节点"), flowPanel); flowDeleteButton->setObjectName(QStringLiteral("dangerOutlineButton")); + QLabel *flowVelocityLabel = new QLabel(QStringLiteral("MoveJ 速度"), flowPanel); + m_jointFlowVelocitySpin = new QDoubleSpinBox(flowPanel); + m_jointFlowVelocitySpin->setRange(0.001, 10.0); + m_jointFlowVelocitySpin->setDecimals(3); + m_jointFlowVelocitySpin->setSingleStep(0.01); + m_jointFlowVelocitySpin->setValue(0.1); + m_jointFlowVelocitySpin->setSuffix(QStringLiteral(" rad/s")); + m_jointFlowVelocitySpin->setMinimumWidth(140); + QLabel *flowAccelerationLabel = new QLabel(QStringLiteral("加速度"), flowPanel); + m_jointFlowAccelerationSpin = new QDoubleSpinBox(flowPanel); + m_jointFlowAccelerationSpin->setRange(0.001, 20.0); + m_jointFlowAccelerationSpin->setDecimals(3); + m_jointFlowAccelerationSpin->setSingleStep(0.01); + m_jointFlowAccelerationSpin->setValue(0.1); + m_jointFlowAccelerationSpin->setSuffix(QStringLiteral(" rad/s²")); + m_jointFlowAccelerationSpin->setMinimumWidth(140); m_startJointPointLoopButton->setObjectName(QStringLiteral("primaryButton")); m_stopJointPointLoopButton->setObjectName(QStringLiteral("dangerButton")); flowActions->addWidget(flowDeleteButton); + flowActions->addSpacing(10); + flowActions->addWidget(flowVelocityLabel); + flowActions->addWidget(m_jointFlowVelocitySpin); + flowActions->addWidget(flowAccelerationLabel); + flowActions->addWidget(m_jointFlowAccelerationSpin); flowActions->addStretch(1); flowActions->addWidget(loopCountLabel); loopCountLabel->setVisible(false); @@ -691,9 +791,12 @@ QWidget *MainWindow::createArmPage() m_jointFlowEditor->removeSelectedNode(); }); connect(m_jointFlowEditor, &JointFlowEditor::changed, this, [this]() { - QSettings settings; - saveJointPrograms(settings); + saveJointPrograms(); }); + connect(m_jointFlowVelocitySpin, QOverload::of(&QDoubleSpinBox::valueChanged), + this, [this](double) { saveJointPrograms(); }); + connect(m_jointFlowAccelerationSpin, QOverload::of(&QDoubleSpinBox::valueChanged), + this, [this](double) { saveJointPrograms(); }); FramelessToolDialog *jointFlowDialog = new FramelessToolDialog(this); m_jointFlowDialog = jointFlowDialog; m_jointFlowDialog->setObjectName(QStringLiteral("jointFlowDialog")); @@ -734,7 +837,7 @@ QWidget *MainWindow::createArmPage() jointFlowClose->setToolTip(QStringLiteral("关闭")); jointFlowClose->setFixedSize(48, 45); jointFlowClose->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"), - QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#ffffff")))); + QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#4f5964")))); jointFlowTitleLayout->addWidget(jointFlowMark); jointFlowTitleLayout->addWidget(jointFlowTitle); jointFlowTitleLayout->addWidget(jointFlowSubtitle); @@ -797,9 +900,52 @@ QWidget *MainWindow::createArmPage() ui.telemetryLayout->setStretch(0, 1); ui.telemetryLayout->setStretch(1, 1); - // Replace the old target/teaching workspace with hold-to-jog controls and - // a read-only telemetry panel. - ui.targetsPanel->hide(); + // Keep the MoveJ target panel in its own position-control tab. The model + // workspace below only replaces the old teaching/telemetry arrangement. + ui.targetsPanel->show(); + m_syncCurrentToTargetButton = new QPushButton( + QStringLiteral("当前位置同步到目标"), ui.targetsPanel); + m_syncCurrentToTargetButton->setObjectName(QStringLiteral("secondaryButton")); + m_syncCurrentToTargetButton->setToolTip( + QStringLiteral("按关节名称将最新遥测位置复制到目标角度和目标弧度")); + const int zeroButtonIndex = ui.targetsHeader->indexOf(ui.zeroButton); + ui.targetsHeader->insertWidget( + zeroButtonIndex >= 0 ? zeroButtonIndex : ui.targetsHeader->count(), + m_syncCurrentToTargetButton); + + QFrame *moveJParameters = new QFrame(ui.targetsPanel); + moveJParameters->setObjectName(QStringLiteral("jointFlowToolbar")); + QHBoxLayout *moveJParametersLayout = new QHBoxLayout(moveJParameters); + moveJParametersLayout->setContentsMargins(12, 8, 12, 8); + moveJParametersLayout->setSpacing(8); + QLabel *moveJParametersTitle = new QLabel( + QStringLiteral("MoveJ 运动参数"), moveJParameters); + moveJParametersTitle->setObjectName(QStringLiteral("eyebrow")); + QLabel *moveJVelocityLabel = new QLabel(QStringLiteral("速度"), moveJParameters); + m_moveJVelocitySpin = new QDoubleSpinBox(moveJParameters); + m_moveJVelocitySpin->setRange(0.001, 10.0); + m_moveJVelocitySpin->setDecimals(3); + m_moveJVelocitySpin->setSingleStep(0.01); + m_moveJVelocitySpin->setValue(0.1); + m_moveJVelocitySpin->setSuffix(QStringLiteral(" rad/s")); + m_moveJVelocitySpin->setMinimumWidth(150); + QLabel *moveJAccelerationLabel = new QLabel( + QStringLiteral("加速度"), moveJParameters); + m_moveJAccelerationSpin = new QDoubleSpinBox(moveJParameters); + m_moveJAccelerationSpin->setRange(0.001, 20.0); + m_moveJAccelerationSpin->setDecimals(3); + m_moveJAccelerationSpin->setSingleStep(0.01); + m_moveJAccelerationSpin->setValue(0.1); + m_moveJAccelerationSpin->setSuffix(QStringLiteral(" rad/s²")); + m_moveJAccelerationSpin->setMinimumWidth(150); + moveJParametersLayout->addWidget(moveJParametersTitle); + moveJParametersLayout->addSpacing(12); + moveJParametersLayout->addWidget(moveJVelocityLabel); + moveJParametersLayout->addWidget(m_moveJVelocitySpin); + moveJParametersLayout->addWidget(moveJAccelerationLabel); + moveJParametersLayout->addWidget(m_moveJAccelerationSpin); + moveJParametersLayout->addStretch(1); + ui.targetsLayout->insertWidget(1, moveJParameters); ui.teachPanel->hide(); ui.urdfTabLayout->removeWidget(ui.urdfViewer); ui.urdfTabLayout->removeWidget(ui.teachPanel); @@ -1112,8 +1258,8 @@ QWidget *MainWindow::createArmPage() const int commandTabIndex = ui.armTabs->indexOf(ui.jointControlTab); if (commandTabIndex >= 0) - ui.armTabs->removeTab(commandTabIndex); - ui.jointControlTab->hide(); + ui.armTabs->setTabText(commandTabIndex, QStringLiteral("关节位置控制")); + ui.jointControlTab->show(); ui.armTabs->addTab(new RpcServiceWidget(QStringLiteral("cmvr.api.ArmService"), m_client), QStringLiteral("全部接口")); ui.armTabs->setCurrentWidget(ui.urdfTab); @@ -1124,6 +1270,8 @@ QWidget *MainWindow::createArmPage() m_calibrateZeroButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/crosshair.svg"))); m_stopButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/square.svg"), Qt::white, Qt::white, QColor(QStringLiteral("#f4dddd")))); + m_sendMoveButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/send.svg"), Qt::white, + Qt::white, QColor(QStringLiteral("#e8eef5")))); m_jogStopButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/square.svg"), QColor(QStringLiteral("#cc3434")))); connect(m_armIdEdit, &QLineEdit::textChanged, m_armDeviceSummary, @@ -1177,6 +1325,33 @@ QWidget *MainWindow::createArmPage() connect(m_stopButton, &QPushButton::clicked, this, [this]() { m_client->requestArmStop(m_armIdEdit->text().trimmed()); }); + connect(ui.zeroButton, &QPushButton::clicked, this, [this]() { + for (QDoubleSpinBox *spin : m_targetSpins) + spin->setValue(0.0); + }); + connect(m_syncCurrentToTargetButton, &QPushButton::clicked, this, [this]() { + QStringList missing; + for (int row = 0; row < m_activeArmJointNames.size(); ++row) { + const QString &jointName = m_activeArmJointNames.at(row); + if (!m_latestArmJointPositions.contains(jointName) + || row >= m_targetRadianSpins.size()) { + missing.append(jointName); + continue; + } + m_targetRadianSpins.at(row)->setValue( + m_latestArmJointPositions.value(jointName)); + } + if (!missing.isEmpty()) { + QMessageBox::warning(this, QStringLiteral("同步当前位置"), + QStringLiteral("以下关节尚无遥测位置:\n%1\n\n请先启动遥测。") + .arg(missing.join(QStringLiteral(", ")))); + return; + } + appendLog(QStringLiteral("OK"), + QStringLiteral("已将 %1 个关节的遥测位置同步到 MoveJ 目标") + .arg(m_activeArmJointNames.size())); + }); + connect(m_sendMoveButton, &QPushButton::clicked, this, &MainWindow::sendMoveJ); connect(m_jogStopButton, &QPushButton::clicked, this, &MainWindow::stopArmJog); connect(m_jogSpeedSlider, &QSlider::valueChanged, this, [this](int value) { m_jogSpeedValue->setText(QStringLiteral("%1%").arg(value)); @@ -1238,6 +1413,22 @@ QWidget *MainWindow::createArmPage() m_jointTable->verticalHeader()->setDefaultSectionSize(28); m_jointTable->horizontalHeader()->setStretchLastSection(true); + m_motionTable->setColumnCount(5); + m_motionTable->setHorizontalHeaderLabels({ + QStringLiteral("关节"), QStringLiteral("当前位置 (°)"), + QStringLiteral("当前位置 (rad)"), QStringLiteral("目标角度 (°)"), + QStringLiteral("目标弧度 (rad)")}); + m_motionTable->setAlternatingRowColors(true); + m_motionTable->setSelectionMode(QAbstractItemView::NoSelection); + m_motionTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_motionTable->verticalHeader()->setVisible(false); + m_motionTable->verticalHeader()->setDefaultSectionSize(38); + m_motionTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); + m_motionTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); + m_motionTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); + m_motionTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); + m_motionTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch); + m_activeArmJointNames.clear(); m_jointTable->setRowCount(0); m_zeroJointCombo->clear(); @@ -1253,7 +1444,14 @@ QWidget *MainWindow::createArmPage() m_client->setArmTelemetry(oldDeviceId, false); m_armIdEdit->setText(newDeviceId); m_activeArmJointNames.clear(); + m_latestArmJointPositions.clear(); m_jointTable->setRowCount(0); + m_targetSpins.clear(); + m_targetRadianSpins.clear(); + m_motionTable->clearContents(); + m_motionTable->setRowCount(0); + m_sendMoveButton->setEnabled(false); + m_syncCurrentToTargetButton->setEnabled(false); rebuildArmJogControls(); m_zeroJointCombo->clear(); m_armDefaultBaseFrame.clear(); @@ -1273,7 +1471,8 @@ QWidget *MainWindow::createArmPage() m_serviceButtons << m_armTelemetryButton << m_armGlobalStopButton << m_torqueOnButton << m_torqueOffButton << m_clearFaultButton << m_calibrateZeroButton - << m_stopButton << m_jogStopButton; + << m_stopButton << m_jogStopButton << m_sendMoveButton + << m_syncCurrentToTargetButton; return page; } @@ -1372,6 +1571,8 @@ void MainWindow::refreshCameraStreamControls() m_cameraCodecCombo->setEnabled(false); m_cameraStreamModeCombo->setEnabled(!m_cameraStreaming); m_snapshotButton->setEnabled(m_connected && !m_cameraStreaming); + if (m_depthSnapshotButton) + m_depthSnapshotButton->setEnabled(m_connected && !m_cameraStreaming); m_cameraStreamStateLabel->setText(m_cameraStreaming ? QStringLiteral("%1 路播放中").arg(m_runningCameraIds.size()) : QStringLiteral("已停止")); @@ -1396,6 +1597,10 @@ QWidget *MainWindow::createCameraPage() ui.viewerLayout->addWidget(m_cameraPreviewContainer, 1); m_cameraDeviceCombo = ui.cameraDeviceCombo; m_snapshotButton = ui.snapshotButton; + m_depthSnapshotButton = new QPushButton(QStringLiteral("获取深度图像"), ui.controlsPanel); + m_depthSnapshotButton->setObjectName(QStringLiteral("secondaryButton")); + const int snapshotIndex = ui.controlsLayout->indexOf(m_snapshotButton); + ui.controlsLayout->insertWidget(snapshotIndex + 1, m_depthSnapshotButton); m_cameraStreamButton = ui.cameraStreamButton; m_cameraCodecCombo = ui.codecCombo; m_cameraStreamModeCombo = ui.streamModeCombo; @@ -1410,6 +1615,7 @@ QWidget *MainWindow::createCameraPage() m_cameraRecordStateLabel = ui.cameraRecordStateLabel; m_saveImageButton->setIcon(style()->standardIcon(QStyle::SP_DialogSaveButton)); m_snapshotButton->setIcon(style()->standardIcon(QStyle::SP_DialogOpenButton)); + m_depthSnapshotButton->setIcon(style()->standardIcon(QStyle::SP_DialogOpenButton)); m_cameraStreamButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay)); m_cameraRecordButton->setIcon(style()->standardIcon(QStyle::SP_DialogSaveButton)); @@ -1419,6 +1625,11 @@ QWidget *MainWindow::createCameraPage() if (!cameraIds.isEmpty()) m_client->requestSnapshot(cameraIds.first()); }); + connect(m_depthSnapshotButton, &QPushButton::clicked, this, [this]() { + const QStringList cameraIds = configuredCameraIds(); + if (!cameraIds.isEmpty()) + m_client->requestDepthSnapshot(cameraIds.first()); + }); connect(m_cameraCodecCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int index) { const QString codec = index == 1 ? QStringLiteral("h265") : QStringLiteral("h264"); @@ -1488,7 +1699,9 @@ QWidget *MainWindow::createCameraPage() } }); rebuildCameraPreviewGrid(configuredCameraIds()); - m_serviceButtons << m_snapshotButton << m_cameraStreamButton << m_cameraRecordButton; + ui.viewerTitle->setText(QStringLiteral("RGB / 深度预览")); + m_serviceButtons << m_snapshotButton << m_depthSnapshotButton + << m_cameraStreamButton << m_cameraRecordButton; return withRpcExplorer(page, m_client, QStringLiteral("cmvr.api.CameraService")); } diff --git a/src/robotclient.cpp b/src/robotclient.cpp index c2dd6e9..2f80dea 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -175,6 +175,46 @@ VideoFrame videoFrameFromImage(const QImage &image) } #ifdef CMVR_WITH_GRPC +QImage depthImageFromFrame(const cmvr::api::FrameData &frame) +{ + if (frame.width() <= 0 || frame.height() <= 0) + return {}; + const bool uint16Depth = frame.type() == cmvr::api::FrameData::U16C1; + const bool floatDepth = frame.type() == cmvr::api::FrameData::F32C1; + const int bytesPerPixel = uint16Depth ? 2 : (floatDepth ? 4 : 0); + if (bytesPerPixel == 0 + || frame.data().size() < frame.width() * frame.height() * bytesPerPixel) + return {}; + + QImage image(frame.width(), frame.height(), QImage::Format_RGB888); + const char *source = frame.data().data(); + for (int y = 0; y < frame.height(); ++y) { + uchar *destination = image.scanLine(y); + for (int x = 0; x < frame.width(); ++x) { + const int index = y * frame.width() + x; + double metres = 0.0; + if (uint16Depth) { + quint16 millimetres = 0; + std::memcpy(&millimetres, source + index * 2, sizeof(millimetres)); + metres = millimetres / 1000.0; + } else { + float value = 0.0f; + std::memcpy(&value, source + index * 4, sizeof(value)); + metres = value; + } + QColor color(Qt::black); + if (std::isfinite(metres) && metres > 0.0) { + const double normalized = qBound(0.0, metres / 5.0, 1.0); + color = QColor::fromHsvF(normalized * 0.66, 0.9, 1.0); + } + destination[x * 3] = static_cast(color.red()); + destination[x * 3 + 1] = static_cast(color.green()); + destination[x * 3 + 2] = static_cast(color.blue()); + } + } + return image; +} + VideoFrame videoFrameFromDepth(const cmvr::api::FrameData &frame) { if (frame.width() <= 0 || frame.height() <= 0 || @@ -1073,6 +1113,56 @@ public: #endif } + void depthSnapshot(const QString &cameraId) + { + if (!ensureConnected(QStringLiteral("Depth Snapshot")) + || !ensureDeviceId(QStringLiteral("Depth Snapshot"), cameraId)) + return; + if (m_demoMode) { + QImage image(640, 480, QImage::Format_RGB888); + for (int y = 0; y < image.height(); ++y) { + uchar *line = image.scanLine(y); + for (int x = 0; x < image.width(); ++x) { + const QColor color = QColor::fromHsvF( + (static_cast(x) / image.width()) * 0.66, 0.9, 1.0); + line[x * 3] = static_cast(color.red()); + line[x * 3 + 1] = static_cast(color.green()); + line[x * 3 + 2] = static_cast(color.blue()); + } + } + emit imageReceived(image, QStringLiteral("深度 · 640 x 480 · DEMO · 0–5 m")); + emit commandFinished(QStringLiteral("Depth Snapshot"), true, + QStringLiteral("深度图像获取成功")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::GetDepthImageCommand::Request request; + fillHeader(request.mutable_header(), cameraId); + cmvr::api::GetDepthImageCommand::Feedback response; + grpc::ClientContext context; + setDeadline(context, 3000); + const grpc::Status status = m_camera->GetDepthImage(&context, request, &response); + if (!status.ok() || !response.header().success()) { + finish(QStringLiteral("Depth Snapshot"), status, response.header().success(), + QString::fromStdString(response.header().error_message())); + return; + } + const auto &frame = response.depth_frame(); + const QImage image = depthImageFromFrame(frame); + if (image.isNull()) { + emit commandFinished(QStringLiteral("Depth Snapshot"), false, + QStringLiteral("不支持的深度图格式:type=%1, codec=%2") + .arg(frame.type()).arg(QString::fromStdString(frame.codec()))); + return; + } + emit imageReceived(image, QStringLiteral("深度 · %1 x %2 · %3 · 0–5 m") + .arg(frame.width()).arg(frame.height()) + .arg(QString::fromStdString(frame.codec()))); + emit commandFinished(QStringLiteral("Depth Snapshot"), true, + QStringLiteral("深度图像获取成功")); +#endif + } + void startDexHandTactileStream(const QString &deviceId) { if (!ensureConnected(QStringLiteral("DexHand Tactile Stream")) @@ -3660,6 +3750,8 @@ RobotClient::RobotClient(QObject *parent) connect(this, &RobotClient::armCalibrateZeroRequested, m_worker, &BackendWorker::armCalibrateZero); connect(this, &RobotClient::snapshotRequested, m_worker, &BackendWorker::snapshot); + connect(this, &RobotClient::depthSnapshotRequested, + m_worker, &BackendWorker::depthSnapshot); connect(this, &RobotClient::cameraStatusRequested, m_worker, &BackendWorker::getCameraStatus); connect(this, &RobotClient::dexHandStatusRequested, m_worker, &BackendWorker::getDexHandStatus); @@ -3794,6 +3886,10 @@ void RobotClient::requestArmCalibrateZero(const QString &deviceId, const QString emit armCalibrateZeroRequested(deviceId, jointName); } void RobotClient::requestSnapshot(const QString &cameraId) { emit snapshotRequested(cameraId); } +void RobotClient::requestDepthSnapshot(const QString &cameraId) +{ + emit depthSnapshotRequested(cameraId); +} void RobotClient::requestCameraStatus(const QString &cameraId) { emit cameraStatusRequested(cameraId); diff --git a/src/robotclient.h b/src/robotclient.h index dcbf7e1..84a2566 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -47,6 +47,7 @@ public slots: void requestArmClearFault(const QString &deviceId); void requestArmCalibrateZero(const QString &deviceId, const QString &jointName); void requestSnapshot(const QString &cameraId); + void requestDepthSnapshot(const QString &cameraId); void requestCameraStatus(const QString &cameraId); void requestDexHandStatus(const QString &deviceId); void requestDexHandCommand(const QString &deviceId, const QString &command, @@ -115,6 +116,7 @@ signals: void armClearFaultRequested(const QString &deviceId); void armCalibrateZeroRequested(const QString &deviceId, const QString &jointName); void snapshotRequested(const QString &cameraId); + void depthSnapshotRequested(const QString &cameraId); void cameraStatusRequested(const QString &cameraId); void dexHandStatusRequested(const QString &deviceId); void dexHandCommandRequested(const QString &deviceId, const QString &command, diff --git a/styles.qss b/styles.qss index fff8f53..c835a3c 100644 --- a/styles.qss +++ b/styles.qss @@ -1699,13 +1699,14 @@ QPushButton#jointFlowDialogCloseButton { border-top-right-radius: 8px; } QPushButton#jointFlowDialogCloseButton:hover { - background: #d83b3b; + background: #fde8e8; } QWidget#jointFlowWorkspace { background: #f3f6f9; } QFrame#jointPointPanel, -QFrame#jointFlowPanel { +QFrame#jointFlowPanel, +QFrame#jointProgramGroupPanel { background: #ffffff; border: 1px solid #dce3ea; border-radius: 8px; From 7804c026316bb9be58b21dd87643604abbcd7da1 Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Tue, 13 Oct 2026 09:24:03 +0800 Subject: [PATCH 14/15] feat: display arm motor current --- protos/cmvr/api/arm_command.proto | 1 + src/mainwindow.cpp | 4 +++- src/mainwindow_ui.cpp | 4 +++- src/robotclient.cpp | 2 ++ 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/protos/cmvr/api/arm_command.proto b/protos/cmvr/api/arm_command.proto index d9a32ef..7d29f97 100644 --- a/protos/cmvr/api/arm_command.proto +++ b/protos/cmvr/api/arm_command.proto @@ -176,6 +176,7 @@ message JointState { repeated double velocity = 3; repeated double effort = 4; double timestamp = 5; + repeated double current = 6; // Motor current in mA. } message JointRequest { diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 4dd1d01..eca100b 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1198,7 +1198,7 @@ void MainWindow::rebuildArmJointTables(const QStringList &jointNames) 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) + for (int column = 1; column < 5; ++column) m_jointTable->setItem(row, column, new QTableWidgetItem(QStringLiteral("--"))); } @@ -1463,6 +1463,7 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo continue; const double position = joint.value(QStringLiteral("position")).toDouble(); const double velocity = joint.value(QStringLiteral("velocity")).toDouble(); + const double current = joint.value(QStringLiteral("current")).toDouble(); const double acceleration = deltaSeconds > 0.0001 && m_previousJointVelocities.contains(nameItem->text()) ? (velocity - m_previousJointVelocities.value(nameItem->text())) / deltaSeconds @@ -1470,6 +1471,7 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo m_jointTable->item(row, 1)->setText(QString::number(position, 'f', 5)); m_jointTable->item(row, 2)->setText(QString::number(velocity, 'f', 5)); m_jointTable->item(row, 3)->setText(QString::number(acceleration, 'f', 4)); + m_jointTable->item(row, 4)->setText(QString::number(current, 'f', 0)); if (m_motionTable) { for (int targetRow = 0; targetRow < m_motionTable->rowCount(); ++targetRow) { QTableWidgetItem *targetName = m_motionTable->item(targetRow, 0); diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 614442b..f884539 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -1404,8 +1404,10 @@ QWidget *MainWindow::createArmPage() connect(m_urdfViewer, &UrdfViewerWidget::logMessage, this, &MainWindow::appendLog); + m_jointTable->setColumnCount(5); m_jointTable->setHorizontalHeaderLabels({QStringLiteral("关节"), QStringLiteral("位置 rad"), - QStringLiteral("速度 rad/s"), QStringLiteral("加速度 rad/s²")}); + QStringLiteral("速度 rad/s"), QStringLiteral("加速度 rad/s²"), + QStringLiteral("电流 mA")}); m_jointTable->setAlternatingRowColors(true); m_jointTable->setEditTriggers(QAbstractItemView::NoEditTriggers); m_jointTable->setSelectionMode(QAbstractItemView::NoSelection); diff --git a/src/robotclient.cpp b/src/robotclient.cpp index 2f80dea..3114c36 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -2774,6 +2774,7 @@ private: 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))); + joint.insert(QStringLiteral("current"), 320.0 + 180.0 * qAbs(qSin(phase * 0.9))); joints.append(joint); } QVariantMap pose; @@ -3399,6 +3400,7 @@ private: 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); + joint.insert(QStringLiteral("current"), i < jointState.current_size() ? jointState.current(i) : 0.0); joints.append(joint); } const auto &tcp = robotState.actual_tcp_pose(); From 83b123c046bab2ff7666f7327f3c23eb77d420e3 Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Tue, 13 Oct 2026 10:19:28 +0800 Subject: [PATCH 15/15] feat: improve joint flow node insertion --- src/jointfloweditor.cpp | 151 +++++++++++++++++++++++++--------------- src/jointfloweditor.h | 4 ++ src/mainwindow_ui.cpp | 24 ++++--- 3 files changed, 114 insertions(+), 65 deletions(-) diff --git a/src/jointfloweditor.cpp b/src/jointfloweditor.cpp index 00a15f2..a60e512 100644 --- a/src/jointfloweditor.cpp +++ b/src/jointfloweditor.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -319,8 +320,16 @@ JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent) connect(m_scene, &QGraphicsScene::selectionChanged, this, [this]() { for (QGraphicsItem *item : m_scene->selectedItems()) { const QString id = item->data(0).toString(); - if (!id.isEmpty()) { m_selectedNodeId = id; return; } + if (!id.isEmpty()) { + m_selectedNodeId = id; + if (const Node *selected = nodeById(id)) + m_insertionParentId = selected->parentId; + notifyInsertionContext(); + return; + } } + m_selectedNodeId.clear(); + notifyInsertionContext(); }); } @@ -338,10 +347,12 @@ void JointFlowEditor::addSingleNode(const QString &nodeName, const QString &poin const Node *insertionParent = nodeById(m_insertionParentId); node.parentId = insertionParent && insertionParent->type == LoopNode ? insertionParent->id : QString(); - node.order = childrenOf(node.parentId).size(); + node.order = insertionOrder(node.parentId); + makeRoomForInsertion(node.parentId, node.order); node.position = QPointF(40 + node.order * 220, 40 + (node.parentId.isEmpty() ? 0 : 100)); m_nodes.append(node); m_selectedNodeId = node.id; + layoutSiblings(node.parentId); rebuildScene(); emit changed(); } @@ -360,10 +371,12 @@ void JointFlowEditor::addLoopNode(const QString &nodeName, int loopCount, const Node *insertionParent = nodeById(m_insertionParentId); node.parentId = insertionParent && insertionParent->type == LoopNode ? insertionParent->id : QString(); - node.order = childrenOf(node.parentId).size(); + node.order = insertionOrder(node.parentId); + makeRoomForInsertion(node.parentId, node.order); node.position = QPointF(40 + node.order * 220, 40 + (node.parentId.isEmpty() ? 0 : 100)); m_nodes.append(node); m_selectedNodeId = node.id; + layoutSiblings(node.parentId); rebuildScene(); emit changed(); } @@ -515,7 +528,7 @@ void JointFlowEditor::setAvailablePointNames(const QStringList &pointNames) void JointFlowEditor::setInsertionAtRoot() { m_insertionParentId.clear(); - emit insertionContextChanged(QStringLiteral("根流程")); + notifyInsertionContext(); } bool JointFlowEditor::useSelectedLoopAsInsertionParent() @@ -524,7 +537,8 @@ bool JointFlowEditor::useSelectedLoopAsInsertionParent() if (!selected || selected->type != LoopNode) return false; m_insertionParentId = selected->id; - emit insertionContextChanged(selected->nodeName); + m_selectedNodeId.clear(); + notifyInsertionContext(); return true; } @@ -626,61 +640,87 @@ void JointFlowEditor::moveNode(const QString &id, const QPointF &position) { Node *node = nodeById(id); if (!node) return; - const QString originalParent = node->parentId; - const QPointF center = position + QPointF(kNodeWidth / 2.0, kNodeHeight / 2.0); - if (!originalParent.isEmpty()) { - for (const Node &candidate : m_nodes) { - if (candidate.id == id || candidate.parentId != originalParent) - continue; - if (QRectF(candidate.position, QSizeF(kNodeWidth, kNodeHeight)).contains(center)) { - rebuildScene(); - return; - } - } - } - node->position = position; - QString newParent = originalParent; - // Once a node belongs to a loop, dragging only changes its order inside that loop. - // This prevents an existing child from accidentally becoming a child of a sibling loop. - if (originalParent.isEmpty()) { - for (const Node &candidate : m_nodes) { - if (candidate.id == id || candidate.type != LoopNode) - continue; - if (!QRectF(candidate.position, QSizeF(kNodeWidth, kNodeHeight)).contains(center)) - continue; - bool createsCycle = false; - const Node *ancestor = &candidate; - while (ancestor && !ancestor->parentId.isEmpty()) { - if (ancestor->parentId == id) { createsCycle = true; break; } - ancestor = nodeById(ancestor->parentId); - } - if (!createsCycle) { - newParent = candidate.id; - break; - } - } - } - node = nodeById(id); - if (node) - node->parentId = newParent; - QStringList parents{newParent}; - for (const Node &candidate : m_nodes) - if (!parents.contains(candidate.parentId)) parents.append(candidate.parentId); - for (const QString &parent : parents) { - QList siblings; - for (Node &candidate : m_nodes) - if (candidate.parentId == parent) siblings.append(&candidate); - std::sort(siblings.begin(), siblings.end(), [](const Node *a, const Node *b) { - return a->position.x() == b->position.x() - ? a->position.y() < b->position.y() : a->position.x() < b->position.x(); - }); - for (int order = 0; order < siblings.size(); ++order) - siblings.at(order)->order = order; + const QString parentId = node->parentId; + const qreal droppedCenterX = position.x() + kNodeWidth / 2.0; + QList siblings; + for (Node &candidate : m_nodes) + if (candidate.parentId == parentId && candidate.id != id) + siblings.append(&candidate); + std::sort(siblings.begin(), siblings.end(), [](const Node *a, const Node *b) { + return a->order < b->order; + }); + + int targetOrder = 0; + for (const Node *sibling : siblings) { + if (droppedCenterX > sibling->position.x() + kNodeWidth / 2.0) + ++targetOrder; } + siblings.insert(targetOrder, node); + for (int order = 0; order < siblings.size(); ++order) + siblings.at(order)->order = order; + layoutSiblings(parentId); rebuildScene(); emit changed(); } +int JointFlowEditor::insertionOrder(const QString &parentId) const +{ + const Node *selected = nodeById(selectedNodeId()); + if (selected && selected->parentId == parentId) + return selected->order + 1; + return childrenOf(parentId).size(); +} + +void JointFlowEditor::makeRoomForInsertion(const QString &parentId, int order) +{ + for (Node &candidate : m_nodes) + if (candidate.parentId == parentId && candidate.order >= order) + ++candidate.order; +} + +void JointFlowEditor::layoutSiblings(const QString &parentId) +{ + QList siblings; + for (Node &candidate : m_nodes) + if (candidate.parentId == parentId) + siblings.append(&candidate); + std::sort(siblings.begin(), siblings.end(), [](const Node *a, const Node *b) { + return a->order < b->order; + }); + qreal startX = 40.0; + qreal y = 40.0; + if (!parentId.isEmpty()) { + const Node *parent = nodeById(parentId); + if (parent) { + startX = parent->position.x() + 40.0; + y = parent->position.y() + 112.0; + } else { + y = 140.0; + } + } + for (int order = 0; order < siblings.size(); ++order) { + siblings.at(order)->order = order; + siblings.at(order)->position = QPointF(startX + order * 220.0, y); + } + for (Node *sibling : siblings) + if (sibling->type == LoopNode) + layoutSiblings(sibling->id); +} + +void JointFlowEditor::notifyInsertionContext() +{ + const Node *parent = nodeById(m_insertionParentId); + const QString container = parent && parent->type == LoopNode + ? parent->nodeName : QStringLiteral("根流程"); + const Node *selected = nodeById(selectedNodeId()); + if (selected && selected->parentId == (parent ? parent->id : QString())) { + emit insertionContextChanged(QStringLiteral("%1(插入到“%2”之后)") + .arg(container, selected->nodeName)); + return; + } + emit insertionContextChanged(QStringLiteral("%1(末尾)").arg(container)); +} + void JointFlowEditor::normalizeOrders(const QString &parentId) { int order = 0; @@ -690,6 +730,7 @@ void JointFlowEditor::normalizeOrders(const QString &parentId) void JointFlowEditor::rebuildScene() { + const QSignalBlocker sceneBlocker(m_scene); m_scene->clear(); QHash cards; for (const Node &node : m_nodes) { diff --git a/src/jointfloweditor.h b/src/jointfloweditor.h index 0cd1aeb..2aaa469 100644 --- a/src/jointfloweditor.h +++ b/src/jointfloweditor.h @@ -62,6 +62,10 @@ private: void editNode(const QString &id); void toggleLoopCollapsed(const QString &id); void moveNode(const QString &id, const QPointF &position); + int insertionOrder(const QString &parentId) const; + void makeRoomForInsertion(const QString &parentId, int order); + void layoutSiblings(const QString &parentId); + void notifyInsertionContext(); void normalizeOrders(const QString &parentId); void rebuildScene(); void appendJsonNode(QJsonArray &target, const Node &node) const; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index f884539..6f13167 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -651,7 +651,7 @@ QWidget *MainWindow::createArmPage() QLabel *flowTitle = new QLabel(QStringLiteral("自定义执行流程"), flowPanel); flowTitle->setObjectName(QStringLiteral("jointFlowSectionTitle")); QLabel *flowSubtitle = new QLabel( - QStringLiteral("组合单步与循环节点,拖动调整执行顺序"), flowPanel); + QStringLiteral("选中节点后可在其后插入,拖动可调整同级执行顺序"), flowPanel); flowSubtitle->setObjectName(QStringLiteral("jointFlowSectionSubtitle")); QLabel *intervalLabel = new QLabel(QStringLiteral("完成后等待"), flowPanel); m_jointPointInterval = new QDoubleSpinBox(flowPanel); @@ -662,10 +662,12 @@ QWidget *MainWindow::createArmPage() m_jointFlowGroupCount = new QSpinBox(flowPanel); m_jointFlowGroupCount->setRange(1, 10000); m_jointFlowGroupCount->setValue(2); - QLabel *insertionContextLabel = new QLabel(QStringLiteral("添加到:根流程"), flowPanel); + QLabel *insertionContextLabel = new QLabel(QStringLiteral("添加到:根流程(末尾)"), flowPanel); insertionContextLabel->setObjectName(QStringLiteral("jointFlowContextChip")); - QPushButton *insertAtRootButton = new QPushButton(QStringLiteral("返回根流程"), flowPanel); - QPushButton *enterSelectedLoopButton = new QPushButton(QStringLiteral("进入选中循环"), flowPanel); + QPushButton *insertAtRootButton = new QPushButton( + QStringLiteral("切换到根流程末尾"), flowPanel); + QPushButton *enterSelectedLoopButton = new QPushButton( + QStringLiteral("添加到选中循环"), flowPanel); QPushButton *addFlowStepButton = new QPushButton(QStringLiteral("+ 单步节点"), flowPanel); QPushButton *addFlowLoopButton = new QPushButton(QStringLiteral("+ 循环节点"), flowPanel); insertAtRootButton->setObjectName(QStringLiteral("secondaryButton")); @@ -699,9 +701,11 @@ QWidget *MainWindow::createArmPage() flowBuilder->addWidget(addFlowLoopButton); flowLayout->addWidget(flowToolbar); QLabel *flowHint = new QLabel(QStringLiteral( - "默认在根流程添加;选中循环后点击“进入选中循环”,可向循环内添加节点。" - "点击“返回根流程”退出循环;双击卡片编辑参数,左键拖动节点,右键拖动画布。" - "循环卡片右上角可展开或收起子节点;循环内子节点只能在当前循环内调整顺序。"), flowPanel); + "未选中节点时添加到当前流程末尾;选中节点后,新节点将插入到该节点之后。" + "选中循环并点击“添加到选中循环”可添加第一个或末尾子节点;" + "点击“切换到根流程末尾”可退出循环并继续添加根节点。" + "双击卡片编辑参数;左键拖动仅调整同级顺序并自动吸附,右键拖动画布。" + "循环卡片右上角可展开或收起子节点。"), flowPanel); flowHint->setObjectName(QStringLiteral("mutedLabel")); flowLayout->addWidget(flowHint); m_jointFlowEditor = new JointFlowEditor(flowPanel); @@ -779,7 +783,7 @@ QWidget *MainWindow::createArmPage() m_jointFlowEditor, &JointFlowEditor::setInsertionAtRoot); connect(enterSelectedLoopButton, &QPushButton::clicked, this, [this]() { if (!m_jointFlowEditor->useSelectedLoopAsInsertionParent()) { - QMessageBox::information(m_jointFlowDialog, QStringLiteral("进入循环"), + QMessageBox::information(m_jointFlowDialog, QStringLiteral("添加到循环"), QStringLiteral("请先在画布中选择一个循环节点。")); } }); @@ -802,8 +806,8 @@ QWidget *MainWindow::createArmPage() m_jointFlowDialog->setObjectName(QStringLiteral("jointFlowDialog")); m_jointFlowDialog->setWindowTitle(QStringLiteral("机械臂点位与流程编排")); m_jointFlowDialog->setModal(false); - m_jointFlowDialog->resize(1240, 820); - m_jointFlowDialog->setMinimumSize(980, 680); + m_jointFlowDialog->resize(1480, 920); + m_jointFlowDialog->setMinimumSize(1120, 740); QVBoxLayout *jointFlowDialogLayout = new QVBoxLayout(m_jointFlowDialog); jointFlowDialogLayout->setContentsMargins(14, 14, 14, 14); jointFlowDialogLayout->setSpacing(0);