Compare commits

...

17 Commits

Author SHA1 Message Date
lgv
db1c34a706 chore(touch): tune Xiaozhao alignment offsets and thresholds
Adjust alignment offsets and Y tolerance, and disable automatic head initialization in the Xiaozhao real-device touch task.
2026-12-02 11:55:54 +08:00
lgv
49137cce0b feat(ik): optimize pose solutions away from joint limits
Add configurable joint-limit clearance optimization after pose convergence and regression coverage. Enable the optimizer for the Xiaozhao arm with bounded iteration and joint steps.
2026-12-02 11:55:54 +08:00
lgv
a761f4e935 Merge remote-tracking branch 'origin/dev' into dev 2026-12-02 11:52:02 +08:00
lgv
054cd4a211 chore(config): tune Xiaozhao real-device settings 2026-12-01 11:53:19 +08:00
lgv
5443a05972 chore(quic): enable edge task and reduce service logs 2026-11-30 17:16:48 +08:00
lgv
59576ff7e9 chore(ethercat): log cyclic timing on missed deadlines 2026-11-30 17:16:48 +08:00
lgv
f667bbde73 chore(config): tune Xiaozhao touch and neck settings 2026-11-30 17:16:47 +08:00
lgv
8df528ed7c fix(touch): recover SpeedL faults and record MoveP pose samples 2026-11-30 17:16:47 +08:00
3e10160411 feat: port Huayan cabinet IO and bounded SocketCAN receive to dev 2026-11-27 09:35:16 +08:00
lgv
b293b1d6f2 fix(touch): use elapsed visual update time for PBVS 2026-11-26 17:50:55 +08:00
lgv
2ea3dc7467 fix(ethercat): skip expired cycle deadlines and report timing 2026-11-26 17:50:55 +08:00
lgv
b6a7c8a2b4 chore(systemd): add CMVR ES service unit 2026-11-26 17:06:06 +08:00
lgv
68286bf220 chore(config): calibrate Xiaozhao touch and device settings 2026-11-26 17:06:06 +08:00
lgv
ef0fa4ee2c feat(touch): update AprilTag sizing and camera preview overlays 2026-11-26 17:06:06 +08:00
lgv
e22d86deb1 fix(speedl): preserve recoverable braking fault classification 2026-11-26 17:06:06 +08:00
lgv
f7cc998c3d fix(config): tune Xiaozhao right-arm SpeedL limits 2026-11-26 17:03:45 +08:00
lgv
4c4f4971f9 config : add touch config 2026-11-23 11:10:51 +08:00
58 changed files with 2002 additions and 788 deletions

View File

@ -78,6 +78,15 @@ public:
private:
bool refreshJointLimitPolicy_();
Eigen::Matrix<double, 6, 1> poseErrorAt_(const Eigen::VectorXd& q_full,
pinocchio::FrameIndex target_frame,
const pinocchio::SE3& base_target);
Eigen::Matrix<double, 6, 1> weightedPoseError_(Eigen::Matrix<double, 6, 1> error) const;
Eigen::MatrixXd poseJacobianAt_(const Eigen::VectorXd& q_full,
pinocchio::FrameIndex target_frame);
void improvePoseJointLimitDistance_(Eigen::VectorXd& q_full,
pinocchio::FrameIndex target_frame,
const pinocchio::SE3& base_target);
// 配置
config::PinocchioQpIKConfig config_;

View File

@ -160,6 +160,15 @@ namespace cmvr {
}
bool PinocchioQpIKSolver::init() {
const auto& pose_avoidance = config_.pose_ik_joint_limit_avoidance();
if (pose_avoidance.enable() &&
((pose_avoidance.has_max_iters() && pose_avoidance.max_iters() <= 0) ||
(pose_avoidance.has_max_joint_step_rad() &&
(!std::isfinite(pose_avoidance.max_joint_step_rad()) || pose_avoidance.max_joint_step_rad() <= 0.0)))) {
CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] invalid pose IK joint limit avoidance settings";
return false;
}
if (!urdf_chain_cached_) {
if (urdf_path_.empty() ||
chain_base_frame_name_.empty() ||
@ -337,6 +346,157 @@ namespace cmvr {
return true;
}
Eigen::Matrix<double, 6, 1> PinocchioQpIKSolver::poseErrorAt_(
const VectorXd& q_full, const pinocchio::FrameIndex target_frame,
const pinocchio::SE3& base_target)
{
updateKinematics(q_full);
const pinocchio::SE3 world_target = base_frame_id_ == static_cast<pinocchio::FrameIndex>(-1)
? base_target : data_->oMf[base_frame_id_] * base_target;
return pinocchio::log6(data_->oMf[target_frame].inverse() * world_target).toVector();
}
Eigen::Matrix<double, 6, 1> PinocchioQpIKSolver::weightedPoseError_(
Eigen::Matrix<double, 6, 1> error) const
{
error.head<3>() *= 1.0 - w_posrot_;
error.tail<3>() *= w_posrot_;
return error;
}
MatrixXd PinocchioQpIKSolver::poseJacobianAt_(
const VectorXd& q_full, const pinocchio::FrameIndex target_frame)
{
Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian =
Eigen::Matrix<double, 6, Eigen::Dynamic>::Zero(6, model().nv);
pinocchio::computeFrameJacobian(model(), *data_, q_full, target_frame,
pinocchio::ReferenceFrame::LOCAL, jacobian);
return extractChainJacobian(jacobian);
}
void PinocchioQpIKSolver::improvePoseJointLimitDistance_(
VectorXd& q_full, const pinocchio::FrameIndex target_frame,
const pinocchio::SE3& base_target)
{
const auto& settings = config_.pose_ik_joint_limit_avoidance();
if (!settings.enable() || jointLimitsDisabled()) return;
const Eigen::Index dof = chain_q_dof_;
const auto& lower = joint_pos_lower_limits_;
const auto& upper = joint_pos_upper_limits_;
const VectorXd spans = upper - lower;
std::vector<Eigen::Index> bounded_joints;
for (Eigen::Index i = 0; i < dof; ++i) {
if (std::isfinite(spans[i]) && spans[i] > 0.0) bounded_joints.push_back(i);
}
if (bounded_joints.empty()) return;
const auto clearance = [&](const VectorXd& q) {
double distance_ratio = 0.5;
for (const auto i : bounded_joints) {
distance_ratio = std::min(distance_ratio,
std::min(q[i] - lower[i], upper[i] - q[i]) / spans[i]);
}
return distance_ratio;
};
constexpr Eigen::Index pose_dimension = 6;
const Eigen::Index limit_row = dof + 1 + pose_dimension;
const Eigen::Index rows = limit_row + 2 * static_cast<Eigen::Index>(bounded_joints.size());
MatrixXd constraints = MatrixXd::Zero(rows, dof + 1);
constraints.topRows(dof + 1).setIdentity();
VectorXd min_constraint = VectorXd::Zero(rows);
VectorXd max_constraint = VectorXd::Zero(rows);
max_constraint[dof] = 0.5;
// With rho in [0, 0.5], minimizing (rho - 0.5)^2 maximizes clearance.
MatrixXd cost = MatrixXd::Zero(1, dof + 1);
cost(0, dof) = 1.0;
QPSolver clearance_solver;
clearance_solver.Setup(dof + 1, rows, qp_time_limit_, 1e-8, 1e-8, true);
clearance_solver.SetCostFunction(cost, VectorXd::Constant(1, 0.5));
const double max_step = settings.has_max_joint_step_rad() ? settings.max_joint_step_rad() : 0.02;
const int max_iters = settings.has_max_iters() ? settings.max_iters() : 20;
const VectorXd step_limit = joint_vel_limits_.cwiseMin(qdd_max_global_).cwiseMin(max_step);
VectorXd best_q = q_full.segment(chain_q_start_, dof);
const double initial_clearance = clearance(best_q);
double best_clearance = initial_clearance;
constexpr double min_improvement = 1e-7;
for (int iteration = 0; iteration < max_iters && best_clearance < 0.5 - min_improvement; ++iteration) {
const VectorXd min_step = (-step_limit).cwiseMax(lower - best_q);
const VectorXd max_step_at_q = step_limit.cwiseMin(upper - best_q);
min_constraint.head(dof) = min_step;
max_constraint.head(dof) = max_step_at_q;
const MatrixXd jacobian = poseJacobianAt_(q_full, target_frame);
if (!jacobian.allFinite()) break;
constraints.block(dof + 1, 0, pose_dimension, dof) = jacobian;
Eigen::Index row = limit_row;
for (const auto i : bounded_joints) {
constraints(row, i) = 1.0;
constraints(row, dof) = -spans[i];
min_constraint[row] = lower[i] - best_q[i];
max_constraint[row++] = max_step_at_q[i];
constraints(row, i) = 1.0;
constraints(row, dof) = spans[i];
min_constraint[row] = min_step[i];
max_constraint[row++] = upper[i] - best_q[i];
}
clearance_solver.SetConstraintsFunction(constraints, min_constraint, max_constraint);
VectorXd initial = VectorXd::Zero(dof + 1);
initial[dof] = best_clearance;
clearance_solver.SetPrimalVariable(initial);
VectorXd solution;
try {
solution = clearance_solver.Solve();
} catch (const QPSolverException&) {
break;
}
if (solution.size() != dof + 1 || !solution.allFinite() ||
solution[dof] <= best_clearance + min_improvement) break;
const VectorXd step = solution.head(dof).cwiseMax(min_step).cwiseMin(max_step_at_q);
bool accepted = false;
double scale = 1.0;
constexpr int max_backtracks = 8;
for (int attempt = 0; attempt < max_backtracks; ++attempt, scale *= 0.5) {
VectorXd candidate = kinematics::clampToJointPositionLimits(best_q + scale * step, lower, upper);
if (clearance(candidate) <= best_clearance + min_improvement) continue;
q_full.segment(chain_q_start_, dof) = candidate;
auto error = poseErrorAt_(q_full, target_frame, base_target);
if (!error.allFinite()) continue;
if (weightedPoseError_(error).norm() >= tol_) {
// A null-space step is only first-order accurate. Correct
// its residual within the same local joint step bounds.
const MatrixXd candidate_jacobian = poseJacobianAt_(q_full, target_frame);
const VectorXd correction = moorePenrosePseudoInverse(candidate_jacobian) * error;
const VectorXd corrected_step = (candidate - best_q + correction).cwiseMax(min_step).cwiseMin(max_step_at_q);
candidate = kinematics::clampToJointPositionLimits(best_q + corrected_step, lower, upper);
q_full.segment(chain_q_start_, dof) = candidate;
error = poseErrorAt_(q_full, target_frame, base_target);
}
const double candidate_clearance = clearance(candidate);
if (candidate.allFinite() && weightedPoseError_(error).norm() < tol_ &&
candidate_clearance > best_clearance + min_improvement) {
best_q = candidate;
best_clearance = candidate_clearance;
accepted = true;
break;
}
}
q_full.segment(chain_q_start_, dof) = best_q;
if (!accepted) break;
}
updateKinematics(q_full);
CMVR_LOG(DEBUG) << "[PinocchioQpIKSolver][POSE_JOINT_LIMIT_AVOIDANCE] initial_clearance_ratio="
<< initial_clearance << ", final_clearance_ratio=" << best_clearance
<< ", goal=" << vectorToString(best_q);
}
bool PinocchioQpIKSolver::ik(const Matrix4d &target_pose,
std::vector<double> &joints_angle,
bool is_tcp) {
@ -367,15 +527,19 @@ namespace cmvr {
// 约定:target_pose 是 base_frame_name_ 下的 ^baseT_target
pinocchio::SE3 base_M_target = matrix4ToSE3(target_pose);
// 子链当前关节角(局部 DOF 大小)
Eigen::VectorXd q_local = Eigen::Map<Eigen::VectorXd>(
cur_joints_angle_.data(), cur_joints_angle_.size());
Eigen::VectorXd q_full;
if (!buildFullQFromInput(cur_joints_angle_, q_full, "ik(qp)")) {
return false;
}
const VectorXd &q_min = joint_pos_lower_limits_;
const VectorXd &q_max = joint_pos_upper_limits_;
const VectorXd &qd_max = joint_vel_limits_;
const VectorXd &qdd_max = qdd_max_global_;
VectorXd q_local = kinematics::clampToJointPositionLimits(
q_full.segment(chain_q_start_, chain_q_dof_), q_min, q_max);
q_full.segment(chain_q_start_, chain_q_dof_) = q_local;
auto error = weightedPoseError_(poseErrorAt_(q_full, target_frame_id, base_M_target));
// 初始化 QP(变量 = 子链 DOF,约束 = 子链 DOF,因为只做 box 约束)
solver_.Setup(chain_q_dof_, chain_q_dof_, qp_time_limit_);
@ -384,51 +548,15 @@ namespace cmvr {
MatrixXd A_cost;
VectorXd b_cost;
const VectorXd &q_min = joint_pos_lower_limits_;
const VectorXd &q_max = joint_pos_upper_limits_;
const VectorXd &qd_max = joint_vel_limits_;
const VectorXd &qdd_max = qdd_max_global_;
for (int iter = 0; iter < max_iters_; ++iter) {
// 1) 用 q_full 做正解 + frame pose + J_full
updateKinematics(q_full);
const pinocchio::SE3 &oM_curr = data_->oMf[target_frame_id];
// 0Tbase
pinocchio::SE3 oM_base = pinocchio::SE3::Identity();
if (base_frame_id_ != (pinocchio::FrameIndex) (-1)) {
oM_base = data_->oMf[base_frame_id_];
}
// 0Ttarget = 0Tbase * baseTtarget
pinocchio::SE3 oM_target = oM_base * base_M_target;
// 当前 -> 目标的 SE3 误差
pinocchio::SE3 dM = oM_curr.inverse() * oM_target;
Eigen::Matrix<double, 6, 1> dx = pinocchio::log6(dM).toVector();
dx.head<3>() *= (1.0 - w_posrot_);
dx.tail<3>() *= w_posrot_;
// 6×nv Jacobian(LOCAL)
Eigen::Matrix<double, 6, Eigen::Dynamic> J_full(6, model().nv);
pinocchio::computeFrameJacobian(model(), *data_, q_full,
target_frame_id,
pinocchio::ReferenceFrame::LOCAL,
J_full);
// 抽取子链对应列 => 6×chain_q_dof_ 雅可比
MatrixXd J = J_full.middleCols(chain_v_start_, chain_v_dof_);
for (int iter = 0; iter < max_iters_ && error.allFinite() && error.norm() >= tol_; ++iter) {
// 2) 构造代价:|| A_cost * dq - b_cost ||^2
constexpr std::size_t n_eq = 6;
constexpr Eigen::Index n_eq = 6;
A_cost.resize(n_eq + chain_q_dof_, chain_q_dof_);
b_cost.resize(n_eq + chain_q_dof_);
// 任务部分
A_cost.block(0, 0, 6, chain_q_dof_) = J;
b_cost.segment(0, 6) = dx;
A_cost.topRows(n_eq) = poseJacobianAt_(q_full, target_frame_id);
b_cost.head(n_eq) = error;
// 阻尼项
A_cost.bottomRows(chain_q_dof_) = std::sqrt(lambda_) *
@ -475,24 +603,18 @@ namespace cmvr {
q_local = cmvr::kinematics::clampToJointPositionLimits(q_local, q_min, q_max);
q_full.segment(chain_q_start_, chain_q_dof_) = q_local;
// 6) 收敛检查
double err_norm = b_cost.head(n_eq).norm();
if (err_norm < tol_) {
cur_joints_angle_.assign(q_local.data(), q_local.data() + q_local.size());
joints_angle = cur_joints_angle_;
return true;
}
if (dq_local.norm() < 1e-6) {
cur_joints_angle_.assign(q_local.data(), q_local.data() + q_local.size());
joints_angle = cur_joints_angle_;
return false;
}
error = weightedPoseError_(poseErrorAt_(q_full, target_frame_id, base_M_target));
if (dq_local.norm() < 1e-6) break;
}
// 未收敛,返回 best effort
const bool converged = error.norm() < tol_;
if (converged) {
improvePoseJointLimitDistance_(q_full, target_frame_id, base_M_target);
q_local = q_full.segment(chain_q_start_, chain_q_dof_);
}
cur_joints_angle_.assign(q_local.data(), q_local.data() + q_local.size());
joints_angle = cur_joints_angle_;
return false;
return converged;
}
bool PinocchioQpIKSolver::solveVelocityBase(

View File

@ -6,6 +6,7 @@
#include <vector>
#include <gtest/gtest.h>
#include <pinocchio/spatial/explog.hpp>
#include "common/io/proto_file_io.h"
#include "cmvr/config/arm_config/arm_config.pb.h"
@ -44,6 +45,23 @@ config::PinocchioQpIKConfig loadQpConfig(const std::filesystem::path& root)
return solver_config;
}
config::PinocchioQpIKConfig loadXiaozhaoRightArmQpConfig(const std::filesystem::path& root)
{
config::ArmRootConfig root_config;
const auto config_path = root / "cmvr-es/config/devices/arm/xiaozhao_tchl_arm.pb.txt";
if (ProtoMessageIo::getProtoFromAsciiFile(config_path.string(), &root_config)) {
for (const auto& arm : root_config.arm().robot_arms()) {
if (arm.id() == "xiaozhao_tchl_right_arm") {
auto solver_config = arm.kinematics().pinocchio_qp_ik_solver();
solver_config.set_urdf_path((root / solver_config.urdf_path()).string());
return solver_config;
}
}
}
ADD_FAILURE() << "Missing Xiaozhao right-arm QP IK fixture";
return {};
}
TEST(PinocchioQpIKSolverTest, JointLimitAvoidanceIsInCartesianNullspace)
{
Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7);
@ -466,5 +484,90 @@ TEST(PinocchioQpIKSolverTest, PoseIkStillConvergesWithExistingConfiguration)
EXPECT_LT((achieved_pose.block<3, 3>(0, 0) - target_pose.block<3, 3>(0, 0)).norm(), 1e-5);
}
TEST(PinocchioQpIKSolverTest, PoseIkJointLimitAvoidanceImprovesClearanceAtSameTcpPose)
{
const auto root = findProjectRoot();
ASSERT_FALSE(root.empty());
auto baseline_config = loadXiaozhaoRightArmQpConfig(root);
baseline_config.clear_pose_ik_joint_limit_avoidance();
auto avoided_config = baseline_config;
avoided_config.mutable_pose_ik_joint_limit_avoidance()->set_enable(true);
PinocchioQpIKSolver baseline_solver(baseline_config);
PinocchioQpIKSolver avoided_solver(avoided_config);
ASSERT_TRUE(baseline_solver.init());
ASSERT_TRUE(avoided_solver.init());
// Joint 6 starts near its 0.42 rad limit with room to move in the null space.
const std::vector<double> seed = {0.0986988, 0.786383, 1.43618, -1.62011,
-2.26993, 0.419, -0.135876};
Eigen::Matrix4d target_pose;
ASSERT_TRUE(baseline_solver.fk(seed, target_pose, true));
baseline_solver.update_joints_state(seed);
avoided_solver.update_joints_state(seed);
std::vector<double> baseline;
std::vector<double> avoided;
ASSERT_TRUE(baseline_solver.ik(target_pose, baseline, true));
ASSERT_TRUE(avoided_solver.ik(target_pose, avoided, true));
ASSERT_EQ(baseline.size(), seed.size());
ASSERT_EQ(avoided.size(), seed.size());
Eigen::VectorXd lower, upper;
ASSERT_TRUE(avoided_solver.getJointPositionLimits(lower, upper));
ASSERT_EQ(lower.size(), seed.size());
ASSERT_EQ(upper.size(), seed.size());
double baseline_clearance = 0.5;
double avoided_clearance = 0.5;
for (Eigen::Index i = 0; i < lower.size(); ++i) {
SCOPED_TRACE(i);
EXPECT_GE(avoided[i], lower[i]);
EXPECT_LE(avoided[i], upper[i]);
const double span = upper[i] - lower[i];
ASSERT_GT(span, 0.0);
baseline_clearance = std::min(
baseline_clearance, std::min(baseline[i] - lower[i], upper[i] - baseline[i]) / span);
avoided_clearance = std::min(
avoided_clearance, std::min(avoided[i] - lower[i], upper[i] - avoided[i]) / span);
}
EXPECT_GT(avoided_clearance, baseline_clearance + 1e-4);
EXPECT_LT(avoided[5], baseline[5] - 1e-4);
Eigen::Matrix4d achieved_pose;
ASSERT_TRUE(avoided_solver.fk(avoided, achieved_pose, true));
const pinocchio::SE3 achieved(achieved_pose.block<3, 3>(0, 0), achieved_pose.block<3, 1>(0, 3));
const pinocchio::SE3 target(target_pose.block<3, 3>(0, 0), target_pose.block<3, 1>(0, 3));
Eigen::Matrix<double, 6, 1> error = pinocchio::log6(achieved.inverse() * target).toVector();
error.head<3>() *= 1.0 - avoided_config.w_posrot();
error.tail<3>() *= avoided_config.w_posrot();
EXPECT_LE(error.norm(), avoided_config.tol());
}
TEST(PinocchioQpIKSolverTest, PoseIkJointLimitAvoidanceKeepsAlreadyCenteredSolution)
{
const auto root = findProjectRoot();
ASSERT_FALSE(root.empty());
auto config = loadXiaozhaoRightArmQpConfig(root);
auto* limits = config.mutable_joint_limit_policy()->mutable_limits();
const std::vector<double> seed = {0.1, 0.7, 1.4, -1.6, -2.2, 0.2, -0.1};
ASSERT_EQ(limits->joints_size(), seed.size());
for (int i = 0; i < limits->joints_size(); ++i) {
limits->mutable_joints(i)->set_q_lb(seed[i] - 0.2);
limits->mutable_joints(i)->set_q_ub(seed[i] + 0.2);
}
config.mutable_pose_ik_joint_limit_avoidance()->set_enable(true);
PinocchioQpIKSolver solver(config);
ASSERT_TRUE(solver.init());
Eigen::Matrix4d target_pose;
ASSERT_TRUE(solver.fk(seed, target_pose, true));
solver.update_joints_state(seed);
std::vector<double> result;
ASSERT_TRUE(solver.ik(target_pose, result, true));
ASSERT_EQ(result.size(), seed.size());
for (std::size_t i = 0; i < result.size(); ++i) {
EXPECT_NEAR(result[i], seed[i], 1e-12);
}
}
} // namespace
} // namespace cmvr

View File

@ -31,7 +31,7 @@ namespace cmvr::perception {
* - `t`:AprilTag 自身坐标系,原点位于 tag 中心,z 轴垂直于 tag 平面。
*
* 使用约定:
* - 每周期调用一次 `update()`;
* - 每周期调用一次 `update()` 或 `updateFromRgbFrame()`;
* - 其他模块(如 `TagRelativeTarget3D` / `IbvsController`)只读取缓存,不重复抓帧。
*/
class AprilTagPerception {
@ -70,6 +70,9 @@ public:
// 抓取编码帧时传入相机驱动的索引。
size_t encoded_index{0};
// Raw RGB acquisition timing, independent of any encoded frame request.
bool capture_rgb_timing{false};
};
struct Tag {
@ -112,9 +115,11 @@ public:
// `visp_I` 当前缓存的图像高度。
int visp_h{0};
// 本类内部维护的帧序号,每次 `update()` 成功后自增。
// 本类内部维护的帧序号,每次更新成功后自增。
uint64_t frame_id{0};
device::RgbFrameTiming rgb_timing;
void clearDerived() {
gray.release();
has_gray = false;
@ -138,12 +143,17 @@ public:
const std::shared_ptr<cmvr::device::AbstractCamera>& camera() const { return camera_; }
/**
* @brief 设置 tag 物理边长。
* @brief 设置未单独配置的 tag 的默认物理边长。
* @param tag_size_m tag 边长,单位米。
*/
void setTagSize(double tag_size_m);
double tagSize() const { return tag_size_m_; }
/**
* @brief 按 ID 设置 tag 的黑框外边长,单位米。
*/
void setTagSizeForId(int id, double tag_size_m);
/**
* @brief 设置 AprilTag 家族。
* @param fam AprilTag 家族类型。
@ -157,7 +167,15 @@ public:
bool update(const Options& opt);
/**
* @brief 获取最近一次 `update()` 的状态。
* @brief 在已有的彩色帧上检测 AprilTag,无需相机对象。
* @param color 灰度、BGR 或 BGRA 图像。缓存共享像素数据,调用方需保持帧内容不变。
* @param intrinsics 与该帧尺寸对应的相机内参。
* @return 成功检测到至少一个标签时返回 `true`。
*/
bool updateFromRgbFrame(const cv::Mat& color, const device::Rs2Intrinsics& intrinsics);
/**
* @brief 获取最近一次更新的状态。
* @return 最近一次状态枚举。
*/
Status lastStatus() const { return last_status_; }
@ -215,6 +233,10 @@ public:
const Tag* findTag(int id) const;
private:
void clearFrameResults();
bool validateColorFrame();
bool processFrame(const Options& opt);
/**
* @brief 按 `Options` 抓取当前帧的 RGB / depth 数据并填充 `frame_.stream`。
* @param opt 本次更新使用的抓帧选项。
@ -261,8 +283,9 @@ private:
// AprilTag 检测器。
vpDetectorAprilTag detector_{vpDetectorAprilTag::TAG_36h11};
// tag 物理边长,单位米。
// 默认和按 ID 配置的 tag 物理边长,单位米。
double tag_size_m_{0.12};
std::unordered_map<int, double> tag_sizes_by_id_;
// 与当前内参对应的 ViSP 相机模型。
vpCameraParameters visp_cam_;
@ -276,7 +299,7 @@ private:
// tag id 到 `tags_` 下标的映射。
std::unordered_map<int, size_t> id_to_index_;
// 最近一次 `update()` 的状态。
// 最近一次更新的状态。
Status last_status_{Status::NO_NEW_FRAME};
};

View File

@ -4,9 +4,10 @@
#include "algorithms/perception/apriltag/include/apriltag_perception.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
#include <utility>
#include <opencv2/imgproc.hpp>
@ -19,10 +20,8 @@ AprilTagPerception::AprilTagPerception(const std::shared_ptr<cmvr::device::Abstr
void AprilTagPerception::setCamera(const std::shared_ptr<cmvr::device::AbstractCamera>& camera) {
camera_ = camera;
tags_.clear();
id_to_index_.clear();
clearFrameResults();
frame_.stream = device::StreamFrameData{};
frame_.clearDerived();
frame_.frame_id = 0;
last_status_ = Status::NO_NEW_FRAME;
}
@ -33,6 +32,12 @@ void AprilTagPerception::setTagSize(double tag_size_m) {
}
}
void AprilTagPerception::setTagSizeForId(int id, double tag_size_m) {
if (id >= 0 && std::isfinite(tag_size_m) && tag_size_m > 0.0) {
tag_sizes_by_id_[id] = tag_size_m;
}
}
void AprilTagPerception::setTagFamily(vpDetectorAprilTag::vpAprilTagFamily fam) {
detector_ = vpDetectorAprilTag(fam);
detector_.setAprilTagPoseEstimationMethod(vpDetectorAprilTag::HOMOGRAPHY_VIRTUAL_VS);
@ -53,14 +58,28 @@ const char* AprilTagPerception::statusToString(Status s) {
}
bool AprilTagPerception::update(const Options& opt) {
clearFrameResults();
return grabFrame(opt) && processFrame(opt);
}
bool AprilTagPerception::updateFromRgbFrame(const cv::Mat& color,
const device::Rs2Intrinsics& intrinsics) {
device::StreamFrameData stream;
stream.rgbImage = color;
stream.intrinsics = intrinsics;
clearFrameResults();
frame_.stream = std::move(stream);
return validateColorFrame() && processFrame(Options{});
}
void AprilTagPerception::clearFrameResults() {
tags_.clear();
id_to_index_.clear();
frame_.clearDerived();
frame_.rgb_timing = {};
}
if (!grabFrame(opt)) {
return false;
}
bool AprilTagPerception::processFrame(const Options& opt) {
// intrinsics -> visp camera params
const double fx = static_cast<double>(frame_.stream.intrinsics.fx);
const double fy = static_cast<double>(frame_.stream.intrinsics.fy);
@ -109,9 +128,18 @@ bool AprilTagPerception::grabFrame(const Options& opt) {
frame_.stream.bKey = false;
frame_.stream.depthKey = false;
const auto read_rgb = [&] {
if (opt.capture_rgb_timing) {
camera_->getRGBImageWithTiming(frame_.stream.rgbImage, frame_.stream.intrinsics,
frame_.rgb_timing);
frame_.rgb_timing.host_read_complete_at = std::chrono::steady_clock::now();
} else {
camera_->getRGBImage(frame_.stream.rgbImage, frame_.stream.intrinsics);
}
};
try {
if (opt.depth_policy == DepthPolicy::NONE) {
camera_->getRGBImage(frame_.stream.rgbImage, frame_.stream.intrinsics);
read_rgb();
} else {
camera_->getRGBDImages(frame_.stream.rgbImage, frame_.stream.depthImage, frame_.stream.intrinsics);
}
@ -119,7 +147,7 @@ bool AprilTagPerception::grabFrame(const Options& opt) {
// PREFER: 允许回退 RGB
if (opt.depth_policy == DepthPolicy::PREFER) {
try {
camera_->getRGBImage(frame_.stream.rgbImage, frame_.stream.intrinsics);
read_rgb();
frame_.stream.depthImage.release();
} catch (...) {
last_status_ = Status::NO_NEW_FRAME;
@ -131,15 +159,7 @@ bool AprilTagPerception::grabFrame(const Options& opt) {
}
}
if (frame_.stream.rgbImage.empty()) {
last_status_ = Status::NO_NEW_FRAME;
return false;
}
// basic image sanity
const int ch = frame_.stream.rgbImage.channels();
if (ch != 1 && ch != 3 && ch != 4) {
last_status_ = Status::BAD_IMAGE;
if (!validateColorFrame()) {
return false;
}
@ -155,6 +175,20 @@ bool AprilTagPerception::grabFrame(const Options& opt) {
return true;
}
bool AprilTagPerception::validateColorFrame() {
if (frame_.stream.rgbImage.empty()) {
last_status_ = Status::NO_NEW_FRAME;
return false;
}
const int channels = frame_.stream.rgbImage.channels();
if (channels != 1 && channels != 3 && channels != 4) {
last_status_ = Status::BAD_IMAGE;
return false;
}
return true;
}
bool AprilTagPerception::fetchEncoded(size_t encoded_index) {
if (!camera_) {
last_status_ = Status::NO_CAMERA;
@ -228,27 +262,24 @@ bool AprilTagPerception::ensureVispImage() {
}
bool AprilTagPerception::detectTags() {
std::vector<vpHomogeneousMatrix> cMo_vec;
const bool detected = detector_.detect(frame_.visp_I, tag_size_m_, visp_cam_, cMo_vec);
if (!detected || cMo_vec.empty()) {
if (!detector_.detect(frame_.visp_I)) {
last_status_ = Status::NO_TAG;
return false;
}
const std::vector<int> tag_ids = detector_.getTagsId();
const std::vector<float> margins = detector_.getTagsDecisionMargin();
const size_t n = std::min(tag_ids.size(), cMo_vec.size());
if (n == 0) {
last_status_ = Status::NO_TAG;
return false;
}
tags_.reserve(n);
for (size_t i = 0; i < n; ++i) {
tags_.reserve(tag_ids.size());
for (size_t i = 0; i < tag_ids.size(); ++i) {
Tag t;
t.id = tag_ids[i];
t.cMo = cMo_vec[i];
t.T_c_t = toEigen4(cMo_vec[i]);
const auto size = tag_sizes_by_id_.find(t.id);
const double tag_size_m = size == tag_sizes_by_id_.end() ? tag_size_m_ : size->second;
if (!detector_.getPose(i, tag_size_m, visp_cam_, t.cMo)) {
continue;
}
t.T_c_t = toEigen4(t.cMo);
double w = 1.0;
if (i < margins.size() && std::isfinite(margins[i]) && margins[i] > 0.0f) {
@ -260,8 +291,8 @@ bool AprilTagPerception::detectTags() {
tags_.push_back(t);
}
last_status_ = Status::OK;
return true;
last_status_ = tags_.empty() ? Status::NO_TAG : Status::OK;
return !tags_.empty();
}
const AprilTagPerception::Tag* AprilTagPerception::findTag(int id) const {

View File

@ -0,0 +1,31 @@
-----BEGIN CERTIFICATE-----
MIIFRDCCAyygAwIBAgIUTTkz+NAkngH99QsEX9tlBX2pTuwwDQYJKoZIhvcNAQEL
BQAwJzElMCMGA1UEAwwcQ01WUiBUb3VjaCBRVUlDIFJvb3QgQ0EgMjAyNjAgFw0y
NjExMTgwODI2MDRaGA8yMDg2MTExOTA4MjYwNFowJzElMCMGA1UEAwwcQ01WUiBU
b3VjaCBRVUlDIFJvb3QgQ0EgMjAyNjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC
AgoCggIBAMZZHZFarjrokqNCoBMzR9s9PA3P5ykBTEYzm34TwRN1YLC9sgfC95lq
0QYCunOllPG4oWGT9IPbDNxPfDNz9Pls7GPggH3RGOEEGaUKmNqTVsI+pxap7F7/
Ck+Pst9nPj9nYYKVp74tcvR3EpOoy3ipD9wHbfzwOyyUR1U4ELFAs1Ip891kkmXY
THo0FHOwKzuImsHt1v3tBQ/VbupgAZh4zn3TGKhMcpv2d8esm0oK4aqDV/xc+JJW
8qCALbRypoCPZ8eP5KHGk4DXZmDeXUsFeGhJeT86Zegp2D+3BANvAYec3gyRUlTo
oqwRydxeliwGQBvczyY7bXudagMx/3ZF3qftW3oulFz19LCEb2lpy4yyQbxYIySM
cam5hDb/0J0xM0iDCWg7i52GUOOZhXEuiyouOKolYUlkorO7o7qL3oCGrF21HrQ8
dOfBaiY+ZPnXuByuqVuKoxT/TA680DnimHejHTdQHa7XW/dMmKx7xYuPMY1zn1L6
8vT+JeotLziMp6lyDDqoyUB/T773sboUXNRYIQhGDp2TH3rKj1rbwkiVvi8WDZSw
1FRc1CaHT9EYuvEZCOvjZCSRNfBGvGvqhtb3YEdxJ3ZTdIvmlztLIajSDcqYUUTu
ZTx6AOEDTDBUwN2oXzl6TKC6uBMc6wwvhX5WWIXmkQcTmMiDGSnFAgMBAAGjZjBk
MB8GA1UdIwQYMBaAFMVzjDkjqS148pB+WyuSCUuf3KQvMBIGA1UdEwEB/wQIMAYB
Af8CAQAwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTFc4w5I6ktePKQflsrkglL
n9ykLzANBgkqhkiG9w0BAQsFAAOCAgEAg7BfGO8j+3oq5lJp21EhmBi9l+M7e092
w2ndKU+E4H2OppsQYDliSILNt2A7rq50j/AgZh33JI+UcDrAM9qAIbXdHQRU6R6S
U6EpipBE32tXG7YGqtawsHJASxGiRboNJnrWrkHPQi9xCa1YBdXnfWxFGwXqj9DU
5jLe5liBiXy89a2T4I1Q7JRz/Ogzzbtmq+Bp478jSilZ/jjhCvuZrqvvKK4CiJNQ
k9RCMn8NeAE9dN8EIuIQ1pLT9bxHEScPbfjzFhkGIJyrLVhl48stwzmK70P4iegT
THUb3UToWKyqh8aR466N1FL1Sh7kvUW05S/4Gls+2SIyxG8ZC5kXTCM6EF0YIm5f
KVCgsraWCFlxMqDiDmzKizbb+5Nt207UrSd521XayAcNmTh+GNVwvZdE5pqYZmXR
dcaK9lF4FvugrWPcpf56YE2DMPJbcHLMIYN0vH8MF72HWxtjpnKfrpHzF9W4XbT5
uNaTXL5zCSYouB6a+kXsko9oCoJBb385CqpfY/u4wZCdLB73/hYSXOFoS3SkLRdc
8GAaYy6YXU5Qx5CqHMYWH6tvjuNXv0x6Y1mrpfBnIqUTVVRlMHAdM8uAxErKXI5e
hIyOFRYA7prDdBuLCMu0cumts3rxJ8pOkS7M+QZMTOVclE34xBnA3DBhaAFilkjs
SPHUV6dJqbQ=
-----END CERTIFICATE-----

View File

@ -1,15 +1,15 @@
# Joint-only minimal configuration; MoveJ follows joint_names order.
arm {
robot_arms {
id: "lingkong_mixed_arm"
id: "xiaozhao_lingkong_neck"
motor {
motor_system_id: "lingkong_mixed_motors"
motor_system_id: "xiaozhao_linkong_motors"
motor_group_ids: "lingkong_mixed_v236"
motor_group_ids: "lingkong_mixed_v238"
dof: 3
joint_names: "LINGKONG_MIXED_AXIS_1"
joint_names: "LINGKONG_MIXED_AXIS_2"
joint_names: "LINGKONG_MIXED_AXIS_3"
joint_names: "neck-joint1"
joint_names: "neck-joint2"
joint_names: "neck-joint3"
upd_freq: 50
}
motion {
@ -21,7 +21,7 @@ arm {
}
move_j {
settle_timeout_s: 2.0
settle_position_tolerance_rad: 0.002
settle_position_tolerance_rad: 0.02
settle_velocity_tolerance_rad_s: 0.02
settle_stable_sample_count: 3
}

View File

@ -31,17 +31,22 @@ arm {
max_iters: 100
tol: 1e-6
qp_time_limit: 1e-2
pose_ik_joint_limit_avoidance {
enable: true
max_iters: 20
max_joint_step_rad: 0.02
}
joint_limit_policy {
limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "joint1-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-right" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-right" q_lb: -2.35 q_ub: 0 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-right" q_lb: -0.45 q_ub: 0.785 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-right" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint1-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 20.0 }
joints { joint_name: "joint2-right" q_lb: -0.65 q_ub: 1.5 qd: 1.0 qdd: 20.0 }
joints { joint_name: "joint3-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 20.0 }
joints { joint_name: "joint4-right" q_lb: -2.1 q_ub: 0 qd: 1.0 qdd: 20.0 }
joints { joint_name: "joint5-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 20.0 }
joints { joint_name: "joint6-right" q_lb: -0.5 q_ub: 0.42 qd: 1.0 qdd: 20.0 }
joints { joint_name: "joint7-right" q_lb: -0.70 q_ub: 0.7 qd: 1.0 qdd: 20.0 }
}
soft_limit {
enable: true
@ -49,7 +54,10 @@ arm {
min_margin_rad: 0.01
}
avoidance {
enable: false
enable: true
gain: 0.2
margin_ratio: 0.15
max_push: 0.25
}
}
}
@ -138,8 +146,8 @@ arm {
}
joint_velocity_check {
enable: true
max_joint_velocity_rad_s: 1.0
max_joint_acceleration_rad_s2: 5.0
max_joint_velocity_rad_s: 1.5
max_joint_acceleration_rad_s2: 40.0
}
cartesian_velocity_feasibility_check {
enable: true

View File

@ -20,7 +20,7 @@ dexhand {
model: "ROH-LiteS001"
has_tactile_feedback: false
oymotion_ap001 {
can_interface: "can0"
can_interface: "can1"
hand_id: 2
master_id: 1
command_timeout_ms: 255

View File

@ -1,23 +1,23 @@
# Alternative deployment: do not enable together with the original can3 IDs 1/2/3.
# Xiaozhao neck on can2: node 1 uses V2.36, nodes 2 and 3 use V2.38.
# Both groups are loaded by the MotorConfig.id below, with unique motor IDs.
motor {
id: "lingkong_mixed_motors"
id: "xiaozhao_linkong_motors"
motor_groups {
id: "lingkong_mixed_v236"
bus_type: MOTOR_BUS_CAN
vendor: MOTOR_VENDOR_LINGKONG
protocol: MOTOR_PROTOCOL_LINGKONG_CAN
can { channel_id: 3 }
can { channel_id: 2 }
motors {
motors {
id: 1
joint_name: "LINGKONG_MIXED_AXIS_1"
joint_name: "neck-joint1"
gear_ratio: 10
limit_q_lb: -3.14
limit_q_ub: 3.14
limit_q_lb: -2.4
limit_q_ub: -0.4
limit_qd: 10
lingkong {
response_timeout_ms: 100
response_timeout_ms: 500
reached_position_tolerance_rad: 0.001
# Iq conversion intentionally unspecified until confirmed for this motor.
}
@ -29,30 +29,30 @@ motor {
bus_type: MOTOR_BUS_CAN
vendor: MOTOR_VENDOR_LINGKONG
protocol: MOTOR_PROTOCOL_LINGKONG_CAN_V2_38
can { channel_id: 3 }
can { channel_id: 2 }
motors {
motors {
id: 2
joint_name: "LINGKONG_MIXED_AXIS_2"
joint_name: "neck-joint2"
gear_ratio: 10
limit_q_lb: -3.14
limit_q_ub: 3.14
limit_q_lb: -0.75
limit_q_ub: 0.77
limit_qd: 10
lingkong {
response_timeout_ms: 100
response_timeout_ms: 500
reached_position_tolerance_rad: 0.001
# Iq conversion intentionally unspecified until confirmed for this motor.
}
}
motors {
id: 3
joint_name: "LINGKONG_MIXED_AXIS_3"
joint_name: "neck-joint3"
gear_ratio: 10
limit_q_lb: -3.14
limit_q_ub: 3.14
limit_q_lb: -0.45
limit_q_ub: 0.42
limit_qd: 10
lingkong {
response_timeout_ms: 100
response_timeout_ms: 500
reached_position_tolerance_rad: 0.001
# Iq conversion intentionally unspecified until confirmed for this motor.
}

View File

@ -56,13 +56,13 @@ motor {
joint_limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "joint1-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-right" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-right" q_lb: -2.35 q_ub: 0 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-right" q_lb: -0.45 q_ub: 0.785 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-right" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint1-right" q_lb: -3.14 q_ub: 3.14 qd: 1.5 qdd: 40.0 }
joints { joint_name: "joint2-right" q_lb: -0.65 q_ub: 1.5 qd: 1.5 qdd: 40.0 }
joints { joint_name: "joint3-right" q_lb: -3.14 q_ub: 3.14 qd: 1.5 qdd: 40.0 }
joints { joint_name: "joint4-right" q_lb: -2.1 q_ub: 0 qd: 1.5 qdd: 40.0 }
joints { joint_name: "joint5-right" q_lb: -3.14 q_ub: 3.14 qd: 1.5 qdd: 40.0 }
joints { joint_name: "joint6-right" q_lb: -0.59 q_ub: 0.42 qd: 1.5 qdd: 40.0 }
joints { joint_name: "joint7-right" q_lb: -0.70 q_ub: 0.7 qd: 1.5 qdd: 40.0 }
joints { joint_name: "joint1-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-left" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }

View File

@ -1,12 +1,12 @@
touch {
touches {
id: "paxini_tip_1"
id: "paxini_tip"
px_6ax_genx_can {
# 系统预先配置 can0 为 1 Mbps;设备以约 2 ms 为目标采读并主动发送有效值,非严格周期。
channel_id: 0
channel_id: 1
force_can_id: 0x600
# 按主机本地接收时间计算的最大有效期;超过此时间无有效报文则报不可用。
max_sample_age_ms: 300
max_sample_age_ms: 1000
}
}

View File

@ -6,199 +6,30 @@ device_manager {
id: "head_carme"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/xiaozhao_camera.pb.txt"
enable: false
enable: true
}
devices {
id: "right_hand_carme"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/xiaozhao_camera.pb.txt"
enable: false
}
devices {
id: "right_hand_cam"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
enable: false
}
devices {
id: "left_hand_cam"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
enable: false
}
devices {
id: "right_hand_ap001"
type: DEVICE_TYPE_DEXHAND
config_file: "devices/dexhand/dexhand.pb.txt"
enable: false
enable: true
}
devices {
id: "right_hand_lites001"
type: DEVICE_TYPE_DEXHAND
config_file: "devices/dexhand/dexhand.pb.txt"
enable: false
enable: true
}
devices {
id: "hand2"
type: DEVICE_TYPE_DEXHAND
config_file: "devices/dexhand/dexhand.pb.txt"
enable: false
}
devices {
id: "paxini_tip_1"
id: "paxini_tip"
type: DEVICE_TYPE_TOUCH
config_file: "devices/touch/touch.pb.txt"
enable: false
enable: true
}
devices {
id: "left_arm_can_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/ti5_motors.pb.txt"
enable: false
}
devices {
id: "right_arm_can_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/ti5_motors.pb.txt"
enable: false
}
devices {
id: "head_can_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/ti5_motors.pb.txt"
enable: false
}
devices {
id: "waist_can_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/ti5_motors.pb.txt"
enable: false
}
devices {
id: "right_arm_ethercat_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/ethercat_single_arm_motors.pb.txt"
enable: false
}
devices {
id: "right_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/arm_qp.pb.txt"
enable: false
}
devices {
id: "aubo_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/aubo_arm.pb.txt"
enable: false
}
devices {
id: "huayan_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/huayan_arm.pb.txt"
enable: false
}
devices {
id: "bio_head"
type: DEVICE_TYPE_BIO_HEAD_ROBOT
config_file: "devices/biohead/bio_head.pb.txt"
enable: false
}
devices {
id: "src1100"
type: DEVICE_TYPE_AGV
config_file: "devices/agv/agv.pb.txt"
enable: false
}
devices {
id: "hikvision_cam"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
enable: false
}
devices {
id: "hikvision_thermal_cam"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
enable: false
}
devices {
id: "mic1"
type: DEVICE_TYPE_MICROPHONE
config_file: "devices/microphone/microphone.pb.txt"
enable: false
}
devices {
id: "spk1"
type: DEVICE_TYPE_SPEAKER
config_file: "devices/speaker/speaker.pb.txt"
enable: false
}
devices {
id: "real_cam1"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
enable: false
}
devices {
id: "usb_cam1"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
enable: false
}
devices {
id: "usb_cam2"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
enable: false
}
devices {
id: "tchl_dual_arm_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/tchl_dual_arm_motors.pb.txt"
enable: false
}
devices {
id: "right_tchl_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/tchl_dual_arm.pb.txt"
enable: false
}
devices {
id: "left_tchl_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/tchl_dual_arm.pb.txt"
enable: false
}
# 小赵实机双臂共用一个 TCHL EtherCAT 电机组。
devices {
id: "xiaozhao_tchl_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
@ -206,6 +37,20 @@ device_manager {
enable: true
}
devices {
id: "xiaozhao_linkong_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/xiaozhao_linkong_motors.pb.txt"
enable: true
}
devices {
id: "xiaozhao_lingkong_neck"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/xiaozhao_lingkong_neck.pb.txt"
enable: true
}
devices {
id: "xiaozhao_tchl_right_arm"
type: DEVICE_TYPE_ROBOT_ARM
@ -217,63 +62,7 @@ device_manager {
id: "xiaozhao_tchl_left_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/xiaozhao_tchl_arm.pb.txt"
enable: true
}
devices {
id: "tchl_single_axis"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/tchl_motors.pb.txt"
enable: false
}
devices {
id: "lingkong_can_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/lingkong_motors.pb.txt"
enable: false
}
devices {
id: "lingkong_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/lingkong_arm.pb.txt"
enable: false
}
devices {
id: "tchl_joint_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/tchl_multi_motors.pb.txt"
enable: false
}
devices {
id: "tchl_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/tchl_arm.pb.txt"
enable: false
}
# Alternative hardware deployment; enable only on the matching device.
devices {
id: "lingkong_mixed_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/lingkong_mixed_motors.pb.txt"
enable: false
}
devices {
id: "lingkong_mixed_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/lingkong_mixed_arm.pb.txt"
enable: false
}
devices {
id: "usb_head"
type: DEVICE_TYPE_BIO_HEAD_ROBOT
config_file: "devices/biohead/bio_head_usb.pb.txt"
enable: false
}
}

View File

@ -5,8 +5,8 @@ task_manager {
type: TASK_TYPE_TOUCH_SCREEN
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.001
config_file: "tasks/touch_screen_task/touch_screen_task_xiaozhao_mujoco.pb.txt"
enable: false
config_file: "tasks/touch_screen_task/touch_screen_task_xiaozhao_real.pb.txt"
enable: true
}
tasks {
id: "grpc_server"
@ -15,20 +15,12 @@ task_manager {
config_file: "tasks/grpc_server_task/grpc_server_task.pb.txt"
enable: true
}
tasks {
id: "right_arm_self_collision"
type: TASK_TYPE_SELF_COLLISION
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.002
config_file: "tasks/self_collision_task/self_collision_task.pb.txt"
enable: false
}
# 小赵 MuJoCo 实时自碰撞监控。
tasks {
id: "xiaozhao_left_arm_self_collision"
type: TASK_TYPE_SELF_COLLISION
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.002
control_period_s: 0.02
config_file: "tasks/self_collision_task/self_collision_task_xiaozhao_left.pb.txt"
enable: false
}
@ -36,15 +28,15 @@ task_manager {
id: "xiaozhao_right_arm_self_collision"
type: TASK_TYPE_SELF_COLLISION
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.002
control_period_s: 0.02
config_file: "tasks/self_collision_task/self_collision_task_xiaozhao_right.pb.txt"
enable: false
enable: true
}
tasks {
id: "quic_edge"
type: TASK_TYPE_QUIC_EDGE
run_mode: TASK_RUN_MODE_BLOCKING_SERVICE
config_file: "tasks/quic_edge_task/quic_edge_task.pb.txt"
enable: false
enable: true
}
}

View File

@ -3,11 +3,11 @@ quic_edge {
# Task enablement is controlled by manager/task_manager.pb.txt. Configure a
# reachable QUIC Gateway and TLS policy before enabling the task there.
server_host: "192.168.0.222"
server_host: "192.168.1.222"
server_port: 4433
alpn: "cmvr-quic-edge/1"
node_id: "cmvr-edge"
robot_id: "CN-CMVR-MBLRV1-AIMA-20260806-002"
robot_id: "CN-CMVR-MBLRV1-CQCVC-20261123-003"
software_version: "0.1"
# The existing cmvr-es gRPC server remains the robot-control endpoint. "auto"
@ -24,8 +24,8 @@ quic_edge {
control_response_timeout_ms: 1000
tls {
ca_file: "certs/cmvr-quic-ca.crt"
server_name: "192.168.0.222"
ca_file: "certs/cmvr-touch-quic-ca-60y.crt"
server_name: "192.168.1.222"
allow_insecure: false
}
@ -44,17 +44,6 @@ quic_edge {
# }
# }
platforms {
id: "platform_199"
server_host: "192.168.0.199"
server_port: 4433
enable_media: false
tls {
ca_file: "certs/cmvr-quic-ca.crt"
server_name: "192.168.0.199"
allow_insecure: false
}
}
reconnect {
initial_delay_ms: 500

View File

@ -1,7 +1,7 @@
# 小赵右臂独立自碰撞检测:仅本臂 + 固定 base,排除另一臂与活动头部。
# 小赵实机右臂独立自碰撞检测:仅本臂 + 固定 base,排除另一臂与活动头部。
self_collision_task {
id: "xiaozhao_right_arm_self_collision"
arm_id: "xiaozhao_mujoco_right_arm"
arm_id: "xiaozhao_tchl_right_arm"
checker {
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"

View File

@ -8,7 +8,7 @@ touch_screen_task {
devices {
arm_id: "right_arm"
# devices/touch/touch.pb.txt 中的 PX6AXGenXCan,使用 CAN 合力数据,单位为 N。
touch_id: "paxini_tip_1"
touch_id: "paxini_tip"
# 手部相机和外部相机的 DeviceManager ID。
camera_id: "right_hand_cam"
external_camera_id: "left_hand_cam"
@ -76,9 +76,9 @@ touch_screen_task {
# rx、ry、rz 表示绕固定 G 坐标轴 X、Y、Z 依次旋转。
# 旋转组合为 R_G_H = Rz(rz) * Ry(ry) * Rx(rx)。
# PBVS 会结合上面的 T_H_P 将该目标转换为 TCP P 的目标姿态。
hand_orientation_G { rx: 0.0 ry: 0.0 rz: -1.57 }
hand_orientation_G { rx: -0.1 ry: 0.0 rz: -1.57 }
# 点击目标点到 TCP 预对齐位置的偏移,表达在 G 坐标系,单位为米。
position_offset_G { x: 0.0 y: 0.0 z: 0.00 }
position_offset_G { x: 0.003 y: 0.0 z: 0.00 }
mode: TOUCH_SCREEN_ALIGN_MODE_RX_RY_AND_POSITION
}
error_threshold {

View File

@ -21,9 +21,9 @@ touch_screen_task {
head_initialization {
enable: true
# 头部朝向使外部相机同时看到屏幕和手背的 AprilTag。
joint_positions { joint_name: "neck-joint1" rad: 0.0 }
joint_positions { joint_name: "neck-joint2" rad: -0.1 }
joint_positions { joint_name: "neck-joint3" rad: 0.1 }
joint_positions { joint_name: "neck-joint1" rad:-1.055819 }
joint_positions { joint_name: "neck-joint2" rad: 0.621808 }
joint_positions { joint_name: "neck-joint3" rad: -0.160239 }
velocity: 0.25
acceleration: 0.5
}

View File

@ -0,0 +1,129 @@
# 小赵实机右臂触屏任务。启用前核对 AprilTag、T_H_P、目标姿态和 Paxini 零载 Fz。
touch_screen_task {
id: "touch_screen"
debug_draw_coordinate_frames: true
debug_coordinate_axis_length_m: 0.02
devices {
arm_id: "xiaozhao_tchl_right_arm"
head_id: "xiaozhao_lingkong_neck"
touch_id: "paxini_tip"
camera_id: "right_hand_carme"
external_camera_id: "head_carme"
}
# 参考 MuJoCo 头部姿态。实机确认视野和关节位置后,可启用启动时的头部 MoveJ。
head_initialization {
enable: false
joint_positions { joint_name: "neck-joint1" rad: -1.235204 }
joint_positions { joint_name: "neck-joint2" rad: 0.612523}
joint_positions { joint_name: "neck-joint3" rad:-0.279480 }
velocity: 0.25 # rad/s
acceleration: 1 # rad/s^2
}
# 参考 MuJoCo 右臂姿态。按实机屏幕位置确认初始位后,再选择自动回位时机。
initialization {
motion_method: USE_MOVEJ
before_start: true
after_finish: true
after_failure: true
joint_positions { joint_name: "joint1-right" rad: -0.742312}
joint_positions { joint_name: "joint2-right" rad:0.871908 }
joint_positions { joint_name: "joint3-right" rad: 2.109117 }
joint_positions { joint_name: "joint4-right" rad: -1.892831 }
joint_positions { joint_name: "joint5-right" rad:-2.249530}
joint_positions { joint_name: "joint6-right" rad:0.268739 }
joint_positions { joint_name: "joint7-right" rad:0.146545 }
velocity: 1 # rad/s
acceleration: 1 # rad/s^2
jerk: 5.0 # rad/s^3
skip_position_tolerance_rad: 0.001
skip_velocity_tolerance_rad_s: 0.01
}
perception {
# size_m 填各自标签的黑框外边长,不含白边。
tags {
screen { id: 1 size_m: 0.03 }
hand { id: 2 size_m: 0.025 }
}
# 实机两路相机采集 RGB。触屏像素 u/v 使用手相机 1280×720 原图坐标。
hand_camera {
depth_policy: TOUCH_SCREEN_DEPTH_POLICY_NONE
target_point_method: TOUCH_SCREEN_TARGET_POINT_METHOD_TAG_PLANE
}
}
approach {
# MoveP 移至视觉对齐目标,再进入 PBVS。最小间隙检查针对 TCP。
enable: true
velocity: 0.8 # rad/s
acceleration: 5 # rad/s^2
jerk: 50.0 # rad/s^3
timeout_s: 15.0
minimum_clearance_m: 0.01
}
alignment {
calibration {
# T_H_P 为 MJCF 名义安装值,平移单位为米。用实测的手部 Tag H 到 TCP 变换复核。
hand_tag_to_tcp {
m00: -1.0 m01: 0.0 m02: 0.0 m03: -0.01
m10: 0.0 m11: 0.0 m12: 1.0 m13: -0.07
m20: 0.0 m21: 1.0 m22: 0.0 m23: -0.13
m30: 0.0 m31: 0.0 m32: 0.0 m33: 1.0
}
}
pbvs {
position_gain { x: 2.0 y: 2.0 z: 1.5 }
rotation_gain { x: 1.5 y: 1.5 z: 1.5 }
vmax6 { x: 0.03 y: 0.03 z: 0.03 rx: 0.10 ry: 0.10 rz: 0.10 }
amax6 { x: 0.50 y: 0.50 z: 0.50 rx: 2.0 ry: 2.0 rz: 2.0 }
twist_filter_alpha: 1.0
}
target {
# H 相对 G 的目标姿态(rad)。按实机标签朝向复核,使 Tool -Y 指向屏面。
hand_orientation_G { rx: 0.0 ry: 0.0 rz: -3.141592653589793 }
# MoveP 和 PBVS 共用此偏移,绕屏幕 Tag G 的固定 X 轴再转 -5°,单位为弧度。
rotation_offset_G { x: -0.32 y: 0.0 z: 0.0 }
# TCP 对齐至点击点沿 G +Z 外移 20 mm 的位置。
position_offset_G { x: 0.005 y:0.003 z: 0.05 }
mode: TOUCH_SCREEN_ALIGN_MODE_POSE_AND_POSITION
}
error_threshold {
x: 0.005
y: 0.003
z: 0.005
rx: 0.08726646259971647
ry: 0.08726646259971647
rz: 0.08726646259971647
}
stable_frames: 5
timeout_s: 30.0
pause_when_reached: false
}
touch {
speed_l {
twist_tool { x: 0.0 y: -0.02 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 2 # m/s^2
linear_jerk: 15 # m/s^3
max_distance_m: 0.03
}
tactile {
# Paxini CAN 的有符号 Fz(N)。按实机零载噪声及接触方向核对阈值。
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
force_threshold: 0.1
}
dwell_time_s: 0.0
}
retract {
# 接触后立即沿 Tool +Y 回撤。未触发接触而到达限距时也回撤。
twist_tool { x: 0.0 y: 0.035 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 5 # m/s^2
linear_jerk: 30 # m/s^3
distance_m: 0.03
}
}

View File

@ -21,6 +21,7 @@ target_link_libraries(huayan_arm
cmvr_es::proto
PRIVATE
HR_Pro
jsoncpp
glog
Threads::Threads
)
@ -29,3 +30,10 @@ add_library(cmvr_es::device::huayan_arm ALIAS huayan_arm)
install(TARGETS huayan_arm LIBRARY DESTINATION lib)
install(FILES ${HUAYAN_ARM_SDK_DIR}/lib/libHR_Pro.so DESTINATION lib)
if(BUILD_TESTING)
add_executable(huayan_cabinet_io_test tests/huayan_cabinet_io_test.cpp)
set_target_properties(huayan_cabinet_io_test PROPERTIES ENABLE_EXPORTS ON)
target_link_libraries(huayan_cabinet_io_test PRIVATE cmvr_es::device::huayan_arm jsoncpp gtest gtest_main)
add_test(NAME huayan_cabinet_io_test COMMAND huayan_cabinet_io_test)
endif()

View File

@ -0,0 +1,31 @@
# Cabinet CI/CO IO
Use `cmvr.api.ArmService.ExecuteJsonCommand`, with the same parameter names as Aubo.
The request header selects the Huayan arm device. The following object is serialized
as the `request_json` string:
```json
{"command":"cabinet_io","operation":"set_do","index":0,"value":true}
```
`index: 0` selects **CO0**, not DO0. `true` writes 1, `false` writes 0.
Writing calls `HRIF_SetBoxCO`; reading uses `HRIF_ReadBoxCO`.
For readback, use:
```json
{"command":"cabinet_io","operation":"get_do","index":0}
```
`get_di` reads the corresponding configurable **CI** input.
The SDK supplies the available CI/CO count; channel numbers start at zero.
`value` must be a JSON boolean for writes. No motion enable is performed.
The gRPC response uses the existing `header` and `response_json` fields.
The JSON response contains `success`, `command`, `operation`, `index`, `count`,
`io_type` (CI or CO), and `sdk_return_code`. Reads return `value`; successful
writes return `requested_value`, which indicates SDK command success and does not
claim physical readback. Failures return `error_code` and `error_message`.
Aubo-specific `runstate` fields are not fabricated for Huayan.
Build `huayan_cabinet_io_test` with `BUILD_TESTING=ON` for offline verification.
The test executable replaces the IO SDK symbols and does not connect to hardware.

View File

@ -1,6 +1,8 @@
#include "huayan_arm.h"
#include <algorithm>
#include <cctype>
#include <json/json.h>
#include <array>
#include <chrono>
#include <cmath>
@ -112,6 +114,88 @@ HuayanRobot::~HuayanRobot()
(void)disconnect();
}
bool HuayanRobot::executeJsonCommand(const std::string& request_json, std::string& response_json)
{
Json::Value response(Json::objectValue);
const auto put = [&](const char* key) -> Json::Value& {
return *response.demand(key, key + std::char_traits<char>::length(key));
};
const auto serialize = [&]() {
Json::StreamWriterBuilder writer;
writer[std::string("indentation")] = "";
response_json = Json::writeString(writer, response);
};
put("success") = false;
const auto fail = [&](const std::string& code, const std::string& message) {
put("error_code") = code; put("error_message") = message; serialize();
CMVR_LOG(ERROR) << "[HuayanRobot] cabinet_io: " << message;
return false;
};
Json::Value root; Json::CharReaderBuilder builder;
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
std::string error;
if (!reader->parse(request_json.data(), request_json.data() + request_json.size(), &root, &error))
return fail("invalid_json", "invalid json: " + error);
if (!root.isObject()) return fail("invalid_json", "invalid json: root must be an object");
const auto member = [&](const char* key) { return root.find(key, key + std::char_traits<char>::length(key)); };
const auto text = [&](const char* key) {
const auto* v = member(key);
std::string value = v && v->isString() ? v->asString() : std::string{};
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); });
return value;
};
const auto command = text("command");
if (command.empty()) return fail("invalid_argument", "field 'command' is required and must be a non-empty string");
if (command != "cabinet_io") return fail("unsupported_command", "unsupported json command: " + command);
put("command") = command;
const auto operation = text("operation");
if (operation.empty()) return fail("invalid_argument", "field 'operation' is required and must be a non-empty string");
if (operation != "get_di" && operation != "get_do" && operation != "set_do")
return fail("invalid_operation", "unsupported cabinet_io operation: " + operation);
put("operation") = operation;
const auto* index_value = member("index");
if (!index_value || !index_value->isInt() || index_value->asInt() < 0)
return fail("invalid_argument", "field 'index' is required and must be a non-negative JSON integer");
const int index = index_value->asInt(); put("index") = index;
const auto* value = member("value");
if (operation == "set_do" && (!value || !value->isBool()))
return fail("invalid_argument", "field 'value' is required for set_do and must be a JSON boolean");
std::lock_guard<std::mutex> lock(mutex_);
const auto ready = ensureConnected_("cabinet_io");
if (!ready.ok()) return fail("not_connected", ready.message);
try {
// Same request shape as Aubo; Huayan configurable cabinet ports are CI/CO.
// CO0 is index 0, not the separate general-purpose DO0 terminal.
std::vector<int> ports;
const bool input = operation == "get_di";
int ret = input ? HRIF_ReadAllBoxCI(box_id_, ports) : HRIF_ReadAllBoxCO(box_id_, ports);
put("io_type") = input ? "CI" : "CO"; put("sdk_return_code") = ret;
if (ret != 0) return fail("sdk_command_failed", "failed to read IO count: sdk ret=" + std::to_string(ret));
put("count") = static_cast<int>(ports.size());
if (static_cast<std::size_t>(index) >= ports.size())
return fail("index_out_of_range", "cabinet_io index out of range: index=" + std::to_string(index) + ", count=" + std::to_string(ports.size()));
if (operation == "set_do") {
ret = HRIF_SetBoxCO(box_id_, index, value->asBool() ? 1 : 0);
put("sdk_return_code") = ret;
if (ret != 0) return fail("sdk_command_failed", "cabinet_io set_do failed: sdk ret=" + std::to_string(ret));
put("requested_value") = value->asBool();
} else {
int actual = -1;
ret = input ? HRIF_ReadBoxCI(box_id_, index, actual) : HRIF_ReadBoxCO(box_id_, index, actual);
put("sdk_return_code") = ret;
if (ret != 0) return fail("sdk_command_failed", "cabinet_io read failed: sdk ret=" + std::to_string(ret));
if (actual != 0 && actual != 1) return fail("invalid_io_value", "cabinet_io returned a non-digital value");
put("value") = actual != 0;
}
put("success") = true; serialize();
CMVR_LOG(INFO) << "[HuayanRobot] cabinet_io: operation=" << operation << ", index=" << index << ", sdk ret=" << ret;
return true;
} catch (const std::exception& e) {
return fail("sdk_exception", std::string("[HuayanRobot] cabinet_io failed: ") + e.what());
}
}
bool HuayanRobot::init()
{
if (ip_.empty()) {

View File

@ -28,6 +28,7 @@ public:
~HuayanRobot() override;
std::string typeName() const override { return "HuayanRobot"; }
bool executeJsonCommand(const std::string& request_json, std::string& response_json) override;
bool init() override;
bool stop() override;
@ -107,6 +108,7 @@ public:
bool busy() const override { return busy_.load(); }
private:
friend struct HuayanIoTestAccess;
struct HrState {
int moving{0};
int enabled{0};

View File

@ -0,0 +1,53 @@
// Executable SDK symbol overrides: no connection to hardware and no physical IO writes.
#include "huayan_arm.h"
#include <gtest/gtest.h>
#include <json/json.h>
#include <sstream>
#include <vector>
namespace { int calls=0, written=-1, channel=-1, result=0, actual=1; }
extern "C" bool HRIF_IsConnected(unsigned int) { return true; }
extern "C" int HRIF_ReadAllBoxCO(unsigned int,std::vector<int>& v) { ++calls;v={0,0,0,0};return result; }
extern "C" int HRIF_ReadAllBoxCI(unsigned int,std::vector<int>& v) { ++calls;v={0,0};return result; }
extern "C" int HRIF_SetBoxCO(unsigned int,int bit,int value) { ++calls;channel=bit;written=value;return result; }
extern "C" int HRIF_ReadBoxCO(unsigned int,int bit,int& value) { ++calls;channel=bit;value=actual;return result; }
extern "C" int HRIF_ReadBoxCI(unsigned int,int bit,int& value) { ++calls;channel=bit;value=actual;return result; }
namespace cmvr::device {
const Json::Value& get(const Json::Value& r,const char* key) {const auto* p=r.find(key,key+std::char_traits<char>::length(key));if(!p)throw std::runtime_error("missing response field");return *p;}
struct HuayanIoTestAccess {static void connected(HuayanRobot& arm,bool value){arm.connected_=value;}};
class HuayanCabinetIo : public ::testing::Test {
protected:
config::RobotArmConfig cfg;
std::unique_ptr<HuayanRobot> arm;
void SetUp()override {calls=0;written=-1;channel=-1;result=0;actual=1;cfg.set_id("fake_huayan");arm=std::make_unique<HuayanRobot>(cfg);HuayanIoTestAccess::connected(*arm,true);}
void TearDown()override {HuayanIoTestAccess::connected(*arm,false);arm.reset();}
Json::Value invoke(const std::string& request,bool success) {std::string response;EXPECT_EQ(arm->executeJsonCommand(request,response),success);Json::Value value;Json::CharReaderBuilder reader;std::string error;std::istringstream in(response);EXPECT_TRUE(Json::parseFromStream(reader,in,&value,&error));return value;}
};
TEST_F(HuayanCabinetIo, SameAuboParametersSetCO0HighAndLow) {
auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",true);
EXPECT_EQ(channel,0);EXPECT_EQ(written,1);EXPECT_TRUE(get(r,"requested_value").asBool());EXPECT_EQ(get(r,"io_type").asString(),"CO");
invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":false})",true);EXPECT_EQ(written,0);
}
TEST_F(HuayanCabinetIo, ReadActualCOAndCI) {
auto r=invoke(R"({"command":"cabinet_io","operation":"get_do","index":0})",true);EXPECT_TRUE(get(r,"value").asBool());EXPECT_EQ(channel,0);
actual=0;r=invoke(R"({"command":"cabinet_io","operation":"get_di","index":1})",true);EXPECT_FALSE(get(r,"value").asBool());EXPECT_EQ(get(r,"io_type").asString(),"CI");
}
TEST_F(HuayanCabinetIo, RejectInvalidWithoutSdkCalls) {
for(auto request:{"{","[]",R"({"command":"other"})",R"({"command":"cabinet_io","operation":"set_do","index":0,"value":1})",R"({"command":"cabinet_io","operation":"set_do","index":-1,"value":true})",R"({"command":"cabinet_io","operation":"get_do","index":0.5})"})invoke(request,false);
EXPECT_EQ(calls,0);
}
TEST_F(HuayanCabinetIo, RejectOutOfRangeWithoutWriting) {
auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":4,"value":true})",false);
EXPECT_EQ(get(r,"error_code").asString(),"index_out_of_range");EXPECT_EQ(written,-1);
}
TEST_F(HuayanCabinetIo, PropagateSdkFailure) {
result=123;auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",false);
EXPECT_EQ(get(r,"sdk_return_code").asInt(),123);EXPECT_EQ(written,-1);
}
TEST_F(HuayanCabinetIo, DisconnectedNeverCallsSdk) {
HuayanIoTestAccess::connected(*arm,false);auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",false);
EXPECT_EQ(get(r,"error_code").asString(),"not_connected");EXPECT_EQ(calls,0);
}
TEST_F(HuayanCabinetIo, InvalidFeedbackIsNotReportedAsTrue) {
actual=7;auto r=invoke(R"({"command":"cabinet_io","operation":"get_do","index":0})",false);EXPECT_EQ(get(r,"error_code").asString(),"invalid_io_value");
}
}

View File

@ -253,9 +253,6 @@ JointGroupState MotorRobotArm::getJointState() const
for (const auto& motor : motors) {
state.current.push_back(static_cast<double>(motor->getCurrent()));
}
if (!motor_manager_ || !motor_manager_->readFeedbacksAtomic(motors, state.position, state.velocity))
return {};
state.effort.assign(motors.size(), 0.0);
return state;
}

View File

@ -330,11 +330,13 @@ void SpeedLExecutor::workerLoop_()
{
CycleGuard cycle{end_cycle_, status, computation_result};
const auto emergency_zero = [&] {
computation_result = false;
CMVR_LOG(ERROR) << "[SpeedLExecutor] constrained braking failed; issuing emergency zero"
<< " (acceleration/jerk not guaranteed): " << status.message;
const auto zero_result = sendVelocity_(JointVelocityCommand{std::vector<double>(dof_, 0.0)});
if (!zero_result.ok()) status.message += "; " + zero_result.message;
if (!zero_result.ok()) {
computation_result = false;
status.message += "; " + zero_result.message;
}
};
try {
if (begin_cycle_) {
@ -402,10 +404,12 @@ void SpeedLExecutor::workerLoop_()
!stop_requested_.load()) {
// Use the feedback from this acquired cycle: never release
// the failed cycle while the previous speed is still held.
computation_result = false;
planning_result = false;
computation_result = true;
planned = planner_->brakeStep(dt, q_now, qd_now);
status = planned.status;
// A joint-limit rejection still belongs to planning if
// emergency zero and the final measured stop succeed.
planning_result = status.code == ArmErrorCode::OutOfJointLimit;
}
if (status.ok() && !stop_requested_.load()) {
computation_result = false;

View File

@ -646,13 +646,16 @@ TEST(SpeedLExecutor, FailedCycleBrakesBeforeReleaseAndKeepsOriginalFaultUntilSto
}
TEST(SpeedLExecutor, FailedBrakeOrBrakeOutputSendsEmergencyZeroWithoutCommitting) {
for (const bool fail_output : {false, true}) {
SCOPED_TRACE(fail_output);
for (const std::string_view failure : {"braking limit", "brake output", "emergency zero"}) {
SCOPED_TRACE(failure);
auto planner = std::make_shared<Planner>();
planner->check = [](std::string_view operation) { return operation != "step"; };
std::atomic<bool> reject_step{true};
planner->check = [&](std::string_view operation) {
return operation != "step" || !reject_step.load();
};
planner->brake = [&](double, const auto&, const auto&) {
CartesianVelocityStep result;
result.status = fail_output ? Result::success()
result.status = failure == "brake output" ? Result::success()
: Result::failure(ArmErrorCode::OutOfJointLimit, "braking distance exhausted");
result.joint_velocity.velocity = {.02};
return result;
@ -662,10 +665,16 @@ TEST(SpeedLExecutor, FailedBrakeOrBrakeOutputSendsEmergencyZeroWithoutCommitting
SpeedLExecutor executor({}, planner, 1,
[](auto& q, auto& qd) { q = {0}; qd = {0}; return true; },
[&](const JointVelocityCommand& command) {
if (command.velocity.front() != 0)
return Result::failure(ArmErrorCode::CommandFailed, "brake send rejected");
if (command.velocity.front() != 0) {
return failure == "brake output"
? Result::failure(ArmErrorCode::CommandFailed, "brake send rejected")
: Result::success();
}
++zero_sends;
if (releases == 0) zero_before_release = true;
if (failure == "emergency zero" && zero_sends == 1) {
return Result::failure(ArmErrorCode::CommandFailed, "emergency zero rejected");
}
return Result::success();
}, {}, [] { return .001; }, [&](bool) { ++releases; });
CartesianVelocity target;
@ -678,8 +687,23 @@ TEST(SpeedLExecutor, FailedBrakeOrBrakeOutputSendsEmergencyZeroWithoutCommitting
EXPECT_EQ(planner->brakes, 1);
EXPECT_NE(executor.lastResult().message.find("step failed"), std::string::npos);
EXPECT_NE(executor.lastResult().message.find(
fail_output ? "brake send rejected" : "braking distance exhausted"), std::string::npos);
EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault);
failure == "brake output" ? "brake send rejected" : "braking distance exhausted"),
std::string::npos);
if (failure == "emergency zero") {
EXPECT_NE(executor.lastResult().message.find("emergency zero rejected"), std::string::npos);
}
ASSERT_TRUE(executor.shutdown().ok());
const auto recovery = executor.clearPlanningFault();
if (failure == "braking limit") {
ASSERT_TRUE(recovery.ok()) << recovery.message;
EXPECT_FALSE(executor.faulted());
reject_step.store(false);
ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok());
EXPECT_TRUE(waitUntil([&] { return planner->commits > 0; }));
} else {
EXPECT_EQ(recovery.code, ArmErrorCode::RobotInFault);
EXPECT_TRUE(executor.faulted());
}
EXPECT_TRUE(executor.shutdown().ok());
}
}

View File

@ -26,6 +26,18 @@ namespace cmvr::device {
float coeffs[5]{};
};
struct RgbFrameTiming
{
uint64_t frame_number{0};
double source_timestamp_ms{0};
const char* timestamp_domain{nullptr};
// Host arrival at the capture API. The source clock has its own epoch.
std::chrono::steady_clock::time_point host_received_at{};
std::chrono::steady_clock::time_point host_read_complete_at{};
bool buffered{false};
};
struct StreamFrameData
{
//原始图像数据
@ -66,6 +78,7 @@ namespace cmvr::device {
bool discontinuity = false;
uint32_t codec_config_generation = 0;
std::vector<uint8_t> codec_config;
RgbFrameTiming rgb_timing;
};
enum class PtzCommand {
@ -144,6 +157,11 @@ namespace cmvr::device {
}
virtual bool requestKeyFrame() { return false; }
virtual Eigen::Vector3f get3DPointFromPixel(int u, int v) {return {0,0,0};}
virtual void getRGBImageWithTiming(cv::Mat& color, Rs2Intrinsics& intrinsics,
RgbFrameTiming& timing) {
timing = {};
getRGBImage(color, intrinsics);
}
protected:
CameraState state_{};
mutable std::mutex stream_overlay_mutex_;

View File

@ -26,6 +26,8 @@ namespace cmvr::device{
bool stop() override;
void getState(CameraState& state) override;
void getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) override;
void getRGBImageWithTiming(cv::Mat& color, Rs2Intrinsics& intrinsics,
RgbFrameTiming& timing) override;
bool supportsDepthImage() const override { return stream_mode_ != COLOR_MODE; }
bool supportsDepthStream() const override { return stream_mode_ != COLOR_MODE; }
void getDepthImage(cv::Mat& depth, Rs2Intrinsics& intrinsics) override;
@ -44,6 +46,7 @@ namespace cmvr::device{
Eigen::Vector3f get3DPointFromPixel(int u, int v) override;
private:
void getRGBImage_(cv::Mat& color, Rs2Intrinsics& intrinsics, RgbFrameTiming* timing);
rs2::frameset get_frameset(bool align);
void streaming_worker_();
void recording_worker_();

View File

@ -10,6 +10,24 @@
using namespace std;
using namespace cmvr::device;
namespace {
RgbFrameTiming readRgbFrameTiming(const rs2::video_frame& frame,
std::chrono::steady_clock::time_point host_received_at)
{
RgbFrameTiming timing;
timing.host_received_at = host_received_at;
try {
timing.frame_number = frame.get_frame_number();
timing.source_timestamp_ms = frame.get_timestamp();
timing.timestamp_domain = rs2_timestamp_domain_to_string(frame.get_frame_timestamp_domain());
} catch (const rs2::error&) {
// RGB acquisition remains valid when source timing is unavailable.
}
return timing;
}
} // namespace
// 检查系统中是否存在指定序列号的 RealSense 设备
bool checkRealSenseCamera(const std::string& serialNumber = "") {
@ -352,6 +370,16 @@ bool RealsenseCamera::stop() {
}
void RealsenseCamera::getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) {
getRGBImage_(color, intrinsics, nullptr);
}
void RealsenseCamera::getRGBImageWithTiming(cv::Mat& color, Rs2Intrinsics& intrinsics,
RgbFrameTiming& timing) {
timing = {};
getRGBImage_(color, intrinsics, &timing);
}
void RealsenseCamera::getRGBImage_(cv::Mat& color, Rs2Intrinsics& intrinsics, RgbFrameTiming* timing) {
intrinsics.cx = intrinsics_.ppx;
intrinsics.cy = intrinsics_.ppy;
intrinsics.fx = intrinsics_.fx;
@ -377,10 +405,16 @@ void RealsenseCamera::getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) {
std::lock_guard<std::mutex> lock(frame_mtx_);
latest_depth_ = frame.value().depthImage.clone();
}
if (timing && !color.empty()) {
*timing = frame.value().rgb_timing;
timing->buffered = true;
}
}
else
{
rs2::frameset frames = get_frameset(false);
const auto host_received_at = timing ? std::chrono::steady_clock::now()
: std::chrono::steady_clock::time_point{};
auto color_frame = frames.get_color_frame();
auto depth_frame = frames.get_depth_frame();
@ -395,6 +429,9 @@ void RealsenseCamera::getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) {
std::lock_guard<std::mutex> lock(frame_mtx_);
latest_depth_ = depth;
}
if (timing && !color.empty()) {
*timing = readRgbFrameTiming(color_frame, host_received_at);
}
}
// CMVR_LOG(INFO) << "realsense get rgb frame successfully";
}
@ -755,6 +792,7 @@ void RealsenseCamera::streaming_worker_() {
rs2::frameset frames;
frames = get_frameset(true);
const auto host_received_at = std::chrono::steady_clock::now();
rs2::video_frame color_frame = frames.get_color_frame();
rs2::depth_frame depth_frame = frames.get_depth_frame();
const bool needs_color = stream_mode_ == COLOR_MODE || stream_mode_ == RGBD_MODE;
@ -787,6 +825,7 @@ void RealsenseCamera::streaming_worker_() {
cv::Mat temp(cv::Size(color_frame.get_width(), color_frame.get_height()),
CV_8UC3, const_cast<void*>(color_frame.get_data()), cv::Mat::AUTO_STEP);
temp.copyTo(frame_data.rgbImage); // 执行深拷贝
frame_data.rgb_timing = readRgbFrameTiming(color_frame, host_received_at);
}
if (depth_frame) {
cv::Mat temp(cv::Size(depth_frame.get_width(), depth_frame.get_height()),

View File

@ -200,7 +200,8 @@ namespace cmvr {
ErrorCode SocketCanClientRaw::receive(std::vector<CanFrame> *const frames,
int32_t *const frame_num) {
return receive(frames, frame_num, std::chrono::milliseconds{-1});
// Periodically return to CanReceiver stop checks, even on an idle bus.
return receive(frames, frame_num, std::chrono::milliseconds{100});
}
ErrorCode SocketCanClientRaw::receive(std::vector<CanFrame> *const frames,
@ -214,6 +215,7 @@ namespace cmvr {
if (frames == nullptr) {
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
frames->clear();
if (!is_started_) {
CMVR_LOG(ERROR) << "Nvidia can client is not init! Please init first!";
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;

View File

@ -54,7 +54,7 @@ namespace cmvr {
int32_t *const frame_num) override;
/**
* @brief Receive messages
* @brief Receive messages with a bounded 100 ms wait so receivers can stop
* @param frames The messages to receive.
* @param frame_num The amount of messages to receive.
* @return The status of the receiving action
@ -78,6 +78,7 @@ namespace cmvr {
*/
std::string getErrorString(const int32_t status) override;
private:
friend class SocketCanClientRawTestPeer;
int dev_handler_ = -1;
cmvr::msgs::CANCardParameter::CANChannelId port_;
cmvr::msgs::CANCardParameter::CANInterface interface_;

View File

@ -23,6 +23,7 @@
#pragma once
#include <atomic>
#include <chrono>
#include <cmath>
#include <future>
#include <iostream>
@ -138,12 +139,17 @@ namespace cmvr {
int32_t receive_error_count = 0;
const int32_t ERROR_COUNT_MAX = 10;
auto default_period = 10 * 1000; // 10 ms
auto* socket_can_client = dynamic_cast<SocketCanClientRaw*>(can_client_);
constexpr auto socket_receive_timeout = std::chrono::milliseconds{20};
while (IsRunning()) {
std::vector<CanFrame> buf;
int32_t frame_num = MAX_CAN_RECV_FRAME_LEN;
if (can_client_->receive(&buf, &frame_num) !=
cmvr::msgs::ErrorCode::OK) {
// Polling with a timeout lets Stop() join even when the bus is idle.
const auto result = socket_can_client
? socket_can_client->receive(&buf, &frame_num, socket_receive_timeout)
: can_client_->receive(&buf, &frame_num);
if (result != cmvr::msgs::ErrorCode::OK) {
CMVR_LOG_IF_EVERY_N(ERROR, receive_error_count++ > ERROR_COUNT_MAX,
ERROR_COUNT_MAX)
<< "Received " << receive_error_count << " error messages.";
@ -159,9 +165,10 @@ namespace cmvr {
}
if (frame_num == 0) {
// A bounded receive timeout on a silent bus is normal,
// not a transport error. Return to the stop-flag check.
std::this_thread::sleep_for(std::chrono::microseconds(default_period));
// SocketCAN already waited in poll. Back off only for nonblocking clients.
if (!socket_can_client) {
std::this_thread::sleep_for(std::chrono::microseconds(default_period));
}
continue;
}

View File

@ -158,11 +158,13 @@ private:
unsigned int al_state{0};
};
struct CycleTiming;
bool configureSlave_(SlaveRuntime& slave);
bool configureDc_();
bool waitSlavesOperational_();
void cyclicLoop_();
void monitorBusHealth_();
void monitorBusHealth_(const CycleTiming& timing);
void readFeedbackLocked_();
void writeCommandsLocked_();
void releaseMaster_();

View File

@ -15,6 +15,38 @@
namespace cmvr::device {
namespace {
using SteadyClock = std::chrono::steady_clock;
constexpr std::uint64_t skipExpiredCycleDeadlines(SteadyClock::time_point finished_at,
SteadyClock::duration period,
SteadyClock::time_point& next_cycle)
{
if (next_cycle > finished_at) {
return 0;
}
const auto missed = 1 + (finished_at - next_cycle) / period;
// Give the last PDO send a full period before processing the next cycle.
next_cycle = finished_at + period;
return static_cast<std::uint64_t>(missed);
}
auto toMicroseconds(SteadyClock::duration duration)
{
return std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
}
} // namespace
struct EthercatMotorBusRuntime::CycleTiming {
SteadyClock::duration last_send_interval{};
SteadyClock::duration min_send_interval{SteadyClock::duration::max()};
SteadyClock::duration max_send_interval{};
SteadyClock::duration max_wake_lateness{};
std::uint64_t missed_deadlines{0};
};
EthercatMotorBusRuntime::~EthercatMotorBusRuntime()
{
stop();
@ -538,11 +570,17 @@ void EthercatMotorBusRuntime::cyclicLoop_()
: std::chrono::milliseconds(0);
std::uint32_t dc_sync_counter = 0;
bool dc_monitor_queued = false;
auto cycle_time = std::chrono::steady_clock::now();
auto cycle_time = SteadyClock::now();
auto next_dc_monitor_time = cycle_time + dc_monitor_period;
const auto bus_monitor_period = std::chrono::milliseconds(100);
auto next_bus_monitor_time = cycle_time;
constexpr auto timing_log_period = std::chrono::seconds(1);
auto next_timing_log = cycle_time + timing_log_period;
SteadyClock::time_point last_send_at{};
CycleTiming timing;
while (running_.load()) {
const auto wake_lateness = SteadyClock::now() - cycle_time;
timing.max_wake_lateness = std::max(timing.max_wake_lateness, wake_lateness);
if (dc_enabled) {
ecrt_master_application_time(master_, timePointNs_(cycle_time));
}
@ -590,21 +628,45 @@ void EthercatMotorBusRuntime::cyclicLoop_()
} while (cycle_time >= next_dc_monitor_time);
}
}
const auto send_at = SteadyClock::now();
ecrt_master_send(master_);
if (last_send_at != SteadyClock::time_point{}) {
timing.last_send_interval = send_at - last_send_at;
timing.min_send_interval = std::min(timing.min_send_interval, timing.last_send_interval);
timing.max_send_interval = std::max(timing.max_send_interval, timing.last_send_interval);
}
last_send_at = send_at;
if (health_monitor_enabled_.load() && cycle_time >= next_bus_monitor_time) {
monitorBusHealth_();
monitorBusHealth_(timing);
do {
next_bus_monitor_time += bus_monitor_period;
} while (cycle_time >= next_bus_monitor_time);
}
if (send_at >= next_timing_log && timing.min_send_interval != SteadyClock::duration::max()) {
if (timing.missed_deadlines > 0) {
CMVR_LOG(DEBUG) << "[EthercatMotorBusRuntime] cyclic timing: " << id_
<< ", period_us=" << period.count()
<< ", min_send_interval_us="
<< toMicroseconds(timing.min_send_interval)
<< ", max_send_interval_us="
<< toMicroseconds(timing.max_send_interval)
<< ", max_wake_lateness_us="
<< toMicroseconds(timing.max_wake_lateness)
<< ", missed_deadlines=" << timing.missed_deadlines;
}
timing = {};
next_timing_log = send_at + timing_log_period;
}
cycle_time += period;
timing.missed_deadlines += skipExpiredCycleDeadlines(SteadyClock::now(), period, cycle_time);
std::this_thread::sleep_until(cycle_time);
}
}
void EthercatMotorBusRuntime::monitorBusHealth_()
void EthercatMotorBusRuntime::monitorBusHealth_(const CycleTiming& timing)
{
if (!master_ || !domain_) {
healthy_.store(false);
@ -685,7 +747,11 @@ void EthercatMotorBusRuntime::monitorBusHealth_()
<< ", master_al_states=" << current.master_al_states
<< ", domain_result=" << current.domain_result
<< ", wc_state=" << current.wc_state
<< ", working_counter=" << current.working_counter;
<< ", working_counter=" << current.working_counter
<< ", last_send_interval_us=" << toMicroseconds(timing.last_send_interval)
<< ", max_send_interval_us=" << toMicroseconds(timing.max_send_interval)
<< ", max_wake_lateness_us=" << toMicroseconds(timing.max_wake_lateness)
<< ", missed_deadlines=" << timing.missed_deadlines;
} else if (changed && last_bus_health_.initialized && current.healthy) {
CMVR_LOG(INFO) << "[EthercatMotorBusRuntime] bus communication recovered: "
<< id_

View File

@ -131,7 +131,15 @@ bool LingkongCanProtocol::probe(uint8_t id)
Status status;
double q, qd;
// Read-only initialization: no NMT, PDO setup, enabling or ROM writes.
return readStatus(id, status) && !status.isFault() && readFeedback(id, q, qd);
if (!readStatus(id, status)) return false;
if (status.isFault()) {
CMVR_LOG(ERROR) << "[LingkongCanProtocol] drive status rejected initialization: node=" << int(id)
<< ", protocol=" << (version_ == V2_38 ? "V2.38" : "V2.36")
<< ", motor_state=0x" << std::hex << int(status.motor_state)
<< ", error=0x" << status.error << std::dec;
return false;
}
return readFeedback(id, q, qd);
}
bool LingkongCanProtocol::setMode(uint8_t id, msgs::RunMode mode)
@ -397,8 +405,10 @@ bool LingkongCanProtocol::readFeedback(uint8_t id, double& q, double& qd)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
// Separate replies, not a simultaneous/atomic hardware sample.
const double position = getQ(id), velocity = getQd(id);
if (!std::isfinite(position) || !std::isfinite(velocity)) return false;
const double position = getQ(id);
if (!std::isfinite(position)) return false;
const double velocity = getQd(id);
if (!std::isfinite(velocity)) return false;
q = position;
qd = velocity;
return true;

View File

@ -267,7 +267,10 @@ TEST_F(LingkongTest, MissingRepliesNeverReuseOldData) {
EXPECT_TRUE(std::isnan(protocol->getQ(1)));
EXPECT_THROW(protocol->torqueOn(1), std::runtime_error);
double q = 42, qd = 43;
sent.clear();
EXPECT_FALSE(protocol->readFeedback(1, q, qd));
ASSERT_EQ(sent.size(), 1);
EXPECT_EQ(sent.front().data[0], 0x92);
EXPECT_EQ(q, 42); EXPECT_EQ(qd, 43);
transport_ok = false;
EXPECT_FALSE(protocol->quickStop(1));

View File

@ -4,7 +4,7 @@
## 配置与协议
`devices/touch/touch.pb.txt` 中的 `paxini_tip_1` 默认使用 CAN:
`devices/touch/touch.pb.txt` 中的 `paxini_tip` 默认使用 CAN:
```protobuf
px_6ax_genx_can {

View File

@ -18,6 +18,7 @@ add_library(cmvr_es::media_source_hub ALIAS media_source_hub)
if(NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
add_library(device_media_source_adapter STATIC
src/camera_coordinate_overlay.cpp
src/device_media_source_adapter.cpp
)
target_compile_features(device_media_source_adapter PUBLIC cxx_std_17)
@ -31,6 +32,8 @@ if(NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
cmvr_es::common
cmvr_es::proto
cmvr_es::logging
PRIVATE
cmvr_es::perception
)
add_library(cmvr_es::device_media_source_adapter ALIAS device_media_source_adapter)
endif()

View File

@ -0,0 +1,66 @@
#pragma once
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <optional>
#include <thread>
#include "devices/camera/abstract_camera.h"
namespace cmvr::perception {
class AprilTagPerception;
}
namespace cmvr::media {
struct CameraCoordinateOverlayConfig {
int screen_tag_id{-1};
double screen_tag_size_m{0.0};
int hand_tag_id{-1};
double hand_tag_size_m{0.0};
double axis_length_m{0.02};
};
// Consumes frames already captured for a color stream. Only the latest frame
// waits for detection, and publishing a frame never waits for the detector.
class CameraCoordinateOverlay {
public:
CameraCoordinateOverlay(std::shared_ptr<device::AbstractCamera> camera,
CameraCoordinateOverlayConfig config);
~CameraCoordinateOverlay();
void start();
void stop() noexcept;
void submit(const device::StreamFrameData& frame);
private:
using Clock = std::chrono::steady_clock;
struct Frame {
cv::Mat color;
device::Rs2Intrinsics intrinsics;
Clock::time_point expires_at;
std::uint64_t generation;
};
void run(perception::AprilTagPerception& detector);
const std::shared_ptr<device::AbstractCamera> camera_;
const CameraCoordinateOverlayConfig config_;
std::mutex lifecycle_mutex_;
std::thread worker_;
std::mutex mutex_;
std::condition_variable frame_ready_;
bool running_{false};
Clock::time_point started_at_{};
std::optional<std::uint64_t> stream_epoch_;
std::uint64_t generation_{0};
std::optional<Frame> pending_frame_;
};
} // namespace cmvr::media

View File

@ -13,6 +13,8 @@
namespace cmvr::media {
struct CameraCoordinateOverlayConfig;
// Process-wide protocol-neutral media hub shared by gRPC and QUIC services.
MediaSourceHub& globalMediaSourceHub();
@ -26,7 +28,8 @@ std::string microphoneTrackId(const std::string& device_id);
bool ensureCameraMediaSource(
MediaSourceHub& hub,
const std::shared_ptr<device::AbstractCamera>& camera,
size_t ring_capacity = 64);
size_t ring_capacity = 64,
const CameraCoordinateOverlayConfig* overlay_config = nullptr);
bool ensureMicrophoneMediaSource(
MediaSourceHub& hub,

View File

@ -0,0 +1,145 @@
#include "manager/media_source_hub/include/camera_coordinate_overlay.h"
#include <algorithm>
#include <exception>
#include <utility>
#include "algorithms/perception/apriltag/include/apriltag_perception.h"
#include "common/base/logging/logger.h"
namespace cmvr::media {
namespace {
constexpr auto kMaxOverlayFrameAge = std::chrono::milliseconds(250);
device::CameraStreamOverlay makeOverlay(const perception::AprilTagPerception& detector,
const CameraCoordinateOverlayConfig& config) {
device::CameraStreamOverlay overlay;
overlay.coordinate_axis_length_m = config.axis_length_m;
for (const auto& [id, label] : {std::pair{config.screen_tag_id, "G"},
std::pair{config.hand_tag_id, "H"}}) {
const auto* tag = detector.findTag(id);
if (tag && tag->T_C_Tag().allFinite()) {
overlay.coordinate_frames.push_back({tag->T_C_Tag(), label, id, true});
}
}
overlay.draw_coordinate_frames = !overlay.coordinate_frames.empty();
return overlay;
}
} // namespace
CameraCoordinateOverlay::CameraCoordinateOverlay(std::shared_ptr<device::AbstractCamera> camera,
CameraCoordinateOverlayConfig config)
: camera_(std::move(camera)), config_(config) {}
CameraCoordinateOverlay::~CameraCoordinateOverlay() {
stop();
}
void CameraCoordinateOverlay::start() {
std::lock_guard lifecycle_lock(lifecycle_mutex_);
if (worker_.joinable()) return;
auto detector = std::make_unique<perception::AprilTagPerception>();
detector->setTagSize(config_.screen_tag_size_m);
detector->setTagSizeForId(config_.hand_tag_id, config_.hand_tag_size_m);
std::lock_guard lock(mutex_);
camera_->setStreamOverlay({});
started_at_ = Clock::now();
worker_ = std::thread([this, detector = std::move(detector)] { run(*detector); });
running_ = true;
}
void CameraCoordinateOverlay::stop() noexcept {
std::lock_guard lifecycle_lock(lifecycle_mutex_);
if (!worker_.joinable()) return;
{
std::lock_guard lock(mutex_);
running_ = false;
pending_frame_.reset();
stream_epoch_.reset();
camera_->setStreamOverlay({});
}
frame_ready_.notify_one();
worker_.join();
}
void CameraCoordinateOverlay::submit(const device::StreamFrameData& frame) {
const auto now = Clock::now();
const auto captured_at = frame.capture_monotonic_ns > 0
? std::min(now, Clock::time_point(std::chrono::duration_cast<Clock::duration>(
std::chrono::nanoseconds(frame.capture_monotonic_ns))))
: now;
const auto expires_at = captured_at + kMaxOverlayFrameAge;
{
std::lock_guard lock(mutex_);
if (!running_ || captured_at < started_at_ || expires_at <= now) return;
if (stream_epoch_ != frame.stream_epoch || frame.discontinuity) {
stream_epoch_ = frame.stream_epoch;
++generation_;
pending_frame_.reset();
camera_->setStreamOverlay({});
}
if (frame.rgbImage.empty()) return;
// The stream frame owns its pixels. Retaining the Mat shares that
// immutable allocation without copying the encoded payload.
pending_frame_ = Frame{frame.rgbImage, frame.intrinsics, expires_at, generation_};
}
frame_ready_.notify_one();
}
void CameraCoordinateOverlay::run(perception::AprilTagPerception& detector) {
std::unique_lock lock(mutex_);
std::optional<Clock::time_point> overlay_expires_at;
const auto ready = [this] { return !running_ || pending_frame_.has_value(); };
while (running_) {
if (overlay_expires_at) {
frame_ready_.wait_until(lock, *overlay_expires_at, ready);
} else {
frame_ready_.wait(lock, ready);
}
if (!running_) break;
if (overlay_expires_at && Clock::now() >= *overlay_expires_at) {
camera_->setStreamOverlay({});
overlay_expires_at.reset();
}
if (!pending_frame_) continue;
const auto frame = std::move(*pending_frame_);
pending_frame_.reset();
lock.unlock();
device::CameraStreamOverlay overlay;
try {
if (frame.expires_at > Clock::now() &&
detector.updateFromRgbFrame(frame.color, frame.intrinsics)) {
overlay = makeOverlay(detector, config_);
}
} catch (const std::exception& error) {
CMVR_LOG_EVERY_N(WARNING, 30)
<< "[CameraCoordinateOverlay] Detection failed for "
<< camera_->id() << ": " << error.what();
} catch (...) {
CMVR_LOG_EVERY_N(WARNING, 30)
<< "[CameraCoordinateOverlay] Detection failed for " << camera_->id();
}
lock.lock();
if (!running_ || generation_ != frame.generation) continue;
if (overlay.draw_coordinate_frames && frame.expires_at > Clock::now()) {
camera_->setStreamOverlay(overlay);
overlay_expires_at = frame.expires_at;
} else {
camera_->setStreamOverlay({});
overlay_expires_at.reset();
}
}
}
} // namespace cmvr::media

View File

@ -14,6 +14,7 @@
#include <vector>
#include "common/base/logging/logger.h"
#include "manager/media_source_hub/include/camera_coordinate_overlay.h"
namespace cmvr::media {
namespace {
@ -282,10 +283,36 @@ struct PumpState : public std::enable_shared_from_this<PumpState<DeviceT>> {
};
struct CameraPump final : PumpState<device::AbstractCamera> {
CameraPump(std::shared_ptr<device::AbstractCamera> camera, std::string id)
: PumpState(std::move(camera)), track_id(std::move(id)) {}
CameraPump(std::shared_ptr<device::AbstractCamera> camera, std::string id,
const CameraCoordinateOverlayConfig* overlay_config)
: PumpState(std::move(camera)), track_id(std::move(id)),
overlay(overlay_config ? std::make_unique<CameraCoordinateOverlay>(device, *overlay_config)
: nullptr) {}
~CameraPump() override { stop(); }
bool begin(const MediaSourceHub::FrameSink& sink,
const MediaSourceHub::CancelPredicate& cancelled) {
if (!PumpState::begin(sink, cancelled)) {
return false;
}
if (overlay) {
try {
overlay->start();
} catch (const std::exception& error) {
CMVR_LOG(WARNING) << "[DeviceMediaSourceAdapter] Failed to start camera overlay for "
<< track_id << ": " << error.what();
}
}
return true;
}
void stop() noexcept {
if (overlay) {
overlay->stop();
}
PumpState::stop();
}
void run() override {
size_t cursor = 0;
uint64_t last_epoch = 0;
@ -337,6 +364,9 @@ struct CameraPump final : PumpState<device::AbstractCamera> {
if (source.rgbFrame.empty()) {
continue;
}
if (overlay) {
overlay->submit(source);
}
const uint64_t descriptor_generation = descriptorGeneration(
source.stream_epoch, source.codec_config_generation);
@ -456,6 +486,7 @@ struct CameraPump final : PumpState<device::AbstractCamera> {
}
std::string track_id;
std::unique_ptr<CameraCoordinateOverlay> overlay;
};
struct MicrophonePump final : PumpState<device::AbstractMicrophone> {
@ -624,7 +655,8 @@ std::string microphoneTrackId(const std::string& device_id) {
bool ensureCameraMediaSource(
MediaSourceHub& hub,
const std::shared_ptr<device::AbstractCamera>& camera,
const size_t ring_capacity) {
const size_t ring_capacity,
const CameraCoordinateOverlayConfig* overlay_config) {
if (!camera || camera->id().empty()) {
return false;
}
@ -633,7 +665,7 @@ bool ensureCameraMediaSource(
return true;
}
const auto pump = std::make_shared<CameraPump>(camera, track_id);
const auto pump = std::make_shared<CameraPump>(camera, track_id, overlay_config);
MediaSourceHub::SourceCallbacks callbacks;
callbacks.start = [pump](
const MediaSourceHub::FrameSink& sink,

View File

@ -14,6 +14,8 @@ target_link_libraries(cmvr_runtime PUBLIC
cmvr_es::service
cmvr_es::quic_edge_task
cmvr_es::mujoco_viewer
PRIVATE
cmvr_es::device_media_source_adapter
)
add_library(cmvr_es::runtime ALIAS cmvr_runtime)

View File

@ -1,5 +1,6 @@
#include "runtime/include/cmvr_runtime.h"
#include <cmath>
#include <limits.h>
#include <unistd.h>
@ -7,9 +8,12 @@
#include "cmvr/config/device_manager_config/device_manager_config.pb.h"
#include "cmvr/config/logger_config/logger_config.pb.h"
#include "cmvr/config/task_manager_config/task_manager_config.pb.h"
#include "cmvr/config/touch_screen_task_config/touch_screen_task_config.pb.h"
#include "common/base/logging/logger.h"
#include "common/config/config_files.h"
#include "common/io/proto_file_io.h"
#include "manager/media_source_hub/include/camera_coordinate_overlay.h"
#include "manager/media_source_hub/include/device_media_source_adapter.h"
#include "task/grpc_server_task/include/grpc_server_task.h"
#include "task/quic_edge_task/include/quic_edge_task.h"
@ -21,6 +25,49 @@ void logSection(const char* title)
CMVR_LOG(INFO) << "---------------- " << title << " ----------------";
}
void registerPreviewOverlays(const config::TaskManagerConfig& tasks,
device::DeviceManager& devices)
{
auto& hub = media::globalMediaSourceHub();
for (const auto& entry : tasks.tasks()) {
if (entry.type() != config::TaskConfigEntry::TASK_TYPE_TOUCH_SCREEN ||
entry.config_file().empty()) {
continue;
}
config::TouchScreenTaskRootConfig root;
if (!ConfigHelper::loadConfigFile(entry.config_file(), root) ||
!root.has_touch_screen_task()) {
continue;
}
const auto& cfg = root.touch_screen_task();
if (cfg.has_debug_draw_coordinate_frames() && !cfg.debug_draw_coordinate_frames()) {
continue;
}
const auto& camera_id = cfg.devices().external_camera_id();
const auto& screen = cfg.perception().tags().screen();
const auto& hand = cfg.perception().tags().hand();
if (camera_id.empty() || !screen.has_id() || !hand.has_id() ||
screen.id() < 0 || hand.id() < 0 || screen.id() == hand.id() ||
!std::isfinite(screen.size_m()) || screen.size_m() <= 0.0 ||
!std::isfinite(hand.size_m()) || hand.size_m() <= 0.0) {
CMVR_LOG(WARNING) << "[Startup] Invalid preview overlay configuration: "
<< entry.config_file();
continue;
}
const auto camera = devices.getDevice<device::AbstractCamera>(camera_id);
if (!camera) {
continue;
}
const double axis_length = cfg.debug_coordinate_axis_length_m();
const media::CameraCoordinateOverlayConfig overlay{
screen.id(), screen.size_m(), hand.id(), hand.size_m(),
std::isfinite(axis_length) && axis_length > 0.0 ? axis_length : 0.02};
if (!media::ensureCameraMediaSource(hub, camera, 64, &overlay)) {
CMVR_LOG(WARNING) << "[Startup] Failed to register preview overlay: " << camera_id;
}
}
}
} // namespace
Runtime::~Runtime()
@ -100,7 +147,7 @@ bool Runtime::init_(const std::string& config_path,
return false;
}
CMVR_LOG(INFO) << "[Startup] Initialize DeviceManager";
device::DeviceManager::getInstance(device_manager_root.device_manager());
auto& devices = device::DeviceManager::getInstance(device_manager_root.device_manager());
task::registerGrpcServerTaskFactory();
task::registerQuicEdgeTaskFactory();
@ -119,6 +166,7 @@ bool Runtime::init_(const std::string& config_path,
return false;
}
registerPreviewOverlays(task_manager_root.task_manager(), devices);
CMVR_LOG(INFO) << "[Startup] Initialize TaskManager";
task::TaskManager::getInstance(task_manager_root.task_manager());
initialized_ = true;
@ -156,6 +204,7 @@ void Runtime::shutdown()
stopTasks();
}
if (initialized_) {
media::globalMediaSourceHub().shutdown();
device::DeviceManager::getInstance().stop();
task::TaskManager::destroyInstance();
device::DeviceManager::destroyInstance();

View File

@ -12,8 +12,6 @@
#include <unordered_set>
#include <utility>
#include "common/base/logging/logger.h"
namespace cmvr::quic_edge {
namespace {
@ -112,12 +110,6 @@ public:
const std::string& server_name =
config.tls().allow_insecure() || config.tls().server_name().empty()
? config.server_host() : config.tls().server_name();
CMVR_LOG(INFO) << "[MsQuicTransport] ConnectionStart"
<< ", connect_host=" << server_name
<< ", configured_server_host=" << config.server_host()
<< ", port=" << config.server_port()
<< ", ca_file=" << config.tls().ca_file()
<< ", allow_insecure=" << config.tls().allow_insecure();
status = api_->ConnectionStart(
opened_connection, configuration_, QUIC_ADDRESS_FAMILY_UNSPEC,
server_name.c_str(),

View File

@ -753,24 +753,12 @@ void QuicEdgeService::run()
}
resetConnectionStatus();
setState(QuicEdgeServiceState::CONNECTING);
CMVR_LOG(INFO) << "[QuicEdgeService] connecting"
<< ", target=" << config_.server_host() << ':'
<< config_.server_port()
<< ", tls_server_name=" << config_.tls().server_name()
<< ", alpn=" << config_.alpn()
<< ", node_id=" << node_id_;
std::string error;
if (!transport_->connect(
config_,
std::chrono::milliseconds(config_.reconnect().connect_timeout_ms()),
&error)) {
CMVR_LOG(ERROR) << "[QuicEdgeService] connect failed"
<< ", target=" << config_.server_host() << ':'
<< config_.server_port()
<< ", error="
<< (error.empty() ? "QUIC connect failed" : error)
<< ", backoff_ms=" << backoff.count();
setState(QuicEdgeServiceState::BACKOFF,
error.empty() ? "QUIC connect failed" : error);
if (waitForStop(jittered(backoff))) break;
@ -792,10 +780,6 @@ void QuicEdgeService::run()
has_inbound_message_sequence_ = false;
ControlFrameDecoder decoder(config_.maximum_control_frame_bytes());
setState(QuicEdgeServiceState::REGISTERING);
CMVR_LOG(INFO) << "[QuicEdgeService] connected, registering node"
<< ", target=" << config_.server_host() << ':'
<< config_.server_port()
<< ", node_id=" << node_id_;
if (!performRegistration(&decoder, &error)) {
transport_->disconnect();
@ -803,22 +787,13 @@ void QuicEdgeService::run()
std::lock_guard lock(mutex_);
if (stop_requested_) break;
}
CMVR_LOG(ERROR) << "[QuicEdgeService] registration failed"
<< ", target=" << config_.server_host() << ':'
<< config_.server_port()
<< ", error=" << error
<< ", backoff_ms=" << backoff.count();
setState(QuicEdgeServiceState::BACKOFF, error);
setState(QuicEdgeServiceState::BACKOFF,
error.empty() ? "QUIC node registration failed" : error);
if (waitForStop(jittered(backoff))) break;
backoff = nextBackoff(backoff);
continue;
}
setState(QuicEdgeServiceState::ONLINE);
CMVR_LOG(INFO) << "[QuicEdgeService] online"
<< ", target=" << config_.server_host() << ':'
<< config_.server_port()
<< ", node_id=" << node_id_
<< ", session=" << session_id_;
if (!startMediaWorker(&error)) {
transport_->disconnect();
@ -826,7 +801,8 @@ void QuicEdgeService::run()
std::lock_guard lock(mutex_);
if (stop_requested_) break;
}
setState(QuicEdgeServiceState::BACKOFF, error);
setState(QuicEdgeServiceState::BACKOFF,
error.empty() ? "QUIC media worker failed to start" : error);
if (waitForStop(jittered(backoff))) break;
backoff = nextBackoff(backoff);
continue;
@ -1192,18 +1168,6 @@ bool QuicEdgeService::sendNodeRegistration(std::string* error)
return false;
}
if (!sendControlEnvelope(serialized, error)) return false;
const auto& node = request->node();
CMVR_LOG(INFO) << "[QuicEdgeService] sent NodeRegisterRequest"
<< ", message_sequence=" << envelope.message_sequence()
<< ", payload_bytes=" << serialized.size()
<< ", node_id=" << node.node_id()
<< ", robot_id=" << node.robot_id()
<< ", boot_id=" << node.boot_id()
<< ", grpc_endpoint=" << node.grpc_endpoint().host()
<< ':' << node.grpc_endpoint().port()
<< ", grpc_tls=" << node.grpc_endpoint().tls()
<< ", interfaces=" << node.local_interfaces_size()
<< ", sent_at_unix_ms=" << request->sent_at_unix_ms();
std::lock_guard lock(mutex_);
++stats_.registrations_sent;
return true;
@ -1268,19 +1232,7 @@ bool QuicEdgeService::sendHeartbeat(const std::uint64_t sequence,
setError(error, "failed to serialize NodeHeartbeat");
return false;
}
if (!sendControlEnvelope(serialized, error)) return false;
CMVR_LOG(INFO) << "[QuicEdgeService] sent NodeHeartbeat"
<< ", message_sequence=" << envelope.message_sequence()
<< ", payload_bytes=" << serialized.size()
<< ", robot_id=" << heartbeat->robot_id()
<< ", session=" << session_id
<< ", heartbeat_sequence=" << sequence
<< ", grpc_endpoint=" << heartbeat->grpc_endpoint().host()
<< ':' << heartbeat->grpc_endpoint().port()
<< ", interfaces=" << heartbeat->local_interfaces_size()
<< ", devices=" << heartbeat->device_manager().devices_size()
<< ", sent_at_unix_ms=" << sent_at_unix_ms;
return true;
return sendControlEnvelope(serialized, error);
}
bool QuicEdgeService::receiveAndDispatchControl(
@ -1561,14 +1513,7 @@ bool QuicEdgeService::sendSessionOpen(std::string* error)
setError(error, "failed to serialize MediaSessionOpen");
return false;
}
if (!sendControlEnvelope(serialized, error)) return false;
CMVR_LOG(INFO) << "[QuicEdgeService] sent MediaSessionOpen"
<< ", message_sequence=" << envelope.message_sequence()
<< ", payload_bytes=" << serialized.size()
<< ", session=" << session_id
<< ", session_epoch=" << session_epoch_
<< ", node_id=" << node_id_;
return true;
return sendControlEnvelope(serialized, error);
}
bool QuicEdgeService::sendTrackDescription(
@ -1602,25 +1547,7 @@ bool QuicEdgeService::sendTrackDescription(
setError(error, "failed to serialize MediaTrackDescriptor");
return false;
}
if (!sendControlEnvelope(serialized, error)) return false;
CMVR_LOG(INFO) << "[QuicEdgeService] sent MediaTrackDescriptor"
<< ", message_sequence=" << envelope.message_sequence()
<< ", payload_bytes=" << serialized.size()
<< ", track_id=" << description.track_id
<< ", source_track_id=" << description.source_track_id
<< ", source_id=" << description.source_id
<< ", kind=" << static_cast<int>(description.kind)
<< ", codec=" << codecName(description.codec)
<< ", payload_format=" << payloadFormatName(description.payload_format)
<< ", codec_generation=" << description.codec_generation
<< ", codec_generation_token="
<< description.codec_generation_token
<< ", size=" << description.width << 'x' << description.height
<< ", fps=" << description.nominal_rate
<< ", sample_rate=" << description.sample_rate
<< ", channels=" << description.channels
<< ", codec_config_bytes=" << description.codec_config.size();
return true;
return sendControlEnvelope(serialized, error);
}
bool QuicEdgeService::sendControlEnvelope(const std::string& serialized,
@ -1813,22 +1740,6 @@ bool QuicEdgeService::processTrack(ActiveTrack* track,
std::lock_guard lock(mutex_);
++stats_.frames_queued;
stats_.datagrams_queued += datagram_count;
CMVR_LOG(INFO) << "[QuicEdgeService] queued media frame"
<< ", track_id=" << track->config.track_id()
<< ", source_track_id=" << track->source_track_id
<< ", frame_sequence=" << frame->sequence
<< ", wire_frame_sequence=" << wire_frame_sequence
<< ", payload_bytes=" << frame->size()
<< ", datagrams=" << datagram_count
<< ", key_frame=" << frame->key_frame
<< ", discontinuity=" << discontinuity
<< ", codec=" << codecName(description.codec)
<< ", payload_format="
<< payloadFormatName(description.payload_format)
<< ", capture_timestamp_us="
<< frame->capture_time_ns / 1000U
<< ", source_timestamp=" << frame->source_timestamp
<< ", source_frame_number=" << frame->source_frame_number;
return true;
}
if (result == TransportSendResult::WOULD_BLOCK) {
@ -1923,13 +1834,26 @@ void QuicEdgeService::recordMediaError(const std::string& error)
void QuicEdgeService::setState(const QuicEdgeServiceState state,
const std::string& error)
{
std::lock_guard lock(mutex_);
state_ = state;
if (!error.empty()) {
last_error_ = error;
} else if (state == QuicEdgeServiceState::ONLINE ||
state == QuicEdgeServiceState::STOPPED) {
last_error_.clear();
QuicEdgeServiceState previous_state;
bool report_error;
{
std::lock_guard lock(mutex_);
previous_state = state_;
state_ = state;
if (!error.empty()) {
last_error_ = error;
} else if (state == QuicEdgeServiceState::ONLINE ||
state == QuicEdgeServiceState::STOPPED) {
last_error_.clear();
}
report_error = !error.empty() &&
!(state == QuicEdgeServiceState::BACKOFF && stop_requested_);
}
if (report_error) {
CMVR_LOG(ERROR) << "[QuicEdgeService] phase=" << toString(previous_state)
<< ", state=" << toString(state)
<< ", target=" << config_.server_host() << ':' << config_.server_port()
<< ", error=" << error;
}
}

View File

@ -35,6 +35,7 @@ target_link_libraries(touch_screen_task_test PRIVATE
cmvr_es::proto
cmvr_es::device_manager
cmvr_es::service
cmvr_es::device_media_source_adapter
gtest
gtest_main
pthread

View File

@ -244,8 +244,6 @@ bool QuicEdgeTask::start()
}
last_error_.clear();
state_ = TaskState::RUNNING;
CMVR_LOG(INFO) << "[QuicEdgeTask] Started, id=" << id_
<< ", platforms=" << services_.size();
return true;
}

View File

@ -6,12 +6,11 @@
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
#include <vector>
#include <Eigen/Dense>
@ -135,7 +134,12 @@ private:
bool stepPreparing();
bool stepApproaching();
void cancelApproach();
bool stepAligning(double dt);
void logApproachPoseSample(const char* stage,
const Eigen::Matrix4d& T_B_P,
const Eigen::Matrix4d& T_B_G,
Clock::time_point fk_started_at,
Clock::time_point fk_finished_at) const;
bool stepAligning(double nominal_dt);
// Perception helpers return readiness; waiting keeps stepAligning active.
bool updateAlignmentAnchor(Eigen::Vector3d& p_target_G);
bool updateAlignmentTcpPose();
@ -143,6 +147,7 @@ private:
const Eigen::Matrix4d& T_G_P);
bool mapAlignmentCommandToBase(const Eigen::Matrix4d& T_G_P,
const PbvsController::Output& output,
double pbvs_dt,
device::CartesianVelocity& twist_B);
bool applyAlignmentCommand(const PbvsController::Output& output,
const device::CartesianVelocity& twist_B);
@ -150,6 +155,7 @@ private:
bool stepDwelling();
bool stepRetracting();
void resetPbvsCommandState();
void stopPbvsMotion();
bool buildInitJointPositions(std::vector<double>& positions_out) const;
bool isAtInitPosition(const std::vector<double>& positions) const;
@ -166,25 +172,12 @@ private:
bool updateTouchPressure();
void logTouchPressure(bool force = false);
device::CameraStreamOverlay buildCoordinateOverlay(
const perception::AprilTagPerception* overlay_perception) const;
void publishCoordinateOverlay();
void startCoordinateOverlayWorker();
void stopCoordinateOverlayWorker();
void setCoordinateOverlayEnabled(bool enabled);
void coordinateOverlayLoop(std::shared_ptr<perception::AprilTagPerception> overlay_perception);
private:
mutable std::mutex mutex_;
// The motion worker captures values only; it never takes the task mutex.
std::future<device::Result> approach_motion_;
std::shared_ptr<std::atomic<bool>> approach_cancel_;
// The display worker never takes mutex_ or uses the PBVS perception state.
std::mutex coordinate_overlay_mutex_;
std::condition_variable coordinate_overlay_cv_;
std::thread coordinate_overlay_thread_;
bool coordinate_overlay_stop_{false};
bool coordinate_overlay_enabled_{true};
std::string id_;
std::shared_ptr<device::RobotArm> arm_{nullptr};
std::shared_ptr<device::AbstractTouch> touch_{nullptr};
@ -242,6 +235,7 @@ private:
double max_T_B_G_rotation_delta_rad_{0.0};
Clock::time_point phase_start_time_{};
std::optional<Clock::time_point> last_pbvs_update_time_;
Clock::time_point last_touch_pressure_log_time_{};
Clock::time_point last_retract_log_time_{};
Status final_status_after_retract_{Status::DONE};

View File

@ -3,11 +3,11 @@
#include <algorithm>
#include <cmath>
#include <exception>
#include <iomanip>
#include <limits>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <opencv2/imgcodecs.hpp>
@ -45,6 +45,12 @@ bool computeLinearMoveDeltaTool(const Eigen::Matrix<double, 6, 1>& twist_base,
using TouchScreenTaskConfig = cmvr::config::TouchScreenTaskConfig;
void configureTagSizes(perception::AprilTagPerception& detector,
const cmvr::config::TouchScreenTaskTagsConfig& tags) {
detector.setTagSize(tags.screen().size_m());
detector.setTagSizeForId(tags.hand().id(), tags.hand().size_m());
}
std::array<double, 6> toArray6(const Eigen::Matrix<double, 6, 1>& value) {
return {{value[0], value[1], value[2], value[3], value[4], value[5]}};
}
@ -193,14 +199,12 @@ TouchScreenTask::TouchScreenTask(const cmvr::config::TouchScreenTaskConfig& cfg)
TouchScreenTask::~TouchScreenTask() {
cancelApproach();
stopCoordinateOverlayWorker();
}
bool TouchScreenTask::init() {
{
std::lock_guard<std::mutex> lock(mutex_);
stopUnlocked();
stopCoordinateOverlayWorker();
initialized_ = false;
last_status_ = config_valid_ ? Status::NOT_INITIALIZED : Status::INVALID_CONFIG;
if (!config_valid_) return false;
@ -256,7 +260,6 @@ bool TouchScreenTask::init(const std::shared_ptr<device::RobotArm>& arm,
std::lock_guard<std::mutex> lock(mutex_);
stopUnlocked();
initialized_ = false;
stopCoordinateOverlayWorker();
arm_ = arm;
touch_ = touch_sensor;
camera_ = camera;
@ -295,9 +298,6 @@ bool TouchScreenTask::init(const std::shared_ptr<device::RobotArm>& arm,
phase_ = Phase::IDLE;
resetRunState();
last_status_ = Status::IDLE;
// Make presentation settings available before the first task tick.
publishCoordinateOverlay();
startCoordinateOverlayWorker();
return initialized_;
}
@ -331,7 +331,6 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) {
CMVR_LOG(ERROR) << "[TouchScreenTask][START_REJECTED] " << message;
if (phase_ != Phase::FAILED) last_status_ = Status::ROBOT_COMMAND_FAILED;
phase_ = Phase::FAILED;
setCoordinateOverlayEnabled(true);
return false;
};
cancelApproach();
@ -342,6 +341,19 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) {
if (!arm_->isConnected()) return reject_start("arm is not connected");
const auto stopped = arm_->stopMotion();
if (!stopped.ok()) return reject_start("stop failed: " + stopped.message);
const auto speed_l_result = arm_->getSpeedLResult();
if (!speed_l_result.ok() && speed_l_result.code != device::ArmErrorCode::UnsupportedCommand &&
arm_->isFault()) {
if (arm_->isEmergencyStopped() || arm_->isProtectiveStopped()) {
return reject_start("safety stop active");
}
if (!arm_->isConnected()) return reject_start("arm is not connected");
const auto cleared = arm_->clearFault();
if (!cleared.ok()) return reject_start("speedL clearFault failed: " + cleared.message);
CMVR_LOG(INFO) << "[TouchScreenTask] cleared speedL fault on "
<< config_.devices().arm_id() << ": " << speed_l_result.message;
}
const auto recovered = arm_->recoverSpeedLPlanningFault();
if (!recovered.ok()) return reject_start(recovered.message);
} catch (const std::exception& error) {
@ -363,8 +375,6 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) {
target_u_ = u;
target_v_ = v;
phase_ = config_.approach().enable() ? Phase::PREPARING : Phase::ALIGNING;
setCoordinateOverlayEnabled(false);
startCoordinateOverlayWorker();
phase_start_time_ = Clock::now();
last_status_ = config_.approach().enable() ? Status::PREPARING : Status::ALIGN_WAITING_TRACK;
return true;
@ -438,168 +448,16 @@ bool TouchScreenTask::step(const double dt) {
return false;
}
device::CameraStreamOverlay TouchScreenTask::buildCoordinateOverlay(
const perception::AprilTagPerception* overlay_perception) const
{
device::CameraStreamOverlay overlay;
overlay.draw_coordinate_frames =
!config_.has_debug_draw_coordinate_frames() ||
config_.debug_draw_coordinate_frames();
overlay.coordinate_axis_length_m = 0.02;
if (config_.has_debug_coordinate_axis_length_m() &&
std::isfinite(config_.debug_coordinate_axis_length_m()) &&
config_.debug_coordinate_axis_length_m() > 0.0) {
overlay.coordinate_axis_length_m = config_.debug_coordinate_axis_length_m();
}
if (overlay.draw_coordinate_frames && overlay_perception) {
const auto& tags = config_.perception().tags();
const int screen_tag_id = tags.screen().id();
const int hand_tag_id = tags.hand().id();
const auto* screen_tag = overlay_perception->findTag(screen_tag_id);
if (screen_tag) {
device::CoordinateFrameOverlay frame;
frame.T_C_Frame = screen_tag->T_C_Tag();
frame.label = "G";
frame.tag_id = screen_tag->id;
frame.valid = true;
overlay.coordinate_frames.push_back(std::move(frame));
}
if (const auto* hand_tag = overlay_perception->findTag(hand_tag_id)) {
device::CoordinateFrameOverlay frame;
frame.T_C_Frame = hand_tag->T_C_Tag();
frame.label = "H";
frame.tag_id = hand_tag->id;
frame.valid = true;
overlay.coordinate_frames.push_back(std::move(frame));
}
}
return overlay;
}
void TouchScreenTask::publishCoordinateOverlay()
{
if (external_camera_) {
external_camera_->setStreamOverlay(buildCoordinateOverlay(external_perception_.get()));
}
}
void TouchScreenTask::startCoordinateOverlayWorker()
{
if (coordinate_overlay_thread_.joinable() || !external_camera_ ||
(config_.has_debug_draw_coordinate_frames() &&
!config_.debug_draw_coordinate_frames())) {
return;
}
try {
// AprilTagPerception owns mutable frame/detector state. Never share
// the PBVS instance with the display worker.
auto overlay_perception =
std::make_shared<perception::AprilTagPerception>(external_camera_);
overlay_perception->setTagSize(config_.perception().tags().screen().size_m());
{
std::lock_guard<std::mutex> lock(coordinate_overlay_mutex_);
coordinate_overlay_stop_ = false;
coordinate_overlay_enabled_ = phase_ != Phase::ALIGNING;
}
coordinate_overlay_thread_ = std::thread(
&TouchScreenTask::coordinateOverlayLoop, this, std::move(overlay_perception));
} catch (const std::exception& e) {
CMVR_LOG(WARNING) << "[TouchScreenTask] Failed to start coordinate overlay worker: "
<< e.what();
}
}
void TouchScreenTask::stopCoordinateOverlayWorker()
{
{
std::lock_guard<std::mutex> lock(coordinate_overlay_mutex_);
coordinate_overlay_stop_ = true;
}
coordinate_overlay_cv_.notify_all();
if (coordinate_overlay_thread_.joinable()) {
coordinate_overlay_thread_.join();
}
}
void TouchScreenTask::setCoordinateOverlayEnabled(const bool enabled)
{
{
std::lock_guard<std::mutex> lock(coordinate_overlay_mutex_);
coordinate_overlay_enabled_ = enabled;
}
coordinate_overlay_cv_.notify_all();
}
void TouchScreenTask::coordinateOverlayLoop(
std::shared_ptr<perception::AprilTagPerception> overlay_perception)
{
perception::AprilTagPerception::Options options;
options.depth_policy = perception::AprilTagPerception::DepthPolicy::NONE;
options.detect_tags = true;
options.fetch_encoded = false;
const auto refresh_period =
std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(1.0 / 30.0));
std::unique_lock<std::mutex> lock(coordinate_overlay_mutex_);
while (true) {
coordinate_overlay_cv_.wait(lock, [this] {
return coordinate_overlay_stop_ || coordinate_overlay_enabled_;
});
if (coordinate_overlay_stop_) {
break;
}
const auto next_refresh = Clock::now() + refresh_period;
lock.unlock();
// No task/worker lock is held during camera acquisition or tag detection.
try {
overlay_perception->update(options);
const auto overlay = buildCoordinateOverlay(overlay_perception.get());
std::lock_guard<std::mutex> publish_lock(coordinate_overlay_mutex_);
// ALIGNING publishes its own perception snapshot. Discard an
// in-flight display frame if alignment or shutdown has started.
if (!coordinate_overlay_stop_ && coordinate_overlay_enabled_) {
external_camera_->setStreamOverlay(overlay);
}
} catch (const std::exception& e) {
CMVR_LOG_EVERY_N(WARNING, 30)
<< "[TouchScreenTask] Coordinate overlay refresh failed: " << e.what();
} catch (...) {
CMVR_LOG_EVERY_N(WARNING, 30)
<< "[TouchScreenTask] Coordinate overlay refresh failed: unknown exception";
}
lock.lock();
coordinate_overlay_cv_.wait_until(lock, next_refresh, [this] {
return coordinate_overlay_stop_ || !coordinate_overlay_enabled_;
});
}
}
void TouchScreenTask::stop() {
std::lock_guard<std::mutex> lock(mutex_);
stopUnlocked();
stopCoordinateOverlayWorker();
}
void TouchScreenTask::stopUnlocked() {
cancelApproach();
if (arm_) {
try {
arm_->stopL();
} catch (...) {
}
}
pbvs_.resetTwistCommandState();
stopPbvsMotion();
phase_ = Phase::IDLE;
setCoordinateOverlayEnabled(true);
resetRunState();
last_status_ = Status::STOPPED;
}
@ -629,6 +487,7 @@ void TouchScreenTask::resetRunState() {
last_T_B_G_.setIdentity();
max_T_B_G_translation_delta_m_ = 0.0;
max_T_B_G_rotation_delta_rad_ = 0.0;
last_pbvs_update_time_.reset();
last_touch_pressure_log_time_ = Clock::time_point{};
}
@ -904,7 +763,6 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig&
screen_tag.id() == hand_tag.id() ||
!std::isfinite(screen_tag.size_m()) || screen_tag.size_m() <= 0.0 ||
!std::isfinite(hand_tag.size_m()) || hand_tag.size_m() <= 0.0 ||
std::abs(screen_tag.size_m() - hand_tag.size_m()) > 1e-12 ||
config.devices().camera_id().empty() ||
config.devices().external_camera_id().empty() ||
!isHomogeneousTransform(T_H_P) ||
@ -1048,8 +906,8 @@ bool TouchScreenTask::applyConfig() {
const auto& hand_camera_config = perception.hand_camera();
const auto& calibration = config_.alignment().calibration();
const auto& pbvs = config_.alignment().pbvs();
perception_->setTagSize(tags.screen().size_m());
external_perception_->setTagSize(tags.screen().size_m());
configureTagSizes(*perception_, tags);
configureTagSizes(*external_perception_, tags);
tracker_.setTargetPointMethod(toTargetPointMethod(hand_camera_config.target_point_method()));
tcp_pose_tracker_.setPerception(external_perception_);
tcp_pose_tracker_.setScreenTagId(tags.screen().id());
@ -1119,7 +977,9 @@ bool TouchScreenTask::stepPreparing() {
if (!updatePbvsTarget(anchor_G, T_G_P)) return false;
try {
const auto fk_started_at = Clock::now();
const Eigen::Matrix4d T_B_P = common::math::poseToMatrix(arm_->fk(true));
const auto fk_finished_at = Clock::now();
const Eigen::Matrix4d T_B_G = T_B_P * T_G_P.inverse();
const Eigen::Matrix4d target_B = T_B_G * pbvs_.targetPose();
if (!isHomogeneousTransform(T_B_G) || !isHomogeneousTransform(target_B)) {
@ -1151,6 +1011,7 @@ bool TouchScreenTask::stepPreparing() {
return false;
}
logApproachPoseSample("BEFORE_MOVE_P", T_B_P, T_B_G, fk_started_at, fk_finished_at);
phase_start_time_ = Clock::now();
const auto started = phase_start_time_;
const double timeout_s = cfg.timeout_s();
@ -1210,7 +1071,7 @@ bool TouchScreenTask::stepApproaching() {
// Keep the original screen anchor and desired pose, but reacquire the live
// TCP pose and start PBVS with zero command history and its own timeout.
tcp_pose_tracker_.clear();
pbvs_.resetTwistCommandState();
resetPbvsCommandState();
align_stable_count_ = 0;
phase_ = Phase::ALIGNING;
phase_start_time_ = Clock::now();
@ -1219,7 +1080,50 @@ bool TouchScreenTask::stepApproaching() {
return true;
}
bool TouchScreenTask::stepAligning(const double dt) {
void TouchScreenTask::logApproachPoseSample(const char* stage,
const Eigen::Matrix4d& T_B_P,
const Eigen::Matrix4d& T_B_G,
const Clock::time_point fk_started_at,
const Clock::time_point fk_finished_at) const {
const auto monotonic_ns = [](Clock::time_point time) {
return std::chrono::duration_cast<std::chrono::nanoseconds>(time.time_since_epoch()).count();
};
const auto& frame = external_perception_->frame();
const auto& timing = frame.rgb_timing;
const auto& tags = config_.perception().tags();
const auto* screen_tag = external_perception_->findTag(tags.screen().id());
const auto* hand_tag = external_perception_->findTag(tags.hand().id());
const Eigen::Matrix4d target_B = T_B_G * pbvs_.targetPose();
const Eigen::IOFormat matrix_format(9, Eigen::DontAlignCols, ",", ",", "[", "]", "[", "]");
const Eigen::IOFormat vector_format(9, Eigen::DontAlignCols, ",", ",", "", "", "[", "]");
CMVR_LOG(INFO) << "[TouchScreenTask][APPROACH_POSE][" << stage << "] id=" << id_
<< ", u=" << target_u_ << ", v=" << target_v_
<< ", camera=" << config_.devices().external_camera_id()
<< ", perception_frame_id=" << frame.frame_id
<< ", rgb_frame_number=" << timing.frame_number
<< ", rgb_source_timestamp_ms=" << std::fixed << std::setprecision(3)
<< timing.source_timestamp_ms << std::defaultfloat
<< ", rgb_timestamp_domain=" << (timing.timestamp_domain ? timing.timestamp_domain : "unavailable")
<< ", rgb_buffered=" << timing.buffered
<< ", rgb_host_received_mono_ns=" << monotonic_ns(timing.host_received_at)
<< ", rgb_read_complete_mono_ns=" << monotonic_ns(timing.host_read_complete_at)
<< ", fk_start_mono_ns=" << monotonic_ns(fk_started_at)
<< ", fk_end_mono_ns=" << monotonic_ns(fk_finished_at)
<< ", screen_tag_id=" << tags.screen().id()
<< ", screen_tag_margin=" << (screen_tag ? screen_tag->margin : 0.0)
<< ", hand_tag_id=" << tags.hand().id()
<< ", hand_tag_margin=" << (hand_tag ? hand_tag->margin : 0.0)
<< ", T_C_G=" << tcp_pose_tracker_.T_C_G().topRows<3>().format(matrix_format)
<< ", T_C_H=" << tcp_pose_tracker_.T_C_H().topRows<3>().format(matrix_format)
<< ", T_H_P=" << T_H_P_.topRows<3>().format(matrix_format)
<< ", T_G_P=" << tcp_pose_tracker_.T_G_P().topRows<3>().format(matrix_format)
<< ", T_B_P=" << T_B_P.topRows<3>().format(matrix_format)
<< ", T_B_G=" << T_B_G.topRows<3>().format(matrix_format)
<< ", target_G_m=" << pbvs_.targetPose().block<3, 1>(0, 3).transpose().format(vector_format)
<< ", target_B_m=" << target_B.block<3, 1>(0, 3).transpose().format(vector_format);
}
bool TouchScreenTask::stepAligning(const double nominal_dt) {
const double elapsed =
std::chrono::duration<double>(Clock::now() - phase_start_time_).count();
if (elapsed > config_.alignment().timeout_s()) {
@ -1238,14 +1142,21 @@ bool TouchScreenTask::stepAligning(const double dt) {
if (!updatePbvsTarget(p_target_G, T_G_P)) {
return false;
}
// Camera acquisition can take longer than the TaskManager step period.
const auto update_time = Clock::now();
const double elapsed_since_update = last_pbvs_update_time_
? std::chrono::duration<double>(update_time - *last_pbvs_update_time_).count()
: nominal_dt;
const double pbvs_dt = std::clamp(elapsed_since_update, 0.0001, 0.05);
PbvsController::Output output;
if (!pbvs_.compute(T_G_P, std::clamp(dt, 0.0001, 0.05), output)) {
if (!pbvs_.compute(T_G_P, pbvs_dt, output)) {
enterFailed(Status::ALIGN_COMPUTE_FAILED);
return false;
}
last_pbvs_update_time_ = update_time;
device::CartesianVelocity twist_B;
if (!mapAlignmentCommandToBase(T_G_P, output, twist_B)) {
if (!mapAlignmentCommandToBase(T_G_P, output, pbvs_dt, twist_B)) {
return false;
}
return applyAlignmentCommand(output, twist_B);
@ -1336,8 +1247,8 @@ bool TouchScreenTask::updateAlignmentTcpPose() {
external_options.depth_policy = perception::AprilTagPerception::DepthPolicy::NONE;
external_options.detect_tags = true;
external_options.fetch_encoded = false;
external_options.capture_rgb_timing = config_.approach().enable() && !have_last_T_B_G_;
const bool perception_ok = external_perception_->update(external_options);
publishCoordinateOverlay();
if (!perception_ok) {
stopPbvsMotion();
align_stable_count_ = 0;
@ -1433,7 +1344,7 @@ bool TouchScreenTask::updatePbvsTarget(const Eigen::Vector3d& p_target_G,
const bool refresh_target = !pbvs_target_initialized_ || tracker_.lastSwitched();
if (refresh_target) {
if (tracker_.lastSwitched()) {
pbvs_.resetTwistCommandState();
resetPbvsCommandState();
}
if (!pbvs_.setTargetPose(p_target_G + position_offset_G, R_target)) {
enterFailed(Status::ALIGN_TARGET_SETUP_FAILED);
@ -1447,14 +1358,17 @@ bool TouchScreenTask::updatePbvsTarget(const Eigen::Vector3d& p_target_G,
bool TouchScreenTask::mapAlignmentCommandToBase(const Eigen::Matrix4d& T_G_P,
const PbvsController::Output& output,
const double pbvs_dt,
device::CartesianVelocity& twist_B) {
Eigen::Matrix4d T_B_P = Eigen::Matrix4d::Identity();
const auto fk_started_at = Clock::now();
try {
T_B_P = cmvr::common::math::poseToMatrix(arm_->fk(true));
} catch (...) {
enterFailed(Status::ROBOT_STATE_FAILED);
return false;
}
const auto fk_finished_at = Clock::now();
if (!isHomogeneousTransform(T_B_P)) {
enterFailed(Status::ROBOT_STATE_FAILED);
return false;
@ -1479,6 +1393,8 @@ bool TouchScreenTask::mapAlignmentCommandToBase(const Eigen::Matrix4d& T_G_P,
std::max(max_T_B_G_translation_delta_m_, T_B_G_delta_translation_m);
max_T_B_G_rotation_delta_rad_ =
std::max(max_T_B_G_rotation_delta_rad_, T_B_G_delta_rotation_rad);
} else if (config_.approach().enable()) {
logApproachPoseSample("AFTER_MOVE_P", T_B_P, T_B_G, fk_started_at, fk_finished_at);
}
last_T_B_G_ = T_B_G;
have_last_T_B_G_ = true;
@ -1511,6 +1427,7 @@ bool TouchScreenTask::mapAlignmentCommandToBase(const Eigen::Matrix4d& T_G_P,
: 0.0;
CMVR_LOG(DEBUG) << "[PBVS_DEBUG]"
<< " dt_s=" << pbvs_dt
<< " target_G_mm=["
<< p_target_used_G.x() * kMetersToMillimeters << ' '
<< p_target_used_G.y() * kMetersToMillimeters << ' '
@ -1586,7 +1503,6 @@ bool TouchScreenTask::applyAlignmentCommand(const PbvsController::Output& output
<< output.rotation_error_G.z() << "]";
stopPbvsMotion();
phase_ = Phase::ALIGN_REACHED;
setCoordinateOverlayEnabled(true);
phase_start_time_ = Clock::now();
touch_command_started_ = false;
last_status_ = Status::ALIGN_REACHED;
@ -1842,6 +1758,11 @@ bool TouchScreenTask::stepRetracting() {
return phase_ != Phase::FAILED;
}
void TouchScreenTask::resetPbvsCommandState() {
pbvs_.resetTwistCommandState();
last_pbvs_update_time_.reset();
}
void TouchScreenTask::stopPbvsMotion() {
if (arm_) {
try {
@ -1849,7 +1770,7 @@ void TouchScreenTask::stopPbvsMotion() {
} catch (...) {
}
}
pbvs_.resetTwistCommandState();
resetPbvsCommandState();
}
bool TouchScreenTask::readCurrentTouchPointPositionBase(Eigen::Vector3d& p_out) const {
@ -1935,10 +1856,30 @@ bool TouchScreenTask::initializeHead(const std::shared_ptr<device::RobotArm>& he
command.position.push_back(it->second);
targets.erase(it);
}
if (!head->isConnected() || head->isEmergencyStopped() ||
head->isProtectiveStopped() || head->isFault() || head->busy()) {
const auto read_ready_state = [&](device::ArmState& state) {
if (!head->isConnected() || head->isEmergencyStopped() ||
head->isProtectiveStopped() || head->isFault() || head->busy()) {
return false;
}
state = head->getRobotState();
return state.connected && !state.emergency_stopped && !state.protective_stopped &&
!state.fault && !state.moving;
};
device::ArmState state;
if (!read_ready_state(state)) {
return fail(Status::ROBOT_COMMAND_FAILED, "head is disconnected, stopped, faulted or busy");
}
if (!state.powered_on) {
CMVR_LOG(INFO) << "[TouchScreenTask][HEAD_INIT] torqueOn start, head="
<< config_.devices().head_id();
const auto enabled = head->torqueOn();
if (!enabled.ok()) {
return fail(Status::ROBOT_COMMAND_FAILED, "torqueOn failed: " + enabled.message);
}
if (!read_ready_state(state) || !state.powered_on) {
return fail(Status::ROBOT_COMMAND_FAILED, "head did not report ready and enabled after torqueOn");
}
}
device::MotionOptions options;
options.velocity = head_init.velocity();
@ -1953,7 +1894,7 @@ bool TouchScreenTask::initializeHead(const std::shared_ptr<device::RobotArm>& he
} catch (const std::exception& error) {
return fail(Status::ROBOT_COMMAND_FAILED, error.what());
} catch (...) {
return fail(Status::ROBOT_COMMAND_FAILED, "unknown moveJ initialization error");
return fail(Status::ROBOT_COMMAND_FAILED, "unknown head initialization error");
}
}
@ -2177,13 +2118,12 @@ bool TouchScreenTask::startRetractPhase(const Phase next_phase_after_retract,
void TouchScreenTask::enterFailed(const Status status) {
cancelApproach();
pbvs_.resetTwistCommandState();
resetPbvsCommandState();
if (phase_ == Phase::RETRACTING && retract_start_position_valid_) {
CMVR_LOG(WARNING) << "[TouchScreenTask][RETRACT_FAILED] status=" << statusToString(status)
<< ", max_forward_after_retract_mm=" << max_forward_after_retract_m_ * 1000.0;
}
phase_ = Phase::FAILED;
setCoordinateOverlayEnabled(true);
touch_command_started_ = false;
retract_command_started_ = false;
last_status_ = status;

View File

@ -37,6 +37,8 @@
#include "devices/camera/mujoco_camera/include/mujoco_camera.h"
#include "devices/motor/manager/include/motor_manager.h"
#include "manager/device_manager/include/device_manager.h"
#include "manager/media_source_hub/include/camera_coordinate_overlay.h"
#include "manager/media_source_hub/include/device_media_source_adapter.h"
#include "manager/task_manager/include/task_manager.h"
#include "service/grpc/include/grpc_dexhand_service.h"
#include "service/grpc/include/grpc_system_service.h"
@ -161,6 +163,19 @@ cmvr::config::TouchScreenTaskConfig loadMujocoTouchConfig(const std::filesystem:
return root_config.touch_screen_task();
}
cv::Mat makeAlignmentTagFrame()
{
cv::Mat frame(480, 640, CV_8UC3, cv::Scalar::all(255));
const auto tag_directory = findProjectRoot() / "model/april_tag";
for (const auto& [file, x] : {std::pair{"tag36_11_00001.png", 100}, {"tag36_11.png", 380}}) {
const cv::Mat tag = cv::imread((tag_directory / file).string());
if (tag.empty()) return {};
const cv::Rect roi(x, 160, 160, 160);
cv::resize(tag, frame(roi), roi.size(), 0, 0, cv::INTER_NEAREST);
}
return frame;
}
class FailureReturnCamera final : public cmvr::device::AbstractCamera {
public:
std::string typeName() const override { return "FailureReturnCamera"; }
@ -172,6 +187,60 @@ public:
cv::Mat frame;
};
class OverlayCamera final : public cmvr::device::AbstractCamera {
public:
explicit OverlayCamera(cv::Mat frame)
: frame_(std::move(frame)), blank_frame_(frame_.size(), frame_.type(), cv::Scalar::all(255)) {
id_ = "overlay_camera";
}
std::string typeName() const override { return "OverlayCamera"; }
bool startStreaming() override {
++stream_starts;
return true;
}
void stopStreaming() override { ++stream_stops; }
void getState(cmvr::device::CameraState& state) override {
state = {};
state.is_initialized = true;
state.is_opened = true;
}
void getRGBImage(cv::Mat& color, cmvr::device::Rs2Intrinsics& intrinsics) override {
color = frame_;
intrinsics = {320, 240, 600, 600};
++rgb_reads;
}
bool waitEncodedFrame(cmvr::device::StreamFrameData& frame, size_t& cursor,
std::chrono::milliseconds timeout) override {
std::this_thread::sleep_for(std::min(timeout, std::chrono::milliseconds(10)));
const auto epoch = stream_starts.load();
if (epoch == stream_stops.load()) return false;
frame = {};
frame.rgbImage = show_tags.load() ? frame_ : blank_frame_;
frame.rgbFrame = {0x00, 0x00, 0x00, 0x01, 0x65, 0x88};
frame.intrinsics = {320, 240, 600, 600};
frame.width = frame_.cols;
frame.height = frame_.rows;
frame.fps = 30;
frame.bKey = true;
frame.stream_epoch = epoch;
frame.sequence = cursor++;
frame.time_base_den = frame.fps;
frame.capture_monotonic_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
return true;
}
std::atomic<bool> show_tags{true};
std::atomic<std::uint64_t> stream_starts{0};
std::atomic<std::uint64_t> stream_stops{0};
std::atomic<int> rgb_reads{0};
private:
const cv::Mat frame_;
const cv::Mat blank_frame_;
};
class ScriptedTouch final : public cmvr::device::AbstractTouch {
public:
std::string typeName() const override { return "ScriptedTouch"; }
@ -206,7 +275,17 @@ public:
std::string typeName() const override { return "FailureReturnArm"; }
cmvr::RobotModel getRobotModel() const override { return model; }
std::size_t getDof() const override { return model.dof; }
cmvr::device::ArmState getRobotState() const override { return {}; }
cmvr::device::ArmState getRobotState() const override {
cmvr::device::ArmState snapshot;
snapshot.connected = connected;
snapshot.powered_on = powered_on;
snapshot.moving = motion_busy;
snapshot.fault = planning_fault;
snapshot.emergency_stopped = emergency;
snapshot.protective_stopped = protective;
snapshot.safety_mode = getSafetyMode();
return snapshot;
}
cmvr::device::JointGroupState getJointState() const override { return state; }
cmvr::device::CartesianPose getTcpPose(cmvr::device::FrameType) const override { return {}; }
cmvr::device::RobotMode getRobotMode() const override { return cmvr::device::RobotMode::Idle; }
@ -231,6 +310,9 @@ public:
calls.push_back("stopMotion");
return stop_result;
}
Result getSpeedLResult() const override {
return speed_l_result.value_or(RobotArm::getSpeedLResult());
}
Result recoverSpeedLPlanningFault() override {
calls.push_back("recoverSpeedLPlanningFault");
if (recovery_result.ok()) planning_fault = false;
@ -252,9 +334,18 @@ public:
return move_result;
}
Result torqueOn() override { return unsupported(); }
Result torqueOn() override {
if (!torque_on_result) return unsupported();
calls.push_back("torqueOn");
if (torque_on_throws) throw std::runtime_error("injected torqueOn exception");
if (torque_on_result->ok() && confirm_torque_on) powered_on = true;
return *torque_on_result;
}
Result moveP(const cmvr::device::CartesianPose&, const cmvr::device::MotionOptions&,
cmvr::device::FrameType) override { return unsupported(); }
cmvr::device::FrameType) override {
if (allow_cartesian_move_p) return Result::success();
return unsupported();
}
Result torqueOff() override { return unsupported(); }
Result calibrateZeroQ(const std::string&) override { return unsupported(); }
Result emergencyStop() override { return unsupported(); }
@ -269,8 +360,12 @@ public:
calls.push_back("moveL");
return Result::success();
}
Result speedL(const cmvr::device::CartesianVelocity&, double, double,
cmvr::device::FrameType) override { return unsupported(); }
Result speedL(const cmvr::device::CartesianVelocity& velocity, double, double,
cmvr::device::FrameType) override {
if (!speed_l_commands) return unsupported();
speed_l_commands->push_back(velocity);
return Result::success();
}
Result startServoMode(const cmvr::device::ServoOptions&) override { return unsupported(); }
Result servoJ(const cmvr::device::JointPositionCommand&) override { return unsupported(); }
Result servoL(const cmvr::device::CartesianPose&, cmvr::device::FrameType) override { return unsupported(); }
@ -283,7 +378,15 @@ public:
Result powerOff() override { return unsupported(); }
Result brakeRelease() override { return unsupported(); }
Result shutdown() override { return unsupported(); }
Result clearFault() override { return unsupported(); }
Result clearFault() override {
calls.push_back("clearFault");
if (!clear_fault_result) return unsupported();
if (clear_fault_result->ok()) {
planning_fault = false;
speed_l_result = Result::success();
}
return *clear_fault_result;
}
Result unlockProtectiveStop() override { return unsupported(); }
Result loadProgram(const std::string&) override { return unsupported(); }
Result playProgram() override { return unsupported(); }
@ -301,13 +404,21 @@ public:
Result stop_result{Result::success()};
Result move_result{Result::success()};
Result recovery_result{Result::success()};
std::optional<Result> speed_l_result;
std::optional<Result> clear_fault_result;
std::optional<Result> torque_on_result;
bool planning_fault{false};
bool connected{true};
bool powered_on{false};
bool confirm_torque_on{true};
bool emergency{false};
bool protective{false};
bool motion_busy{false};
bool allow_cartesian_move_p{false};
bool move_j_throws{false};
bool torque_on_throws{false};
int stop_l_calls{0};
std::optional<std::vector<cmvr::device::CartesianVelocity>> speed_l_commands;
std::vector<std::string> calls;
std::vector<double> return_target;
cmvr::device::MotionOptions return_options;
@ -351,6 +462,27 @@ protected:
EXPECT_EQ(arm->calls, calls) << "failure return must run only once";
}
bool configureSuccessfulTouch() {
auto* alignment = config.mutable_alignment();
alignment->set_stable_frames(1);
alignment->set_timeout_s(10);
alignment->set_pause_when_reached(false);
alignment->mutable_target()->set_mode(cmvr::config::TOUCH_SCREEN_ALIGN_MODE_POSITION_ONLY);
auto* threshold = alignment->mutable_error_threshold();
threshold->set_x(1.0);
threshold->set_y(1.0);
threshold->set_z(1.0);
auto* touch_move = config.mutable_touch()->mutable_move_l();
if (!google::protobuf::TextFormat::ParseFromString(R"(
direction_tool { x: 1 y: 0 z: 0 rx: 0 ry: 0 rz: 0 }
distance_m: 0.01 velocity: 0.1 acceleration: 0.1 jerk: 1
)", touch_move)) {
return false;
}
for (std::size_t i = 0; i < arm->getDof(); ++i) touch_move->add_joint_velocity_limits(1.0);
return true;
}
cmvr::config::TouchScreenTaskConfig config;
std::shared_ptr<FailureReturnArm> arm;
};
@ -380,6 +512,7 @@ protected:
arm = std::make_shared<FailureReturnArm>(config);
head = std::make_shared<FailureReturnArm>(config);
head->torque_on_result = cmvr::device::Result::success();
head->model.joint_names = {"neck-joint1", "neck-joint2"};
head->model.dof = 2;
head->state.position = {0.0, 0.0};
@ -641,29 +774,10 @@ TEST_F(TouchScreenFailureReturnTest, SelectedMethodAppliesBeforeStartAndAfterFai
TEST_F(TouchScreenFailureReturnTest, SelectedMethodAppliesAfterFinishWhenEnabled) {
using Init = cmvr::config::TouchScreenTaskInitializationConfig;
const auto camera = std::make_shared<FailureReturnCamera>();
camera->frame = cv::Mat(480, 640, CV_8UC3, cv::Scalar::all(255));
const auto tag_directory = findProjectRoot() / "model/april_tag";
for (const auto& [file, x] : {std::pair{"tag36_11_00001.png", 100}, {"tag36_11.png", 380}}) {
const cv::Mat tag = cv::imread((tag_directory / file).string());
ASSERT_FALSE(tag.empty()) << file;
const cv::Rect roi(x, 160, 160, 160);
cv::resize(tag, camera->frame(roi), roi.size(), 0, 0, cv::INTER_NEAREST);
}
camera->frame = makeAlignmentTagFrame();
ASSERT_FALSE(camera->frame.empty());
config.set_debug_draw_coordinate_frames(false);
auto* alignment = config.mutable_alignment();
alignment->set_stable_frames(1);
alignment->set_timeout_s(10);
alignment->mutable_target()->set_mode(cmvr::config::TOUCH_SCREEN_ALIGN_MODE_POSITION_ONLY);
auto* threshold = alignment->mutable_error_threshold();
threshold->set_x(1.0);
threshold->set_y(1.0);
threshold->set_z(1.0);
auto* touch_move = config.mutable_touch()->mutable_move_l();
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
direction_tool { x: 1 y: 0 z: 0 rx: 0 ry: 0 rz: 0 }
distance_m: 0.01 velocity: 0.1 acceleration: 0.1 jerk: 1
)", touch_move));
for (std::size_t i = 0; i < arm->getDof(); ++i) touch_move->add_joint_velocity_limits(1.0);
ASSERT_TRUE(configureSuccessfulTouch());
// Click the screen tag. Relaxed alignment tolerances let the two fixed
// tag images drive a successful touch without simulating arm motion.
@ -695,6 +809,122 @@ TEST_F(TouchScreenFailureReturnTest, SelectedMethodAppliesAfterFinishWhenEnabled
}
}
TEST_F(TouchScreenFailureReturnTest, PbvsUsesElapsedUpdateTimeAndResetsAfterTrackingLoss) {
const auto frame = makeAlignmentTagFrame();
ASSERT_FALSE(frame.empty());
const auto camera = std::make_shared<FailureReturnCamera>();
camera->frame = frame;
config.set_debug_draw_coordinate_frames(false);
auto* alignment = config.mutable_alignment();
alignment->set_timeout_s(10.0);
alignment->mutable_target()->set_mode(cmvr::config::TOUCH_SCREEN_ALIGN_MODE_POSITION_ONLY);
alignment->mutable_error_threshold()->set_x(0.001);
alignment->mutable_error_threshold()->set_y(1.0);
alignment->mutable_error_threshold()->set_z(1.0);
alignment->mutable_pbvs()->mutable_amax6()->set_x(0.1);
auto& commands = arm->speed_l_commands.emplace();
const auto linear_speed = [](const cmvr::device::CartesianVelocity& command) {
return std::hypot(command.vx, command.vy, command.vz);
};
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera));
ASSERT_TRUE(task.touch(180, 240));
constexpr double nominal_dt = 0.001;
ASSERT_TRUE(task.step(nominal_dt));
ASSERT_EQ(commands.size(), 1u);
EXPECT_NEAR(linear_speed(commands[0]), 0.0001, 1e-8);
std::this_thread::sleep_for(std::chrono::milliseconds(30));
ASSERT_TRUE(task.step(nominal_dt));
ASSERT_EQ(commands.size(), 2u);
const double speed_change = linear_speed(commands[1]) - linear_speed(commands[0]);
EXPECT_GE(speed_change, 0.0025);
EXPECT_LE(speed_change, 0.005 + 1e-8);
camera->frame.release();
const auto stops_before_loss = arm->stop_l_calls;
ASSERT_TRUE(task.step(nominal_dt));
EXPECT_EQ(arm->stop_l_calls, stops_before_loss + 1);
EXPECT_EQ(commands.size(), 2u);
camera->frame = frame;
ASSERT_TRUE(task.step(nominal_dt));
ASSERT_EQ(commands.size(), 3u);
EXPECT_NEAR(linear_speed(commands[2]), 0.0001, 1e-8);
}
TEST_F(TouchScreenFailureReturnTest, LogsApproachPoseOnceBeforeAndAfterMoveP) {
const auto camera = std::make_shared<FailureReturnCamera>();
camera->frame = makeAlignmentTagFrame();
ASSERT_FALSE(camera->frame.empty());
config.set_debug_draw_coordinate_frames(false);
config.mutable_approach()->set_enable(true);
auto* alignment = config.mutable_alignment();
alignment->set_timeout_s(10.0);
alignment->mutable_target()->set_mode(cmvr::config::TOUCH_SCREEN_ALIGN_MODE_POSITION_ONLY);
// Both synthetic tags lie at the same depth. Place the fake TCP in front
// of the screen plane so the approach start passes the clearance check.
alignment->mutable_calibration()->mutable_hand_tag_to_tcp()->set_m23(0.08);
arm->allow_cartesian_move_p = true;
auto& commands = arm->speed_l_commands.emplace();
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera));
using Phase = cmvr::task::TouchScreenTask::Phase;
constexpr double nominal_dt = 0.001;
::testing::internal::CaptureStdout();
[&] {
ASSERT_TRUE(task.touch(180, 240));
ASSERT_TRUE(task.step(nominal_dt));
ASSERT_EQ(task.phase(), Phase::APPROACHING);
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(1);
while (task.phase() == Phase::APPROACHING &&
std::chrono::steady_clock::now() < deadline) {
ASSERT_TRUE(task.step(nominal_dt));
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ASSERT_EQ(task.phase(), Phase::ALIGNING);
ASSERT_TRUE(task.step(nominal_dt));
ASSERT_TRUE(task.step(nominal_dt));
ASSERT_EQ(commands.size(), 2u);
}();
const auto logs = ::testing::internal::GetCapturedStdout();
if (HasFatalFailure()) return;
constexpr char before_marker[] = "[APPROACH_POSE][BEFORE_MOVE_P]";
constexpr char after_marker[] = "[APPROACH_POSE][AFTER_MOVE_P]";
const auto before = logs.find(before_marker);
const auto after = logs.find(after_marker);
ASSERT_NE(before, std::string::npos) << logs;
ASSERT_NE(after, std::string::npos) << logs;
EXPECT_LT(before, after);
EXPECT_EQ(logs.find(before_marker, before + 1), std::string::npos);
EXPECT_EQ(logs.find(after_marker, after + 1), std::string::npos);
const auto before_line = logs.substr(before, logs.find('\n', before) - before);
const auto after_line = logs.substr(after, logs.find('\n', after) - after);
const auto field = [](const std::string& line, const std::string& name) {
const auto start = line.find(name + "=");
if (start == std::string::npos) return std::string{};
const auto value = start + name.size() + 1;
return line.substr(value, line.find(", ", value) - value);
};
for (const auto* line : {&before_line, &after_line}) {
EXPECT_EQ(field(*line, "rgb_timestamp_domain"), "unavailable");
EXPECT_EQ(field(*line, "rgb_frame_number"), "0");
const auto read_time = field(*line, "rgb_read_complete_mono_ns");
ASSERT_FALSE(read_time.empty());
EXPECT_GT(std::stoll(read_time), 0);
}
const auto target = field(before_line, "target_G_m");
ASSERT_FALSE(target.empty());
EXPECT_EQ(field(after_line, "target_G_m"), target);
}
TEST_F(TouchScreenFailureReturnTest, RejectsUnknownInitializationMotionMethod) {
using Init = cmvr::config::TouchScreenTaskInitializationConfig;
config.mutable_initialization()->set_motion_method(static_cast<Init::MotionMethod>(99));
@ -800,10 +1030,29 @@ TEST_F(TouchScreenFailureReturnTest, DisabledInitializationStillRecoversBeforeSt
EXPECT_TRUE(task.isBusy());
}
TEST_F(TouchScreenFailureReturnTest, NextRunClearsSpeedLFaultBeforeInitialization) {
config.mutable_initialization()->set_before_start(true);
cmvr::task::TouchScreenTask task(config);
const auto camera = std::make_shared<FailureReturnCamera>();
ASSERT_TRUE(task.init(arm, nullptr, camera, camera));
arm->planning_fault = true;
arm->speed_l_result = cmvr::device::Result::failure(
cmvr::device::ArmErrorCode::InvalidArgument,
"S-curve limits exclude the remaining direction transition");
arm->clear_fault_result = cmvr::device::Result::success();
ASSERT_TRUE(task.touch(320, 240));
EXPECT_EQ(arm->calls, (std::vector<std::string>{
"stopMotion", "clearFault", "recoverSpeedLPlanningFault", "moveJ"}));
EXPECT_FALSE(arm->isFault());
EXPECT_TRUE(task.isBusy());
}
TEST_F(TouchScreenFailureReturnTest, RejectedRestartPreservesPreviousFailureAndDoesNotMove) {
config.mutable_initialization()->set_before_start(true);
config.mutable_initialization()->set_after_failure(false);
for (const auto* reason : {"failed_stop", "fatal_fault", "emergency", "protective", "disconnected"}) {
for (const auto* reason : {"failed_stop", "failed_clear", "fatal_fault", "emergency",
"protective", "disconnected"}) {
SCOPED_TRACE(reason);
arm = std::make_shared<FailureReturnArm>(config);
cmvr::task::TouchScreenTask task(config);
@ -826,6 +1075,14 @@ TEST_F(TouchScreenFailureReturnTest, RejectedRestartPreservesPreviousFailureAndD
if (failure == "fatal_fault") {
arm->recovery_result = cmvr::device::Result::failure(
cmvr::device::ArmErrorCode::CommandFailed, "injected nonrecoverable fault");
} else {
arm->speed_l_result = cmvr::device::Result::failure(
cmvr::device::ArmErrorCode::InvalidArgument,
"S-curve limits exclude the remaining direction transition");
}
if (failure == "failed_clear") {
arm->clear_fault_result = cmvr::device::Result::failure(
cmvr::device::ArmErrorCode::Timeout, "speedL measured stop was not confirmed");
}
EXPECT_FALSE(task.touch(350, 260));
@ -836,6 +1093,8 @@ TEST_F(TouchScreenFailureReturnTest, RejectedRestartPreservesPreviousFailureAndD
if (failure == "fatal_fault") {
EXPECT_EQ(arm->calls, (std::vector<std::string>{
"stopMotion", "recoverSpeedLPlanningFault"}));
} else if (failure == "failed_clear") {
EXPECT_EQ(arm->calls, (std::vector<std::string>{"stopMotion", "clearFault"}));
} else if (failure == "failed_stop") {
EXPECT_EQ(arm->calls, std::vector<std::string>{"stopMotion"});
} else {
@ -885,12 +1144,13 @@ TEST_F(TouchScreenHeadInitializationTest, AbsentOrDisabledConfigurationDoesNotCo
}
}
TEST_F(TouchScreenHeadInitializationTest, MovesOnlyHeadOnceInModelJointOrderWithConfiguredLimits) {
TEST_F(TouchScreenHeadInitializationTest, EnablesAndMovesOnlyHeadOnceInModelJointOrderWithConfiguredLimits) {
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::IDLE);
EXPECT_EQ(task.phase(), cmvr::task::TouchScreenTask::Phase::IDLE);
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_EQ(head->calls, (std::vector<std::string>{"torqueOn", "moveJ"}));
EXPECT_TRUE(head->powered_on);
EXPECT_EQ(head->startup_target, (std::vector<double>{-0.2, 0.15}));
EXPECT_DOUBLE_EQ(head->startup_options.velocity, 0.25);
EXPECT_DOUBLE_EQ(head->startup_options.acceleration, 0.5);
@ -899,13 +1159,21 @@ TEST_F(TouchScreenHeadInitializationTest, MovesOnlyHeadOnceInModelJointOrderWith
EXPECT_EQ(arm->stop_l_calls, 0);
}
TEST_F(TouchScreenHeadInitializationTest, AlreadyEnabledHeadMovesWithoutRepeatEnable) {
head->powered_on = true;
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_TRUE(arm->calls.empty());
}
TEST_F(TouchScreenHeadInitializationTest, RepeatedTouchRequestsDoNotRepeatHeadInitialization) {
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera, head));
ASSERT_TRUE(task.touch(320, 240));
task.stop();
ASSERT_TRUE(task.touch(350, 260));
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_EQ(head->calls, (std::vector<std::string>{"torqueOn", "moveJ"}));
EXPECT_EQ(head->stop_l_calls, 0);
EXPECT_EQ(arm->calls, (std::vector<std::string>{
"stopMotion", "recoverSpeedLPlanningFault",
@ -1021,10 +1289,40 @@ TEST_F(TouchScreenHeadInitializationTest, UnavailableHeadFailsWithoutRecoveryOrM
}
}
TEST_F(TouchScreenHeadInitializationTest, FailedOrThrowingHeadEnablePreventsMotionAndTaskInitialization) {
for (const bool throws : {false, true}) {
SCOPED_TRACE(throws);
head->calls.clear();
head->torque_on_throws = throws;
head->torque_on_result = cmvr::device::Result::failure(
cmvr::device::ArmErrorCode::CommandFailed, "injected head enable failure");
cmvr::task::TouchScreenTask task(config);
EXPECT_FALSE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ROBOT_COMMAND_FAILED);
EXPECT_EQ(task.phase(), cmvr::task::TouchScreenTask::Phase::FAILED);
EXPECT_EQ(head->calls, std::vector<std::string>{"torqueOn"});
EXPECT_TRUE(arm->calls.empty());
EXPECT_FALSE(task.touch(320, 240));
EXPECT_EQ(head->calls, std::vector<std::string>{"torqueOn"});
EXPECT_TRUE(arm->calls.empty());
}
}
TEST_F(TouchScreenHeadInitializationTest, UnconfirmedHeadEnablePreventsMotionAndTaskInitialization) {
head->confirm_torque_on = false;
cmvr::task::TouchScreenTask task(config);
EXPECT_FALSE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ROBOT_COMMAND_FAILED);
EXPECT_EQ(task.phase(), cmvr::task::TouchScreenTask::Phase::FAILED);
EXPECT_EQ(head->calls, std::vector<std::string>{"torqueOn"});
EXPECT_TRUE(arm->calls.empty());
}
TEST_F(TouchScreenHeadInitializationTest, FailedOrThrowingHeadMovePreventsTaskInitialization) {
for (const bool throws : {false, true}) {
SCOPED_TRACE(throws);
head->calls.clear();
head->powered_on = false;
head->move_j_throws = throws;
head->move_result = cmvr::device::Result::failure(
cmvr::device::ArmErrorCode::CommandFailed, "injected head move failure");
@ -1032,12 +1330,12 @@ TEST_F(TouchScreenHeadInitializationTest, FailedOrThrowingHeadMovePreventsTaskIn
EXPECT_FALSE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ROBOT_COMMAND_FAILED);
EXPECT_EQ(task.phase(), cmvr::task::TouchScreenTask::Phase::FAILED);
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_EQ(head->calls, (std::vector<std::string>{"torqueOn", "moveJ"}));
EXPECT_EQ(head->stop_l_calls, 0);
EXPECT_TRUE(arm->calls.empty());
EXPECT_EQ(arm->stop_l_calls, 0);
EXPECT_FALSE(task.touch(320, 240));
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_EQ(head->calls, (std::vector<std::string>{"torqueOn", "moveJ"}));
EXPECT_TRUE(arm->calls.empty());
}
}
@ -1132,6 +1430,114 @@ TEST(TouchScreenTaskTest, ConfigFilesUseStructuredSchema) {
}
}
TEST(TouchScreenTaskTest, EstimatesPoseForDifferentTagSizes) {
const auto project_root = findProjectRoot();
auto config = loadMujocoTouchConfig(project_root);
config.set_debug_draw_coordinate_frames(false);
auto* tags = config.mutable_perception()->mutable_tags();
tags->mutable_screen()->set_id(1);
tags->mutable_screen()->set_size_m(0.030);
tags->mutable_hand()->set_id(2);
tags->mutable_hand()->set_size_m(0.025);
const auto tag_dir = project_root / "model/april_tag";
const auto screen = cv::imread((tag_dir / "tag36_11_00001.png").string(), cv::IMREAD_GRAYSCALE);
const auto hand = cv::imread((tag_dir / "tag36_11_00002_1000.png").string(), cv::IMREAD_GRAYSCALE);
ASSERT_FALSE(screen.empty());
ASSERT_FALSE(hand.empty());
const auto camera = std::make_shared<FailureReturnCamera>();
camera->frame = cv::Mat(480, 640, CV_8UC1, cv::Scalar(255));
// The black borders span 80% of the images. At 96 px and 80 px,
// both tags should be 187.5 mm from the camera with a 600 px focal length.
cv::resize(screen, camera->frame(cv::Rect(140, 180, 120, 120)),
cv::Size(120, 120), 0, 0, cv::INTER_NEAREST);
cv::resize(hand, camera->frame(cv::Rect(380, 190, 100, 100)),
cv::Size(100, 100), 0, 0, cv::INTER_NEAREST);
cmvr::task::TouchScreenTask task(config);
const auto arm = std::make_shared<FailureReturnArm>(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera));
for (const auto& perception : {task.perception(), task.externalPerception()}) {
ASSERT_TRUE(perception->update({}));
const auto* screen_tag = perception->findTag(tags->screen().id());
const auto* hand_tag = perception->findTag(tags->hand().id());
ASSERT_NE(screen_tag, nullptr);
ASSERT_NE(hand_tag, nullptr);
EXPECT_NEAR(screen_tag->T_c_t(2, 3), 0.1875, 0.003);
EXPECT_NEAR(hand_tag->T_c_t(2, 3), 0.1875, 0.003);
}
}
TEST_F(TouchScreenFailureReturnTest, CoordinateOverlayFollowsVideoSubscriptions) {
const auto frame = makeAlignmentTagFrame();
ASSERT_FALSE(frame.empty());
const auto camera = std::make_shared<OverlayCamera>(frame);
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera));
cmvr::media::MediaSourceHub hub;
cmvr::media::CameraCoordinateOverlayConfig overlay_config;
const auto& tags = config.perception().tags();
overlay_config.screen_tag_id = tags.screen().id();
overlay_config.screen_tag_size_m = tags.screen().size_m();
overlay_config.hand_tag_id = tags.hand().id();
overlay_config.hand_tag_size_m = tags.hand().size_m();
overlay_config.axis_length_m = 0.03;
ASSERT_TRUE(cmvr::media::ensureCameraMediaSource(hub, camera, 64, &overlay_config));
const auto track = cmvr::media::cameraColorTrackId(camera->id());
const auto wait_for = [](const auto& ready) {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
while (!ready() && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
return ready();
};
const auto has_both_tags = [&] {
const auto overlay = camera->streamOverlay();
return overlay.draw_coordinate_frames && overlay.coordinate_frames.size() == 2;
};
EXPECT_EQ(camera->stream_starts.load(), 0);
EXPECT_TRUE(camera->streamOverlay().coordinate_frames.empty());
auto first = hub.subscribe(track);
ASSERT_TRUE(first);
ASSERT_TRUE(first.waitRead(std::chrono::seconds(2)).has_value());
ASSERT_TRUE(wait_for(has_both_tags));
const auto overlay = camera->streamOverlay();
EXPECT_DOUBLE_EQ(overlay.coordinate_axis_length_m, 0.03);
EXPECT_EQ(overlay.coordinate_frames.front().tag_id, tags.screen().id());
EXPECT_EQ(overlay.coordinate_frames.front().label, "G");
EXPECT_EQ(overlay.coordinate_frames.back().tag_id, tags.hand().id());
EXPECT_EQ(overlay.coordinate_frames.back().label, "H");
task.stop();
EXPECT_TRUE(has_both_tags());
auto second = hub.subscribe(track);
ASSERT_TRUE(second);
EXPECT_EQ(camera->stream_starts.load(), 1);
first.reset();
EXPECT_EQ(camera->stream_stops.load(), 0);
ASSERT_TRUE(second.waitRead(std::chrono::seconds(2)).has_value());
camera->show_tags.store(false);
ASSERT_TRUE(wait_for([&] { return camera->streamOverlay().coordinate_frames.empty(); }));
camera->show_tags.store(true);
ASSERT_TRUE(wait_for(has_both_tags));
second.reset();
EXPECT_EQ(camera->stream_stops.load(), 1);
EXPECT_TRUE(camera->streamOverlay().coordinate_frames.empty());
auto after_reconnect = hub.subscribe(track);
ASSERT_TRUE(after_reconnect);
ASSERT_TRUE(wait_for(has_both_tags));
after_reconnect.reset();
EXPECT_EQ(camera->stream_starts.load(), 2);
EXPECT_EQ(camera->stream_stops.load(), 2);
EXPECT_TRUE(camera->streamOverlay().coordinate_frames.empty());
EXPECT_EQ(camera->rgb_reads.load(), 0);
}
TEST(TouchScreenTaskTest, MotorArmConfigurationsSupportMoveP) {
const auto project_root = findProjectRoot();
ASSERT_FALSE(project_root.empty());

BIN
docs/can协议 V2.38.pdf Normal file

Binary file not shown.

Binary file not shown.

View File

@ -111,7 +111,7 @@ Python 分块测试与 C++ collision checker 测试覆盖倒角分层、层间
## 在线任务状态
两套配置分别绑定 `xiaozhao_mujoco_left_arm`、`xiaozhao_mujoco_right_arm`:
左臂配置绑定仿真 `xiaozhao_mujoco_left_arm`,右臂配置绑定实机 `xiaozhao_tchl_right_arm`。
- `cmvr-es/config/tasks/self_collision_task/self_collision_task_xiaozhao_left.pb.txt`
- `cmvr-es/config/tasks/self_collision_task/self_collision_task_xiaozhao_right.pb.txt`

View File

@ -4,6 +4,13 @@ package cmvr.config;
import "cmvr/config/joint_limits_config.proto";
message PoseIKJointLimitAvoidanceConfig {
// Optimize distance from joint limits after the pose IK converges.
bool enable = 1;
optional int32 max_iters = 2; // Defaults to 20.
optional double max_joint_step_rad = 3; // Defaults to 0.02 rad.
}
// 只管 QP 这个 IK 的参数
message PinocchioQpIKConfig {
string urdf_path = 1;
@ -17,4 +24,5 @@ message PinocchioQpIKConfig {
double tol = 8;
double qp_time_limit = 9;
JointLimitPolicyConfig joint_limit_policy = 10;
PoseIKJointLimitAvoidanceConfig pose_ik_joint_limit_avoidance = 11;
}

View File

@ -6,6 +6,9 @@ usage() {
Usage:
sudo scripts/ethercat/stop_ethercat.sh [iface] [--restore-network]
Before unloading the drivers, the script asks cmvr_es processes using an
EtherCAT master to exit. Suspended instances are resumed to finish shutdown.
Examples:
sudo scripts/ethercat/stop_ethercat.sh eno1
sudo scripts/ethercat/stop_ethercat.sh eno1 --restore-network
@ -56,6 +59,43 @@ if [[ ! -x "${ETHERCATCTL}" ]]; then
exit 1
fi
stop_cmvr_clients() {
(( $# > 0 )) || return 0
if ! command -v fuser >/dev/null; then
echo "error: fuser (psmisc) is required to check EtherCAT device usage." >&2
return 1
fi
local pid exe deadline
local -A seen=()
for pid in $(fuser "$@" 2>/dev/null); do
[[ -z "${seen[$pid]:-}" ]] || continue
seen[$pid]=1
exe=$(readlink "/proc/$pid/exe") || continue
case "$exe" in
*/cmvr_es|*/'cmvr_es (deleted)') ;;
*) continue ;;
esac
echo "Requesting shutdown of cmvr_es (PID $pid)..."
if kill -TERM "$pid" && [[ $(ps -o state= -p "$pid") == T ]]; then
kill -CONT "$pid" || true
fi
done
deadline=$((SECONDS + 15))
while fuser -s "$@"; do
if (( SECONDS >= deadline )); then
echo "error: EtherCAT devices are still in use after 15s. Current holders:" >&2
fuser -v "$@" >&2 || true
return 1
fi
sleep 0.2
done
}
shopt -s nullglob
stop_cmvr_clients /dev/EtherCAT[0-9]*
"${ETHERCATCTL}" -c "${ETHERCAT_CONF}" stop
if [[ "${RESTORE_NETWORK}" == "true" ]]; then

View File

@ -0,0 +1,31 @@
[Unit]
Description=CMVR ES (CAN -> EtherCAT enp2s0 -> runtime)
Wants=network-online.target
Requires=sys-subsystem-net-devices-can0.device sys-subsystem-net-devices-can1.device sys-subsystem-net-devices-can2.device sys-subsystem-net-devices-can3.device
After=network-online.target sys-subsystem-net-devices-can0.device sys-subsystem-net-devices-can1.device sys-subsystem-net-devices-can2.device sys-subsystem-net-devices-can3.device itekon-can@can0.service itekon-can@can1.service itekon-can@can2.service itekon-can@can3.service
StartLimitIntervalSec=300
StartLimitBurst=3
[Service]
Type=simple
User=cmvr
Group=cmvr
SupplementaryGroups=plugdev
WorkingDirectory=/home/cmvr/project/cmvr-es/output/bin
Environment=LD_LIBRARY_PATH=/home/cmvr/project/cmvr-es/output/lib
ExecStartPre=+/bin/bash -e /home/cmvr/project/cmvr-es/scripts/start_can.sh
ExecStartPre=+/bin/bash /home/cmvr/project/cmvr-es/scripts/ethercat/start_ethercat.sh enp2s0
ExecStart=/home/cmvr/project/cmvr-es/output/bin/cmvr_es
ExecStopPost=+/bin/bash /home/cmvr/project/cmvr-es/scripts/ethercat/stop_ethercat.sh enp2s0
Restart=on-failure
RestartSec=10
TimeoutStartSec=120
TimeoutStopSec=30
KillSignal=SIGTERM
LimitRTPRIO=99
LimitMEMLOCK=infinity
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target