From 8518b999ffdcb524416d918eb69299ad8502bcae Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Tue, 10 Nov 2026 16:40:39 +0800 Subject: [PATCH] feat(arm): add pose MoveJ and action queue testing with joint limits --- CmvrControlStation.pro | 3 + protos/cmvr/api/arm_command.proto | 23 ++++ protos/cmvr/api/arm_service.proto | 3 +- protos/cmvr/api/system_command.proto | 51 ++++++++ protos/cmvr/api/system_service.proto | 1 + src/actionqueuetestwidget.cpp | 180 +++++++++++++++++++++++++++ src/actionqueuetestwidget.h | 36 ++++++ src/mainwindow.cpp | 130 +++++++++++++++++-- src/mainwindow.h | 10 +- src/mainwindow_ui.cpp | 44 +++++-- src/robotclient.cpp | 46 +++++-- src/robotclient.h | 8 +- src/usercoordinatewidget.cpp | 18 ++- src/usercoordinatewidget.h | 3 +- tests/handeyeintegration_test.cpp | 2 +- tests/tcpintegration_test.cpp | 4 +- 16 files changed, 515 insertions(+), 47 deletions(-) create mode 100644 src/actionqueuetestwidget.cpp create mode 100644 src/actionqueuetestwidget.h diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index 5eb83bb..6a13967 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -384,3 +384,6 @@ SOURCES += src/motordebugwidget.cpp src/motorplot.cpp HEADERS += src/motorplot.h SOURCES += src/usercoordinatewidget.cpp HEADERS += src/usercoordinatewidget.h src/usercoordinatestore.h + +SOURCES += src/actionqueuetestwidget.cpp +HEADERS += src/actionqueuetestwidget.h diff --git a/protos/cmvr/api/arm_command.proto b/protos/cmvr/api/arm_command.proto index 9cbf483..5b44712 100644 --- a/protos/cmvr/api/arm_command.proto +++ b/protos/cmvr/api/arm_command.proto @@ -398,6 +398,15 @@ message JointResponse { } // 机械臂静态能力与 SDK 自动识别信息。 +// Per-joint position limits, matched by name; radians. Missing/invalid limits are not zero limits. +message ArmJointLimit { + string joint_name = 1; + bool position_limits_available = 2; + double lower = 3; + double upper = 4; + // aubo_sdk: controller readback; driver_model: driver model/configuration/URDF, not hardware readback. + string source = 5; +} message GetArmInfo { message Request { CommandHeader.Request header = 1; @@ -416,6 +425,7 @@ message GetArmInfo { string description_id = 10; bool detected_from_sdk = 11; string driver_type = 12; + repeated ArmJointLimit joint_limits = 13; } } @@ -539,3 +549,16 @@ message ComputeForwardKinematics { TransformMatrix4x4 matrix = 2; } } + +// Joint-space motion to an absolute TCP pose in an explicitly applied coordinate. +// AUBO converts with SDK Math, solves IK near current joints, then calls moveJoint. +message MoveJPose { + message Request { + CommandHeader.Request header = 1; + CartesianPose target = 2; // Absolute TCP pose: m / rad, RzRyRx. + MotionOptions options = 3; // Joint limits: rad/s, rad/s^2; AUBO does not use jerk. + string user_coordinate_name = 4; // Required. Apply this saved/builtin coordinate first. + uint64 user_coordinate_revision = 5; // 0 = latest saved revision; active revision must match. + } + message Response { CommandHeader.Feedback header = 1; } +} diff --git a/protos/cmvr/api/arm_service.proto b/protos/cmvr/api/arm_service.proto index 17cbf69..d75fa4b 100644 --- a/protos/cmvr/api/arm_service.proto +++ b/protos/cmvr/api/arm_service.proto @@ -14,8 +14,9 @@ service ArmService { // 清除机械臂可恢复故障;不包含数值参数,无单位。 rpc clearFault(CommandHeader.Request) returns (CommandHeader.Feedback); // 执行关节空间点到点运动;目标角度单位为 rad。 + rpc moveJPose(MoveJPose.Request) returns (MoveJPose.Response); rpc moveJ(MoveJ.Request) returns (MoveJ.Response); - // 执行 TCP 笛卡尔直线运动;位置单位为 m,姿态单位为 rad。 + // 执行所选坐标系下的绝对TCP目标直线运动,位置m、姿态rad;不接受增量目标。 rpc moveL(MoveL.Request) returns (MoveL.Response); // 查询可用基准坐标系名称;返回名称列表,无单位。 rpc ListBaseFrame(ListFrame.Request) returns (ListFrame.Response); diff --git a/protos/cmvr/api/system_command.proto b/protos/cmvr/api/system_command.proto index 277e856..163d35a 100644 --- a/protos/cmvr/api/system_command.proto +++ b/protos/cmvr/api/system_command.proto @@ -1,5 +1,6 @@ syntax = "proto3"; +import "cmvr/api/arm_command.proto"; import "cmvr/api/common.proto"; package cmvr.api; @@ -101,3 +102,53 @@ message StopAllCommand { CommandHeader.Feedback header = 1; } } + +enum ActionResultCode { + ACTION_RESULT_CODE_UNSPECIFIED = 0; + ACTION_RESULT_CODE_COMPLETED = 1; + ACTION_RESULT_CODE_FAILED = 2; + ACTION_RESULT_CODE_CANCELED = 3; + ACTION_RESULT_CODE_TIMED_OUT = 4; + ACTION_RESULT_CODE_REJECTED = 5; +} + +message ActionStep { + reserved 1; + reserved "step_id"; + + // Zero inherits the remaining ActionQueue timeout. + uint32 timeout_ms = 2; + + oneof command { + MoveJ.Request arm_move_j = 10; + MoveL.Request arm_move_l = 11; + MoveJPose.Request arm_move_j_pose = 13; + // Apply a saved coordinate before subsequent arm steps. Uses header.device_id, + // name and expected_revision (0 = latest); coordinate payload is not accepted. + // AUBO MoveL without legacy frame overrides follows this selection until switched. + // Switching does not move the arm. A failure aborts the remaining queue. + UserCoordinateSystemCommand.Request arm_apply_user_coordinate = 12; + } +} + +message ActionQueueCommand { + message Request { + reserved 1; + reserved "action_id"; + + repeated ActionStep steps = 2; + // Zero uses the server default. + uint32 total_timeout_ms = 3; + } + + message Feedback { + CommandHeader.Feedback header = 1; + + reserved 2; + reserved "action_id"; + + uint32 completed_steps = 3; + optional uint32 failed_step_index = 4; + ActionResultCode result = 5; + } +} diff --git a/protos/cmvr/api/system_service.proto b/protos/cmvr/api/system_service.proto index 84d1c9b..87914d9 100644 --- a/protos/cmvr/api/system_service.proto +++ b/protos/cmvr/api/system_service.proto @@ -7,6 +7,7 @@ package cmvr.api; service SystemService { + rpc ExecuteActionQueue(ActionQueueCommand.Request) returns (ActionQueueCommand.Feedback) {} rpc GetSystemInfo(GetSystemInfoCommand.Request) returns (GetSystemInfoCommand.Feedback) {} rpc GetSystemStatus(GetSystemStatusCommand.Request) returns (GetSystemStatusCommand.Feedback) {} diff --git a/src/actionqueuetestwidget.cpp b/src/actionqueuetestwidget.cpp new file mode 100644 index 0000000..40b4849 --- /dev/null +++ b/src/actionqueuetestwidget.cpp @@ -0,0 +1,180 @@ +#include "actionqueuetestwidget.h" +#include "robotclient.h" +#include "appmessagebox.h" +#include "cmvr/api/system_service.grpc.pb.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +QString json(const google::protobuf::Message& message) { + std::string text; google::protobuf::util::JsonPrintOptions options; + options.add_whitespace=true; options.preserve_proto_field_names=true; + google::protobuf::util::MessageToJsonString(message,&text,options); + return QString::fromStdString(text); +} +QString caption(const QString& name) { + if(name=="__builtin_base__")return QStringLiteral("基座坐标系"); + if(name=="__builtin_tool__")return QStringLiteral("工具坐标系"); + return name; +} +} + +ActionQueueTestWidget::ActionQueueTestWidget(RobotClient* client,QWidget* parent) + :QWidget(parent),m_client(client) { + auto* layout=new QVBoxLayout(this); + auto* group=new QGroupBox(QStringLiteral("服务端动作队列 · 应用坐标系 → 末端位姿运动"),this); + auto* grid=new QGridLayout(group); + m_coordinate=new QComboBox(group);m_refresh=new QPushButton(QStringLiteral("刷新坐标系"),group); + grid->addWidget(new QLabel(QStringLiteral("参考坐标系"),group),0,0); + grid->addWidget(m_coordinate,0,1,1,4);grid->addWidget(m_refresh,0,5); + const char* axes[]={"X · m","Y · m","Z · m","RX · rad","RY · rad","RZ · rad"}; + for(int i=0;i<6;++i){ + grid->addWidget(new QLabel(QString::fromUtf8(axes[i]),group),1,i); + auto* input=new QDoubleSpinBox(group);input->setDecimals(6);input->setRange(-100000,100000); + input->setButtonSymbols(QAbstractSpinBox::NoButtons);m_target[i]=input;grid->addWidget(input,2,i); + connect(input,QOverload::of(&QDoubleSpinBox::valueChanged),this,[this]{preview();}); + } + m_pose=new QPushButton(QStringLiteral("获取所选坐标系当前位姿并填入目标"),group); + grid->addWidget(m_pose,3,0,1,6); + m_speed=new QDoubleSpinBox(group);m_speed->setDecimals(3);m_speed->setRange(.001,2);m_speed->setValue(.005);m_speed->setSuffix(" m/s"); + m_accel=new QDoubleSpinBox(group);m_accel->setDecimals(3);m_accel->setRange(.001,10);m_accel->setValue(.01);m_accel->setSuffix(" m/s²"); + m_deadline=new QSpinBox(group);m_deadline->setRange(1,1800);m_deadline->setValue(120);m_deadline->setSuffix(" s"); + grid->addWidget(new QLabel(QStringLiteral("速度"),group),4,0);grid->addWidget(m_speed,4,1); + grid->addWidget(new QLabel(QStringLiteral("加速度"),group),4,2);grid->addWidget(m_accel,4,3); + grid->addWidget(new QLabel(QStringLiteral("队列总超时"),group),4,4);grid->addWidget(m_deadline,4,5); + m_motion=new QComboBox(group);m_motion->addItem(QStringLiteral("MoveL · 直线运动"));m_motion->addItem(QStringLiteral("MoveJ · 末端位姿关节运动")); + grid->addWidget(new QLabel(QStringLiteral("运动方式"),group),5,0);grid->addWidget(m_motion,5,1,1,5); + layout->addWidget(group); + auto* tip=new QLabel(QStringLiteral("目标是所选坐标系下的完整绝对 TCP 位姿。队列先应用坐标系,再执行所选运动。MoveJ 经服务端 SDK 逆解,路径不保证直线;其速度/加速度是关节参数。"),this); + tip->setWordWrap(true);layout->addWidget(tip); + auto* buttons=new QHBoxLayout; + m_execute=new QPushButton(QStringLiteral("执行两步动作队列"),this);m_execute->setObjectName("primaryButton"); + m_cancel=new QPushButton(QStringLiteral("取消当前队列"),this);m_cancel->setObjectName("dangerButton"); + buttons->addWidget(m_execute);buttons->addWidget(m_cancel);buttons->addStretch();layout->addLayout(buttons); + m_status=new QLabel(QStringLiteral("尚未执行"),this);m_status->setWordWrap(true);m_status->setTextInteractionFlags(Qt::TextSelectableByMouse);layout->addWidget(m_status); + auto* documents=new QHBoxLayout; + auto* requestGroup=new QGroupBox(QStringLiteral("请求 JSON · 可复制"),this);auto* requestLayout=new QVBoxLayout(requestGroup); + m_request=new QPlainTextEdit(requestGroup);m_request->setReadOnly(true);requestLayout->addWidget(m_request); + auto* responseGroup=new QGroupBox(QStringLiteral("原始反馈 / 错误 · 可复制"),this);auto* responseLayout=new QVBoxLayout(responseGroup); + m_response=new QPlainTextEdit(responseGroup);m_response->setReadOnly(true);responseLayout->addWidget(m_response); + documents->addWidget(requestGroup);documents->addWidget(responseGroup);layout->addLayout(documents,1); + connect(m_refresh,&QPushButton::clicked,this,[this]{query("list");}); + connect(m_pose,&QPushButton::clicked,this,[this]{query("selected_pose");}); + connect(m_coordinate,QOverload::of(&QComboBox::currentIndexChanged),this,[this]{preview();updateActions();}); + for(auto* b:{m_speed,m_accel})connect(b,QOverload::of(&QDoubleSpinBox::valueChanged),this,[this]{preview();}); + connect(m_deadline,QOverload::of(&QSpinBox::valueChanged),this,[this]{preview();}); + connect(m_motion,QOverload::of(&QComboBox::currentIndexChanged),this,[this](int index){ + if(m_jointMode){m_jointVelocity=m_speed->value();m_jointAcceleration=m_accel->value();} + else{m_linearVelocity=m_speed->value();m_linearAcceleration=m_accel->value();} + m_jointMode=index==1; + m_speed->setRange(.001,m_jointMode?10:2);m_accel->setRange(.001,m_jointMode?100:10); + m_speed->setSuffix(m_jointMode?" rad/s":" m/s");m_accel->setSuffix(m_jointMode?" rad/s²":" m/s²"); + m_speed->setValue(m_jointMode?m_jointVelocity:m_linearVelocity);m_accel->setValue(m_jointMode?m_jointAcceleration:m_linearAcceleration);preview(); + }); + connect(m_execute,&QPushButton::clicked,this,[this]{execute();}); + connect(m_cancel,&QPushButton::clicked,this,[this]{if(m_context){m_context->TryCancel();m_status->setText(QStringLiteral("正在取消,等待服务端返回;取消不代表已确认停稳。"));}}); + connect(client,&RobotClient::rpcFinished,this,[this](const QString& service,const QString& token,bool ok,const QString& text){ + if(service!="cmvr.user_coordinates"||m_pending.isEmpty()||token!=QString::number(m_token))return; + const QString operation=m_pending;m_pending.clear(); + const auto r=QJsonDocument::fromJson(text.toUtf8()).object(); + if(!ok||!r.value("success").toBool()||r.value("device_id").toString()!=m_device){m_status->setText(QStringLiteral("读取失败:")+text);updateActions();return;} + if(operation=="list"){ + const QString previous=m_coordinate->currentData().toString();m_profiles=r.value("coordinates").toArray();m_coordinate->clear(); + for(const auto& v:m_profiles){const auto p=v.toObject();const QString name=p.value("name").toString();m_coordinate->addItem(caption(name)+QStringLiteral(" · 版本 ")+p.value("revision").toVariant().toString(),name);} + const int at=m_coordinate->findData(previous);if(at>=0)m_coordinate->setCurrentIndex(at); + m_status->setText(QStringLiteral("已读取服务端坐标系。")); + }else{ + const auto pose=r.value("pose").toArray();QString expected=m_coordinate->currentData().toString();if(expected=="__builtin_base__")expected="base"; + bool valid=pose.size()==6&&r.value("reference").toString()==expected&&r.value("end_frame").toString()=="tcp"; + for(const auto& v:pose)valid=valid&&v.isDouble()&&std::isfinite(v.toDouble()); + if(valid){for(int i=0;i<6;++i)m_target[i]->setValue(pose[i].toDouble());m_status->setText(QStringLiteral("已填入所选坐标系下当前 TCP 绝对位姿,请按需要调整目标。"));} + else m_status->setText(QStringLiteral("位姿反馈参考系或数值无效,未填入目标。")); + } + preview();updateActions(); + }); + preview();updateActions(); +} +ActionQueueTestWidget::~ActionQueueTestWidget(){ + if(m_context)m_context->TryCancel(); + if(m_thread){m_thread->wait();delete m_thread;} +} +void ActionQueueTestWidget::setContext(const QString& endpoint,const QString& device,bool connected){ + if(endpoint==m_endpoint&&device==m_device&&connected==m_connected)return; + if(m_context)m_context->TryCancel(); + ++m_token;m_pending.clear();m_endpoint=endpoint;m_device=device;m_connected=connected;m_profiles={};m_coordinate->clear(); + m_status->setText(QStringLiteral("连接或设备已变化,请刷新坐标系。"));preview();updateActions(); +} +void ActionQueueTestWidget::updateActions(){ + const bool ready=m_connected&&!m_device.isEmpty()&&!m_busy&&m_pending.isEmpty(); + m_refresh->setEnabled(ready);m_coordinate->setEnabled(!m_busy&&m_pending.isEmpty()); + m_pose->setEnabled(ready&&m_coordinate->currentIndex()>=0);m_execute->setEnabled(ready&&m_coordinate->currentIndex()>=0); + m_cancel->setEnabled(m_busy);for(auto* b:m_target)b->setEnabled(!m_busy); + m_speed->setEnabled(!m_busy);m_accel->setEnabled(!m_busy);m_deadline->setEnabled(!m_busy);m_motion->setEnabled(!m_busy); +} +void ActionQueueTestWidget::preview(){ + QJsonObject target;const char* keys[]={"x","y","z","rx","ry","rz"};for(int i=0;i<6;++i)target[keys[i]]=m_target[i]->value(); + const int i=m_coordinate->currentIndex();const auto profile=i>=0&&icurrentData().toString()},{"expected_revision",profile.value("revision").toVariant().toString()}}; + QJsonObject move{{"header",header},{"target",target},{"options",QJsonObject{{"velocity",m_speed->value()},{"acceleration",m_accel->value()}}}}; + if(m_jointMode){move.insert("user_coordinate_name",m_coordinate->currentData().toString());move.insert("user_coordinate_revision",profile.value("revision").toVariant().toString());} + const QJsonObject request{{"steps",QJsonArray{QJsonObject{{"arm_apply_user_coordinate",apply}},QJsonObject{{m_jointMode?"arm_move_j_pose":"arm_move_l",move}}}},{"total_timeout_ms",m_deadline->value()*1000}}; + m_request->setPlainText(QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Indented))); +} +void ActionQueueTestWidget::query(const QString& operation){ + if(m_busy||!m_pending.isEmpty()||!m_connected)return; + m_token=qMax(m_token+1,quint64(QDateTime::currentMSecsSinceEpoch()));m_pending=operation; + const quint64 token=m_token; + m_client->requestUserCoordinates(m_device,{{"operation",operation},{"name",m_coordinate->currentData().toString()}},token); + m_status->setText(QStringLiteral("读取中…"));updateActions(); + QTimer::singleShot(25000,this,[this,token]{if(token==m_token&&!m_pending.isEmpty()){m_pending.clear();++m_token;m_status->setText(QStringLiteral("读取超时,请刷新。"));updateActions();}}); +} +void ActionQueueTestWidget::execute(){ + if(m_busy||!m_pending.isEmpty()||!m_connected||m_coordinate->currentIndex()<0)return; + preview(); + cmvr::api::ActionQueueCommand::Request request; + const auto parsed=google::protobuf::util::JsonStringToMessage(m_request->toPlainText().toStdString(),&request); + if(!parsed.ok()){m_status->setText(QString::fromStdString(parsed.ToString()));return;} + if(AppMessageBox::question(this,QStringLiteral("执行动作队列"),QStringLiteral("将先应用“%1”,再执行 %2 到界面完整绝对目标。速度 %3 %4。请确认目标和现场空间安全;MoveJ 路径不保证直线。").arg(caption(m_coordinate->currentData().toString()),m_jointMode?QStringLiteral("末端位姿 MoveJ"):QStringLiteral("MoveL")).arg(m_speed->value()).arg(m_jointMode?"rad/s":"m/s"))!=AppMessageBox::Yes)return; + // The exact transmitted headers are included in the visible request for diagnosis. + const auto now=QDateTime::currentMSecsSinceEpoch(); + for(auto& step:*request.mutable_steps()){ + auto* h=step.has_arm_move_l()?step.mutable_arm_move_l()->mutable_header():step.has_arm_move_j_pose()?step.mutable_arm_move_j_pose()->mutable_header():step.mutable_arm_apply_user_coordinate()->mutable_header(); + h->set_command_id(QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString()); + h->mutable_timestamp()->set_seconds(now/1000);h->mutable_timestamp()->set_nanos((now%1000)*1000000); + } + m_request->setPlainText(json(request));m_response->clear();m_busy=true; + m_status->setText(QStringLiteral("队列执行中,等待服务端返回。"));updateActions(); + if(m_thread){m_thread->wait();delete m_thread;} + m_context=std::make_shared(); + m_context->set_deadline(std::chrono::system_clock::now()+std::chrono::milliseconds(request.total_timeout_ms()+5000)); + const auto context=m_context;const QString endpoint=m_endpoint; + m_thread=QThread::create([this,request,context,endpoint]{ + auto stub=cmvr::api::SystemService::NewStub(grpc::CreateChannel(endpoint.toStdString(),grpc::InsecureChannelCredentials())); + cmvr::api::ActionQueueCommand::Feedback feedback; + const auto status=stub->ExecuteActionQueue(context.get(),request,&feedback); + const QString response=json(feedback); + const bool ok=status.ok()&&feedback.header().success()&&feedback.result()==cmvr::api::ACTION_RESULT_CODE_COMPLETED; + const QString detail=status.ok()?QStringLiteral("%1 · 完成 %2 / 2 步%3 · %4").arg(ok?QStringLiteral("成功"):QStringLiteral("失败")).arg(feedback.completed_steps()).arg(feedback.has_failed_step_index()?QStringLiteral(" · 失败节点 %1").arg(feedback.failed_step_index()+1):QString()).arg(QString::fromStdString(feedback.header().error_message())):QStringLiteral("gRPC 错误 %1:%2;执行结果未确认,请检查服务端状态。").arg(status.error_code()).arg(QString::fromStdString(status.error_message())); + QMetaObject::invokeMethod(this,[this,response,detail]{m_busy=false;m_context.reset();m_response->setPlainText(response+"\n"+detail);m_status->setText(detail);updateActions();},Qt::QueuedConnection); + }); + m_thread->start(); +} diff --git a/src/actionqueuetestwidget.h b/src/actionqueuetestwidget.h new file mode 100644 index 0000000..8661a67 --- /dev/null +++ b/src/actionqueuetestwidget.h @@ -0,0 +1,36 @@ +#pragma once +#include +#include +#include +#include +class RobotClient; class QComboBox; class QDoubleSpinBox; class QSpinBox; +class QPlainTextEdit; class QPushButton; class QLabel; class QThread; +namespace grpc { class ClientContext; } +class ActionQueueTestWidget final : public QWidget { +public: + explicit ActionQueueTestWidget(RobotClient*, QWidget* = nullptr); + ~ActionQueueTestWidget() override; + void setContext(const QString&, const QString&, bool); +private: + RobotClient* m_client; + QString m_endpoint, m_device, m_pending; + bool m_connected=false, m_busy=false; + quint64 m_token=0; + QJsonArray m_profiles; + QComboBox* m_coordinate; + QComboBox* m_motion; + bool m_jointMode=false; + double m_linearVelocity=.005,m_linearAcceleration=.01,m_jointVelocity=.1,m_jointAcceleration=.5; + std::array m_target; + QDoubleSpinBox *m_speed,*m_accel; + QSpinBox* m_deadline; + QPushButton *m_refresh,*m_pose,*m_execute,*m_cancel; + QPlainTextEdit *m_request,*m_response; + QLabel* m_status; + QThread* m_thread=nullptr; + std::shared_ptr m_context; + void updateActions(); + void preview(); + void query(const QString&); + void execute(); +}; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 585ee69..e0f50c3 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -70,6 +70,8 @@ #include #include #include +#include +#include #include #include #include @@ -2139,6 +2141,51 @@ void MainWindow::updateConnection(bool connected, int latencyMs, const QString & appendLog(connected ? QStringLiteral("INFO") : QStringLiteral("WARN"), detail); } +void MainWindow::setArmJointLimit(int row, double lower, double upper, const QString &source) +{ + if(row<0 || row>=m_targetRadianSpins.size() || !qIsFinite(lower) || !qIsFinite(upper) || lower>=upper)return; + auto *rad=m_targetRadianSpins[row];auto *deg=m_targetSpins[row]; + auto *slider=qobject_cast(m_motionTable->cellWidget(row,5)); + auto *limits=m_motionTable->cellWidget(row,6); + const double previous=rad->value(); + const QSignalBlocker br(rad),bd(deg),bs(slider); + rad->setRange(lower,upper);rad->setProperty("hasLimit",true); + deg->setRange(qRadiansToDegrees(rad->minimum()),qRadiansToDegrees(rad->maximum())); + rad->setValue(previous);deg->setValue(qRadiansToDegrees(rad->value())); + slider->setValue(qRound((rad->value()-rad->minimum())/(rad->maximum()-rad->minimum())*10000)); + slider->setEnabled(m_connected); + limits->setProperty("invalid",false); + limits->findChild("lower")->setText(QString::number(lower,'g',12)); + limits->findChild("upper")->setText(QString::number(upper,'g',12)); + const QString hint=QStringLiteral("%1:[%2, %3] rad;仅编辑目标,点击 MoveJ 执行").arg(source).arg(lower).arg(upper); + limits->setToolTip(hint);slider->setToolTip(hint); + if(previous!=rad->value())appendLog(QStringLiteral("WARN"),QStringLiteral("%1 目标超出新限位,已调整为 %2 rad").arg(m_activeArmJointNames[row]).arg(rad->value())); +} + +void MainWindow::refreshArmJointLimits() +{ + for(int row=0;rowproperty("serverLimit").toBool()){ + spin->setProperty("serverLimit",false);spin->setProperty("hasLimit",false); + spin->setRange(-1e7,1e7);m_targetSpins[row]->setRange(-1e9,1e9); + m_motionTable->cellWidget(row,5)->setEnabled(false); + for(auto *edit:m_motionTable->cellWidget(row,6)->findChildren()){edit->clear();edit->setReadOnly(false);} + } + continue; + } + const double lower=limit.value("lower").toDouble(),upper=limit.value("upper").toDouble(); + auto *spin=m_targetRadianSpins[row]; + if(spin->property("hasLimit").toBool() && spin->property("serverLimit").toBool() && + qAbs(spin->minimum()-lower)<1e-6 && qAbs(spin->maximum()-upper)<1e-6)continue; + setArmJointLimit(row,lower,upper,QStringLiteral("服务端:%1").arg(limit.value("source").toString())); + spin->setProperty("serverLimit",true); + for(auto* edit:m_motionTable->cellWidget(row,6)->findChildren())edit->setReadOnly(true); + } +} + void MainWindow::rebuildArmJointTables(const QStringList &jointNames) { if (!m_jointTable) @@ -2155,7 +2202,7 @@ void MainWindow::rebuildArmJointTables(const QStringList &jointNames) if (m_motionTable) { m_motionTable->clearContents(); - m_motionTable->setColumnCount(5); + m_motionTable->setColumnCount(7); m_motionTable->setRowCount(jointNames.size()); m_targetSpins.clear(); m_targetRadianSpins.clear(); @@ -2173,28 +2220,68 @@ void MainWindow::rebuildArmJointTables(const QStringList &jointNames) m_motionTable->setCellWidget(row, 2, currentRadians); QDoubleSpinBox *targetDegrees = new QDoubleSpinBox(m_motionTable); - targetDegrees->setRange(-360.0, 360.0); + targetDegrees->setRange(-1e9, 1e9); targetDegrees->setDecimals(3); targetDegrees->setSingleStep(1.0); targetDegrees->setSuffix(QStringLiteral(" °")); targetDegrees->setKeyboardTracking(false); QDoubleSpinBox *targetRadians = new QDoubleSpinBox(m_motionTable); - targetRadians->setRange(-2.0 * M_PI, 2.0 * M_PI); + targetRadians->setRange(-1e7, 1e7); targetRadians->setDecimals(6); targetRadians->setSingleStep(0.01); targetRadians->setSuffix(QStringLiteral(" rad")); targetRadians->setKeyboardTracking(false); m_motionTable->setCellWidget(row, 3, targetDegrees); m_motionTable->setCellWidget(row, 4, targetRadians); + auto *slider = new QSlider(Qt::Horizontal, m_motionTable); + slider->setRange(0, 10000); + slider->setEnabled(false); + slider->setToolTip(QStringLiteral("未提供限位,填写上下限后可拖动;拖动不会发送运动")); + m_motionTable->setCellWidget(row, 5, slider); + auto *limits = new QWidget(m_motionTable); + auto *limitLayout = new QHBoxLayout(limits); + limitLayout->setContentsMargins(4, 0, 4, 0); + for (const auto &key : {QStringLiteral("lower"), QStringLiteral("upper")}) { + auto *input = new QLineEdit(limits); + input->setObjectName(key); + input->setPlaceholderText(key == "lower" ? QStringLiteral("未提供下限") : QStringLiteral("未提供上限")); + input->setToolTip(QStringLiteral("手动输入关节位置限位,单位 rad;不会修改服务端限位")); + limitLayout->addWidget(input); + connect(input, &QLineEdit::editingFinished, this, [this, row, limits] { + bool a=false, b=false; + const double lower=QLocale::c().toDouble(limits->findChild("lower")->text(), &a); + const double upper=QLocale::c().toDouble(limits->findChild("upper")->text(), &b); + if(a && b && qIsFinite(lower) && qIsFinite(upper) && lower < upper) + setArmJointLimit(row, lower, upper, QStringLiteral("手动限位")); + else { + limits->setProperty("invalid", true); + m_motionTable->cellWidget(row,5)->setEnabled(false); + limits->setToolTip(QStringLiteral("请填写有效的下限与上限(下限 < 上限);无效时禁止发送 MoveJ")); + } + }); + } + m_motionTable->setCellWidget(row, 6, limits); + connect(slider, &QSlider::valueChanged, this, [targetRadians](int value) { + targetRadians->setValue(targetRadians->minimum() + + (targetRadians->maximum()-targetRadians->minimum()) * value / 10000.0); + }); + const auto syncSlider=[slider,targetRadians] { + if(!targetRadians->property("hasLimit").toBool())return; + const QSignalBlocker block(slider); + slider->setValue(qRound((targetRadians->value()-targetRadians->minimum()) / + (targetRadians->maximum()-targetRadians->minimum()) * 10000.0)); + }; connect(targetDegrees, QOverload::of(&QDoubleSpinBox::valueChanged), - this, [targetRadians](double degrees) { + this, [targetRadians,syncSlider](double degrees) { const QSignalBlocker blocker(targetRadians); targetRadians->setValue(qDegreesToRadians(degrees)); + syncSlider(); }); connect(targetRadians, QOverload::of(&QDoubleSpinBox::valueChanged), - this, [targetDegrees](double radians) { + this, [targetDegrees,syncSlider](double radians) { const QSignalBlocker blocker(targetDegrees); targetDegrees->setValue(qRadiansToDegrees(radians)); + syncSlider(); }); m_targetSpins.append(targetDegrees); m_targetRadianSpins.append(targetRadians); @@ -2215,6 +2302,7 @@ void MainWindow::rebuildArmJointTables(const QStringList &jointNames) m_previousJointVelocities.clear(); m_lastArmTelemetryMs = 0; rebuildArmJogControls(); + refreshArmJointLimits(); } void MainWindow::rebuildArmJogControls() @@ -2579,6 +2667,7 @@ void MainWindow::updateArmInfo(const QString &deviceId, const QVariantMap &info) == QStringLiteral("getJointState"); m_armDefaultBaseFrame = info.value(QStringLiteral("defaultBaseFrame")).toString(); m_armDefaultTcpFrame = info.value(QStringLiteral("defaultTcpFrame")).toString(); + if(!jointInfoOnly)m_serverArmJointLimits=info.value(QStringLiteral("jointLimits")).toMap(); const QStringList jointNames = info.value(QStringLiteral("jointNames")).toStringList(); // Some older controllers do not implement joint_names. Do not erase rows // recovered from real telemetry, or recreate a button while it is held. @@ -2609,6 +2698,7 @@ void MainWindow::updateArmInfo(const QString &deviceId, const QVariantMap &info) m_controllerTcpFrames = m_armDefaultTcpFrame.isEmpty() ? QStringList{} : QStringList{m_armDefaultTcpFrame}; refreshTcpChoices(); + refreshArmJointLimits(); appendLog(QStringLiteral("INFO"), jointInfoOnly ? QStringLiteral("机械臂 %1:已读取 %2 轴关节信息,服务端未提供型号接口") .arg(deviceId).arg(jointNames.size()) @@ -2649,6 +2739,7 @@ void MainWindow::updateTelemetry(const QString &deviceId, const QVariantList &jo } m_latestArmJointPositions = jointPositions; + refreshArmJointLimits(); const qint64 nowMs = QDateTime::currentMSecsSinceEpoch(); const double deltaSeconds = m_lastArmTelemetryMs > 0 ? (nowMs - m_lastArmTelemetryMs) / 1000.0 : 0.0; @@ -3708,6 +3799,11 @@ void MainWindow::sendMoveJ() QStringLiteral("请先选择机械臂并等待关节信息加载完成。")); return; } + for(int row=0;rowrowCount();++row){ + if(m_motionTable->cellWidget(row,6)->property("invalid").toBool()){ + AppMessageBox::warning(this,QStringLiteral("关节限位"),QStringLiteral("请先修正 %1 的上下限。").arg(m_activeArmJointNames[row]));return; + } + } QVariantList positions; for (QDoubleSpinBox *spin : m_targetRadianSpins) positions.append(spin->value()); @@ -3715,7 +3811,8 @@ void MainWindow::sendMoveJ() m_moveJVelocitySpin ? m_moveJVelocitySpin->value() : m_velocitySpin->value(), m_moveJAccelerationSpin ? m_moveJAccelerationSpin->value() - : m_accelerationSpin->value()); + : m_accelerationSpin->value(), + m_moveJJerkSpin ? m_moveJJerkSpin->value() : 0.0); } void MainWindow::refreshRecordedJointPoints() @@ -4007,9 +4104,9 @@ void MainWindow::stopJointPointLoop(const QString &reason) reason); } -void MainWindow::sendMoveJPose() +void MainWindow::sendMoveLPose() { - if (m_moveJPoseSpins.size() != 6 || !m_moveJPoseBaseLinkCombo) + if (m_moveLPoseSpins.size() != 6 || !m_moveLPoseBaseLinkCombo) return; QVariantMap pose; static const QStringList keys = { @@ -4017,8 +4114,8 @@ void MainWindow::sendMoveJPose() QStringLiteral("rx"), QStringLiteral("ry"), QStringLiteral("rz") }; for (int i = 0; i < keys.size(); ++i) - pose.insert(keys.at(i), m_moveJPoseSpins.at(i)->value()); - m_client->requestMoveJPose(m_armIdEdit->text().trimmed(), pose, + pose.insert(keys.at(i), m_moveLPoseSpins.at(i)->value()); + m_client->requestMoveLPose(m_armIdEdit->text().trimmed(), pose, m_armDefaultBaseFrame, m_armDefaultTcpFrame, m_velocitySpin->value(), m_accelerationSpin->value()); @@ -4433,10 +4530,15 @@ void MainWindow::setControlsEnabled(bool enabled) } for (QDoubleSpinBox *spin : m_targetSpins) spin->setEnabled(enabled); - for (QDoubleSpinBox *spin : m_moveJPoseSpins) + for(int row=0;rowsetEnabled(enabled); + m_motionTable->cellWidget(row,5)->setEnabled(enabled && m_targetRadianSpins[row]->property("hasLimit").toBool() + && !m_motionTable->cellWidget(row,6)->property("invalid").toBool()); + } + for (QDoubleSpinBox *spin : m_moveLPoseSpins) spin->setEnabled(enabled); - if (m_moveJPoseBaseLinkCombo) - m_moveJPoseBaseLinkCombo->setEnabled(enabled); + if (m_moveLPoseBaseLinkCombo) + m_moveLPoseBaseLinkCombo->setEnabled(enabled); if (m_velocitySpin) m_velocitySpin->setEnabled(enabled); if (m_accelerationSpin) @@ -4445,6 +4547,8 @@ void MainWindow::setControlsEnabled(bool enabled) m_moveJVelocitySpin->setEnabled(enabled); if (m_moveJAccelerationSpin) m_moveJAccelerationSpin->setEnabled(enabled); + if (m_moveJJerkSpin) + m_moveJJerkSpin->setEnabled(enabled); if (m_jointFlowVelocitySpin) m_jointFlowVelocitySpin->setEnabled(enabled && !m_jointPointLoopActive); if (m_jointFlowAccelerationSpin) diff --git a/src/mainwindow.h b/src/mainwindow.h index 8ab0b5c..2fe0724 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -105,7 +105,7 @@ private slots: void updateQuicRunning(bool running, quint16 port, const QString &detail); void appendQuicLog(const QString &level, const QString &message); void sendMoveJ(); - void sendMoveJPose(); + void sendMoveLPose(); void recordCurrentJointPoint(); void combineSelectedJointPoints(); void dispatchJointPoint(int row); @@ -149,6 +149,8 @@ private: void updateWindowChrome(); void ensureArmModelLoaded(); void rebuildArmJointTables(const QStringList &jointNames); + void setArmJointLimit(int row, double lower, double upper, const QString &source); + void refreshArmJointLimits(); void rebuildArmJogControls(); void refreshArmJogAvailability(); void setArmTelemetryEnabled(bool enabled); @@ -248,14 +250,16 @@ private: TrendWidget *m_trend = nullptr; QTableWidget *m_jointTable = nullptr; QTableWidget *m_motionTable = nullptr; + QVariantMap m_serverArmJointLimits; QList m_targetSpins; QList m_targetRadianSpins; QPushButton *m_syncCurrentToTargetButton = nullptr; QDoubleSpinBox *m_moveJVelocitySpin = nullptr; QDoubleSpinBox *m_moveJAccelerationSpin = nullptr; + QDoubleSpinBox *m_moveJJerkSpin = nullptr; QStringList m_activeArmJointNames; - QList m_moveJPoseSpins; - QComboBox *m_moveJPoseBaseLinkCombo = nullptr; + QList m_moveLPoseSpins; + QComboBox *m_moveLPoseBaseLinkCombo = nullptr; QPushButton *m_copyCurrentPoseButton = nullptr; QVariantMap m_latestArmPose; QString m_armDefaultBaseFrame; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 40a12f8..e16db34 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -1,3 +1,4 @@ +#include "actionqueuetestwidget.h" #include "mainwindow.h" #include "agvmapviewwidget.h" @@ -955,7 +956,7 @@ QWidget *MainWindow::createArmPage() m_moveJVelocitySpin->setRange(0.001, 10.0); m_moveJVelocitySpin->setDecimals(3); m_moveJVelocitySpin->setSingleStep(0.01); - m_moveJVelocitySpin->setValue(0.1); + m_moveJVelocitySpin->setValue(1.0); m_moveJVelocitySpin->setSuffix(QStringLiteral(" rad/s")); m_moveJVelocitySpin->setMinimumWidth(150); QLabel *moveJAccelerationLabel = new QLabel( @@ -964,15 +965,27 @@ QWidget *MainWindow::createArmPage() m_moveJAccelerationSpin->setRange(0.001, 20.0); m_moveJAccelerationSpin->setDecimals(3); m_moveJAccelerationSpin->setSingleStep(0.01); - m_moveJAccelerationSpin->setValue(0.1); + m_moveJAccelerationSpin->setValue(5.0); m_moveJAccelerationSpin->setSuffix(QStringLiteral(" rad/s²")); m_moveJAccelerationSpin->setMinimumWidth(150); + auto *moveJJerkLabel = new QLabel(QStringLiteral("加加速度"), moveJParameters); + m_moveJJerkSpin = new QDoubleSpinBox(moveJParameters); + m_moveJJerkSpin->setObjectName(QStringLiteral("moveJJerkSpin")); + m_moveJJerkSpin->setRange(0.001, 10000.0); + m_moveJJerkSpin->setDecimals(3); + m_moveJJerkSpin->setSingleStep(0.1); + m_moveJJerkSpin->setValue(5.0); + m_moveJJerkSpin->setSuffix(QStringLiteral(" rad/s³")); + m_moveJJerkSpin->setMinimumWidth(150); + m_moveJJerkSpin->setToolTip(QStringLiteral("通过 MotionOptions.jerk 发送;是否生效取决于服务端驱动支持,当前遨博 MoveJ 未使用此参数")); moveJParametersLayout->addWidget(moveJParametersTitle); moveJParametersLayout->addSpacing(12); moveJParametersLayout->addWidget(moveJVelocityLabel); moveJParametersLayout->addWidget(m_moveJVelocitySpin); moveJParametersLayout->addWidget(moveJAccelerationLabel); moveJParametersLayout->addWidget(m_moveJAccelerationSpin); + moveJParametersLayout->addWidget(moveJJerkLabel); + moveJParametersLayout->addWidget(m_moveJJerkSpin); moveJParametersLayout->addStretch(1); ui.targetsLayout->insertWidget(1, moveJParameters); ui.teachPanel->hide(); @@ -1007,7 +1020,8 @@ QWidget *MainWindow::createArmPage() jogHeader->addWidget(jogTitle); jogHeader->addStretch(1); jogHeader->addWidget(jogHint); - jogHeader->addWidget(openJointFlowButton); + ui.targetsHeader->addWidget(openJointFlowButton); + ui.targetsSubtitle->setText(QStringLiteral("角度、弧度与滑动条同步;拖动仅编辑目标,点击 MoveJ 后执行。未提供限位时可手动填写(rad)。")); jogLayout->addLayout(jogHeader); connect(openJointFlowButton, &QPushButton::clicked, this, [this]() { if (!m_jointFlowDialog) @@ -1399,9 +1413,13 @@ QWidget *MainWindow::createArmPage() ui.armTabs->addTab(deviceTeachingPage, QStringLiteral("拖动示教")); auto *userCoordinates = new UserCoordinateWidget(m_client, ui.armTabs); ui.armTabs->addTab(userCoordinates, QStringLiteral("自定义坐标系")); + auto *queueTest = new ActionQueueTestWidget(m_client, ui.armTabs); + ui.armTabs->addTab(queueTest, QStringLiteral("动作队列测试")); struct CoordinateConnection { QString requestedEndpoint; bool ready=false; }; const auto coordinateConnection=std::make_shared(); - const auto syncUserCoordinates = [this,userCoordinates,coordinateConnection] { + const auto syncUserCoordinates = [this,userCoordinates,queueTest,coordinateConnection] { + queueTest->setContext(endpoint(),m_armIdEdit->text().trimmed(), + coordinateConnection->ready && coordinateConnection->requestedEndpoint==endpoint()); userCoordinates->setContext(endpoint(),m_armIdEdit->text().trimmed(), coordinateConnection->ready && coordinateConnection->requestedEndpoint==endpoint()); }; @@ -1519,8 +1537,12 @@ QWidget *MainWindow::createArmPage() missing.append(jointName); continue; } - m_targetRadianSpins.at(row)->setValue( - m_latestArmJointPositions.value(jointName)); + auto *target=m_targetRadianSpins.at(row); + const double actual=m_latestArmJointPositions.value(jointName); + if(!qIsFinite(actual) || actualminimum() || actual>target->maximum()){ + missing.append(jointName+QStringLiteral("(超出目标限位)"));continue; + } + target->setValue(actual); } if (!missing.isEmpty()) { AppMessageBox::warning(this, QStringLiteral("同步当前位置"), @@ -1592,16 +1614,19 @@ QWidget *MainWindow::createArmPage() m_jointTable->verticalHeader()->setDefaultSectionSize(28); m_jointTable->horizontalHeader()->setStretchLastSection(true); - m_motionTable->setColumnCount(5); + m_motionTable->setColumnCount(7); m_motionTable->setHorizontalHeaderLabels({ QStringLiteral("关节"), QStringLiteral("当前位置 (°)"), QStringLiteral("当前位置 (rad)"), QStringLiteral("目标角度 (°)"), - QStringLiteral("目标弧度 (rad)")}); + QStringLiteral("目标弧度 (rad)"), QStringLiteral("目标滑动条"), QStringLiteral("限位 (rad):下限 / 上限")}); m_motionTable->setAlternatingRowColors(true); m_motionTable->setSelectionMode(QAbstractItemView::NoSelection); m_motionTable->setEditTriggers(QAbstractItemView::NoEditTriggers); m_motionTable->verticalHeader()->setVisible(false); - m_motionTable->verticalHeader()->setDefaultSectionSize(38); + m_motionTable->verticalHeader()->setDefaultSectionSize(52); + m_motionTable->horizontalHeader()->setSectionResizeMode(5, QHeaderView::Stretch); + m_motionTable->horizontalHeader()->setSectionResizeMode(6, QHeaderView::Stretch); + m_motionTable->setMinimumWidth(900); m_motionTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); m_motionTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); m_motionTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); @@ -1622,6 +1647,7 @@ QWidget *MainWindow::createArmPage() setArmTelemetryEnabled(false); m_armIdEdit->setText(newDeviceId); m_activeArmJointNames.clear(); + m_serverArmJointLimits.clear(); m_latestArmJointPositions.clear(); m_jointTable->setRowCount(0); m_targetSpins.clear(); diff --git a/src/robotclient.cpp b/src/robotclient.cpp index 3968ec3..c494f15 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -783,6 +783,13 @@ public: info.insert(QStringLiteral("subtype"), QString::fromStdString(response.subtype())); info.insert(QStringLiteral("dof"), static_cast(response.dof())); info.insert(QStringLiteral("jointNames"), jointNames); + QVariantMap jointLimits; + for(const auto& limit:response.joint_limits()){ + if(!limit.position_limits_available() || !std::isfinite(limit.lower()) || !std::isfinite(limit.upper()) || limit.lower()>=limit.upper())continue; + jointLimits.insert(QString::fromStdString(limit.joint_name()),QVariantMap{ + {"lower",limit.lower()},{"upper",limit.upper()},{"source",QString::fromStdString(limit.source())}}); + } + info.insert(QStringLiteral("jointLimits"),jointLimits); info.insert(QStringLiteral("defaultBaseFrame"), QString::fromStdString(response.default_base_frame())); info.insert(QStringLiteral("defaultTcpFrame"), QString::fromStdString(response.default_tcp_frame())); info.insert(QStringLiteral("descriptionId"), QString::fromStdString(response.description_id())); @@ -798,7 +805,8 @@ public: void userCoordinates(const QString &deviceId, const QVariantMap ¶meters, quint64 token) { const QString service = QStringLiteral("cmvr.user_coordinates"); - const bool move = parameters.value("operation").toString() == "move"; + const bool jointMove = parameters.value("operation").toString() == "move_joint"; + const bool move = jointMove || parameters.value("operation").toString() == "move"; const QString command = QStringLiteral("User Frame Move:%1").arg(token); const auto fail = [&](const QString &why) { if (move) emit commandFinished(command,false,why); @@ -807,6 +815,23 @@ public: if (!ensureConnected(service) || !ensureDeviceId(service,deviceId)) { fail(QStringLiteral("设备未连接")); return; } if (m_demoMode) { fail(QStringLiteral("演示模式不应用坐标系或运动")); return; } #ifdef CMVR_WITH_GRPC + if (jointMove) { + cmvr::api::MoveJPose::Request request; + fillHeader(request.mutable_header(),deviceId,kArmMotionTimeoutMs); + const auto values=parameters.value("target").toList(); + const auto name=parameters.value("name").toString(); + if(values.size()!=6 || name.isEmpty()){fail(QStringLiteral("Select a saved coordinate and a six-component absolute TCP target"));return;} + request.set_user_coordinate_name(name.toStdString()); + request.set_user_coordinate_revision(parameters.value("revision").toString().toULongLong()); + auto* p=request.mutable_target(); + p->set_x(values[0].toDouble());p->set_y(values[1].toDouble());p->set_z(values[2].toDouble()); + p->set_rx(values[3].toDouble());p->set_ry(values[4].toDouble());p->set_rz(values[5].toDouble()); + request.mutable_options()->set_velocity(parameters.value("velocity").toDouble()); + request.mutable_options()->set_acceleration(parameters.value("acceleration").toDouble()); + startArmMotion(command,std::move(request), + [](cmvr::api::ArmService::Stub& stub,grpc::ClientContext* context,const cmvr::api::MoveJPose::Request& q,cmvr::api::MoveJPose::Response* r){return stub.moveJPose(context,q,r);}); + return; + } if (move) { cmvr::api::MoveL::Request request; fillHeader(request.mutable_header(),deviceId,kArmMotionTimeoutMs); @@ -1702,7 +1727,7 @@ public: } void moveJ(const QString &deviceId, const QVariantList &positions, - double velocity, double acceleration) + double velocity, double acceleration, double jerk) { if (!ensureConnected(QStringLiteral("MoveJ"))) return; @@ -1717,8 +1742,8 @@ public: for (const QVariant &value : positions) m_demoTargets.append(value.toDouble()); emit commandFinished(QStringLiteral("MoveJ"), true, - QStringLiteral("已发送 %1 个目标,v=%2,a=%3") - .arg(positions.size()).arg(velocity, 0, 'f', 2).arg(acceleration, 0, 'f', 2)); + QStringLiteral("已发送 %1 个目标,v=%2,a=%3,j=%4") + .arg(positions.size()).arg(velocity, 0, 'f', 2).arg(acceleration, 0, 'f', 2).arg(jerk, 0, 'f', 2)); return; } #ifdef CMVR_WITH_GRPC @@ -1728,6 +1753,7 @@ public: request.mutable_target()->add_position(value.toDouble()); request.mutable_options()->set_velocity(velocity); request.mutable_options()->set_acceleration(acceleration); + request.mutable_options()->set_jerk(jerk); startArmMotion( QStringLiteral("MoveJ"), std::move(request), [](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context, @@ -1738,7 +1764,7 @@ public: #endif } - void moveJPose(const QString &deviceId, const QVariantMap &pose, + void moveLPose(const QString &deviceId, const QVariantMap &pose, const QString &baseLink, const QString &eeLink, double velocity, double acceleration) { @@ -5820,7 +5846,7 @@ RobotClient::RobotClient(QObject *parent) 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::moveLPoseRequested, m_worker, &BackendWorker::moveLPose); connect(this, &RobotClient::torqueRequested, m_worker, &BackendWorker::torque); connect(this, &RobotClient::armStopRequested, m_worker, &BackendWorker::armStop); connect(this, &RobotClient::armClearFaultRequested, m_worker, &BackendWorker::armClearFault); @@ -6059,17 +6085,17 @@ void RobotClient::requestJointPointMove(const QVariantList &targets, double velo emit jointPointMoveRequested(targets, velocity, acceleration, token); } void RobotClient::requestMoveJ(const QString &deviceId, const QVariantList &positions, - double velocity, double acceleration) + double velocity, double acceleration, double jerk) { emit armCommandStarting(deviceId); - emit moveJRequested(deviceId, positions, velocity, acceleration); + emit moveJRequested(deviceId, positions, velocity, acceleration, jerk); } -void RobotClient::requestMoveJPose(const QString &deviceId, const QVariantMap &pose, +void RobotClient::requestMoveLPose(const QString &deviceId, const QVariantMap &pose, const QString &baseLink, const QString &eeLink, double velocity, double acceleration) { emit tcpReferenceInvalidated(deviceId); - emit moveJPoseRequested(deviceId, pose, baseLink, eeLink, velocity, acceleration); + emit moveLPoseRequested(deviceId, pose, baseLink, eeLink, velocity, acceleration); } void RobotClient::requestTorque(const QString &deviceId, bool enabled) { emit armCommandStarting(deviceId); emit torqueRequested(deviceId, enabled); } void RobotClient::requestArmStop(const QString &deviceId) { emit armStopRequested(deviceId); } diff --git a/src/robotclient.h b/src/robotclient.h index f70767e..970665f 100644 --- a/src/robotclient.h +++ b/src/robotclient.h @@ -53,8 +53,8 @@ public slots: void requestSpeedL(const QString &deviceId, const QVariantMap &velocity, double acceleration, double duration, bool toolFrame); void requestMoveJ(const QString &deviceId, const QVariantList &positions, - double velocity, double acceleration); - void requestMoveJPose(const QString &deviceId, const QVariantMap &pose, + double velocity, double acceleration, double jerk = 0.0); + void requestMoveLPose(const QString &deviceId, const QVariantMap &pose, const QString &baseLink, const QString &eeLink, double velocity, double acceleration); void requestTorque(const QString &deviceId, bool enabled); @@ -168,8 +168,8 @@ signals: void speedLRequested(const QString &deviceId, const QVariantMap &velocity, double acceleration, double duration, bool toolFrame); void moveJRequested(const QString &deviceId, const QVariantList &positions, - double velocity, double acceleration); - void moveJPoseRequested(const QString &deviceId, const QVariantMap &pose, + double velocity, double acceleration, double jerk); + void moveLPoseRequested(const QString &deviceId, const QVariantMap &pose, const QString &baseLink, const QString &eeLink, double velocity, double acceleration); void torqueRequested(const QString &deviceId, bool enabled); diff --git a/src/usercoordinatewidget.cpp b/src/usercoordinatewidget.cpp index 4a4bcdd..7fb0be2 100644 --- a/src/usercoordinatewidget.cpp +++ b/src/usercoordinatewidget.cpp @@ -63,6 +63,13 @@ UserCoordinateWidget::UserCoordinateWidget(RobotClient* client,QWidget* parent): auto* absolute=new QGroupBox(QStringLiteral("绝对目标 MoveL · 相对所选坐标系(m / rad)"),body);auto* targetGrid=new QGridLayout(absolute); for(int i=0;i<6;++i){targetGrid->addWidget(new QLabel(QString::fromLatin1(axes[i]).replace("mm","m"),body),0,i);m_target[i]=box(body,i<3?" m":" rad");targetGrid->addWidget(m_target[i],1,i);connect(m_target[i],QOverload::of(&QDoubleSpinBox::valueChanged),this,[this]{if(!m_loading)m_targetReady=true;updateActions();});} m_move=new QPushButton(QStringLiteral("执行目标 MoveL"),body);targetGrid->addWidget(m_move,2,0,1,6);layout->addWidget(absolute); + m_jointSpeed=box(body," rad/s",3);m_jointSpeed->setRange(.001,10);m_jointSpeed->setValue(.1); + m_jointAccel=box(body," rad/s²",3);m_jointAccel->setRange(.001,100);m_jointAccel->setValue(.5); + targetGrid->addWidget(new QLabel(QStringLiteral("MoveJ 关节速度"),body),3,0);targetGrid->addWidget(m_jointSpeed,3,1,1,2); + targetGrid->addWidget(new QLabel(QStringLiteral("MoveJ 关节加速度"),body),3,3);targetGrid->addWidget(m_jointAccel,3,4,1,2); + m_moveJoint=new QPushButton(QStringLiteral("执行目标末端位姿 MoveJ"),body);targetGrid->addWidget(m_moveJoint,4,0,1,6); + auto* jointHint=new QLabel(QStringLiteral("使用上方同一绝对 TCP 目标,经服务端坐标变换、SDK 逆解后执行关节运动,路径不保证直线。"),body); + jointHint->setWordWrap(true);targetGrid->addWidget(jointHint,5,0,1,6); m_status=new QLabel(QStringLiteral("选择并应用坐标系后,获取所选坐标系位姿,可填入绝对目标后调整。获取、保存和应用不会发送运动。"),body);m_status->setWordWrap(true);m_status->setTextInteractionFlags(Qt::TextSelectableByMouse);layout->addWidget(m_status);layout->addStretch(); m_timeout=new QTimer(this);m_timeout->setSingleShot(true);connect(m_timeout,&QTimer::timeout,this,[this]{if(m_moving)m_client->requestArmStop(m_device);finish(false,QStringLiteral("请求超时,请检查服务端状态"));}); connect(m_list,QOverload::of(&QComboBox::currentIndexChanged),this,[this](int i){loadSelection(i);}); @@ -78,6 +85,9 @@ UserCoordinateWidget::UserCoordinateWidget(RobotClient* client,QWidget* parent): connect(m_fillTarget,&QPushButton::clicked,this,[this]{for(int i=0;i<6;++i)m_target[i]->setValue(m_currentPose[i]->text().toDouble());m_targetReady=true;updateActions();}); connect(m_remove,&QPushButton::clicked,this,[this]{if(AppMessageBox::question(this,QStringLiteral("删除坐标系"),QStringLiteral("删除所选服务端记录?"))==AppMessageBox::Yes)send("delete");}); connect(m_move,&QPushButton::clicked,this,[this]{m_relative=false;send("move");}); + connect(m_moveJoint,&QPushButton::clicked,this,[this]{ + if(AppMessageBox::question(this,QStringLiteral("末端位姿 MoveJ"),QStringLiteral("将沿关节运动路径到达所选坐标系下的绝对 TCP 目标,途中不保证直线。确认目标及运动空间安全?"))==AppMessageBox::Yes)send("move_joint"); + }); connect(stop,&QPushButton::clicked,this,[this]{if(m_connected)m_client->requestArmStop(m_device);}); connect(client,&RobotClient::rpcFinished,this,[this](const QString& service,const QString& token,bool ok,const QString& text){ if(service!="cmvr.user_coordinates"||token!=QString::number(m_token)||!m_busy)return; @@ -150,7 +160,8 @@ void UserCoordinateWidget::updateActions(){ for(auto* button:m_captureButtons)button->setEnabled(ready&&!b); m_calibration->setVisible(!b);m_tcpGroup->setVisible(!b);m_calibration->setEnabled(!m_busy);m_tcpGroup->setEnabled(!m_busy); m_calibrate->setEnabled(ready&&!b);m_save->setEnabled(ready&&m_loadOk&&!b&&!m_name->text().trimmed().isEmpty());m_remove->setEnabled(ready&&m_loadOk&&!b&&i>=0);m_apply->setEnabled(ready&&m_loadOk&&saved); - m_move->setEnabled(applied&&m_targetReady); + m_move->setEnabled(applied&&m_targetReady);m_moveJoint->setEnabled(applied&&m_targetReady); + m_jointSpeed->setEnabled(!m_busy);m_jointAccel->setEnabled(!m_busy); m_appliedState->setText(QStringLiteral("当前应用:%1%2").arg(m_appliedName.isEmpty()?QStringLiteral("尚未应用"):label(m_appliedName),applied?QString():QStringLiteral(" · 所选记录未应用或有未保存修改"))); } void UserCoordinateWidget::send(const QString& operation){ @@ -158,6 +169,7 @@ void UserCoordinateWidget::send(const QString& operation){ auto p=draft().toVariantMap();p.insert("operation",operation);p.insert("velocity",m_speed->value());p.insert("acceleration",m_accel->value());p.insert("relative_translation",m_relative); p.insert("target",(operation=="move"&&m_relative?m_delta:values(m_target)).toVariantList()); if(m_list->currentIndex()>=0)p.insert("revision",m_profiles[m_list->currentIndex()].toObject().value("revision").toString()); - m_busy=true;m_moving=operation=="move";m_timeout->start(m_moving?120000:25000);m_status->setText(QStringLiteral("处理中…"));updateActions();m_client->requestUserCoordinates(m_device,p,m_token); + if(operation=="move_joint"){p.insert("velocity",m_jointSpeed->value());p.insert("acceleration",m_jointAccel->value());} + m_busy=true;m_moving=operation=="move"||operation=="move_joint";m_timeout->start(m_moving?120000:25000);m_status->setText(QStringLiteral("处理中…"));updateActions();m_client->requestUserCoordinates(m_device,p,m_token); } -void UserCoordinateWidget::finish(bool ok,const QString& detail){m_busy=m_moving=false;m_timeout->stop();if(!ok){m_capture=-1;if(m_operation=="apply"||m_operation=="move"){m_appliedName.clear();m_appliedRevision.clear();}}m_status->setText((ok?QStringLiteral("成功:"):QStringLiteral("失败:"))+detail);updateActions();} +void UserCoordinateWidget::finish(bool ok,const QString& detail){m_busy=m_moving=false;m_timeout->stop();if(!ok){m_capture=-1;if(m_operation=="apply"||m_operation=="move"||m_operation=="move_joint"){m_appliedName.clear();m_appliedRevision.clear();}}m_status->setText((ok?QStringLiteral("成功:"):QStringLiteral("失败:"))+detail);updateActions();} diff --git a/src/usercoordinatewidget.h b/src/usercoordinatewidget.h index 48d72fd..c15c2d8 100644 --- a/src/usercoordinatewidget.h +++ b/src/usercoordinatewidget.h @@ -25,7 +25,8 @@ private: std::array m_currentPose,m_result; std::array m_captureButtons; std::array m_axes; - QDoubleSpinBox *m_speed,*m_accel,*m_step; + QDoubleSpinBox *m_speed,*m_accel,*m_step,*m_jointSpeed,*m_jointAccel; + QPushButton* m_moveJoint; QLabel *m_status,*m_appliedState,*m_poseReference; QGroupBox *m_calibration,*m_tcpGroup; QPushButton *m_getBasePose,*m_fillTarget,*m_getPose,*m_save,*m_remove,*m_apply,*m_move,*m_read,*m_new,*m_refresh,*m_calibrate; diff --git a/tests/handeyeintegration_test.cpp b/tests/handeyeintegration_test.cpp index 42a495e..1c14958 100644 --- a/tests/handeyeintegration_test.cpp +++ b/tests/handeyeintegration_test.cpp @@ -221,7 +221,7 @@ int main(int argc,char **argv) QSignalSpy points(panel,&HandEyeMotionWidget::basePointPrepared); QSignalSpy captures(panel,&HandEyeMotionWidget::captureRequested); QSignalSpy moveJ(window.m_client,&RobotClient::moveJRequested); - QSignalSpy moveL(window.m_client,&RobotClient::moveJPoseRequested); + QSignalSpy moveL(window.m_client,&RobotClient::moveLPoseRequested); QSignalSpy jog(window.m_client,&RobotClient::tcpJogMoveRequested); QSignalSpy speedJ(window.m_client,&RobotClient::speedJRequested); QSignalSpy speedL(window.m_client,&RobotClient::speedLRequested); diff --git a/tests/tcpintegration_test.cpp b/tests/tcpintegration_test.cpp index 4ceeb84..3d43f7f 100644 --- a/tests/tcpintegration_test.cpp +++ b/tests/tcpintegration_test.cpp @@ -164,12 +164,12 @@ int main(int argc,char **argv) { confirmed->setChecked(true); require(window.m_tcpCalibration->referenceConfirmed(),"nonzero reference not confirmed"); bool invalidBeforeDispatch=false; - QObject::connect(window.m_client,&RobotClient::moveJPoseRequested,&window,[&] { + QObject::connect(window.m_client,&RobotClient::moveLPoseRequested,&window,[&] { invalidBeforeDispatch=!window.m_tcpCalibration->referenceConfirmed(); }); const int beforeOrdinaryMove=fake.moves.load(); QVariantMap ordinary{{"x",.4},{"y",.2},{"z",.5},{"rx",0.},{"ry",0.},{"rz",0.}}; - window.m_client->requestMoveJPose("arm-b",ordinary,"base","tool0",.01,.1); + window.m_client->requestMoveLPose("arm-b",ordinary,"base","tool0",.01,.1); require(invalidBeforeDispatch,"ordinary MoveL left a stale active TCP confirmation"); require(until([&]{return fake.moves.load()>beforeOrdinaryMove;}),"ordinary MoveL regression"); confirmed->setChecked(true);