diff --git a/CMakeLists.txt b/CMakeLists.txt index 00d56a0..1008af4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -162,6 +162,8 @@ set(CMVR_SOURCES src/jointfloweditor.h src/motordebugwidget.h src/motordebugwidget.cpp + src/motorplot.h + src/motorplot.cpp src/jointpointdata.h src/main.cpp src/mainwindow.cpp diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index 5f4e02f..e71ffca 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -371,4 +371,5 @@ SOURCES += src/touchplanestore.cpp HEADERS += src/touchplanestore.h src/cameracapabilities.h src/bioheadoperations.h SOURCES += src/bioheadwidget.cpp HEADERS += src/bioheadwidget.h src/jointpointdata.h src/motordebugwidget.h -SOURCES += src/motordebugwidget.cpp +SOURCES += src/motordebugwidget.cpp src/motorplot.cpp +HEADERS += src/motorplot.h diff --git a/protos/cmvr/api/arm_command.proto b/protos/cmvr/api/arm_command.proto index 7d29f97..edb3a02 100644 --- a/protos/cmvr/api/arm_command.proto +++ b/protos/cmvr/api/arm_command.proto @@ -170,6 +170,18 @@ message ServoJ { } } +// Starts controller-side recording of a manually taught trajectory. +message StartTrajectoryRecording { + message Request { + CommandHeader.Request header = 1; + string file_name = 2; + } + + message Response { + CommandHeader.Feedback header = 1; + } +} + message JointState { repeated string name = 1; repeated double position = 2; diff --git a/protos/cmvr/api/arm_service.proto b/protos/cmvr/api/arm_service.proto index b772ee6..afb8ee0 100644 --- a/protos/cmvr/api/arm_service.proto +++ b/protos/cmvr/api/arm_service.proto @@ -27,4 +27,9 @@ service ArmService { // Vendor-specific arm extension currently used for AUBO cabinet IO. rpc ExecuteJsonCommand(JsonDeviceCommand.Request) returns (JsonDeviceCommand.Feedback); + rpc EnterTeachingMode(CommandHeader.Request) returns (CommandHeader.Feedback); + rpc StartTrajectoryRecording(StartTrajectoryRecording.Request) returns (StartTrajectoryRecording.Response); + rpc CompleteTeaching(CommandHeader.Request) returns (CommandHeader.Feedback); + rpc StopTrajectoryRecording(CommandHeader.Request) returns (CommandHeader.Feedback); + rpc ExitTeachingMode(CommandHeader.Request) returns (CommandHeader.Feedback); } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 88072e1..d4487a2 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1516,7 +1516,6 @@ void MainWindow::setArmTelemetryEnabled(bool enabled) if (shouldEnable) { m_client->requestArmInfo(deviceId); - m_client->requestArmFrames(deviceId); } m_client->setArmTelemetry(deviceId, shouldEnable); } @@ -1540,8 +1539,6 @@ void MainWindow::selectPage(int index) m_armHeaderControls->setVisible(index == 1); if (index == 1) ensureArmModelLoaded(); - if (pageUsesArmTelemetry(index) && !pageUsesArmTelemetry(previousIndex) && m_connected) - setArmTelemetryEnabled(true); if (index != 3) { stopAgvManualMotion(); if (m_agvStatusRefreshTimer) @@ -1705,8 +1702,6 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString & state->style()->polish(state); } setControlsEnabled(connected); - if (connected && m_pages && pageUsesArmTelemetry(m_pages->currentIndex())) - setArmTelemetryEnabled(true); if (m_agvStatusRefreshTimer) { if (connected && m_pages && m_pages->currentIndex() == 3) { m_client->requestAgvRefresh(m_agvIdEdit->text().trimmed()); @@ -2164,13 +2159,13 @@ void MainWindow::updateArmPoseFrames() ? QStringLiteral("使用当前机器人的标定偏移进行点动;单步最多 2 mm / 0.29°,松开即停止") : QStringLiteral("控制器坐标名称;原速度命令仍使用基座方向")); // Display fallbacks such as "base" and "tool0" are UI labels only. A - // named getPose request is safe only for a pair returned by the server's - // frame-list RPCs; motor-backed arms otherwise reject those invented names - // against their URDF. Empty names deliberately keep telemetry on - // getRobotState.actual_tcp_pose. + // Metadata defaults use getRobotState.actual_tcp_pose directly. Do not + // duplicate every sample with a named getPose query, or enumerate frames. const QString baseFrame = m_baseFrameCombo->currentText().trimmed(); const QString tcpFrame = m_tcpFrameCombo->currentText().trimmed(); - const bool serverFramePair = !local + const bool defaultPair = baseFrame == m_armDefaultBaseFrame + && tcpFrame == m_armDefaultTcpFrame; + const bool serverFramePair = !local && !defaultPair && m_controllerBaseFrames.contains(baseFrame) && m_controllerTcpFrames.contains(tcpFrame); m_client->setArmTelemetryFrames(m_armIdEdit->text().trimmed(), @@ -2187,6 +2182,8 @@ void MainWindow::updateArmInfo(const QString &deviceId, const QVariantMap &info) const QString manufacturer = info.value(QStringLiteral("manufacturer")).toString(); const QString model = info.value(QStringLiteral("model")).toString(); const QString subtype = info.value(QStringLiteral("subtype")).toString(); + const bool jointInfoOnly = info.value(QStringLiteral("source")).toString() + == QStringLiteral("getJointState"); m_armDefaultBaseFrame = info.value(QStringLiteral("defaultBaseFrame")).toString(); m_armDefaultTcpFrame = info.value(QStringLiteral("defaultTcpFrame")).toString(); const QStringList jointNames = info.value(QStringLiteral("jointNames")).toStringList(); @@ -2194,14 +2191,16 @@ void MainWindow::updateArmInfo(const QString &deviceId, const QVariantMap &info) // recovered from real telemetry, or recreate a button while it is held. if (!jointNames.isEmpty() && jointNames != m_activeArmJointNames) rebuildArmJointTables(jointNames); - if (m_baseFrameCombo && m_baseFrameCombo->count() == 0) + if (!jointInfoOnly && m_baseFrameCombo && m_baseFrameCombo->count() == 0) m_baseFrameCombo->addItem(m_armDefaultBaseFrame.isEmpty() ? QStringLiteral("base") : m_armDefaultBaseFrame); - if (m_tcpFrameCombo && m_tcpFrameCombo->count() == 0) + if (!jointInfoOnly && m_tcpFrameCombo && m_tcpFrameCombo->count() == 0) m_tcpFrameCombo->addItem(m_armDefaultTcpFrame.isEmpty() ? QStringLiteral("tool0") : m_armDefaultTcpFrame); if (m_armDeviceSummary) { - const QString identity = subtype.isEmpty() + const QString identity = jointInfoOnly + ? QStringLiteral("%1 · %2轴 · 型号未提供").arg(deviceId).arg(jointNames.size()) + : subtype.isEmpty() ? QStringLiteral("%1 · %2 %3").arg(deviceId, manufacturer, model) : QStringLiteral("%1 · %2 %3 (%4)").arg(deviceId, manufacturer, model, subtype); m_armDeviceSummary->setText(identity); @@ -2211,9 +2210,16 @@ void MainWindow::updateArmInfo(const QString &deviceId, const QVariantMap &info) manufacturer, model, subtype, info.value(QStringLiteral("descriptionId")).toString()); } - m_client->requestArmFrames(deviceId); - appendLog(QStringLiteral("INFO"), - QStringLiteral("机械臂 %1:SDK 型号 %2 %3,自由度 %4") + // Metadata defaults avoid traversing unsupported AUBO frame trees. + m_controllerBaseFrames = m_armDefaultBaseFrame.isEmpty() + ? QStringList{} : QStringList{m_armDefaultBaseFrame}; + m_controllerTcpFrames = m_armDefaultTcpFrame.isEmpty() + ? QStringList{} : QStringList{m_armDefaultTcpFrame}; + refreshTcpChoices(); + appendLog(QStringLiteral("INFO"), jointInfoOnly + ? QStringLiteral("机械臂 %1:已读取 %2 轴关节信息,服务端未提供型号接口") + .arg(deviceId).arg(jointNames.size()) + : QStringLiteral("机械臂 %1:SDK 型号 %2 %3,自由度 %4") .arg(deviceId, manufacturer, model) .arg(jointNames.size())); } @@ -2351,6 +2357,11 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo m_lastArmTelemetryMs = nowMs; QVariantMap displayPose = pose; + if (pose.isEmpty()) { + m_latestArmPose.clear(); + for (auto *label : m_poseMetricValues) label->setText(QStringLiteral("--")); + for (auto *label : m_cartesianJogPoseLabels) label->setText(QStringLiteral("--")); + } if (selectedLocalTcp()) { displayPose.clear(); if (m_tcpCalibration && m_tcpCalibration->referenceConfirmed()) { @@ -2391,9 +2402,23 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo .arg(index < 3 ? QStringLiteral("m") : QStringLiteral("rad"))); } } - if (!state.isEmpty()) { + if (state.contains(QStringLiteral("robotStateAvailable")) + && !state.value(QStringLiteral("robotStateAvailable")).toBool()) { + for (QLabel *label : {m_servoStatusValue, m_faultStatusValue}) { + if (!label) continue; + label->setText(QStringLiteral("服务端未提供")); + label->setProperty("state", QStringLiteral("unknown")); + label->setToolTip(QStringLiteral("关节数据正常;服务端未提供整体使能与故障状态接口")); + label->style()->unpolish(label); + label->style()->polish(label); + } + } else if (!state.isEmpty()) { + if (m_servoStatusValue) m_servoStatusValue->setToolTip(QString()); + if (m_faultStatusValue) m_faultStatusValue->setToolTip(QString()); const bool connected = state.value(QStringLiteral("connected")).toBool(); const bool powered = state.value(QStringLiteral("poweredOn")).toBool(); + const bool enabled = powered && (!state.contains(QStringLiteral("brakeReleased")) + || state.value(QStringLiteral("brakeReleased")).toBool()); const bool moving = state.value(QStringLiteral("moving")).toBool(); const bool fault = state.value(QStringLiteral("fault")).toBool(); const bool emergency = state.value(QStringLiteral("emergencyStopped")).toBool(); @@ -2420,8 +2445,9 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo m_servoStatusValue, isDisconnected ? QStringLiteral("已断开") : freedrive ? QStringLiteral("拖动示教") - : powered ? (moving ? QStringLiteral("已使能 · 运动中") + : enabled ? (moving ? QStringLiteral("已使能 · 运动中") : QStringLiteral("已使能 · 空闲")) + : powered ? QStringLiteral("已上电 · 未使能") : QStringLiteral("未使能"), (isDisconnected || isEmergency || isFault || isProtective) ? QStringLiteral("error") : QStringLiteral("good")); @@ -2599,20 +2625,14 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk, const QString selectedId = m_armSideCombo->currentData().toString(); if (m_armIdEdit && !selectedId.isEmpty() && (selectedId != previousId || m_activeArmJointNames.isEmpty())) { + if (selectedId != previousId && m_armTelemetryButton->isChecked()) + setArmTelemetryEnabled(false); m_armIdEdit->setText(selectedId); m_client->requestArmInfo(selectedId); - m_client->requestArmFrames(selectedId); } else if (m_armIdEdit && m_armIdEdit->text().trimmed().isEmpty() && !firstArmId.isEmpty()) { m_armIdEdit->setText(firstArmId); m_client->requestArmInfo(firstArmId); - m_client->requestArmFrames(firstArmId); - } - if (m_connected && m_pages && pageUsesArmTelemetry(m_pages->currentIndex()) - && !selectedId.isEmpty() && m_armTelemetryButton - && (selectedId != previousId - || !m_armTelemetryButton->isChecked())) { - setArmTelemetryEnabled(true); } if (m_cameraDeviceCombo) { @@ -3085,6 +3105,21 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri } else if (command == QStringLiteral("Clear Fault")) { stateLabel = m_faultStatusValue; stateText = success ? QStringLiteral("正常") : QStringLiteral("清除失败"); + } else if (command == QStringLiteral("Enter Teaching Mode")) { + stateLabel = m_deviceTeachingStateLabel; + stateText = success ? QStringLiteral("已进入示教,可拖动机械臂") : QStringLiteral("进入示教失败"); + } else if (command == QStringLiteral("Start Trajectory Recording")) { + stateLabel = m_deviceTeachingStateLabel; + stateText = success ? QStringLiteral("正在记录轨迹") : QStringLiteral("开始记录失败"); + } else if (command == QStringLiteral("Stop Trajectory Recording")) { + stateLabel = m_deviceTeachingStateLabel; + stateText = success ? QStringLiteral("已停止记录,仍处于示教模式") : QStringLiteral("停止记录失败"); + } else if (command == QStringLiteral("Exit Teaching Mode")) { + stateLabel = m_deviceTeachingStateLabel; + stateText = success ? QStringLiteral("已退出示教") : QStringLiteral("退出示教失败"); + } else if (command == QStringLiteral("Complete Teaching")) { + stateLabel = m_deviceTeachingStateLabel; + stateText = success ? QStringLiteral("示教已完成并退出") : QStringLiteral("完成示教失败"); } if (stateLabel) { stateLabel->setText(stateText); diff --git a/src/mainwindow.h b/src/mainwindow.h index 3327976..5212e39 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -284,6 +284,13 @@ private: QLabel *m_teachSelectedLabel = nullptr; QDoubleSpinBox *m_teachPositionSpin = nullptr; QTableWidget *m_teachJointTable = nullptr; + QLineEdit *m_trajectoryFileNameEdit = nullptr; + QPushButton *m_enterTeachingButton = nullptr; + QPushButton *m_startTrajectoryRecordingButton = nullptr; + QPushButton *m_completeTeachingButton = nullptr; + QPushButton *m_stopTrajectoryRecordingButton = nullptr; + QPushButton *m_exitTeachingButton = nullptr; + QLabel *m_deviceTeachingStateLabel = nullptr; QString m_teachSelectedJoint; QString m_pendingUrdfPath; bool m_armModelLoadScheduled = false; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 7fdd19f..53bd2f8 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -4,6 +4,7 @@ #include "audiostreammanager.h" #include "cameracapabilities.h" #include "robotclient.h" +#include "tcpjogcontroller.h" #include "tcptoolstore.h" #include "handeyemotionwidget.h" #include "tactileheatmapwidget.h" @@ -438,6 +439,13 @@ QWidget *MainWindow::createArmPage() m_teachSelectedLabel = ui.teachSelectedLabel; m_teachPositionSpin = ui.teachPositionSpin; m_teachJointTable = ui.teachJointTable; + m_trajectoryFileNameEdit = ui.trajectoryFileNameEdit; + m_enterTeachingButton = ui.enterTeachingButton; + m_startTrajectoryRecordingButton = ui.startTrajectoryRecordingButton; + m_completeTeachingButton = ui.completeTeachingButton; + m_stopTrajectoryRecordingButton = ui.stopTrajectoryRecordingButton; + m_exitTeachingButton = ui.exitTeachingButton; + m_deviceTeachingStateLabel = ui.deviceTeachingStateLabel; ui.jointTitle->setText(QStringLiteral("关节实时状态")); ui.jointTitle->setContentsMargins(16, 0, 0, 4); ui.poseTitle->setText(QStringLiteral("末端实时位姿")); @@ -1252,6 +1260,22 @@ QWidget *MainWindow::createArmPage() connect(m_stopButton, &QPushButton::clicked, this, [this]() { m_client->requestArmStop(m_armIdEdit->text().trimmed()); }); + connect(m_enterTeachingButton, &QPushButton::clicked, this, [this]() { + m_client->requestEnterTeachingMode(m_armIdEdit->text().trimmed()); + }); + connect(m_startTrajectoryRecordingButton, &QPushButton::clicked, this, [this]() { + m_client->requestStartTrajectoryRecording(m_armIdEdit->text().trimmed(), + m_trajectoryFileNameEdit->text().trimmed()); + }); + connect(m_completeTeachingButton, &QPushButton::clicked, this, [this]() { + m_client->requestCompleteTeaching(m_armIdEdit->text().trimmed()); + }); + connect(m_stopTrajectoryRecordingButton, &QPushButton::clicked, this, [this]() { + m_client->requestStopTrajectoryRecording(m_armIdEdit->text().trimmed()); + }); + connect(m_exitTeachingButton, &QPushButton::clicked, this, [this]() { + m_client->requestExitTeachingMode(m_armIdEdit->text().trimmed()); + }); connect(ui.zeroButton, &QPushButton::clicked, this, [this]() { for (QDoubleSpinBox *spin : m_targetSpins) spin->setValue(0.0); @@ -1283,10 +1307,9 @@ QWidget *MainWindow::createArmPage() 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(); - if (index == 1 && m_connected) - m_client->requestArmFrames(m_armIdEdit->text().trimmed()); + connect(m_jogModeTabs, &QTabWidget::currentChanged, this, [this](int) { + if (m_armJogActive) stopArmJog(); + if (m_tcpJog) m_tcpJog->stop(); }); connect(m_client, &RobotClient::armFramesReceived, this, [this](const QString &deviceId, @@ -1366,9 +1389,7 @@ QWidget *MainWindow::createArmPage() const QString newDeviceId = m_armSideCombo->currentData().toString().trimmed(); if (newDeviceId.isEmpty() || newDeviceId == oldDeviceId) return; - const bool telemetryRunning = m_armTelemetryButton->isChecked(); - if (telemetryRunning) - m_client->setArmTelemetry(oldDeviceId, false); + setArmTelemetryEnabled(false); m_armIdEdit->setText(newDeviceId); m_activeArmJointNames.clear(); m_latestArmJointPositions.clear(); @@ -1392,17 +1413,16 @@ QWidget *MainWindow::createArmPage() poseSubtitle->setText(QStringLiteral("等待 SDK 默认坐标系信息")); if (m_connected) { m_client->requestArmInfo(newDeviceId); - m_client->requestArmFrames(newDeviceId); } - if (telemetryRunning) - m_client->setArmTelemetry(newDeviceId, true); }); m_serviceButtons << m_armTelemetryButton << m_armGlobalStopButton << m_torqueOnButton << m_torqueOffButton << m_clearFaultButton << m_calibrateZeroButton << m_stopButton << m_jogStopButton << m_sendMoveButton - << m_syncCurrentToTargetButton; + << m_syncCurrentToTargetButton << m_enterTeachingButton + << m_startTrajectoryRecordingButton << m_completeTeachingButton + << m_stopTrajectoryRecordingButton << m_exitTeachingButton; return page; } diff --git a/src/motordebugwidget.cpp b/src/motordebugwidget.cpp index c05f110..920f21b 100644 --- a/src/motordebugwidget.cpp +++ b/src/motordebugwidget.cpp @@ -1,4 +1,5 @@ #include "motordebugwidget.h" +#include "motorplot.h" #include "robotclient.h" #include "applicationstyle.h" #include "appmessagebox.h" @@ -13,21 +14,15 @@ #include #include #include -#include #include #include #include -#include -#include -#include -#include #include #include #include #include #include #include -#include #include #include @@ -62,77 +57,6 @@ QString number(const QVariantMap &s,const QString &key,bool valid) { return valid && std::isfinite(v)?QString::number(v,'f',5):QStringLiteral("--"); } } -class MotorPlot final : public QWidget { -public: - struct Sample { double t,q,qd,qdd,tau; }; - QVector samples; - double window=30.0; - explicit MotorPlot(QWidget *parent):QWidget(parent) { setObjectName("motorFeedbackPlot");setMinimumHeight(480); } - void append(const QVariantMap &s) { - const double time=s.value("sampledAtS",missing()).toDouble(); - if (!std::isfinite(time)) return; - if (!samples.isEmpty() && time0&&dt<=1.0&&std::isfinite(previous.qd)&&std::isfinite(velocity))acceleration=(velocity-previous.qd)/dt; - } - samples.append({time,valid?s.value("position",missing()).toDouble():missing(), - valid?s.value("velocity",missing()).toDouble():missing(), - acceleration, - valid && s.value("torqueValid").toBool()?s.value("torque",missing()).toDouble():missing()}); - if (samples.size()>6000) samples.remove(0,samples.size()-6000); - update(); - } - void clear() { samples.clear(); update(); } -protected: - void paintEvent(QPaintEvent*) override { - QPainter p(this); p.setRenderHint(QPainter::Antialiasing); - p.fillRect(rect(),Qt::white); - const QStringList labels={QStringLiteral("位置 · rad"),QStringLiteral("速度 · rad/s"),QStringLiteral("加速度 · rad/s²(速度差分估算)"),QStringLiteral("力矩 · ‰ 额定转矩(1000‰ = 额定转矩)")}; - const QColor colors[]={QColor("#1b6ef3"),QColor("#16a085"),QColor("#7c3aed"),QColor("#d97706")}; - const double end=samples.isEmpty()?window:samples.last().t; - const double begin=end-window; - for (int k=0;k<4;++k) { - QRectF plot(85,k*height()/4.0+29,width()-105,height()/4.0-54); - p.setPen(QColor("#334155")); p.drawText(QPointF(12,k*height()/4.0+18),labels[k]); - double lo=missing(),hi=missing(); - auto value=[k](const Sample &s) { return k==0?s.q:k==1?s.qd:k==2?s.qdd:s.tau; }; - for (const auto &s:samples) if (s.t>=begin && std::isfinite(value(s))) { - if (!std::isfinite(lo)) lo=hi=value(s); - else { lo=qMin(lo,value(s)); hi=qMax(hi,value(s)); } - } - const bool have=std::isfinite(lo); - if (!have) { lo=-1;hi=1; } - const double pad=qMax((hi-lo)*0.12,k==3?1.0:0.001); lo-=pad;hi+=pad; - for (int i=0;i<=4;++i) { - const double y=plot.top()+plot.height()*i/4; - p.setPen(QColor("#e7edf5")); p.drawLine(QPointF(plot.left(),y),QPointF(plot.right(),y)); - p.setPen(QColor("#64748b")); p.drawText(QRectF(0,y-9,77,18),Qt::AlignRight|Qt::AlignVCenter,QString::number(hi-(hi-lo)*i/4,'g',5)); - } - for (int i=0;i<=4;++i) { - const double x=plot.left()+plot.width()*i/4; - p.setPen(QColor("#e7edf5")); p.drawLine(QPointF(x,plot.top()),QPointF(x,plot.bottom())); - p.setPen(QColor("#64748b")); p.drawText(QRectF(x-30,plot.bottom()+3,60,18),Qt::AlignCenter,QString::number(-window+window*i/4,'g',3)+" s"); - } - p.save(); p.setClipRect(plot); - QPainterPath path; bool started=false; double previous=0; - for (const auto &s:samples) { - const double v=value(s); - if (s.t1.0) path.moveTo(pt); else path.lineTo(pt); - started=true; previous=s.t; - } - p.setPen(QPen(colors[k],1.8)); p.drawPath(path); p.restore(); - if (!have) { p.setPen(QColor("#94a3b8"));p.drawText(plot,Qt::AlignCenter,QStringLiteral("等待有效反馈(不支持的数据不会以 0 代替)")); } - } - } -}; - MotorDebugWidget::MotorDebugWidget(RobotClient *client,QWidget *parent):QWidget(parent),m_client(client) { setObjectName("motorDebugPage"); @@ -150,7 +74,7 @@ MotorDebugWidget::MotorDebugWidget(RobotClient *client,QWidget *parent):QWidget( auto *title=new QLabel(QStringLiteral("电机反馈与曲线"),telemetry);title->setObjectName("sectionTitle");plotLayout->addWidget(title); auto *tools=new QHBoxLayout; m_acquire=new QCheckBox(QStringLiteral("持续采集"),telemetry);m_acquire->setObjectName("motorAcquire");tools->addWidget(m_acquire); - m_rate=new MotorInputBox(telemetry);m_rate->setRange(1,50);m_rate->setValue(20);m_rate->setSuffix(" Hz");tools->addWidget(m_rate); + m_rate=new MotorInputBox(telemetry);m_rate->setRange(1,std::numeric_limits::max());m_rate->setValue(20);m_rate->setSuffix(" Hz");tools->addWidget(m_rate); auto *read=new QPushButton(QStringLiteral("读取一次"),telemetry);tools->addWidget(read); auto *clear=new QPushButton(QStringLiteral("清空曲线"),telemetry);tools->addWidget(clear); auto *csv=new QPushButton(QStringLiteral("导出 CSV"),telemetry);tools->addWidget(csv); @@ -163,46 +87,78 @@ MotorDebugWidget::MotorDebugWidget(RobotClient *client,QWidget *parent):QWidget( auto *controls=new QWidget(scroll);scroll->setWidget(controls);auto *box=new QVBoxLayout(controls);box->setContentsMargins(0,0,0,0);box->setSpacing(10); auto panel=[&](const QString &text){ auto *card=new QFrame(controls);card->setObjectName("panel");auto *v=new QVBoxLayout(card); + card->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Maximum);v->setSpacing(8);v->setAlignment(Qt::AlignTop); auto *label=new QLabel(text,card);label->setObjectName("sectionTitle");v->addWidget(label);box->addWidget(card);return v; }; auto *parameters=panel(QStringLiteral("接口参数")); auto *form=new QFormLayout;form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);form->setSpacing(8);parameters->addLayout(form); m_mode=new QComboBox(controls);m_mode->setObjectName("motorRunMode"); - for(int mode:{0,1,2,3,4,5,7,8,9,10})m_mode->addItem(modeName(mode),mode); - m_mode->setCurrentIndex(1);form->addRow(QStringLiteral("mode · 运行模式"),m_mode); + for(int mode:{1,3,4,8,9,10})m_mode->addItem(modeName(mode),mode); + auto *modeLabel=new QLabel(QStringLiteral("运行模式"),controls);modeLabel->setFixedWidth(126); + m_mode->setCurrentIndex(0);form->addRow(modeLabel,m_mode); auto param=[&](const QString &key,const QString &label,double value){ auto *spin=new MotorInputBox(controls);spin->setObjectName("motorParam_"+key);spin->setDecimals(6);spin->setRange(-1e9,1e9);spin->setValue(value);spin->setKeyboardTracking(false); - m_parameters.insert(key,spin);form->addRow(label,spin); + m_parameters.insert(key,spin); + auto *caption=new QLabel(label,controls);caption->setFixedWidth(126);m_parameterLabels.insert(key,caption); + auto *row=new QWidget(controls);auto *fields=new QHBoxLayout(row);fields->setContentsMargins(0,0,0,0);fields->setSpacing(8); + fields->addWidget(caption);fields->addWidget(spin,1);parameters->addWidget(row);m_parameterRows.insert(key,row); }; param("q",QStringLiteral("q · 位置 rad"),0);param("qd",QStringLiteral("qd · 速度 rad/s"),0.05); param("qdd",QStringLiteral("qdd · 加速度 rad/s²"),0.1);param("tau",QStringLiteral("tau · 力矩 ‰"),0); - param("upper",QStringLiteral("upper · 上限"),1);param("lower",QStringLiteral("lower · 下限"),-1); - m_slope=new MotorInputBox(controls);m_slope->setObjectName("motorTorqueSlope");m_slope->setRange(0,1000000000);m_slope->setValue(100);form->addRow(QStringLiteral("torque_slope · ‰/s"),m_slope); - auto *hint=new QLabel(QStringLiteral("参数按接口原样发送;控制模式、使能及执行结果由服务端处理。"),controls);hint->setObjectName("mutedLabel");hint->setWordWrap(true);parameters->addWidget(hint); + m_slope=new MotorInputBox(controls);m_slope->setObjectName("motorTorqueSlope");m_slope->setRange(0,1000000000);m_slope->setValue(100); + m_slopeLabel=new QLabel(QStringLiteral("力矩变化率 · ‰/s"),controls);m_slopeLabel->setFixedWidth(126); + m_slopeRow=new QWidget(controls);auto *slopeFields=new QHBoxLayout(m_slopeRow);slopeFields->setContentsMargins(0,0,0,0);slopeFields->setSpacing(8); + slopeFields->addWidget(m_slopeLabel);slopeFields->addWidget(m_slope,1);parameters->addWidget(m_slopeRow); + auto *hint=new QLabel(QStringLiteral("选择模式仅调整输入项;设置模式、使能仍由对应按钮调用。"),controls);hint->setObjectName("mutedLabel");hint->setWordWrap(true);parameters->addWidget(hint); + auto *modeActions=new QHBoxLayout; + auto *setMode=new QPushButton(QStringLiteral("设置模式\nsetMode"),controls);setMode->setObjectName("motorRpc_setMode");setMode->setMinimumHeight(48); + m_rpcButtons.insert("setMode",setMode);connect(setMode,&QPushButton::clicked,this,[this]{invoke("setMode");}); + m_sendMotion=new QPushButton(controls);m_sendMotion->setObjectName("primaryButton");m_sendMotion->setMinimumHeight(48); + modeActions->addWidget(setMode,1);modeActions->addWidget(m_sendMotion,2);parameters->addLayout(modeActions); + connect(m_mode,QOverload::of(&QComboBox::currentIndexChanged),this,&MotorDebugWidget::refreshModeParameters); + connect(m_sendMotion,&QPushButton::clicked,this,[this]{invoke(motionMethod());}); + refreshModeParameters(); + auto rpcButton=[&](const QString &caption,const QString &method){ + auto *button=new QPushButton(caption+"\n"+method,controls);button->setObjectName("motorRpc_"+method);button->setMinimumHeight(46); + m_rpcButtons.insert(method,button); + connect(button,&QPushButton::clicked,this,[this,method]{invoke(method);}); + return button; + }; auto group=[&](const QString &name,const QList> &methods){ auto *v=panel(name);auto *grid=new QGridLayout;v->addLayout(grid);int index=0; for(const auto &entry:methods){ - auto *button=new QPushButton(entry.first+"\n"+entry.second,controls);button->setObjectName("motorRpc_"+entry.second);button->setMinimumHeight(46); - m_rpcButtons.insert(entry.second,button);grid->addWidget(button,index/2,index%2);++index; - connect(button,&QPushButton::clicked,this,[this,method=entry.second]{invoke(method);}); + auto *button=rpcButton(entry.first,entry.second);grid->addWidget(button,index/2,index%2);++index; } }; group(QStringLiteral("状态与参数读取"),{{QStringLiteral("列出电机"),"ListMotors"},{QStringLiteral("读取参数"),"GetInfo"}, {QStringLiteral("读取状态"),"GetState"},{QStringLiteral("读取模式"),"getMode"},{QStringLiteral("读取位置"),"getQ"}, {QStringLiteral("读取速度"),"getQd"},{QStringLiteral("读取力矩"),"getTau"},{QStringLiteral("查询到位"),"reachedTargetQ"}}); - group(QStringLiteral("电机控制"),{{QStringLiteral("设置模式"),"setMode"},{QStringLiteral("使能"),"torqueOn"},{QStringLiteral("去使能"),"torqueOff"}, + group(QStringLiteral("电机控制"),{{QStringLiteral("使能"),"torqueOn"},{QStringLiteral("去使能"),"torqueOff"}, {QStringLiteral("释放刹车"),"brakeRelease"},{QStringLiteral("快速停止"),"quickStop"},{QStringLiteral("零位校准"),"calibrateZeroQ"}}); - group(QStringLiteral("运动指令"),{{QStringLiteral("轮廓位置"),"commandProfilePosition"},{QStringLiteral("周期位置"),"commandCyclicPosition"}, - {QStringLiteral("轮廓速度"),"commandProfileVelocity"},{QStringLiteral("周期速度"),"commandCyclicVelocity"}, - {QStringLiteral("轮廓力矩"),"commandProfileTorque"},{QStringLiteral("周期力矩"),"commandCyclicTorque"}}); - group(QStringLiteral("限位参数设置"),{{QStringLiteral("位置限位"),"setLimitQ"},{QStringLiteral("速度上限"),"setLimitQd"},{QStringLiteral("加速度限位"),"setLimitQdd"}}); - auto *information=panel(QStringLiteral("电机参数"));m_info=new QLabel(controls);m_info->setWordWrap(true);m_info->setTextInteractionFlags(Qt::TextSelectableByMouse);information->addWidget(m_info);box->addStretch(); + auto *limits=panel(QStringLiteral("限位参数设置")); + auto limitInput=[&](QFormLayout *rows,const QString &key,const QString &caption,double initial){ + auto *spin=new MotorInputBox(controls);spin->setObjectName("motorLimit_"+key); + spin->setDecimals(6);spin->setRange(-1e9,1e9);spin->setValue(initial);spin->setKeyboardTracking(false); + m_limitParameters.insert(key,spin);rows->addRow(caption,spin); + }; + auto *positionLimits=new QFormLayout;positionLimits->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); + limitInput(positionLimits,"qLower",QStringLiteral("位置下限 · rad"),-1); + limitInput(positionLimits,"qUpper",QStringLiteral("位置上限 · rad"),1); + limits->addLayout(positionLimits);limits->addWidget(rpcButton(QStringLiteral("设置位置限位"),"setLimitQ")); + auto *velocityLimits=new QFormLayout;velocityLimits->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); + limitInput(velocityLimits,"qd",QStringLiteral("速度上限 · rad/s"),1); + limits->addLayout(velocityLimits);limits->addWidget(rpcButton(QStringLiteral("设置速度上限"),"setLimitQd")); + auto *accelerationLimits=new QFormLayout;accelerationLimits->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); + limitInput(accelerationLimits,"qddLower",QStringLiteral("加速度下限 · rad/s²"),-1); + limitInput(accelerationLimits,"qddUpper",QStringLiteral("加速度上限 · rad/s²"),1); + limits->addLayout(accelerationLimits);limits->addWidget(rpcButton(QStringLiteral("设置加速度限位"),"setLimitQdd")); + auto *information=panel(QStringLiteral("限位参数"));m_info=new QLabel(controls);m_info->setWordWrap(true);m_info->setTextInteractionFlags(Qt::TextSelectableByMouse);information->addWidget(m_info);box->addStretch(); splitter->setStretchFactor(0,1);splitter->setStretchFactor(1,0);splitter->setSizes({880,470}); - m_timer=new QTimer(this);m_timer->setInterval(50); + m_timer=new QTimer(this);m_timer->setTimerType(Qt::PreciseTimer);m_timer->setInterval(50); connect(m_timer,&QTimer::timeout,this,[this]{if(!m_inFlight)invoke("GetState");}); connect(m_acquire,&QCheckBox::toggled,this,[this](bool on){m_samples=0;m_elapsed.restart();if(on)m_timer->start();else m_timer->stop();}); - connect(m_rate,QOverload::of(&QSpinBox::valueChanged),this,[this](int v){m_timer->setInterval(qMax(20,1000/v));}); - connect(window,QOverload::of(&QComboBox::currentIndexChanged),this,[this,window]{m_plot->window=window->currentData().toDouble();m_plot->update();}); + connect(m_rate,QOverload::of(&QSpinBox::valueChanged),this,[this](int v){m_timer->setInterval(qMax(1,1000/v));}); + connect(window,QOverload::of(&QComboBox::currentIndexChanged),this,[this,window]{m_plot->setWindow(window->currentData().toDouble());}); connect(clear,&QPushButton::clicked,this,&MotorDebugWidget::clearSamples);connect(csv,&QPushButton::clicked,this,&MotorDebugWidget::exportCsv); connect(read,&QPushButton::clicked,this,[this]{invoke("GetState");}); connect(refresh,&QPushButton::clicked,this,[this]{invoke("ListMotors");}); @@ -223,20 +179,61 @@ MotorDebugWidget::MotorDebugWidget(RobotClient *client,QWidget *parent):QWidget( for(auto *combo:findChildren())ApplicationStyle::styleComboBox(combo); refreshControls(); } +QString MotorDebugWidget::motionMethod() const +{ + switch(m_mode->currentData().toInt()){ + case 1:return "commandProfilePosition"; + case 3:return "commandProfileVelocity"; + case 4:return "commandProfileTorque"; + case 8:return "commandCyclicPosition"; + case 9:return "commandCyclicVelocity"; + case 10:return "commandCyclicTorque"; + default:return {}; + } +} +void MotorDebugWidget::refreshModeParameters() +{ + const int mode=m_mode->currentData().toInt(); + const QHash visible{{"q",mode==1||mode==8},{"qd",mode==1||mode==3||mode==8||mode==9}, + {"qdd",mode==1||mode==3},{"tau",mode==4||mode==10}}; + for(auto it=visible.begin();it!=visible.end();++it){ + m_parameterRows[it.key()]->setVisible(it.value()); + m_parameters[it.key()]->setVisible(it.value());m_parameterLabels[it.key()]->setVisible(it.value()); + } + m_parameterLabels["q"]->setText(QStringLiteral("目标位置 · rad")); + m_parameterLabels["qd"]->setText(mode==1?QStringLiteral("轮廓速度 · rad/s"):mode==8?QStringLiteral("速度前馈 · rad/s"):QStringLiteral("目标速度 · rad/s")); + m_parameterLabels["qdd"]->setText(QStringLiteral("加速度 · rad/s²")); + m_parameterLabels["tau"]->setText(QStringLiteral("目标力矩 · ‰")); + m_slopeRow->setVisible(mode==4);m_slope->setVisible(mode==4);m_slopeLabel->setVisible(mode==4); + m_sendMotion->setText(QStringLiteral("发送%1指令\n%2").arg(modeName(mode),motionMethod())); +} void MotorDebugWidget::resetSelection(){ ++m_token;m_pending=0;m_inFlight=false;m_acquire->setChecked(false);m_lastResult.clear();clearSamples(); - m_values->setText(QStringLiteral("尚未读取电机状态"));showInfo();refreshControls(); + m_values->setText(QStringLiteral("尚未读取电机状态"));showInfo(true);refreshControls(); } void MotorDebugWidget::clearSamples(){m_plot->clear();m_rateStatus->setText(QStringLiteral("实际采集 -- Hz"));} double MotorDebugWidget::accelerationEstimate() const {return m_plot->samples.isEmpty()?missing():m_plot->samples.last().qdd;} -void MotorDebugWidget::showInfo(){ +void MotorDebugWidget::showInfo(bool updateLimits){ const auto i=m_motor->currentData().toMap(); - m_info->setText(QStringLiteral("%1 · ID %2 · %3\n配置限位 [%4, %5] rad\n速度 %6 rad/s · 加速度 %7 rad/s²(非硬件回读)") - .arg(i.value("jointName").toString()).arg(i.value("nodeId").toInt()).arg(i.value("driver").toString()) - .arg(i.value("limitQLb").toDouble()).arg(i.value("limitQUb").toDouble()).arg(i.value("limitQd").toDouble()).arg(i.value("limitQdd").toDouble())); + if(updateLimits&&!i.isEmpty()){ + m_limitParameters["qLower"]->setValue(i.value("limitQLb").toDouble()); + m_limitParameters["qUpper"]->setValue(i.value("limitQUb").toDouble()); + m_limitParameters["qd"]->setValue(i.value("limitQd").toDouble()); + const double acceleration=std::abs(i.value("limitQdd").toDouble()); + m_limitParameters["qddLower"]->setValue(-acceleration); + m_limitParameters["qddUpper"]->setValue(acceleration); + } + if(i.isEmpty()){ + m_info->setText(QStringLiteral("尚未读取限位参数")); + return; + } + m_info->setText(QStringLiteral("位置下限:%1 rad\n位置上限:%2 rad\n速度上限:%3 rad/s\n加速度上限:%4 rad/s²\n来源:服务端缓存(非硬件回读)") + .arg(number(i,"limitQLb",i.contains("limitQLb")),number(i,"limitQUb",i.contains("limitQUb")), + number(i,"limitQd",i.contains("limitQd")),number(i,"limitQdd",i.contains("limitQdd")))); } void MotorDebugWidget::refreshControls(){ const bool busy=m_inFlight&&m_pendingOperation!="GetState"; + m_sendMotion->setEnabled(m_connected&&!busy&&m_motor->currentIndex()>=0); m_manager->setEnabled(!busy);m_motor->setEnabled(!busy);m_acquire->setEnabled(m_connected&&m_motor->currentIndex()>=0); for(auto it=m_rpcButtons.begin();it!=m_rpcButtons.end();++it) it.value()->setEnabled(m_connected&&!busy&&!m_manager->currentData().toString().isEmpty()&&(it.key()=="ListMotors"||m_motor->currentIndex()>=0)); @@ -249,8 +246,23 @@ void MotorDebugWidget::invoke(const QString &method){ // so a deliberate interface click is not swallowed by background reads. ++m_token;m_inFlight=false; } - QVariantMap parameters;for(auto it=m_parameters.begin();it!=m_parameters.end();++it)parameters.insert(it.key(),it.value()->value()); - parameters.insert("mode",m_mode->currentData());parameters.insert("torqueSlope",m_slope->value()); + QVariantMap parameters; + parameters.insert("mode",m_mode->currentData()); + const auto put=[&](const QString &key){parameters.insert(key,m_parameters[key]->value());}; + if(method=="commandProfilePosition"){put("q");put("qd");put("qdd");} + else if(method=="commandProfileVelocity"){put("qd");put("qdd");} + else if(method=="commandProfileTorque"){put("tau");parameters.insert("torqueSlope",m_slope->value());} + else if(method=="commandCyclicPosition"){put("q");put("qd");} + else if(method=="commandCyclicVelocity")put("qd"); + else if(method=="commandCyclicTorque")put("tau"); + else if(method=="setLimitQ"){ + parameters.insert("upper",m_limitParameters["qUpper"]->value()); + parameters.insert("lower",m_limitParameters["qLower"]->value()); + }else if(method=="setLimitQd")parameters.insert("qd",m_limitParameters["qd"]->value()); + else if(method=="setLimitQdd"){ + parameters.insert("upper",m_limitParameters["qddUpper"]->value()); + parameters.insert("lower",m_limitParameters["qddLower"]->value()); + } m_pending=++m_token;m_pendingOperation=method;m_pendingManager=m_manager->currentData().toString(); m_pendingNode=m_motor->currentIndex()<0?-1:m_motor->currentData().toMap().value("nodeId").toInt();m_inFlight=true; if(method!="GetState")refreshControls(); @@ -266,7 +278,7 @@ void MotorDebugWidget::reply(quint64 token,const QString &method,bool ok,const Q if(i.value("nodeId").toInt()==m_pendingNode)selected=m_motor->count()-1; }if(m_motor->count())m_motor->setCurrentIndex(selected);} if(m_motor->currentIndex()<0||m_motor->currentData().toMap().value("nodeId").toInt()!=m_pendingNode)clearSamples(); - showInfo();refreshControls();m_status->setText(QStringLiteral("ListMotors:%1 个电机").arg(m_motor->count()));return; + showInfo(true);refreshControls();m_status->setText(QStringLiteral("ListMotors:%1 个电机").arg(m_motor->count()));return; } if(m_motor->currentData().toMap().value("nodeId").toInt()!=m_pendingNode)return; const auto s=response.value("state").toMap(); @@ -280,7 +292,7 @@ void MotorDebugWidget::reply(quint64 token,const QString &method,bool ok,const Q if(m_acquire->isChecked()){++m_samples;const double seconds=m_elapsed.elapsed()/1000.0;m_rateStatus->setText(QStringLiteral("实际 %1 Hz").arg(seconds>0?m_samples/seconds:0,0,'f',1));} m_status->setText(m_lastResult.isEmpty()?QStringLiteral("GetState:反馈已更新"):m_lastResult);return; } - if(method=="GetInfo"){QSignalBlocker b(m_motor);m_motor->setItemData(m_motor->currentIndex(),response.value("info"));showInfo();} + if(method=="GetInfo"){QSignalBlocker b(m_motor);m_motor->setItemData(m_motor->currentIndex(),response.value("info"));showInfo(true);} QString result=detail; if(method=="getQ")result=QString::number(s.value("position").toDouble(),'g',12)+" rad"; else if(method=="getQd")result=QString::number(s.value("velocity").toDouble(),'g',12)+" rad/s"; diff --git a/src/motordebugwidget.h b/src/motordebugwidget.h index 96af8e1..93a1c21 100644 --- a/src/motordebugwidget.h +++ b/src/motordebugwidget.h @@ -26,9 +26,11 @@ private: void invoke(const QString&); void reply(quint64,const QString&,bool,const QVariantMap&,const QString&); void refreshControls(); + void refreshModeParameters(); + QString motionMethod() const; void resetSelection(); void clearSamples(); - void showInfo(); + void showInfo(bool updateLimits = false); void exportCsv(); double accelerationEstimate() const; RobotClient *m_client; @@ -39,6 +41,12 @@ private: MotorPlot *m_plot; QTimer *m_timer; QHash m_parameters; + QHash m_limitParameters; + QHash m_parameterLabels; + QHash m_parameterRows; + QLabel *m_slopeLabel; + QWidget *m_slopeRow; + QPushButton *m_sendMotion; QHash m_rpcButtons; bool m_connected=false,m_inFlight=false; quint64 m_token=0,m_pending=0; diff --git a/src/motorplot.cpp b/src/motorplot.cpp new file mode 100644 index 0000000..c08a2f0 --- /dev/null +++ b/src/motorplot.cpp @@ -0,0 +1,279 @@ +#include "motorplot.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +double missing() { return std::numeric_limits::quiet_NaN(); } +const QStringList titles = { + QStringLiteral("位置 · rad"), QStringLiteral("速度 · rad/s"), + QStringLiteral("加速度 · rad/s²(速度窗口拟合估算)"), + QStringLiteral("力矩 · ‰ 额定转矩(1000‰ = 额定转矩)") +}; +const QStringList units = {"rad", "rad/s", QStringLiteral("rad/s²"), QStringLiteral("‰")}; +const QColor colors[] = {QColor("#1b6ef3"), QColor("#16a085"), QColor("#7c3aed"), QColor("#d97706")}; +double niceStep(double raw) +{ + const double power = std::pow(10.0, std::floor(std::log10(raw))); + const double fraction = raw / power; + return (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * power; +} +} + +MotorPlot::MotorPlot(QWidget *parent) : QWidget(parent) +{ + setObjectName("motorFeedbackPlot"); + setMinimumSize(360, 560); + setMouseTracking(true); +} + +double MotorPlot::value(const Sample &sample, int channel) +{ + return channel == 0 ? sample.q : channel == 1 ? sample.qd : channel == 2 ? sample.qdd : sample.tau; +} + +double MotorPlot::estimateAcceleration(double time, double velocity) const +{ + // Fit actual feedback velocities over an actual-time window, not a fixed + // sample count or the requested polling rate. High-rate samples must still + // cover the minimum time span before an acceleration can be estimated. + if (!std::isfinite(velocity) || samples.isEmpty()) return missing(); + const double interval = time - samples.last().t; + double previousInterval = interval; + if (samples.size() >= 2 && std::isfinite(samples[samples.size() - 2].qd)) + previousInterval = samples.last().t - samples[samples.size() - 2].t; + const double gapLimit = std::max(0.25, previousInterval * 3.0); + if (interval <= 0 || interval > gapLimit) return missing(); + const double horizon = std::max(0.25, interval * 4.0); + double sx = 0, sy = velocity, sxx = 0, sxy = 0; + double newer = time, oldest = time; + int count = 1; + for (int i = samples.size() - 1; i >= 0; --i) { + const auto &sample = samples[i]; + const double dt = newer - sample.t; + if (!std::isfinite(sample.qd) || dt <= 0 || dt > gapLimit || time - sample.t > horizon + 1e-9) break; + const double x = sample.t - time; + sx += x; + sy += sample.qd; + sxx += x * x; + sxy += x * sample.qd; + oldest = newer = sample.t; + ++count; + } + const double denominator = count * sxx - sx * sx; + if (count < 3 || time - oldest < 0.02 || denominator <= 1e-12) return missing(); + const double acceleration = (count * sxy - sx * sy) / denominator; + return std::isfinite(acceleration) ? acceleration : missing(); +} + +void MotorPlot::append(const QVariantMap &state) +{ + const double time = state.value("sampledAtS", missing()).toDouble(); + if (!std::isfinite(time)) return; + if (!samples.isEmpty() && time < samples.last().t) clear(); + if (!samples.isEmpty() && time == samples.last().t) return; + const bool valid = state.value("feedbackValid").toBool(); + const double position = valid ? state.value("position", missing()).toDouble() : missing(); + const double velocity = valid ? state.value("velocity", missing()).toDouble() : missing(); + const double torque = state.value("torqueValid").toBool() + ? state.value("torque", missing()).toDouble() : missing(); + samples.append({time, position, velocity, estimateAcceleration(time, velocity), torque}); + if (samples.size() > 6000) samples.remove(0, samples.size() - 6000); + update(); +} + +void MotorPlot::clear() +{ + samples.clear(); + m_views = {}; + m_hoverChannel = -1; + update(); +} + +void MotorPlot::setWindow(double seconds) +{ + m_window = seconds; + m_views = {}; + update(); +} + +QRectF MotorPlot::plotRect(int channel) const +{ + return QRectF(85, channel * height() / 4.0 + 29, width() - 105, height() / 4.0 - 54); +} + +int MotorPlot::channelAt(const QPointF &position) const +{ + for (int channel = 0; channel < 4; ++channel) + if (plotRect(channel).contains(position)) return channel; + return -1; +} + +MotorPlot::Range MotorPlot::rangeFor(int channel) const +{ + if (m_views[channel].manual) return m_views[channel].range; + double low = missing(), high = missing(); + const double end = samples.isEmpty() ? 0 : samples.last().t; + for (const auto &sample : samples) { + const double v = value(sample, channel); + if (sample.t < end - m_window || !std::isfinite(v)) continue; + if (!std::isfinite(low)) low = high = v; + else { low = std::min(low, v); high = std::max(high, v); } + } + if (!std::isfinite(low)) { low = -1; high = 1; } + const double padding = std::max((high - low) * 0.12, channel == 3 ? 1.0 : 0.001); + const double step = niceStep((high - low + 2 * padding) / 4); + return {-m_window, 0, std::floor((low - padding) / step) * step, + std::ceil((high + padding) / step) * step}; +} + +bool MotorPlot::hoverSample(int &index, QPointF &point) const +{ + if (m_hoverChannel < 0 || samples.isEmpty()) return false; + const auto plot = plotRect(m_hoverChannel); + const auto range = rangeFor(m_hoverChannel); + const double end = samples.last().t; + const double target = end + range.left + + (m_mouse.x() - plot.left()) / plot.width() * (range.right - range.left); + double distance = std::numeric_limits::max(); + index = -1; + for (int i = 0; i < samples.size(); ++i) { + const double t = samples[i].t - end, v = value(samples[i], m_hoverChannel); + if (t < range.left || t > range.right || !std::isfinite(v) || v < range.bottom || v > range.top) continue; + const double d = std::abs(samples[i].t - target); + if (d < distance) { distance = d; index = i; } + } + if (index < 0) return false; + point = QPointF(plot.left() + (samples[index].t - end - range.left) / (range.right - range.left) * plot.width(), + plot.bottom() - (value(samples[index], m_hoverChannel) - range.bottom) / (range.top - range.bottom) * plot.height()); + // Do not claim a nearby value inside a missing-data gap or empty time range. + return std::abs(point.x() - m_mouse.x()) <= 16; +} + +void MotorPlot::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.fillRect(rect(), Qt::white); + const double end = samples.isEmpty() ? 0 : samples.last().t; + for (int channel = 0; channel < 4; ++channel) { + const auto plot = plotRect(channel); + const auto range = rangeFor(channel); + painter.setPen(QColor("#334155")); + painter.drawText(QPointF(12, channel * height() / 4.0 + 18), titles[channel]); + for (int i = 0; i <= 4; ++i) { + const double y = plot.top() + plot.height() * i / 4; + painter.setPen(QColor("#e7edf5")); + painter.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y)); + painter.setPen(QColor("#64748b")); + painter.drawText(QRectF(0, y - 9, 77, 18), Qt::AlignRight | Qt::AlignVCenter, + QString::number(range.top - (range.top - range.bottom) * i / 4, 'g', 5)); + const double x = plot.left() + plot.width() * i / 4; + painter.setPen(QColor("#e7edf5")); + painter.drawLine(QPointF(x, plot.top()), QPointF(x, plot.bottom())); + painter.setPen(QColor("#64748b")); + painter.drawText(QRectF(x - 35, plot.bottom() + 3, 70, 18), Qt::AlignCenter, + QString::number(range.left + (range.right - range.left) * i / 4, 'g', 4) + " s"); + } + painter.save(); + painter.setClipRect(plot); + QPainterPath path; + bool started = false, have = false; + double previous = 0; + for (const auto &sample : samples) { + const double v = value(sample, channel), t = sample.t - end; + if (t < range.left || t > range.right || !std::isfinite(v)) { started = false; continue; } + const QPointF point(plot.left() + (t - range.left) / (range.right - range.left) * plot.width(), + plot.bottom() - (v - range.bottom) / (range.top - range.bottom) * plot.height()); + if (!started || sample.t - previous > 1.5) { + path.moveTo(point); + painter.setPen(QPen(colors[channel], 2)); + painter.drawPoint(point); + } else path.lineTo(point); + started = have = true; + previous = sample.t; + } + painter.setPen(QPen(colors[channel], 1.8)); + painter.drawPath(path); + painter.restore(); + if (!have) { + painter.setPen(QColor("#94a3b8")); + painter.drawText(plot, Qt::AlignCenter, QStringLiteral("等待有效反馈")); + } + if (channel == m_hoverChannel) { + int index; + QPointF point; + if (hoverSample(index, point)) { + painter.setPen(QPen(QColor("#94a3b8"), 1, Qt::DashLine)); + painter.drawLine(QPointF(point.x(), plot.top()), QPointF(point.x(), plot.bottom())); + painter.drawLine(QPointF(plot.left(), point.y()), QPointF(plot.right(), point.y())); + painter.setPen(QPen(colors[channel], 2)); + painter.setBrush(Qt::white); + painter.drawEllipse(point, 4, 4); + const QString text = QStringLiteral("距最新 %1 s\n数值 %2 %3") + .arg(samples[index].t - end, 0, 'f', 3) + .arg(value(samples[index], channel), 0, 'g', 9).arg(units[channel]); + const auto size = painter.fontMetrics().boundingRect(QRect(0, 0, 320, 70), Qt::AlignLeft, text).size(); + QRectF bubble(QPointF(m_mouse.x() + 12, m_mouse.y() - size.height() - 22), QSizeF(size.width() + 20, size.height() + 14)); + bubble.moveLeft(std::max(plot.left(), std::min(bubble.left(), plot.right() - bubble.width()))); + bubble.moveTop(std::max(plot.top(), std::min(bubble.top(), plot.bottom() - bubble.height()))); + painter.setPen(QColor("#b9cbe1")); + painter.setBrush(QColor("#f8fbff")); + painter.drawRoundedRect(bubble, 5, 5); + painter.setPen(QColor("#17395c")); + painter.drawText(bubble.adjusted(10, 7, -10, -7), Qt::AlignLeft | Qt::AlignVCenter, text); + } + } + } +} + +void MotorPlot::mouseMoveEvent(QMouseEvent *event) +{ + m_mouse = event->localPos(); + m_hoverChannel = channelAt(m_mouse); + update(); +} + +void MotorPlot::leaveEvent(QEvent *event) +{ + m_hoverChannel = -1; + update(); + QWidget::leaveEvent(event); +} + +void MotorPlot::wheelEvent(QWheelEvent *event) +{ + const int channel = channelAt(event->posF()); + if (channel < 0 || event->angleDelta().y() == 0) { event->ignore(); return; } + const auto plot = plotRect(channel); + const auto range = rangeFor(channel); + const double factor = std::pow(0.8, event->angleDelta().y() / 120.0); + const double xFraction = (event->posF().x() - plot.left()) / plot.width(); + const double yFraction = (plot.bottom() - event->posF().y()) / plot.height(); + const double x = range.left + xFraction * (range.right - range.left); + const double y = range.bottom + yFraction * (range.top - range.bottom); + const double width = qBound(0.02, (range.right - range.left) * factor, 3600.0); + const double height = qBound(1e-9, (range.top - range.bottom) * factor, 1e15); + m_views[channel] = {true, {x - xFraction * width, x + (1 - xFraction) * width, + y - yFraction * height, y + (1 - yFraction) * height}}; + m_mouse = event->posF(); + m_hoverChannel = channel; + event->accept(); + update(); +} + +void MotorPlot::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::RightButton) { + const int channel = channelAt(event->localPos()); + if (channel >= 0) { m_views[channel] = {}; update(); } + event->accept(); + return; + } + QWidget::mousePressEvent(event); +} diff --git a/src/motorplot.h b/src/motorplot.h new file mode 100644 index 0000000..071248e --- /dev/null +++ b/src/motorplot.h @@ -0,0 +1,40 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +class MotorPlot final : public QWidget { + friend struct MotorDebugTestAccess; +public: + struct Sample { double t, q, qd, qdd, tau; }; + explicit MotorPlot(QWidget *parent = nullptr); + void append(const QVariantMap &state); + void clear(); + void setWindow(double seconds); + QVector samples; + +protected: + void paintEvent(QPaintEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void leaveEvent(QEvent *) override; + void wheelEvent(QWheelEvent *) override; + void mousePressEvent(QMouseEvent *) override; + +private: + struct Range { double left, right, bottom, top; }; + struct View { bool manual = false; Range range{}; }; + QRectF plotRect(int channel) const; + int channelAt(const QPointF &position) const; + Range rangeFor(int channel) const; + double estimateAcceleration(double time, double velocity) const; + static double value(const Sample &sample, int channel); + bool hoverSample(int &index, QPointF &point) const; + double m_window = 30.0; + std::array m_views{}; + QPointF m_mouse; + int m_hoverChannel = -1; +}; diff --git a/src/robotclient.cpp b/src/robotclient.cpp index d34b3cf..9a6be0d 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -57,6 +57,20 @@ namespace { constexpr int kGrpcMaxMessageBytes = 64 * 1024 * 1024; constexpr int kArmMotionTimeoutMs = 120000; +bool confirmedJointNames(const cmvr::api::JointState &state, QStringList &names) +{ + names.clear(); + if (state.position_size() == 0 || state.name_size() != state.position_size()) + return false; + for (int i = 0; i < state.name_size(); ++i) { + const QString name = QString::fromStdString(state.name(i)).trimmed(); + if (name.isEmpty() || names.contains(name) || !std::isfinite(state.position(i))) + return false; + names.append(name); + } + return true; +} + std::shared_ptr createGrpcChannel(const std::string &endpoint) { grpc::ChannelArguments arguments; @@ -307,6 +321,11 @@ public: m_port = port; m_demoMode = demoMode; m_tick = 0; +#ifdef CMVR_WITH_GRPC + m_jointTelemetryOnly = false; + m_legacyArmDiscovery.clear(); + m_armFrameDefaults.clear(); +#endif if (m_host.isEmpty()) { emit connectionChanged(false, 0, QStringLiteral("主机地址不能为空")); @@ -568,6 +587,31 @@ public: grpc::ClientContext context; setDeadline(context, 1200); const grpc::Status status = m_arm->GetArmInfo(&context, request, &response); + if (status.error_code() == grpc::StatusCode::UNIMPLEMENTED) { + cmvr::api::JointRequest jointRequest; + fillHeader(jointRequest.mutable_header(), deviceId); + cmvr::api::JointResponse jointResponse; + grpc::ClientContext jointContext; + setDeadline(jointContext, 1200); + const auto jointStatus = m_arm->getJointState(&jointContext, jointRequest, &jointResponse); + QStringList names; + if (!jointStatus.ok() || !jointResponse.header().success() + || !confirmedJointNames(jointResponse.state(), names)) { + emit commandFinished(QStringLiteral("GetArmInfo"), false, + QStringLiteral("服务端未提供 GetArmInfo,关节信息读取失败:%1").arg( + !jointStatus.ok() ? QString::fromStdString(jointStatus.error_message()) + : QStringLiteral("关节名称或位置缺失、重复或无效"))); + return; + } + info.insert(QStringLiteral("dof"), names.size()); + info.insert(QStringLiteral("jointNames"), names); + info.insert(QStringLiteral("source"), QStringLiteral("getJointState")); + emit armInfoReceived(deviceId.trimmed(), info); + emit commandFinished(QStringLiteral("GetArmInfo"), true, + QStringLiteral("已从关节接口读取 %1 轴信息;型号和整体使能状态由服务端提供后显示") + .arg(names.size())); + return; + } if (!status.ok() || !response.header().success()) { const QString detail = status.ok() ? QString::fromStdString(response.header().error_message()) @@ -589,6 +633,9 @@ public: info.insert(QStringLiteral("descriptionId"), QString::fromStdString(response.description_id())); info.insert(QStringLiteral("detectedFromSdk"), response.detected_from_sdk()); info.insert(QStringLiteral("driverType"), QString::fromStdString(response.driver_type())); + m_armFrameDefaults.insert(deviceId.trimmed(), + {QString::fromStdString(response.default_base_frame()).trimmed(), + QString::fromStdString(response.default_tcp_frame()).trimmed()}); emit armInfoReceived(deviceId.trimmed(), info); #endif } @@ -798,35 +845,12 @@ public: return; } #ifdef CMVR_WITH_GRPC - cmvr::api::ListFrame::Request baseRequest; - fillHeader(baseRequest.mutable_header(), deviceId); - cmvr::api::ListFrame::Response baseResponse; - grpc::ClientContext baseContext; - setDeadline(baseContext, 1500); - const grpc::Status baseStatus = - m_arm->ListBaseFrame(&baseContext, baseRequest, &baseResponse); - if (baseStatus.ok() && baseResponse.header().success()) { - for (const auto &name : baseResponse.frame_names()) - baseFrames.append(QString::fromStdString(name)); - } - - cmvr::api::ListFrame::Request tcpRequest; - fillHeader(tcpRequest.mutable_header(), deviceId); - cmvr::api::ListFrame::Response tcpResponse; - grpc::ClientContext tcpContext; - setDeadline(tcpContext, 1500); - const grpc::Status tcpStatus = - m_arm->ListTCPFrame(&tcpContext, tcpRequest, &tcpResponse); - if (tcpStatus.ok() && tcpResponse.header().success()) { - for (const auto &name : tcpResponse.frame_names()) - tcpFrames.append(QString::fromStdString(name)); - } + // No remote frame enumeration: some AUBO controllers do not implement + // SyncMove.frameGetChildren. Use only defaults returned by GetArmInfo. + const auto defaults = m_armFrameDefaults.value(deviceId.trimmed()); + if (!defaults.first.isEmpty()) baseFrames.append(defaults.first); + if (!defaults.second.isEmpty()) tcpFrames.append(defaults.second); emit armFramesReceived(deviceId.trimmed(), baseFrames, tcpFrames); - if (!baseStatus.ok() || !baseResponse.header().success() - || !tcpStatus.ok() || !tcpResponse.header().success()) { - emit logMessage(QStringLiteral("WARN"), - QStringLiteral("机械臂坐标系列表未完整返回,将使用 SDK 默认坐标系")); - } #endif } @@ -1277,13 +1301,30 @@ public: cmvr::api::GetArmInfo::Request request; fillHeader(request.mutable_header(), id); cmvr::api::GetArmInfo::Response response; - const auto status = cmvr::api::ArmService::NewStub(channel)->GetArmInfo(context.get(), request, &response); + auto stub = cmvr::api::ArmService::NewStub(channel); + auto status = stub->GetArmInfo(context.get(), request, &response); { std::lock_guard lock(session->contextMutex); session->groupContexts.clear(); } QStringList names; for (const auto &n : response.joint_names()) names.append(QString::fromStdString(n)); - if (!status.ok() || !response.header().success()) { - const auto error=QString::fromStdString(status.ok() - ? response.header().error_message() : status.error_message()); + bool infoSuccess = response.header().success(); + QString infoError = QString::fromStdString(response.header().error_message()); + if (status.error_code() == grpc::StatusCode::UNIMPLEMENTED && !session->stop.load()) { + context = std::make_shared(); + setDeadline(*context, 2000); + { std::lock_guard lock(session->contextMutex); + session->groupContexts.push_back(context); + if (session->stop.load()) context->TryCancel(); } + cmvr::api::JointRequest jointRequest; + fillHeader(jointRequest.mutable_header(), id); + cmvr::api::JointResponse jointResponse; + status = stub->getJointState(context.get(), jointRequest, &jointResponse); + { std::lock_guard lock(session->contextMutex); session->groupContexts.clear(); } + infoSuccess = jointResponse.header().success() + && confirmedJointNames(jointResponse.state(), names); + infoError = QString::fromStdString(jointResponse.header().error_message()); + } + if (!status.ok() || !infoSuccess) { + const auto error = status.ok() ? infoError : QString::fromStdString(status.error_message()); fail(id + QStringLiteral(":读取机械臂信息失败:") + (error.isEmpty() ? QStringLiteral("接口未返回成功") : error)); break; @@ -1466,7 +1507,8 @@ public: fillHeader(&request, deviceId); cmvr::api::CommandHeader::Feedback response; grpc::ClientContext context; - setDeadline(context, 2000); + // Vendor arms may need to wait for power-on and brake-release states. + setDeadline(context, enabled ? 35000 : 2000); const grpc::Status status = enabled ? m_arm->torqueOn(&context, request, &response) : m_arm->torqueOff(&context, request, &response); @@ -1548,6 +1590,53 @@ public: #endif } + void enterTeachingMode(const QString &deviceId) + { + teachingCommand(QStringLiteral("Enter Teaching Mode"), deviceId, 0); + } + + void startTrajectoryRecording(const QString &deviceId, const QString &fileName) + { + const QString command = QStringLiteral("Start Trajectory Recording"); + if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) + return; + if (fileName.trimmed().isEmpty()) { + emit commandFinished(command, false, QStringLiteral("轨迹文件名不能为空")); + return; + } + if (m_demoMode) { + emit commandFinished(command, true, + QStringLiteral("已开始记录示教轨迹:%1(演示)").arg(fileName)); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::StartTrajectoryRecording::Request request; + fillHeader(request.mutable_header(), deviceId); + request.set_file_name(fileName.trimmed().toStdString()); + cmvr::api::StartTrajectoryRecording::Response response; + grpc::ClientContext context; + setDeadline(context, 2500); + const grpc::Status status = m_arm->StartTrajectoryRecording(&context, request, &response); + finish(command, status, response.header().success(), + QString::fromStdString(response.header().error_message())); +#endif + } + + void completeTeaching(const QString &deviceId) + { + teachingCommand(QStringLiteral("Complete Teaching"), deviceId, 1); + } + + void stopTrajectoryRecording(const QString &deviceId) + { + teachingCommand(QStringLiteral("Stop Trajectory Recording"), deviceId, 2); + } + + void exitTeachingMode(const QString &deviceId) + { + teachingCommand(QStringLiteral("Exit Teaching Mode"), deviceId, 3); + } + void snapshot(const QString &cameraId) { if (!ensureConnected(QStringLiteral("Snapshot"))) @@ -2341,7 +2430,7 @@ public: const double disk = statusResponse.disk_total_gb() > 0 ? statusResponse.disk_used_gb() * 100.0 / statusResponse.disk_total_gb() : 0.0; emit systemStatusReceived(statusResponse.cpu_usage(), memory, disk, - deviceListFromStatus(statusResponse)); + discoverLegacyArms(statusResponse)); } if (!infoStatus.ok() || !response.header().success()) { @@ -3500,6 +3589,42 @@ private: } private: + void teachingCommand(const QString &command, const QString &deviceId, int operation) + { + if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) + return; + if (m_demoMode) { + emit commandFinished(command, true, QStringLiteral("示教命令执行成功(演示)")); + return; + } +#ifdef CMVR_WITH_GRPC + cmvr::api::CommandHeader::Request request; + fillHeader(&request, deviceId); + cmvr::api::CommandHeader::Feedback response; + grpc::ClientContext context; + setDeadline(context, 2500); + grpc::Status status; + switch (operation) { + case 0: + status = m_arm->EnterTeachingMode(&context, request, &response); + break; + case 1: + status = m_arm->CompleteTeaching(&context, request, &response); + break; + case 2: + status = m_arm->StopTrajectoryRecording(&context, request, &response); + break; + default: + status = m_arm->ExitTeachingMode(&context, request, &response); + break; + } + finish(command, status, response.success(), + QString::fromStdString(response.error_message())); +#else + Q_UNUSED(operation) +#endif + } + bool ensureConnected(const QString &command) { if (m_connected) @@ -4251,6 +4376,9 @@ private: const bool armPollDue = m_consecutivePollErrors < 3 || m_tick % 10 == 0; if (m_armPollingEnabled && !m_armDeviceId.isEmpty() && armPollDue) { const QString polledDeviceId = m_armDeviceId; + if (m_jointTelemetryOnly) { + pollLegacyArmTelemetry(polledDeviceId); + } else { cmvr::api::GetRobotState::Request request; fillHeader(request.mutable_header(), polledDeviceId); cmvr::api::GetRobotState::Response response; @@ -4335,6 +4463,9 @@ private: emit armTelemetryHealthChanged( polledDeviceId, true, QStringLiteral("机械臂遥测通信已恢复")); } + } else if (status.error_code() == grpc::StatusCode::UNIMPLEMENTED) { + m_jointTelemetryOnly = true; + pollLegacyArmTelemetry(polledDeviceId); } else { ++m_consecutivePollErrors; QString detail; @@ -4353,6 +4484,7 @@ private: if (m_consecutivePollErrors == 3) emit armTelemetryHealthChanged(polledDeviceId, false, detail); } + } } if (m_tick % 10 != 0) @@ -4368,10 +4500,90 @@ private: const double disk = statusResponse.disk_total_gb() > 0 ? statusResponse.disk_used_gb() * 100.0 / statusResponse.disk_total_gb() : 0.0; emit systemStatusReceived(statusResponse.cpu_usage(), memory, disk, - deviceListFromStatus(statusResponse)); + discoverLegacyArms(statusResponse)); } } + QVariantList discoverLegacyArms(const cmvr::api::GetSystemStatusCommand::Feedback &response) + { + auto devices = deviceListFromStatus(response); + QSet present; + for (auto &value : devices) { + auto device = value.toMap(); + const QString id = device.value(QStringLiteral("deviceId")).toString(); + present.insert(id); + // Older servers default unknown drivers to enum zero (AGV). Probe + // only ambiguous entries, never override explicit device metadata. + if (device.value(QStringLiteral("type")).toInt() != cmvr::api::AGV + || device.value(QStringLiteral("deviceKind")).toInt() != cmvr::api::DEVICE_KIND_UNKNOWN + || !device.value(QStringLiteral("driverType")).toString().isEmpty()) + continue; + if (!m_legacyArmDiscovery.contains(id)) { + cmvr::api::JointRequest request; + fillHeader(request.mutable_header(), id); + cmvr::api::JointResponse joints; + grpc::ClientContext context; + setDeadline(context, 350); + const auto status = m_arm->getJointState(&context, request, &joints); + QStringList names; + if (status.ok() && joints.header().success() + && confirmedJointNames(joints.state(), names)) + m_legacyArmDiscovery.insert(id, true); + else if (status.error_code() == grpc::StatusCode::NOT_FOUND + || status.error_code() == grpc::StatusCode::UNIMPLEMENTED) + m_legacyArmDiscovery.insert(id, false); + } + if (m_legacyArmDiscovery.value(id, false)) { + device.insert(QStringLiteral("type"), int(cmvr::api::Robot)); + device.insert(QStringLiteral("typeName"), QStringLiteral("Robot")); + device.insert(QStringLiteral("deviceKind"), int(cmvr::api::DEVICE_KIND_ARM)); + device.insert(QStringLiteral("deviceKindName"), QStringLiteral("DEVICE_KIND_ARM")); + device.insert(QStringLiteral("identitySource"), QStringLiteral("ArmService.getJointState")); + value = device; + } + } + for (auto it = m_legacyArmDiscovery.begin(); it != m_legacyArmDiscovery.end(); ) { + if (!present.contains(it.key())) it = m_legacyArmDiscovery.erase(it); + else ++it; + } + return devices; + } + + void pollLegacyArmTelemetry(const QString &deviceId) + { + cmvr::api::JointRequest request; + fillHeader(request.mutable_header(), deviceId); + cmvr::api::JointResponse response; + grpc::ClientContext context; + setDeadline(context, 350); + const auto status = m_arm->getJointState(&context, request, &response); + QStringList names; + if (!status.ok() || !response.header().success() + || !confirmedJointNames(response.state(), names)) { + if (++m_consecutivePollErrors == 3) + emit armTelemetryHealthChanged(deviceId, false, + !status.ok() ? QString::fromStdString(status.error_message()) + : QStringLiteral("服务端未返回有效关节数据")); + return; + } + const bool recovered = m_consecutivePollErrors >= 3; + m_consecutivePollErrors = 0; + QVariantList joints; + const auto &values = response.state(); + for (int i = 0; i < names.size(); ++i) { + QVariantMap joint{{QStringLiteral("name"), names.at(i)}, + {QStringLiteral("position"), values.position(i)}}; + if (i < values.velocity_size()) joint.insert(QStringLiteral("velocity"), values.velocity(i)); + if (i < values.effort_size()) joint.insert(QStringLiteral("effort"), values.effort(i)); + if (i < values.current_size()) joint.insert(QStringLiteral("current"), values.current(i)); + joints.append(joint); + } + emit telemetryReceived(deviceId, joints, {}, + {{QStringLiteral("robotStateAvailable"), false}, + {QStringLiteral("source"), QStringLiteral("getJointState")}}); + if (recovered) emit armTelemetryHealthChanged(deviceId, true, QStringLiteral("关节遥测通信已恢复")); + } + std::shared_ptr m_channel; std::shared_ptr m_configChannel; std::unique_ptr m_arm; @@ -4382,6 +4594,9 @@ private: std::unique_ptr m_microphone; std::unique_ptr m_generic; std::unique_ptr m_configuration; + bool m_jointTelemetryOnly = false; + QHash m_legacyArmDiscovery; + QHash> m_armFrameDefaults; grpc::ClientContext *m_speakerStreamContext = nullptr; std::mutex m_speakerContextMutex; grpc::ClientContext *m_microphoneStreamContext = nullptr; @@ -4724,6 +4939,16 @@ RobotClient::RobotClient(QObject *parent) connect(this, &RobotClient::armClearFaultRequested, m_worker, &BackendWorker::armClearFault); connect(this, &RobotClient::armCalibrateZeroRequested, m_worker, &BackendWorker::armCalibrateZero); + connect(this, &RobotClient::enterTeachingModeRequested, + m_worker, &BackendWorker::enterTeachingMode); + connect(this, &RobotClient::startTrajectoryRecordingRequested, + m_worker, &BackendWorker::startTrajectoryRecording); + connect(this, &RobotClient::completeTeachingRequested, + m_worker, &BackendWorker::completeTeaching); + connect(this, &RobotClient::stopTrajectoryRecordingRequested, + m_worker, &BackendWorker::stopTrajectoryRecording); + connect(this, &RobotClient::exitTeachingModeRequested, + m_worker, &BackendWorker::exitTeachingMode); connect(this, &RobotClient::snapshotRequested, m_worker, &BackendWorker::snapshot); connect(this, &RobotClient::handEyeImageRequested, m_worker, [this](const QString& camera,quint64 token) { m_worker->getHandEyeImage(camera,token); }); connect(this,&RobotClient::cameraCapabilitiesRequested,m_worker,&BackendWorker::getCameraCapabilities); @@ -4897,6 +5122,29 @@ void RobotClient::requestArmCalibrateZero(const QString &deviceId, const QString emit armCommandStarting(deviceId); emit armCalibrateZeroRequested(deviceId, jointName); } +void RobotClient::requestEnterTeachingMode(const QString &deviceId) +{ + emit armCommandStarting(deviceId); + emit enterTeachingModeRequested(deviceId); +} +void RobotClient::requestStartTrajectoryRecording(const QString &deviceId, + const QString &fileName) +{ + emit armCommandStarting(deviceId); + emit startTrajectoryRecordingRequested(deviceId, fileName); +} +void RobotClient::requestCompleteTeaching(const QString &deviceId) +{ + emit completeTeachingRequested(deviceId); +} +void RobotClient::requestStopTrajectoryRecording(const QString &deviceId) +{ + emit stopTrajectoryRecordingRequested(deviceId); +} +void RobotClient::requestExitTeachingMode(const QString &deviceId) +{ + emit exitTeachingModeRequested(deviceId); +} void RobotClient::requestSnapshot(const QString &cameraId) { emit snapshotRequested(cameraId); } void RobotClient::requestTouchRgbdImage(const QString &cameraId, quint64 token) { diff --git a/src/robotclient.h b/src/robotclient.h index b1bde67..a61b7b0 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -55,6 +55,11 @@ public slots: void requestArmStop(const QString &deviceId); void requestArmClearFault(const QString &deviceId); void requestArmCalibrateZero(const QString &deviceId, const QString &jointName); + void requestEnterTeachingMode(const QString &deviceId); + void requestStartTrajectoryRecording(const QString &deviceId, const QString &fileName); + void requestCompleteTeaching(const QString &deviceId); + void requestStopTrajectoryRecording(const QString &deviceId); + void requestExitTeachingMode(const QString &deviceId); void requestSnapshot(const QString &cameraId); void requestHandEyeImage(const QString &cameraId, quint64 token); void requestTouchRgbdImage(const QString &cameraId, quint64 token); @@ -148,6 +153,11 @@ signals: void armStopRequested(const QString &deviceId); void armClearFaultRequested(const QString &deviceId); void armCalibrateZeroRequested(const QString &deviceId, const QString &jointName); + void enterTeachingModeRequested(const QString &deviceId); + void startTrajectoryRecordingRequested(const QString &deviceId, const QString &fileName); + void completeTeachingRequested(const QString &deviceId); + void stopTrajectoryRecordingRequested(const QString &deviceId); + void exitTeachingModeRequested(const QString &deviceId); void snapshotRequested(const QString &cameraId); void handEyeImageRequested(const QString &cameraId, quint64 token); void touchRgbdImageRequested(const QString &cameraId, quint64 token); diff --git a/tests/application_shell_test.cpp b/tests/application_shell_test.cpp index 10fe721..813a936 100644 --- a/tests/application_shell_test.cpp +++ b/tests/application_shell_test.cpp @@ -6,6 +6,7 @@ #include "bioheadwidget.h" #include "robotclient.h" #include "motordebugwidget.h" +#include "motorplot.h" #include #include #include @@ -27,6 +28,8 @@ #include #include #include +#include +#include #include #include #include @@ -58,7 +61,7 @@ static bool waitFor(const std::function &ready, int timeout=4000) struct MotorDebugTestAccess { static bool verify(){ RobotClient c;QObject::disconnect(&c,&RobotClient::motorRpcRequested,nullptr,nullptr); - MotorDebugWidget w(&c);w.resize(1450,1000);w.show(); + MotorDebugWidget w(&c);w.resize(1450,1060);w.show(); quint64 token=0;QString method;QVariantMap parameters;int requests=0; QObject::connect(&c,&RobotClient::motorRpcRequested,&w,[&](const QString &m,const QString&,int node,const QVariantMap& p,quint64 t){ method=m;token=t;parameters=p;++requests;if(node!=0)qFatal("unexpected node"); @@ -67,54 +70,162 @@ struct MotorDebugTestAccess { if(method!="ListMotors")return false; const QVariantMap motor{{"nodeId",0},{"jointName","test_J0"},{"driver","TchlMotor"},{"limitQLb",-1.0},{"limitQUb",1.0},{"limitQd",1.0},{"limitQdd",2.0}}; c.motorRpcFinished(token,"ListMotors",true,{{"motors",QVariantList{motor}}},""); - if(w.m_rpcButtons.size()!=23||w.findChild("motorDebugUnlock"))return false; - const QStringList modeNames={QStringLiteral("未指定"),QStringLiteral("轮廓位置"),QStringLiteral("速度"),QStringLiteral("轮廓速度"),QStringLiteral("轮廓力矩"),QStringLiteral("回零"),QStringLiteral("位置插补"),QStringLiteral("周期位置"),QStringLiteral("周期速度"),QStringLiteral("周期力矩")}; - const QList modeValues={0,1,2,3,4,5,7,8,9,10}; - if(w.m_mode->count()!=modeNames.size())return false; - for(int i=0;iitemText(i)!=modeNames[i]||w.m_mode->itemData(i).toInt()!=modeValues[i])return false; + if(w.m_info->text().contains("test_J0")||w.m_info->text().contains("TchlMotor")||w.m_info->text().contains("ID"))return false; + for(const auto &caption:QStringList{QStringLiteral("位置下限"),QStringLiteral("位置上限"),QStringLiteral("速度上限"),QStringLiteral("加速度上限"),QStringLiteral("服务端缓存")}) + if(!w.m_info->text().contains(caption))return false; + if(w.m_rpcButtons.size()!=17||w.findChild("motorDebugUnlock"))return false; + if(w.m_rate->maximum()<=1000||w.m_timer->timerType()!=Qt::PreciseTimer)return false; + w.m_rate->setValue(200);if(w.m_timer->interval()!=5)return false; + w.m_rate->setValue(1000);if(w.m_timer->interval()!=1)return false; + w.m_rate->setValue(20); + for(auto *label:w.findChildren())if(label->text()==QStringLiteral("运动指令"))return false; + const QStringList names={QStringLiteral("轮廓位置"),QStringLiteral("轮廓速度"),QStringLiteral("轮廓力矩"),QStringLiteral("周期位置"),QStringLiteral("周期速度"),QStringLiteral("周期力矩")}; + const QList modes={1,3,4,8,9,10}; + const QStringList methods={"commandProfilePosition","commandProfileVelocity","commandProfileTorque","commandCyclicPosition","commandCyclicVelocity","commandCyclicTorque"}; + const QList fields={QStringList{"q","qd","qdd"},QStringList{"qd","qdd"},QStringList{"tau"}, + QStringList{"q","qd"},QStringList{"qd"},QStringList{"tau"}}; + if(w.m_mode->count()!=6||w.m_limitParameters.size()!=5)return false; + w.m_parameters["q"]->setValue(2.5);w.m_parameters["qd"]->setValue(-0.2);w.m_parameters["qdd"]->setValue(0.4); + w.m_parameters["tau"]->setValue(12.5);w.m_slope->setValue(150); + for(int i=0;iitemText(i)!=names[i]||w.m_mode->itemData(i).toInt()!=modes[i])return false; + w.m_mode->setCurrentIndex(i); + if(requests!=before)return false; // Choosing a mode must not issue control RPCs. + for(auto it=w.m_parameters.begin();it!=w.m_parameters.end();++it) + if(it.value()->isHidden()==fields[i].contains(it.key())||w.m_parameterLabels[it.key()]->isHidden()==fields[i].contains(it.key())||w.m_parameterRows[it.key()]->isHidden()==fields[i].contains(it.key()))return false; + if(w.m_slope->isHidden()!=(modes[i]!=4)||w.m_slopeLabel->isHidden()!=(modes[i]!=4))return false; + w.m_rpcButtons["setMode"]->click(); + if(method!="setMode"||requests!=before+1||parameters!=QVariantMap{{"mode",modes[i]}})return false; + c.motorRpcFinished(token,method,true,{},"mode set"); + w.m_sendMotion->click(); + if(method!=methods[i]||requests!=before+2||QApplication::activeModalWidget())return false; + QVariantMap expected{{"mode",modes[i]}}; + for(const auto &field:fields[i])expected.insert(field,w.m_parameters[field]->value()); + if(modes[i]==4)expected.insert("torqueSlope",150); + if(parameters!=expected)return false; + c.motorRpcFinished(token,method,true,{},"mock result"); + QApplication::processEvents(); + if(i==0||i==2||i==3)w.grab().save(QString("motor-mode-%1.png").arg(modes[i])); + } for(auto *input:w.findChildren()){ if(input->buttonSymbols()!=QAbstractSpinBox::NoButtons)return false; input->setFocus();const QString original=input->text(); - for(int delta:{120,-120}){ - QWheelEvent wheel(QPointF(5,5),QPointF(input->mapToGlobal(QPoint(5,5))),QPoint(),QPoint(0,delta),Qt::NoButton,Qt::NoModifier,Qt::NoScrollPhase,false); - QApplication::sendEvent(input,&wheel); - if(input->text()!=original)return false; - } + QWheelEvent wheel(QPointF(5,5),QPointF(input->mapToGlobal(QPoint(5,5))),QPoint(),QPoint(0,120),Qt::NoButton,Qt::NoModifier,Qt::NoScrollPhase,false); + QApplication::sendEvent(input,&wheel); + if(input->text()!=original)return false; } w.m_parameters["q"]->findChild()->setText("0.125");w.m_parameters["q"]->interpretText(); if(w.m_parameters["q"]->value()!=0.125)return false; - w.m_parameters["q"]->setValue(2.5);w.m_parameters["qd"]->setValue(-0.2);w.m_parameters["qdd"]->setValue(0.4); - w.m_parameters["tau"]->setValue(12.5);w.m_slope->setValue(150);w.m_mode->setCurrentIndex(w.m_mode->findData(0)); - const auto methods=w.m_rpcButtons.keys(); - for(const QString& m:methods){ - const int before=requests;w.m_rpcButtons[m]->click(); - if(requests!=before+1||method!=m||QApplication::activeModalWidget()||parameters.contains("planMotion")||parameters.contains("confirmDebug"))return false; - if(m=="ListMotors")c.motorRpcFinished(token,m,true,{{"motors",QVariantList{motor}}},""); - else { - if(parameters.value("q").toDouble()!=2.5||parameters.value("mode").toInt()!=0)return false; - c.motorRpcFinished(token,m,true,{{"info",motor},{"state",QVariantMap{{"sampledAtS",1.0},{"feedbackValid",false}}}},"mock result"); - } + w.m_parameters["q"]->setValue(2.5); + w.m_limitParameters["qLower"]->setValue(-2);w.m_limitParameters["qUpper"]->setValue(3); + w.m_limitParameters["qd"]->setValue(4);w.m_limitParameters["qddLower"]->setValue(-5);w.m_limitParameters["qddUpper"]->setValue(6); + for(const QString &rpc:QStringList{"setLimitQ","setLimitQd","setLimitQdd"}){ + w.m_rpcButtons[rpc]->click(); + const QVariantMap expected=rpc=="setLimitQ"?QVariantMap{{"mode",10},{"lower",-2.0},{"upper",3.0}}: + rpc=="setLimitQd"?QVariantMap{{"mode",10},{"qd",4.0}}:QVariantMap{{"mode",10},{"lower",-5.0},{"upper",6.0}}; + if(method!=rpc||parameters!=expected)return false; + c.motorRpcFinished(token,rpc,true,{},"mock result"); + } + for(const QString &rpc:w.m_rpcButtons.keys()){ + const int before=requests;w.m_rpcButtons[rpc]->click(); + if(requests!=before+1||method!=rpc||QApplication::activeModalWidget()||parameters.contains("planMotion")||parameters.contains("confirmDebug"))return false; + if(rpc=="ListMotors")c.motorRpcFinished(token,rpc,true,{{"motors",QVariantList{motor}}},""); + else c.motorRpcFinished(token,rpc,true,{{"info",motor}},"mock result"); } - // Deliberate clicks directly queue their API, not a hidden GetState. w.invoke("GetState");const quint64 oldRead=token;const int before=requests; w.m_rpcButtons["torqueOn"]->click();if(method!="torqueOn"||requests!=before+1)return false; c.motorRpcFinished(oldRead,"GetState",true,{},"stale");if(!w.m_inFlight)return false; c.motorRpcFinished(token,"torqueOn",false,{},"server error"); if(!w.m_rpcButtons["setMode"]->isEnabled())return false; struct Changes:QObject{int count=0;bool eventFilter(QObject*,QEvent*e)override{if(e->type()==QEvent::EnabledChange)++count;return false;}} changes; - const QList controls={w.m_manager,w.m_motor,w.m_mode,w.m_parameters["q"],w.m_rpcButtons["torqueOn"]}; + const QList controls={w.m_manager,w.m_motor,w.m_mode,w.m_parameters["q"],w.m_rpcButtons["torqueOn"],w.m_sendMotion}; for(auto *control:controls)control->installEventFilter(&changes); w.clearSamples(); for(int i=0;i<120;++i){ - w.invoke("GetState");const QVariantMap s{{"sampledAtS",1000.0+i*0.05},{"feedbackValid",true},{"torqueValid",true}, - {"position",0.2*std::sin(i*0.1)},{"velocity",i*0.05},{"torque",20.0*std::sin(i*0.1)},{"mode",0},{"statusValid",true},{"enabled",false},{"statusWord",0x40}}; - c.motorRpcFinished(token,"GetState",true,{{"state",s}},""); - if(i==0&&std::isfinite(w.accelerationEstimate()))return false; + w.invoke("GetState");const QVariantMap state{{"sampledAtS",1000.0+i*0.05},{"feedbackValid",true},{"torqueValid",true}, + {"position",0.2*std::sin(i*0.1)},{"velocity",i*0.05},{"torque",20.0*std::sin(i*0.1)},{"mode",3},{"statusValid",true},{"enabled",false},{"statusWord",0x40}}; + c.motorRpcFinished(token,"GetState",true,{{"state",state}},""); + if(i<2&&std::isfinite(w.accelerationEstimate()))return false; } if(changes.count||std::abs(w.accelerationEstimate()-1)>1e-6)return false; for(auto *control:controls)control->removeEventFilter(&changes); - QApplication::processEvents();w.grab().save("motor-debug-direct.png"); + w.m_plot->setWindow(5); + QApplication::processEvents(); + // Each plot zooms independently in both axes and restores with right click. + for(int channel=0;channel<4;++channel){ + const auto old=w.m_plot->rangeFor(channel);const QPointF p=w.m_plot->plotRect(channel).center(); + QWheelEvent wheel(p,QPointF(w.m_plot->mapToGlobal(p.toPoint())),QPoint(),QPoint(0,120),Qt::NoButton,Qt::NoModifier,Qt::NoScrollPhase,false); + QApplication::sendEvent(w.m_plot,&wheel); + const auto zoom=w.m_plot->rangeFor(channel); + if(!w.m_plot->m_views[channel].manual||zoom.right-zoom.left>=old.right-old.left||zoom.top-zoom.bottom>=old.top-old.bottom)return false; + for(int other=channel+1;other<4;++other)if(w.m_plot->m_views[other].manual)return false; + } + for(int channel=0;channel<4;++channel){ + const auto p=w.m_plot->plotRect(channel).center(); + QMouseEvent click(QEvent::MouseButtonPress,p,Qt::RightButton,Qt::RightButton,Qt::NoModifier); + QApplication::sendEvent(w.m_plot,&click); + if(w.m_plot->m_views[channel].manual)return false; + for(int other=channel+1;other<4;++other)if(!w.m_plot->m_views[other].manual)return false; + } + w.m_mode->setCurrentIndex(1); + for(int channel=0;channel<4;++channel){ + const int expected=100;const auto range=w.m_plot->rangeFor(channel);const auto rect=w.m_plot->plotRect(channel); + const QPointF p(rect.left()+(w.m_plot->samples[expected].t-w.m_plot->samples.last().t-range.left)/(range.right-range.left)*rect.width(),rect.center().y()); + QMouseEvent move(QEvent::MouseMove,p,Qt::NoButton,Qt::NoButton,Qt::NoModifier); + QApplication::sendEvent(w.m_plot,&move); + int index=-1;QPointF point; + if(!w.m_plot->hoverSample(index,point)||index!=expected||!std::isfinite(MotorPlot::value(w.m_plot->samples[index],channel)))return false; + } + QApplication::processEvents();w.grab().save("motor-debug-interactive.png"); + auto *scroll=w.findChild("motorControlScroll"); + scroll->verticalScrollBar()->setValue(scroll->verticalScrollBar()->maximum()); + QApplication::processEvents();w.grab().save("motor-limits-panel.png"); + if(w.m_limitParameters["qLower"]->parentWidget()==w.m_parameters["q"]->parentWidget())return false; + // Window fitting reduces jitter without assuming the requested polling rate. + MotorPlot fit; + double time=0,oldVelocity=0,oldTime=0,fitError=0,rawError=0; + int compared=0; + for(int i=0;i<120;++i){ + time+=0.035+0.005*(i%3); + const double velocity=2*time+(i%2?0.006:-0.006); + fit.append({{"sampledAtS",time},{"feedbackValid",true},{"position",time*time},{"velocity",velocity}}); + if(i>10){ + const double raw=(velocity-oldVelocity)/(time-oldTime); + fitError+=std::pow(fit.samples.last().qdd-2,2);rawError+=std::pow(raw-2,2);++compared; + } + oldTime=time;oldVelocity=velocity; + } + if(!compared||!std::isfinite(fitError)||fitError>=rawError*0.5)return false; + const int count=fit.samples.size(); + fit.append({{"sampledAtS",time},{"feedbackValid",true},{"velocity",1e9}}); + if(fit.samples.size()!=count)return false; + time+=0.04;fit.append({{"sampledAtS",time},{"feedbackValid",false}}); + time+=0.04;fit.append({{"sampledAtS",time},{"feedbackValid",true},{"velocity",1.0}}); + if(std::isfinite(fit.samples.last().qdd))return false; + time+=2;fit.append({{"sampledAtS",time},{"feedbackValid",true},{"velocity",100.0}}); + if(std::isfinite(fit.samples.last().qdd))return false; + fit.append({{"sampledAtS",1.0},{"feedbackValid",true},{"velocity",0.0}}); + if(fit.samples.size()!=1||std::isfinite(fit.samples.last().qdd))return false; + fit.clear(); + for(int i=0;i<8;++i)fit.append({{"sampledAtS",100.0+i*1.01},{"feedbackValid",true},{"velocity",i*2.02}}); + if(!std::isfinite(fit.samples.last().qdd)||std::abs(fit.samples.last().qdd-2)>1e-6)return false; + // Continuous valid high-rate feedback must not create artificial gaps. + for(double rate:{100.0,200.0,300.0,400.0,1000.0}){ + fit.clear();double actualTime=1000; + for(int i=0;i<1000;++i){ + actualTime+=1.0/rate; + fit.append({{"sampledAtS",actualTime},{"feedbackValid",true},{"velocity",2*(actualTime-1000)}}); + if(actualTime-1000>0.05&&(!std::isfinite(fit.samples.last().qdd)||std::abs(fit.samples.last().qdd-2)>1e-6))return false; + } + } + fit.clear();double actualTime=1000; + const double burstIntervals[]={0.001,0.002,0.002,0.002,0.002,0.012,0.001,0.001,0.002,0.002}; + for(int i=0;i<1000;++i){ + actualTime+=burstIntervals[i%10]; + fit.append({{"sampledAtS",actualTime},{"feedbackValid",true},{"velocity",2*(actualTime-1000)}}); + if(actualTime-1000>0.05&&(!std::isfinite(fit.samples.last().qdd)||std::abs(fit.samples.last().qdd-2)>1e-6))return false; + } const QString feedback=w.m_values->text();w.m_acquire->setChecked(true);w.invoke("setMode"); c.motorRpcFinished(token,"setMode",false,{},"driver rejected mode"); if(!w.m_acquire->isChecked()||w.m_values->text()!=feedback)return false; @@ -122,7 +233,7 @@ struct MotorDebugTestAccess { if(std::isfinite(w.accelerationEstimate()))return false; const int beforeHide=requests;w.hide();if(w.m_acquire->isChecked()||requests!=beforeHide)return false; QFile f("motor-debug-ui-test.txt");f.open(QIODevice::WriteOnly); - f.write("PASS: all 23 RPC buttons, direct dispatch without preflight/dialogs/planning, unchanged parameters, stable controls, acceleration estimate, failure preservation, hide without writes\n"); + f.write("PASS: six modes and visible parameters, 23 direct APIs, independent limits, keyboard-only numeric inputs, stable sampling, hover values, independent zoom/reset, timestamp-based acceleration fitting and gap handling\n"); return true; } }; diff --git a/tests/armcompatibility_test.cpp b/tests/armcompatibility_test.cpp new file mode 100644 index 0000000..5b50fc9 --- /dev/null +++ b/tests/armcompatibility_test.cpp @@ -0,0 +1,378 @@ +#include "robotclient.h" +#include "mainwindow.h" +#include "applicationstyle.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cmvr/api/arm_service.grpc.pb.h" +#include "cmvr/api/system_service.grpc.pb.h" + +static bool waitFor(const std::function &ready, int timeout = 7000) +{ + QElapsedTimer timer; timer.start(); + while (!ready() && timer.elapsed() < timeout) { + QCoreApplication::processEvents(QEventLoop::AllEvents, 10); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + return ready(); +} + +static void pumpEvents(int milliseconds) +{ + QElapsedTimer timer; timer.start(); + while (timer.elapsed() < milliseconds) { + QCoreApplication::processEvents(QEventLoop::AllEvents, 10); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } +} + +class System final : public cmvr::api::SystemService::Service { + grpc::Status GetSystemInfo(grpc::ServerContext*, const cmvr::api::GetSystemInfoCommand::Request*, + cmvr::api::GetSystemInfoCommand::Feedback *r) override { + r->mutable_header()->set_success(true); return grpc::Status::OK; + } + grpc::Status GetSystemStatus(grpc::ServerContext*, const cmvr::api::GetSystemStatusCommand::Request*, + cmvr::api::GetSystemStatusCommand::Feedback *r) override { + r->mutable_header()->set_success(true); + r->add_device_list()->set_device_id("tchl_arm"); // Legacy default enum zero is AGV. + r->add_device_list()->set_device_id("real_agv"); + auto *motor = r->add_device_list(); motor->set_device_id("tchl_joint_motors"); + motor->set_device_type(cmvr::api::MotorSystem); + return grpc::Status::OK; + } +}; + +class Arm final : public cmvr::api::ArmService::Service { +public: + bool modern = false; + std::atomic stateCalls{0}, jointCalls{0}, controlCalls{0}, agvProbes{0}, frameCalls{0}; + std::atomic teachingCalls{0}; + std::atomic rejectTeaching{false}; + std::string recordedFile; + grpc::Status teaching(const cmvr::api::CommandHeader::Request *q, + cmvr::api::CommandHeader::Feedback *r) { + ++teachingCalls; + if (q->device_id() != "tchl_arm") return {grpc::StatusCode::NOT_FOUND, "unknown arm"}; + r->set_success(!rejectTeaching); + if (rejectTeaching) r->set_error_message("controller rejected teaching"); + return grpc::Status::OK; + } + grpc::Status EnterTeachingMode(grpc::ServerContext*, const cmvr::api::CommandHeader::Request *q, + cmvr::api::CommandHeader::Feedback *r) override { return teaching(q, r); } + grpc::Status CompleteTeaching(grpc::ServerContext*, const cmvr::api::CommandHeader::Request *q, + cmvr::api::CommandHeader::Feedback *r) override { return teaching(q, r); } + grpc::Status StopTrajectoryRecording(grpc::ServerContext*, const cmvr::api::CommandHeader::Request *q, + cmvr::api::CommandHeader::Feedback *r) override { return teaching(q, r); } + grpc::Status ExitTeachingMode(grpc::ServerContext*, const cmvr::api::CommandHeader::Request *q, + cmvr::api::CommandHeader::Feedback *r) override { return teaching(q, r); } + grpc::Status StartTrajectoryRecording(grpc::ServerContext*, const cmvr::api::StartTrajectoryRecording::Request *q, + cmvr::api::StartTrajectoryRecording::Response *r) override { + recordedFile = q->file_name(); + return teaching(&q->header(), r->mutable_header()); + } + grpc::Status GetArmInfo(grpc::ServerContext*, const cmvr::api::GetArmInfo::Request *q, + cmvr::api::GetArmInfo::Response *r) override { + if (!modern) return {grpc::StatusCode::UNIMPLEMENTED, "legacy"}; + r->mutable_header()->set_success(true); r->set_device_id(q->header().device_id()); + r->set_manufacturer("test"); r->set_model("modern_arm"); r->set_dof(6); + r->set_default_base_frame("base"); r->set_default_tcp_frame("tool0"); + for (int i = 1; i <= 6; ++i) r->add_joint_names("TCHL_AXIS_" + std::to_string(i)); + return grpc::Status::OK; + } + grpc::Status getJointState(grpc::ServerContext*, const cmvr::api::JointRequest *q, + cmvr::api::JointResponse *r) override { + ++jointCalls; + if (q->header().device_id() != "tchl_arm") { + ++agvProbes; return {grpc::StatusCode::NOT_FOUND, "not an arm"}; + } + r->mutable_header()->set_success(true); + for (int i = 1; i <= 6; ++i) { + r->mutable_state()->add_name("TCHL_AXIS_" + std::to_string(i)); + r->mutable_state()->add_position(i * 0.1); + r->mutable_state()->add_velocity(i * -0.001); + r->mutable_state()->add_effort(0); + } + return grpc::Status::OK; + } + grpc::Status getRobotState(grpc::ServerContext*, const cmvr::api::GetRobotState::Request*, + cmvr::api::GetRobotState::Response *r) override { + ++stateCalls; + if (!modern) return {grpc::StatusCode::UNIMPLEMENTED, "legacy"}; + r->mutable_header()->set_success(true); + auto *state = r->mutable_state(); state->set_connected(true); state->set_powered_on(true); + state->set_robot_mode(cmvr::api::ARM_ROBOT_MODE_IDLE); + state->set_safety_mode(cmvr::api::ARM_SAFETY_MODE_NORMAL); + for (int i = 1; i <= 6; ++i) { + state->mutable_actual_joint_state()->add_name("TCHL_AXIS_" + std::to_string(i)); + state->mutable_actual_joint_state()->add_position(i * 0.2); + state->mutable_actual_joint_state()->add_velocity(0); + } + return grpc::Status::OK; + } + grpc::Status moveJ(grpc::ServerContext*, const cmvr::api::MoveJ::Request*, cmvr::api::MoveJ::Response*) override { + ++controlCalls; return {grpc::StatusCode::PERMISSION_DENIED, "test prohibits motion"}; + } + grpc::Status ListBaseFrame(grpc::ServerContext*, const cmvr::api::ListFrame::Request*, cmvr::api::ListFrame::Response*) override { + ++frameCalls; return {grpc::StatusCode::UNIMPLEMENTED, "frameGetChildren must not be invoked"}; + } + grpc::Status ListTCPFrame(grpc::ServerContext*, const cmvr::api::ListFrame::Request*, cmvr::api::ListFrame::Response*) override { + ++frameCalls; return {grpc::StatusCode::UNIMPLEMENTED, "frameGetChildren must not be invoked"}; + } +}; + +struct JointPointTestAccess { + static bool verifyTeaching(const QString &host, int port, Arm &mock) { + MainWindow window; + window.m_demoCheck->setChecked(false); + window.selectPage(1); + QString command; + bool success = false; + int results = 0; + QObject::connect(window.m_client, &RobotClient::commandFinished, &window, + [&](const QString &name, bool ok, const QString&) { command = name; success = ok; ++results; }); + window.m_client->connectToServer(host, port, false); + if (!waitFor([&] { return window.m_connected && window.m_armIdEdit->text() == "tchl_arm"; })) return false; + const auto click = [&](QPushButton *button, const char *expected, bool expectedSuccess) { + const int previous = results; + button->click(); + return waitFor([&] { return results > previous; }) && command == expected && success == expectedSuccess; + }; + // Empty file names must not reach the controller. + window.m_trajectoryFileNameEdit->clear(); + if (!click(window.m_startTrajectoryRecordingButton, "Start Trajectory Recording", false) + || mock.teachingCalls != 0) return false; + window.m_trajectoryFileNameEdit->setText(" test_teaching.traj "); + if (!click(window.m_enterTeachingButton, "Enter Teaching Mode", true) + || !click(window.m_startTrajectoryRecordingButton, "Start Trajectory Recording", true) + || mock.recordedFile != "test_teaching.traj" + || !click(window.m_stopTrajectoryRecordingButton, "Stop Trajectory Recording", true) + || !click(window.m_exitTeachingButton, "Exit Teaching Mode", true) + || !click(window.m_completeTeachingButton, "Complete Teaching", true) + || mock.teachingCalls != 5) return false; + mock.rejectTeaching = true; + if (!click(window.m_enterTeachingButton, "Enter Teaching Mode", false) + || window.m_deviceTeachingStateLabel->text() != QStringLiteral("进入示教失败")) return false; + window.m_client->disconnectFromServer(); + pumpEvents(100); + fprintf(stderr, "PASS five teaching buttons, filename validation and controller error feedback\n"); + return true; + } + static bool verifyManualTelemetry(const QString &host, int port, const QString &deviceId, + Arm *mock = nullptr, bool allowPower = false) { + MainWindow window; + window.m_demoCheck->setChecked(false); + window.m_hostEdit->setText(host); + window.m_portSpin->setValue(port); + window.selectPage(1); + int samples = 0, powerResults = 0; + bool powerSuccess = false; + QVariantMap lastState; + QObject::connect(window.m_client, &RobotClient::telemetryReceived, &window, + [&](const QString &id, const QVariantList&, const QVariantMap&, const QVariantMap &state) { + if (id == deviceId) { ++samples; lastState = state; } + }); + QObject::connect(window.m_client, &RobotClient::commandFinished, &window, + [&](const QString &command, bool ok, const QString &detail) { + if (command == "Torque On") { ++powerResults; powerSuccess = ok; } + if (!ok || command == "Torque On") + fprintf(stderr, "UI command %s ok=%d %s\n", command.toUtf8().constData(), ok, detail.toUtf8().constData()); + }); + window.m_client->connectToServer(host, port, false); + if (!waitFor([&] { return window.m_connected && window.m_armIdEdit->text() == deviceId + && window.m_activeArmJointNames.size() == 6; }, 10000)) { + fprintf(stderr, "FAIL UI connection or arm metadata\n"); return false; + } + pumpEvents(1300); + if (window.m_armTelemetryButton->isChecked() || samples || (mock && mock->stateCalls)) { + fprintf(stderr, "FAIL automatic telemetry on connection\n"); return false; + } + window.selectPage(0); window.selectPage(1); + window.m_jogModeTabs->setCurrentIndex(1); + window.m_client->requestArmFrames(deviceId); // Compatibility API must be cache-only. + pumpEvents(1300); + if (window.m_armTelemetryButton->isChecked() || samples || (mock && mock->frameCalls)) { + fprintf(stderr, "FAIL automatic page telemetry or frame RPC\n"); return false; + } + fprintf(stderr, "PASS UI enters arm page without telemetry or frame enumeration\n"); + if (allowPower) { + window.m_torqueOnButton->click(); + if (!waitFor([&] { return powerResults > 0; }, 40000) || !powerSuccess) { + fprintf(stderr, "FAIL power-on/enable result; not retrying\n"); return false; + } + } + window.m_armTelemetryButton->click(); + if (!waitFor([&] { return samples >= 4 && window.m_latestArmJointPositions.size() == 6; }, 10000)) { + fprintf(stderr, "FAIL manual telemetry samples=%d\n", samples); return false; + } + fprintf(stderr, "PASS UI manual telemetry received %d samples, robotMode=%d poweredOn=%d fault=%d\n", + samples, lastState.value("robotMode").toInt(), lastState.value("poweredOn").toBool(), + lastState.value("fault").toBool()); + if (allowPower && (!lastState.value("poweredOn").toBool() + || !lastState.value("brakeReleased").toBool() || lastState.value("fault").toBool())) { + fprintf(stderr, "FAIL controller did not confirm enabled state\n"); return false; + } + window.m_armTelemetryButton->click(); + pumpEvents(500); + const int stoppedSamples = samples; + pumpEvents(1300); + if (samples != stoppedSamples || window.m_armTelemetryButton->isChecked()) { + fprintf(stderr, "FAIL telemetry restarted after manual stop\n"); return false; + } + if (mock && (mock->frameCalls || mock->controlCalls)) return false; + fprintf(stderr, "PASS UI manual stop stays stopped across device refresh\n"); + window.m_client->disconnectFromServer(); + pumpEvents(100); + return true; + } + static bool verifyUnknownState(const QVariantList &joints) { + MainWindow window; + window.m_armIdEdit->setText("tchl_arm"); + QStringList names; + for (const auto &v : joints) names << v.toMap().value("name").toString(); + window.updateArmInfo("tchl_arm", {{"source", "getJointState"}, {"jointNames", names}, {"dof", 6}}); + QVariantMap controllerState{{"connected", true}, {"poweredOn", true}, + {"brakeReleased", false}, {"robotMode", 3}}; + window.updateTelemetry("tchl_arm", joints, {}, controllerState); + if (window.m_servoStatusValue->text() != QStringLiteral("已上电 · 未使能")) return false; + controllerState["brakeReleased"] = true; + window.updateTelemetry("tchl_arm", joints, {}, controllerState); + if (window.m_servoStatusValue->text() != QStringLiteral("已使能 · 空闲")) return false; + controllerState["poweredOn"] = false; + controllerState["brakeReleased"] = false; + window.updateTelemetry("tchl_arm", joints, {}, controllerState); + if (window.m_servoStatusValue->text() != QStringLiteral("未使能")) return false; + window.m_servoStatusValue->setText(QStringLiteral("已使能")); + window.m_faultStatusValue->setText(QStringLiteral("正常")); + window.updateTelemetry("tchl_arm", joints, {}, {{"robotStateAvailable", false}}); + return window.m_jointTable->rowCount() == 6 + && window.m_motionTable->rowCount() == 6 + && window.m_jointTable->item(0, 0)->text() == "TCHL_AXIS_1" + && window.m_servoStatusValue->text() == QStringLiteral("服务端未提供") + && window.m_faultStatusValue->text() == QStringLiteral("服务端未提供") + && window.m_armDeviceSummary->text().contains(QStringLiteral("6轴")) + && window.m_latestArmPose.isEmpty(); + } +}; + +static bool verifyClient(const QString &host, int port, bool legacy, bool live, Arm *mock) +{ + RobotClient client; + bool connected = false, infoReady = false; + QVariantList devices, joints; + QVariantMap info, state, pose; + int telemetry = 0; + QObject::connect(&client, &RobotClient::connectionChanged, &client, + [&](bool value, int, const QString &detail) { + connected = value; + fprintf(stderr, "connection=%d %s\n", value, detail.toUtf8().constData()); + }); + QObject::connect(&client, &RobotClient::systemStatusReceived, &client, + [&](double, double, double, const QVariantList &value) { devices = value; }); + QObject::connect(&client, &RobotClient::armInfoReceived, &client, + [&](const QString &id, const QVariantMap &value) { if (id == "tchl_arm") { info = value; infoReady = true; } }); + QObject::connect(&client, &RobotClient::telemetryReceived, &client, + [&](const QString &id, const QVariantList &j, const QVariantMap &p, const QVariantMap &s) { + if (id == "tchl_arm") { ++telemetry; joints = j; pose = p; state = s; } + }); + client.connectToServer(host, port, false); + if (!waitFor([&] { return connected; })) { fprintf(stderr, "FAIL connect\n"); return false; } + client.requestSystemRefresh(); + if (!waitFor([&] { return !devices.isEmpty(); })) { fprintf(stderr, "FAIL system discovery\n"); return false; } + bool found = false; + for (const auto &value : devices) { + auto item = value.toMap(); + if (item.value("deviceId") == "tchl_arm") found = item.value("type").toInt() == cmvr::api::Robot; + if (item.value("deviceId") == "real_agv" && item.value("type").toInt() != cmvr::api::AGV) return false; + } + if (!found) { fprintf(stderr, "FAIL arm not identified\n"); return false; } + client.requestArmInfo("tchl_arm"); + client.setArmTelemetry("tchl_arm", true); + if (!waitFor([&] { return infoReady && telemetry >= 4; })) { + fprintf(stderr, "FAIL info=%d telemetry=%d\n", infoReady, telemetry); return false; + } + const QStringList names = info.value("jointNames").toStringList(); + if (names.size() != 6 || names.front() != "TCHL_AXIS_1" || joints.size() != 6) return false; + if (legacy) { + if (info.value("source") != "getJointState" || !info.value("manufacturer").toString().isEmpty() + || state.value("robotStateAvailable", true).toBool() || state.contains("poweredOn") || !pose.isEmpty()) return false; + if (!live && (mock->stateCalls != 1 || mock->agvProbes != 1)) return false; + if (!JointPointTestAccess::verifyUnknownState(joints)) return false; + } else if (info.value("model") != "modern_arm" || !state.value("poweredOn").toBool()) return false; + if (!live && mock->controlCalls != 0) return false; + client.setArmTelemetry("tchl_arm", false); + client.disconnectFromServer(); + qInfo() << "PASS arm info, discovery, telemetry:" << (live ? host : legacy ? "legacy mock" : "modern mock") + << names << "positions" << joints; + fprintf(stderr, "PASS %s: six real joint names, info, telemetry and UI\n", + live ? "live" : legacy ? "legacy mock" : "modern mock"); + return true; +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + app.setOrganizationName("CMVR Tests"); app.setApplicationName("Arm Compatibility Test"); + ApplicationStyle::install(app); + if (app.arguments().contains("--live-204-teaching-contract")) { + auto channel = grpc::CreateChannel("192.168.0.204:50052", grpc::InsecureChannelCredentials()); + auto stub = cmvr::api::ArmService::NewStub(channel); + cmvr::api::CommandHeader::Request request; + request.set_device_id("__cmvr_teaching_probe_missing__"); + const auto probe = [&](const char *name, auto call) { + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3)); + cmvr::api::CommandHeader::Feedback response; + const auto status = call(&context, request, &response); + if (status.error_code() != grpc::StatusCode::NOT_FOUND || response.success()) return false; + fprintf(stderr, "PASS deployed %s exists and rejects unknown device without hardware access\n", name); + return true; + }; + if (!probe("EnterTeachingMode", [&](auto *c, const auto &q, auto *r) { return stub->EnterTeachingMode(c, q, r); }) + || !probe("CompleteTeaching", [&](auto *c, const auto &q, auto *r) { return stub->CompleteTeaching(c, q, r); }) + || !probe("StopTrajectoryRecording", [&](auto *c, const auto &q, auto *r) { return stub->StopTrajectoryRecording(c, q, r); }) + || !probe("ExitTeachingMode", [&](auto *c, const auto &q, auto *r) { return stub->ExitTeachingMode(c, q, r); })) return 6; + cmvr::api::StartTrajectoryRecording::Request recording; + *recording.mutable_header() = request; + recording.set_file_name("probe_not_created.traj"); + cmvr::api::StartTrajectoryRecording::Response response; + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3)); + const auto status = stub->StartTrajectoryRecording(&context, recording, &response); + if (status.error_code() != grpc::StatusCode::NOT_FOUND || response.header().success()) return 6; + fprintf(stderr, "PASS deployed StartTrajectoryRecording exists and rejects unknown device without hardware access\n"); + return 0; + } + if (app.arguments().contains("--live-204")) + return JointPointTestAccess::verifyManualTelemetry("192.168.0.204", 50052, "aubo_arm", nullptr, + app.arguments().contains("--allow-power")) ? 0 : 3; + if (app.arguments().contains("--live")) return verifyClient("192.168.0.234", 50052, true, true, nullptr) ? 0 : 1; + for (bool modern : {false, true}) { + System system; Arm arm; arm.modern = modern; + grpc::ServerBuilder builder; int port = 0; + builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port); + builder.RegisterService(&system); builder.RegisterService(&arm); + auto server = builder.BuildAndStart(); + if (!server || !verifyClient("127.0.0.1", port, !modern, false, &arm)) return 2; + if (modern) { + arm.stateCalls = 0; arm.frameCalls = 0; + if (!JointPointTestAccess::verifyManualTelemetry("127.0.0.1", port, "tchl_arm", &arm)) return 4; + if (!JointPointTestAccess::verifyTeaching("127.0.0.1", port, arm)) return 5; + } + server->Shutdown(); + } + return 0; +} diff --git a/tests/run_armcompatibility_test.py b/tests/run_armcompatibility_test.py new file mode 100644 index 0000000..c519f7e --- /dev/null +++ b/tests/run_armcompatibility_test.py @@ -0,0 +1,29 @@ +"""Link the compatibility regression against the existing Release objects.""" +import os +from pathlib import Path +import runpy +import subprocess +import sys + +root = Path(__file__).resolve().parents[1] +helpers = runpy.run_path(str(root / 'tests/run_theme_shell_test.py')) +args, value = helpers['args'], helpers['value'] +qt, toolchain = helpers['qt'], helpers['toolchain'] +env = dict(os.environ) +env['PATH'] = os.pathsep.join((str(toolchain), str(qt / 'bin'), str(root / 'bin/release'), env['PATH'])) +env['QT_QPA_PLATFORM'] = 'offscreen' +env['QT_QPA_FONTDIR'] = 'C:/Windows/Fonts' +output = root / 'build/armcompatibility-test' +output.mkdir(parents=True, exist_ok=True) +obj, binary = output / 'test.o', output / 'armcompatibility_test.exe' +flags = value('CXXFLAGS').replace('$(DEFINES)', value('DEFINES')) +subprocess.run([str(toolchain / 'g++.exe'), '-c', *args(flags), *args(value('INCPATH')), + '-I' + str(root / 'src'), str(root / 'tests/armcompatibility_test.cpp'), '-o', str(obj)], + cwd=root, env=env, check=True) +objects = (root / 'object_script.CmvrControlStation.Release').read_text().splitlines() +objects = [item for item in objects if not item.replace('\\', '/').endswith('/main.o')] +response = output / 'objects.rsp' +response.write_text('\n'.join(objects), encoding='utf-8') +subprocess.run([str(toolchain / 'g++.exe'), '-mthreads', '-o', str(binary), str(obj), + '@' + str(response), *args(value('LIBS'))], cwd=root, env=env, check=True) +subprocess.run([str(binary), *sys.argv[1:]], cwd=output, env=env, check=True, timeout=90) diff --git a/ui/armservicepage.ui b/ui/armservicepage.ui index 717c9f1..84baa2c 100644 --- a/ui/armservicepage.ui +++ b/ui/armservicepage.ui @@ -66,6 +66,12 @@ RZ --poseValue16 关节示教sectionTitle 拖动模型关节,确认后再发送到设备panelSubtitle + 设备拖动示教eyebrow + 控制器轨迹文件名(例如 demo.traj)true + 8进入示教退出示教 + 8记录轨迹primaryButton停止记录 + 完成示教 + 未进入示教mutedLabeltrue 8示教模式truefalse实际姿态false QFrame::HLineQFrame::Plain 当前关节eyebrow