CmvrControlStation/src/handeyemotionwidget.cpp

392 lines
20 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "handeyemotionwidget.h"
#include "handeyeurdf.h"
#include <QCheckBox>
#include <QFileDialog>
#include <QFileInfo>
#include <QDir>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QFrame>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QSettings>
#include <QScrollArea>
#include <QSignalBlocker>
#include <QTimer>
#include <QVBoxLayout>
#include <cmath>
HandEyeMotionWidget::HandEyeMotionWidget(QWidget *parent) : QWidget(parent)
{
setObjectName(QStringLiteral("handEyeMotionPanel"));
auto *outer = new QVBoxLayout(this);
outer->setContentsMargins(0,0,0,0);
auto *frame = new QFrame;
frame->setObjectName(QStringLiteral("panel"));
auto *scroll = new QScrollArea(this);
scroll->setFrameShape(QFrame::NoFrame);
scroll->setWidgetResizable(true);
scroll->setWidget(frame);
outer->addWidget(scroll);
auto *layout = new QVBoxLayout(frame);
layout->setSizeConstraint(QLayout::SetMinimumSize);
layout->setContentsMargins(16,14,16,14);
layout->setSpacing(10);
auto *title = new QLabel(QStringLiteral("视觉标定"));
title->setObjectName(QStringLiteral("eyebrow"));
layout->addWidget(title);
auto *row = new QHBoxLayout;
m_records = new QComboBox;
m_records->setObjectName(QStringLiteral("handEyeMotionProfiles"));
m_records->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
m_records->setMinimumContentsLength(18);
m_records->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed);
row->addWidget(new QLabel(QStringLiteral("标定结果")));
row->addWidget(m_records,1);
auto *reloadButton = new QPushButton(QStringLiteral("重新加载"));
reloadButton->setObjectName(QStringLiteral("handEyeMotionReload"));
row->addWidget(reloadButton);
layout->addLayout(row);
m_recordInfo = new QLabel; m_recordInfo->setObjectName(QStringLiteral("handEyeSelectedResult"));
m_recordInfo->setWordWrap(true); layout->addWidget(m_recordInfo);
m_identityConfirmed=new QCheckBox(QStringLiteral("已确认旧标定属于当前相机")); m_identityConfirmed->hide(); layout->addWidget(m_identityConfirmed);
connect(m_identityConfirmed,&QCheckBox::toggled,this,[this] { invalidate(); refresh(); });
auto *grid = new QGridLayout;
grid->addWidget(new QLabel(QStringLiteral("相机点")),1,0);
grid->addWidget(new QLabel(QStringLiteral("基座点")),2,0);
for (int i=0;i<3;++i) {
grid->addWidget(new QLabel(QString(QChar('X'+i))+QStringLiteral(" (mm)")),0,i+1);
auto *input = new QDoubleSpinBox;
input->setObjectName(QStringLiteral("handEyeCameraPoint%1").arg(i));
input->setRange(-1000000,1000000);
input->setDecimals(3);
input->setButtonSymbols(QAbstractSpinBox::NoButtons);
input->setKeyboardTracking(false);
input->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed);
m_inputs.append(input);
grid->addWidget(input,1,i+1);
auto *result = new QLineEdit;
result->setObjectName(QStringLiteral("handEyeBasePoint%1").arg(i));
result->setReadOnly(true);
result->setPlaceholderText(QStringLiteral("待转换 · mm"));
m_results.append(result);
grid->addWidget(result,2,i+1);
grid->setColumnStretch(i+1,1);
connect(input,QOverload<double>::of(&QDoubleSpinBox::valueChanged),this,[this] { invalidate(); refresh(); });
// Editing text invalidates immediately, before a spin box commits its value.
connect(input->findChild<QLineEdit *>(),&QLineEdit::textEdited,this,[this] { invalidate(); refresh(); });
}
layout->addLayout(grid);
auto *actions = new QHBoxLayout;
m_status = new QLabel;
m_status->setObjectName(QStringLiteral("mutedLabel"));
m_status->setWordWrap(true);
actions->addWidget(m_status,1);
m_convert = new QPushButton(QStringLiteral("转换为基座坐标"));
m_convert->setObjectName(QStringLiteral("handEyeConvert"));
actions->addWidget(m_convert);
layout->addLayout(actions);
m_convert->setToolTip(QStringLiteral("仅转换坐标,不发送运动指令。"));
auto *urdfTitle = new QLabel(QStringLiteral("URDF 标定更新"));
urdfTitle->setObjectName(QStringLiteral("sectionTitle")); layout->addWidget(urdfTitle);
auto *fileRow = new QHBoxLayout;
m_urdfPath = new QLineEdit; m_urdfPath->setReadOnly(true);
m_urdfPath->setObjectName(QStringLiteral("handEyeUrdfPath"));
m_urdfPath->setPlaceholderText(QStringLiteral("选择机器人 URDF"));
auto *current = new QPushButton(QStringLiteral("当前模型"));
auto *browse = new QPushButton(QStringLiteral("选择"));
fileRow->addWidget(m_urdfPath,1); fileRow->addWidget(current); fileRow->addWidget(browse);
layout->addLayout(fileRow);
auto *mapping = new QGridLayout;
m_urdfReference=new QComboBox; m_urdfReference->setObjectName(QStringLiteral("handEyeUrdfReference"));
m_urdfCamera=new QComboBox; m_urdfCamera->setObjectName(QStringLiteral("handEyeUrdfCamera"));
m_urdfCamera->setEditable(true); m_urdfCamera->setInsertPolicy(QComboBox::NoInsert);
for (auto *combo : {m_urdfReference,m_urdfCamera})
combo->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed);
m_urdfCamera->lineEdit()->setPlaceholderText(QStringLiteral("选择或输入相机坐标系"));
mapping->addWidget(new QLabel(QStringLiteral("参考 Link")),0,0); mapping->addWidget(m_urdfReference,0,1);
mapping->addWidget(new QLabel(QStringLiteral("相机 Link")),1,0); mapping->addWidget(m_urdfCamera,1,1);
mapping->setColumnStretch(1,1); layout->addLayout(mapping);
m_urdfConfirmed = new QCheckBox; m_urdfConfirmed->setObjectName(QStringLiteral("handEyeUrdfConfirmed"));
m_urdfConfirmed->setToolTip(QStringLiteral("参考 Link 必须与标定的基座/法兰坐标一致;相机 Link 必须为标定使用的光学坐标系,而非未经换算的相机外壳坐标系。新相机 Link 将作为固定子节点添加。"));
layout->addWidget(m_urdfConfirmed);
m_updateUrdf=new QPushButton(QStringLiteral("导出并加载 URDF"));
m_updateUrdf->setObjectName(QStringLiteral("handEyeUpdateUrdf"));
m_updateUrdf->setToolTip(QStringLiteral("根据选中标定更新相机固定关节并保存为新文件,保留原模型。建议保存在原模型目录以保持 package:// 资源解析。"));
layout->addWidget(m_updateUrdf);
connect(current,&QPushButton::clicked,this,&HandEyeMotionWidget::currentUrdfRequested);
connect(browse,&QPushButton::clicked,this,[this] {
const QString path=QFileDialog::getOpenFileName(this,QStringLiteral("选择 URDF"),m_urdfSource,QStringLiteral("URDF (*.urdf)"));
if (!path.isEmpty()) setUrdfFile(path);
});
connect(m_urdfReference,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { m_urdfConfirmed->setChecked(false); refresh(); });
connect(m_urdfCamera,&QComboBox::currentTextChanged,this,[this] { m_urdfConfirmed->setChecked(false); refresh(); });
connect(m_urdfConfirmed,&QCheckBox::toggled,this,[this] { refresh(); });
connect(m_updateUrdf,&QPushButton::clicked,this,&HandEyeMotionWidget::chooseUrdfOutput);
m_timeout = new QTimer(this);
m_timeout->setSingleShot(true);
m_timeout->setInterval(6000);
connect(m_timeout,&QTimer::timeout,this,[this] {
if (!m_pendingToken) return;
invalidate(); refresh();
reportError(QStringLiteral("读取实时位姿超时,请检查机械臂连接后重试"));
});
connect(m_records,QOverload<int>::of(&QComboBox::currentIndexChanged),this,&HandEyeMotionWidget::selectRecord);
connect(reloadButton,&QPushButton::clicked,this,[this] { reload(); });
connect(m_convert,&QPushButton::clicked,this,&HandEyeMotionWidget::convert);
refresh();
}
void HandEyeMotionWidget::setContext(const QString &endpoint, const QString &device,
bool connected, bool demo, bool referenceConfirmed,
const TcpCalibration::Pose &activeOffset)
{
const bool scopeChanged = m_endpoint != endpoint || m_device != device;
const bool changed = scopeChanged || m_connected != connected || m_demo != demo
|| m_referenceConfirmed != referenceConfirmed || m_activeOffset != activeOffset;
m_endpoint=endpoint; m_device=device; m_connected=connected; m_demo=demo;
m_referenceConfirmed=referenceConfirmed; m_activeOffset=activeOffset;
if (!changed) return;
invalidate();
if (scopeChanged) {
m_urdfSource.clear(); m_urdfPath->clear(); m_urdfReference->clear(); m_urdfCamera->clear();
m_urdfConfirmed->setChecked(false); reload();
}
else refresh();
}
void HandEyeMotionWidget::reload(const QString &preferredName)
{
invalidate();
m_loading=true;
m_selected=-1;
m_snapshot=HandEyeStore::Snapshot{};
m_records->clear();
QString error;
bool loaded=true;
if (!m_endpoint.trimmed().isEmpty() && !m_device.trimmed().isEmpty()) {
QSettings settings;
loaded=HandEyeStore::load(settings,m_endpoint,m_device,m_snapshot,error);
}
int selected=-1;
const QString wanted=preferredName.isEmpty() ? m_snapshot.current : preferredName;
if(m_cameraScoped && !m_cameraSerial.isEmpty()) {
for(auto i=m_snapshot.records.begin();i!=m_snapshot.records.end();) {
if(!i->cameraSerial.isEmpty()&&i->cameraSerial!=m_cameraSerial) i=m_snapshot.records.erase(i); else ++i;
}
}
for (const auto &record : m_snapshot.records) {
const QString mode=record.mode==QStringLiteral("eye_in_hand")
? QStringLiteral("眼在手上") : QStringLiteral("眼在手外");
m_records->addItem(QStringLiteral("%1 · %2 · %3").arg(record.name,record.cameraId,mode),record.name);
if (record.name==wanted) selected=m_records->count()-1;
}
if (selected<0 && !m_snapshot.records.isEmpty()) selected=0;
m_records->setCurrentIndex(selected);
m_loading=false;
if (loaded && selected>=0) selectRecord(selected);
else refresh();
if (!loaded) reportError(error);
}
void HandEyeMotionWidget::invalidate()
{
++m_serial;
m_pendingToken=0;
m_resultValid=false;
if (m_timeout) m_timeout->stop();
for (auto *result : m_results) result->clear();
}
void HandEyeMotionWidget::setCameraCapabilities(const QString&,const QVariantMap& caps) {
const auto serial=caps.value("serial").toString();
const auto generation=caps.value("sessionGeneration").toULongLong();
if(m_cameraScoped && serial==m_cameraSerial && generation==m_cameraGeneration) return;
m_cameraScoped=true; m_cameraSerial=serial; m_cameraGeneration=generation; m_identityConfirmed->setChecked(false); reload();
}
void HandEyeMotionWidget::selectRecord(int index)
{
if (m_loading) return;
invalidate();
m_urdfConfirmed->setChecked(false);
m_identityConfirmed->setChecked(false);
m_selected=-1;
if (index>=0 && index<m_snapshot.records.size()) {
QSettings settings; QString error;
if (!HandEyeStore::select(settings,m_endpoint,m_device,m_snapshot.records.at(index).name,error)) {
refresh(); reportError(error); return;
}
m_selected=index;
}
refresh();
}
bool HandEyeMotionWidget::canConvert() const
{
if (m_selected<0 || m_selected>=m_snapshot.records.size() || m_pendingToken) return false;
if(m_cameraScoped && m_connected && !m_demo) {
if(m_cameraSerial.isEmpty()) return false;
const auto serial=m_snapshot.records.at(m_selected).cameraSerial;
if(serial.isEmpty()&&!m_identityConfirmed->isChecked()) return false;
if(!serial.isEmpty()&&serial!=m_cameraSerial) return false;
}
if (m_snapshot.records.at(m_selected).mode==QStringLiteral("eye_to_hand")) return true;
return m_connected && !m_demo && m_referenceConfirmed && TcpCalibration::validPose(m_activeOffset);
}
void HandEyeMotionWidget::refresh()
{
const bool selected=m_selected>=0 && m_selected<m_snapshot.records.size();
m_identityConfirmed->setVisible(m_cameraScoped && selected && m_snapshot.records[m_selected].cameraSerial.isEmpty());
m_identityConfirmed->setToolTip(QStringLiteral("确认该旧格式标定与当前相机序列号 %1 匹配;切换相机后需重新确认。").arg(m_cameraSerial));
const bool eyeInHand=selected && m_snapshot.records[m_selected].mode==QStringLiteral("eye_in_hand");
m_urdfConfirmed->setText(eyeInHand ? QStringLiteral("已核对:法兰 / 相机光学坐标系")
: QStringLiteral("已核对:基座 / 相机光学坐标系"));
m_updateUrdf->setEnabled(selected && !m_pendingToken && !m_urdfSource.isEmpty()
&& !m_urdfReference->currentData().toString().isEmpty() && !m_urdfCamera->currentText().trimmed().isEmpty()
&& m_urdfConfirmed->isChecked());
if (selected) {
const auto &r=m_snapshot.records[m_selected]; TcpCalibration::Pose p{};
TcpCalibration::matrixPose(r.transform,p);
m_recordInfo->setText(QStringLiteral("%1 · %2\nXYZ:%3 / %4 / %5 mm")
.arg(r.cameraId,eyeInHand?QStringLiteral("相机 → 法兰"):QStringLiteral("相机 → 基座"))
.arg(p[0]*1000,0,'f',3).arg(p[1]*1000,0,'f',3).arg(p[2]*1000,0,'f',3));
} else m_recordInfo->clear();
m_convert->setEnabled(canConvert());
m_records->setEnabled(!m_snapshot.records.isEmpty());
QString status, tooltip;
if (m_selected<0) status=QStringLiteral("当前机械臂暂无可用手眼标定");
else {
const bool onHand=m_snapshot.records.at(m_selected).mode==QStringLiteral("eye_in_hand");
tooltip=onHand ? QStringLiteral("Flange_T_Camera:相机 → 法兰;Base_T_Camera = Base_T_Flange × Flange_T_Camera;内部单位 m / rad")
: QStringLiteral("Base_T_Camera:相机 → 基座;内部单位 m / rad");
if (m_pendingToken) status=QStringLiteral("正在读取真实位姿…");
else if (m_resultValid) status=QStringLiteral("基座点已就绪 · 未发送运动");
else if (onHand && !canConvert()) status=QStringLiteral("请连接真实机械臂并核对活动 TCP 偏移");
else status=onHand ? QStringLiteral("转换时读取当前法兰位姿") : QStringLiteral("使用固定相机到基座的标定变换");
}
m_status->setText(status);
m_records->setToolTip(tooltip);
for (auto *result : m_results) result->setToolTip(tooltip);
}
void HandEyeMotionWidget::setUrdfFile(const QString &path)
{
m_urdfConfirmed->setChecked(false);
m_urdfSource.clear(); m_urdfPath->clear(); m_urdfReference->clear(); m_urdfCamera->clear();
QStringList links; QList<HandEyeUrdf::FixedJoint> joints; QString error;
if (!HandEyeUrdf::readUrdf(path,links,joints,error)) { refresh(); reportError(error); return; }
m_urdfSource=QFileInfo(path).absoluteFilePath();
m_urdfPath->setText(QDir::toNativeSeparators(m_urdfSource)); m_urdfPath->setToolTip(m_urdfPath->text());
m_urdfReference->addItem(QStringLiteral("选择基座 / 法兰坐标系"),QString());
for (const auto &link:links) m_urdfReference->addItem(link,link);
m_urdfCamera->addItems(links); m_urdfCamera->setCurrentIndex(-1); m_urdfCamera->setEditText(QString());
refresh();
}
bool HandEyeMotionWidget::exportUrdf(const QString &target,QString &error)
{
if (!m_updateUrdf->isEnabled()) { error=QStringLiteral("请选择标定结果、URDF 和坐标系,并确认坐标关系。"); return false; }
const auto record=m_snapshot.records[m_selected];
if (!HandEyeUrdf::update(m_urdfSource,target,m_urdfReference->currentData().toString(),
m_urdfCamera->currentText().trimmed(),record,error)) return false;
emit logMessage(QStringLiteral("OK"),QStringLiteral("已导出标定 URDF:%1 · %2").arg(record.name,target));
emit urdfUpdated(m_endpoint,m_device,QFileInfo(target).absoluteFilePath());
return true;
}
void HandEyeMotionWidget::chooseUrdfOutput()
{
if (!m_updateUrdf->isEnabled()) return;
const QString endpoint=m_endpoint,device=m_device,name=m_snapshot.records[m_selected].name,source=m_urdfSource;
const QFileInfo file(source);
const QString target=QFileDialog::getSaveFileName(this,QStringLiteral("导出标定 URDF(新文件)"),
file.dir().filePath(file.completeBaseName()+QStringLiteral("_calibrated.urdf")),QStringLiteral("URDF (*.urdf)"));
if (target.isEmpty()) return;
if (endpoint!=m_endpoint || device!=m_device || source!=m_urdfSource || m_selected<0
|| name!=m_snapshot.records[m_selected].name) { reportError(QStringLiteral("设备或标定结果已变化,请重新选择。")); return; }
QString error;
if (!exportUrdf(target,error)) reportError(error);
}
void HandEyeMotionWidget::convert()
{
if (!canConvert()) return;
for (auto *input : m_inputs) input->interpretText();
invalidate();
if (m_snapshot.records.at(m_selected).mode==QStringLiteral("eye_to_hand")) {
prepare({}); return;
}
m_pendingToken=(quint64(1)<<61) | (m_serial & ((quint64(1)<<61)-1));
m_timeout->start();
refresh();
emit captureRequested(m_device,m_pendingToken);
}
void HandEyeMotionWidget::acceptPose(quint64 requestId, const QString &deviceId,
const QVariantMap &pose, const QVariantMap &state,
bool success, const QString &detail)
{
if (!m_pendingToken || requestId!=m_pendingToken || deviceId!=m_device) return;
m_pendingToken=0;
m_timeout->stop();
refresh();
if (!success) {
reportError(detail.isEmpty() ? QStringLiteral("读取真实位姿失败") : detail); return;
}
if (!canConvert() || state.value("connected").type()!=QVariant::Bool
|| state.value("moving").type()!=QVariant::Bool || state.value("fault").type()!=QVariant::Bool
|| !state.value("connected").toBool() || state.value("moving").toBool() || state.value("fault").toBool()) {
reportError(QStringLiteral("机械臂状态不可用于转换,请停稳并重新核对")); return;
}
TcpCalibration::Pose tcp{}, flange{};
const char *keys[]={"x","y","z","rx","ry","rz"};
for (int i=0;i<6;++i) {
const QVariant value=pose.value(QLatin1String(keys[i]));
bool valid=false;
tcp[size_t(i)]=value.toDouble(&valid);
if (value.type()==QVariant::Bool || !valid || !std::isfinite(tcp[size_t(i)])) {
reportError(QStringLiteral("实时 TCP 位姿包含缺失或无效数值")); return;
}
}
QString error;
if (!TcpCalibration::flangePose(tcp,m_activeOffset,flange,&error)) {
reportError(QStringLiteral("无法由活动 TCP 换算法兰位姿:%1").arg(error)); return;
}
prepare(flange);
}
void HandEyeMotionWidget::prepare(const TcpCalibration::Pose &baseFlange)
{
if (m_selected<0 || m_selected>=m_snapshot.records.size()) return;
const auto record=m_snapshot.records.at(m_selected);
std::array<double,3> point{}, base{};
for (int i=0;i<3;++i) point[size_t(i)]=m_inputs.at(i)->value()/1000.0;
QString error;
if (!HandEyeStore::cameraPointToBase(record,baseFlange,point,base,error)) {
refresh(); reportError(error); return;
}
QVariantList values;
for (int i=0;i<3;++i) {
m_results.at(i)->setText(QStringLiteral("%1 mm").arg(base[size_t(i)]*1000.0,0,'f',3));
values.append(base[size_t(i)]);
}
m_resultValid=true;
refresh();
emit logMessage(QStringLiteral("OK"),QStringLiteral("相机点已转换为基座坐标 · %1 · %2 · 仅坐标转换")
.arg(record.cameraId,record.name));
// TODO: Integrate only after a visual-target motion pipeline and explicit
// target orientation semantics exist. A point alone must never command motion.
emit basePointPrepared(record.cameraId,record.name,values);
}
void HandEyeMotionWidget::reportError(const QString &message)
{
emit logMessage(QStringLiteral("WARN"),message);
QMessageBox::warning(this,QStringLiteral("手眼坐标转换"),message);
}