Add direct motor debugging and multi-arm point execution
This commit is contained in:
parent
4f8d153ac3
commit
8d4b84afd8
@ -160,6 +160,9 @@ set(CMVR_SOURCES
|
||||
src/configeditorwidget.h
|
||||
src/jointfloweditor.cpp
|
||||
src/jointfloweditor.h
|
||||
src/motordebugwidget.h
|
||||
src/motordebugwidget.cpp
|
||||
src/jointpointdata.h
|
||||
src/main.cpp
|
||||
src/mainwindow.cpp
|
||||
src/mainwindow_ui.cpp
|
||||
@ -267,6 +270,7 @@ file(GLOB_RECURSE PROTO_FILES CONFIGURE_DEPENDS
|
||||
"${PROTO_ROOT}/cmvr/quic_edge/v1/*.proto")
|
||||
|
||||
set(SERVICE_NAMES
|
||||
cmvr/api/motor_service
|
||||
cmvr/api/agv_service
|
||||
cmvr/api/arm_service
|
||||
cmvr/api/biohead_service
|
||||
|
||||
@ -32,6 +32,7 @@ QT_SCENEPARSER_DIR = $$clean_path($$[QT_INSTALL_PLUGINS]/sceneparsers)
|
||||
!exists($$LIB_DIR/liburdfdom_model.dll): error("urdfdom runtime DLL not found in lib.")
|
||||
|
||||
PROTO_FILES = \
|
||||
$$PROTO_ROOT/cmvr/api/motor_service.proto \
|
||||
$$PROTO_ROOT/cmvr/api/common.proto \
|
||||
$$PROTO_ROOT/cmvr/api/agv_command.proto \
|
||||
$$PROTO_ROOT/cmvr/api/agv_service.proto \
|
||||
@ -56,6 +57,7 @@ PROTO_FILES = \
|
||||
$$PROTO_ROOT/cmvr/api/test_service.proto
|
||||
|
||||
GRPC_PROTO_FILES = \
|
||||
$$PROTO_ROOT/cmvr/api/motor_service.proto \
|
||||
$$PROTO_ROOT/cmvr/api/agv_service.proto \
|
||||
$$PROTO_ROOT/cmvr/api/arm_service.proto \
|
||||
$$PROTO_ROOT/cmvr/api/biohead_service.proto \
|
||||
@ -368,4 +370,5 @@ HEADERS += src/calibrationfile.h
|
||||
SOURCES += src/touchplanestore.cpp
|
||||
HEADERS += src/touchplanestore.h src/cameracapabilities.h src/bioheadoperations.h
|
||||
SOURCES += src/bioheadwidget.cpp
|
||||
HEADERS += src/bioheadwidget.h
|
||||
HEADERS += src/bioheadwidget.h src/jointpointdata.h src/motordebugwidget.h
|
||||
SOURCES += src/motordebugwidget.cpp
|
||||
|
||||
88
protos/cmvr/api/motor_service.proto
Normal file
88
protos/cmvr/api/motor_service.proto
Normal file
@ -0,0 +1,88 @@
|
||||
syntax = "proto3";
|
||||
package cmvr.api;
|
||||
import "cmvr/api/common.proto";
|
||||
|
||||
// header.device_id identifies a MotorManager, NOT an individual motor.
|
||||
// A nonempty joint_name selects by name; otherwise node_id (including 0) is used.
|
||||
message MotorRequest {
|
||||
CommandHeader.Request header = 1;
|
||||
uint32 node_id = 2;
|
||||
string joint_name = 3;
|
||||
reserved 4; // Retired UI confirmation flag.
|
||||
int32 mode = 5; // cmvr.msgs.RunMode numeric values.
|
||||
double q = 6; // rad
|
||||
double qd = 7; // rad/s: profile speed or cyclic velocity/feedforward, per driver API.
|
||||
double qdd = 8; // rad/s^2: profile acceleration parameter.
|
||||
double tau = 9; // Per mille of rated torque: 1000 = rated torque.
|
||||
double upper = 10;
|
||||
double lower = 11;
|
||||
uint32 torque_slope = 12; // Per mille/s, > 0 for profile torque.
|
||||
reserved 13 to 16; // Retired gRPC planning parameters.
|
||||
}
|
||||
message MotorInfo {
|
||||
string manager_id = 1;
|
||||
uint32 node_id = 2;
|
||||
string joint_name = 3;
|
||||
string driver = 4;
|
||||
// Software/configured limits; these are NOT an SDO dictionary readback.
|
||||
double limit_q_lb = 5;
|
||||
double limit_q_ub = 6;
|
||||
double limit_qd = 7;
|
||||
double limit_qdd = 8;
|
||||
reserved 9; // Retired planning capability.
|
||||
}
|
||||
message MotorDebugState {
|
||||
double position = 1; // rad
|
||||
double velocity = 2; // rad/s
|
||||
bool feedback_valid = 3;
|
||||
double torque = 4;
|
||||
bool torque_valid = 5;
|
||||
string torque_unit = 6; // "per_mille_rated" (not N*m).
|
||||
int32 mode = 7;
|
||||
uint32 status_word = 8;
|
||||
uint32 error_code = 9;
|
||||
bool enabled = 10;
|
||||
bool fault = 11;
|
||||
bool status_valid = 12;
|
||||
reserved 13, 14; // No current getter in this branch's AbstractMotor contract.
|
||||
double sampled_at_s = 15;
|
||||
}
|
||||
message MotorResponse {
|
||||
CommandHeader.Feedback header = 1;
|
||||
MotorInfo info = 2;
|
||||
MotorDebugState state = 3;
|
||||
bool reached_target = 4;
|
||||
// False for void setters; true only means the driver's bool result was true.
|
||||
bool driver_acknowledged = 5;
|
||||
string detail = 6;
|
||||
reserved 7; // Retired background trajectory status.
|
||||
}
|
||||
message MotorListResponse {
|
||||
CommandHeader.Feedback header = 1;
|
||||
repeated MotorInfo motors = 2;
|
||||
}
|
||||
service MotorService {
|
||||
rpc ListMotors(MotorRequest) returns (MotorListResponse);
|
||||
rpc GetInfo(MotorRequest) returns (MotorResponse);
|
||||
rpc GetState(MotorRequest) returns (MotorResponse);
|
||||
rpc getMode(MotorRequest) returns (MotorResponse);
|
||||
rpc getQ(MotorRequest) returns (MotorResponse);
|
||||
rpc getQd(MotorRequest) returns (MotorResponse);
|
||||
rpc getTau(MotorRequest) returns (MotorResponse);
|
||||
rpc reachedTargetQ(MotorRequest) returns (MotorResponse);
|
||||
rpc setMode(MotorRequest) returns (MotorResponse);
|
||||
rpc torqueOn(MotorRequest) returns (MotorResponse);
|
||||
rpc torqueOff(MotorRequest) returns (MotorResponse);
|
||||
rpc brakeRelease(MotorRequest) returns (MotorResponse);
|
||||
rpc quickStop(MotorRequest) returns (MotorResponse);
|
||||
rpc calibrateZeroQ(MotorRequest) returns (MotorResponse);
|
||||
rpc commandProfilePosition(MotorRequest) returns (MotorResponse);
|
||||
rpc commandProfileVelocity(MotorRequest) returns (MotorResponse);
|
||||
rpc commandProfileTorque(MotorRequest) returns (MotorResponse);
|
||||
rpc commandCyclicPosition(MotorRequest) returns (MotorResponse);
|
||||
rpc commandCyclicVelocity(MotorRequest) returns (MotorResponse);
|
||||
rpc commandCyclicTorque(MotorRequest) returns (MotorResponse);
|
||||
rpc setLimitQ(MotorRequest) returns (MotorResponse);
|
||||
rpc setLimitQd(MotorRequest) returns (MotorResponse);
|
||||
rpc setLimitQdd(MotorRequest) returns (MotorResponse);
|
||||
}
|
||||
84
src/jointpointdata.h
Normal file
84
src/jointpointdata.h
Normal file
@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QSet>
|
||||
#include <QVariant>
|
||||
#include <QVector>
|
||||
#include <cmath>
|
||||
|
||||
// A legacy point remains a single target. Only new composite points have arms.
|
||||
struct JointPointTarget {
|
||||
QString side;
|
||||
QString deviceId;
|
||||
QStringList jointNames;
|
||||
QVector<double> positions;
|
||||
|
||||
QJsonObject toJson() const {
|
||||
QJsonArray names, values;
|
||||
for (const auto &name : jointNames) names.append(name);
|
||||
for (double value : positions) values.append(value);
|
||||
return {{"side", side}, {"deviceId", deviceId},
|
||||
{"jointNames", names}, {"positions", values}};
|
||||
}
|
||||
static JointPointTarget fromJson(const QJsonObject &o) {
|
||||
JointPointTarget t;
|
||||
t.side = o.value("side").toString();
|
||||
t.deviceId = o.value("deviceId").toString();
|
||||
for (const auto &v : o.value("jointNames").toArray()) t.jointNames.append(v.toString());
|
||||
for (const auto &v : o.value("positions").toArray())
|
||||
t.positions.append(v.isDouble() ? v.toDouble() : qQNaN());
|
||||
return t;
|
||||
}
|
||||
bool valid() const {
|
||||
if (deviceId.trimmed().isEmpty() || positions.isEmpty()
|
||||
|| jointNames.size() != positions.size()) return false;
|
||||
QSet<QString> names;
|
||||
for (int i = 0; i < positions.size(); ++i) {
|
||||
if (jointNames[i].trimmed().isEmpty() || names.contains(jointNames[i])
|
||||
|| !std::isfinite(positions[i])) return false;
|
||||
names.insert(jointNames[i]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
struct RecordedJointPoint : JointPointTarget {
|
||||
QString name;
|
||||
QList<JointPointTarget> arms;
|
||||
QList<JointPointTarget> targets() const {
|
||||
return arms.isEmpty() ? QList<JointPointTarget>{*this} : arms;
|
||||
}
|
||||
bool valid() const {
|
||||
if (name.trimmed().isEmpty()) return false;
|
||||
QSet<QString> ids;
|
||||
for (const auto &t : targets()) {
|
||||
if (!t.valid() || ids.contains(t.deviceId)) return false;
|
||||
ids.insert(t.deviceId);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
QJsonObject toJson() const {
|
||||
QJsonObject o = JointPointTarget::toJson();
|
||||
o.insert("name", name);
|
||||
if (!arms.isEmpty()) {
|
||||
QJsonArray a;
|
||||
for (const auto &t : arms) a.append(t.toJson());
|
||||
o.insert("arms", a);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
static RecordedJointPoint fromJson(const QJsonObject &o) {
|
||||
RecordedJointPoint p;
|
||||
static_cast<JointPointTarget &>(p) = JointPointTarget::fromJson(o);
|
||||
p.name = o.value("name").toString();
|
||||
for (const auto &v : o.value("arms").toArray())
|
||||
p.arms.append(JointPointTarget::fromJson(v.toObject()));
|
||||
return p;
|
||||
}
|
||||
QVariantList commandTargets() const {
|
||||
QVariantList result;
|
||||
for (const auto &t : targets()) result.append(t.toJson().toVariantMap());
|
||||
return result;
|
||||
}
|
||||
};
|
||||
@ -6,6 +6,7 @@
|
||||
#include "taskorchestrationwidget.h"
|
||||
#include "bioheadoperations.h"
|
||||
#include "bioheadwidget.h"
|
||||
#include "motordebugwidget.h"
|
||||
#include "videorenderwidget.h"
|
||||
|
||||
#include "agvmapviewwidget.h"
|
||||
@ -35,6 +36,8 @@
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QDir>
|
||||
#include <QDialog>
|
||||
#include <QDialogButtonBox>
|
||||
#include <QListWidget>
|
||||
#include <QEvent>
|
||||
#include <QFileDialog>
|
||||
#include <QFile>
|
||||
@ -174,7 +177,7 @@ const QStringList kPageTitles = {
|
||||
QStringLiteral("QUIC Server"), QStringLiteral("设备管理"),
|
||||
QStringLiteral("运行日志"), QStringLiteral("工具坐标标定"),
|
||||
QStringLiteral("手眼标定"), QStringLiteral("末端操作"),
|
||||
QStringLiteral("任务编排")
|
||||
QStringLiteral("任务编排"), QStringLiteral("电机调试")
|
||||
};
|
||||
const QStringList kPageSubtitles = {
|
||||
QStringLiteral("系统信息、运行资源与全局停止"),
|
||||
@ -193,7 +196,8 @@ const QStringList kPageSubtitles = {
|
||||
QStringLiteral("机械臂工具中心点与工具坐标系标定入口"),
|
||||
QStringLiteral("相机与机械臂坐标系的手眼标定入口"),
|
||||
QStringLiteral("视觉取点与触控笔单击、双击、滑动"),
|
||||
QStringLiteral("跨设备任务、循环与执行等待编排")
|
||||
QStringLiteral("跨设备任务、循环与执行等待编排"),
|
||||
QStringLiteral("MotorManager / 单电机接口与位置、速度、加速度、力矩曲线")
|
||||
};
|
||||
|
||||
}
|
||||
@ -373,6 +377,8 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
button->setProperty("navLevel", 2);
|
||||
deviceLayout->addWidget(button);
|
||||
}
|
||||
auto *motorNavButton=createPageButton(QStringLiteral("电机调试"),deviceContent,2);
|
||||
deviceLayout->addWidget(motorNavButton);
|
||||
|
||||
QPushButton *complexGroupButton = createGroupButton(
|
||||
QStringLiteral("复杂操作"), grpcContent, 1);
|
||||
@ -441,7 +447,7 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
ui.dexhandNavButton, ui.bioheadNavButton, ui.hlcNavButton,
|
||||
ui.testNavButton, ui.quicNavButton, ui.configurationNavButton,
|
||||
ui.diagnosticsNavButton, toolCalibrationNavButton, handEyeNavButton, touchNavButton,
|
||||
taskOrchestrationNavButton
|
||||
taskOrchestrationNavButton, motorNavButton
|
||||
};
|
||||
const QStringList icons = {
|
||||
QStringLiteral(":/icons/activity.svg"),
|
||||
@ -459,7 +465,7 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
QStringLiteral(":/icons/scroll-text.svg"),
|
||||
QStringLiteral(":/icons/crosshair.svg"),
|
||||
QStringLiteral(":/icons/camera.svg"), QStringLiteral(":/icons/crosshair.svg"),
|
||||
QStringLiteral(":/icons/braces.svg")
|
||||
QStringLiteral(":/icons/braces.svg"), QStringLiteral(":/icons/activity.svg")
|
||||
};
|
||||
for (int i = 0; i < m_navButtons.size(); ++i) {
|
||||
m_navButtons.at(i)->setIcon(UiIcons::icon(
|
||||
@ -667,6 +673,9 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
setupTouchOperation();
|
||||
m_taskOrchestration = new TaskOrchestrationWidget(m_pages);
|
||||
m_pages->addWidget(m_taskOrchestration);
|
||||
auto *motorDebugPage=new MotorDebugWidget(m_client,m_pages);
|
||||
m_pages->addWidget(motorDebugPage);
|
||||
connect(motorDebugPage,&MotorDebugWidget::statusMessage,this,&MainWindow::appendLog);
|
||||
connect(m_taskOrchestration, &TaskOrchestrationWidget::statusMessage,
|
||||
this, &MainWindow::appendLog);
|
||||
connect(m_taskOrchestration, &TaskOrchestrationWidget::taskRequested, this,
|
||||
@ -857,13 +866,15 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
}
|
||||
});
|
||||
const auto cancelJointFlow = [this](const QString &device) {
|
||||
if (!m_jointPointLoopActive || m_jointPointDispatching) return;
|
||||
if ((!m_jointPointLoopActive && !m_jointPointMovePending) || m_jointPointDispatching) return;
|
||||
bool affected=device.isEmpty() || device==QStringLiteral("*");
|
||||
for (int row:m_jointPointLoopRows) {
|
||||
if (row>=0 && row<m_recordedJointPoints.size()
|
||||
&& m_recordedJointPoints.at(row).deviceId==device) affected=true;
|
||||
if (row>=0 && row<m_recordedJointPoints.size())
|
||||
for (const auto &t : m_recordedJointPoints.at(row).targets())
|
||||
if (t.deviceId==device) affected=true;
|
||||
}
|
||||
if (affected) stopJointPointLoop(QStringLiteral("流程已停止"));
|
||||
if (m_jointPointMovingDevices.contains(device)) affected=true;
|
||||
if (affected) { stopJointPointMotion(); stopJointPointLoop(QStringLiteral("流程已停止")); }
|
||||
};
|
||||
connect(m_client,&RobotClient::armStopRequested,this,cancelJointFlow);
|
||||
connect(m_client,&RobotClient::systemStopAllRequested,this,cancelJointFlow);
|
||||
@ -871,7 +882,39 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
connect(m_client,&RobotClient::tcpJogMoveRequested,this,
|
||||
[cancelJointFlow](const QString &device,const QVariantMap &,double,double,quint64) { cancelJointFlow(device); });
|
||||
connect(m_client,&RobotClient::disconnectRequested,this,
|
||||
[this] { stopJointPointLoop(QStringLiteral("连接已断开")); });
|
||||
[this] { ++m_jointPointCaptureToken; m_jointPointCapturePending=false;
|
||||
m_recordJointPointButton->setEnabled(true);
|
||||
stopJointPointLoop(QStringLiteral("连接已断开")); });
|
||||
connect(m_client, &RobotClient::jointPointMoveFinished, this, &MainWindow::finishJointPoint);
|
||||
connect(m_client, &RobotClient::jointPointCaptured, this,
|
||||
[this](quint64 token, const QVariantList &targets, bool success, const QString &detail) {
|
||||
if (token != m_jointPointCaptureToken || !m_jointPointCapturePending) return;
|
||||
m_jointPointCapturePending=false;
|
||||
m_recordJointPointButton->setEnabled(!m_jointPointLoopActive);
|
||||
if (m_activeJointProgramGroup != m_jointPointCaptureGroup) return;
|
||||
RecordedJointPoint p;
|
||||
p.name=m_jointPointCaptureName;
|
||||
for (const auto &v : targets) {
|
||||
auto t=JointPointTarget::fromJson(QJsonObject::fromVariantMap(v.toMap()));
|
||||
t.side=t.deviceId.contains(QStringLiteral("left"),Qt::CaseInsensitive)
|
||||
? QStringLiteral("left")
|
||||
: t.deviceId.contains(QStringLiteral("right"),Qt::CaseInsensitive)
|
||||
? QStringLiteral("right") : QString();
|
||||
p.arms.append(t);
|
||||
}
|
||||
if (p.arms.size()==1) { static_cast<JointPointTarget &>(p)=p.arms.first(); p.arms.clear(); }
|
||||
if (!success || !p.valid()) {
|
||||
AppMessageBox::warning(m_jointFlowDialog, QStringLiteral("记录点位"),
|
||||
detail.isEmpty() ? QStringLiteral("设备未返回完整有效的关节名称和角度,未保存点位。") : detail);
|
||||
return;
|
||||
}
|
||||
for (const auto &existing : m_recordedJointPoints) if (existing.name.compare(p.name,Qt::CaseInsensitive)==0) return;
|
||||
m_recordedJointPoints.append(p);
|
||||
refreshRecordedJointPoints(); saveJointPrograms();
|
||||
m_jointPointNameEdit->clear();
|
||||
m_jointPointTable->selectRow(m_recordedJointPoints.size()-1);
|
||||
appendLog(QStringLiteral("OK"),QStringLiteral("已记录点位:%1(%2 条机械臂)").arg(p.name).arg(p.targets().size()));
|
||||
});
|
||||
|
||||
const QList<QComboBox *> comboBoxes = findChildren<QComboBox *>();
|
||||
for (QComboBox *comboBox : comboBoxes)
|
||||
@ -1636,6 +1679,11 @@ void MainWindow::toggleConnection()
|
||||
void MainWindow::updateConnection(bool connected, int latencyMs, const QString &detail)
|
||||
{
|
||||
m_connected = connected;
|
||||
if (!connected) {
|
||||
++m_jointPointCaptureToken;
|
||||
m_jointPointCapturePending=false;
|
||||
stopJointPointLoop(QStringLiteral("连接已断开"));
|
||||
}
|
||||
if (!connected && m_taskOrchestration)
|
||||
m_taskOrchestration->failActiveTask(
|
||||
detail.isEmpty() ? QStringLiteral("gRPC 连接已断开") : detail);
|
||||
@ -3092,22 +3140,6 @@ void MainWindow::handleCommand(const QString &command, bool success, const QStri
|
||||
|
||||
appendLog(success ? QStringLiteral("OK") : QStringLiteral("ERROR"),
|
||||
QStringLiteral("%1 · %2").arg(command, detail));
|
||||
if (command == QStringLiteral("MoveJ") && m_jointPointMovePending) {
|
||||
m_jointPointMovePending = false;
|
||||
if (!success) {
|
||||
stopJointPointLoop(QStringLiteral("MoveJ 执行失败:%1").arg(detail));
|
||||
} else if (m_jointPointLoopActive) {
|
||||
const int completedIndex = m_jointPointLoopCursor - 1;
|
||||
const double waitSeconds = completedIndex >= 0
|
||||
&& completedIndex < m_jointPointExecutionWaits.size()
|
||||
? m_jointPointExecutionWaits.at(completedIndex) : 0.0;
|
||||
const int delayMs = qRound(waitSeconds * 1000.0);
|
||||
const quint64 generation=m_jointPointLoopGeneration;
|
||||
QTimer::singleShot(delayMs,this,[this,generation] {
|
||||
if (generation==m_jointPointLoopGeneration) advanceJointPointLoop();
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!success)
|
||||
m_connectionText->setToolTip(detail);
|
||||
}
|
||||
@ -3173,20 +3205,28 @@ void MainWindow::refreshRecordedJointPoints()
|
||||
m_jointPointTable->setRowCount(m_recordedJointPoints.size());
|
||||
for (int row = 0; row < m_recordedJointPoints.size(); ++row) {
|
||||
const RecordedJointPoint &point = m_recordedJointPoints.at(row);
|
||||
QStringList values;
|
||||
for (double position : point.positions)
|
||||
values.append(QString::number(position, 'f', 6));
|
||||
QStringList values, ids, names;
|
||||
int count=0;
|
||||
for (const auto &t : point.targets()) {
|
||||
QStringList angles;
|
||||
for (double position : t.positions) angles.append(QString::number(position,'f',6));
|
||||
ids.append(t.deviceId);
|
||||
names.append(t.jointNames);
|
||||
values.append(t.deviceId+QStringLiteral(": ")+angles.join(", "));
|
||||
count+=t.positions.size();
|
||||
}
|
||||
m_jointPointTable->setItem(row, 0, new QTableWidgetItem(point.name));
|
||||
m_jointPointTable->setItem(row, 1, new QTableWidgetItem(
|
||||
point.side == QStringLiteral("left") ? QStringLiteral("左臂")
|
||||
: QStringLiteral("右臂")));
|
||||
m_jointPointTable->setItem(row, 2, new QTableWidgetItem(point.deviceId));
|
||||
point.targets().size()>1 ? QStringLiteral("组合 · %1 臂").arg(point.targets().size())
|
||||
: (point.side == QStringLiteral("left") ? QStringLiteral("左臂")
|
||||
: point.side == QStringLiteral("right") ? QStringLiteral("右臂") : QStringLiteral("单臂"))));
|
||||
m_jointPointTable->setItem(row, 2, new QTableWidgetItem(ids.join(" + ")));
|
||||
m_jointPointTable->setItem(row, 3, new QTableWidgetItem(
|
||||
QString::number(point.positions.size())));
|
||||
QTableWidgetItem *positionsItem = new QTableWidgetItem(values.join(QStringLiteral(", ")));
|
||||
QString::number(count)));
|
||||
QTableWidgetItem *positionsItem = new QTableWidgetItem(values.join(QStringLiteral(" | ")));
|
||||
positionsItem->setToolTip(QStringLiteral("关节顺序:%1\n角度(rad):%2")
|
||||
.arg(point.jointNames.join(QStringLiteral(", ")),
|
||||
values.join(QStringLiteral(", "))));
|
||||
.arg(names.join(QStringLiteral(", ")),
|
||||
values.join(QStringLiteral("\n"))));
|
||||
m_jointPointTable->setItem(row, 4, positionsItem);
|
||||
}
|
||||
}
|
||||
@ -3199,6 +3239,7 @@ void MainWindow::refreshJointFlowTable()
|
||||
|
||||
void MainWindow::recordCurrentJointPoint()
|
||||
{
|
||||
if (m_jointPointCapturePending || m_jointPointMovePending || m_jointPointLoopActive) return;
|
||||
const QString name = m_jointPointNameEdit
|
||||
? m_jointPointNameEdit->text().trimmed() : QString();
|
||||
if (name.isEmpty()) {
|
||||
@ -3215,52 +3256,96 @@ void MainWindow::recordCurrentJointPoint()
|
||||
}
|
||||
}
|
||||
|
||||
const QStringList jointNames = m_activeArmJointNames;
|
||||
if (jointNames.isEmpty()) {
|
||||
AppMessageBox::warning(this, QStringLiteral("记录关节点位"),
|
||||
QStringLiteral("当前 URDF 中没有该机械臂的可运动关节。"));
|
||||
return;
|
||||
QDialog dialog(m_jointFlowDialog);
|
||||
dialog.setWindowTitle(QStringLiteral("选择记录的机械臂"));
|
||||
auto *layout=new QVBoxLayout(&dialog);
|
||||
layout->addWidget(new QLabel(QStringLiteral("勾选一条或多条机械臂,读取当前关节角度。"),&dialog));
|
||||
auto *list=new QListWidget(&dialog);
|
||||
for (int i=0;i<m_armSideCombo->count();++i) {
|
||||
const QString id=m_armSideCombo->itemData(i).toString();
|
||||
if (id.isEmpty()) continue;
|
||||
auto *item=new QListWidgetItem(m_armSideCombo->itemText(i),list);
|
||||
item->setData(Qt::UserRole,id);
|
||||
item->setFlags(item->flags()|Qt::ItemIsUserCheckable);
|
||||
item->setCheckState(id==m_armIdEdit->text().trimmed()?Qt::Checked:Qt::Unchecked);
|
||||
}
|
||||
layout->addWidget(list);
|
||||
auto *buttons=new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel,&dialog);
|
||||
layout->addWidget(buttons);
|
||||
connect(buttons,&QDialogButtonBox::accepted,&dialog,&QDialog::accept);
|
||||
connect(buttons,&QDialogButtonBox::rejected,&dialog,&QDialog::reject);
|
||||
ApplicationStyle::decorateDialog(&dialog);
|
||||
dialog.resize(520,330);
|
||||
if (dialog.exec()!=QDialog::Accepted) return;
|
||||
QStringList devices;
|
||||
for (int i=0;i<list->count();++i) if (list->item(i)->checkState()==Qt::Checked)
|
||||
devices.append(list->item(i)->data(Qt::UserRole).toString());
|
||||
if (devices.isEmpty()) return;
|
||||
m_jointPointCapturePending=true;
|
||||
m_jointPointCaptureName=name;
|
||||
m_jointPointCaptureGroup=m_activeJointProgramGroup;
|
||||
m_recordJointPointButton->setEnabled(false);
|
||||
m_client->requestJointPointCapture(devices,++m_jointPointCaptureToken);
|
||||
}
|
||||
|
||||
RecordedJointPoint point;
|
||||
point.name = name;
|
||||
point.deviceId = m_armIdEdit->text().trimmed();
|
||||
point.side = point.deviceId.contains(QStringLiteral("left"), Qt::CaseInsensitive)
|
||||
? QStringLiteral("left") : QStringLiteral("right");
|
||||
point.jointNames = jointNames;
|
||||
QStringList missing;
|
||||
for (const QString &jointName : jointNames) {
|
||||
if (!m_latestArmJointPositions.contains(jointName)) {
|
||||
missing.append(jointName);
|
||||
continue;
|
||||
}
|
||||
point.positions.append(m_latestArmJointPositions.value(jointName));
|
||||
void MainWindow::combineSelectedJointPoints()
|
||||
{
|
||||
if (m_jointPointCapturePending || m_jointPointMovePending || m_jointPointLoopActive) return;
|
||||
const QString name=m_jointPointNameEdit->text().trimmed();
|
||||
RecordedJointPoint p; p.name=name;
|
||||
for (const auto &old : m_recordedJointPoints) if (old.name.compare(name,Qt::CaseInsensitive)==0) {
|
||||
AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("组合点位"),QStringLiteral("请使用不同的点位名称。")); return;
|
||||
}
|
||||
if (!missing.isEmpty()) {
|
||||
AppMessageBox::warning(this, QStringLiteral("记录关节点位"),
|
||||
QStringLiteral("尚未收到以下关节的实时角度:\n%1\n\n请先启动遥测。")
|
||||
.arg(missing.join(QStringLiteral(", "))));
|
||||
return;
|
||||
}
|
||||
if (point.deviceId.isEmpty()) {
|
||||
AppMessageBox::warning(this, QStringLiteral("记录关节点位"),
|
||||
QStringLiteral("当前 Device ID 为空。"));
|
||||
return;
|
||||
for (const auto &row : m_jointPointTable->selectionModel()->selectedRows())
|
||||
p.arms.append(m_recordedJointPoints.at(row.row()).targets());
|
||||
if (p.arms.size()<2 || !p.valid()) {
|
||||
AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("组合点位"),
|
||||
QStringLiteral("请填写新名称,并选中不同机械臂的点位。每条机械臂只能出现一次,原点位将保留。")); return;
|
||||
}
|
||||
m_recordedJointPoints.append(p); refreshRecordedJointPoints(); saveJointPrograms();
|
||||
m_jointPointNameEdit->clear(); m_jointPointTable->selectRow(m_recordedJointPoints.size()-1);
|
||||
}
|
||||
|
||||
m_recordedJointPoints.append(point);
|
||||
refreshRecordedJointPoints();
|
||||
saveJointPrograms();
|
||||
m_jointPointNameEdit->clear();
|
||||
m_jointPointTable->selectRow(m_recordedJointPoints.size() - 1);
|
||||
appendLog(QStringLiteral("OK"),
|
||||
QStringLiteral("已记录动作“%1”,%2 个关节(rad)")
|
||||
.arg(point.name).arg(point.positions.size()));
|
||||
void MainWindow::dispatchJointPoint(int row)
|
||||
{
|
||||
const auto &p=m_recordedJointPoints.at(row);
|
||||
if (!p.valid()) { stopJointPointLoop(QStringLiteral("点位数据无效,未发送")); return; }
|
||||
m_jointPointMovingDevices.clear();
|
||||
for (const auto &t : p.targets()) m_jointPointMovingDevices.append(t.deviceId);
|
||||
m_jointPointMovePending=true;
|
||||
m_stopJointPointLoopButton->setEnabled(true);
|
||||
const QScopedValueRollback<bool> dispatch(m_jointPointDispatching,true);
|
||||
m_client->requestJointPointMove(p.commandTargets(),m_jointFlowVelocitySpin->value(),
|
||||
m_jointFlowAccelerationSpin->value(),++m_jointPointRequestToken);
|
||||
}
|
||||
|
||||
void MainWindow::finishJointPoint(quint64 token,bool success,const QString &detail)
|
||||
{
|
||||
if (token!=m_jointPointRequestToken || !m_jointPointMovePending) return;
|
||||
m_jointPointMovePending=false;
|
||||
m_jointPointMovingDevices.clear();
|
||||
appendLog(success?QStringLiteral("OK"):QStringLiteral("ERROR"),detail);
|
||||
if (!success || !m_jointPointLoopActive) { stopJointPointLoop(detail); return; }
|
||||
const int index=m_jointPointLoopCursor-1;
|
||||
const int delay=index>=0 && index<m_jointPointExecutionWaits.size()
|
||||
? qRound(m_jointPointExecutionWaits[index]*1000.0) : 0;
|
||||
const quint64 generation=m_jointPointLoopGeneration;
|
||||
QTimer::singleShot(delay,this,[this,generation] {
|
||||
if (generation==m_jointPointLoopGeneration) advanceJointPointLoop();
|
||||
});
|
||||
}
|
||||
|
||||
void MainWindow::stopJointPointMotion()
|
||||
{
|
||||
const QStringList devices=m_jointPointMovingDevices;
|
||||
m_jointPointMovingDevices.clear();
|
||||
const QScopedValueRollback<bool> dispatch(m_jointPointDispatching,true);
|
||||
for (const auto &id : devices) m_client->requestArmStop(id);
|
||||
}
|
||||
|
||||
void MainWindow::executeSelectedJointPoint()
|
||||
{
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending)
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending)
|
||||
return;
|
||||
const QModelIndexList selected = m_jointPointTable
|
||||
? m_jointPointTable->selectionModel()->selectedRows() : QModelIndexList();
|
||||
@ -3273,20 +3358,14 @@ void MainWindow::executeSelectedJointPoint()
|
||||
if (row < 0 || row >= m_recordedJointPoints.size())
|
||||
return;
|
||||
const RecordedJointPoint &point = m_recordedJointPoints.at(row);
|
||||
QVariantList positions;
|
||||
for (double position : point.positions)
|
||||
positions.append(position);
|
||||
m_jointPointMovePending = true;
|
||||
m_client->requestMoveJ(point.deviceId, positions,
|
||||
m_jointFlowVelocitySpin->value(),
|
||||
m_jointFlowAccelerationSpin->value());
|
||||
dispatchJointPoint(row);
|
||||
if (m_jointPointLoopStatus)
|
||||
m_jointPointLoopStatus->setText(QStringLiteral("执行:%1").arg(point.name));
|
||||
}
|
||||
|
||||
void MainWindow::startJointPointLoop()
|
||||
{
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending)
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending)
|
||||
return;
|
||||
++m_jointPointLoopGeneration;
|
||||
if (!m_jointFlowEditor || m_jointFlowEditor->isEmpty()) {
|
||||
@ -3361,20 +3440,15 @@ void MainWindow::advanceJointPointLoop()
|
||||
const RecordedJointPoint &point = m_recordedJointPoints.at(row);
|
||||
if (m_jointFlowEditor && executionIndex < m_jointPointExecutionNodeIds.size())
|
||||
m_jointFlowEditor->setActiveNode(m_jointPointExecutionNodeIds.at(executionIndex));
|
||||
QVariantList positions;
|
||||
for (double position : point.positions)
|
||||
positions.append(position);
|
||||
m_jointPointMovePending = true;
|
||||
m_jointPointLoopStatus->setText(QStringLiteral("步骤 %1/%2 · %3")
|
||||
.arg(executionIndex + 1).arg(m_jointPointLoopRows.size()).arg(point.name));
|
||||
const QScopedValueRollback<bool> dispatch(m_jointPointDispatching,true);
|
||||
m_client->requestMoveJ(point.deviceId, positions,
|
||||
m_jointFlowVelocitySpin->value(),
|
||||
m_jointFlowAccelerationSpin->value());
|
||||
dispatchJointPoint(row);
|
||||
}
|
||||
|
||||
void MainWindow::stopJointPointLoop(const QString &reason)
|
||||
{
|
||||
++m_jointPointRequestToken;
|
||||
m_jointPointMovingDevices.clear();
|
||||
++m_jointPointLoopGeneration;
|
||||
const bool wasActive = m_jointPointLoopActive;
|
||||
m_jointPointLoopActive = false;
|
||||
@ -3391,7 +3465,7 @@ void MainWindow::stopJointPointLoop(const QString &reason)
|
||||
if (m_deleteJointPointButton)
|
||||
m_deleteJointPointButton->setEnabled(true);
|
||||
if (m_recordJointPointButton)
|
||||
m_recordJointPointButton->setEnabled(true);
|
||||
m_recordJointPointButton->setEnabled(!m_jointPointCapturePending);
|
||||
if (m_stopJointPointLoopButton)
|
||||
m_stopJointPointLoopButton->setEnabled(false);
|
||||
if (m_jointPointTable)
|
||||
@ -3610,7 +3684,12 @@ void MainWindow::activateJointProgramGroup(int index)
|
||||
|| index >= m_jointProgramGroups.size()
|
||||
|| index == m_activeJointProgramGroup)
|
||||
return;
|
||||
if (m_jointPointLoopActive)
|
||||
++m_jointPointCaptureToken;
|
||||
m_jointPointCapturePending=false;
|
||||
if (m_recordJointPointButton) m_recordJointPointButton->setEnabled(true);
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending)
|
||||
stopJointPointMotion();
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending)
|
||||
stopJointPointLoop(QStringLiteral("切换点位组"));
|
||||
storeCurrentJointProgramGroup();
|
||||
m_activeJointProgramGroup = index;
|
||||
@ -3663,16 +3742,9 @@ void MainWindow::loadJointPrograms(QSettings &legacySettings)
|
||||
QStringLiteral("moveJAcceleration")).toDouble(0.1);
|
||||
for (const QJsonValue &pointValue : groupObject.value(QStringLiteral("points")).toArray()) {
|
||||
const QJsonObject pointObject = pointValue.toObject();
|
||||
RecordedJointPoint point;
|
||||
point.name = pointObject.value(QStringLiteral("name")).toString();
|
||||
point.side = pointObject.value(QStringLiteral("side")).toString();
|
||||
point.deviceId = pointObject.value(QStringLiteral("deviceId")).toString();
|
||||
for (const QJsonValue &name : pointObject.value(QStringLiteral("jointNames")).toArray())
|
||||
point.jointNames.append(name.toString());
|
||||
for (const QJsonValue &position : pointObject.value(QStringLiteral("positions")).toArray())
|
||||
point.positions.append(position.toDouble());
|
||||
const RecordedJointPoint point=RecordedJointPoint::fromJson(pointObject);
|
||||
if (!point.name.isEmpty()
|
||||
&& point.jointNames.size() == point.positions.size())
|
||||
&& (point.jointNames.size() == point.positions.size() || !point.arms.isEmpty()))
|
||||
group.points.append(point);
|
||||
}
|
||||
if (!group.name.isEmpty())
|
||||
@ -3761,19 +3833,7 @@ void MainWindow::saveJointPrograms()
|
||||
groupObject.insert(QStringLiteral("name"), group.name);
|
||||
QJsonArray points;
|
||||
for (const RecordedJointPoint &point : group.points) {
|
||||
QJsonObject pointObject;
|
||||
pointObject.insert(QStringLiteral("name"), point.name);
|
||||
pointObject.insert(QStringLiteral("side"), point.side);
|
||||
pointObject.insert(QStringLiteral("deviceId"), point.deviceId);
|
||||
QJsonArray names;
|
||||
for (const QString &name : point.jointNames)
|
||||
names.append(name);
|
||||
QJsonArray positions;
|
||||
for (double position : point.positions)
|
||||
positions.append(position);
|
||||
pointObject.insert(QStringLiteral("jointNames"), names);
|
||||
pointObject.insert(QStringLiteral("positions"), positions);
|
||||
points.append(pointObject);
|
||||
points.append(point.toJson());
|
||||
}
|
||||
groupObject.insert(QStringLiteral("points"), points);
|
||||
groupObject.insert(QStringLiteral("flow"), group.flow);
|
||||
@ -3782,7 +3842,7 @@ void MainWindow::saveJointPrograms()
|
||||
groups.append(groupObject);
|
||||
}
|
||||
QJsonObject root;
|
||||
root.insert(QStringLiteral("version"), 1);
|
||||
root.insert(QStringLiteral("version"), 2);
|
||||
root.insert(QStringLiteral("activeGroup"),
|
||||
m_jointProgramGroups.at(m_activeJointProgramGroup).name);
|
||||
root.insert(QStringLiteral("groups"), groups);
|
||||
|
||||
@ -14,6 +14,7 @@
|
||||
#include <QVector>
|
||||
|
||||
#include "videoframe.h"
|
||||
#include "jointpointdata.h"
|
||||
|
||||
class QButtonGroup;
|
||||
class QCheckBox;
|
||||
@ -56,6 +57,7 @@ class TaskOrchestrationWidget;
|
||||
class MainWindow : public QMainWindow
|
||||
{
|
||||
Q_OBJECT
|
||||
friend struct JointPointTestAccess;
|
||||
|
||||
public:
|
||||
explicit MainWindow(QWidget *parent = nullptr);
|
||||
@ -101,6 +103,10 @@ private slots:
|
||||
void sendMoveJ();
|
||||
void sendMoveJPose();
|
||||
void recordCurrentJointPoint();
|
||||
void combineSelectedJointPoints();
|
||||
void dispatchJointPoint(int row);
|
||||
void finishJointPoint(quint64 token, bool success, const QString &detail);
|
||||
void stopJointPointMotion();
|
||||
void executeSelectedJointPoint();
|
||||
void startJointPointLoop();
|
||||
void stopJointPointLoop(const QString &reason = QString());
|
||||
@ -281,13 +287,7 @@ private:
|
||||
QString m_teachSelectedJoint;
|
||||
QString m_pendingUrdfPath;
|
||||
bool m_armModelLoadScheduled = false;
|
||||
struct RecordedJointPoint {
|
||||
QString name;
|
||||
QString side;
|
||||
QString deviceId;
|
||||
QStringList jointNames;
|
||||
QVector<double> positions;
|
||||
};
|
||||
using RecordedJointPoint = ::RecordedJointPoint;
|
||||
struct JointProgramGroup {
|
||||
QString name;
|
||||
QList<RecordedJointPoint> points;
|
||||
@ -328,6 +328,12 @@ private:
|
||||
bool m_jointPointMovePending = false;
|
||||
quint64 m_jointPointLoopGeneration = 0;
|
||||
bool m_jointPointDispatching = false;
|
||||
quint64 m_jointPointRequestToken = 0;
|
||||
QStringList m_jointPointMovingDevices;
|
||||
bool m_jointPointCapturePending = false;
|
||||
quint64 m_jointPointCaptureToken = 0;
|
||||
QString m_jointPointCaptureName;
|
||||
int m_jointPointCaptureGroup = -1;
|
||||
|
||||
QComboBox *m_cameraDeviceCombo = nullptr;
|
||||
VideoRenderWidget *m_videoRender = nullptr;
|
||||
|
||||
@ -538,7 +538,7 @@ QWidget *MainWindow::createArmPage()
|
||||
QLabel *pointTitle = new QLabel(QStringLiteral("关节点位记录与循环"), pointPanel);
|
||||
pointTitle->setObjectName(QStringLiteral("jointFlowSectionTitle"));
|
||||
QLabel *pointSubtitle = new QLabel(
|
||||
QStringLiteral("记录当前关节角度,作为流程中的可执行点位"), pointPanel);
|
||||
QStringLiteral("可记录单臂或多臂点位,也可组合已有点位,原记录保留"), pointPanel);
|
||||
pointSubtitle->setObjectName(QStringLiteral("jointFlowSectionSubtitle"));
|
||||
QVBoxLayout *pointHeading = new QVBoxLayout;
|
||||
pointHeading->setSpacing(2);
|
||||
@ -595,6 +595,10 @@ QWidget *MainWindow::createArmPage()
|
||||
m_jointPointLoopStatus->setObjectName(QStringLiteral("mutedLabel"));
|
||||
pointActions->addWidget(m_runJointPointButton);
|
||||
pointActions->addWidget(m_deleteJointPointButton);
|
||||
auto *combineButton=new QPushButton(QStringLiteral("组合选中点位"),pointPanel);
|
||||
combineButton->setToolTip(QStringLiteral("填写新名称,选择不同机械臂的已有点位,生成组合点位;保留原点位"));
|
||||
pointActions->addWidget(combineButton);
|
||||
connect(combineButton,&QPushButton::clicked,this,&MainWindow::combineSelectedJointPoints);
|
||||
pointActions->addStretch(1);
|
||||
pointActions->addWidget(m_jointPointLoopStatus);
|
||||
pointLayout->addLayout(pointActions);
|
||||
@ -605,11 +609,11 @@ QWidget *MainWindow::createArmPage()
|
||||
connect(m_startJointPointLoopButton, &QPushButton::clicked,
|
||||
this, &MainWindow::startJointPointLoop);
|
||||
connect(m_stopJointPointLoopButton, &QPushButton::clicked, this, [this]() {
|
||||
stopJointPointMotion();
|
||||
stopJointPointLoop(QStringLiteral("用户停止"));
|
||||
m_client->requestArmStop(m_armIdEdit->text().trimmed());
|
||||
});
|
||||
connect(m_deleteJointPointButton, &QPushButton::clicked, this, [this]() {
|
||||
if (m_jointPointLoopActive)
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending)
|
||||
return;
|
||||
QList<int> rows;
|
||||
for (const QModelIndex &index : m_jointPointTable->selectionModel()->selectedRows())
|
||||
@ -634,17 +638,13 @@ QWidget *MainWindow::createArmPage()
|
||||
return;
|
||||
const RecordedJointPoint &point = m_recordedJointPoints.at(row);
|
||||
QStringList details;
|
||||
for (int i = 0; i < point.jointNames.size() && i < point.positions.size(); ++i) {
|
||||
details.append(QStringLiteral("%1 = %2 rad")
|
||||
.arg(point.jointNames.at(i))
|
||||
.arg(point.positions.at(i), 0, 'f', 6));
|
||||
for (const auto &t : point.targets()) {
|
||||
QStringList angles;
|
||||
for (int i=0;i<t.jointNames.size() && i<t.positions.size();++i)
|
||||
angles.append(QStringLiteral("%1 = %2 rad").arg(t.jointNames[i]).arg(t.positions[i],0,'f',6));
|
||||
details.append(t.deviceId+QStringLiteral(": ")+angles.join(" "));
|
||||
}
|
||||
m_jointPointDetailLabel->setText(
|
||||
QStringLiteral("%1 · %2 · %3\n%4")
|
||||
.arg(point.name,
|
||||
point.side == QStringLiteral("left") ? QStringLiteral("左臂")
|
||||
: QStringLiteral("右臂"),
|
||||
point.deviceId, details.join(QStringLiteral(" "))));
|
||||
m_jointPointDetailLabel->setText(point.name+"\n"+details.join("\n"));
|
||||
});
|
||||
|
||||
QFrame *flowPanel = new QFrame(moveJPage);
|
||||
|
||||
301
src/motordebugwidget.cpp
Normal file
301
src/motordebugwidget.cpp
Normal file
@ -0,0 +1,301 @@
|
||||
#include "motordebugwidget.h"
|
||||
#include "robotclient.h"
|
||||
#include "applicationstyle.h"
|
||||
#include "appmessagebox.h"
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QSpinBox>
|
||||
#include <QLabel>
|
||||
#include <QPushButton>
|
||||
#include <QTimer>
|
||||
#include <QFrame>
|
||||
#include <QFormLayout>
|
||||
#include <QHBoxLayout>
|
||||
#include <QVBoxLayout>
|
||||
#include <QTabWidget>
|
||||
#include <QScrollArea>
|
||||
#include <QSplitter>
|
||||
#include <QGridLayout>
|
||||
#include <QToolButton>
|
||||
#include <QButtonGroup>
|
||||
#include <QPainter>
|
||||
#include <QPainterPath>
|
||||
#include <QFileDialog>
|
||||
#include <QSaveFile>
|
||||
#include <QTextStream>
|
||||
#include <QSignalBlocker>
|
||||
#include <QHideEvent>
|
||||
#include <QWheelEvent>
|
||||
#include <QJsonDocument>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace {
|
||||
template<class Base>
|
||||
class MotorInputBox final : public Base {
|
||||
public:
|
||||
explicit MotorInputBox(QWidget *parent):Base(parent) {
|
||||
this->setButtonSymbols(QAbstractSpinBox::NoButtons);
|
||||
}
|
||||
protected:
|
||||
void wheelEvent(QWheelEvent *event) override { event->ignore(); }
|
||||
};
|
||||
QString modeName(int mode) {
|
||||
switch(mode) {
|
||||
case 0:return QStringLiteral("未指定");
|
||||
case 1:return QStringLiteral("轮廓位置");
|
||||
case 2:return QStringLiteral("速度");
|
||||
case 3:return QStringLiteral("轮廓速度");
|
||||
case 4:return QStringLiteral("轮廓力矩");
|
||||
case 5:return QStringLiteral("回零");
|
||||
case 7:return QStringLiteral("位置插补");
|
||||
case 8:return QStringLiteral("周期位置");
|
||||
case 9:return QStringLiteral("周期速度");
|
||||
case 10:return QStringLiteral("周期力矩");
|
||||
default:return QString::number(mode);
|
||||
}
|
||||
}
|
||||
double missing() { return std::numeric_limits<double>::quiet_NaN(); }
|
||||
QString number(const QVariantMap &s,const QString &key,bool valid) {
|
||||
const double v=s.value(key,missing()).toDouble();
|
||||
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<Sample> 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() && time<samples.last().t) samples.clear();
|
||||
if (!samples.isEmpty() && time==samples.last().t) return;
|
||||
const bool valid=s.value("feedbackValid").toBool();
|
||||
double acceleration=missing();
|
||||
if(valid&&!samples.isEmpty()) {
|
||||
const auto &previous=samples.last();const double dt=time-previous.t;
|
||||
const double velocity=s.value("velocity",missing()).toDouble();
|
||||
if(dt>0&&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.t<begin || !std::isfinite(v)) { started=false;continue; }
|
||||
const QPointF pt(plot.left()+(s.t-begin)/window*plot.width(),plot.bottom()-(v-lo)/(hi-lo)*plot.height());
|
||||
if (!started || s.t-previous>1.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");
|
||||
auto *layout=new QVBoxLayout(this);layout->setContentsMargins(16,12,16,14);layout->setSpacing(10);
|
||||
auto *header=new QFrame(this);header->setObjectName("panel");auto *row=new QHBoxLayout(header);
|
||||
row->addWidget(new QLabel(QStringLiteral("电机系统"),header));
|
||||
m_manager=new QComboBox(header);m_manager->setObjectName("motorManagerCombo");m_manager->setMinimumWidth(170);row->addWidget(m_manager);
|
||||
row->addWidget(new QLabel(QStringLiteral("电机"),header));
|
||||
m_motor=new QComboBox(header);m_motor->setObjectName("motorNodeCombo");m_motor->setMinimumWidth(170);row->addWidget(m_motor);
|
||||
auto *refresh=new QPushButton(QStringLiteral("刷新电机 / ListMotors"),header);row->addWidget(refresh);row->addStretch();
|
||||
auto *stop=new QPushButton(QStringLiteral("快速停止 / quickStop"),header);stop->setObjectName("dangerButton");row->addWidget(stop);
|
||||
layout->addWidget(header);
|
||||
auto *splitter=new QSplitter(Qt::Horizontal,this);splitter->setChildrenCollapsible(false);layout->addWidget(splitter,1);
|
||||
auto *telemetry=new QFrame(splitter);telemetry->setObjectName("panel");auto *plotLayout=new QVBoxLayout(telemetry);
|
||||
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<QSpinBox>(telemetry);m_rate->setRange(1,50);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);
|
||||
auto *window=new QComboBox(telemetry);for(int v:{5,10,30,60})window->addItem(QStringLiteral("最近 %1 秒").arg(v),v);window->setCurrentIndex(2);tools->addWidget(window);tools->addStretch();plotLayout->addLayout(tools);
|
||||
m_rateStatus=new QLabel(QStringLiteral("实际采集 -- Hz"),telemetry);m_rateStatus->setObjectName("mutedLabel");plotLayout->addWidget(m_rateStatus);
|
||||
m_values=new QLabel(QStringLiteral("尚未读取电机状态"),telemetry);m_values->setWordWrap(true);m_values->setTextInteractionFlags(Qt::TextSelectableByMouse);plotLayout->addWidget(m_values);
|
||||
m_plot=new MotorPlot(telemetry);plotLayout->addWidget(m_plot,1);
|
||||
m_status=new QLabel(QStringLiteral("未连接"),telemetry);m_status->setWordWrap(true);m_status->setTextInteractionFlags(Qt::TextSelectableByMouse);plotLayout->addWidget(m_status);
|
||||
auto *scroll=new QScrollArea(splitter);scroll->setObjectName("motorControlScroll");scroll->setWidgetResizable(true);scroll->setFrameShape(QFrame::NoFrame);scroll->setMinimumWidth(455);
|
||||
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);
|
||||
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);
|
||||
auto param=[&](const QString &key,const QString &label,double value){
|
||||
auto *spin=new MotorInputBox<QDoubleSpinBox>(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);
|
||||
};
|
||||
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<QSpinBox>(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);
|
||||
auto group=[&](const QString &name,const QList<QPair<QString,QString>> &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);});
|
||||
}
|
||||
};
|
||||
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"},
|
||||
{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();
|
||||
splitter->setStretchFactor(0,1);splitter->setStretchFactor(1,0);splitter->setSizes({880,470});
|
||||
m_timer=new QTimer(this);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<int>::of(&QSpinBox::valueChanged),this,[this](int v){m_timer->setInterval(qMax(20,1000/v));});
|
||||
connect(window,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this,window]{m_plot->window=window->currentData().toDouble();m_plot->update();});
|
||||
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");});
|
||||
connect(stop,&QPushButton::clicked,this,[this]{invoke("quickStop");});
|
||||
connect(m_manager,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this]{resetSelection();{QSignalBlocker b(m_motor);m_motor->clear();}invoke("ListMotors");});
|
||||
connect(m_motor,QOverload<int>::of(&QComboBox::currentIndexChanged),this,&MotorDebugWidget::resetSelection);
|
||||
connect(client,&RobotClient::motorRpcFinished,this,&MotorDebugWidget::reply);
|
||||
connect(client,&RobotClient::connectionChanged,this,[this](bool connected,int,const QString &detail){
|
||||
m_connected=connected;resetSelection();if(!connected){QSignalBlocker a(m_manager),b(m_motor);m_manager->clear();m_motor->clear();m_status->setText(detail);}refreshControls();
|
||||
});
|
||||
connect(client,&RobotClient::systemStatusReceived,this,[this](double,double,double,const QVariantList &devices){
|
||||
QStringList ids,old;for(const auto &v:devices)if(v.toMap().value("type").toInt()==10)ids.append(v.toMap().value("deviceId").toString());
|
||||
for(int i=0;i<m_manager->count();++i)old.append(m_manager->itemData(i).toString());if(ids==old)return;
|
||||
const QString selected=m_manager->currentData().toString();
|
||||
{QSignalBlocker b(m_manager);m_manager->clear();for(const auto &id:ids)m_manager->addItem(id,id);const int index=m_manager->findData(selected);if(index>=0)m_manager->setCurrentIndex(index);}
|
||||
resetSelection();{QSignalBlocker b(m_motor);m_motor->clear();}invoke("ListMotors");
|
||||
});
|
||||
for(auto *combo:findChildren<QComboBox*>())ApplicationStyle::styleComboBox(combo);
|
||||
refreshControls();
|
||||
}
|
||||
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();
|
||||
}
|
||||
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(){
|
||||
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()));
|
||||
}
|
||||
void MotorDebugWidget::refreshControls(){
|
||||
const bool busy=m_inFlight&&m_pendingOperation!="GetState";
|
||||
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));
|
||||
}
|
||||
void MotorDebugWidget::invoke(const QString &method){
|
||||
if(!m_connected||m_manager->currentData().toString().isEmpty()||(method!="ListMotors"&&m_motor->currentIndex()<0))return;
|
||||
if(m_inFlight){
|
||||
if(method!="quickStop"&&m_pendingOperation!="GetState")return;
|
||||
// Keep the transport serialized, but discard an obsolete sample reply
|
||||
// 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());
|
||||
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();
|
||||
m_client->requestMotorRpc(method,m_pendingManager,qMax(0,m_pendingNode),parameters,m_pending);
|
||||
}
|
||||
void MotorDebugWidget::reply(quint64 token,const QString &method,bool ok,const QVariantMap &response,const QString &detail){
|
||||
if(token!=m_pending||method!=m_pendingOperation||m_manager->currentData().toString()!=m_pendingManager)return;
|
||||
m_inFlight=false;if(method!="GetState")refreshControls();
|
||||
if(!ok){m_lastResult=method+": "+detail;m_status->setText(m_lastResult);emit statusMessage("ERROR",m_lastResult);return;}
|
||||
if(method=="ListMotors"){
|
||||
{QSignalBlocker b(m_motor);m_motor->clear();int selected=0;for(const auto &value:response.value("motors").toList()){
|
||||
const auto i=value.toMap();m_motor->addItem(QStringLiteral("%1 · ID %2").arg(i.value("jointName").toString()).arg(i.value("nodeId").toInt()),i);
|
||||
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;
|
||||
}
|
||||
if(m_motor->currentData().toMap().value("nodeId").toInt()!=m_pendingNode)return;
|
||||
const auto s=response.value("state").toMap();
|
||||
if(method=="GetState"){
|
||||
m_plot->append(s);const bool valid=s.value("feedbackValid").toBool();const double acceleration=accelerationEstimate();
|
||||
m_values->setText(QStringLiteral("位置 %1 rad · 速度 %2 rad/s · 加速度 %3 rad/s²(估算) · 力矩 %4 ‰\n驱动模式 %5 · 使能 %6 · 状态字 0x%7 · 错误码 0x%8")
|
||||
.arg(number(s,"position",valid),number(s,"velocity",valid),std::isfinite(acceleration)?QString::number(acceleration,'f',5):QStringLiteral("--"),number(s,"torque",s.value("torqueValid").toBool()))
|
||||
.arg(modeName(s.value("mode").toInt())).arg(s.value("statusValid").toBool()?(s.value("enabled").toBool()?QStringLiteral("是"):QStringLiteral("否")):QStringLiteral("未知"))
|
||||
.arg(s.value("statusValid").toBool()?QString::number(s.value("statusWord").toUInt(),16):QStringLiteral("----"))
|
||||
.arg(s.value("statusValid").toBool()?QString::number(s.value("errorCode").toUInt(),16):QStringLiteral("----")));
|
||||
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();}
|
||||
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";
|
||||
else if(method=="getTau")result=QString::number(s.value("torque").toDouble(),'g',12)+QStringLiteral(" ‰");
|
||||
else if(method=="getMode")result=modeName(s.value("mode").toInt())+" ("+s.value("mode").toString()+")";
|
||||
else if(method=="reachedTargetQ")result=response.value("reachedTarget").toBool()?QStringLiteral("已到位"):QStringLiteral("未到位");
|
||||
else if(result.isEmpty())result=QStringLiteral("接口调用成功");
|
||||
m_lastResult=method+": "+result;m_status->setText(m_lastResult);emit statusMessage("OK",m_lastResult);
|
||||
}
|
||||
void MotorDebugWidget::hideEvent(QHideEvent *event){m_acquire->setChecked(false);QWidget::hideEvent(event);}
|
||||
void MotorDebugWidget::exportCsv(){
|
||||
const QString path=QFileDialog::getSaveFileName(this,QStringLiteral("导出电机曲线"),"motor-feedback.csv","CSV (*.csv)");if(path.isEmpty())return;
|
||||
QSaveFile file(path);if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){AppMessageBox::warning(this,QStringLiteral("导出失败"),file.errorString());return;}
|
||||
QTextStream out(&file);out.setCodec("UTF-8");out<<"time_s,position_rad,velocity_rad_s,acceleration_estimate_rad_s2,torque_per_mille_rated\n";
|
||||
const double start=m_plot->samples.isEmpty()?0:m_plot->samples.first().t;
|
||||
for(const auto &s:m_plot->samples){out<<QString::number(s.t-start,'f',6);for(double v:{s.q,s.qd,s.qdd,s.tau})out<<","<<(std::isfinite(v)?QString::number(v,'g',15):QString());out<<"\n";}
|
||||
out.flush();if(!file.commit())AppMessageBox::warning(this,QStringLiteral("导出失败"),file.errorString());
|
||||
}
|
||||
48
src/motordebugwidget.h
Normal file
48
src/motordebugwidget.h
Normal file
@ -0,0 +1,48 @@
|
||||
#pragma once
|
||||
#include <QWidget>
|
||||
#include <QVariantMap>
|
||||
#include <QHash>
|
||||
#include <QElapsedTimer>
|
||||
class RobotClient;
|
||||
class QComboBox;
|
||||
class QDoubleSpinBox;
|
||||
class QCheckBox;
|
||||
class QSpinBox;
|
||||
class QLabel;
|
||||
class QTimer;
|
||||
class QPushButton;
|
||||
class MotorPlot;
|
||||
|
||||
class MotorDebugWidget final : public QWidget {
|
||||
Q_OBJECT
|
||||
friend struct MotorDebugTestAccess;
|
||||
public:
|
||||
explicit MotorDebugWidget(RobotClient*,QWidget *parent=nullptr);
|
||||
signals:
|
||||
void statusMessage(const QString&,const QString&);
|
||||
protected:
|
||||
void hideEvent(QHideEvent*) override;
|
||||
private:
|
||||
void invoke(const QString&);
|
||||
void reply(quint64,const QString&,bool,const QVariantMap&,const QString&);
|
||||
void refreshControls();
|
||||
void resetSelection();
|
||||
void clearSamples();
|
||||
void showInfo();
|
||||
void exportCsv();
|
||||
double accelerationEstimate() const;
|
||||
RobotClient *m_client;
|
||||
QComboBox *m_manager,*m_motor,*m_mode;
|
||||
QCheckBox *m_acquire;
|
||||
QSpinBox *m_rate,*m_slope;
|
||||
QLabel *m_values,*m_status,*m_info,*m_rateStatus;
|
||||
MotorPlot *m_plot;
|
||||
QTimer *m_timer;
|
||||
QHash<QString,QDoubleSpinBox*> m_parameters;
|
||||
QHash<QString,QPushButton*> m_rpcButtons;
|
||||
bool m_connected=false,m_inFlight=false;
|
||||
quint64 m_token=0,m_pending=0;
|
||||
QString m_pendingOperation,m_pendingManager,m_lastResult;
|
||||
int m_pendingNode=-1,m_samples=0;
|
||||
QElapsedTimer m_elapsed;
|
||||
};
|
||||
@ -27,6 +27,7 @@
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#ifdef CMVR_WITH_GRPC
|
||||
#include <grpcpp/grpcpp.h>
|
||||
@ -37,6 +38,7 @@
|
||||
#include "cmvr/api/agv_service.grpc.pb.h"
|
||||
#include "cmvr/api/arm_command.pb.h"
|
||||
#include "cmvr/api/arm_service.grpc.pb.h"
|
||||
#include "cmvr/api/motor_service.grpc.pb.h"
|
||||
#include "cmvr/api/camera_command.pb.h"
|
||||
#include "cmvr/api/camera_service.grpc.pb.h"
|
||||
#include "cmvr/api/dexhand_command.pb.h"
|
||||
@ -265,6 +267,7 @@ public:
|
||||
std::thread thread;
|
||||
#ifdef CMVR_WITH_GRPC
|
||||
grpc::ClientContext *context = nullptr;
|
||||
std::vector<std::shared_ptr<grpc::ClientContext>> groupContexts;
|
||||
std::mutex contextMutex;
|
||||
#endif
|
||||
};
|
||||
@ -1077,6 +1080,280 @@ public:
|
||||
#endif
|
||||
}
|
||||
|
||||
void motorRpc(const QString &method,const QString &manager,int node,const QVariantMap ¶ms,quint64 token)
|
||||
{
|
||||
const auto fail=[&](const QString &error) { motorRpcFinished(token,method,false,{},error); };
|
||||
if (!m_connected || manager.isEmpty()) { fail(QStringLiteral("服务未连接或电机系统为空")); return; }
|
||||
if (m_demoMode) { fail(QStringLiteral("电机调试需要连接支持 MotorService 的真实服务端")); return; }
|
||||
#ifdef CMVR_WITH_GRPC
|
||||
try {
|
||||
cmvr::api::MotorRequest request;
|
||||
fillHeader(request.mutable_header(),manager,method=="GetState"?500:5000);
|
||||
if (node<0 || node>255) { fail(QStringLiteral("电机 ID 超出范围")); return; }
|
||||
request.set_node_id(node);
|
||||
request.set_mode(params.value("mode").toInt());
|
||||
request.set_q(params.value("q").toDouble()); request.set_qd(params.value("qd").toDouble());
|
||||
request.set_qdd(params.value("qdd").toDouble()); request.set_tau(params.value("tau").toDouble());
|
||||
request.set_torque_slope(params.value("torqueSlope").toUInt());
|
||||
request.set_upper(params.value("upper").toDouble()); request.set_lower(params.value("lower").toDouble());
|
||||
grpc::ClientContext context; setDeadline(context,method=="GetState"?500:5000);
|
||||
auto stub=cmvr::api::MotorService::NewStub(m_channel);
|
||||
cmvr::api::MotorResponse response;
|
||||
cmvr::api::MotorListResponse list;
|
||||
grpc::Status status;
|
||||
bool accepted=false;
|
||||
QString applicationError;
|
||||
if (method=="ListMotors") {
|
||||
status=stub->ListMotors(&context,request,&list);
|
||||
accepted=list.header().success(); applicationError=QString::fromStdString(list.header().error_message());
|
||||
} else {
|
||||
#define MOTOR_CALL(name) if (method==#name) status=stub->name(&context,request,&response); else
|
||||
MOTOR_CALL(GetInfo) MOTOR_CALL(GetState) MOTOR_CALL(getMode) MOTOR_CALL(getQ) MOTOR_CALL(getQd)
|
||||
MOTOR_CALL(getTau) MOTOR_CALL(reachedTargetQ) MOTOR_CALL(setMode) MOTOR_CALL(torqueOn)
|
||||
MOTOR_CALL(torqueOff) MOTOR_CALL(brakeRelease) MOTOR_CALL(quickStop) MOTOR_CALL(calibrateZeroQ)
|
||||
MOTOR_CALL(commandProfilePosition) MOTOR_CALL(commandProfileVelocity)
|
||||
MOTOR_CALL(commandProfileTorque)
|
||||
MOTOR_CALL(commandCyclicPosition) MOTOR_CALL(commandCyclicVelocity) MOTOR_CALL(commandCyclicTorque)
|
||||
MOTOR_CALL(setLimitQ) MOTOR_CALL(setLimitQd) MOTOR_CALL(setLimitQdd)
|
||||
{ fail(QStringLiteral("未知电机接口")); return; }
|
||||
#undef MOTOR_CALL
|
||||
accepted=response.header().success(); applicationError=QString::fromStdString(response.header().error_message());
|
||||
}
|
||||
if (!status.ok()) { fail(QStringLiteral("gRPC %1:%2").arg(status.error_code()).arg(QString::fromStdString(status.error_message()))); return; }
|
||||
if (!accepted) { fail(applicationError.isEmpty()?QStringLiteral("电机接口未返回成功"):applicationError); return; }
|
||||
// Preserve typed feedback directly; no JSON round trip in the sampling path.
|
||||
const auto motorInfo=[](const cmvr::api::MotorInfo &i) {
|
||||
return QVariantMap{{"managerId",QString::fromStdString(i.manager_id())},{"nodeId",i.node_id()},
|
||||
{"jointName",QString::fromStdString(i.joint_name())},{"driver",QString::fromStdString(i.driver())},
|
||||
{"limitQLb",i.limit_q_lb()},{"limitQUb",i.limit_q_ub()},{"limitQd",i.limit_qd()},{"limitQdd",i.limit_qdd()}};
|
||||
};
|
||||
QVariantMap payload;
|
||||
if(method=="ListMotors") {
|
||||
QVariantList motors;
|
||||
for(const auto &i:list.motors())motors.append(motorInfo(i));
|
||||
payload.insert("motors",motors);
|
||||
} else {
|
||||
payload.insert("info",motorInfo(response.info()));
|
||||
payload.insert("reachedTarget",response.reached_target());
|
||||
payload.insert("driverAcknowledged",response.driver_acknowledged());
|
||||
const auto &s=response.state();
|
||||
payload.insert("state",QVariantMap{{"position",s.position()},{"velocity",s.velocity()},
|
||||
{"torque",s.torque()},{"feedbackValid",s.feedback_valid()},{"torqueValid",s.torque_valid()},
|
||||
{"torqueUnit",QString::fromStdString(s.torque_unit())},{"mode",s.mode()},
|
||||
{"statusWord",s.status_word()},{"errorCode",s.error_code()},{"statusValid",s.status_valid()},
|
||||
{"enabled",s.enabled()},{"fault",s.fault()},{"sampledAtS",s.sampled_at_s()}});
|
||||
}
|
||||
motorRpcFinished(token,method,true,payload,QString::fromStdString(response.detail()));
|
||||
} catch (const std::exception &e) { fail(QString::fromLocal8Bit(e.what())); }
|
||||
#else
|
||||
fail(QStringLiteral("此构建未启用 gRPC"));
|
||||
#endif
|
||||
}
|
||||
|
||||
void captureJointPoint(const QStringList &devices, quint64 token)
|
||||
{
|
||||
QVariantList targets;
|
||||
QString error;
|
||||
if (!m_connected || devices.isEmpty()) error = QStringLiteral("服务未连接或未选择机械臂");
|
||||
if (error.isEmpty() && m_demoMode) {
|
||||
for (const auto &id : devices) {
|
||||
const auto names=armJointNamesForDevice(id);
|
||||
QVariantList values;
|
||||
for (int i=0;i<names.size();++i) {
|
||||
const double phase=m_tick*0.035+i*0.46;
|
||||
values.append(i<m_demoTargets.size() ? m_demoTargets[i]+0.025*qSin(phase*1.7) : 0.36*qSin(phase));
|
||||
}
|
||||
targets.append(QVariantMap{{"deviceId",id},{"jointNames",names},{"positions",values}});
|
||||
}
|
||||
emit jointPointCaptured(token,targets,true,QStringLiteral("演示点位"));
|
||||
return;
|
||||
}
|
||||
#ifdef CMVR_WITH_GRPC
|
||||
QSet<QString> seen;
|
||||
for (const auto &id : devices) {
|
||||
if (!error.isEmpty()) break;
|
||||
if (id.trimmed().isEmpty() || seen.contains(id)) {
|
||||
error = QStringLiteral("请选择真实且不重复的机械臂"); break;
|
||||
}
|
||||
seen.insert(id);
|
||||
cmvr::api::JointRequest request;
|
||||
fillHeader(request.mutable_header(), id);
|
||||
cmvr::api::JointResponse response;
|
||||
grpc::ClientContext context;
|
||||
setDeadline(context, 2000);
|
||||
const auto status = m_arm->getJointState(&context, request, &response);
|
||||
if (!status.ok() || !response.header().success()) {
|
||||
error = id + QStringLiteral(":") + QString::fromStdString(
|
||||
status.ok() ? response.header().error_message() : status.error_message());
|
||||
break;
|
||||
}
|
||||
QVariantList names, positions;
|
||||
for (const auto &name : response.state().name()) names.append(QString::fromStdString(name));
|
||||
for (double value : response.state().position()) positions.append(value);
|
||||
targets.append(QVariantMap{{"deviceId", id}, {"jointNames", names},
|
||||
{"positions", positions}});
|
||||
}
|
||||
#else
|
||||
error = QStringLiteral("当前构建不支持 gRPC");
|
||||
#endif
|
||||
emit jointPointCaptured(token, error.isEmpty() ? targets : QVariantList(), error.isEmpty(), error);
|
||||
}
|
||||
|
||||
void moveJointPoint(const QVariantList &targets, double velocity, double acceleration, quint64 token)
|
||||
{
|
||||
const auto reject = [this, token](const QString &error) {
|
||||
emit jointPointMoveFinished(token, false, error);
|
||||
};
|
||||
if (!m_connected || targets.isEmpty()) { reject(QStringLiteral("服务未连接或点位为空")); return; }
|
||||
if (!std::isfinite(velocity) || velocity <= 0 || !std::isfinite(acceleration) || acceleration <= 0) {
|
||||
reject(QStringLiteral("速度和加速度必须为正数")); return;
|
||||
}
|
||||
QSet<QString> ids;
|
||||
for (const auto &value : targets) {
|
||||
const auto target = value.toMap();
|
||||
const auto id = target.value("deviceId").toString();
|
||||
const auto names = target.value("jointNames").toStringList();
|
||||
const auto positions = target.value("positions").toList();
|
||||
if (id.isEmpty() || ids.contains(id) || positions.isEmpty() || names.size() != positions.size()) {
|
||||
reject(QStringLiteral("点位的设备或关节数据无效")); return;
|
||||
}
|
||||
ids.insert(id);
|
||||
QSet<QString> uniqueNames;
|
||||
for (const auto &name : names) {
|
||||
if (name.trimmed().isEmpty() || uniqueNames.contains(name)) {
|
||||
reject(QStringLiteral("关节名称为空或重复")); return;
|
||||
}
|
||||
uniqueNames.insert(name);
|
||||
}
|
||||
for (const auto &p : positions) {
|
||||
bool ok = false;
|
||||
const double v = p.toDouble(&ok);
|
||||
if (!ok || !std::isfinite(v)) { reject(QStringLiteral("目标角度无效")); return; }
|
||||
}
|
||||
}
|
||||
if (m_demoMode) {
|
||||
for (const auto &value : targets) {
|
||||
const auto t=value.toMap();
|
||||
if (t.value("deviceId").toString()==m_armDeviceId || targets.size()==1) {
|
||||
m_demoTargets.clear();
|
||||
for (const auto &p : t.value("positions").toList()) m_demoTargets.append(p.toDouble());
|
||||
}
|
||||
}
|
||||
emit jointPointMoveFinished(token,true,QStringLiteral("演示点位已执行(未控制真实设备)"));
|
||||
return;
|
||||
}
|
||||
#ifdef CMVR_WITH_GRPC
|
||||
// Keep the existing global motion gate; one group owns one session.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_armMotionSessionMutex);
|
||||
if (m_armMotionSession && m_armMotionSession->running.load()) {
|
||||
reject(QStringLiteral("已有机械臂运动命令正在执行")); return;
|
||||
}
|
||||
}
|
||||
const auto session = prepareArmMotionSession(QStringLiteral("JointPoint"));
|
||||
if (!session) { reject(QStringLiteral("无法创建运动会话")); return; }
|
||||
const auto channel = m_channel;
|
||||
session->thread = std::thread([this, channel, session, targets, velocity, acceleration, token] {
|
||||
QStringList results;
|
||||
std::mutex resultMutex;
|
||||
const auto fail = [&](const QString &error) {
|
||||
{ std::lock_guard<std::mutex> lock(resultMutex); results.append(error); }
|
||||
session->stop.store(true);
|
||||
std::lock_guard<std::mutex> lock(session->contextMutex);
|
||||
for (const auto &c : session->groupContexts) c->TryCancel();
|
||||
};
|
||||
std::vector<std::thread> calls;
|
||||
bool dispatched = false;
|
||||
try {
|
||||
// Verify every recorded joint order before any arm is commanded.
|
||||
for (const auto &value : targets) {
|
||||
const auto t = value.toMap();
|
||||
const auto id = t.value("deviceId").toString();
|
||||
auto context=std::make_shared<grpc::ClientContext>();
|
||||
setDeadline(*context, 2000);
|
||||
{ std::lock_guard<std::mutex> lock(session->contextMutex);
|
||||
session->groupContexts.push_back(context);
|
||||
if (session->stop.load()) context->TryCancel(); }
|
||||
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);
|
||||
{ std::lock_guard<std::mutex> 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());
|
||||
fail(id + QStringLiteral(":读取机械臂信息失败:")
|
||||
+ (error.isEmpty() ? QStringLiteral("接口未返回成功") : error));
|
||||
break;
|
||||
}
|
||||
if (names != t.value("jointNames").toStringList()) {
|
||||
fail(id + QStringLiteral(":无法确认点位关节顺序,请检查连接及记录的关节名称")); break;
|
||||
}
|
||||
}
|
||||
if (!session->stop.load()) {
|
||||
dispatched = true;
|
||||
for (const auto &value : targets) {
|
||||
calls.emplace_back([&, value] {
|
||||
const auto t = value.toMap();
|
||||
const QString id = t.value("deviceId").toString();
|
||||
auto context=std::make_shared<grpc::ClientContext>();
|
||||
setDeadline(*context, kArmMotionTimeoutMs);
|
||||
{ std::lock_guard<std::mutex> lock(session->contextMutex);
|
||||
session->groupContexts.push_back(context);
|
||||
if (session->stop.load()) context->TryCancel(); }
|
||||
try {
|
||||
cmvr::api::MoveJ::Request request;
|
||||
fillHeader(request.mutable_header(), id, kArmMotionTimeoutMs);
|
||||
for (const auto &p : t.value("positions").toList()) request.mutable_target()->add_position(p.toDouble());
|
||||
request.mutable_options()->set_velocity(velocity);
|
||||
request.mutable_options()->set_acceleration(acceleration);
|
||||
request.mutable_options()->set_asynchronous(false);
|
||||
cmvr::api::MoveJ::Response response;
|
||||
if (!session->stop.load()) {
|
||||
const auto status = cmvr::api::ArmService::NewStub(channel)->moveJ(context.get(), request, &response);
|
||||
if (!status.ok() || !response.header().success()) {
|
||||
const auto error=QString::fromStdString(status.ok()
|
||||
? response.header().error_message() : status.error_message());
|
||||
fail(id + QStringLiteral(":")
|
||||
+ (error.isEmpty() ? QStringLiteral("MoveJ 未返回成功") : error));
|
||||
}
|
||||
}
|
||||
} catch (const std::exception &e) { fail(id + QStringLiteral(":") + QString::fromLocal8Bit(e.what())); }
|
||||
catch (...) { fail(id + QStringLiteral(":运动调用异常")); }
|
||||
std::lock_guard<std::mutex> lock(session->contextMutex);
|
||||
auto &cs = session->groupContexts;
|
||||
cs.erase(std::remove(cs.begin(), cs.end(), context), cs.end());
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (const std::exception &e) { fail(QString::fromLocal8Bit(e.what())); }
|
||||
catch (...) { fail(QStringLiteral("组合运动异常")); }
|
||||
for (auto &call : calls) if (call.joinable()) call.join();
|
||||
if (session->stop.load() && dispatched) {
|
||||
// Cancellation alone is not a hardware stop on every driver.
|
||||
for (const auto &value : targets) {
|
||||
grpc::ClientContext context;
|
||||
setDeadline(context, 1500);
|
||||
cmvr::api::CommandHeader::Request request;
|
||||
fillHeader(&request, value.toMap().value("deviceId").toString());
|
||||
cmvr::api::CommandHeader::Feedback response;
|
||||
const auto status = cmvr::api::ArmService::NewStub(channel)->stopMotion(&context, request, &response);
|
||||
if (!status.ok() || !response.success()) results.append(
|
||||
value.toMap().value("deviceId").toString()+QStringLiteral(":停止确认失败,请检查设备"));
|
||||
}
|
||||
}
|
||||
const bool ok = !session->stop.load();
|
||||
session->running.store(false);
|
||||
emit jointPointMoveFinished(token, ok, ok ? QStringLiteral("所有机械臂已完成点位")
|
||||
: (results.isEmpty() ? QStringLiteral("点位执行已取消") : results.join("\n")));
|
||||
});
|
||||
#else
|
||||
reject(QStringLiteral("当前构建不支持 gRPC"));
|
||||
#endif
|
||||
}
|
||||
|
||||
void moveJ(const QString &deviceId, const QVariantList &positions,
|
||||
double velocity, double acceleration)
|
||||
{
|
||||
@ -2907,6 +3184,9 @@ public:
|
||||
std::function<void(const QString &, const QString &, bool, const QString &)>
|
||||
configurationSaveFinished;
|
||||
std::function<void(const QString &, bool, const QString &)> commandFinished;
|
||||
std::function<void(quint64, const QVariantList &, bool, const QString &)> jointPointCaptured;
|
||||
std::function<void(quint64, bool, const QString &)> jointPointMoveFinished;
|
||||
std::function<void(quint64,const QString&,bool,const QVariantMap&,const QString&)> motorRpcFinished;
|
||||
std::function<void(const QString &, const QString &)> logMessage;
|
||||
|
||||
private:
|
||||
@ -3052,6 +3332,8 @@ private:
|
||||
std::lock_guard<std::mutex> lock(session->contextMutex);
|
||||
if (session->context)
|
||||
session->context->TryCancel();
|
||||
for (const auto &context : session->groupContexts)
|
||||
context->TryCancel();
|
||||
}
|
||||
#endif
|
||||
if (session->thread.joinable() &&
|
||||
@ -4401,6 +4683,15 @@ RobotClient::RobotClient(QObject *parent)
|
||||
emit commandFinished(command, success, detail);
|
||||
}, Qt::QueuedConnection);
|
||||
};
|
||||
m_worker->jointPointCaptured = [this](quint64 token, const QVariantList &targets, bool ok, const QString &detail) {
|
||||
QMetaObject::invokeMethod(this, [=] { emit jointPointCaptured(token, targets, ok, detail); }, Qt::QueuedConnection);
|
||||
};
|
||||
m_worker->jointPointMoveFinished = [this](quint64 token, bool ok, const QString &detail) {
|
||||
QMetaObject::invokeMethod(this, [=] { emit jointPointMoveFinished(token, ok, detail); }, Qt::QueuedConnection);
|
||||
};
|
||||
m_worker->motorRpcFinished=[this](quint64 token,const QString &method,bool ok,const QVariantMap &response,const QString &detail) {
|
||||
QMetaObject::invokeMethod(this,[=] { emit motorRpcFinished(token,method,ok,response,detail); },Qt::QueuedConnection);
|
||||
};
|
||||
m_worker->logMessage = [this](const QString &level, const QString &message) {
|
||||
QMetaObject::invokeMethod(this, [this, level, message]() {
|
||||
emit logMessage(level, message);
|
||||
@ -4424,6 +4715,9 @@ RobotClient::RobotClient(QObject *parent)
|
||||
connect(this, &RobotClient::speedJRequested, m_worker, &BackendWorker::speedJ);
|
||||
connect(this, &RobotClient::speedLRequested, m_worker, &BackendWorker::speedL);
|
||||
connect(this, &RobotClient::moveJRequested, m_worker, &BackendWorker::moveJ);
|
||||
connect(this,&RobotClient::motorRpcRequested,m_worker,&BackendWorker::motorRpc);
|
||||
connect(this, &RobotClient::jointPointCaptureRequested, m_worker, &BackendWorker::captureJointPoint);
|
||||
connect(this, &RobotClient::jointPointMoveRequested, m_worker, &BackendWorker::moveJointPoint);
|
||||
connect(this, &RobotClient::moveJPoseRequested, m_worker, &BackendWorker::moveJPose);
|
||||
connect(this, &RobotClient::torqueRequested, m_worker, &BackendWorker::torque);
|
||||
connect(this, &RobotClient::armStopRequested, m_worker, &BackendWorker::armStop);
|
||||
@ -4568,6 +4862,20 @@ void RobotClient::requestSpeedL(const QString &deviceId, const QVariantMap &velo
|
||||
emit armCommandStarting(deviceId);
|
||||
emit speedLRequested(deviceId, velocity, acceleration, duration, toolFrame);
|
||||
}
|
||||
void RobotClient::requestMotorRpc(const QString &method,const QString &manager,int node,const QVariantMap ¶meters,quint64 token)
|
||||
{
|
||||
emit motorRpcRequested(method,manager,node,parameters,token);
|
||||
}
|
||||
void RobotClient::requestJointPointCapture(const QStringList &devices, quint64 token)
|
||||
{
|
||||
emit jointPointCaptureRequested(devices, token);
|
||||
}
|
||||
void RobotClient::requestJointPointMove(const QVariantList &targets, double velocity,
|
||||
double acceleration, quint64 token)
|
||||
{
|
||||
for (const auto &target : targets) emit armCommandStarting(target.toMap().value("deviceId").toString());
|
||||
emit jointPointMoveRequested(targets, velocity, acceleration, token);
|
||||
}
|
||||
void RobotClient::requestMoveJ(const QString &deviceId, const QVariantList &positions,
|
||||
double velocity, double acceleration)
|
||||
{
|
||||
|
||||
@ -26,6 +26,11 @@ public:
|
||||
bool grpcAvailable() const;
|
||||
|
||||
public slots:
|
||||
void requestMotorRpc(const QString &method, const QString &managerId, int nodeId,
|
||||
const QVariantMap ¶meters, quint64 token);
|
||||
void requestJointPointCapture(const QStringList &devices, quint64 token);
|
||||
void requestJointPointMove(const QVariantList &targets, double velocity,
|
||||
double acceleration, quint64 token);
|
||||
void connectToServer(const QString &host, int port, bool demoMode);
|
||||
void disconnectFromServer();
|
||||
void setArmTelemetry(const QString &deviceId, bool enabled);
|
||||
@ -103,6 +108,16 @@ public slots:
|
||||
const QString &expectedRevision);
|
||||
|
||||
signals:
|
||||
void motorRpcRequested(const QString &method, const QString &managerId, int nodeId,
|
||||
const QVariantMap ¶meters, quint64 token);
|
||||
void motorRpcFinished(quint64 token, const QString &method, bool success,
|
||||
const QVariantMap &response, const QString &detail);
|
||||
void jointPointCaptureRequested(const QStringList &devices, quint64 token);
|
||||
void jointPointCaptured(quint64 token, const QVariantList &targets,
|
||||
bool success, const QString &detail);
|
||||
void jointPointMoveRequested(const QVariantList &targets, double velocity,
|
||||
double acceleration, quint64 token);
|
||||
void jointPointMoveFinished(quint64 token, bool success, const QString &detail);
|
||||
// Synchronous arbitration before manual arm commands enter the worker queue.
|
||||
void armCommandStarting(const QString &deviceId);
|
||||
// Emitted synchronously before a command that may select another active TCP.
|
||||
|
||||
@ -5,11 +5,13 @@
|
||||
#include "bioheadoperations.h"
|
||||
#include "bioheadwidget.h"
|
||||
#include "robotclient.h"
|
||||
#include "motordebugwidget.h"
|
||||
#include <QApplication>
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QAbstractItemView>
|
||||
#include <QDialog>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QTimer>
|
||||
#include <QDebug>
|
||||
@ -24,6 +26,318 @@
|
||||
#include <QGraphicsItem>
|
||||
#include <QGraphicsView>
|
||||
#include <QMouseEvent>
|
||||
#include <QWheelEvent>
|
||||
#include <QTableWidget>
|
||||
#include <QLineEdit>
|
||||
#include <QJsonDocument>
|
||||
#include <QElapsedTimer>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QSignalBlocker>
|
||||
#include <QFileInfo>
|
||||
#include <QDir>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <QSpinBox>
|
||||
#ifdef CMVR_WITH_GRPC
|
||||
#include <grpcpp/grpcpp.h>
|
||||
#include "cmvr/api/arm_service.grpc.pb.h"
|
||||
#include "cmvr/api/motor_service.grpc.pb.h"
|
||||
#endif
|
||||
|
||||
static bool waitFor(const std::function<bool()> &ready, int timeout=4000)
|
||||
{
|
||||
QElapsedTimer timer; timer.start();
|
||||
while (!ready() && timer.elapsed()<timeout) {
|
||||
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
return ready();
|
||||
}
|
||||
|
||||
struct MotorDebugTestAccess {
|
||||
static bool verify(){
|
||||
RobotClient c;QObject::disconnect(&c,&RobotClient::motorRpcRequested,nullptr,nullptr);
|
||||
MotorDebugWidget w(&c);w.resize(1450,1000);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");
|
||||
});
|
||||
c.connectionChanged(true,1,"mock");c.systemStatusReceived(0,0,0,{QVariantMap{{"deviceId","test_manager"},{"type",10}}});
|
||||
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<QCheckBox*>("motorDebugUnlock"))return false;
|
||||
const QStringList modeNames={QStringLiteral("未指定"),QStringLiteral("轮廓位置"),QStringLiteral("速度"),QStringLiteral("轮廓速度"),QStringLiteral("轮廓力矩"),QStringLiteral("回零"),QStringLiteral("位置插补"),QStringLiteral("周期位置"),QStringLiteral("周期速度"),QStringLiteral("周期力矩")};
|
||||
const QList<int> modeValues={0,1,2,3,4,5,7,8,9,10};
|
||||
if(w.m_mode->count()!=modeNames.size())return false;
|
||||
for(int i=0;i<modeNames.size();++i)
|
||||
if(w.m_mode->itemText(i)!=modeNames[i]||w.m_mode->itemData(i).toInt()!=modeValues[i])return false;
|
||||
for(auto *input:w.findChildren<QAbstractSpinBox*>()){
|
||||
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;
|
||||
}
|
||||
}
|
||||
w.m_parameters["q"]->findChild<QLineEdit*>()->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");
|
||||
}
|
||||
}
|
||||
// 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<QWidget*> controls={w.m_manager,w.m_motor,w.m_mode,w.m_parameters["q"],w.m_rpcButtons["torqueOn"]};
|
||||
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;
|
||||
}
|
||||
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");
|
||||
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;
|
||||
w.invoke("GetState");c.motorRpcFinished(token,"GetState",true,{{"state",QVariantMap{{"sampledAtS",1010.0},{"feedbackValid",false}}}},"");
|
||||
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");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
struct JointPointTestAccess {
|
||||
static bool verify() {
|
||||
int legacyCount=0;
|
||||
const QDir testDir=QFileInfo(QString::fromUtf8(__FILE__)).absoluteDir();
|
||||
for (const QString &relative : {QStringLiteral("../resources/joint_programs.json"),
|
||||
QStringLiteral("../bin/release/joint_programs.json")}) {
|
||||
QFile old(testDir.filePath(relative));
|
||||
if (!old.exists()) continue;
|
||||
if (!old.open(QIODevice::ReadOnly)) return false;
|
||||
const auto root=QJsonDocument::fromJson(old.readAll()).object();
|
||||
for (const auto &group : root.value("groups").toArray())
|
||||
for (const auto &value : group.toObject().value("points").toArray()) {
|
||||
const auto p=RecordedJointPoint::fromJson(value.toObject());
|
||||
if (!p.valid() || p.toJson()!=value.toObject()) return false;
|
||||
++legacyCount;
|
||||
}
|
||||
}
|
||||
if (!legacyCount) return false;
|
||||
RecordedJointPoint right;
|
||||
right.name="saved right"; right.deviceId="right"; right.jointNames=QStringList{"right_J1"}; right.positions={-1.249};
|
||||
RecordedJointPoint left;
|
||||
left.name="left"; left.deviceId="left"; left.jointNames=QStringList{"left_J1"}; left.positions={0.3};
|
||||
RecordedJointPoint both; both.name="both"; both.arms={right,left};
|
||||
if (!both.valid() || RecordedJointPoint::fromJson(both.toJson()).toJson()!=both.toJson()) return false;
|
||||
auto bad=both; bad.arms.append(right); if (bad.valid()) return false;
|
||||
bad=both; bad.arms[0].positions[0]=qQNaN(); if (bad.valid()) return false;
|
||||
|
||||
MainWindow w;
|
||||
QObject::disconnect(w.m_client,&RobotClient::jointPointMoveRequested,nullptr,nullptr);
|
||||
QObject::disconnect(w.m_client,&RobotClient::armStopRequested,nullptr,nullptr);
|
||||
w.m_jointProgramGroups.clear(); w.m_activeJointProgramGroup=0;
|
||||
MainWindow::JointProgramGroup g; g.name="test"; w.m_jointProgramGroups.append(g);
|
||||
w.m_recordedJointPoints={right,left}; w.refreshRecordedJointPoints();
|
||||
w.m_jointPointNameEdit->setText("both");
|
||||
w.m_jointPointTable->selectAll(); w.combineSelectedJointPoints();
|
||||
if (w.m_recordedJointPoints.size()!=3 || w.m_recordedJointPoints[0].toJson()!=right.toJson()
|
||||
|| w.m_recordedJointPoints[2].targets().size()!=2) return false;
|
||||
int requests=0; quint64 token=0;
|
||||
QObject::connect(w.m_client,&RobotClient::jointPointMoveRequested,&w,
|
||||
[&](const QVariantList &targets,double,double,quint64 t) { ++requests; token=t;
|
||||
if (targets.size()!=2) requests=-100; });
|
||||
w.dispatchJointPoint(2);
|
||||
if (requests!=1 || !w.m_jointPointMovePending) return false;
|
||||
w.finishJointPoint(token-1,true,"stale"); if (!w.m_jointPointMovePending) return false;
|
||||
QStringList stops;
|
||||
QObject::connect(w.m_client,&RobotClient::armStopRequested,&w,[&](const QString &id) { stops.append(id); });
|
||||
w.stopJointPointMotion(); w.stopJointPointLoop("test stop");
|
||||
if (stops.size()!=2 || !stops.contains("right") || !stops.contains("left")) return false;
|
||||
w.finishJointPoint(token,true,"late"); if (w.m_jointPointMovePending) return false;
|
||||
QFile saved(QCoreApplication::applicationDirPath()+"/joint_programs.json");
|
||||
if (!saved.open(QIODevice::ReadOnly)) return false;
|
||||
const auto points=QJsonDocument::fromJson(saved.readAll()).object().value("groups").toArray()[0].toObject().value("points").toArray();
|
||||
if (points.size()!=3 || points[0].toObject()!=right.toJson()) return false;
|
||||
// Only the aggregate reply advances the flow; manual MoveJ cannot do so.
|
||||
w.m_jointPointLoopRows={2,2}; w.m_jointPointExecutionWaits={0.02,0.0};
|
||||
w.m_jointPointLoopCursor=0; w.m_jointPointLoopActive=true;
|
||||
w.advanceJointPointLoop();
|
||||
if (requests!=2) return false;
|
||||
w.handleCommand("MoveJ",true,"unrelated reply");
|
||||
QCoreApplication::processEvents();
|
||||
if (requests!=2 || !w.m_jointPointMovePending) return false;
|
||||
w.finishJointPoint(token,true,"both finished");
|
||||
if (requests!=2 || !waitFor([&] { return requests==3; })) return false;
|
||||
w.finishJointPoint(token,false,"failure");
|
||||
if (w.m_jointPointLoopActive || w.m_jointPointMovePending) return false;
|
||||
{
|
||||
const QSignalBlocker block(w.m_armSideCombo), blockEdit(w.m_armIdEdit);
|
||||
w.m_armSideCombo->clear(); w.m_armSideCombo->addItem("Right arm","right");
|
||||
w.m_armSideCombo->addItem("Left arm","left"); w.m_armIdEdit->setText("right");
|
||||
}
|
||||
w.m_jointPointNameEdit->setText("capture selection");
|
||||
bool dialogChecked=false;
|
||||
QTimer::singleShot(0,&w,[&] {
|
||||
auto *dialog=qobject_cast<QDialog *>(QApplication::activeModalWidget());
|
||||
auto *list=dialog ? dialog->findChild<QListWidget *>() : nullptr;
|
||||
dialogChecked=list && list->count()==2 && list->item(0)->checkState()==Qt::Checked
|
||||
&& list->item(1)->checkState()==Qt::Unchecked && dialog->property("applicationChrome").toBool();
|
||||
if (dialog) { dialog->grab().save("joint-point-capture-dialog.png"); dialog->reject(); }
|
||||
});
|
||||
w.recordCurrentJointPoint();
|
||||
if (!dialogChecked) return false;
|
||||
qInfo()<<"PASS legacy point round-trip, composite creation, stale replies and group stop";
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
#ifdef CMVR_WITH_GRPC
|
||||
class MockDebugMotorService final : public cmvr::api::MotorService::Service {
|
||||
public:
|
||||
std::atomic<int> torqueWrites{0};
|
||||
grpc::Status ListMotors(grpc::ServerContext*,const cmvr::api::MotorRequest* r,cmvr::api::MotorListResponse* s) override {
|
||||
s->mutable_header()->set_success(true);auto *i=s->add_motors();i->set_manager_id(r->header().device_id());i->set_node_id(0);i->set_joint_name("test_J0");return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status GetState(grpc::ServerContext*,const cmvr::api::MotorRequest*,cmvr::api::MotorResponse* s) override {
|
||||
s->mutable_header()->set_success(true);s->mutable_state()->set_position(0.25);s->mutable_state()->set_velocity(-0.1);
|
||||
s->mutable_state()->set_torque(35);s->mutable_state()->set_feedback_valid(true);s->mutable_state()->set_torque_valid(true);
|
||||
s->mutable_state()->set_torque_unit("per_mille_rated");return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status commandProfileTorque(grpc::ServerContext*,const cmvr::api::MotorRequest* r,cmvr::api::MotorResponse* s) override {
|
||||
const bool ok=r->tau()==12.5&&r->torque_slope()==100;
|
||||
s->mutable_header()->set_success(ok);if(ok)++torqueWrites;return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status commandCyclicPosition(grpc::ServerContext*,const cmvr::api::MotorRequest* r,cmvr::api::MotorResponse* s) override {
|
||||
s->mutable_header()->set_success(r->q()==0.3&&r->qd()==-0.2);return grpc::Status::OK;
|
||||
}
|
||||
};
|
||||
class MockPointArm final : public cmvr::api::ArmService::Service {
|
||||
public:
|
||||
std::atomic<int> active{0}, peak{0}, moves{0}, stops{0};
|
||||
std::atomic<bool> failRight{false};
|
||||
grpc::Status GetArmInfo(grpc::ServerContext *,const cmvr::api::GetArmInfo::Request *r,
|
||||
cmvr::api::GetArmInfo::Response *s) override {
|
||||
s->mutable_header()->set_success(true);
|
||||
s->add_joint_names(r->header().device_id()+"_J1"); return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status getJointState(grpc::ServerContext *,const cmvr::api::JointRequest *r,
|
||||
cmvr::api::JointResponse *s) override {
|
||||
s->mutable_header()->set_success(true); s->mutable_state()->add_name(r->header().device_id()+"_J1");
|
||||
s->mutable_state()->add_position(0.25); return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status moveJ(grpc::ServerContext *c,const cmvr::api::MoveJ::Request *r,
|
||||
cmvr::api::MoveJ::Response *s) override {
|
||||
++moves; const int n=++active;
|
||||
int old=peak.load(); while (old<n && !peak.compare_exchange_weak(old,n)) {}
|
||||
const bool right=r->header().device_id()=="right";
|
||||
const int delay=right && failRight ? 25 : (right?180:60);
|
||||
for (int ms=0;ms<delay && !c->IsCancelled();ms+=5)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
--active;
|
||||
s->mutable_header()->set_success(!c->IsCancelled() && !(right && failRight));
|
||||
s->mutable_header()->set_error_message("mock failure"); return grpc::Status::OK;
|
||||
}
|
||||
grpc::Status stopMotion(grpc::ServerContext *,const cmvr::api::CommandHeader::Request *,
|
||||
cmvr::api::CommandHeader::Feedback *s) override {
|
||||
++stops; s->set_success(true); return grpc::Status::OK;
|
||||
}
|
||||
};
|
||||
|
||||
static bool verifyPointRpc()
|
||||
{
|
||||
QFile report("joint-point-rpc-test.txt"); report.open(QIODevice::WriteOnly|QIODevice::Text);
|
||||
QTextStream out(&report);
|
||||
out.setCodec("UTF-8");
|
||||
MockPointArm mock;
|
||||
MockDebugMotorService motorMock;
|
||||
grpc::ServerBuilder b; int port=0;
|
||||
b.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);
|
||||
b.RegisterService(&mock);b.RegisterService(&motorMock); auto server=b.BuildAndStart(); if (!server) return false;
|
||||
bool result=true;
|
||||
auto check=[&](bool ok,const QString &stage) { out<<(ok?"PASS ":"FAIL ")<<stage<<"\n"; out.flush(); result &= ok; };
|
||||
{
|
||||
RobotClient c; bool connected=false,done=false,success=false; quint64 last=0;
|
||||
QObject::connect(&c,&RobotClient::connectionChanged,&c,[&](bool ok,int,const QString &) { connected=ok; });
|
||||
QObject::connect(&c,&RobotClient::jointPointMoveFinished,&c,[&](quint64 t,bool ok,const QString &detail) {
|
||||
done=true; success=ok; last=t;
|
||||
out<<"reply "<<t<<" "<<ok<<" "<<detail<<"\n"; out.flush();
|
||||
});
|
||||
c.connectToServer("127.0.0.1",port,false);
|
||||
const bool hasConnection=waitFor([&] { return connected; });
|
||||
check(hasConnection,"connect");
|
||||
if (hasConnection) {
|
||||
RecordedJointPoint p; p.name="test";
|
||||
JointPointTarget a; a.deviceId="left"; a.jointNames=QStringList{"left_J1"}; a.positions={0.1};
|
||||
JointPointTarget d; d.deviceId="right"; d.jointNames=QStringList{"right_J1"}; d.positions={0.2};
|
||||
p.arms={a,d};
|
||||
int heartbeats=0; QTimer timer; timer.setInterval(10);
|
||||
QObject::connect(&timer,&QTimer::timeout,&c,[&] { ++heartbeats; }); timer.start();
|
||||
c.requestJointPointMove(p.commandTargets(),0.1,0.1,101);
|
||||
check(waitFor([&] { return done; }) && success && last==101
|
||||
&& mock.peak>=2 && mock.active==0 && heartbeats>=5,"concurrent move and responsive UI");
|
||||
done=false; const int moves=mock.moves;
|
||||
auto invalid=p; invalid.arms[1].jointNames=QStringList{"wrong"};
|
||||
c.requestJointPointMove(invalid.commandTargets(),0.1,0.1,102);
|
||||
check(waitFor([&] { return done; }) && !success && mock.moves==moves,"preflight blocks all motion");
|
||||
done=false; mock.failRight=true;
|
||||
c.requestJointPointMove(p.commandTargets(),0.1,0.1,103);
|
||||
check(waitFor([&] { return done; }) && !success && last==103
|
||||
&& waitFor([&] { return mock.active==0 && mock.stops>=2; }),"failure stops both arms");
|
||||
done=false; mock.failRight=false; const int stops=mock.stops;
|
||||
c.requestJointPointMove(p.commandTargets(),0.1,0.1,104);
|
||||
check(waitFor([&] { return mock.active>=2; }),"cancel during concurrent moves");
|
||||
c.requestArmStop("left");
|
||||
check(waitFor([&] { return done; }) && !success && last==104
|
||||
&& waitFor([&] { return mock.active==0 && mock.stops>=stops+2; }),"cancel stops both arms");
|
||||
bool captured=false;
|
||||
QObject::connect(&c,&RobotClient::jointPointCaptured,&c,
|
||||
[&](quint64 t,const QVariantList &targets,bool ok,const QString &) {
|
||||
captured=t==105 && ok && targets.size()==2;
|
||||
});
|
||||
c.requestJointPointCapture({"left","right"},105);
|
||||
check(waitFor([&] { return captured; }),"capture two arms");
|
||||
bool motorDone=false,motorOk=false;QVariantMap payload;
|
||||
QObject::connect(&c,&RobotClient::motorRpcFinished,&c,[&](quint64,const QString& method,bool ok,const QVariantMap &p,const QString& detail) {
|
||||
motorDone=true;motorOk=ok;payload=p;
|
||||
out<<"motor reply "<<method<<" "<<ok<<" "<<detail<<" "<<QJsonDocument::fromVariant(p).toJson(QJsonDocument::Compact)<<"\n";out.flush();
|
||||
});
|
||||
c.requestMotorRpc("ListMotors","test_manager",0,{},201);
|
||||
check(waitFor([&] {return motorDone;})&&motorOk&&payload.value("motors").toList().size()==1,"typed MotorService ListMotors");
|
||||
motorDone=false;c.requestMotorRpc("GetState","test_manager",0,{},202);
|
||||
check(waitFor([&] {return motorDone;})&&motorOk&&payload.value("state").toMap().value("torque").toDouble()==35,"position velocity torque feedback");
|
||||
motorDone=false;c.requestMotorRpc("commandProfileTorque","test_manager",0,{{"tau",12.5},{"torqueSlope",100}},203);
|
||||
check(waitFor([&] {return motorDone;})&&motorOk&&motorMock.torqueWrites==1,"per mille profile torque and slope");
|
||||
motorDone=false;c.requestMotorRpc("commandCyclicPosition","test_manager",0,{{"q",0.3},{"qd",-0.2}},204);
|
||||
check(waitFor([&] {return motorDone;})&&motorOk,"direct cyclic position parameters");
|
||||
}
|
||||
}
|
||||
server->Shutdown();
|
||||
if (result) qInfo()<<"PASS concurrent synchronous RPCs, responsive UI, preflight, error, cancel and capture";
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
|
||||
struct TaskFlowTestAccess
|
||||
{
|
||||
@ -236,6 +550,11 @@ int main(int argc, char **argv)
|
||||
application.setApplicationName(QStringLiteral("CMVR Theme Verification"));
|
||||
application.setOrganizationName(QStringLiteral("CMVR Tests"));
|
||||
ApplicationStyle::install(application);
|
||||
if (!MotorDebugTestAccess::verify()) return 14;
|
||||
if (!JointPointTestAccess::verify()) return 12;
|
||||
#ifdef CMVR_WITH_GRPC
|
||||
if (!verifyPointRpc()) return 13;
|
||||
#endif
|
||||
if (!TaskFlowTestAccess::verify()) return 11;
|
||||
if (!verifyBioheadPage()) return 10;
|
||||
if (!verifyBioheadTaskRun()) return 9;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user