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
61 changed files with 1825 additions and 1425 deletions

View File

@ -163,16 +163,10 @@ target_link_libraries(cmvr_es PRIVATE
)
install(TARGETS cmvr_es RUNTIME DESTINATION bin)
# Preserve deployed configuration; install only missing defaults.
install(CODE "set(CMVR_DEFAULT_CONFIG \"${CMAKE_CURRENT_SOURCE_DIR}/cmvr-es/config\")")
install(CODE [[
file(GLOB_RECURSE defaults RELATIVE "${CMVR_DEFAULT_CONFIG}" "${CMVR_DEFAULT_CONFIG}/*")
foreach(relative IN LISTS defaults)
if(NOT EXISTS "${CMAKE_INSTALL_PREFIX}/bin/config/${relative}")
get_filename_component(parent "${relative}" DIRECTORY)
file(INSTALL "${CMVR_DEFAULT_CONFIG}/${relative}" DESTINATION "${CMAKE_INSTALL_PREFIX}/bin/config/${parent}")
endif()
endforeach()
file(REMOVE_RECURSE
"${CMAKE_INSTALL_PREFIX}/bin/config"
"${CMAKE_INSTALL_PREFIX}/bin/model")
]])
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/cmvr-es/config DESTINATION bin)
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/model DESTINATION bin)
add_subdirectory(cmvr-es/management)

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,211 +6,56 @@ 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
config_file: "devices/motor/xiaozhao_tchl_motors.pb.txt"
enable: false
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
config_file: "devices/arm/xiaozhao_tchl_arm.pb.txt"
enable: false
enable: true
}
devices {
@ -220,60 +65,4 @@ device_manager {
enable: false
}
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

@ -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

@ -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

@ -1,22 +0,0 @@
add_executable(cmvr_manager manager_main.cpp)
target_compile_definitions(cmvr_manager PRIVATE _GNU_SOURCE)
target_link_libraries(cmvr_manager PRIVATE cmvr_es::proto pthread)
# Bundled gRPC's indirect shared dependencies also live in output/lib.
# DT_RPATH applies to those dependencies without relying on the launch shell.
target_link_options(cmvr_manager PRIVATE "-Wl,--disable-new-dtags")
file(GLOB_RECURSE _config_protos RELATIVE "${PROTO_IMPORT_DIR}" "${PROTO_IMPORT_DIR}/cmvr/config/*.proto")
set(_config_registry "")
foreach(_file IN LISTS _config_protos)
string(APPEND _config_registry "CMVR_CONFIG_FILE(\"${_file}\")\n")
endforeach()
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/config_types.inc" "${_config_registry}")
target_include_directories(cmvr_manager PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")
install(TARGETS cmvr_manager RUNTIME DESTINATION bin)
add_executable(cmvr_manager_ctl manager_ctl.cpp)
target_link_libraries(cmvr_manager_ctl PRIVATE cmvr_es::proto pthread)
target_link_options(cmvr_manager_ctl PRIVATE "-Wl,--disable-new-dtags")
install(TARGETS cmvr_manager_ctl RUNTIME DESTINATION bin)
install(PROGRAMS start_all.sh DESTINATION bin)
add_executable(cmvr_manager_test EXCLUDE_FROM_ALL manager_test.cpp)
target_link_libraries(cmvr_manager_test PRIVATE cmvr_es::proto pthread)
target_link_options(cmvr_manager_test PRIVATE "-Wl,--disable-new-dtags")

View File

@ -1,109 +0,0 @@
# Independent cmvr-es management
`cmvr_manager` is a separate gRPC process. Device RPCs remain in `cmvr_es`.
It uses the existing executable and configuration layout:
```
output/bin/cmvr_es
output/bin/cmvr_manager
output/bin/config/...
output/lib/...
```
Build with the existing CMake build directory:
```
cmake --build cmake-build-debug --target cmvr_manager
cmake --install cmake-build-debug/cmvr-es/management
```
When first installing a newly generated management protocol, install the matching
`libproto.so` in `output/lib` as well. A normal full project install does this.
Installing defaults now preserves existing deployed configuration files and adds
only missing files. Models retain their existing install location.
Run as the ordinary deployment user:
```
cd output/bin
./cmvr_manager --listen 0.0.0.0:50053
```
To start both programs together, run `output/bin/start_all.sh` as the deployment
user. It starts/reuses the matching management endpoint and requests cmvr_es
startup over gRPC, so cmvr_es remains owned by the manager. Repeated execution
does not restart either process. `CMVR_MANAGEMENT_PORT` overrides port 50053.
Logs append to the existing `output/bin/cmvr_manager.log`.
`output/bin/cmvr_manager_ctl status` queries status; `start`, `stop`, and `restart`
use the same typed management gRPC interface. An application started outside the
manager must first be stopped through its original launcher.
Initialize bus hardware before starting cmvr_es, using the existing repository
layout:
```
./scripts/start_hardware.sh --ethercat-iface enp2s0 --check
./scripts/start_hardware.sh --ethercat-iface enp2s0
./output/bin/start_all.sh
```
The hardware script is installed in the repository's existing `scripts` directory.
It discovers currently present CAN interfaces, uses the existing CAN script's
1 Mbps default. EtherCAT always requires an explicit `--ethercat-iface IFACE`,
including in `--check` mode; there is no fallback from configuration or environment.
`--can-only` does not need an EtherCAT interface. `--ethercat-only`, repeatable
`--can-iface`, and `--bitrate` are available. It requests sudo only for actual
initialization. It refuses a normal-network interface and refuses hardware
reinitialization while cmvr_es is running. Existing CAN links at the requested
rate and an existing EtherCAT master on the selected MAC are kept running.
Changing a running CAN link's bitrate requires `--reconfigure-can`.
In these examples `enp2s0` is only an example: pass the actual dedicated port.
On 234, the existing EtherCAT config names `enp2s0`; both Ethernet ports use IgH's
igc driver. At script creation there were no CAN interfaces and both Ethernet
ports had no carrier. The script was checked without altering network interfaces;
real bus communication requires connecting the hardware and confirming the
dedicated EtherCAT port. No drive enable or movement is performed by this script.
The default executable and working directory are the manager's own directory.
`--bin-dir` selects another existing deployment directory for isolated testing.
No shell commands, executable paths or arbitrary filenames are accepted over RPC.
This is the same trusted-LAN, insecure-gRPC transport as the existing device
service; it does not introduce a public internet endpoint.
`GetStatus` reports process existence/ownership, not device readiness. A running
process started by CLion or another launcher is detected but not stopped or
adopted. Stop it in the original launcher before starting it through the manager.
`STOP` sends SIGTERM and waits up to 30 seconds; timeout never escalates to SIGKILL
and cancels `RESTART`. Process startup errors remain visible through management
RPC and the manager's redirected output. Stop the managed child before stopping
the manager itself; this initial implementation does not provide boot autostart
or adopt an orphaned child after the manager is killed.
Configuration RPCs access existing `.pb.txt` files inside the existing `config`
directory. Writes check protobuf syntax, known fields/enums, message type and
configuration-file references. The root config must retain logger, device manager
and task manager references. Writes require the revision returned by `ReadConfig`
and use a flushed temporary file beside the destination followed by rename.
The temporary file is not a server-side draft. The editor stores drafts on the
Windows client in `data/management_drafts.json`, keyed by endpoint and filename.
Saving does not automatically restart the application. File validation does not
certify device parameters or hardware readiness; runtime/device initialization
continues to perform those checks.
Protocol: `protos/cmvr/management/manager.proto`.
Tests:
```
cmake --build cmake-build-debug --target cmvr_manager cmvr_manager_test
python3 cmvr-es/management/test_manager.py
cmake-build-debug/cmvr-es/management/cmvr_manager_test 127.0.0.1:50053 --read-only
```
The fixture test uses a temporary directory and replacement child process. The
`--lifecycle` mode is specifically for a deployment whose cmvr_es is stopped and
whose enabled tasks/devices have been checked first. It saves identical config
bytes, starts/restarts/stops the real program, checks control gRPC on 50052, and
leaves it stopped. Do not use that mode against a deployment in active operation.

View File

@ -1,23 +0,0 @@
#include "cmvr/management/manager.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <chrono>
#include <filesystem>
#include <iostream>
namespace api=cmvr::management;
int main(int argc,char** argv){
std::string endpoint="127.0.0.1:50053",command="status",expected;
for(int i=1;i<argc;++i){std::string arg=argv[i];if(arg=="--endpoint"&&i+1<argc)endpoint=argv[++i];else if(arg=="--expected-executable"&&i+1<argc)expected=argv[++i];else if(arg=="status"||arg=="ensure-running"||arg=="start"||arg=="stop"||arg=="restart")command=arg;else{std::cerr<<"Usage: cmvr_manager_ctl [status|ensure-running|start|stop|restart] [--endpoint HOST:PORT] [--expected-executable PATH]\n";return 2;}}
auto stub=api::ManagerService::NewStub(grpc::CreateChannel(endpoint,grpc::InsecureChannelCredentials()));
api::ProcessStatus status;grpc::ClientContext query;query.set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(2));auto result=stub->GetStatus(&query,api::Empty(),&status);
if(!result.ok()){std::cerr<<result.error_message()<<"\n";return 1;}
if(!expected.empty()&&std::filesystem::weakly_canonical(expected)!=std::filesystem::weakly_canonical(status.executable())){std::cerr<<"Management endpoint belongs to a different deployment: "<<status.executable()<<"\n";return 3;}
if(command!="status"){
if(status.running()&&!status.managed()){std::cerr<<"cmvr_es was started outside this manager. Stop the original launcher first.\n";return 3;}
if(command!="ensure-running"||!status.running()){
api::ProcessRequest request;request.set_action(command=="stop"?api::ProcessRequest::STOP:command=="restart"?api::ProcessRequest::RESTART:api::ProcessRequest::START);grpc::ClientContext context;context.set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(40));result=stub->Control(&context,request,&status);
if(!result.ok()){std::cerr<<result.error_message()<<"\n";return 1;}
}
}
std::cout<<"cmvr_es "<<(status.running()?"running":"stopped")<<" pid="<<status.pid()<<" managed="<<status.managed()<<" executable="<<status.executable()<<"\n";
return 0;
}

View File

@ -1,223 +0,0 @@
#include "cmvr/management/manager.grpc.pb.h"
#include "cmvr/config/cmvr_es_config/cmvr_es_config.pb.h"
#include <grpcpp/grpcpp.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/tokenizer.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <mutex>
#include <thread>
#include <chrono>
#include <vector>
#include <memory>
#include <algorithm>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <cstring>
#include <spawn.h>
#include <signal.h>
#include <unistd.h>
extern char **environ;
namespace fs=std::filesystem;
namespace api=cmvr::management;
using grpc::Status;
using grpc::StatusCode;
using google::protobuf::Message;
struct ParseErrors final:google::protobuf::io::ErrorCollector {
std::string detail;
void RecordError(int line,google::protobuf::io::ColumnNumber col,absl::string_view text) override {
detail+=std::to_string(line+1)+":"+std::to_string(col+1)+" "+std::string(text)+"\n";
}
void RecordWarning(int,google::protobuf::io::ColumnNumber,absl::string_view) override {}
};
static std::string readFile(const fs::path& path) {
std::ifstream file(path,std::ios::binary);
if(!file)throw std::runtime_error("Cannot read "+path.string());
std::string text((std::istreambuf_iterator<char>(file)),{});
if(text.size()>1024*1024)throw std::runtime_error("Configuration exceeds 1 MiB");
return text;
}
// A revision identifies bytes, including formatting. It is not an authorization token.
static std::string revision(const std::string& text) {
uint64_t h=14695981039346656037ULL;
for(unsigned char c:text){h^=c;h*=1099511628211ULL;}
std::ostringstream out;out<<std::hex<<h<<"-"<<text.size();return out.str();
}
class Manager final:public api::ManagerService::Service {
fs::path bin_,root_,exe_;
std::mutex mutex_;
pid_t child_=-1;
int lastExit_=0;
std::vector<const google::protobuf::Descriptor*> types_;
google::protobuf::DynamicMessageFactory factory_;
fs::path configPath(const std::string& name) const {
fs::path input(name);
if(input.empty()||input.is_absolute())throw std::runtime_error("Expected relative configuration path");
for(const auto& part:input)if(part=="..")throw std::runtime_error("Parent traversal is forbidden");
const auto p=fs::canonical(root_/input);
const auto rel=p.lexically_relative(root_);
if(rel.empty()||*rel.begin()==".."||!fs::is_regular_file(p)||p.extension()!=".txt"||p.string().size()<7||p.string().substr(p.string().size()-7)!=".pb.txt")
throw std::runtime_error("Only existing .pb.txt files inside config are accessible");
return p;
}
void reap() {
if(child_<=0)return;
int code=0;const auto result=waitpid(child_,&code,WNOHANG);
if(result==child_){lastExit_=WIFEXITED(code)?WEXITSTATUS(code):128+WTERMSIG(code);child_=-1;}
}
pid_t existingProcess() {
reap();if(child_>0)return child_;
for(const auto& item:fs::directory_iterator("/proc")){
const auto name=item.path().filename().string();
if(name.empty()||!std::all_of(name.begin(),name.end(),[](char c){return c>='0'&&c<='9';}))continue;
std::error_code error;const auto executable=fs::read_symlink(item.path()/"exe",error);
if(!error&&executable==exe_)return std::stoi(name);
}return -1;
}
void status(api::ProcessStatus* result,const std::string& detail={}) {
auto pid=existingProcess();result->set_running(pid>0);result->set_pid(pid>0?pid:0);
result->set_managed(pid>0&&pid==child_);result->set_executable(exe_.string());
result->set_working_directory(bin_.string());result->set_last_exit_code(lastExit_);
result->set_detail(detail.empty()?(pid>0?(pid==child_?"Process running (not a device readiness check)":"Process started outside manager; stop it in its original launcher first"):"Process stopped"):detail);
}
std::unique_ptr<Message> parse(const std::string& text,std::string& error) {
std::string candidateError;
for(auto* type:types_){
std::unique_ptr<Message> message(factory_.GetPrototype(type)->New());
ParseErrors errors;google::protobuf::TextFormat::Parser parser;parser.RecordErrorsTo(&errors);
if(parser.ParseFromString(text,message.get())){
std::vector<const google::protobuf::FieldDescriptor*> fields;
message->GetReflection()->ListFields(*message,&fields);
if(!fields.empty())return message;
}
for(int i=0;i<type->field_count();++i)if(text.find(std::string(type->field(i)->name())+" {")!=std::string::npos&&candidateError.empty())candidateError=errors.detail;
}
error=candidateError.empty()?"No configuration schema matches this document (unknown field, enum, or invalid protobuf text)":candidateError;return {};
}
bool references(const Message& message,std::string& error) {
const auto* reflection=message.GetReflection();std::vector<const google::protobuf::FieldDescriptor*> fields;
reflection->ListFields(message,&fields);
for(auto* field:fields){
if(field->cpp_type()==google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE){
int count=field->is_repeated()?reflection->FieldSize(message,field):1;
for(int i=0;i<count;++i)if(!references(field->is_repeated()?reflection->GetRepeatedMessage(message,field,i):reflection->GetMessage(message,field),error))return false;
}else if(field->cpp_type()==google::protobuf::FieldDescriptor::CPPTYPE_STRING&&field->name().size()>=11&&field->name().substr(field->name().size()-11)=="config_file"){
const auto name=reflection->GetString(message,field);
if(!name.empty())try{configPath(name);}catch(const std::exception& e){error=std::string(field->full_name())+": "+e.what();return false;}
}
}return true;
}
bool validate(const std::string& text,std::string& error) {
if(text.empty()||text.size()>1024*1024){error="Configuration must contain 1 byte to 1 MiB";return false;}
auto parsed=parse(text,error);return parsed&&references(*parsed,error);
}
bool validateFile(const fs::path& path,const std::string& text,std::string& error) {
if(!validate(text,error))return false;
auto replacement=parse(text,error);
std::string previousError;auto previous=parse(readFile(path),previousError);
const auto* expected=path==root_/"cmvr_es.pb.txt"?cmvr::config::CMVRESRootConfig::descriptor():(previous?previous->GetDescriptor():nullptr);
if(expected&&replacement->GetDescriptor()!=expected){error="Configuration message type must remain "+std::string(expected->full_name());return false;}
if(expected==cmvr::config::CMVRESRootConfig::descriptor()){
cmvr::config::CMVRESRootConfig root;root.ParseFromString(replacement->SerializeAsString());
if(root.cmvr_es().logger_config_file().empty()||root.cmvr_es().device_manager_config_file().empty()||root.cmvr_es().task_manager_config_file().empty()){
error="logger_config_file, device_manager_config_file and task_manager_config_file are required";return false;
}
}
return true;
}
Status stop() {
const auto pid=existingProcess();if(pid<=0)return Status::OK;
if(pid!=child_)return {StatusCode::FAILED_PRECONDITION,"Process is not owned by this manager. Stop the original launcher first."};
if(kill(child_,SIGTERM)!=0&&errno!=ESRCH)return {StatusCode::INTERNAL,"Cannot send SIGTERM"};
for(int i=0;i<300;++i){reap();if(child_<=0)return Status::OK;std::this_thread::sleep_for(std::chrono::milliseconds(100));}
return {StatusCode::DEADLINE_EXCEEDED,"Graceful shutdown exceeded 30 seconds; process was not killed. Restart was cancelled."};
}
Status start() {
if(existingProcess()>0)return {StatusCode::FAILED_PRECONDITION,"cmvr_es is already running"};
std::string error;
if(!validateFile(root_/"cmvr_es.pb.txt",readFile(root_/"cmvr_es.pb.txt"),error))return {StatusCode::INVALID_ARGUMENT,error};
posix_spawn_file_actions_t actions;posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_addchdir_np(&actions,bin_.c_str());
posix_spawnattr_t attr;posix_spawnattr_init(&attr);
sigset_t empty;sigemptyset(&empty);posix_spawnattr_setsigmask(&attr,&empty);posix_spawnattr_setflags(&attr,POSIX_SPAWN_SETSIGMASK);
std::string executable=exe_.string();char* argv[]={executable.data(),nullptr};
const auto result=posix_spawn(&child_,exe_.c_str(),&actions,&attr,argv,environ);
posix_spawn_file_actions_destroy(&actions);posix_spawnattr_destroy(&attr);
if(result){child_=-1;return {StatusCode::INTERNAL,"Cannot launch cmvr_es: "+std::string(strerror(result))};}
std::this_thread::sleep_for(std::chrono::milliseconds(800));reap();
if(child_<=0)return {StatusCode::FAILED_PRECONDITION,"cmvr_es exited during startup, exit="+std::to_string(lastExit_)+". Check manager output."};
return Status::OK;
}
public:
explicit Manager(fs::path bin):bin_(fs::canonical(bin)),root_(fs::canonical(bin_/"config")),exe_(fs::canonical(bin_/"cmvr_es")) {
(void)cmvr::config::CMVRESRootConfig::descriptor();
auto* pool=google::protobuf::DescriptorPool::generated_pool();
const auto add=[&](const char* name){if(auto* file=pool->FindFileByName(name))for(int i=0;i<file->message_type_count();++i)types_.push_back(file->message_type(i));};
#define CMVR_CONFIG_FILE(name) add(name);
#include "config_types.inc"
#undef CMVR_CONFIG_FILE
}
Status GetStatus(grpc::ServerContext*,const api::Empty*,api::ProcessStatus* result) override {
std::lock_guard<std::mutex> lock(mutex_);try{status(result);return Status::OK;}catch(const std::exception& e){return {StatusCode::INTERNAL,e.what()};}
}
Status ListConfigs(grpc::ServerContext*,const api::Empty*,api::ConfigList* result) override {
std::lock_guard<std::mutex> lock(mutex_);
try{std::vector<std::string> names;for(const auto& file:fs::recursive_directory_iterator(root_)){
if(file.is_regular_file()){auto name=file.path().lexically_relative(root_).generic_string();try{configPath(name);names.push_back(name);}catch(...) {}}}
std::sort(names.begin(),names.end());for(const auto& name:names)result->add_paths(name);return Status::OK;
}catch(const std::exception& e){return {StatusCode::INTERNAL,e.what()};}
}
Status ReadConfig(grpc::ServerContext*,const api::ConfigPath* request,api::ConfigFile* result) override {
std::lock_guard<std::mutex> lock(mutex_);try{const auto text=readFile(configPath(request->path()));result->set_path(request->path());result->set_text(text);result->set_revision(revision(text));return Status::OK;}catch(const std::exception& e){return {StatusCode::INVALID_ARGUMENT,e.what()};}
}
Status ValidateConfig(grpc::ServerContext*,const api::ConfigFile* request,api::Validation* result) override {
std::lock_guard<std::mutex> lock(mutex_);try{auto path=configPath(request->path());std::string error;result->set_valid(validateFile(path,request->text(),error));result->set_detail(result->valid()?"Protobuf syntax, fields, document type and configuration references validated":error);return Status::OK;}catch(const std::exception& e){return {StatusCode::INVALID_ARGUMENT,e.what()};}
}
Status WriteConfig(grpc::ServerContext*,const api::ConfigFile* request,api::ConfigFile* result) override {
std::lock_guard<std::mutex> lock(mutex_);
try{
const auto path=configPath(request->path());std::string error;
if(!validateFile(path,request->text(),error))return {StatusCode::INVALID_ARGUMENT,error};
const auto old=readFile(path);
if(request->revision().empty()||request->revision()!=revision(old))return {StatusCode::ABORTED,"Configuration changed since it was read. Read it again before saving."};
auto temp=path.string()+".XXXXXX";int fd=mkstemp(temp.data());if(fd<0)return {StatusCode::INTERNAL,"Cannot create temporary file beside configuration"};
bool ok=true;size_t offset=0;while(offset<request->text().size()) {auto n=write(fd,request->text().data()+offset,request->text().size()-offset);if(n<0&&errno==EINTR)continue;if(n<=0){ok=false;break;}offset+=n;}
const auto perms=fs::status(path).permissions();fchmod(fd,static_cast<mode_t>(perms)&0777);if(fsync(fd)!=0)ok=false;if(close(fd)!=0)ok=false;
if(!ok){unlink(temp.c_str());return {StatusCode::INTERNAL,"Failed to flush configuration; original preserved"};}
// Recheck immediately before replacement to catch external edits during validation.
if(readFile(path)!=old){unlink(temp.c_str());return {StatusCode::ABORTED,"Configuration changed while saving"};}
if(rename(temp.c_str(),path.c_str())!=0){unlink(temp.c_str());return {StatusCode::INTERNAL,"Cannot replace configuration"};}
int directory=open(path.parent_path().c_str(),O_RDONLY|O_DIRECTORY);if(directory>=0){fsync(directory);close(directory);}
*result=*request;result->set_revision(revision(request->text()));return Status::OK;
}catch(const std::exception& e){return {StatusCode::INVALID_ARGUMENT,e.what()};}
}
Status Control(grpc::ServerContext*,const api::ProcessRequest* request,api::ProcessStatus* result) override {
std::lock_guard<std::mutex> lock(mutex_);
try{Status outcome;
switch(request->action()){
case api::ProcessRequest::START:outcome=start();break;
case api::ProcessRequest::STOP:outcome=stop();break;
case api::ProcessRequest::RESTART:outcome=stop();if(outcome.ok())outcome=start();break;
default:return {StatusCode::INVALID_ARGUMENT,"Explicit START, STOP or RESTART required"};
}status(result);return outcome;
}catch(const std::exception& e){return {StatusCode::INTERNAL,e.what()};}
}
};
int main(int argc,char** argv) {
try {
fs::path bin=fs::canonical("/proc/self/exe").parent_path();std::string address="0.0.0.0:50053";
for(int i=1;i<argc;++i){std::string arg=argv[i];if(arg=="--bin-dir"&&i+1<argc)bin=argv[++i];else if(arg=="--listen"&&i+1<argc)address=argv[++i];else {std::cerr<<"Usage: cmvr_manager [--listen IP:PORT] [--bin-dir existing-bin-directory]\n";return 2;}}
bin=fs::canonical(bin);int lockfd=open((bin/".cmvr_manager.lock").c_str(),O_CREAT|O_RDWR|O_CLOEXEC,0600);
if(lockfd<0||flock(lockfd,LOCK_EX|LOCK_NB)!=0)throw std::runtime_error("Another manager owns this deployment, or bin is not writable");
Manager manager(bin);grpc::ServerBuilder builder;builder.SetMaxReceiveMessageSize(2*1024*1024);
builder.AddListeningPort(address,grpc::InsecureServerCredentials());builder.RegisterService(&manager);
auto server=builder.BuildAndStart();if(!server)throw std::runtime_error("Cannot bind management gRPC address");
std::cout<<"cmvr_manager listening="<<address<<" bin="<<bin<<std::endl;server->Wait();
}catch(const std::exception& e){std::cerr<<e.what()<<std::endl;return 1;}
}

View File

@ -1,48 +0,0 @@
#include "cmvr/management/manager.grpc.pb.h"
#include "cmvr/api/system_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <iostream>
#include <stdexcept>
#include <chrono>
#include <thread>
namespace api=cmvr::management;
static void check(bool ok,const char* why){if(!ok)throw std::runtime_error(why);}
int main(int argc,char** argv){try{
check(argc>=2,"Expected endpoint [--read-only]");bool readOnly=argc>2;
auto stub=api::ManagerService::NewStub(grpc::CreateChannel(argv[1],grpc::InsecureChannelCredentials()));
auto context=[](){auto result=std::make_unique<grpc::ClientContext>();result->set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(40));return result;};
api::Empty empty;api::ProcessStatus status;auto c=context();check(stub->GetStatus(c.get(),empty,&status).ok(),"GetStatus");
std::cout<<"Status running="<<status.running()<<" managed="<<status.managed()<<" pid="<<status.pid()<<"\n";
api::ConfigList list;c=context();check(stub->ListConfigs(c.get(),empty,&list).ok()&&list.paths_size()>0,"ListConfigs");
api::ConfigPath path;path.set_path("cmvr_es.pb.txt");api::ConfigFile file;c=context();check(stub->ReadConfig(c.get(),path,&file).ok()&&!file.revision().empty(),"ReadConfig and revision");
api::Validation validation;c=context();check(stub->ValidateConfig(c.get(),file,&validation).ok()&&validation.valid(),"Validate root configuration");
if(readOnly&&std::string(argv[2])=="--lifecycle"){
check(!status.running(),"Lifecycle test requires initially stopped deployment");
struct Cleanup {api::ManagerService::Stub* stub;~Cleanup(){api::ProcessRequest request;request.set_action(api::ProcessRequest::STOP);api::ProcessStatus status;grpc::ClientContext c;c.set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(35));stub->Control(&c,request,&status);}} cleanup{stub.get()};
auto run=[&](api::ProcessRequest::Action value){api::ProcessRequest action;action.set_action(value);auto ctx=context();auto result=stub->Control(ctx.get(),action,&status);if(!result.ok())throw std::runtime_error("Control: "+result.error_message());};
auto ping=[&]{auto system=cmvr::api::SystemService::NewStub(grpc::CreateChannel("127.0.0.1:50052",grpc::InsecureChannelCredentials()));cmvr::api::GetSystemInfoCommand::Request request;cmvr::api::GetSystemInfoCommand::Feedback reply;auto ctx=context();ctx->set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(10));check(system->GetSystemInfo(ctx.get(),request,&reply).ok(),"Real cmvr-es control gRPC becomes reachable");};
api::ConfigFile saved;c=context();check(stub->WriteConfig(c.get(),file,&saved).ok()&&saved.text()==file.text(),"Save identical real configuration without changing content");
run(api::ProcessRequest::START);check(status.running()&&status.managed(),"Real managed startup");auto first=status.pid();ping();
run(api::ProcessRequest::RESTART);check(status.running()&&status.pid()!=first,"Real restart changes PID");ping();
run(api::ProcessRequest::STOP);check(!status.running(),"Real graceful stop");
c=context();check(stub->GetStatus(c.get(),empty,&status).ok(),"Management remains reachable while real service stopped");
std::cout<<"REAL CMVR-ES START / CONTROL GRPC / RESTART / STOP PASS\n";return 0;
}
if(readOnly){std::cout<<"REAL DEPLOYMENT READ-ONLY PASS files="<<list.paths_size()<<"\n";return 0;}
auto initial=file;
file.set_text(file.text()+"\n# management integration test\n");api::ConfigFile saved;c=context();check(stub->WriteConfig(c.get(),file,&saved).ok(),"Write valid configuration");
check(saved.revision()!=initial.revision(),"Revision changes");
c=context();check(stub->WriteConfig(c.get(),initial,&file).error_code()==grpc::StatusCode::ABORTED,"Stale writes rejected");
auto bad=saved;bad.set_text("cmvr_es { invented_parameter: true }");c=context();check(stub->ValidateConfig(c.get(),bad,&validation).ok()&&!validation.valid(),"Unknown field rejected");
c=context();check(stub->WriteConfig(c.get(),bad,&file).error_code()==grpc::StatusCode::INVALID_ARGUMENT,"Invalid configuration never saved");
bad=saved;bad.set_text("device_manager { name: \"wrong type\" }");c=context();check(stub->ValidateConfig(c.get(),bad,&validation).ok()&&!validation.valid(),"Cannot replace root configuration with another message type");
bad=saved;bad.set_text("cmvr_es { logger_config_file: \"missing.pb.txt\" }");c=context();check(stub->ValidateConfig(c.get(),bad,&validation).ok()&&!validation.valid(),"Missing reference rejected");
for(const auto& invalid:{"../outside.pb.txt","/etc/passwd","escape.pb.txt"}){path.set_path(invalid);c=context();check(!stub->ReadConfig(c.get(),path,&file).ok(),"Traversal, absolute paths, symlink escape rejected");}
api::ProcessRequest action;action.set_action(api::ProcessRequest::START);c=context();check(stub->Control(c.get(),action,&status).ok()&&status.running()&&status.managed(),"Start managed child");auto first=status.pid();
c=context();check(stub->Control(c.get(),action,&status).error_code()==grpc::StatusCode::FAILED_PRECONDITION,"Duplicate start rejected");
action.set_action(api::ProcessRequest::RESTART);c=context();check(stub->Control(c.get(),action,&status).ok()&&status.running()&&status.pid()!=first,"Graceful restart changes PID");
action.set_action(api::ProcessRequest::STOP);c=context();check(stub->Control(c.get(),action,&status).ok()&&!status.running(),"Graceful stop");
c=context();check(stub->GetStatus(c.get(),empty,&status).ok()&&!status.running(),"Manager survives child shutdown");
saved.set_text(initial.text());c=context();check(stub->WriteConfig(c.get(),saved,&file).ok(),"Restore configuration");
std::cout<<"MANAGEMENT INTEGRATION PASS\n";return 0;
}catch(const std::exception& e){std::cerr<<e.what()<<"\n";return 1;}}

View File

@ -1,38 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# Run as the deployment user, not sudo. The manager owns the cmvr_es child.
BIN_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
PORT="${CMVR_MANAGEMENT_PORT:-50053}"
if [[ "${1:-}" == --help || "${1:-}" == -h ]]; then
echo 'Usage: ./start_all.sh (optional CMVR_MANAGEMENT_PORT=50053)'
exit 0
fi
[[ $# -eq 0 ]] || { echo 'Unexpected arguments; use --help.' >&2; exit 2; }
[[ "$PORT" =~ ^[0-9]{1,5}$ ]] && (( 10#$PORT > 0 && 10#$PORT < 65536 )) || { echo 'Invalid management port.' >&2; exit 2; }
if (( EUID == 0 )); then echo 'Run this script as the normal deployment user; hardware setup has a separate sudo script.' >&2; exit 1; fi
for name in cmvr_es cmvr_manager cmvr_manager_ctl; do
[[ -x "$BIN_DIR/$name" ]] || { echo "Missing executable: $BIN_DIR/$name" >&2; exit 1; }
done
cd "$BIN_DIR"
exec 9>"$BIN_DIR/.cmvr_start.lock"
flock -w 15 9 || { echo 'Another startup is in progress.' >&2; exit 1; }
CTL=("$BIN_DIR/cmvr_manager_ctl" --endpoint "127.0.0.1:$PORT" --expected-executable "$BIN_DIR/cmvr_es")
if ! "${CTL[@]}" status >/dev/null 2>&1; then
# FD 9 must not leak into the long-lived manager/child.
nohup "$BIN_DIR/cmvr_manager" --listen "0.0.0.0:$PORT" >>"$BIN_DIR/cmvr_manager.log" 2>&1 </dev/null 9>&- &
manager_pid=$!
ready=0
for ((i=0;i<10;i++)); do
if "${CTL[@]}" status >/dev/null 2>&1; then ready=1; break; fi
kill -0 "$manager_pid" 2>/dev/null || break
sleep 0.5
done
if (( ready == 0 )); then
echo "Management service failed to become ready; see $BIN_DIR/cmvr_manager.log" >&2
tail -15 "$BIN_DIR/cmvr_manager.log" >&2
exit 1
fi
fi
"${CTL[@]}" ensure-running
echo "Management gRPC: $PORT; log: $BIN_DIR/cmvr_manager.log"
echo 'Process started. Device/control-service readiness is reported separately by cmvr_es.'

View File

@ -1,20 +0,0 @@
"""Run on the Linux device. Fixtures never replace deployed device configuration."""
import pathlib, subprocess, tempfile, shutil, time, os, signal
repo=pathlib.Path(__file__).resolve().parents[2]
build=repo/'cmake-build-debug/cmvr-es/management'
with tempfile.TemporaryDirectory(prefix='cmvr-manager-test-') as temp:
root=pathlib.Path(temp)
shutil.copytree(repo/'output/bin/config',root/'config')
(root/'outside.pb.txt').write_text('outside')
(root/'config/escape.pb.txt').symlink_to(root/'outside.pb.txt')
fake=root/'cmvr_es'
fake.write_text('#!/usr/bin/python3\nimport signal,time\nsignal.signal(signal.SIGTERM,lambda *_:exit(0))\nwhile True: time.sleep(0.05)\n')
fake.chmod(0o755)
log=open(root/'manager.log','w+')
proc=subprocess.Popen([str(build/'cmvr_manager'),'--bin-dir',temp,'--listen','127.0.0.1:50054'],stdout=log,stderr=log)
try:
time.sleep(1)
subprocess.run([str(build/'cmvr_manager_test'),'127.0.0.1:50054'],check=True,timeout=80)
finally:
proc.terminate();proc.wait(timeout=5)
log.seek(0);print(log.read())

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

@ -1,35 +0,0 @@
syntax = "proto3";
package cmvr.management;
// Independent process. This service remains available while cmvr_es is stopped.
service ManagerService {
rpc GetStatus(Empty) returns (ProcessStatus);
rpc ListConfigs(Empty) returns (ConfigList);
rpc ReadConfig(ConfigPath) returns (ConfigFile);
rpc ValidateConfig(ConfigFile) returns (Validation);
rpc WriteConfig(ConfigFile) returns (ConfigFile);
rpc Control(ProcessRequest) returns (ProcessStatus);
}
message Empty {}
message ProcessStatus {
bool running = 1;
int64 pid = 2;
bool managed = 3;
string executable = 4;
string working_directory = 5;
string detail = 6;
int32 last_exit_code = 7;
}
message ConfigPath { string path = 1; }
message ConfigList { repeated string paths = 1; }
message ConfigFile {
string path = 1;
string text = 2;
// Opaque revision returned by ReadConfig; required for optimistic writes.
string revision = 3;
}
message Validation { bool valid = 1; string detail = 2; }
message ProcessRequest {
enum Action { UNSPECIFIED = 0; START = 1; STOP = 2; RESTART = 3; }
Action action = 1;
}

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

@ -1,109 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
CAN=1; EC=1; CHECK=0; RECONFIGURE=0
BITRATE="${CAN_BITRATE:-1000000}"
IFACE=""; CAN_IFACES=()
IGH_ROOT="${IGH_ROOT:-$ROOT/dependency/x86/third_party/ethercat/v1.7.0}"
CONF="${ETHERCAT_CONF:-$IGH_ROOT/etc/ethercat.conf}"
usage(){ cat <<'EOF'
Usage: scripts/start_hardware.sh --ethercat-iface IFACE [--can-iface can0 ...]
[--bitrate 1000000] [--can-only|--ethercat-only] [--check] [--reconfigure-can]
scripts/start_hardware.sh --can-only [--can-iface can0 ...] [--check]
--check only checks prerequisites and prints the plan; no sudo or changes.
Without --can-iface, select existing CAN interfaces. Default bitrate: 1000000.
EtherCAT requires --ethercat-iface on every invocation, including --check.
No interface is selected from configuration or environment. Normal execution needs sudo.
No motor enable or motion commands are issued.
EOF
}
while (( $# )); do
case "$1" in
--ethercat-iface) [[ $# -ge 2 ]] || exit 2; IFACE="$2"; shift 2;;
--can-iface) [[ $# -ge 2 ]] || exit 2; CAN_IFACES+=("$2"); shift 2;;
--bitrate) [[ $# -ge 2 ]] || exit 2; BITRATE="$2"; shift 2;;
--can-only) EC=0; shift;;
--ethercat-only) CAN=0; shift;;
--check) CHECK=1; shift;;
--reconfigure-can) RECONFIGURE=1; shift;;
--help|-h) usage; exit 0;;
*) usage >&2; exit 2;;
esac
done
(( CAN || EC )) || { echo 'Select at least one bus.' >&2; exit 2; }
if (( EC )) && [[ -z "$IFACE" ]]; then
echo 'EtherCAT: --ethercat-iface IFACE is required (for example --ethercat-iface enp2s0).' >&2
exit 2
fi
[[ "$BITRATE" =~ ^[0-9]{1,8}$ ]] && (( 10#$BITRATE > 0 )) || { echo 'Invalid CAN bitrate' >&2; exit 2; }
for command in ip python3 modinfo; do command -v "$command" >/dev/null || { echo "Missing command: $command" >&2; exit 1; }; done
if (( CAN && ${#CAN_IFACES[@]} == 0 )); then
for path in /sys/class/net/*; do
if [[ "$(cat "$path/type")" == 280 ]]; then CAN_IFACES+=("${path##*/}"); fi
done
fi
failed=0
if (( CAN )); then
if (( ${#CAN_IFACES[@]} == 0 )); then
echo 'CAN: no CAN interface detected. Check the adapter and driver; no interface was created or marked ready.' >&2
failed=1
fi
for interface in "${CAN_IFACES[@]}"; do
if [[ ! -f "/sys/class/net/$interface/type" ]] || [[ "$(cat "/sys/class/net/$interface/type")" != 280 ]]; then
echo "CAN: not a CAN interface: $interface" >&2; failed=1
else echo "CAN plan: $interface, bitrate=$BITRATE"; fi
done
fi
if (( EC )); then
if [[ -z "$IFACE" || ! "$IFACE" =~ ^[[:alnum:]_.:-]+$ || ! -d "/sys/class/net/$IFACE" ]]; then
echo 'EtherCAT: specify an existing dedicated Ethernet port using --ethercat-iface.' >&2; failed=1
elif [[ "$IFACE" == lo || -d "/sys/class/net/$IFACE/wireless" ]] || ip route show default | grep -qE " dev $IFACE( |$)" || [[ -n "$(ip -o addr show dev "$IFACE" scope global)" ]]; then
echo "EtherCAT: $IFACE carries normal networking; refusing to disconnect or flush it." >&2; failed=1
else
echo "EtherCAT plan: $IFACE, MAC=$(cat "/sys/class/net/$IFACE/address"), existing config=$CONF"
if [[ "$(cat "/sys/class/net/$IFACE/carrier" 2>/dev/null || echo 0)" != 1 ]]; then
echo "EtherCAT: $IFACE has no link; a connected slave cannot be verified." >&2
fi
fi
for module in ec_master ec_igc; do
modinfo "$module" >/dev/null 2>&1 || { echo "EtherCAT: missing kernel module $module" >&2; failed=1; }
done
[[ -x "$IGH_ROOT/sbin/ethercatctl" && -x "$IGH_ROOT/bin/ethercat" ]] || { echo "EtherCAT: incomplete IgH tools in $IGH_ROOT" >&2; failed=1; }
fi
(( failed == 0 )) || exit 1
(( CHECK == 0 )) || { echo 'Prerequisite checks passed; no changes made.'; exit 0; }
if (( EUID != 0 )); then
args=(); (( CAN )) || args+=(--ethercat-only); (( EC )) || args+=(--can-only)
[[ -z "$IFACE" ]] || args+=(--ethercat-iface "$IFACE")
for interface in "${CAN_IFACES[@]}"; do args+=(--can-iface "$interface"); done
(( RECONFIGURE == 0 )) || args+=(--reconfigure-can)
exec sudo env "IGH_ROOT=$IGH_ROOT" "ETHERCAT_CONF=$CONF" bash "$ROOT/scripts/start_hardware.sh" "${args[@]}" --bitrate "$BITRATE"
fi
# Do not reinitialize a bus while the application may be using it.
if pgrep -x cmvr_es >/dev/null; then echo 'Stop cmvr_es through its manager before initializing hardware.' >&2; exit 1; fi
if (( CAN )); then
modprobe can; modprobe can_raw
for interface in "${CAN_IFACES[@]}"; do
read -r up current_rate < <(ip -details -json link show dev "$interface" | python3 -c 'import sys,json; d=json.load(sys.stdin)[0]; print(int("UP" in d.get("flags",[])),d.get("linkinfo",{}).get("info_data",{}).get("bitrate",0))')
if (( up )); then
if [[ "$current_rate" == "$BITRATE" ]]; then echo "CAN: $interface already up at $BITRATE; kept running."; continue; fi
(( RECONFIGURE )) || { echo "CAN: $interface already up at $current_rate; use --reconfigure-can to change bitrate." >&2; exit 1; }
ip link set dev "$interface" down
fi
ip link set dev "$interface" type can bitrate "$BITRATE"
ip link set dev "$interface" up
echo "CAN: $interface started, bitrate=$BITRATE"
done
fi
if (( EC )); then
mac="$(cat "/sys/class/net/$IFACE/address")"
if [[ -e /dev/EtherCAT0 ]] && "$IGH_ROOT/bin/ethercat" master 2>/dev/null | grep -qi "$mac"; then
echo "EtherCAT: master already uses $IFACE; kept running."
else
IGH_ROOT="$IGH_ROOT" ETHERCAT_CONF="$CONF" DEVICE_MODULES=igc bash "$ROOT/scripts/ethercat/start_ethercat.sh" "$IFACE"
fi
[[ -e /dev/EtherCAT0 ]] || { echo 'EtherCAT: /dev/EtherCAT0 was not created.' >&2; exit 1; }
"$IGH_ROOT/bin/ethercat" master
"$IGH_ROOT/bin/ethercat" slaves
fi

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