#include "touchsequencecontroller.h" #include #include #include namespace { constexpr int kReadTimeoutMs = 6000; constexpr int kMoveTimeoutMs = 30000; constexpr int kSequenceTimeoutMs = 180000; constexpr double kPositionToleranceM = .0005; constexpr double kRotationToleranceRad = .2 * 3.14159265358979323846 / 180; bool poseMatches(const TcpCalibration::Pose &actual, const TcpCalibration::Pose &expected) { double squaredDistance = 0; for (int i = 0; i < 3; ++i) squaredDistance += std::pow(actual[size_t(i)] - expected[size_t(i)], 2); if (squaredDistance > kPositionToleranceM * kPositionToleranceM) return false; TcpCalibration::Matrix a{}, b{}; if (!TcpCalibration::poseMatrix(actual, a) || !TcpCalibration::poseMatrix(expected, b)) return false; // Relative rotation, including equivalent Euler representations at +/-pi. double trace = 0; for (int row = 0; row < 3; ++row) for (int col = 0; col < 3; ++col) trace += a[size_t(row * 4 + col)] * b[size_t(row * 4 + col)]; const double angle = std::acos(std::max(-1.0, std::min(1.0, (trace - 1) / 2))); return angle <= kRotationToleranceRad; } bool stoppedHealthy(const QVariantMap &state) { return state.value("connected").toBool() && !state.value("moving", true).toBool() && !state.value("fault", true).toBool() && !state.value("protectiveStopped", true).toBool() && !state.value("emergencyStopped", true).toBool(); } } TouchSequenceController::TouchSequenceController(QObject *parent) : QObject(parent) { m_timeout.setSingleShot(true); m_deadline.setSingleShot(true); m_dwell.setSingleShot(true); m_dwell.setTimerType(Qt::PreciseTimer); connect(&m_timeout, &QTimer::timeout, this, [this] { fail(QStringLiteral("触控动作反馈超时,已请求停止;不会自动回程")); }); connect(&m_deadline, &QTimer::timeout, this, [this] { fail(QStringLiteral("触控任务超出总时限,已请求停止;不会自动回程")); }); connect(&m_dwell, &QTimer::timeout, this, [this] { if (m_phase == Phase::Dwelling) readPose(Phase::AfterDwellRead); }); } QString TouchSequenceController::commandName(quint64 token) { // RobotClient::requestTcpJogMove uses this existing command namespace. return QStringLiteral("TCPJog/%1").arg(token); } void TouchSequenceController::setContext(const QString &endpoint, const QString &device, bool ready, const TcpCalibration::Pose &activeOffset, const QString &contextRevision) { if (m_endpoint != endpoint || m_device != device || m_ready != ready || m_activeOffset != activeOffset || m_contextRevision != contextRevision) stop(); // Stop the old device before replacing its identity. m_endpoint = endpoint; m_device = device; m_ready = ready; m_activeOffset = activeOffset; m_contextRevision = contextRevision; } bool TouchSequenceController::start(const QVector &steps, const TcpCalibration::Pose &expectedInitialPose) { if (running()) return false; bool valid = m_ready && !m_endpoint.trimmed().isEmpty() && !m_device.trimmed().isEmpty() && TcpCalibration::validPose(m_activeOffset) && TcpCalibration::validPose(expectedInitialPose) && !steps.isEmpty() && steps.size() <= 128; for (const auto &step : steps) { valid = valid && TcpCalibration::validPose(step.target) && std::isfinite(step.speed) && step.speed > 0 && step.speed <= .05 && std::isfinite(step.acceleration) && step.acceleration > 0 && step.acceleration <= .5 && step.dwellMs >= 0 && step.dwellMs <= 5000; } if (!valid) { emit errorOccurred(QStringLiteral("触控路径或机械臂上下文无效,请核对连接、活动 TCP 和运动参数")); return false; } m_steps = steps; m_expected = expectedInitialPose; m_index = 0; m_deadline.start(kSequenceTimeoutMs); readPose(Phase::InitialRead); return true; } void TouchSequenceController::readPose(Phase phase) { m_phase = phase; ++m_token; m_captureIssuedAtMs = QDateTime::currentMSecsSinceEpoch(); m_timeout.start(kReadTimeoutMs); emit captureRequested(m_device, m_token); } void TouchSequenceController::moveNext() { if (!running()) return; const Step step = m_steps.at(m_index); m_phase = Phase::Moving; const quint64 token = ++m_token; m_timeout.start(kMoveTimeoutMs); emit progressChanged(m_index + 1, m_steps.size(), step.label); // A direct progress listener may cancel or change context synchronously. if (m_phase != Phase::Moving || m_token != token) return; QVariantMap target; const char *keys[] = {"x", "y", "z", "rx", "ry", "rz"}; for (int i = 0; i < 6; ++i) target[keys[i]] = step.target[size_t(i)]; emit moveRequested(m_device, target, step.speed, step.acceleration, token); } void TouchSequenceController::acceptPose(quint64 token, const QString &device, const QVariantMap &pose, const QVariantMap &state, bool success, const QString &detail) { if ((m_phase != Phase::InitialRead && m_phase != Phase::VerifyRead && m_phase != Phase::AfterDwellRead) || token != m_token || device != m_device) return; if (!success) { fail(detail.isEmpty() ? QStringLiteral("触控任务读取实时位姿失败") : detail); return; } if (!stoppedHealthy(state)) { fail(QStringLiteral("机械臂未停稳、未连接或处于故障/停止状态,已取消触控任务")); return; } bool requestedOk = false, receivedOk = false; const qint64 requested = state.value("requestedAtMs").toLongLong(&requestedOk); const qint64 received = state.value("receivedAtMs").toLongLong(&receivedOk); const qint64 now = QDateTime::currentMSecsSinceEpoch(); if (!requestedOk || !receivedOk || requested < m_captureIssuedAtMs || received < requested || received > now + 50 || now - received > 1500 || state.value("source").toString() != QStringLiteral("getRobotState.actual_tcp_pose")) { fail(QStringLiteral("触控任务收到过期或来源不明的位姿,已请求停止")); return; } TcpCalibration::Pose actual{}; const char *keys[] = {"x", "y", "z", "rx", "ry", "rz"}; for (int i = 0; i < 6; ++i) { bool ok = false; actual[size_t(i)] = pose.value(keys[i]).toDouble(&ok); if (!ok || !std::isfinite(actual[size_t(i)])) { fail(QStringLiteral("触控任务收到无效的 TCP 位姿")); return; } } if (!poseMatches(actual, m_expected)) { fail(m_phase == Phase::InitialRead ? QStringLiteral("当前位姿已偏离观察位(允许 0.5 mm / 0.2°),请重新定位并确认画面") : QStringLiteral("实际 TCP 未到达触控路径目标(允许 0.5 mm / 0.2°),已停止且不会自动回程")); return; } m_timeout.stop(); if (m_phase == Phase::InitialRead) { moveNext(); } else if (m_phase == Phase::VerifyRead && m_steps.at(m_index).dwellMs > 0) { m_phase = Phase::Dwelling; ++m_token; m_dwell.start(m_steps.at(m_index).dwellMs); } else { completeStep(); } } void TouchSequenceController::acceptCommand(const QString &command, bool success, const QString &detail) { if (m_phase != Phase::Moving || command != commandName(m_token)) return; if (!success) { fail(detail.isEmpty() ? QStringLiteral("触控运动命令失败") : detail); return; } m_expected = m_steps.at(m_index).target; readPose(Phase::VerifyRead); } void TouchSequenceController::completeStep() { ++m_index; if (m_index == m_steps.size()) finish(true, QStringLiteral("触控路径已完成,实际 TCP 已到达最终目标"), false); else moveNext(); } void TouchSequenceController::finish(bool success, const QString &detail, bool requestStop) { if (!running()) return; const QString device = m_device; m_phase = Phase::Idle; ++m_token; m_timeout.stop(); m_deadline.stop(); m_dwell.stop(); m_steps.clear(); if (requestStop) emit stopRequested(device); emit finished(success, detail); } void TouchSequenceController::stop() { finish(false, QStringLiteral("触控任务已取消并请求停止;不会自动回程"), true); } void TouchSequenceController::fail(const QString &message) { if (!running()) return; finish(false, message, true); emit errorOccurred(message); }