Compare commits
No commits in common. "dev" and "lgv_dev_tc_motor" have entirely different histories.
dev
...
lgv_dev_tc
@ -118,7 +118,6 @@ git rev-parse HEAD # 记录本次 userspace 和内核模块共同使用的提
|
||||
--sysconfdir=$IGH_ETHERCAT_ROOT/etc \
|
||||
--with-systemdsystemunitdir=$IGH_ETHERCAT_ROOT/lib/systemd/system \
|
||||
--enable-generic \
|
||||
--enable-igc \
|
||||
--with-linux-dir=/lib/modules/$(uname -r)/build
|
||||
|
||||
make -j$(nproc) all modules
|
||||
@ -159,7 +158,7 @@ sudo scripts/ethercat/start_ethercat.sh eno1
|
||||
$IGH_ETHERCAT_ROOT/etc/ethercat.conf
|
||||
```
|
||||
|
||||
脚本会把该网卡的 MAC 写到 `MASTER0_DEVICE`,使用 `DEVICE_MODULES="igc"`,把网卡从 NetworkManager 断开,并通过 `ethercatctl -c` 启动 IgH master。
|
||||
脚本会把该网卡的 MAC 写到 `MASTER0_DEVICE`,使用 `DEVICE_MODULES="generic"`,把网卡从 NetworkManager 断开,并通过 `ethercatctl -c` 启动 IgH master。
|
||||
|
||||
查看状态:
|
||||
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
add_subdirectory(curves)
|
||||
|
||||
add_subdirectory(common/base/logging)
|
||||
link_libraries(cmvr_es::logging)
|
||||
|
||||
add_subdirectory(environment)
|
||||
add_subdirectory(common)
|
||||
add_subdirectory(hardware)
|
||||
add_subdirectory(curves)
|
||||
add_subdirectory(environment)
|
||||
add_subdirectory(algorithms)
|
||||
add_subdirectory(simulate)
|
||||
add_subdirectory(devices)
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
@ -6,20 +5,15 @@
|
||||
#include <fstream>
|
||||
#include <initializer_list>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <pinocchio/fwd.hpp>
|
||||
#include <coal/shape/geometric_shapes.h>
|
||||
#include <gtest/gtest.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "algorithms/collision_detection/include/distance_sampling_policy.h"
|
||||
#include "algorithms/collision_detection/include/collision_checker.h"
|
||||
#include "cmvr/config/self_collision_task_config/self_collision_task_config.pb.h"
|
||||
#include "common/io/proto_file_io.h"
|
||||
#include "common/types/arm/arm_types.h"
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
@ -465,183 +459,6 @@ TEST(CollisionCheckerTest, LoadsRightArmFromDualArmUrdf)
|
||||
EXPECT_TRUE(result.second.rfind("L_", 0) != 0);
|
||||
}
|
||||
|
||||
TEST(CollisionCheckerTest, XiaozhaoSourceKinematicsAndGeneratedGeometrySelectOnlyRequestedArm)
|
||||
{
|
||||
const std::string model_root = std::string(CMVR_ES_SOURCE_DIR) + "/model/xiaozhao/";
|
||||
for (const std::string side : {"left", "right"}) {
|
||||
SCOPED_TRACE(side);
|
||||
RobotModel model;
|
||||
std::set<std::string> expected_links{"base_link"};
|
||||
for (int joint = 1; joint <= 7; ++joint) {
|
||||
model.joint_names.push_back("joint" + std::to_string(joint) + "-" + side);
|
||||
expected_links.insert("link" + std::to_string(joint) + "-" + side);
|
||||
}
|
||||
const auto selected_joints = model.joint_names;
|
||||
ASSERT_TRUE(model.loadUrdf(model_root + "urdf/xiaozhao.urdf"));
|
||||
ASSERT_TRUE(model.loadCollisionGeometry(
|
||||
model_root + "collision/xiaozhao_collision.urdf"));
|
||||
EXPECT_EQ(model.joint_names, selected_joints);
|
||||
EXPECT_EQ(model.dof, 7U);
|
||||
|
||||
CollisionChecker checker;
|
||||
std::string error;
|
||||
ASSERT_TRUE(checker.init(model, selected_joints, {}, &error)) << error;
|
||||
EXPECT_EQ(checker.jointNames(), selected_joints);
|
||||
EXPECT_EQ(checker.dof(), 7U);
|
||||
EXPECT_GT(checker.activePairCount(), 0U);
|
||||
|
||||
const auto bodies = checker.collisionBodies(std::vector<double>(7, 0.0));
|
||||
std::set<std::string> selected_links;
|
||||
for (const auto& body : bodies) {
|
||||
ASSERT_NE(body.geometry, nullptr);
|
||||
EXPECT_TRUE(body.position.allFinite());
|
||||
EXPECT_TRUE(body.orientation.coeffs().allFinite());
|
||||
selected_links.insert(body.link_name);
|
||||
const bool is_link2 = body.link_name == "link2-" + side;
|
||||
if (is_link2 || body.link_name == "link4-" + side) {
|
||||
ASSERT_EQ(body.geometry->getNodeType(), coal::GEOM_CYLINDER);
|
||||
const auto& cylinder = static_cast<const coal::Cylinder&>(*body.geometry);
|
||||
if (is_link2) {
|
||||
EXPECT_NEAR(cylinder.radius, side == "left" ? 0.0410593 : 0.04152965, 1e-6);
|
||||
EXPECT_NEAR(2.0 * cylinder.halfLength, 0.155, 1e-6);
|
||||
} else {
|
||||
EXPECT_NEAR(cylinder.radius, side == "left" ? 0.04156748 : 0.04203374, 1e-6);
|
||||
EXPECT_NEAR(2.0 * cylinder.halfLength, 0.12400011, 1e-6);
|
||||
}
|
||||
// At zero, the local Y axes of joints 2 and 4 are parallel to base Y.
|
||||
const Eigen::Vector3d axis = body.orientation * Eigen::Vector3d::UnitZ();
|
||||
EXPECT_NEAR(std::abs(axis.y()), 1.0, 1e-9);
|
||||
}
|
||||
if (body.link_name == "link5-" + side) {
|
||||
EXPECT_EQ(body.geometry->getNodeType(), coal::GEOM_BOX);
|
||||
}
|
||||
}
|
||||
const auto piece_count = [&](const std::string& link) {
|
||||
return std::count_if(bodies.begin(), bodies.end(), [&](const auto& body) {
|
||||
return body.link_name == link;
|
||||
});
|
||||
};
|
||||
EXPECT_EQ(piece_count("link2-" + side), 1);
|
||||
EXPECT_EQ(piece_count("link4-" + side), 1);
|
||||
EXPECT_EQ(piece_count("link5-" + side), 3);
|
||||
// Root geometry participates, but the opposite arm, moving neck and
|
||||
// geometry-free TCP frames must not enter this single-arm query.
|
||||
EXPECT_EQ(selected_links, expected_links);
|
||||
for (const auto& link : std::vector<std::string>{
|
||||
"base_link", "link7-" + side}) {
|
||||
EXPECT_GT(piece_count(link), 1) << "Expected multiple collision pieces for " << link;
|
||||
}
|
||||
const auto result = checker.check(bodies);
|
||||
ASSERT_TRUE(result.valid) << result.error;
|
||||
EXPECT_TRUE(std::isfinite(result.minimum_distance_m));
|
||||
EXPECT_EQ(expected_links.count(result.first), 1U);
|
||||
EXPECT_EQ(expected_links.count(result.second), 1U);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CollisionCheckerTest, XiaozhaoWristBoxesAndConfiguredPairExclusions)
|
||||
{
|
||||
const std::string path = std::string(CMVR_ES_SOURCE_DIR) +
|
||||
"/model/xiaozhao/collision/xiaozhao_collision.urdf";
|
||||
for (const std::string side : {"left", "right"}) {
|
||||
SCOPED_TRACE(side);
|
||||
std::vector<std::string> joints;
|
||||
for (int joint = 1; joint <= 7; ++joint) {
|
||||
joints.push_back("joint" + std::to_string(joint) + "-" + side);
|
||||
}
|
||||
CollisionChecker checker;
|
||||
std::string error;
|
||||
ASSERT_TRUE(checker.init(path, joints, {}, &error)) << error;
|
||||
const std::string wrist = "link5-" + side;
|
||||
const std::string hand = "link7-" + side;
|
||||
const auto isolated_wrist_bodies = [&](const std::vector<double>& q) {
|
||||
auto bodies = checker.collisionBodies(q);
|
||||
// Preserve the actual FK and all pieces of both wrist links. Move
|
||||
// every other geometry far apart so shoulder padding cannot mask
|
||||
// wrist regressions.
|
||||
for (std::size_t index = 0; index < bodies.size(); ++index) {
|
||||
auto& body = bodies[index];
|
||||
if (body.link_name != wrist && body.link_name != hand) {
|
||||
body.position = Eigen::Vector3d(
|
||||
10.0 * static_cast<double>(index + 1), 10.0, 10.0);
|
||||
}
|
||||
}
|
||||
return bodies;
|
||||
};
|
||||
const auto is_wrist_pair = [&](const CollisionResult& result) {
|
||||
return (result.first == wrist && result.second == hand) ||
|
||||
(result.first == hand && result.second == wrist);
|
||||
};
|
||||
|
||||
// Preserve the physical all-zero pose from before the J3/J5 origins
|
||||
// gained pi. This is a geometry reference, not a motion target or a
|
||||
// claim that the new all-zero pose (or the whole robot) is collision-free.
|
||||
const double pi = std::acos(-1.0);
|
||||
const std::vector<double> historical_zero{0.0, 0.0, pi, 0.0, pi, 0.0, 0.0};
|
||||
const auto historical = checker.check(isolated_wrist_bodies(historical_zero));
|
||||
ASSERT_TRUE(historical.valid) << historical.error;
|
||||
EXPECT_TRUE(is_wrist_pair(historical));
|
||||
EXPECT_TRUE(std::isfinite(historical.minimum_distance_m));
|
||||
|
||||
if (side == "right") {
|
||||
// Merging the inner supports and outer cheeks closes the historical
|
||||
// gap. Keep the overlap within the 1 mm fitting margin.
|
||||
EXPECT_GE(historical.minimum_distance_m, -0.001);
|
||||
|
||||
// Frozen reference: original STL triangle queries independently
|
||||
// confirmed wrist interference here. Do not read task config;
|
||||
// choosing a new touch initialization must not invalidate this test.
|
||||
// J3/J5 use new coordinates: q_new = wrap(q_old - pi).
|
||||
const std::vector<double> known_interference{
|
||||
1.8648861126, 0.8084619160, 2.727417567789793, 1.6622227972,
|
||||
1.810335360989793, -0.2423592867, -1.0088169947,
|
||||
};
|
||||
const auto full = checker.check(known_interference);
|
||||
ASSERT_TRUE(full.valid) << full.error;
|
||||
EXPECT_TRUE(full.in_collision);
|
||||
|
||||
const auto isolated = checker.check(isolated_wrist_bodies(known_interference));
|
||||
ASSERT_TRUE(isolated.valid) << isolated.error;
|
||||
EXPECT_TRUE(is_wrist_pair(isolated));
|
||||
EXPECT_TRUE(isolated.in_collision);
|
||||
EXPECT_TRUE(std::isfinite(isolated.minimum_distance_m));
|
||||
EXPECT_LE(isolated.minimum_distance_m, 0.0);
|
||||
}
|
||||
|
||||
const auto root = std::filesystem::path(CMVR_ES_SOURCE_DIR);
|
||||
const auto task_path = root / "cmvr-es/config/tasks/self_collision_task" /
|
||||
("self_collision_task_xiaozhao_" + side + ".pb.txt");
|
||||
config::SelfCollisionTaskRootConfig task;
|
||||
ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(task_path.string(), &task));
|
||||
auto config = task.self_collision_task().checker();
|
||||
config.set_urdf_path((root / config.urdf_path()).string());
|
||||
CollisionChecker filtered;
|
||||
ASSERT_TRUE(filtered.init(config, joints, &error)) << error;
|
||||
const auto filtered_zero = filtered.check(isolated_wrist_bodies(historical_zero));
|
||||
ASSERT_TRUE(filtered_zero.valid) << filtered_zero.error;
|
||||
EXPECT_FALSE(filtered_zero.in_collision);
|
||||
EXPECT_FALSE(is_wrist_pair(filtered_zero));
|
||||
|
||||
std::vector<double> bent_wrist(7, 0.0);
|
||||
bent_wrist[5] = side == "left" ? 0.45 : -0.45;
|
||||
const auto bodies = isolated_wrist_bodies(bent_wrist);
|
||||
const auto raw = checker.check(bodies);
|
||||
ASSERT_TRUE(raw.valid) << raw.error;
|
||||
ASSERT_TRUE(is_wrist_pair(raw));
|
||||
ASSERT_TRUE(raw.in_collision);
|
||||
const auto monitored = filtered.check(bodies);
|
||||
ASSERT_TRUE(monitored.valid) << monitored.error;
|
||||
EXPECT_FALSE(monitored.in_collision);
|
||||
EXPECT_FALSE(is_wrist_pair(monitored));
|
||||
const auto piece_count = [&](const std::string& link) {
|
||||
return std::count_if(bodies.begin(), bodies.end(),
|
||||
[&](const auto& body) { return body.link_name == link; });
|
||||
};
|
||||
EXPECT_EQ(checker.activePairCount() - filtered.activePairCount(),
|
||||
piece_count(wrist) * piece_count(hand));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CollisionCheckerTest, RejectsWrongJointVectorSize)
|
||||
{
|
||||
CollisionChecker checker;
|
||||
|
||||
@ -78,15 +78,6 @@ 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_;
|
||||
|
||||
@ -160,15 +160,6 @@ 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() ||
|
||||
@ -346,157 +337,6 @@ 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) {
|
||||
@ -527,19 +367,15 @@ 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_);
|
||||
@ -548,15 +384,51 @@ namespace cmvr {
|
||||
MatrixXd A_cost;
|
||||
VectorXd b_cost;
|
||||
|
||||
for (int iter = 0; iter < max_iters_ && error.allFinite() && error.norm() >= tol_; ++iter) {
|
||||
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_);
|
||||
|
||||
// 2) 构造代价:|| A_cost * dq - b_cost ||^2
|
||||
constexpr Eigen::Index n_eq = 6;
|
||||
constexpr std::size_t n_eq = 6;
|
||||
A_cost.resize(n_eq + chain_q_dof_, chain_q_dof_);
|
||||
b_cost.resize(n_eq + chain_q_dof_);
|
||||
|
||||
// 任务部分
|
||||
A_cost.topRows(n_eq) = poseJacobianAt_(q_full, target_frame_id);
|
||||
b_cost.head(n_eq) = error;
|
||||
A_cost.block(0, 0, 6, chain_q_dof_) = J;
|
||||
b_cost.segment(0, 6) = dx;
|
||||
|
||||
// 阻尼项
|
||||
A_cost.bottomRows(chain_q_dof_) = std::sqrt(lambda_) *
|
||||
@ -603,18 +475,24 @@ namespace cmvr {
|
||||
q_local = cmvr::kinematics::clampToJointPositionLimits(q_local, q_min, q_max);
|
||||
q_full.segment(chain_q_start_, chain_q_dof_) = q_local;
|
||||
|
||||
error = weightedPoseError_(poseErrorAt_(q_full, target_frame_id, base_M_target));
|
||||
if (dq_local.norm() < 1e-6) break;
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
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_);
|
||||
}
|
||||
// 未收敛,返回 best effort
|
||||
cur_joints_angle_.assign(q_local.data(), q_local.data() + q_local.size());
|
||||
joints_angle = cur_joints_angle_;
|
||||
return converged;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool PinocchioQpIKSolver::solveVelocityBase(
|
||||
|
||||
@ -6,7 +6,6 @@
|
||||
#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"
|
||||
@ -45,23 +44,6 @@ 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);
|
||||
@ -484,90 +466,5 @@ 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
|
||||
|
||||
@ -31,7 +31,7 @@ namespace cmvr::perception {
|
||||
* - `t`:AprilTag 自身坐标系,原点位于 tag 中心,z 轴垂直于 tag 平面。
|
||||
*
|
||||
* 使用约定:
|
||||
* - 每周期调用一次 `update()` 或 `updateFromRgbFrame()`;
|
||||
* - 每周期调用一次 `update()`;
|
||||
* - 其他模块(如 `TagRelativeTarget3D` / `IbvsController`)只读取缓存,不重复抓帧。
|
||||
*/
|
||||
class AprilTagPerception {
|
||||
@ -70,9 +70,6 @@ public:
|
||||
|
||||
// 抓取编码帧时传入相机驱动的索引。
|
||||
size_t encoded_index{0};
|
||||
|
||||
// Raw RGB acquisition timing, independent of any encoded frame request.
|
||||
bool capture_rgb_timing{false};
|
||||
};
|
||||
|
||||
struct Tag {
|
||||
@ -115,11 +112,9 @@ public:
|
||||
// `visp_I` 当前缓存的图像高度。
|
||||
int visp_h{0};
|
||||
|
||||
// 本类内部维护的帧序号,每次更新成功后自增。
|
||||
// 本类内部维护的帧序号,每次 `update()` 成功后自增。
|
||||
uint64_t frame_id{0};
|
||||
|
||||
device::RgbFrameTiming rgb_timing;
|
||||
|
||||
void clearDerived() {
|
||||
gray.release();
|
||||
has_gray = false;
|
||||
@ -143,17 +138,12 @@ 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 家族类型。
|
||||
@ -167,15 +157,7 @@ public:
|
||||
bool update(const Options& opt);
|
||||
|
||||
/**
|
||||
* @brief 在已有的彩色帧上检测 AprilTag,无需相机对象。
|
||||
* @param color 灰度、BGR 或 BGRA 图像。缓存共享像素数据,调用方需保持帧内容不变。
|
||||
* @param intrinsics 与该帧尺寸对应的相机内参。
|
||||
* @return 成功检测到至少一个标签时返回 `true`。
|
||||
*/
|
||||
bool updateFromRgbFrame(const cv::Mat& color, const device::Rs2Intrinsics& intrinsics);
|
||||
|
||||
/**
|
||||
* @brief 获取最近一次更新的状态。
|
||||
* @brief 获取最近一次 `update()` 的状态。
|
||||
* @return 最近一次状态枚举。
|
||||
*/
|
||||
Status lastStatus() const { return last_status_; }
|
||||
@ -233,10 +215,6 @@ 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 本次更新使用的抓帧选项。
|
||||
@ -283,9 +261,8 @@ private:
|
||||
// AprilTag 检测器。
|
||||
vpDetectorAprilTag detector_{vpDetectorAprilTag::TAG_36h11};
|
||||
|
||||
// 默认和按 ID 配置的 tag 物理边长,单位米。
|
||||
// tag 物理边长,单位米。
|
||||
double tag_size_m_{0.12};
|
||||
std::unordered_map<int, double> tag_sizes_by_id_;
|
||||
|
||||
// 与当前内参对应的 ViSP 相机模型。
|
||||
vpCameraParameters visp_cam_;
|
||||
@ -299,7 +276,7 @@ private:
|
||||
// tag id 到 `tags_` 下标的映射。
|
||||
std::unordered_map<int, size_t> id_to_index_;
|
||||
|
||||
// 最近一次更新的状态。
|
||||
// 最近一次 `update()` 的状态。
|
||||
Status last_status_{Status::NO_NEW_FRAME};
|
||||
};
|
||||
|
||||
|
||||
@ -4,10 +4,9 @@
|
||||
|
||||
#include "algorithms/perception/apriltag/include/apriltag_perception.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
|
||||
#include <opencv2/imgproc.hpp>
|
||||
|
||||
@ -20,8 +19,10 @@ AprilTagPerception::AprilTagPerception(const std::shared_ptr<cmvr::device::Abstr
|
||||
|
||||
void AprilTagPerception::setCamera(const std::shared_ptr<cmvr::device::AbstractCamera>& camera) {
|
||||
camera_ = camera;
|
||||
clearFrameResults();
|
||||
tags_.clear();
|
||||
id_to_index_.clear();
|
||||
frame_.stream = device::StreamFrameData{};
|
||||
frame_.clearDerived();
|
||||
frame_.frame_id = 0;
|
||||
last_status_ = Status::NO_NEW_FRAME;
|
||||
}
|
||||
@ -32,12 +33,6 @@ 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);
|
||||
@ -58,28 +53,14 @@ 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 = {};
|
||||
}
|
||||
|
||||
bool AprilTagPerception::processFrame(const Options& opt) {
|
||||
if (!grabFrame(opt)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// intrinsics -> visp camera params
|
||||
const double fx = static_cast<double>(frame_.stream.intrinsics.fx);
|
||||
const double fy = static_cast<double>(frame_.stream.intrinsics.fy);
|
||||
@ -128,18 +109,9 @@ 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) {
|
||||
read_rgb();
|
||||
camera_->getRGBImage(frame_.stream.rgbImage, frame_.stream.intrinsics);
|
||||
} else {
|
||||
camera_->getRGBDImages(frame_.stream.rgbImage, frame_.stream.depthImage, frame_.stream.intrinsics);
|
||||
}
|
||||
@ -147,7 +119,7 @@ bool AprilTagPerception::grabFrame(const Options& opt) {
|
||||
// PREFER: 允许回退 RGB
|
||||
if (opt.depth_policy == DepthPolicy::PREFER) {
|
||||
try {
|
||||
read_rgb();
|
||||
camera_->getRGBImage(frame_.stream.rgbImage, frame_.stream.intrinsics);
|
||||
frame_.stream.depthImage.release();
|
||||
} catch (...) {
|
||||
last_status_ = Status::NO_NEW_FRAME;
|
||||
@ -159,7 +131,15 @@ bool AprilTagPerception::grabFrame(const Options& opt) {
|
||||
}
|
||||
}
|
||||
|
||||
if (!validateColorFrame()) {
|
||||
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;
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -175,20 +155,6 @@ 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;
|
||||
@ -262,24 +228,27 @@ bool AprilTagPerception::ensureVispImage() {
|
||||
}
|
||||
|
||||
bool AprilTagPerception::detectTags() {
|
||||
if (!detector_.detect(frame_.visp_I)) {
|
||||
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()) {
|
||||
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(tag_ids.size());
|
||||
for (size_t i = 0; i < tag_ids.size(); ++i) {
|
||||
tags_.reserve(n);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
Tag t;
|
||||
t.id = tag_ids[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);
|
||||
t.cMo = cMo_vec[i];
|
||||
t.T_c_t = toEigen4(cMo_vec[i]);
|
||||
|
||||
double w = 1.0;
|
||||
if (i < margins.size() && std::isfinite(margins[i]) && margins[i] > 0.0f) {
|
||||
@ -291,8 +260,8 @@ bool AprilTagPerception::detectTags() {
|
||||
tags_.push_back(t);
|
||||
}
|
||||
|
||||
last_status_ = tags_.empty() ? Status::NO_TAG : Status::OK;
|
||||
return !tags_.empty();
|
||||
last_status_ = Status::OK;
|
||||
return true;
|
||||
}
|
||||
|
||||
const AprilTagPerception::Tag* AprilTagPerception::findTag(int id) const {
|
||||
|
||||
@ -10,8 +10,6 @@
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
using ::cmvr::JointLimit;
|
||||
using ::cmvr::RobotModel;
|
||||
|
||||
enum class ArmErrorCode {
|
||||
OK = 0,
|
||||
@ -104,14 +102,12 @@ struct JointGroupState {
|
||||
std::vector<double> position;
|
||||
std::vector<double> velocity;
|
||||
std::vector<double> effort;
|
||||
std::vector<double> current;
|
||||
|
||||
bool validForModel(const RobotModel& model) const
|
||||
{
|
||||
return position.size() == model.dof &&
|
||||
velocity.size() == model.dof &&
|
||||
(effort.empty() || effort.size() == model.dof) &&
|
||||
(current.empty() || current.size() == model.dof);
|
||||
(effort.empty() || effort.size() == model.dof);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
-----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-----
|
||||
@ -1,5 +1,5 @@
|
||||
cmvr_es {
|
||||
logger_config_file: "logger/logger.pb.txt"
|
||||
device_manager_config_file: "manager/real_device_manager.pb.txt"
|
||||
device_manager_config_file: "manager/device_manager.pb.txt"
|
||||
task_manager_config_file: "manager/task_manager.pb.txt"
|
||||
}
|
||||
|
||||
@ -20,7 +20,7 @@ agv {
|
||||
port_push: 19301
|
||||
recv_timeout_ms: 1000
|
||||
control_nick_name: "cmvr-es"
|
||||
enable_state_push: false
|
||||
enable_state_push: true
|
||||
state_push_interval_ms: 200
|
||||
state_push_included_fields: "x"
|
||||
state_push_included_fields: "y"
|
||||
|
||||
351
cmvr-es/config/devices/arm/arm.pb.txt
Normal file
351
cmvr-es/config/devices/arm/arm.pb.txt
Normal file
@ -0,0 +1,351 @@
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "right_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "right_arm_can_motors"
|
||||
motor_group_ids: "right_arm_can_motors"
|
||||
dof: 7
|
||||
joint_names: "R_SHOULDER_P"
|
||||
joint_names: "R_SHOULDER_R"
|
||||
joint_names: "R_SHOULDER_Y"
|
||||
joint_names: "R_ELBOW_R"
|
||||
joint_names: "R_WRIST_P"
|
||||
joint_names: "R_WRIST_Y"
|
||||
joint_names: "R_WRIST_R"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 1.0
|
||||
default_acc: 2.0
|
||||
}
|
||||
|
||||
kinematics {
|
||||
pinocchio_dls_ik_solver {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
base_frame_name: "PELVIS_S"
|
||||
flange_frame_name: "R_WRIST_R_S"
|
||||
tcp_frame_name: "R_FINGER_TIP_FIXED"
|
||||
max_iters: 100
|
||||
pos_eps: 1e-6
|
||||
rot_eps: 1e-6
|
||||
damping: 1e-6
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
gain: 0.2
|
||||
margin_ratio: 0.15
|
||||
max_push: 0.25
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
|
||||
settle_position_tolerance_rad: 0.002
|
||||
# MoveJ 完成时允许的最大关节速度,单位为弧度/秒。
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 45.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 45.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.55
|
||||
linear_acceleration_max: 5.0
|
||||
linear_jerk_max: 10.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 30.0
|
||||
max_joint_acceleration_rad_s2: 10000.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 5.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 5.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 10
|
||||
# 等待 Cartesian 速度运动停止的最长时间,单位为秒。
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
robot_arms {
|
||||
id: "left_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "left_arm_can_motors"
|
||||
motor_group_ids: "left_arm_can_motors"
|
||||
dof: 7
|
||||
joint_names: "L_SHOULDER_P"
|
||||
joint_names: "L_SHOULDER_R"
|
||||
joint_names: "L_SHOULDER_Y"
|
||||
joint_names: "L_ELBOW_R"
|
||||
joint_names: "L_WRIST_P"
|
||||
joint_names: "L_WRIST_Y"
|
||||
joint_names: "L_WRIST_R"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 1.0
|
||||
default_acc: 2.0
|
||||
}
|
||||
|
||||
kinematics {
|
||||
pinocchio_dls_ik_solver {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
base_frame_name: "PELVIS_S"
|
||||
flange_frame_name: "L_WRIST_R_S"
|
||||
tcp_frame_name: "L_FINGER_TIP_FIXED"
|
||||
max_iters: 100
|
||||
pos_eps: 1e-6
|
||||
rot_eps: 1e-6
|
||||
damping: 1e-6
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "L_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
gain: 0.2
|
||||
margin_ratio: 0.15
|
||||
max_push: 0.25
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 45.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 45.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.55
|
||||
linear_acceleration_max: 5.0
|
||||
linear_jerk_max: 10.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 30.0
|
||||
max_joint_acceleration_rad_s2: 10000.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 5.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 5.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 10
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
182
cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt
Normal file
182
cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt
Normal file
@ -0,0 +1,182 @@
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "mujoco_right_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "right_arm_mujoco_motors"
|
||||
motor_group_ids: "right_arm_mujoco_motors"
|
||||
dof: 7
|
||||
joint_names: "right_arm_J1"
|
||||
joint_names: "right_arm_J2"
|
||||
joint_names: "right_arm_J3"
|
||||
joint_names: "right_arm_J4"
|
||||
joint_names: "right_arm_J5"
|
||||
joint_names: "right_arm_J6"
|
||||
joint_names: "right_arm_J7"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 0.6
|
||||
default_acc: 2.0
|
||||
}
|
||||
|
||||
kinematics {
|
||||
pinocchio_dls_ik_solver {
|
||||
urdf_path: "model/gen2/robot.urdf"
|
||||
base_frame_name: "body_link"
|
||||
flange_frame_name: "arm_link_7_2"
|
||||
max_iters: 200
|
||||
pos_eps: 1e-6
|
||||
rot_eps: 1e-6
|
||||
damping: 1e-5
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "right_arm_J1" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J2" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J3" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J4" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J5" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J6" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J7" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
gain: 0.2
|
||||
margin_ratio: 0.15
|
||||
max_push: 0.25
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/gen2/collision/robot_collision.urdf"
|
||||
ignored_pairs { first: "arm_link_5_2" second: "arm_link_7_2" }
|
||||
ignored_pairs { first: "body_link" second: "arm_link_2_2" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
|
||||
settle_position_tolerance_rad: 0.002
|
||||
# MoveJ 完成时允许的最大关节速度,单位为弧度/秒。
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 4.0
|
||||
max_joint_acceleration_rad_s2: 100.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.5
|
||||
linear_acceleration_max: 2.0
|
||||
linear_jerk_max: 10.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 4.0
|
||||
max_joint_acceleration_rad_s2: 100.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 0.01
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 2.0
|
||||
# 等待 Cartesian 速度运动停止的最长时间,单位为秒。
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
184
cmvr-es/config/devices/arm/arm_mujoco.pb.txt
Normal file
184
cmvr-es/config/devices/arm/arm_mujoco.pb.txt
Normal file
@ -0,0 +1,184 @@
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "mujoco_right_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "right_arm_mujoco_motors"
|
||||
motor_group_ids: "right_arm_mujoco_motors"
|
||||
dof: 7
|
||||
joint_names: "R_SHOULDER_P"
|
||||
joint_names: "R_SHOULDER_R"
|
||||
joint_names: "R_SHOULDER_Y"
|
||||
joint_names: "R_ELBOW_R"
|
||||
joint_names: "R_WRIST_P"
|
||||
joint_names: "R_WRIST_Y"
|
||||
joint_names: "R_WRIST_R"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 1.0
|
||||
default_acc: 2.0
|
||||
}
|
||||
|
||||
kinematics {
|
||||
pinocchio_dls_ik_solver {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
base_frame_name: "PELVIS_S"
|
||||
flange_frame_name: "R_WRIST_R_S"
|
||||
tcp_frame_name: "R_FINGER_TIP_FIXED"
|
||||
max_iters: 100
|
||||
pos_eps: 1e-6
|
||||
rot_eps: 1e-6
|
||||
damping: 1e-6
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 100.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
gain: 0.2
|
||||
margin_ratio: 0.15
|
||||
max_push: 0.25
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# 轨迹关节位置限位检查的数值容差,单位 rad;0 表示严格检查。
|
||||
joint_limit_tolerance_rad: 0.00001
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
|
||||
settle_position_tolerance_rad: 0.002
|
||||
# MoveJ 完成时允许的最大关节速度,单位为弧度/秒。
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 5.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 5.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 2.0
|
||||
linear_acceleration_max: 15.0
|
||||
linear_jerk_max: 60.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 5.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 5.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 10
|
||||
# 等待 Cartesian 速度运动停止的最长时间,单位为秒。
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
183
cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt
Normal file
183
cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt
Normal file
@ -0,0 +1,183 @@
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "mujoco_right_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "right_arm_mujoco_motors"
|
||||
motor_group_ids: "right_arm_mujoco_motors"
|
||||
dof: 7
|
||||
joint_names: "R_SHOULDER_P"
|
||||
joint_names: "R_SHOULDER_R"
|
||||
joint_names: "R_SHOULDER_Y"
|
||||
joint_names: "R_ELBOW_R"
|
||||
joint_names: "R_WRIST_P"
|
||||
joint_names: "R_WRIST_Y"
|
||||
joint_names: "R_WRIST_R"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 1.0
|
||||
default_acc: 2.0
|
||||
}
|
||||
|
||||
kinematics {
|
||||
pinocchio_qp_ik_solver {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
base_frame_name: "PELVIS_S"
|
||||
flange_frame_name: "R_WRIST_R_S"
|
||||
tcp_frame_name: "R_FINGER_TIP_FIXED"
|
||||
lambda: 1e-4
|
||||
w_posrot: 0.5
|
||||
max_iters: 100
|
||||
tol: 1e-6
|
||||
qp_time_limit: 1e-2
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 100.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
gain: 0.2
|
||||
margin_ratio: 0.01
|
||||
max_push: 0.02
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
|
||||
settle_position_tolerance_rad: 0.002
|
||||
# MoveJ 完成时允许的最大关节速度,单位为弧度/秒。
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 5.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 5.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 2.0
|
||||
linear_acceleration_max: 15.0
|
||||
linear_jerk_max: 500.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.005
|
||||
line_deviation_stop_m: 0.005
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 20.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 20.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 5
|
||||
# 等待 Cartesian 速度运动停止的最长时间,单位为秒。
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
183
cmvr-es/config/devices/arm/arm_qp.pb.txt
Normal file
183
cmvr-es/config/devices/arm/arm_qp.pb.txt
Normal file
@ -0,0 +1,183 @@
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "right_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "right_arm_can_motors"
|
||||
motor_group_ids: "right_arm_can_motors"
|
||||
dof: 7
|
||||
joint_names: "R_SHOULDER_P"
|
||||
joint_names: "R_SHOULDER_R"
|
||||
joint_names: "R_SHOULDER_Y"
|
||||
joint_names: "R_ELBOW_R"
|
||||
joint_names: "R_WRIST_P"
|
||||
joint_names: "R_WRIST_Y"
|
||||
joint_names: "R_WRIST_R"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 1.0
|
||||
default_acc: 2.0
|
||||
}
|
||||
|
||||
kinematics {
|
||||
pinocchio_qp_ik_solver {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
base_frame_name: "PELVIS_S"
|
||||
flange_frame_name: "R_WRIST_R_S"
|
||||
tcp_frame_name: "R_FINGER_TIP_FIXED"
|
||||
lambda: 1e-4
|
||||
w_posrot: 0.5
|
||||
max_iters: 100
|
||||
tol: 1e-6
|
||||
qp_time_limit: 1e-2
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 100.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
gain: 0.2
|
||||
margin_ratio: 0.01
|
||||
max_push: 0.02
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
|
||||
settle_position_tolerance_rad: 0.01
|
||||
# MoveJ 完成时允许的最大关节速度,单位为弧度/秒。
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 45.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 45.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.8
|
||||
linear_acceleration_max: 10.0
|
||||
linear_jerk_max: 200.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 30.0
|
||||
max_joint_acceleration_rad_s2: 10000.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 70
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 70
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 5
|
||||
# 等待 Cartesian 速度运动停止的最长时间,单位为秒。
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
351
cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt
Normal file
351
cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt
Normal file
@ -0,0 +1,351 @@
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "right_ethercat_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "right_arm_ethercat_motors"
|
||||
motor_group_ids: "right_arm_ethercat_motors"
|
||||
dof: 7
|
||||
joint_names: "R_SHOULDER_P"
|
||||
joint_names: "R_SHOULDER_R"
|
||||
joint_names: "R_SHOULDER_Y"
|
||||
joint_names: "R_ELBOW_R"
|
||||
joint_names: "R_WRIST_P"
|
||||
joint_names: "R_WRIST_Y"
|
||||
joint_names: "R_WRIST_R"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 1.0
|
||||
default_acc: 2.0
|
||||
}
|
||||
|
||||
kinematics {
|
||||
pinocchio_dls_ik_solver {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
base_frame_name: "PELVIS_S"
|
||||
flange_frame_name: "R_WRIST_R_S"
|
||||
tcp_frame_name: "R_FINGER_TIP_FIXED"
|
||||
max_iters: 100
|
||||
pos_eps: 1e-6
|
||||
rot_eps: 1e-6
|
||||
damping: 1e-6
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
gain: 0.2
|
||||
margin_ratio: 0.15
|
||||
max_push: 0.25
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
|
||||
settle_timeout_s: 2.0
|
||||
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
|
||||
settle_position_tolerance_rad: 0.002
|
||||
# MoveJ 完成时允许的最大关节速度,单位为弧度/秒。
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
# 位置和速度连续满足条件的采样次数。
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 45.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 45.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.55
|
||||
linear_acceleration_max: 5.0
|
||||
linear_jerk_max: 10.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 30.0
|
||||
max_joint_acceleration_rad_s2: 10000.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 5.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 5.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 10
|
||||
# 等待 Cartesian 速度运动停止的最长时间,单位为秒。
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
robot_arms {
|
||||
id: "left_ethercat_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "dual_arm_ethercat_motors"
|
||||
motor_group_ids: "dual_arm_ethercat_motors"
|
||||
dof: 7
|
||||
joint_names: "L_SHOULDER_P"
|
||||
joint_names: "L_SHOULDER_R"
|
||||
joint_names: "L_SHOULDER_Y"
|
||||
joint_names: "L_ELBOW_R"
|
||||
joint_names: "L_WRIST_P"
|
||||
joint_names: "L_WRIST_Y"
|
||||
joint_names: "L_WRIST_R"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 1.0
|
||||
default_acc: 2.0
|
||||
}
|
||||
|
||||
kinematics {
|
||||
pinocchio_dls_ik_solver {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
base_frame_name: "PELVIS_S"
|
||||
flange_frame_name: "L_WRIST_R_S"
|
||||
tcp_frame_name: "L_FINGER_TIP_FIXED"
|
||||
max_iters: 100
|
||||
pos_eps: 1e-6
|
||||
rot_eps: 1e-6
|
||||
damping: 1e-6
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "L_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "L_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
gain: 0.2
|
||||
margin_ratio: 0.15
|
||||
max_push: 0.25
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
|
||||
ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 10.0
|
||||
max_joint_acceleration_rad_s2: 5000.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 45.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 45.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.55
|
||||
linear_acceleration_max: 5.0
|
||||
linear_jerk_max: 10.0
|
||||
angular_velocity_max: 1.0
|
||||
angular_acceleration_max: 5.0
|
||||
angular_jerk_max: 12.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
|
||||
# 关闭此开关不影响失解后的制动。
|
||||
enable: true
|
||||
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
|
||||
lookahead_s: 0.15
|
||||
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
|
||||
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.01
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 30.0
|
||||
max_joint_acceleration_rad_s2: 10000.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 5.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 5.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 10
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,29 +0,0 @@
|
||||
# Joint-only minimal configuration; MoveJ follows joint_names order.
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "lingkong_arm"
|
||||
motor {
|
||||
motor_system_id: "lingkong_can_motors"
|
||||
motor_group_ids: "lingkong_can_motors"
|
||||
dof: 3
|
||||
joint_names: "MG4005E_AXIS_1"
|
||||
joint_names: "MG4005E_AXIS_2"
|
||||
joint_names: "MG4005E_AXIS_3"
|
||||
upd_freq: 50
|
||||
}
|
||||
motion {
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.02
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.1
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
settle_timeout_s: 2.0
|
||||
settle_position_tolerance_rad: 0.002
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
35
cmvr-es/config/devices/arm/tchl_arm.pb.txt
Normal file
35
cmvr-es/config/devices/arm/tchl_arm.pb.txt
Normal file
@ -0,0 +1,35 @@
|
||||
# 七轴纯关节运动配置;MoveJ 目标向量按 joint_names 的顺序填写。
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "tchl_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "tchl_joint_motors"
|
||||
motor_group_ids: "tchl_joint_motors"
|
||||
dof: 6
|
||||
joint_names: "TCHL_AXIS_1"
|
||||
joint_names: "TCHL_AXIS_2"
|
||||
joint_names: "TCHL_AXIS_3"
|
||||
joint_names: "TCHL_AXIS_4"
|
||||
joint_names: "TCHL_AXIS_5"
|
||||
joint_names: "TCHL_AXIS_6"
|
||||
upd_freq: 1000
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
|
||||
move_j {
|
||||
settle_timeout_s: 2.0
|
||||
settle_position_tolerance_rad: 0.002
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,30 +0,0 @@
|
||||
# Joint-only minimal configuration; MoveJ follows joint_names order.
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "xiaozhao_lingkong_neck"
|
||||
motor {
|
||||
motor_system_id: "xiaozhao_linkong_motors"
|
||||
motor_group_ids: "lingkong_mixed_v236"
|
||||
motor_group_ids: "lingkong_mixed_v238"
|
||||
dof: 3
|
||||
joint_names: "neck-joint1"
|
||||
joint_names: "neck-joint2"
|
||||
joint_names: "neck-joint3"
|
||||
upd_freq: 50
|
||||
}
|
||||
motion {
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.02
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.1
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
settle_timeout_s: 2.0
|
||||
settle_position_tolerance_rad: 0.02
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,331 +0,0 @@
|
||||
# xiaozhao 双臂 MuJoCo 控制,所有关节位置使用 rad。
|
||||
# TCP 与第七连杆同向,局部偏移左 (0.007, 0.23, -0.045) m、右 (0.007, -0.23, -0.045) m。
|
||||
# 两臂分别规划 MoveP,检测本臂与固定基座的碰撞体,最小间距为 20 mm。
|
||||
arm {
|
||||
|
||||
robot_arms {
|
||||
id: "xiaozhao_mujoco_left_arm"
|
||||
motor {
|
||||
motor_system_id: "xiaozhao_mujoco_left_arm_motors"
|
||||
motor_group_ids: "xiaozhao_mujoco_left_arm_motors"
|
||||
dof: 7
|
||||
joint_names: "joint1-left"
|
||||
joint_names: "joint2-left"
|
||||
joint_names: "joint3-left"
|
||||
joint_names: "joint4-left"
|
||||
joint_names: "joint5-left"
|
||||
joint_names: "joint6-left"
|
||||
joint_names: "joint7-left"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 0.5
|
||||
default_acc: 2.0
|
||||
}
|
||||
kinematics {
|
||||
pinocchio_qp_ik_solver {
|
||||
urdf_path: "model/xiaozhao/urdf/xiaozhao.urdf"
|
||||
base_frame_name: "base_link"
|
||||
flange_frame_name: "link7-left"
|
||||
tcp_frame_name: "tcp-left"
|
||||
lambda: 1e-4
|
||||
w_posrot: 0.5
|
||||
max_iters: 100
|
||||
tol: 1e-6
|
||||
qp_time_limit: 1e-2
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
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 }
|
||||
joints { joint_name: "joint4-left" q_lb: 0 q_ub: 2.35 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint5-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint6-left" q_lb: -0.785 q_ub: 0.45 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint7-left" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
|
||||
ignored_pairs { first: "link5-left" second: "link7-left" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
settle_timeout_s: 3.0
|
||||
settle_position_tolerance_rad: 0.002
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 1.0
|
||||
max_joint_acceleration_rad_s2: 5.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.1
|
||||
linear_acceleration_max: 0.5
|
||||
linear_jerk_max: 5.0
|
||||
angular_velocity_max: 0.5
|
||||
angular_acceleration_max: 2.0
|
||||
angular_jerk_max: 10.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
enable: true
|
||||
lookahead_s: 0.15
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 1.0
|
||||
max_joint_acceleration_rad_s2: 5.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 0.01
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 2.0
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
robot_arms {
|
||||
id: "xiaozhao_mujoco_right_arm"
|
||||
motor {
|
||||
motor_system_id: "xiaozhao_mujoco_right_arm_motors"
|
||||
motor_group_ids: "xiaozhao_mujoco_right_arm_motors"
|
||||
dof: 7
|
||||
joint_names: "joint1-right"
|
||||
joint_names: "joint2-right"
|
||||
joint_names: "joint3-right"
|
||||
joint_names: "joint4-right"
|
||||
joint_names: "joint5-right"
|
||||
joint_names: "joint6-right"
|
||||
joint_names: "joint7-right"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 0.5
|
||||
default_acc: 2.0
|
||||
}
|
||||
kinematics {
|
||||
pinocchio_qp_ik_solver {
|
||||
urdf_path: "model/xiaozhao/urdf/xiaozhao.urdf"
|
||||
base_frame_name: "base_link"
|
||||
flange_frame_name: "link7-right"
|
||||
tcp_frame_name: "tcp-right"
|
||||
lambda: 1e-4
|
||||
w_posrot: 0.5
|
||||
max_iters: 100
|
||||
tol: 1e-6
|
||||
qp_time_limit: 1e-2
|
||||
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 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
|
||||
ignored_pairs { first: "link5-right" second: "link7-right" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
settle_timeout_s: 3.0
|
||||
settle_position_tolerance_rad: 0.002
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 1.0
|
||||
max_joint_acceleration_rad_s2: 5.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.1
|
||||
linear_acceleration_max: 0.5
|
||||
linear_jerk_max: 5.0
|
||||
angular_velocity_max: 0.5
|
||||
angular_acceleration_max: 2.0
|
||||
angular_jerk_max: 10.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
enable: true
|
||||
lookahead_s: 0.15
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 1.0
|
||||
max_joint_acceleration_rad_s2: 5.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 0.01
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 2.0
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
# xiaozhao 三轴颈部按 RobotArm 注册,仅使用关节空间控制。
|
||||
# MoveJ 目标顺序为 neck-joint1、neck-joint2、neck-joint3,单位为弧度。
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "xiaozhao_mujoco_head"
|
||||
|
||||
motor {
|
||||
motor_system_id: "xiaozhao_mujoco_head_motors"
|
||||
motor_group_ids: "xiaozhao_mujoco_head_motors"
|
||||
dof: 3
|
||||
joint_names: "neck-joint1"
|
||||
joint_names: "neck-joint2"
|
||||
joint_names: "neck-joint3"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 0.25
|
||||
default_acc: 0.5
|
||||
}
|
||||
|
||||
motion {
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
settle_timeout_s: 3.0
|
||||
settle_position_tolerance_rad: 0.002
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,338 +0,0 @@
|
||||
# 小赵 TCHL 实机双臂配置,所有关节位置使用 rad。
|
||||
# TCP 与第七连杆同向,局部偏移左 (0.007, 0.23, -0.045) m、右 (0.007, -0.23, -0.045) m。
|
||||
# 两臂分别规划 MoveP。关节路径碰撞检测的最小间距为 10 mm。
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "xiaozhao_tchl_right_arm"
|
||||
motor {
|
||||
motor_system_id: "xiaozhao_tchl_motors"
|
||||
motor_group_ids: "xiaozhao_tchl_motors"
|
||||
dof: 7
|
||||
joint_names: "joint1-right"
|
||||
joint_names: "joint2-right"
|
||||
joint_names: "joint3-right"
|
||||
joint_names: "joint4-right"
|
||||
joint_names: "joint5-right"
|
||||
joint_names: "joint6-right"
|
||||
joint_names: "joint7-right"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 0.5
|
||||
default_acc: 2.0
|
||||
}
|
||||
kinematics {
|
||||
pinocchio_qp_ik_solver {
|
||||
urdf_path: "model/xiaozhao/urdf/xiaozhao.urdf"
|
||||
base_frame_name: "base_link"
|
||||
flange_frame_name: "link7-right"
|
||||
tcp_frame_name: "tcp-right"
|
||||
lambda: 1e-4
|
||||
w_posrot: 0.5
|
||||
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: 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
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: true
|
||||
gain: 0.2
|
||||
margin_ratio: 0.15
|
||||
max_push: 0.25
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
|
||||
ignored_pairs { first: "link5-right" second: "link7-right" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
settle_timeout_s: 3.0
|
||||
settle_position_tolerance_rad: 0.002
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 1.0
|
||||
max_joint_acceleration_rad_s2: 5.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.1
|
||||
linear_acceleration_max: 0.5
|
||||
linear_jerk_max: 5.0
|
||||
angular_velocity_max: 0.5
|
||||
angular_acceleration_max: 2.0
|
||||
angular_jerk_max: 10.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
enable: true
|
||||
lookahead_s: 0.15
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 1.5
|
||||
max_joint_acceleration_rad_s2: 40.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 0.01
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 2.0
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
robot_arms {
|
||||
id: "xiaozhao_tchl_left_arm"
|
||||
motor {
|
||||
motor_system_id: "xiaozhao_tchl_motors"
|
||||
motor_group_ids: "xiaozhao_tchl_motors"
|
||||
dof: 7
|
||||
joint_names: "joint1-left"
|
||||
joint_names: "joint2-left"
|
||||
joint_names: "joint3-left"
|
||||
joint_names: "joint4-left"
|
||||
joint_names: "joint5-left"
|
||||
joint_names: "joint6-left"
|
||||
joint_names: "joint7-left"
|
||||
upd_freq: 1000
|
||||
buffer_size: 50
|
||||
default_vel: 0.5
|
||||
default_acc: 2.0
|
||||
}
|
||||
kinematics {
|
||||
pinocchio_qp_ik_solver {
|
||||
urdf_path: "model/xiaozhao/urdf/xiaozhao.urdf"
|
||||
base_frame_name: "base_link"
|
||||
flange_frame_name: "link7-left"
|
||||
tcp_frame_name: "tcp-left"
|
||||
lambda: 1e-4
|
||||
w_posrot: 0.5
|
||||
max_iters: 100
|
||||
tol: 1e-6
|
||||
qp_time_limit: 1e-2
|
||||
joint_limit_policy {
|
||||
limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
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 }
|
||||
joints { joint_name: "joint4-left" q_lb: 0 q_ub: 2.35 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint5-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint6-left" q_lb: -0.785 q_ub: 0.45 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint7-left" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
|
||||
}
|
||||
soft_limit {
|
||||
enable: true
|
||||
margin_ratio: 0.01
|
||||
min_margin_rad: 0.01
|
||||
}
|
||||
avoidance {
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
motion {
|
||||
joint_path {
|
||||
algorithm: RRT_CONNECT
|
||||
rrt_connect {
|
||||
timeout_s: 2.0
|
||||
range_rad: 0.2
|
||||
collision_check_step_rad: 0.02
|
||||
}
|
||||
collision_checker {
|
||||
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
|
||||
ignored_pairs { first: "link5-left" second: "link7-left" }
|
||||
}
|
||||
minimum_distance_m: 0.01
|
||||
}
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
}
|
||||
}
|
||||
move_j {
|
||||
settle_timeout_s: 3.0
|
||||
settle_position_tolerance_rad: 0.002
|
||||
settle_velocity_tolerance_rad_s: 0.02
|
||||
settle_stable_sample_count: 3
|
||||
}
|
||||
move_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
sample_period_s: 0.001
|
||||
position_gain: 4.0
|
||||
rotation_gain: 4.0
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_continuity_check {
|
||||
enable: true
|
||||
max_joint_delta_rad: 0.05
|
||||
max_joint_velocity_rad_s: 1.0
|
||||
max_joint_acceleration_rad_s2: 5.0
|
||||
}
|
||||
cartesian_step_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 1e-4
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
}
|
||||
speed_l {
|
||||
pinocchio_cartesian_motion_planner {
|
||||
linear_velocity_max: 0.1
|
||||
linear_acceleration_max: 0.5
|
||||
linear_jerk_max: 5.0
|
||||
angular_velocity_max: 0.5
|
||||
angular_acceleration_max: 2.0
|
||||
angular_jerk_max: 10.0
|
||||
linear_target_replan_threshold: 1e-4
|
||||
angular_target_replan_threshold: 1e-4
|
||||
enforce_joint_acceleration_limits: true
|
||||
adaptive_speed {
|
||||
enable: true
|
||||
lookahead_s: 0.15
|
||||
min_speed_ratio: 0.10
|
||||
}
|
||||
line_deviation_check {
|
||||
enable: true
|
||||
line_deviation_warn_m: 0.01
|
||||
line_deviation_stop_m: 0.03
|
||||
line_direction_warn_deg: 20.0
|
||||
line_direction_stop_deg: 45.0
|
||||
line_direction_reset_deg: 10.0
|
||||
line_check_min_distance_m: 0.005
|
||||
}
|
||||
joint_velocity_check {
|
||||
enable: true
|
||||
max_joint_velocity_rad_s: 1.0
|
||||
max_joint_acceleration_rad_s2: 5.0
|
||||
}
|
||||
cartesian_velocity_feasibility_check {
|
||||
enable: true
|
||||
min_linear_speed_ratio: 0.2
|
||||
max_linear_direction_deviation_deg: 10.0
|
||||
min_angular_speed_ratio: 0.2
|
||||
max_angular_direction_deviation_deg: 10.0
|
||||
min_desired_linear_speed: 0.01
|
||||
min_desired_angular_speed: 1e-4
|
||||
}
|
||||
}
|
||||
speed_l_controller {
|
||||
cartesian_velocity_controller {
|
||||
control_period_s: 0.001
|
||||
stop_twist_norm: 1e-9
|
||||
stop_command_velocity_norm: 1e-3
|
||||
stop_measured_velocity_norm: 1e-2
|
||||
stop_acceleration: 2.0
|
||||
stop_timeout_s: 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,41 +0,0 @@
|
||||
# Reference calibration from frozen source-channel-config.json and source-servo-config.json.
|
||||
# USB path was enumerated on 192.168.0.234; opening may require user-managed permissions.
|
||||
# Creating/initializing this device never moves to home automatically.
|
||||
bio_head {
|
||||
id: "usb_head"
|
||||
serial_port: "/dev/serial/by-id/usb-CherryUSB_RTT_CDC_ACM_FS_000000000001-if00"
|
||||
baud_rate: 115200
|
||||
usb_erpc {
|
||||
response_timeout_ms: 2000
|
||||
joints {
|
||||
id: "eye_l_up"
|
||||
min_position_rad: -1.0
|
||||
max_position_rad: 1.0
|
||||
home_position_rad: 0.0
|
||||
}
|
||||
joints {
|
||||
id: "eye_l_lower"
|
||||
min_position_rad: -0.35
|
||||
max_position_rad: 0.55
|
||||
home_position_rad: 0.0
|
||||
}
|
||||
joints {
|
||||
id: "eye_l_v"
|
||||
min_position_rad: -1.5
|
||||
max_position_rad: 1.0
|
||||
home_position_rad: 0.0
|
||||
}
|
||||
joints {
|
||||
id: "eye_l_h"
|
||||
min_position_rad: -0.65
|
||||
max_position_rad: 0.70
|
||||
home_position_rad: 0.0
|
||||
}
|
||||
joints {
|
||||
id: "pwm8_local"
|
||||
min_position_rad: -1.5
|
||||
max_position_rad: 0.393
|
||||
home_position_rad: -1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -262,26 +262,4 @@ camera {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cameras {
|
||||
id: "usb_cam2"
|
||||
uvc {
|
||||
usb: "/dev/video2"
|
||||
camera_mode: CAMERA_MODE_VIDEO
|
||||
capture {
|
||||
width: 640
|
||||
height: 480
|
||||
fps: 30
|
||||
stream_mode: STREAM_MODE_RGB
|
||||
}
|
||||
encoder {
|
||||
width: 640
|
||||
height: 480
|
||||
fps: 30
|
||||
codec: "h265_qsv"
|
||||
enable_stream_timestamp: true
|
||||
buffer_size: 30
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,50 +0,0 @@
|
||||
# 小赵实机相机。每路使用该安装位置对应的 RealSense 序列号。
|
||||
camera {
|
||||
cameras {
|
||||
id: "head_carme"
|
||||
realsense {
|
||||
serialNumber: "243122075389"
|
||||
camera_mode: CAMERA_MODE_VIDEO
|
||||
capture {
|
||||
width: 1280
|
||||
height: 720
|
||||
fps: 30
|
||||
stream_mode: STREAM_MODE_RGB
|
||||
}
|
||||
encoder {
|
||||
width: 640
|
||||
height: 360
|
||||
fps: 30
|
||||
codec: "H264"
|
||||
enable_stream_timestamp: true
|
||||
buffer_size: 30
|
||||
}
|
||||
align_mode: ALIGN_MODE_COLOR
|
||||
sync: false
|
||||
}
|
||||
}
|
||||
|
||||
cameras {
|
||||
id: "right_hand_carme"
|
||||
realsense {
|
||||
serialNumber: "263122071711"
|
||||
camera_mode: CAMERA_MODE_VIDEO
|
||||
capture {
|
||||
width: 1280
|
||||
height: 720
|
||||
fps: 30
|
||||
stream_mode: STREAM_MODE_RGB
|
||||
}
|
||||
encoder {
|
||||
width: 640
|
||||
height: 360
|
||||
fps: 30
|
||||
codec: "H264"
|
||||
enable_stream_timestamp: true
|
||||
buffer_size: 30
|
||||
}
|
||||
align_mode: ALIGN_MODE_COLOR
|
||||
sync: false
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,63 +0,0 @@
|
||||
# xiaozhao 触屏仿真相机。手相机保持 1280x720 点击像素坐标。
|
||||
# 头部相机使用 2560x1440,提高 16 mm 屏幕 Tag 的像素尺寸与姿态估计稳定性。
|
||||
camera {
|
||||
cameras {
|
||||
id: "xiaozhao_mujoco_hand_cam"
|
||||
mujoco {
|
||||
world_id: "mujoco_world"
|
||||
camera_name: "hand_cam"
|
||||
render {
|
||||
width: 1280
|
||||
height: 720
|
||||
fps: 30
|
||||
stream_mode: STREAM_MODE_RGBD
|
||||
}
|
||||
encoder {
|
||||
width: 480
|
||||
height: 320
|
||||
fps: 30
|
||||
codec: "H264"
|
||||
enable_stream_timestamp: true
|
||||
buffer_size: 30
|
||||
}
|
||||
consume_new_frame_only: false
|
||||
viewer_pip {
|
||||
enable: false
|
||||
left: -10
|
||||
bottom: 10
|
||||
width: 320
|
||||
height: 180
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cameras {
|
||||
id: "xiaozhao_mujoco_external_touch_cam"
|
||||
mujoco {
|
||||
world_id: "mujoco_world"
|
||||
camera_name: "external_touch_cam"
|
||||
render {
|
||||
width: 2560
|
||||
height: 1440
|
||||
fps: 30
|
||||
stream_mode: STREAM_MODE_RGBD
|
||||
}
|
||||
encoder {
|
||||
width: 480
|
||||
height: 320
|
||||
fps: 30
|
||||
codec: "H264"
|
||||
enable_stream_timestamp: true
|
||||
buffer_size: 30
|
||||
}
|
||||
consume_new_frame_only: false
|
||||
viewer_pip {
|
||||
enable: false
|
||||
left: 10
|
||||
bottom: 10
|
||||
width: 320
|
||||
height: 180
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,36 +1,6 @@
|
||||
dexhand {
|
||||
dexhands {
|
||||
id: "right_hand_ap001"
|
||||
model: "ROH-AP001"
|
||||
has_tactile_feedback: true
|
||||
oymotion_ap001 {
|
||||
can_interface: "can0"
|
||||
hand_id: 2
|
||||
master_id: 1
|
||||
command_timeout_ms: 255
|
||||
}
|
||||
}
|
||||
|
||||
# LiteS001 uses the same six-axis OYMotion CAN control protocol as AP001,
|
||||
# but it has no tactile sensor matrix. Add this id to real_device_manager.pb.txt
|
||||
# when the LiteS001 is installed; do not enable it together with AP001 when
|
||||
# both entries address the same physical CAN hand id.
|
||||
dexhands {
|
||||
id: "right_hand_lites001"
|
||||
model: "ROH-LiteS001"
|
||||
has_tactile_feedback: false
|
||||
oymotion_ap001 {
|
||||
can_interface: "can1"
|
||||
hand_id: 2
|
||||
master_id: 1
|
||||
command_timeout_ms: 255
|
||||
}
|
||||
}
|
||||
|
||||
dexhands {
|
||||
id: "hand1"
|
||||
model: "RH56D"
|
||||
has_tactile_feedback: true
|
||||
rh56dftp {
|
||||
ip: "192.168.1.223"
|
||||
port: 6000
|
||||
@ -40,8 +10,6 @@ dexhand {
|
||||
|
||||
dexhands {
|
||||
id: "hand2"
|
||||
model: "RH56D"
|
||||
has_tactile_feedback: true
|
||||
rh56dftp {
|
||||
ip: "192.168.1.224"
|
||||
port: 6000
|
||||
@ -51,8 +19,6 @@ dexhand {
|
||||
|
||||
dexhands {
|
||||
id: "paxini_tip_1"
|
||||
model: "PX-6AX Gen3"
|
||||
has_tactile_feedback: true
|
||||
px_6ax_gen3 {
|
||||
serial_port: "/dev/ttyACM1"
|
||||
sensor_model: "S1813_core"
|
||||
@ -70,15 +36,13 @@ dexhand {
|
||||
tactile_finger: "INDEX"
|
||||
tactile_region: "TIP"
|
||||
sensor_name: "Paxini Gen3末端压力"
|
||||
polling_read_mode: LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE
|
||||
polling_read_mode: PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE
|
||||
auto_calibrate: false
|
||||
}
|
||||
}
|
||||
|
||||
dexhands {
|
||||
id: "mujoco_zero_touch_dexhand"
|
||||
model: "MuJoCo Zero Touch"
|
||||
has_tactile_feedback: true
|
||||
zero_sim_touch {}
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,7 +5,7 @@ microphone {
|
||||
channels: 2
|
||||
sampleRate: 48000
|
||||
volume: 100
|
||||
input_device: "plughw:CARD=Newmine,DEV=0"
|
||||
input_device: "plughw:CARD=XFMDPV0018,DEV=0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
72
cmvr-es/config/devices/motor/ethercat_motors.pb.txt
Normal file
72
cmvr-es/config/devices/motor/ethercat_motors.pb.txt
Normal file
@ -0,0 +1,72 @@
|
||||
motor {
|
||||
id: "ethercat_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "right_arm_ethercat_motors"
|
||||
bus_type: MOTOR_BUS_ETHERCAT
|
||||
vendor: MOTOR_VENDOR_EYOU
|
||||
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
|
||||
|
||||
ethercat {
|
||||
master_index: 0
|
||||
cycle_us: 1000
|
||||
slave_op_timeout_ms: 12000
|
||||
slave_state_poll_period_ms: 10
|
||||
|
||||
cia402 {
|
||||
state_transition_timeout_ms: 1200
|
||||
velocity_stop_timeout_ms: 2000
|
||||
status_poll_period_ms: 10
|
||||
stopped_velocity_tolerance_rad_s: 0.001
|
||||
}
|
||||
|
||||
zero_calibration {
|
||||
timeout_ms: 2000
|
||||
poll_period_ms: 10
|
||||
stable_sample_count: 5
|
||||
position_tolerance_counts: 10000
|
||||
stable_delta_counts: 1000
|
||||
}
|
||||
|
||||
dc {
|
||||
enable: false
|
||||
reference_motor_id: 1
|
||||
sync0_cycle_us: 1000
|
||||
sync0_shift_us: 0
|
||||
sync_reference_clock_period: 1
|
||||
assign_activate: 768
|
||||
sync_monitor_period_ms: 1000
|
||||
}
|
||||
|
||||
slaves { motor_id: 1 alias: 0 position: 0 }
|
||||
slaves { motor_id: 2 alias: 0 position: 1 }
|
||||
slaves { motor_id: 3 alias: 0 position: 2 }
|
||||
slaves { motor_id: 4 alias: 0 position: 3 }
|
||||
slaves { motor_id: 5 alias: 0 position: 4 }
|
||||
slaves { motor_id: 6 alias: 0 position: 5 }
|
||||
slaves { motor_id: 7 alias: 0 position: 6 }
|
||||
}
|
||||
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.64 q_ub: 1.64 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: -1.60 q_ub: 1.60 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.37 q_ub: 0.79 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.61 q_ub: 0.58 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "R_SHOULDER_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 2 joint_name: "R_SHOULDER_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 3 joint_name: "R_SHOULDER_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 4 joint_name: "R_ELBOW_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 5 joint_name: "R_WRIST_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 6 joint_name: "R_WRIST_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 7 joint_name: "R_WRIST_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,63 @@
|
||||
motor {
|
||||
id: "ethercat_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "right_arm_ethercat_motors"
|
||||
bus_type: MOTOR_BUS_ETHERCAT
|
||||
vendor: MOTOR_VENDOR_EYOU
|
||||
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
|
||||
|
||||
ethercat {
|
||||
master_index: 0
|
||||
cycle_us: 1000
|
||||
slave_op_timeout_ms: 15000
|
||||
slave_state_poll_period_ms: 10
|
||||
|
||||
cia402 {
|
||||
state_transition_timeout_ms: 1200
|
||||
velocity_stop_timeout_ms: 2000
|
||||
status_poll_period_ms: 10
|
||||
stopped_velocity_tolerance_rad_s: 0.001
|
||||
}
|
||||
|
||||
zero_calibration {
|
||||
timeout_ms: 2000
|
||||
poll_period_ms: 10
|
||||
stable_sample_count: 5
|
||||
position_tolerance_counts: 10000
|
||||
stable_delta_counts: 1000
|
||||
}
|
||||
|
||||
dc {
|
||||
enable: false
|
||||
reference_motor_id: 1
|
||||
sync0_cycle_us: 1000
|
||||
sync0_shift_us: 0
|
||||
sync_reference_clock_period: 1
|
||||
assign_activate: 768
|
||||
sync_monitor_period_ms: 1000
|
||||
}
|
||||
|
||||
slaves { motor_id: 1 alias: 0 position: 0 }
|
||||
slaves { motor_id: 2 alias: 0 position: 1 }
|
||||
slaves { motor_id: 3 alias: 0 position: 2 }
|
||||
slaves { motor_id: 4 alias: 0 position: 3 }
|
||||
}
|
||||
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "R_SHOULDER_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 2 joint_name: "R_SHOULDER_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 3 joint_name: "R_SHOULDER_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 4 joint_name: "R_ELBOW_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,57 +0,0 @@
|
||||
# Three Lingkong motors on can3, CAN node IDs 1/2/3.
|
||||
# All public q/qd values refer to OUTPUT shaft radians/radians per second.
|
||||
# SOFTWARE limits retained from the previous single-motor installation.
|
||||
motor {
|
||||
id: "lingkong_motors"
|
||||
motor_groups {
|
||||
id: "lingkong_can_motors"
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_LINGKONG
|
||||
protocol: MOTOR_PROTOCOL_LINGKONG_CAN_V2_38
|
||||
can { channel_id: 3 }
|
||||
motors {
|
||||
motors {
|
||||
id: 1
|
||||
joint_name: "MG4005E_AXIS_1"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -1.06
|
||||
limit_q_ub: 0.75
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
current_amp_per_lsb: 0.01611328125 # MG: 66/4096 A/LSB
|
||||
response_timeout_ms: 100
|
||||
reached_position_tolerance_rad: 0.001
|
||||
# Rated current and B1 parameter conversions remain unspecified.
|
||||
}
|
||||
}
|
||||
motors {
|
||||
id: 2
|
||||
joint_name: "MG4005E_AXIS_2"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -0.72
|
||||
limit_q_ub: 0.75
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
current_amp_per_lsb: 0.01611328125 # MG: 66/4096 A/LSB
|
||||
response_timeout_ms: 100
|
||||
reached_position_tolerance_rad: 0.001
|
||||
# Rated current and B1 parameter conversions remain unspecified.
|
||||
}
|
||||
}
|
||||
motors {
|
||||
id: 3
|
||||
joint_name: "MG4005E_AXIS_3"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -3.14
|
||||
limit_q_ub: 3.14
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
current_amp_per_lsb: 0.01611328125 # MG: 66/4096 A/LSB
|
||||
response_timeout_ms: 100
|
||||
reached_position_tolerance_rad: 0.001
|
||||
# Rated current and B1 parameter conversions remain unspecified.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
35
cmvr-es/config/devices/motor/mujoco_motors.pb.txt
Normal file
35
cmvr-es/config/devices/motor/mujoco_motors.pb.txt
Normal file
@ -0,0 +1,35 @@
|
||||
motor {
|
||||
id: "mujoco_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "right_arm_mujoco_motors"
|
||||
bus_type: MOTOR_BUS_MUJOCO
|
||||
vendor: MOTOR_VENDOR_MUJOCO
|
||||
protocol: MOTOR_PROTOCOL_MUJOCO
|
||||
mujoco {
|
||||
world_id: "mujoco_world"
|
||||
}
|
||||
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "R_SHOULDER_P" }
|
||||
motors { id: 2 joint_name: "R_SHOULDER_R" }
|
||||
motors { id: 3 joint_name: "R_SHOULDER_Y" }
|
||||
motors { id: 4 joint_name: "R_ELBOW_R" }
|
||||
motors { id: 5 joint_name: "R_WRIST_P" }
|
||||
motors { id: 6 joint_name: "R_WRIST_Y" }
|
||||
motors { id: 7 joint_name: "R_WRIST_R" }
|
||||
}
|
||||
}
|
||||
}
|
||||
35
cmvr-es/config/devices/motor/mujoco_motors_gen2.pb.txt
Normal file
35
cmvr-es/config/devices/motor/mujoco_motors_gen2.pb.txt
Normal file
@ -0,0 +1,35 @@
|
||||
motor {
|
||||
id: "mujoco_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "right_arm_mujoco_motors"
|
||||
bus_type: MOTOR_BUS_MUJOCO
|
||||
vendor: MOTOR_VENDOR_MUJOCO
|
||||
protocol: MOTOR_PROTOCOL_MUJOCO
|
||||
mujoco {
|
||||
world_id: "mujoco_world"
|
||||
}
|
||||
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "right_arm_J1" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J2" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J3" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J4" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J5" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J6" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J7" q_lb: -3.14159 q_ub: 3.14159 qd: 2.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "right_arm_J1" }
|
||||
motors { id: 2 joint_name: "right_arm_J2" }
|
||||
motors { id: 3 joint_name: "right_arm_J3" }
|
||||
motors { id: 4 joint_name: "right_arm_J4" }
|
||||
motors { id: 5 joint_name: "right_arm_J5" }
|
||||
motors { id: 6 joint_name: "right_arm_J6" }
|
||||
motors { id: 7 joint_name: "right_arm_J7" }
|
||||
}
|
||||
}
|
||||
}
|
||||
54
cmvr-es/config/devices/motor/tchl_motors.pb.txt
Normal file
54
cmvr-es/config/devices/motor/tchl_motors.pb.txt
Normal file
@ -0,0 +1,54 @@
|
||||
# 同川 TC600E TR 单轴模板;未注册为活动设备。
|
||||
# 当前按实机 PrD.00=0、电子齿轮1:1配置;减速比需读取实机3D06后填写。
|
||||
motor {
|
||||
id: "tchl_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "tchl_single_axis"
|
||||
bus_type: MOTOR_BUS_ETHERCAT
|
||||
vendor: MOTOR_VENDOR_TCHL
|
||||
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
|
||||
|
||||
ethercat {
|
||||
master_index: 0
|
||||
cycle_us: 1000
|
||||
slave_op_timeout_ms: 12000
|
||||
slave_state_poll_period_ms: 10
|
||||
|
||||
cia402 {
|
||||
state_transition_timeout_ms: 1200
|
||||
velocity_stop_timeout_ms: 2000
|
||||
status_poll_period_ms: 10
|
||||
stopped_velocity_tolerance_rad_s: 0.001
|
||||
}
|
||||
|
||||
dc {
|
||||
enable: false
|
||||
reference_motor_id: 1
|
||||
sync0_cycle_us: 1000
|
||||
sync0_shift_us: 0
|
||||
sync_reference_clock_period: 1
|
||||
assign_activate: 768
|
||||
sync_monitor_period_ms: 1000
|
||||
}
|
||||
|
||||
slaves { motor_id: 1 alias: 0 position: 0 }
|
||||
}
|
||||
|
||||
# 必须先填写实际行程及速度/加速度上限,再设 enable: true;0不是可运行值。
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "TCHL_AXIS_1" q_lb: -3.14 q_ub: 3.14 qd: 10 qdd: 100 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors {
|
||||
id: 1
|
||||
joint_name: "TCHL_AXIS_1"
|
||||
encoder_counts_per_rev: 131072
|
||||
gear_ratio: 101
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
61
cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt
Normal file
61
cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt
Normal file
@ -0,0 +1,61 @@
|
||||
# 同川 TC600E TR 七轴模板;设备管理器默认不启用。
|
||||
# 各轴按实机确认 PrD.00、电子齿轮、编码器分辨率和减速比。
|
||||
# 以下 131072 / 101 仅为 PrD.00=0、电子齿轮 1:1 的配置示例。
|
||||
motor {
|
||||
id: "tchl_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "tchl_joint_motors"
|
||||
bus_type: MOTOR_BUS_ETHERCAT
|
||||
vendor: MOTOR_VENDOR_TCHL
|
||||
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
|
||||
|
||||
ethercat {
|
||||
master_index: 0
|
||||
cycle_us: 1000
|
||||
slave_op_timeout_ms: 12000
|
||||
slave_state_poll_period_ms: 10
|
||||
|
||||
cia402 {
|
||||
state_transition_timeout_ms: 1200
|
||||
velocity_stop_timeout_ms: 2000
|
||||
status_poll_period_ms: 10
|
||||
stopped_velocity_tolerance_rad_s: 0.001
|
||||
}
|
||||
|
||||
dc { enable: false }
|
||||
|
||||
slaves { motor_id: 1 alias: 0 position: 0 }
|
||||
slaves { motor_id: 2 alias: 0 position: 1 }
|
||||
slaves { motor_id: 3 alias: 0 position: 2 }
|
||||
slaves { motor_id: 4 alias: 0 position: 3 }
|
||||
slaves { motor_id: 5 alias: 0 position: 4 }
|
||||
slaves { motor_id: 6 alias: 0 position: 5 }
|
||||
|
||||
}
|
||||
|
||||
# 示例限位;启用设备前按各轴实际行程和允许速度、加速度填写。
|
||||
# q: rad,qd: rad/s,qdd: rad/s^2。
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "TCHL_AXIS_1" q_lb: -1.0 q_ub: 1.0 qd: 0.5 qdd: 1.0 }
|
||||
joints { joint_name: "TCHL_AXIS_2" q_lb: -1.0 q_ub: 1.0 qd: 0.5 qdd: 1.0 }
|
||||
joints { joint_name: "TCHL_AXIS_3" q_lb: -1.0 q_ub: 1.0 qd: 0.5 qdd: 1.0 }
|
||||
joints { joint_name: "TCHL_AXIS_4" q_lb: -1.0 q_ub: 1.0 qd: 0.5 qdd: 1.0 }
|
||||
joints { joint_name: "TCHL_AXIS_5" q_lb: -1.0 q_ub: 1.0 qd: 0.5 qdd: 1.0 }
|
||||
joints { joint_name: "TCHL_AXIS_6" q_lb: -1.0 q_ub: 1.0 qd: 0.5 qdd: 1.0 }
|
||||
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "TCHL_AXIS_1" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
motors { id: 2 joint_name: "TCHL_AXIS_2" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
motors { id: 3 joint_name: "TCHL_AXIS_3" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
motors { id: 4 joint_name: "TCHL_AXIS_4" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
motors { id: 5 joint_name: "TCHL_AXIS_5" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
motors { id: 6 joint_name: "TCHL_AXIS_6" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
99
cmvr-es/config/devices/motor/ti5_motors.pb.txt
Normal file
99
cmvr-es/config/devices/motor/ti5_motors.pb.txt
Normal file
@ -0,0 +1,99 @@
|
||||
motor {
|
||||
id: "ti5_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "left_arm_can_motors"
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_TI5
|
||||
protocol: MOTOR_PROTOCOL_CANOPEN
|
||||
can {
|
||||
channel_id: 0
|
||||
}
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_URDF
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
}
|
||||
motors {
|
||||
motors { id: 23 joint_name: "L_SHOULDER_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 24 joint_name: "L_SHOULDER_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 25 joint_name: "L_SHOULDER_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 26 joint_name: "L_ELBOW_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 27 joint_name: "L_WRIST_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 28 joint_name: "L_WRIST_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 29 joint_name: "L_WRIST_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
|
||||
motor_groups {
|
||||
id: "right_arm_can_motors"
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_TI5
|
||||
protocol: MOTOR_PROTOCOL_CANOPEN
|
||||
can {
|
||||
channel_id: 1
|
||||
}
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 16 joint_name: "R_SHOULDER_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 17 joint_name: "R_SHOULDER_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 18 joint_name: "R_SHOULDER_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 19 joint_name: "R_ELBOW_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 20 joint_name: "R_WRIST_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 21 joint_name: "R_WRIST_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 22 joint_name: "R_WRIST_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
|
||||
motor_groups {
|
||||
id: "head_can_motors"
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_TI5
|
||||
protocol: MOTOR_PROTOCOL_CANOPEN
|
||||
can {
|
||||
channel_id: 2
|
||||
}
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "HEAD_Y" q_lb: -3.14 q_ub: 3.14 qd: 3.0 }
|
||||
joints { joint_name: "HEAD_P" q_lb: -3.14 q_ub: 3.14 qd: 3.0 }
|
||||
joints { joint_name: "HEAD_R" q_lb: -3.14 q_ub: 3.14 qd: 3.0 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 32 joint_name: "HEAD_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 30 joint_name: "HEAD_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 31 joint_name: "HEAD_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
|
||||
motor_groups {
|
||||
id: "waist_can_motors"
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_TI5
|
||||
protocol: MOTOR_PROTOCOL_CANOPEN
|
||||
can {
|
||||
channel_id: 3
|
||||
}
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "WAIST_Y" q_lb: -3.14 q_ub: 3.14 qd: 3.0 }
|
||||
joints { joint_name: "WAIST_P" q_lb: -3.14 q_ub: 3.14 qd: 3.0 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 4 joint_name: "WAIST_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 15 joint_name: "WAIST_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,62 +0,0 @@
|
||||
# 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: "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: 2 }
|
||||
motors {
|
||||
motors {
|
||||
id: 1
|
||||
joint_name: "neck-joint1"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -2.4
|
||||
limit_q_ub: -0.4
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
response_timeout_ms: 500
|
||||
reached_position_tolerance_rad: 0.001
|
||||
# Iq conversion intentionally unspecified until confirmed for this motor.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
motor_groups {
|
||||
id: "lingkong_mixed_v238"
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_LINGKONG
|
||||
protocol: MOTOR_PROTOCOL_LINGKONG_CAN_V2_38
|
||||
can { channel_id: 2 }
|
||||
motors {
|
||||
motors {
|
||||
id: 2
|
||||
joint_name: "neck-joint2"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -0.75
|
||||
limit_q_ub: 0.77
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
response_timeout_ms: 500
|
||||
reached_position_tolerance_rad: 0.001
|
||||
# Iq conversion intentionally unspecified until confirmed for this motor.
|
||||
}
|
||||
}
|
||||
motors {
|
||||
id: 3
|
||||
joint_name: "neck-joint3"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -0.45
|
||||
limit_q_ub: 0.42
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
response_timeout_ms: 500
|
||||
reached_position_tolerance_rad: 0.001
|
||||
# Iq conversion intentionally unspecified until confirmed for this motor.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,87 +0,0 @@
|
||||
# MuJoCo 仿真限值:位置范围与 xiaozhao/config/joint_limits.csv 一致。
|
||||
# URDF 的 velocity/effort 为占位值,速度和加速度在这里显式设置。
|
||||
motor {
|
||||
id: "xiaozhao_mujoco_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "xiaozhao_mujoco_left_arm_motors"
|
||||
bus_type: MOTOR_BUS_MUJOCO
|
||||
vendor: MOTOR_VENDOR_MUJOCO
|
||||
protocol: MOTOR_PROTOCOL_MUJOCO
|
||||
mujoco {
|
||||
world_id: "mujoco_world"
|
||||
}
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
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 }
|
||||
joints { joint_name: "joint4-left" q_lb: 0 q_ub: 2.35 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint5-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint6-left" q_lb: -0.785 q_ub: 0.45 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint7-left" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 1 joint_name: "joint1-left" }
|
||||
motors { id: 2 joint_name: "joint2-left" }
|
||||
motors { id: 3 joint_name: "joint3-left" }
|
||||
motors { id: 4 joint_name: "joint4-left" }
|
||||
motors { id: 5 joint_name: "joint5-left" }
|
||||
motors { id: 6 joint_name: "joint6-left" }
|
||||
motors { id: 7 joint_name: "joint7-left" }
|
||||
}
|
||||
}
|
||||
|
||||
motor_groups {
|
||||
id: "xiaozhao_mujoco_right_arm_motors"
|
||||
bus_type: MOTOR_BUS_MUJOCO
|
||||
vendor: MOTOR_VENDOR_MUJOCO
|
||||
protocol: MOTOR_PROTOCOL_MUJOCO
|
||||
mujoco {
|
||||
world_id: "mujoco_world"
|
||||
}
|
||||
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 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 1 joint_name: "joint1-right" }
|
||||
motors { id: 2 joint_name: "joint2-right" }
|
||||
motors { id: 3 joint_name: "joint3-right" }
|
||||
motors { id: 4 joint_name: "joint4-right" }
|
||||
motors { id: 5 joint_name: "joint5-right" }
|
||||
motors { id: 6 joint_name: "joint6-right" }
|
||||
motors { id: 7 joint_name: "joint7-right" }
|
||||
}
|
||||
}
|
||||
|
||||
motor_groups {
|
||||
id: "xiaozhao_mujoco_head_motors"
|
||||
bus_type: MOTOR_BUS_MUJOCO
|
||||
vendor: MOTOR_VENDOR_MUJOCO
|
||||
protocol: MOTOR_PROTOCOL_MUJOCO
|
||||
mujoco {
|
||||
world_id: "mujoco_world"
|
||||
}
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "neck-joint1" q_lb: -1.57 q_ub: 1.57 qd: 0.5 qdd: 2.0 }
|
||||
joints { joint_name: "neck-joint2" q_lb: -1.57 q_ub: 0.44 qd: 0.5 qdd: 2.0 }
|
||||
joints { joint_name: "neck-joint3" q_lb: -0.44 q_ub: 0.44 qd: 0.5 qdd: 2.0 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 1 joint_name: "neck-joint1" }
|
||||
motors { id: 2 joint_name: "neck-joint2" }
|
||||
motors { id: 3 joint_name: "neck-joint3" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,92 +0,0 @@
|
||||
# 双臂共用一个 EtherCAT 主站。接线、编码器计数和减速比沿用 TCHL 双臂模板。
|
||||
# 启用前按实机核对从站顺序、关节方向、零位、编码器计数、减速比和限位。
|
||||
motor {
|
||||
id: "xiaozhao_tchl_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "xiaozhao_tchl_motors"
|
||||
bus_type: MOTOR_BUS_ETHERCAT
|
||||
vendor: MOTOR_VENDOR_TCHL
|
||||
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
|
||||
|
||||
ethercat {
|
||||
master_index: 0
|
||||
cycle_us: 1000
|
||||
slave_op_timeout_ms: 12000
|
||||
slave_state_poll_period_ms: 10
|
||||
|
||||
cia402 {
|
||||
state_transition_timeout_ms: 1200
|
||||
velocity_stop_timeout_ms: 2000
|
||||
status_poll_period_ms: 10
|
||||
stopped_velocity_tolerance_rad_s: 0.001
|
||||
}
|
||||
|
||||
zero_calibration {
|
||||
timeout_ms: 2000
|
||||
poll_period_ms: 10
|
||||
stable_sample_count: 5
|
||||
position_tolerance_counts: 10000
|
||||
stable_delta_counts: 1000
|
||||
}
|
||||
|
||||
dc {
|
||||
enable: false
|
||||
}
|
||||
|
||||
# 分线器位于位置 0。端口 1 接右臂,J1 到 J7 对应位置 1 到 7。
|
||||
slaves { motor_id: 1 alias: 0 position: 1 }
|
||||
slaves { motor_id: 2 alias: 0 position: 2 }
|
||||
slaves { motor_id: 3 alias: 0 position: 3 }
|
||||
slaves { motor_id: 4 alias: 0 position: 4 }
|
||||
slaves { motor_id: 5 alias: 0 position: 5 }
|
||||
slaves { motor_id: 6 alias: 0 position: 6 }
|
||||
slaves { motor_id: 7 alias: 0 position: 7 }
|
||||
# 端口 2 接左臂,J1 到 J7 对应位置 8 到 14。
|
||||
slaves { motor_id: 8 alias: 0 position: 8 }
|
||||
slaves { motor_id: 9 alias: 0 position: 9 }
|
||||
slaves { motor_id: 10 alias: 0 position: 10 }
|
||||
slaves { motor_id: 11 alias: 0 position: 11 }
|
||||
slaves { motor_id: 12 alias: 0 position: 12 }
|
||||
slaves { motor_id: 13 alias: 0 position: 13 }
|
||||
slaves { motor_id: 14 alias: 0 position: 14 }
|
||||
}
|
||||
|
||||
# 初始软件限位沿用小赵模型。位置、速度和加速度分别使用 rad、rad/s 和 rad/s²。
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
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 }
|
||||
joints { joint_name: "joint4-left" q_lb: 0 q_ub: 2.35 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint5-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint6-left" q_lb: -0.785 q_ub: 0.45 qd: 1.0 qdd: 5.0 }
|
||||
joints { joint_name: "joint7-left" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "joint1-right" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 2 joint_name: "joint2-right" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 3 joint_name: "joint3-right" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 4 joint_name: "joint4-right" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 5 joint_name: "joint5-right" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 6 joint_name: "joint6-right" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 7 joint_name: "joint7-right" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 8 joint_name: "joint1-left" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 9 joint_name: "joint2-left" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 10 joint_name: "joint3-left" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 11 joint_name: "joint4-left" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 12 joint_name: "joint5-left" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 13 joint_name: "joint6-left" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 14 joint_name: "joint7-left" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
worlds {
|
||||
id: "mujoco_world"
|
||||
model_path: "model/xiaozhao/xml/scene.xml"
|
||||
timestep_s: 0.001
|
||||
realtime_factor: 1.0
|
||||
require_actuator: true
|
||||
}
|
||||
@ -1,17 +0,0 @@
|
||||
touch {
|
||||
touches {
|
||||
id: "paxini_tip"
|
||||
px_6ax_genx_can {
|
||||
# 系统预先配置 can0 为 1 Mbps;设备以约 2 ms 为目标采读并主动发送有效值,非严格周期。
|
||||
channel_id: 1
|
||||
force_can_id: 0x600
|
||||
# 按主机本地接收时间计算的最大有效期;超过此时间无有效报文则报不可用。
|
||||
max_sample_age_ms: 1000
|
||||
}
|
||||
}
|
||||
|
||||
touches {
|
||||
id: "mujoco_zero_touch"
|
||||
zero_sim {}
|
||||
}
|
||||
}
|
||||
230
cmvr-es/config/manager/device_manager.pb.txt
Normal file
230
cmvr-es/config/manager/device_manager.pb.txt
Normal file
@ -0,0 +1,230 @@
|
||||
device_manager {
|
||||
name: "cmvr_es"
|
||||
version: "0.1"
|
||||
description: "cmvr edge system version 0.1"
|
||||
devices {
|
||||
id: "mujoco_world"
|
||||
type: DEVICE_TYPE_MUJOCO_WORLD
|
||||
config_file: "devices/mujoco/right_arm_eye_to_hand_world.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_arm_mujoco_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/mujoco_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_right_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/arm_mujoco_qp.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_viewer"
|
||||
type: DEVICE_TYPE_MUJOCO_VIEWER
|
||||
config_file: "devices/mujoco/mujoco_viewer.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_hand_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/camera.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_external_touch_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/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: "hand2"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "paxini_tip_1"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_zero_touch_dexhand"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
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_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: "dual_arm_ethercat_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/dual_arm_ethercat_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_ethercat_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/ethercat_dual_arm.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "left_ethercat_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/ethercat_dual_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: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "tchl_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/tchl_arm.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,68 +0,0 @@
|
||||
device_manager {
|
||||
name: "cmvr_es"
|
||||
version: "0.1"
|
||||
description: "cmvr edge system version 0.1"
|
||||
devices {
|
||||
id: "head_carme"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/xiaozhao_camera.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_hand_carme"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/xiaozhao_camera.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_hand_lites001"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "paxini_tip"
|
||||
type: DEVICE_TYPE_TOUCH
|
||||
config_file: "devices/touch/touch.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_tchl_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/xiaozhao_tchl_motors.pb.txt"
|
||||
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: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_tchl_left_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/xiaozhao_tchl_arm.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,96 +0,0 @@
|
||||
device_manager {
|
||||
name: "cmvr_es"
|
||||
version: "0.1"
|
||||
description: "cmvr edge system version 0.1"
|
||||
# xiaozhao 双臂、颈部与右臂触屏仿真:先创建 world,再创建电机、机械臂、viewer 和传感器。
|
||||
devices {
|
||||
id: "mujoco_world"
|
||||
type: DEVICE_TYPE_MUJOCO_WORLD
|
||||
config_file: "devices/mujoco/xiaozhao_world.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_mujoco_left_arm_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/xiaozhao_mujoco_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_mujoco_right_arm_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/xiaozhao_mujoco_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_mujoco_head_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/xiaozhao_mujoco_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_mujoco_left_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/xiaozhao_mujoco_arm.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_mujoco_right_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/xiaozhao_mujoco_arm.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_mujoco_head"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/xiaozhao_mujoco_head.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_arm_mujoco_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/mujoco_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_right_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/arm_mujoco_qp.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_viewer"
|
||||
type: DEVICE_TYPE_MUJOCO_VIEWER
|
||||
config_file: "devices/mujoco/mujoco_viewer.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_mujoco_hand_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/xiaozhao_mujoco_camera.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_mujoco_external_touch_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/xiaozhao_mujoco_camera.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_zero_touch"
|
||||
type: DEVICE_TYPE_TOUCH
|
||||
config_file: "devices/touch/touch.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
@ -1,12 +1,11 @@
|
||||
task_manager {
|
||||
# xiaozhao 触屏仿真:初始化时头部 MoveJ 到预设位,随后等待 gRPC touch 请求。
|
||||
tasks {
|
||||
id: "touch_screen"
|
||||
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_real.pb.txt"
|
||||
enable: true
|
||||
config_file: "tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
tasks {
|
||||
id: "grpc_server"
|
||||
@ -15,28 +14,19 @@ task_manager {
|
||||
config_file: "tasks/grpc_server_task/grpc_server_task.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
|
||||
tasks {
|
||||
id: "xiaozhao_left_arm_self_collision"
|
||||
id: "right_arm_self_collision"
|
||||
type: TASK_TYPE_SELF_COLLISION
|
||||
run_mode: TASK_RUN_MODE_PERIODIC_STEP
|
||||
control_period_s: 0.02
|
||||
config_file: "tasks/self_collision_task/self_collision_task_xiaozhao_left.pb.txt"
|
||||
control_period_s: 0.002
|
||||
config_file: "tasks/self_collision_task/self_collision_task.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
tasks {
|
||||
id: "xiaozhao_right_arm_self_collision"
|
||||
type: TASK_TYPE_SELF_COLLISION
|
||||
run_mode: TASK_RUN_MODE_PERIODIC_STEP
|
||||
control_period_s: 0.02
|
||||
config_file: "tasks/self_collision_task/self_collision_task_xiaozhao_right.pb.txt"
|
||||
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: true
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
|
||||
@ -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.1.222"
|
||||
server_host: "192.168.0.222"
|
||||
server_port: 4433
|
||||
alpn: "cmvr-quic-edge/1"
|
||||
node_id: "cmvr-edge"
|
||||
robot_id: "CN-CMVR-MBLRV1-CQCVC-20261123-003"
|
||||
robot_id: "CN-CMVR-MBLRV1-AIMA-20260806-001"
|
||||
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-touch-quic-ca-60y.crt"
|
||||
server_name: "192.168.1.222"
|
||||
ca_file: "certs/cmvr-quic-ca.crt"
|
||||
server_name: "192.168.0.222"
|
||||
allow_insecure: false
|
||||
}
|
||||
|
||||
@ -44,7 +44,6 @@ quic_edge {
|
||||
# }
|
||||
# }
|
||||
|
||||
|
||||
reconnect {
|
||||
initial_delay_ms: 500
|
||||
maximum_delay_ms: 30000
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
# 小赵左臂独立自碰撞检测:仅本臂 + 固定 base,排除另一臂与活动头部。
|
||||
self_collision_task {
|
||||
id: "xiaozhao_left_arm_self_collision"
|
||||
arm_id: "xiaozhao_mujoco_left_arm"
|
||||
|
||||
checker {
|
||||
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
|
||||
ignored_pairs {
|
||||
first: "link5-left"
|
||||
second: "link7-left"
|
||||
}
|
||||
}
|
||||
|
||||
sampling {
|
||||
max_geometry_displacement_m: 0.002
|
||||
max_check_period_s: 0.01
|
||||
}
|
||||
|
||||
# 距离阈值作用于简化碰撞体之间的最小间距。
|
||||
safety {
|
||||
warning_distance_m: 0.02
|
||||
stop_distance_m: 0.005
|
||||
}
|
||||
|
||||
recovery {
|
||||
clear_distance_m: 0.025
|
||||
stable_period_s: 0.1
|
||||
max_joint_velocity_rad_s: 0.15
|
||||
max_joint_acceleration_rad_s2: 0.3
|
||||
history_duration_s: 10.0
|
||||
max_distance_regression_m: 0.001
|
||||
}
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
# 小赵实机右臂独立自碰撞检测:仅本臂 + 固定 base,排除另一臂与活动头部。
|
||||
self_collision_task {
|
||||
id: "xiaozhao_right_arm_self_collision"
|
||||
arm_id: "xiaozhao_tchl_right_arm"
|
||||
|
||||
checker {
|
||||
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
|
||||
ignored_pairs {
|
||||
first: "link5-right"
|
||||
second: "link7-right"
|
||||
}
|
||||
}
|
||||
|
||||
sampling {
|
||||
max_geometry_displacement_m: 0.002
|
||||
max_check_period_s: 0.01
|
||||
}
|
||||
|
||||
# 距离阈值作用于简化碰撞体之间的最小间距。
|
||||
safety {
|
||||
warning_distance_m: 0.02
|
||||
stop_distance_m: 0.005
|
||||
}
|
||||
|
||||
recovery {
|
||||
clear_distance_m: 0.025
|
||||
stable_period_s: 0.1
|
||||
max_joint_velocity_rad_s: 0.15
|
||||
max_joint_acceleration_rad_s2: 0.3
|
||||
history_duration_s: 10.0
|
||||
max_distance_regression_m: 0.001
|
||||
}
|
||||
}
|
||||
@ -7,8 +7,7 @@ touch_screen_task {
|
||||
|
||||
devices {
|
||||
arm_id: "right_arm"
|
||||
# devices/touch/touch.pb.txt 中的 PX6AXGenXCan,使用 CAN 合力数据,单位为 N。
|
||||
touch_id: "paxini_tip"
|
||||
dexhand_id: "paxini_tip_1"
|
||||
# 手部相机和外部相机的 DeviceManager ID。
|
||||
camera_id: "right_hand_cam"
|
||||
external_camera_id: "left_hand_cam"
|
||||
@ -76,9 +75,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.1 ry: 0.0 rz: -1.57 }
|
||||
hand_orientation_G { rx: 0.0 ry: 0.0 rz: -1.57 }
|
||||
# 点击目标点到 TCP 预对齐位置的偏移,表达在 G 坐标系,单位为米。
|
||||
position_offset_G { x: 0.003 y: 0.0 z: 0.00 }
|
||||
position_offset_G { x: 0.0 y: 0.0 z: 0.00 }
|
||||
mode: TOUCH_SCREEN_ALIGN_MODE_RX_RY_AND_POSITION
|
||||
}
|
||||
error_threshold {
|
||||
@ -104,6 +103,8 @@ touch_screen_task {
|
||||
max_distance_m: 0.03
|
||||
}
|
||||
tactile {
|
||||
finger: TOUCH_SCREEN_FINGER_TYPE_INDEX
|
||||
region: TOUCH_SCREEN_TACTILE_REGION_TIP
|
||||
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
|
||||
force_threshold: 0.1 # N
|
||||
}
|
||||
|
||||
@ -7,8 +7,7 @@ touch_screen_task {
|
||||
|
||||
devices {
|
||||
arm_id: "mujoco_right_arm"
|
||||
# ZeroSimTouch 始终返回零力,用于测试无接触时的前进限距和回撤流程。
|
||||
touch_id: "mujoco_zero_touch"
|
||||
dexhand_id: "mujoco_zero_touch_dexhand"
|
||||
# 手部相机和外部相机的 DeviceManager ID。
|
||||
camera_id: "mujoco_hand_cam"
|
||||
external_camera_id: "mujoco_external_touch_cam"
|
||||
@ -36,16 +35,15 @@ touch_screen_task {
|
||||
}
|
||||
|
||||
perception {
|
||||
# 屏幕 Tag G 与手部 Tag H 的 ID 和黑框外缘边长(不含外围白边),单位为米。
|
||||
# 当前 MuJoCo 标签整张含白边为 20 mm,黑框外缘为 16 mm。
|
||||
# 屏幕 Tag G 与手部 Tag H 的 ID 和物理边长,单位为米。
|
||||
tags {
|
||||
screen {
|
||||
id: 1
|
||||
size_m: 0.016
|
||||
size_m: 0.03
|
||||
}
|
||||
hand {
|
||||
id: 0
|
||||
size_m: 0.016
|
||||
size_m: 0.03
|
||||
}
|
||||
}
|
||||
# 手部相机:用于点击目标点和手部目标跟踪。
|
||||
@ -122,10 +120,11 @@ touch_screen_task {
|
||||
twist_tool { x: 0.0 y: -0.02 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
acceleration: 10.0
|
||||
linear_jerk: 100.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。
|
||||
# 零力不会触发接触;达到此距离后回撤,最终状态为 TOUCH_FORWARD_TIMEOUT。
|
||||
max_distance_m: 0.02
|
||||
}
|
||||
tactile {
|
||||
finger: TOUCH_SCREEN_FINGER_TYPE_INDEX
|
||||
region: TOUCH_SCREEN_TACTILE_REGION_TIP
|
||||
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
|
||||
force_threshold: 0.1 # N
|
||||
}
|
||||
|
||||
@ -1,160 +0,0 @@
|
||||
# xiaozhao 右臂视觉触屏流程仿真;ZeroSimTouch 不模拟真实接触力。
|
||||
touch_screen_task {
|
||||
id: "touch_screen"
|
||||
# 是否在外部相机编码后的 gRPC 视频流中绘制 G/H 坐标系,仅影响显示帧;未配置时默认开启。
|
||||
debug_draw_coordinate_frames: true
|
||||
# G/H 坐标轴长度,单位为米。
|
||||
debug_coordinate_axis_length_m: 0.02
|
||||
|
||||
devices {
|
||||
arm_id: "xiaozhao_mujoco_right_arm"
|
||||
head_id: "xiaozhao_mujoco_head"
|
||||
# ZeroSimTouch 始终返回零力,用于测试无接触时的前进限距和回撤流程。
|
||||
touch_id: "mujoco_zero_touch"
|
||||
# 手部相机和外部相机的 DeviceManager ID。
|
||||
camera_id: "xiaozhao_mujoco_hand_cam"
|
||||
external_camera_id: "xiaozhao_mujoco_external_touch_cam"
|
||||
}
|
||||
|
||||
# 任务 init() 时同步执行一次头部 MoveJ,到位后任务才进入 IDLE。
|
||||
# 后续每次 touch 请求不重复移动头部。角度单位 rad,顺序通过关节名匹配。
|
||||
head_initialization {
|
||||
enable: true
|
||||
# 头部朝向使外部相机同时看到屏幕和手背的 AprilTag。
|
||||
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
|
||||
}
|
||||
|
||||
initialization {
|
||||
# 三个开关决定何时回初始位。启用的回位动作使用 USE_MOVEJ 或 USE_MOVEP。
|
||||
motion_method: USE_MOVEJ
|
||||
before_start: true
|
||||
after_finish: true
|
||||
after_failure: true
|
||||
# S05 场景中 TCP 距屏幕正面约 57 mm。手相机 1280×720 原图的测试点为 (739, 673)。
|
||||
joint_positions { joint_name: "joint1-right" rad: 2.11258599 }
|
||||
joint_positions { joint_name: "joint2-right" rad: 0.76424120 }
|
||||
joint_positions { joint_name: "joint3-right" rad: -0.89182957 }
|
||||
joint_positions { joint_name: "joint4-right" rad: -1.46915085 }
|
||||
joint_positions { joint_name: "joint5-right" rad: -0.98091181 }
|
||||
joint_positions { joint_name: "joint6-right" rad: -0.17745411 }
|
||||
joint_positions { joint_name: "joint7-right" rad: -0.36598028 }
|
||||
velocity: 0.5 # rad/s
|
||||
acceleration: 1.0 # rad/s^2
|
||||
jerk: 300.0 # rad/s^3,沿用原回位默认值。
|
||||
# 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。
|
||||
skip_position_tolerance_rad: 0.001
|
||||
# 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。
|
||||
skip_velocity_tolerance_rad_s: 0.01
|
||||
}
|
||||
|
||||
perception {
|
||||
# 屏幕 Tag G 与手部 Tag H 的 ID 和黑框外缘边长(不含外围白边),单位为米。
|
||||
# 当前 MuJoCo 标签整张含白边为 20 mm,黑框外缘为 16 mm。
|
||||
tags {
|
||||
screen {
|
||||
id: 1
|
||||
size_m: 0.016
|
||||
}
|
||||
hand {
|
||||
id: 0
|
||||
size_m: 0.016
|
||||
}
|
||||
}
|
||||
# 手部相机:用于点击目标点和手部目标跟踪。
|
||||
hand_camera {
|
||||
|
||||
depth_policy: TOUCH_SCREEN_DEPTH_POLICY_NONE
|
||||
target_point_method: TOUCH_SCREEN_TARGET_POINT_METHOD_TAG_PLANE
|
||||
}
|
||||
}
|
||||
|
||||
approach {
|
||||
# MoveP 先将 TCP 移至点击点前方 50 mm,再进入 PBVS 视觉对齐。
|
||||
enable: true
|
||||
velocity: 0.65 # rad/s
|
||||
acceleration: 1.7 # rad/s^2
|
||||
jerk: 30.0 # rad/s^3
|
||||
timeout_s: 10.0
|
||||
# TCP 沿屏幕外法向的最小距离,仅检查 TCP,不覆盖整臂碰撞。
|
||||
minimum_clearance_m: 0.01
|
||||
}
|
||||
|
||||
alignment {
|
||||
calibration {
|
||||
# 手部 Tag H 到 TCP P 的固定安装变换 T_H_P,来自 xiaozhao MJCF。
|
||||
hand_tag_to_tcp {
|
||||
m00: 1.0 m01: 0.0 m02: 0.0 m03: -0.0275
|
||||
m10: 0.0 m11: 0.0 m12: -1.0 m13: 0.081
|
||||
m20: 0.0 m21: 1.0 m22: 0.0 m23: -0.1354
|
||||
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.02 rx: 0.15 ry: 0.15 rz: 0.15 }
|
||||
amax6 { x: 0.10 y: 0.10 z: 0.10 rx: 0.50 ry: 0.50 rz: 0.50 }
|
||||
twist_filter_alpha: 1.0
|
||||
}
|
||||
target {
|
||||
# Hand Tag H 相对于屏幕 Tag G 的目标姿态,单位为弧度。
|
||||
# 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
|
||||
# 使用检测得到的 G:屏幕纹理使 G 相对 MJCF body 绕 Z 旋转 pi,H 与 body 同向。
|
||||
# 因此这里的 pi 对应物理手部正立、TCP +Z 沿屏幕向上;设为 0 反而会翻转手腕。
|
||||
rz: 3.141592653589793
|
||||
}
|
||||
# 点击目标点到 TCP 预对齐位置的偏移,表达在 G 坐标系,单位为米。
|
||||
position_offset_G {
|
||||
x: 0.0
|
||||
y: 0.0
|
||||
z: 0.05
|
||||
}
|
||||
mode: TOUCH_SCREEN_ALIGN_MODE_RX_RY_AND_POSITION
|
||||
}
|
||||
error_threshold {
|
||||
x: 0.005
|
||||
y: 0.005
|
||||
z: 0.005
|
||||
rx: 0.08726646259971647
|
||||
ry: 0.08726646259971647
|
||||
rz: 0.08726646259971647
|
||||
}
|
||||
stable_frames: 5
|
||||
# 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。
|
||||
timeout_s: 30.0
|
||||
# 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。
|
||||
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: 10
|
||||
linear_jerk: 100.0 # m/s^3,不超过小赵 SpeedL 的 5.0 上限。
|
||||
# 零力不会触发接触;达到此距离后回撤,最终状态为 TOUCH_FORWARD_TIMEOUT。
|
||||
max_distance_m: 0.02
|
||||
}
|
||||
tactile {
|
||||
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
|
||||
force_threshold: 0.1 # N
|
||||
}
|
||||
dwell_time_s: 0.0
|
||||
}
|
||||
|
||||
retract {
|
||||
twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
|
||||
acceleration: 10
|
||||
linear_jerk: 100.0 # m/s^3
|
||||
# TCP 后退目标距离,单位为米。
|
||||
distance_m: 0.02
|
||||
}
|
||||
}
|
||||
@ -1,129 +0,0 @@
|
||||
# 小赵实机右臂触屏任务。启用前核对 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
|
||||
}
|
||||
}
|
||||
@ -3,7 +3,6 @@ add_subdirectory(agv)
|
||||
add_subdirectory(speaker)
|
||||
add_subdirectory(microphone)
|
||||
add_subdirectory(dexhand)
|
||||
add_subdirectory(touch)
|
||||
add_subdirectory(biohead)
|
||||
add_subdirectory(arm)
|
||||
add_subdirectory(canbus)
|
||||
|
||||
@ -38,7 +38,7 @@
|
||||
- 设备配置:
|
||||
[`../../../config/devices/agv/agv.pb.txt`](../../../config/devices/agv/agv.pb.txt)
|
||||
- DeviceManager 配置:
|
||||
[`../../../config/manager/real_device_manager.pb.txt`](../../../config/manager/real_device_manager.pb.txt)
|
||||
[`../../../config/manager/device_manager.pb.txt`](../../../config/manager/device_manager.pb.txt)
|
||||
- gRPC API:
|
||||
[`../../../../protos/cmvr/api/agv_service.proto`](../../../../protos/cmvr/api/agv_service.proto)、
|
||||
[`../../../../protos/cmvr/api/agv_command.proto`](../../../../protos/cmvr/api/agv_command.proto)、
|
||||
@ -72,7 +72,7 @@ agv {
|
||||
}
|
||||
```
|
||||
|
||||
还要在 `real_device_manager.pb.txt` 中确认同一个设备 id,并在完成现场安全检查后把
|
||||
还要在 `device_manager.pb.txt` 中确认同一个设备 id,并在完成现场安全检查后把
|
||||
`enable` 改为 `true`。源码默认配置故意保持关闭。
|
||||
|
||||
```textproto
|
||||
|
||||
@ -31,9 +31,6 @@ constexpr std::uint16_t kRobotConfigUploadMap = 4010;
|
||||
constexpr std::uint16_t kRobotConfigDownloadMap = 4011;
|
||||
constexpr std::uint16_t kRobotOtherStartMapping = 6100;
|
||||
constexpr std::uint16_t kRobotOtherStopMapping = 6101;
|
||||
// The controller can emit this asynchronous mapping event on port 19210
|
||||
// while a mapping session is active. It is not the reply to the next command.
|
||||
constexpr std::uint16_t kRobotOtherMappingEventResponse = 17002;
|
||||
constexpr std::uint16_t kRobotPushConfigReq = 9300;
|
||||
constexpr std::uint16_t kRobotPushConfigRes = 19300;
|
||||
constexpr std::uint16_t kRobotPush = 19301;
|
||||
|
||||
@ -33,31 +33,7 @@ static inline const Json::Value* jsonFind(
|
||||
const Json::Value& value,
|
||||
const char* key)
|
||||
{
|
||||
const auto* exact = value.find(key, key + std::strlen(key));
|
||||
if (exact) {
|
||||
return exact;
|
||||
}
|
||||
|
||||
std::string lower_camel;
|
||||
lower_camel.reserve(std::strlen(key));
|
||||
bool uppercase_next = false;
|
||||
for (const char* current = key; *current != '\0'; ++current) {
|
||||
if (*current == '_') {
|
||||
uppercase_next = true;
|
||||
continue;
|
||||
}
|
||||
char character = *current;
|
||||
if (uppercase_next && character >= 'a' && character <= 'z') {
|
||||
character = static_cast<char>(character - 'a' + 'A');
|
||||
}
|
||||
lower_camel.push_back(character);
|
||||
uppercase_next = false;
|
||||
}
|
||||
if (lower_camel == key) {
|
||||
return nullptr;
|
||||
}
|
||||
return value.find(lower_camel.data(),
|
||||
lower_camel.data() + lower_camel.size());
|
||||
return value.find(key, key + std::strlen(key));
|
||||
}
|
||||
|
||||
static inline Json::Value jsonGet(
|
||||
|
||||
@ -715,28 +715,6 @@ AgvResult SeerRobokitAgv::parseSeerRobokitMap2D_(
|
||||
}
|
||||
}
|
||||
|
||||
const auto* occupied_points = jsonFind(root, "normal_pos_list");
|
||||
if (occupied_points && occupied_points->isArray()
|
||||
&& map.resolution > 0.0 && map.width > 0 && map.height > 0) {
|
||||
const auto cell_count = static_cast<std::size_t>(map.width) * map.height;
|
||||
map.data.assign(cell_count, 0);
|
||||
for (const auto& point : *occupied_points) {
|
||||
const auto grid_x = static_cast<int>(std::floor(
|
||||
(jsonGet(point, "x", 0.0).asDouble() - map.origin.x)
|
||||
/ map.resolution));
|
||||
const auto grid_y = static_cast<int>(std::floor(
|
||||
(jsonGet(point, "y", 0.0).asDouble() - map.origin.y)
|
||||
/ map.resolution));
|
||||
if (grid_x >= 0 && grid_y >= 0
|
||||
&& grid_x < static_cast<int>(map.width)
|
||||
&& grid_y < static_cast<int>(map.height)) {
|
||||
const auto index = static_cast<std::size_t>(grid_y) * map.width
|
||||
+ static_cast<std::size_t>(grid_x);
|
||||
map.data[index] = 100;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto make_id = [](const Json::Value& value, const char* prefix, const int index) {
|
||||
std::string id = jsonGet(value, "instance_name", "").asString();
|
||||
if (id.empty()) id = jsonGet(value, "id", "").asString();
|
||||
@ -883,17 +861,6 @@ AgvResult SeerRobokitAgv::parseSeerRobokitMap2D_(
|
||||
if (map_id.empty()) map_id = jsonGet(header, "map_name", "").asString();
|
||||
if (map_id.empty()) map_id = file_name;
|
||||
|
||||
if (map.resolution <= 0.0 || map.width == 0 || map.height == 0) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::CommandFailed,
|
||||
"SEER Robokit 2D map has invalid resolution or bounds: " + file_name);
|
||||
}
|
||||
if (map.data.empty() && map.objects.empty()) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::CommandFailed,
|
||||
"SEER Robokit 2D map has no renderable data: " + file_name);
|
||||
}
|
||||
|
||||
update = {};
|
||||
update.map_id = map_id;
|
||||
update.dimension = AgvMapDimension::Map2D;
|
||||
|
||||
@ -133,40 +133,25 @@ AgvResult SeerRobokitAgv::sendCommandRaw_(
|
||||
"SEER Robokit send command failed: " + systemError());
|
||||
}
|
||||
|
||||
std::uint16_t response_command = 0;
|
||||
std::string payload_text_response;
|
||||
const auto result = receiveFrame_(sock, response_command, payload_text_response);
|
||||
if (!result.ok()) {
|
||||
return result;
|
||||
}
|
||||
const auto expected_response_command = static_cast<std::uint16_t>(
|
||||
command + 10000U);
|
||||
constexpr int kMaximumSkippedMappingEvents = 16;
|
||||
for (int attempt = 0; attempt <= kMaximumSkippedMappingEvents; ++attempt) {
|
||||
std::uint16_t response_command = 0;
|
||||
std::string payload_text_response;
|
||||
const auto result = receiveFrame_(
|
||||
sock, response_command, payload_text_response);
|
||||
if (!result.ok()) {
|
||||
return result;
|
||||
}
|
||||
if (response_command == expected_response_command) {
|
||||
if (response_payload) {
|
||||
*response_payload = std::move(payload_text_response);
|
||||
}
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
const bool is_mapping_event =
|
||||
sock == sock_other_
|
||||
&& response_command == kRobotOtherMappingEventResponse;
|
||||
if (!is_mapping_event) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::CommandFailed,
|
||||
"SEER Robokit response command mismatch: expected="
|
||||
+ std::to_string(expected_response_command)
|
||||
+ ", actual=" + std::to_string(response_command));
|
||||
}
|
||||
if (response_command != expected_response_command) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::CommandFailed,
|
||||
"SEER Robokit response command mismatch: expected="
|
||||
+ std::to_string(expected_response_command)
|
||||
+ ", actual=" + std::to_string(response_command));
|
||||
}
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::Timeout,
|
||||
"SEER Robokit timed out waiting for response command "
|
||||
+ std::to_string(expected_response_command)
|
||||
+ " after repeated asynchronous mapping events");
|
||||
if (response_payload) {
|
||||
*response_payload = std::move(payload_text_response);
|
||||
}
|
||||
return AgvResult::success();
|
||||
};
|
||||
const auto close_matching_socket_locked = [this, sock]() {
|
||||
if (sock == sock_status_) {
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
add_library(aubo_arm SHARED
|
||||
src/aubo_arm.cpp
|
||||
src/aubo_trajectory_csv.cpp
|
||||
)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
@ -17,9 +16,7 @@ set(AUBO_SDK_INCLUDE_DIR ${AUBO_SDK_ROOT}/include)
|
||||
set(AUBO_SDK_LIB_DIR ${AUBO_SDK_ROOT}/lib)
|
||||
|
||||
if (EXISTS "${AUBO_SDK_INCLUDE_DIR}/aubo_sdk/rpc.h")
|
||||
# The public AuboArm header uses this macro in its object layout.
|
||||
# Consumers must compile with the same layout as the shared library.
|
||||
target_compile_definitions(aubo_arm PUBLIC CMVR_HAS_AUBO_SDK)
|
||||
target_compile_definitions(aubo_arm PRIVATE CMVR_HAS_AUBO_SDK)
|
||||
target_include_directories(aubo_arm PRIVATE ${AUBO_SDK_INCLUDE_DIR})
|
||||
if (EXISTS "${AUBO_SDK_LIB_DIR}")
|
||||
target_link_directories(aubo_arm PRIVATE ${AUBO_SDK_LIB_DIR})
|
||||
@ -36,27 +33,12 @@ target_link_libraries(aubo_arm
|
||||
glog
|
||||
jsoncpp
|
||||
Threads::Threads
|
||||
cmvr_es::joint_trajectory_smoother
|
||||
)
|
||||
|
||||
add_library(cmvr_es::device::aubo_arm ALIAS aubo_arm)
|
||||
install(TARGETS aubo_arm LIBRARY DESTINATION lib)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_executable(aubo_absolute_coordinate_test tests/aubo_absolute_coordinate_test.cpp)
|
||||
target_include_directories(aubo_absolute_coordinate_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es)
|
||||
add_test(NAME aubo_absolute_coordinate_test COMMAND aubo_absolute_coordinate_test)
|
||||
add_executable(aubo_user_coordinate_store_test tests/aubo_user_coordinate_store_test.cpp)
|
||||
target_include_directories(aubo_user_coordinate_store_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es)
|
||||
target_link_libraries(aubo_user_coordinate_store_test PRIVATE jsoncpp Threads::Threads)
|
||||
add_test(NAME aubo_user_coordinate_store_test COMMAND aubo_user_coordinate_store_test)
|
||||
add_executable(aubo_user_frame_validation_test tests/aubo_user_frame_validation_test.cpp)
|
||||
target_include_directories(aubo_user_frame_validation_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es)
|
||||
target_link_libraries(aubo_user_frame_validation_test PRIVATE aubo_arm cmvr_es::proto)
|
||||
add_test(NAME aubo_user_frame_validation_test COMMAND aubo_user_frame_validation_test)
|
||||
add_executable(joint_trajectory_csv_test tests/joint_trajectory_csv_test.cpp)
|
||||
target_include_directories(joint_trajectory_csv_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es)
|
||||
add_test(NAME joint_trajectory_csv_test COMMAND joint_trajectory_csv_test)
|
||||
add_executable(aubo_arm_motion_result_test
|
||||
tests/aubo_arm_motion_result_test.cpp)
|
||||
target_include_directories(aubo_arm_motion_result_test
|
||||
|
||||
@ -18,16 +18,6 @@ namespace cmvr::device {
|
||||
|
||||
class AuboArm final : public RobotArm {
|
||||
public:
|
||||
Result applyUserCoordinateSystem(const std::string& name, std::uint64_t revision) override;
|
||||
Result calibrateUserCoordinate(const std::vector<std::vector<double>>& points, std::vector<double>& pose);
|
||||
Result applyBuiltinCoordinate(const std::string& name,
|
||||
std::vector<double>& actual_tcp_offset);
|
||||
Result applyUserCoordinates(const std::vector<double>& user_pose,
|
||||
const std::vector<double>& tcp_offset,
|
||||
std::vector<double>& actual_tcp_offset,
|
||||
const std::string& name = {}, std::uint64_t revision = 0);
|
||||
bool currentUserCoordinateMatches(const std::string& name, std::uint64_t revision) const;
|
||||
bool lastAppliedUserCoordinate(std::string& name,std::uint64_t& revision) const;
|
||||
explicit AuboArm(const config::RobotArmConfig& cfg);
|
||||
~AuboArm() override;
|
||||
|
||||
@ -38,14 +28,13 @@ public:
|
||||
std::string& response_json) override;
|
||||
|
||||
RobotModel getRobotModel() const override { return model_; }
|
||||
RobotModel queryRobotModel() const override;
|
||||
std::size_t getDof() const override { return model_.dof; }
|
||||
ArmState getRobotState() const override;
|
||||
JointGroupState getJointState() const override;
|
||||
CartesianPose getTcpPose(FrameType frame = FrameType::Base) const override;
|
||||
RobotMode getRobotMode() const override;
|
||||
SafetyMode getSafetyMode() const override;
|
||||
ControlMode getControlMode() const override;
|
||||
ControlMode getControlMode() const override { return ControlMode::Position; }
|
||||
bool supportsActionQueueMotion() const noexcept override { return true; }
|
||||
Result listBaseFrame(std::vector<std::string>& frame_names) const override;
|
||||
Result listTCPFrame(std::vector<std::string>& frame_names) const override;
|
||||
@ -72,9 +61,6 @@ public:
|
||||
Result moveJ(const JointPositionCommand& target, const MotionOptions& options) override;
|
||||
Result speedJ(const JointVelocityCommand& velocity, double acceleration, double duration) override;
|
||||
Result stopJ(double acceleration) override;
|
||||
Result moveLInUserFrame(const CartesianPose& target,
|
||||
const MotionOptions& options, const std::vector<double>& user_pose,
|
||||
const std::vector<double>& tcp_offset);
|
||||
Result moveL(const CartesianPose& target,
|
||||
const MotionOptions& options,
|
||||
FrameType frame = FrameType::Base) override;
|
||||
@ -106,16 +92,6 @@ public:
|
||||
Result playProgram() override;
|
||||
Result pauseProgram() override;
|
||||
Result stopProgram() override;
|
||||
Result enterTeachingMode() override;
|
||||
Result startTrajectoryRecording(const std::string& file_name) override;
|
||||
Result startTrajectoryRecording(const std::string& file_name, double frequency_hz) override;
|
||||
Result listRecordedTrajectories(std::vector<RecordedTrajectoryInfo>&,
|
||||
TrajectoryRecordingStatus&) const override;
|
||||
Result replayRecordedTrajectory(const std::string&, double, bool,
|
||||
const MotionOptions&) override;
|
||||
Result completeTeaching() override;
|
||||
Result stopTrajectoryRecording() override;
|
||||
Result exitTeachingMode() override;
|
||||
|
||||
std::vector<double> ik(const std::string& base_link,
|
||||
const std::string& ee_link,
|
||||
@ -123,18 +99,10 @@ public:
|
||||
std::shared_ptr<cmvr::IKSolver> kinematicsSolver() const override { return nullptr; }
|
||||
CartesianPose fk(const std::string& base_link, const std::string& ee_link) override;
|
||||
CartesianPose fk(bool is_tcp = true) override;
|
||||
bool isBaseReference(const std::string& name) const;
|
||||
Result getPoseInCoordinate(const std::string& name, const std::vector<double>& base_reference,
|
||||
const std::string& end_frame, CartesianPose& pose);
|
||||
CartesianVelocity getSpeedLCommandTwistBase() const override { return {}; }
|
||||
bool busy() const override { return busy_.load(); }
|
||||
|
||||
private:
|
||||
Result configureWorkObject_(const std::vector<double>& base_user_pose, bool invalidate = true);
|
||||
Result moveLConfigured_(const CartesianPose& target, const MotionOptions& options,
|
||||
const std::string& base_frame, const std::string& tcp_frame,
|
||||
const std::vector<double>* user_pose,
|
||||
const std::vector<double>* tcp_offset);
|
||||
enum class ActiveMotion {
|
||||
None,
|
||||
Joint,
|
||||
@ -176,17 +144,6 @@ private:
|
||||
std::atomic<bool> hardware_estop_latched_{false};
|
||||
std::atomic<bool> auto_recovery_suppressed_{false};
|
||||
mutable std::mutex mutex_;
|
||||
mutable std::mutex user_coordinate_mutex_;
|
||||
std::atomic<bool> user_coordinates_active_{false};
|
||||
// Absolute tool reference is frozen at Apply and shared by MoveL/GetPose.
|
||||
std::atomic<bool> builtin_tool_reference_{false};
|
||||
std::string applied_user_coordinate_name_;
|
||||
std::uint64_t applied_user_coordinate_revision_{};
|
||||
std::vector<double> applied_base_user_pose_;
|
||||
std::vector<double> applied_tcp_offset_;
|
||||
struct CsvRecording;
|
||||
std::shared_ptr<CsvRecording> csv_recording_;
|
||||
mutable std::mutex trajectory_mutex_;
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
std::unique_ptr<SdkState> sdk_;
|
||||
|
||||
@ -1,124 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace cmvr::device::aubo_csv {
|
||||
constexpr std::size_t maxSamples = 180001; // At most 30 minutes at 100 Hz.
|
||||
inline std::string fileName(std::string name)
|
||||
{
|
||||
if (name.empty() || name.size() > 120 || name.front() == '.' ||
|
||||
name.find("..") != std::string::npos)
|
||||
throw std::runtime_error("invalid trajectory file name");
|
||||
for (const unsigned char c : name)
|
||||
if (c < 32 || std::string("/\\:*?\"<>|").find(c) != std::string::npos)
|
||||
throw std::runtime_error("trajectory name must not contain a path or reserved characters");
|
||||
if (name.size() < 4 || name.substr(name.size() - 4) != ".csv") name += ".csv";
|
||||
return name;
|
||||
}
|
||||
inline std::filesystem::path directory(const std::string& device)
|
||||
{
|
||||
if (device.empty() || device == "." || device == ".." ||
|
||||
device.find_first_of("/\\") != std::string::npos)
|
||||
throw std::runtime_error("invalid device ID for trajectory directory");
|
||||
return std::filesystem::read_symlink("/proc/self/exe").parent_path() /
|
||||
"data" / "trajectories" / device;
|
||||
}
|
||||
inline std::string columns(const std::vector<std::string>& joints)
|
||||
{
|
||||
std::string line = "time_s";
|
||||
for (const auto& joint : joints) {
|
||||
if (joint.empty() || joint.find_first_of(",\r\n") != std::string::npos)
|
||||
throw std::runtime_error("invalid joint name in CSV header");
|
||||
line += "," + joint + "_rad";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
struct Trajectory {
|
||||
std::vector<double> times;
|
||||
std::vector<std::vector<double>> points;
|
||||
double frequency{};
|
||||
};
|
||||
inline double number(const std::string& s)
|
||||
{
|
||||
std::size_t end{};
|
||||
const double value = std::stod(s, &end);
|
||||
if (end != s.size() || !std::isfinite(value)) throw std::runtime_error("invalid CSV number");
|
||||
return value;
|
||||
}
|
||||
inline Trajectory load(const std::filesystem::path& path, const std::string& device,
|
||||
const std::vector<std::string>& joints)
|
||||
{
|
||||
if (std::filesystem::is_symlink(path) || !std::filesystem::is_regular_file(path) ||
|
||||
std::filesystem::file_size(path) > 64 * 1024 * 1024)
|
||||
throw std::runtime_error("trajectory must be a regular CSV smaller than 64 MB");
|
||||
std::ifstream in(path);
|
||||
std::string line;
|
||||
const auto next = [&]() {
|
||||
if (!std::getline(in, line)) throw std::runtime_error("incomplete trajectory CSV");
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
};
|
||||
next();
|
||||
if (line != "# cmvr_joint_trajectory_v1") throw std::runtime_error("unsupported trajectory CSV version");
|
||||
next();
|
||||
if (line != "# device_id=" + device) throw std::runtime_error("trajectory device ID mismatch");
|
||||
next();
|
||||
if (line.rfind("# frequency_hz=", 0) != 0) throw std::runtime_error("missing sample frequency");
|
||||
Trajectory result;
|
||||
result.frequency = number(line.substr(15));
|
||||
if (result.frequency < 1 || result.frequency > 100) throw std::runtime_error("invalid sample frequency");
|
||||
next();
|
||||
if (line != columns(joints)) throw std::runtime_error("trajectory joint names/order mismatch");
|
||||
while (std::getline(in, line)) {
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
std::stringstream row(line);
|
||||
std::string cell;
|
||||
std::vector<double> values;
|
||||
while (std::getline(row, cell, ',')) values.push_back(number(cell));
|
||||
if (line.empty() || line.back() == ',' || values.size() != joints.size() + 1)
|
||||
throw std::runtime_error("invalid CSV joint count");
|
||||
const double t = values.front();
|
||||
if (t < 0 || (result.times.empty() && t != 0) || t > 1800 ||
|
||||
(!result.times.empty() && (t <= result.times.back() ||
|
||||
t - result.times.back() > std::max(0.1, 3.0 / result.frequency))))
|
||||
throw std::runtime_error("non-monotonic time or missing trajectory samples");
|
||||
result.times.push_back(t);
|
||||
result.points.emplace_back(values.begin() + 1, values.end());
|
||||
if (result.times.size() > maxSamples) throw std::runtime_error("trajectory too long");
|
||||
}
|
||||
if (in.bad() || result.points.size() < 3 || result.times.back() < 0.02)
|
||||
throw std::runtime_error("trajectory requires at least 3 valid samples and 20 ms");
|
||||
return result;
|
||||
}
|
||||
// Preserve elapsed controller time, including minor RTDE jitter. Large gaps
|
||||
// are rejected by load(); never replay sparse points as consecutive 10 ms samples.
|
||||
inline Trajectory resample(const Trajectory& source, double ratio)
|
||||
{
|
||||
if (!std::isfinite(ratio) || ratio < 0.1 || ratio > 1)
|
||||
throw std::runtime_error("replay speed ratio must be between 0.1 and 1");
|
||||
Trajectory result;
|
||||
const double duration = source.times.back();
|
||||
const std::size_t intervals = static_cast<std::size_t>(std::floor(duration * 100));
|
||||
const double dt = duration / intervals;
|
||||
result.frequency = ratio / dt;
|
||||
std::size_t k = 1;
|
||||
for (std::size_t i = 0; i <= intervals; ++i) {
|
||||
const double t = (i == intervals) ? duration : dt * i;
|
||||
while (k + 1 < source.times.size() && source.times[k] < t) ++k;
|
||||
const double fraction = std::clamp((t - source.times[k - 1]) /
|
||||
(source.times[k] - source.times[k - 1]), 0.0, 1.0);
|
||||
std::vector<double> q(source.points.front().size());
|
||||
for (std::size_t j = 0; j < q.size(); ++j)
|
||||
q[j] = source.points[k - 1][j] + fraction * (source.points[k][j] - source.points[k - 1][j]);
|
||||
result.points.push_back(std::move(q));
|
||||
result.times.push_back(t / ratio);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
} // namespace cmvr::device::aubo_csv
|
||||
@ -1,56 +0,0 @@
|
||||
#pragma once
|
||||
#include <array>
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
namespace cmvr::device {
|
||||
// Absolute target transform: T_base_tcp_goal = T_base_reference * T_reference_tcp_goal.
|
||||
// It deliberately has no current-TCP argument, so repeated goals cannot accumulate.
|
||||
template<class Compose>
|
||||
inline std::vector<double> coordinateAbsoluteTarget(const std::vector<double>& reference,
|
||||
const std::vector<double>& target,Compose compose) {
|
||||
const auto valid=[](const std::vector<double>& p){return p.size()==6&&std::all_of(p.begin(),p.end(),[](double x){return std::isfinite(x);});};
|
||||
if(!valid(reference)||!valid(target))throw std::invalid_argument("absolute reference and target require six finite m/rad values");
|
||||
auto result=compose(reference,target);
|
||||
if(!valid(result))throw std::runtime_error("SDK Math returned invalid absolute target");
|
||||
return result;
|
||||
}
|
||||
// Feedback transform: T_reference_end = inverse(T_base_reference) * T_base_end.
|
||||
template<class Inverse,class Compose>
|
||||
inline std::vector<double> coordinateFeedbackPose(const std::vector<double>& reference,
|
||||
const std::vector<double>& actual,Inverse inverse,Compose compose) {
|
||||
const auto valid=[](const std::vector<double>& p){return p.size()==6&&std::all_of(p.begin(),p.end(),[](double x){return std::isfinite(x);});};
|
||||
if(!valid(reference)||!valid(actual))throw std::invalid_argument("feedback reference and actual pose require six finite m/rad values");
|
||||
return coordinateAbsoluteTarget(inverse(reference),actual,compose);
|
||||
}
|
||||
// Geometry validation for SDK Math::calibrateCoordinate(poses, 0): O, +X, +Y half-plane.
|
||||
inline std::vector<double> threePointFrame(const std::vector<std::vector<double>>& points) {
|
||||
if(points.size()!=3)throw std::invalid_argument("exactly three base TCP poses required: origin, +X, XY plane");
|
||||
for(const auto& p:points)if(p.size()!=6)throw std::invalid_argument("each point must contain six values (m/rad)");
|
||||
for(const auto& p:points)for(double x:p)if(!std::isfinite(x))throw std::invalid_argument("non-finite calibration point");
|
||||
std::array<double,3> x{},y{},z{};
|
||||
double nx=0,ny=0,projection=0;
|
||||
for(int i=0;i<3;++i){x[i]=points[1][i]-points[0][i];y[i]=points[2][i]-points[0][i];nx+=x[i]*x[i];}
|
||||
nx=std::sqrt(nx);if(nx<1e-5)throw std::invalid_argument("origin and +X point are coincident or too close (<0.01 mm)");
|
||||
for(int i=0;i<3;++i){x[i]/=nx;projection+=x[i]*y[i];}
|
||||
for(int i=0;i<3;++i){y[i]-=projection*x[i];ny+=y[i]*y[i];}
|
||||
ny=std::sqrt(ny);if(ny<1e-5)throw std::invalid_argument("three points are collinear or XY plane height is too small (<0.01 mm)");
|
||||
for(double& v:y)v/=ny;
|
||||
z={x[1]*y[2]-x[2]*y[1],x[2]*y[0]-x[0]*y[2],x[0]*y[1]-x[1]*y[0]};
|
||||
const double ry=std::atan2(-x[2],std::hypot(x[0],x[1]));
|
||||
const bool singular=std::hypot(x[0],x[1])<1e-10;
|
||||
const double rx=singular?0:std::atan2(y[2],z[2]);
|
||||
const double rz=singular?std::atan2(-y[0],y[1]):std::atan2(x[1],x[0]);
|
||||
return {points[0][0],points[0][1],points[0][2],rx,ry,rz};
|
||||
}
|
||||
inline bool sameCoordinateFrame(const std::vector<double>& a,const std::vector<double>& b,double tolerance=1e-6){
|
||||
if(a.size()!=6||b.size()!=6)return false;
|
||||
for(int i=0;i<3;++i)if(!std::isfinite(a[i])||!std::isfinite(b[i])||std::abs(a[i]-b[i])>tolerance)return false;
|
||||
const auto rotation=[](const std::vector<double>& p){
|
||||
const double x=p[3],y=p[4],z=p[5],cx=std::cos(x),sx=std::sin(x),cy=std::cos(y),sy=std::sin(y),cz=std::cos(z),sz=std::sin(z);
|
||||
return std::array<double,9>{cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx,sz*cy,sz*sy*sx+cz*cx,sz*sy*cx-cz*sx,-sy,cy*sx,cy*cx};
|
||||
};
|
||||
const auto ra=rotation(a),rb=rotation(b);for(int i=0;i<9;++i)if(!std::isfinite(ra[i])||!std::isfinite(rb[i])||std::abs(ra[i]-rb[i])>tolerance)return false;return true;
|
||||
}
|
||||
}
|
||||
@ -1,153 +0,0 @@
|
||||
#pragma once
|
||||
#include <json/json.h>
|
||||
#include "three_point_frame.h"
|
||||
#include <filesystem>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace cmvr::device {
|
||||
struct UserCoordinateProfile {
|
||||
std::string name;
|
||||
std::vector<double> user_pose, tcp_offset; // T_base_user and T_flange_tcp, m/rad.
|
||||
std::uint64_t revision{};
|
||||
std::vector<std::vector<double>> calibration_points;
|
||||
};
|
||||
struct CoordinateStoreError : std::runtime_error {
|
||||
enum Kind { Invalid, Missing, Exists, Conflict, Storage } kind;
|
||||
CoordinateStoreError(Kind k,const std::string& text):std::runtime_error(text),kind(k){}
|
||||
};
|
||||
class UserCoordinateStore {
|
||||
std::filesystem::path directory_;
|
||||
static Json::Value& field(Json::Value& value,const char* key) { return *value.demand(key,key+std::strlen(key)); }
|
||||
static const Json::Value& field(const Json::Value& value,const char* key) {
|
||||
const auto* found=value.find(key,key+std::strlen(key));static const Json::Value empty;
|
||||
return found?*found:empty;
|
||||
}
|
||||
static void require(bool ok,CoordinateStoreError::Kind kind,const std::string& text) {
|
||||
if(!ok)throw CoordinateStoreError(kind,text);
|
||||
}
|
||||
struct Lock {
|
||||
int fd{-1};
|
||||
explicit Lock(const std::filesystem::path& path) {
|
||||
fd=::open(path.c_str(),O_RDWR|O_CREAT|O_CLOEXEC|O_NOFOLLOW,0600);
|
||||
if(fd<0 || ::flock(fd,LOCK_EX)!=0){if(fd>=0)::close(fd);throw CoordinateStoreError(CoordinateStoreError::Storage,"cannot lock coordinate store");}
|
||||
}
|
||||
~Lock(){if(fd>=0){::flock(fd,LOCK_UN);::close(fd);}}
|
||||
};
|
||||
Json::Value read() const {
|
||||
const auto path=directory_/"coordinates.json";
|
||||
require(!std::filesystem::is_symlink(path),CoordinateStoreError::Storage,"coordinate file must not be a symbolic link");
|
||||
Json::Value root(Json::objectValue);
|
||||
if(!std::filesystem::exists(path)) {
|
||||
field(root,"version")=2;field(root,"next_revision")=Json::UInt64(1);field(root,"coordinates")=Json::Value(Json::arrayValue);return root;
|
||||
}
|
||||
int fd=::open(path.c_str(),O_RDONLY|O_CLOEXEC|O_NOFOLLOW);
|
||||
require(fd>=0,CoordinateStoreError::Storage,"cannot open coordinate store");
|
||||
std::string bytes;char buffer[4096];ssize_t count;
|
||||
while((count=::read(fd,buffer,sizeof(buffer)))>0){bytes.append(buffer,count);if(bytes.size()>2*1024*1024){::close(fd);throw CoordinateStoreError(CoordinateStoreError::Storage,"coordinate store too large");}}
|
||||
::close(fd);require(count==0,CoordinateStoreError::Storage,"coordinate store read failed");
|
||||
Json::CharReaderBuilder builder;builder[std::string("rejectDupKeys")]=true;builder[std::string("failIfExtra")]=true;
|
||||
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());std::string error;
|
||||
require(reader->parse(bytes.data(),bytes.data()+bytes.size(),&root,&error),CoordinateStoreError::Storage,"invalid coordinate JSON; original file preserved");
|
||||
// Explicitly discard the retired manual-pose schema. Preserve revision monotonicity.
|
||||
if(root.isObject() && field(root,"version").isInt() && field(root,"version").asInt()==1
|
||||
&& field(root,"coordinates").isArray() && field(root,"next_revision").isUInt64()) {
|
||||
field(root,"version")=2;field(root,"coordinates")=Json::Value(Json::arrayValue);write(root);
|
||||
}
|
||||
require(root.isObject()&&field(root,"version").isInt()&&field(root,"version").asInt()==2&&field(root,"next_revision").isUInt64()&&field(root,"coordinates").isArray(),CoordinateStoreError::Storage,"invalid coordinate schema; original file preserved");
|
||||
require(field(root,"coordinates").size()<=1000,CoordinateStoreError::Storage,"too many stored coordinates");
|
||||
std::set<std::string> names;
|
||||
for(const auto& value:field(root,"coordinates")){auto p=decode(value);validate(p);require(p.revision>0&&names.insert(p.name).second,CoordinateStoreError::Storage,"duplicate or invalid stored coordinate revision");}
|
||||
return root;
|
||||
}
|
||||
void write(const Json::Value& root) const {
|
||||
Json::StreamWriterBuilder builder;builder[std::string("indentation")]=" ";
|
||||
const auto bytes=Json::writeString(builder,root);
|
||||
std::string temp=(directory_/"coordinates.tmp.XXXXXX").string();
|
||||
std::vector<char> name(temp.begin(),temp.end());name.push_back(0);
|
||||
int fd=::mkstemp(name.data());require(fd>=0,CoordinateStoreError::Storage,"cannot create coordinate temporary file");
|
||||
bool ok=true;std::size_t offset=0;
|
||||
while(offset<bytes.size()){auto n=::write(fd,bytes.data()+offset,bytes.size()-offset);if(n<=0){ok=false;break;}offset+=n;}
|
||||
ok=(::fsync(fd)==0)&&ok;::close(fd);
|
||||
if(!ok || ::rename(name.data(),(directory_/"coordinates.json").c_str())!=0){::unlink(name.data());throw CoordinateStoreError(CoordinateStoreError::Storage,"cannot commit coordinate store; previous data retained");}
|
||||
int dir=::open(directory_.c_str(),O_RDONLY|O_DIRECTORY|O_CLOEXEC);if(dir>=0){::fsync(dir);::close(dir);}
|
||||
}
|
||||
public:
|
||||
explicit UserCoordinateStore(std::filesystem::path directory):directory_(std::move(directory)){}
|
||||
static UserCoordinateStore forArm(const std::string& id) {
|
||||
require(!id.empty()&&id!="."&&id!=".."&&id.find_first_of("/\\")==std::string::npos&&id.find('\0')==std::string::npos,CoordinateStoreError::Invalid,"invalid device ID");
|
||||
return UserCoordinateStore(std::filesystem::read_symlink("/proc/self/exe").parent_path()/"data"/"user_coordinates"/id);
|
||||
}
|
||||
static bool poseValid(const std::vector<double>& pose) {return pose.size()==6&&std::all_of(pose.begin(),pose.end(),[](double x){return std::isfinite(x);});}
|
||||
static void validate(const UserCoordinateProfile& p) {
|
||||
require(!p.name.empty()&&p.name.size()<=240&&p.name.front()!=' '&&p.name.back()!=' ',CoordinateStoreError::Invalid,"coordinate name is required (max 240 UTF-8 bytes)");
|
||||
for(unsigned char c:p.name)require(c>=32&&c!=127,CoordinateStoreError::Invalid,"coordinate name contains control characters");
|
||||
if(!isBuiltin(p.name)) { try {require(sameCoordinateFrame(threePointFrame(p.calibration_points),p.user_pose),CoordinateStoreError::Invalid,"calibrated frame does not match its three source points");} catch(const std::exception& e){throw CoordinateStoreError(CoordinateStoreError::Invalid,e.what());} }
|
||||
require(poseValid(p.user_pose)&&poseValid(p.tcp_offset),CoordinateStoreError::Invalid,"user_pose and tcp_offset must contain six finite values (m, rad)");
|
||||
}
|
||||
static Json::Value encode(const UserCoordinateProfile& p) {
|
||||
Json::Value v(Json::objectValue);field(v,"name")=p.name;field(v,"revision")=Json::UInt64(p.revision);
|
||||
field(v,"user_reference")="base";field(v,"tcp_reference")="flange";field(v,"units")="m_rad";
|
||||
field(v,"user_pose")=Json::Value(Json::arrayValue);field(v,"tcp_offset")=Json::Value(Json::arrayValue);
|
||||
field(v,"calibration_version")=2;field(v,"calibration_points")=Json::Value(Json::arrayValue);
|
||||
for(const auto& point:p.calibration_points){Json::Value a(Json::arrayValue);for(double x:point)a.append(x);field(v,"calibration_points").append(a);}
|
||||
for(double x:p.user_pose)field(v,"user_pose").append(x);for(double x:p.tcp_offset)field(v,"tcp_offset").append(x);return v;
|
||||
}
|
||||
static UserCoordinateProfile decode(const Json::Value& v) {
|
||||
require(v.isObject()&&field(v,"name").isString()&&field(v,"revision").isUInt64()&&field(v,"user_pose").isArray()&&field(v,"tcp_offset").isArray(),CoordinateStoreError::Storage,"invalid stored coordinate record");
|
||||
require(field(v,"user_reference").asString()=="base"&&field(v,"tcp_reference").asString()=="flange"&&field(v,"units").asString()=="m_rad",CoordinateStoreError::Storage,"unsupported stored coordinate convention");
|
||||
UserCoordinateProfile p;p.name=field(v,"name").asString();p.revision=field(v,"revision").asUInt64();
|
||||
require(field(v,"calibration_version").asInt()==2 && field(v,"calibration_points").isArray(),CoordinateStoreError::Storage,"retired or missing calibration data");
|
||||
for(const auto& point:field(v,"calibration_points")){std::vector<double> a;for(const auto& x:point){require(x.isNumeric(),CoordinateStoreError::Storage,"invalid calibration point");a.push_back(x.asDouble());}p.calibration_points.push_back(a);}
|
||||
for(const auto& x:field(v,"user_pose")){require(x.isNumeric(),CoordinateStoreError::Storage,"invalid pose number");p.user_pose.push_back(x.asDouble());}
|
||||
for(const auto& x:field(v,"tcp_offset")){require(x.isNumeric(),CoordinateStoreError::Storage,"invalid TCP number");p.tcp_offset.push_back(x.asDouble());}return p;
|
||||
}
|
||||
std::vector<UserCoordinateProfile> list() const {
|
||||
std::filesystem::create_directories(directory_);Lock lock(directory_/"coordinates.lock");const auto root=read();
|
||||
std::vector<UserCoordinateProfile> result;for(const auto& v:field(root,"coordinates"))result.push_back(decode(v));return result;
|
||||
}
|
||||
UserCoordinateProfile get(const std::string& name,std::uint64_t expected=0) const {
|
||||
if(isBuiltin(name)) {
|
||||
require(!expected||expected==1,CoordinateStoreError::Conflict,"invalid built-in coordinate revision");
|
||||
return builtin(name);
|
||||
}
|
||||
for(const auto& p:list())if(p.name==name){require(!expected||p.revision==expected,CoordinateStoreError::Conflict,"coordinate revision changed; refresh before applying or moving");return p;}
|
||||
throw CoordinateStoreError(CoordinateStoreError::Missing,"coordinate not found");
|
||||
}
|
||||
UserCoordinateProfile mutate(const std::string& operation,UserCoordinateProfile profile,std::uint64_t expected=0) const {
|
||||
require(!isBuiltin(profile.name),CoordinateStoreError::Invalid,"built-in coordinates cannot be created, edited or deleted");
|
||||
if(operation!="delete")validate(profile);
|
||||
std::filesystem::create_directories(directory_);Lock lock(directory_/"coordinates.lock");auto root=read();auto& records=field(root,"coordinates");
|
||||
int found=-1;for(unsigned i=0;i<records.size();++i)if(field(records[i],"name").asString()==profile.name)found=int(i);
|
||||
if(operation=="create")require(found<0,CoordinateStoreError::Exists,"coordinate already exists; use update");
|
||||
else {require(found>=0,CoordinateStoreError::Missing,"coordinate not found");require(expected>0&&decode(records[found]).revision==expected,CoordinateStoreError::Conflict,"coordinate revision changed or missing; refresh first");}
|
||||
if(operation=="delete"){Json::Value removed;records.removeIndex(found,&removed);profile=decode(removed);}
|
||||
else {
|
||||
const auto revision=field(root,"next_revision").asUInt64();require(revision>0&&revision<std::numeric_limits<std::uint64_t>::max(),CoordinateStoreError::Storage,"invalid revision counter");
|
||||
profile.revision=revision;field(root,"next_revision")=Json::UInt64(revision+1);
|
||||
if(found<0){require(records.size()<1000,CoordinateStoreError::Invalid,"coordinate limit reached");records.append(encode(profile));}else records[found]=encode(profile);
|
||||
}
|
||||
write(root);return profile;
|
||||
}
|
||||
static bool isBuiltin(const std::string& name) {
|
||||
return name=="__builtin_base__"||name=="__builtin_tool__";
|
||||
}
|
||||
static UserCoordinateProfile builtin(const std::string& name) {
|
||||
require(isBuiltin(name),CoordinateStoreError::Invalid,"unknown built-in coordinate");
|
||||
// These zeros are schema placeholders, NOT a TCP readback or saved tool.
|
||||
return {name,std::vector<double>(6,0.0),std::vector<double>(6,0.0),1};
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,6 +1,4 @@
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
#include "devices/arm/aubo_arm/include/three_point_frame.h"
|
||||
#include "devices/arm/aubo_arm/include/user_coordinate_store.h"
|
||||
#include "devices/arm/aubo_arm/include/aubo_motion_result.h"
|
||||
|
||||
#include <algorithm>
|
||||
@ -292,6 +290,26 @@ SafetyMode toPublicSafetyMode(
|
||||
return SafetyMode::Unknown;
|
||||
}
|
||||
|
||||
std::vector<std::string> listAuboWorldFrames(
|
||||
const arcs::common_interface::SyncMovePtr& sync_move)
|
||||
{
|
||||
if (!sync_move) {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::set<std::string> frame_names{"world", "base", "flange", "tcp"};
|
||||
std::vector<std::string> pending(frame_names.begin(), frame_names.end());
|
||||
for (std::size_t index = 0; index < pending.size(); ++index) {
|
||||
for (const auto& child : sync_move->frameGetChildren(pending[index])) {
|
||||
if (!child.empty() && sync_move->frameExist(child) &&
|
||||
frame_names.insert(child).second) {
|
||||
pending.push_back(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {frame_names.begin(), frame_names.end()};
|
||||
}
|
||||
|
||||
CartesianPose auboPoseFromVector(const std::vector<double>& values,
|
||||
const std::string& context)
|
||||
{
|
||||
@ -306,6 +324,14 @@ CartesianPose auboPoseFromVector(const std::vector<double>& values,
|
||||
};
|
||||
}
|
||||
|
||||
void insertFrameName(std::set<std::string>& frame_names,
|
||||
const std::string& frame_name)
|
||||
{
|
||||
if (!frame_name.empty()) {
|
||||
frame_names.insert(frame_name);
|
||||
}
|
||||
}
|
||||
|
||||
bool isAuboTcpFrame(const arcs::common_interface::SyncMovePtr& sync_move,
|
||||
const std::string& frame_name)
|
||||
{
|
||||
@ -425,139 +451,6 @@ bool AuboArm::stop()
|
||||
return stopMotion().ok();
|
||||
}
|
||||
|
||||
Result AuboArm::calibrateUserCoordinate(const std::vector<std::vector<double>>& points, std::vector<double>& pose)
|
||||
{
|
||||
try {threePointFrame(points);} catch(const std::exception& e){return Result::failure(ArmErrorCode::InvalidArgument,e.what());}
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
const auto ready=ensureConnected_("three-point calibration");if(!ready.ok())return ready;
|
||||
try {
|
||||
const auto result=sdk_->rpc_client->getMath()->calibrateCoordinate(points,0);
|
||||
if(std::get<1>(result)!=0)return Result::failure(ArmErrorCode::InvalidArgument,"SDK three-point calibration failed: "+std::to_string(std::get<1>(result)));
|
||||
pose=std::get<0>(result);
|
||||
if(pose.size()!=6 || !std::all_of(pose.begin(),pose.end(),[](double v){return std::isfinite(v);}))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"SDK returned invalid calibrated frame");
|
||||
if(!sameCoordinateFrame(threePointFrame(points),pose))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"SDK calibration does not match origin/+X/XY convention");
|
||||
return Result::success();
|
||||
} catch(const std::exception& e){return Result::failure(ArmErrorCode::CommandFailed,e.what());}
|
||||
#else
|
||||
return unsupported_("three-point calibration");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::configureWorkObject_(const std::vector<double>& base_user_pose, bool invalidate)
|
||||
{
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto names=sdk_->rpc_client->getRobotNames();
|
||||
if(names.empty())return Result::failure(ArmErrorCode::RobotNotReady,"robot name unavailable");
|
||||
auto robot=sdk_->rpc_client->getRobotInterface(names.front());
|
||||
if(!robot || !robot->getRobotConfig())return Result::failure(ArmErrorCode::RobotNotReady,"robot config unavailable");
|
||||
auto config=robot->getRobotConfig();
|
||||
const auto mounting=config->getMountingPose();
|
||||
if(mounting.size()!=6)return Result::failure(ArmErrorCode::CommandFailed,"world-to-base mounting pose unavailable");
|
||||
// The saved pose is T_base_user, while remote_tool=false requires
|
||||
// WObjectData.user_coord in world. Convert the FRAME once, not targets.
|
||||
const auto world_user=sdk_->rpc_client->getMath()->poseTrans(mounting,base_user_pose);
|
||||
if(world_user.size()!=6 || !std::all_of(world_user.begin(),world_user.end(),[](double v){return std::isfinite(v);}))
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"invalid world-to-user pose");
|
||||
arcs::common_interface::WObjectData work_object;
|
||||
work_object.remote_tool=false;
|
||||
work_object.attach_frame=""; // Not a display name or pendant-library key.
|
||||
work_object.user_coord=world_user;
|
||||
work_object.obj_coord.assign(6,0.0);
|
||||
// A timeout can leave controller state uncertain. Invalidate the old
|
||||
// application identity BEFORE the write so it cannot authorize motion.
|
||||
if(invalidate){std::lock_guard<std::mutex> lock(user_coordinate_mutex_);applied_user_coordinate_name_.clear();applied_user_coordinate_revision_=0;user_coordinates_active_.store(false);builtin_tool_reference_.store(false);}
|
||||
const int ret=config->setWorkObjectData(work_object);
|
||||
if(ret!=arcs::common_interface::AUBO_OK)
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"setWorkObjectData rejected: sdk ret="+std::to_string(ret));
|
||||
if(invalidate)user_coordinates_active_.store(true);
|
||||
return Result::success();
|
||||
}catch(const std::exception& e){return Result::failure(ArmErrorCode::CommandFailed,std::string("setWorkObjectData failed: ")+e.what());}
|
||||
#else
|
||||
return unsupported_("setWorkObjectData");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::applyUserCoordinateSystem(const std::string& name,std::uint64_t revision)
|
||||
{
|
||||
try {
|
||||
const auto profile=UserCoordinateStore::forArm(id_).get(name,revision);
|
||||
std::vector<double> actual;
|
||||
return UserCoordinateStore::isBuiltin(profile.name)
|
||||
? applyBuiltinCoordinate(profile.name,actual)
|
||||
: applyUserCoordinates(profile.user_pose,profile.tcp_offset,actual,profile.name,profile.revision);
|
||||
} catch(const CoordinateStoreError& e){
|
||||
return Result::failure(e.kind==CoordinateStoreError::Storage?ArmErrorCode::CommandFailed:ArmErrorCode::InvalidArgument,e.what());
|
||||
}
|
||||
}
|
||||
|
||||
Result AuboArm::applyBuiltinCoordinate(const std::string& name,
|
||||
std::vector<double>& actual_tcp_offset)
|
||||
{
|
||||
if(name!="__builtin_base__" && name!="__builtin_tool__")
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"unknown built-in coordinate");
|
||||
// Keep the actual configured tool; choosing a reference must not zero TCP.
|
||||
std::string response;
|
||||
if(!executeJsonCommand("{\"command\":\"get_active_tcp_offset\"}",response))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,response);
|
||||
Json::Value data;std::string error;
|
||||
if(!parseJsonCommand(response,data,error))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"invalid TCP readback");
|
||||
const auto* offset=findJsonMember(data,"offset");
|
||||
if(!offset || !offset->isArray() || offset->size()!=6)
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"missing TCP readback");
|
||||
std::vector<double> tcp;for(const auto& x:*offset)tcp.push_back(x.asDouble());
|
||||
std::vector<double> reference(6,0.0);
|
||||
if(name=="__builtin_tool__") {
|
||||
// Absolute goals use a fixed reference captured at Apply, not a new
|
||||
// relative offset from whichever TCP position exists at each command.
|
||||
try {
|
||||
const auto current=fk(true);
|
||||
reference={current.x,current.y,current.z,current.rx,current.ry,current.rz};
|
||||
if(!std::all_of(reference.begin(),reference.end(),[](double v){return std::isfinite(v);}))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"invalid current TCP for absolute tool reference");
|
||||
} catch(const std::exception& e){return Result::failure(ArmErrorCode::CommandFailed,e.what());}
|
||||
}
|
||||
const auto result=applyUserCoordinates(reference,tcp,actual_tcp_offset,name,1);
|
||||
if(result.ok())builtin_tool_reference_.store(name=="__builtin_tool__");
|
||||
return result;
|
||||
}
|
||||
|
||||
Result AuboArm::applyUserCoordinates(const std::vector<double>& user_pose,
|
||||
const std::vector<double>& tcp_offset,
|
||||
std::vector<double>& actual_tcp_offset,
|
||||
const std::string& name, std::uint64_t revision)
|
||||
{
|
||||
Json::Value q(Json::objectValue);jsonMember(q,"command")="apply_user_coordinates";
|
||||
Json::Value user(Json::arrayValue),tcp(Json::arrayValue);
|
||||
for(double x:user_pose)user.append(x);for(double x:tcp_offset)tcp.append(x);
|
||||
jsonMember(q,"user_pose")=user;jsonMember(q,"tcp_offset")=tcp;
|
||||
std::string response;
|
||||
if(!executeJsonCommand(compactJson(q),response))return Result::failure(ArmErrorCode::CommandFailed,response);
|
||||
Json::Value r;std::string error;
|
||||
if(!parseJsonCommand(response,r,error))return Result::failure(ArmErrorCode::CommandFailed,"invalid apply response");
|
||||
actual_tcp_offset.clear();const auto* offset=findJsonMember(r,"offset");
|
||||
if(!offset || !offset->isArray() || offset->size()!=6)return Result::failure(ArmErrorCode::CommandFailed,"missing TCP readback");
|
||||
for(const auto& x:*offset)actual_tcp_offset.push_back(x.asDouble());
|
||||
{std::lock_guard<std::mutex> lock(user_coordinate_mutex_);applied_user_coordinate_name_=name;applied_user_coordinate_revision_=revision;applied_base_user_pose_=user_pose;applied_tcp_offset_=actual_tcp_offset;}
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
bool AuboArm::currentUserCoordinateMatches(const std::string& name,std::uint64_t revision) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(user_coordinate_mutex_);
|
||||
return user_coordinates_active_.load() && !name.empty() && applied_user_coordinate_name_==name && applied_user_coordinate_revision_==revision;
|
||||
}
|
||||
|
||||
bool AuboArm::lastAppliedUserCoordinate(std::string& name,std::uint64_t& revision) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(user_coordinate_mutex_);
|
||||
name=applied_user_coordinate_name_;revision=applied_user_coordinate_revision_;
|
||||
return user_coordinates_active_.load()&&!name.empty();
|
||||
}
|
||||
|
||||
bool AuboArm::executeJsonCommand(const std::string& request_json,
|
||||
std::string& response_json)
|
||||
{
|
||||
@ -588,76 +481,6 @@ bool AuboArm::executeJsonCommand(const std::string& request_json,
|
||||
"field 'command' is required and must be a non-empty string");
|
||||
}
|
||||
command = lowerString(command);
|
||||
if (command == "apply_user_coordinates" || command == "get_active_tcp_offset") {
|
||||
const auto read_pose = [&](const char* key, std::vector<double>& pose) {
|
||||
const auto* value = findJsonMember(root, key);
|
||||
if (!value || !value->isArray() || value->size() != 6) return false;
|
||||
for (unsigned i = 0; i < 6; ++i) {
|
||||
if (!(*value)[i].isNumeric() || !std::isfinite((*value)[i].asDouble())) return false;
|
||||
pose.push_back((*value)[i].asDouble());
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const bool read_only = command == "get_active_tcp_offset";
|
||||
std::vector<double> user_pose, tcp_offset;
|
||||
if (!read_only && (!read_pose("user_pose", user_pose) || !read_pose("tcp_offset", tcp_offset)))
|
||||
return fail("invalid_argument", "user_pose and tcp_offset must each contain six finite values (m, rad)");
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
const auto ready = ensureConnected_(command);
|
||||
if (!ready.ok()) return fail("not_connected", ready.message);
|
||||
std::uint64_t token{};
|
||||
if (!read_only && !tryBeginMotion_(ActiveMotion::Joint, token))
|
||||
return fail("busy", "cannot change TCP while arm motion is active");
|
||||
ScopeExit owner([this, token, read_only]() {
|
||||
if (!read_only) releaseMotion_(ActiveMotion::Joint, token);
|
||||
});
|
||||
try {
|
||||
const auto names = sdk_->rpc_client->getRobotNames();
|
||||
if (names.empty()) return fail("not_ready", "robot name unavailable");
|
||||
auto config = sdk_->rpc_client->getRobotInterface(names.front())->getRobotConfig();
|
||||
if (!read_only) {
|
||||
// Any subsequent failure must not leave the old record labelled
|
||||
// as applied after a possibly successful TCP/frame write.
|
||||
{std::lock_guard<std::mutex> lock(user_coordinate_mutex_);applied_user_coordinate_name_.clear();applied_user_coordinate_revision_=0;user_coordinates_active_.store(false);builtin_tool_reference_.store(false);}
|
||||
const auto previous=config->getTcpOffset();
|
||||
bool unchanged=previous.size()==6;
|
||||
if(unchanged)for(std::size_t i=0;i<6;++i)unchanged=unchanged&&std::isfinite(previous[i])&&std::abs(previous[i]-tcp_offset[i])<=1e-9;
|
||||
if(!unchanged && config->setTcpOffset(tcp_offset)!=arcs::common_interface::AUBO_OK)
|
||||
return fail("apply_failed","setTcpOffset rejected");
|
||||
}
|
||||
const auto actual = config->getTcpOffset();
|
||||
if (actual.size() != 6) return fail("readback_failed", "invalid TCP readback size");
|
||||
Json::Value offset(Json::arrayValue);
|
||||
for (std::size_t i=0; i<6; ++i) {
|
||||
if (!std::isfinite(actual[i])) return fail("readback_failed", "non-finite TCP readback");
|
||||
if (!read_only && std::abs(actual[i]-tcp_offset[i]) > 1e-6)
|
||||
return fail("readback_failed", "TCP readback differs from requested offset");
|
||||
offset.append(actual[i]);
|
||||
}
|
||||
if(!read_only){
|
||||
// Configure WorkObject LAST: no TCP setter may follow it before
|
||||
// the caller submits a Cartesian instruction.
|
||||
const auto result=configureWorkObject_(user_pose);
|
||||
if(!result.ok())return fail("work_object_failed",result.message);
|
||||
}
|
||||
jsonMember(response,"success") = true;
|
||||
jsonMember(response,"device_id") = id_;
|
||||
jsonMember(response,"transform") = "T_flange_tcp";
|
||||
jsonMember(response,"units") = "m_rad";
|
||||
jsonMember(response,"rotation_convention") = "RzRyRx";
|
||||
jsonMember(response,"coordinate_api_version") = 4;
|
||||
jsonMember(response,"movel_target_mode") = "absolute_selected_frame";
|
||||
jsonMember(response,"work_object_acknowledged") = !read_only;
|
||||
jsonMember(response,"offset") = offset;
|
||||
jsonMember(response,"user_frame_reference") = "base";
|
||||
jsonMember(response,"persistent_in_controller") = false;
|
||||
response_json = compactJson(response);
|
||||
return true;
|
||||
} catch (const std::exception& e) { return fail("sdk_error",e.what()); }
|
||||
#else
|
||||
return fail("unsupported", "Aubo SDK unavailable");
|
||||
#endif
|
||||
}
|
||||
if (command != "cabinet_io") {
|
||||
return fail("unsupported_command",
|
||||
"unsupported json command: " + command);
|
||||
@ -801,103 +624,20 @@ ArmState AuboArm::getRobotState() const
|
||||
{
|
||||
ArmState state;
|
||||
state.connected = connected_.load();
|
||||
// A live RPC connection does not imply that the robot has power or that
|
||||
// startup has released its brakes. Read both from the controller mode.
|
||||
state.powered_on = false;
|
||||
state.brake_released = false;
|
||||
state.powered_on = state.connected;
|
||||
state.brake_released = state.connected;
|
||||
state.moving = busy_.load();
|
||||
state.robot_mode = getRobotMode();
|
||||
state.safety_mode = getSafetyMode();
|
||||
state.control_mode = getControlMode();
|
||||
state.emergency_stopped = isEmergencyStopped();
|
||||
state.fault = isFault();
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
if (state.connected && sdk_ && sdk_->rpc_client) {
|
||||
try {
|
||||
const auto names = sdk_->rpc_client->getRobotNames();
|
||||
if (names.empty()) {
|
||||
throw std::runtime_error("robot name list is empty");
|
||||
}
|
||||
const auto robot = sdk_->rpc_client->getRobotInterface(names.front());
|
||||
using Mode = arcs::common_interface::RobotModeType;
|
||||
const auto mode = robot->getRobotState()->getRobotModeType();
|
||||
state.powered_on = mode == Mode::PowerOn || mode == Mode::Idle ||
|
||||
mode == Mode::BrakeReleasing || mode == Mode::BackDrive ||
|
||||
mode == Mode::Running;
|
||||
state.brake_released = mode == Mode::Running || mode == Mode::BackDrive;
|
||||
state.fault = state.fault || mode == Mode::Error;
|
||||
} catch (const std::exception& e) {
|
||||
state.robot_mode = RobotMode::Unknown;
|
||||
state.fault = true;
|
||||
CMVR_LOG(ERROR) << "[AuboArm] read controller power state failed: " << e.what();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
state.speed_scaling = speed_scaling_;
|
||||
state.actual_joint_state = getJointState();
|
||||
state.target_joint_state = state.actual_joint_state;
|
||||
state.actual_tcp_pose = getTcpPose(FrameType::Base);
|
||||
// Host read-completion time in Unix seconds, not the controller's sample clock.
|
||||
state.timestamp = std::chrono::duration<double>(
|
||||
std::chrono::system_clock::now().time_since_epoch()).count();
|
||||
return state;
|
||||
}
|
||||
|
||||
RobotModel AuboArm::queryRobotModel() const
|
||||
{
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
if (!connected_.load() || !sdk_ || !sdk_->rpc_client) {
|
||||
throw std::runtime_error("[AuboArm] GetArmInfo failed: robot is not connected");
|
||||
}
|
||||
const auto names = sdk_->rpc_client->getRobotNames();
|
||||
if (names.empty()) {
|
||||
throw std::runtime_error("[AuboArm] GetArmInfo failed: robot name list is empty");
|
||||
}
|
||||
const auto robot = sdk_->rpc_client->getRobotInterface(names.front());
|
||||
if (!robot) {
|
||||
throw std::runtime_error("[AuboArm] GetArmInfo failed: robot interface is null");
|
||||
}
|
||||
const auto config = robot->getRobotConfig();
|
||||
const auto type = config->getRobotType();
|
||||
const auto subtype = config->getRobotSubType();
|
||||
const int dof = config->getDof();
|
||||
if (type.empty() || dof <= 0) {
|
||||
throw std::runtime_error("[AuboArm] GetArmInfo failed: invalid SDK model or dof");
|
||||
}
|
||||
|
||||
// Return a fresh snapshot, without mutating metadata used by motion/state
|
||||
// threads. Names and default frames are application configuration, not SDK
|
||||
// readback. In particular, do not enumerate frames with frameGetChildren.
|
||||
auto result = model_;
|
||||
result.name = type;
|
||||
result.description_id = type;
|
||||
result.subtype = subtype;
|
||||
result.dof = static_cast<std::size_t>(dof);
|
||||
if (result.joint_names.size() != result.dof) {
|
||||
result.joint_names = defaultJointNames(result.dof);
|
||||
}
|
||||
result.detected_from_sdk = true;
|
||||
// Never reuse configured/URDF limits as controller readback for this snapshot.
|
||||
result.joint_limits.clear();result.joint_limits_source="unavailable";
|
||||
try {
|
||||
const auto lower=config->getJointMinPositions();
|
||||
const auto upper=config->getJointMaxPositions();
|
||||
if(lower.size()==result.dof && upper.size()==result.dof){
|
||||
result.joint_limits.resize(result.dof);
|
||||
for(std::size_t i=0;i<result.dof;++i){
|
||||
result.joint_limits[i].lower=lower[i];result.joint_limits[i].upper=upper[i];
|
||||
}
|
||||
result.joint_limits_source="aubo_sdk";
|
||||
}
|
||||
}catch(const std::exception& e){
|
||||
CMVR_LOG(WARNING)<<"[AuboArm] GetArmInfo position limits unavailable: "<<e.what();
|
||||
}
|
||||
return result;
|
||||
#else
|
||||
throw std::runtime_error("[AuboArm] GetArmInfo requires the AUBO SDK");
|
||||
#endif
|
||||
}
|
||||
|
||||
JointGroupState AuboArm::getJointState() const
|
||||
{
|
||||
JointGroupState state;
|
||||
@ -978,35 +718,7 @@ RobotMode AuboArm::getRobotMode() const
|
||||
if (isEmergencyStopped()) {
|
||||
return RobotMode::Stopped;
|
||||
}
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto names = sdk_->rpc_client->getRobotNames();
|
||||
if (names.empty()) {
|
||||
return RobotMode::Unknown;
|
||||
}
|
||||
using Mode = arcs::common_interface::RobotModeType;
|
||||
const auto mode = sdk_->rpc_client->getRobotInterface(names.front())
|
||||
->getRobotState()->getRobotModeType();
|
||||
switch (mode) {
|
||||
case Mode::NoController:
|
||||
case Mode::Disconnected: return RobotMode::Disconnected;
|
||||
case Mode::ConfirmSafety:
|
||||
case Mode::PowerOff:
|
||||
case Mode::PowerOffing: return RobotMode::PowerOff;
|
||||
case Mode::Error: return RobotMode::Fault;
|
||||
case Mode::Running:
|
||||
return busy_.load() ? RobotMode::Running : RobotMode::Idle;
|
||||
case Mode::Idle:
|
||||
case Mode::BackDrive: return RobotMode::Idle;
|
||||
default: return RobotMode::Unknown;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[AuboArm] getRobotMode failed: " << e.what();
|
||||
return RobotMode::Unknown;
|
||||
}
|
||||
#else
|
||||
return RobotMode::Unknown;
|
||||
#endif
|
||||
return busy_.load() ? RobotMode::Running : RobotMode::Idle;
|
||||
}
|
||||
|
||||
SafetyMode AuboArm::getSafetyMode() const
|
||||
@ -1017,39 +729,6 @@ SafetyMode AuboArm::getSafetyMode() const
|
||||
return static_cast<SafetyMode>(hardware_safety_mode_.load());
|
||||
}
|
||||
|
||||
ControlMode AuboArm::getControlMode() const
|
||||
{
|
||||
if (!connected_.load()) {
|
||||
return ControlMode::None;
|
||||
}
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
return ControlMode::Position;
|
||||
}
|
||||
const auto robot_interface =
|
||||
sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface) {
|
||||
return ControlMode::Position;
|
||||
}
|
||||
|
||||
const auto robot_state = robot_interface->getRobotState();
|
||||
if (robot_state &&
|
||||
robot_state->getRobotModeType() ==
|
||||
arcs::common_interface::RobotModeType::BackDrive) {
|
||||
return ControlMode::Freedrive;
|
||||
}
|
||||
} catch (const std::exception&) {
|
||||
// Keep telemetry available when a controller version does not support
|
||||
// one of the optional hand-guiding status queries.
|
||||
}
|
||||
#endif
|
||||
|
||||
return ControlMode::Position;
|
||||
}
|
||||
|
||||
bool AuboArm::isEmergencyStopped() const
|
||||
{
|
||||
return emergency_stopped_.load() || hardware_emergency_stopped_.load();
|
||||
@ -1063,15 +742,104 @@ bool AuboArm::isFault() const
|
||||
Result AuboArm::listBaseFrame(std::vector<std::string>& frame_names) const
|
||||
{
|
||||
frame_names.clear();
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"ListBaseFrame/frameGetChildren is not supported for AUBO");
|
||||
const auto ready = ensureConnected_("ListBaseFrame");
|
||||
if (!ready.ok()) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] robot name list is empty");
|
||||
}
|
||||
const auto robot_interface =
|
||||
sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface || !robot_interface->getSyncMove()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] world-frame interface is unavailable");
|
||||
}
|
||||
std::set<std::string> available_frames{"world", "base"};
|
||||
insertFrameName(available_frames, vendor_cfg_.base_frame());
|
||||
try {
|
||||
const auto discovered_frames =
|
||||
listAuboWorldFrames(robot_interface->getSyncMove());
|
||||
available_frames.insert(
|
||||
discovered_frames.begin(), discovered_frames.end());
|
||||
} catch (const std::exception& e) {
|
||||
// Older Aubo controller releases do not expose
|
||||
// SyncMove.frameGetChildren even though SDK 0.27.1 declares it.
|
||||
// Keep the built-in/configured frames usable instead of failing
|
||||
// the whole gRPC request with JSON-RPC -32601.
|
||||
CMVR_LOG(WARNING)
|
||||
<< "[AuboArm] ListBaseFrame dynamic discovery unavailable; "
|
||||
"using built-in/configured frames: "
|
||||
<< e.what();
|
||||
}
|
||||
frame_names.assign(available_frames.begin(), available_frames.end());
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
std::string("[AuboArm] ListBaseFrame failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("ListBaseFrame");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::listTCPFrame(std::vector<std::string>& frame_names) const
|
||||
{
|
||||
frame_names.clear();
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"ListTCPFrame/frameGetChildren is not supported for AUBO");
|
||||
const auto ready = ensureConnected_("ListTCPFrame");
|
||||
if (!ready.ok()) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] robot name list is empty");
|
||||
}
|
||||
const auto robot_interface =
|
||||
sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface || !robot_interface->getSyncMove()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] world-frame interface is unavailable");
|
||||
}
|
||||
const auto sync_move = robot_interface->getSyncMove();
|
||||
std::set<std::string> available_frames{"tool0", "flange", "tcp"};
|
||||
insertFrameName(available_frames, vendor_cfg_.tool_frame());
|
||||
try {
|
||||
for (const auto& frame_name : listAuboWorldFrames(sync_move)) {
|
||||
if (frame_name != "flange" && frame_name != "tcp" &&
|
||||
isAuboTcpFrame(sync_move, frame_name)) {
|
||||
available_frames.insert(frame_name);
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(WARNING)
|
||||
<< "[AuboArm] ListTCPFrame dynamic discovery unavailable; "
|
||||
"using built-in/configured frames: "
|
||||
<< e.what();
|
||||
}
|
||||
frame_names.assign(available_frames.begin(), available_frames.end());
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
std::string("[AuboArm] ListTCPFrame failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("ListTCPFrame");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::torqueOn()
|
||||
@ -1099,54 +867,16 @@ Result AuboArm::torqueOn()
|
||||
std::vector<double> inertia(6, 0.0);
|
||||
robot_interface->getRobotConfig()->setPayload(mass, cog, aom, inertia);
|
||||
|
||||
using Mode = arcs::common_interface::RobotModeType;
|
||||
const auto read_mode = [&]() {
|
||||
return robot_interface->getRobotState()->getRobotModeType();
|
||||
};
|
||||
// Submit each command at most once. The controller's state, not a
|
||||
// fixed sleep, determines when the next startup stage is permitted.
|
||||
const auto wait_for = [&](Mode target, const char* stage) -> Result {
|
||||
const auto deadline = std::chrono::steady_clock::now() +
|
||||
std::chrono::seconds(15);
|
||||
for (;;) {
|
||||
const auto mode = read_mode();
|
||||
if (mode == target || mode == Mode::Running) {
|
||||
return Result::success();
|
||||
}
|
||||
if (mode == Mode::Error || mode == Mode::Disconnected ||
|
||||
mode == Mode::NoController || isEmergencyStopped()) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,
|
||||
std::string("[AuboArm] ") + stage +
|
||||
" interrupted: controller mode=" + std::to_string(static_cast<int>(mode)));
|
||||
}
|
||||
if (std::chrono::steady_clock::now() >= deadline) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
std::string("[AuboArm] ") + stage +
|
||||
" timed out: controller mode=" + std::to_string(static_cast<int>(mode)));
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
if (robot_interface->getRobotState()->getRobotModeType() !=
|
||||
arcs::common_interface::RobotModeType::Running) {
|
||||
const int power_on_ret = robot_interface->getRobotManage()->poweron();
|
||||
if (power_on_ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
"[AuboArm] poweron failed: sdk ret=" +
|
||||
std::to_string(power_on_ret));
|
||||
}
|
||||
};
|
||||
auto mode = read_mode();
|
||||
if (mode != Mode::Running && mode != Mode::BrakeReleasing) {
|
||||
if (mode == Mode::PowerOff) {
|
||||
const int ret = robot_interface->getRobotManage()->poweron();
|
||||
if (ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"[AuboArm] poweron failed: sdk ret=" + std::to_string(ret));
|
||||
}
|
||||
} else if (mode != Mode::Idle && mode != Mode::PowerOn && mode != Mode::Booting) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] torqueOn rejected: controller mode=" +
|
||||
std::to_string(static_cast<int>(mode)));
|
||||
}
|
||||
const auto powered = wait_for(Mode::Idle, "poweron");
|
||||
if (!powered.ok()) {
|
||||
return powered;
|
||||
}
|
||||
}
|
||||
mode = read_mode();
|
||||
if (mode == Mode::Idle) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
const int startup_ret = robot_interface->getRobotManage()->startup();
|
||||
if (startup_ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(
|
||||
@ -1155,10 +885,6 @@ Result AuboArm::torqueOn()
|
||||
std::to_string(startup_ret));
|
||||
}
|
||||
}
|
||||
const auto started = wait_for(Mode::Running, "startup");
|
||||
if (!started.ok()) {
|
||||
return started;
|
||||
}
|
||||
emergency_stopped_.store(false);
|
||||
// A hardware emergency-stop latch is owned by the monitor. Do not
|
||||
// clear it merely because poweron/startup accepted a request: motion
|
||||
@ -1408,29 +1134,6 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
const MotionOptions& options,
|
||||
const std::string& base_frame,
|
||||
const std::string& tcp_frame)
|
||||
{
|
||||
return moveLConfigured_(target, options, base_frame, tcp_frame, nullptr, nullptr);
|
||||
}
|
||||
|
||||
Result AuboArm::moveLInUserFrame(const CartesianPose& target, const MotionOptions& options,
|
||||
const std::vector<double>& user_pose, const std::vector<double>& tcp_offset)
|
||||
{
|
||||
const auto valid = [](const std::vector<double>& p) {
|
||||
return p.size() == 6 && std::all_of(p.begin(),p.end(),[](double v){return std::isfinite(v);});
|
||||
};
|
||||
const std::vector<double> p{target.x,target.y,target.z,target.rx,target.ry,target.rz};
|
||||
if (!valid(user_pose) || !valid(tcp_offset) || !valid(p) ||
|
||||
!std::isfinite(options.velocity) || options.velocity <= 0 ||
|
||||
!std::isfinite(options.acceleration) || options.acceleration <= 0)
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"invalid explicit user frame, TCP or motion limits");
|
||||
return moveLConfigured_(target, options, "base", "tcp", &user_pose, &tcp_offset);
|
||||
}
|
||||
|
||||
Result AuboArm::moveLConfigured_(const CartesianPose& target,
|
||||
const MotionOptions& options,
|
||||
const std::string& base_frame, const std::string& tcp_frame,
|
||||
const std::vector<double>* user_pose,
|
||||
const std::vector<double>* explicit_tcp_offset)
|
||||
{
|
||||
if (options.cancellation_requested && options.cancellation_requested()) {
|
||||
return Result::failure(ArmErrorCode::CommandRejected,
|
||||
@ -1461,7 +1164,7 @@ Result AuboArm::moveLConfigured_(const CartesianPose& target,
|
||||
auto motion_control = robot_interface->getMotionControl();
|
||||
motion_control->setSpeedFraction(speed_scaling_);
|
||||
|
||||
const std::string selected_base_frame = (user_pose || user_coordinates_active_.load()) ? std::string{"base"} : base_frame.empty()
|
||||
const std::string selected_base_frame = base_frame.empty()
|
||||
? (vendor_cfg_.base_frame().empty()
|
||||
? std::string{"base"}
|
||||
: vendor_cfg_.base_frame())
|
||||
@ -1473,8 +1176,6 @@ Result AuboArm::moveLConfigured_(const CartesianPose& target,
|
||||
: tcp_frame;
|
||||
auto robot_config = robot_interface->getRobotConfig();
|
||||
auto sync_move = robot_interface->getSyncMove();
|
||||
if(user_coordinates_active_.load() && !user_pose && (!base_frame.empty() || !tcp_frame.empty()))
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"controller work-object coordinates are active; omit legacy named base/TCP fields to follow the applied coordinate system");
|
||||
if (selected_base_frame != "base" &&
|
||||
(!sync_move || !sync_move->frameExist(selected_base_frame))) {
|
||||
return Result::failure(
|
||||
@ -1484,11 +1185,7 @@ Result AuboArm::moveLConfigured_(const CartesianPose& target,
|
||||
}
|
||||
|
||||
std::vector<double> tcp_offset;
|
||||
if (explicit_tcp_offset) {
|
||||
tcp_offset = *explicit_tcp_offset;
|
||||
} else if (tcp_frame.empty()) {
|
||||
tcp_offset = robot_config->getTcpOffset();
|
||||
} else if (selected_tcp_frame == "tool0" ||
|
||||
if (selected_tcp_frame == "tool0" ||
|
||||
selected_tcp_frame == "flange") {
|
||||
tcp_offset.assign(6, 0.0);
|
||||
} else if (selected_tcp_frame == "tcp") {
|
||||
@ -1510,10 +1207,7 @@ Result AuboArm::moveLConfigured_(const CartesianPose& target,
|
||||
"[AuboArm] moveL failed: invalid tcp_frame pose: " +
|
||||
selected_tcp_frame);
|
||||
}
|
||||
const auto actual_tcp=robot_config->getTcpOffset();
|
||||
bool same_tcp=actual_tcp.size()==6;
|
||||
if(same_tcp)for(std::size_t i=0;i<6;++i)same_tcp=same_tcp&&std::isfinite(actual_tcp[i])&&std::abs(actual_tcp[i]-tcp_offset[i])<=1e-9;
|
||||
const int tcp_ret = same_tcp ? arcs::common_interface::AUBO_OK : robot_config->setTcpOffset(tcp_offset);
|
||||
const int tcp_ret = robot_config->setTcpOffset(tcp_offset);
|
||||
if (tcp_ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
@ -1523,22 +1217,6 @@ Result AuboArm::moveLConfigured_(const CartesianPose& target,
|
||||
}
|
||||
|
||||
std::vector<double> pose{target.x, target.y, target.z, target.rx, target.ry, target.rz};
|
||||
std::vector<double> selected_user;std::vector<double> selected_tcp;
|
||||
const bool selected=user_coordinates_active_.load();
|
||||
if(selected){std::lock_guard<std::mutex> lock(user_coordinate_mutex_);selected_user=applied_base_user_pose_;selected_tcp=applied_tcp_offset_;}
|
||||
if(selected && (selected_user.size()!=6 || selected_tcp.size()!=6))return Result::failure(ArmErrorCode::CommandRejected,"coordinate application is incomplete");
|
||||
if(selected && actual_tcp.size()!=6)return Result::failure(ArmErrorCode::CommandFailed,"TCP readback unavailable");
|
||||
if(selected)for(int i=0;i<6;++i)if(!std::isfinite(actual_tcp[i]) || std::abs(actual_tcp[i]-selected_tcp[i])>1e-8)
|
||||
return Result::failure(ArmErrorCode::CommandRejected,"TCP changed after Apply; reapply coordinate");
|
||||
auto math=sdk_->rpc_client->getMath();
|
||||
if(user_pose || selected) {
|
||||
// target is an absolute TCP pose expressed in the selected fixed
|
||||
// reference, including all three orientation components.
|
||||
pose=coordinateAbsoluteTarget(user_pose?*user_pose:selected_user,pose,
|
||||
[&math](const auto& a,const auto& b){return math->poseTrans(a,b);});
|
||||
}
|
||||
if(pose.size()!=6 || !std::all_of(pose.begin(),pose.end(),[](double v){return std::isfinite(v);}))
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"invalid SDK-transformed MoveL target");
|
||||
if (selected_base_frame != "base") {
|
||||
pose = sync_move->frameConvertPose(
|
||||
pose, selected_base_frame, "base");
|
||||
@ -1559,14 +1237,6 @@ Result AuboArm::moveLConfigured_(const CartesianPose& target,
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[AuboArm] moveL canceled before submission");
|
||||
}
|
||||
// Targets are now explicitly in Base. Neutralize the native WorkObject
|
||||
// to prevent a second transformation on controllers which consume it.
|
||||
if(selected || user_pose) {
|
||||
const auto base_result=configureWorkObject_(std::vector<double>(6,0.0),false);
|
||||
if(!base_result.ok()){user_coordinates_active_.store(false);return base_result;}
|
||||
}
|
||||
if(canceled())return Result::failure(ArmErrorCode::CommandRejected,"[AuboArm] moveL cancelled after native coordinate setup");
|
||||
CMVR_LOG(DEBUG)<<"[AuboArm] SDK Math Base MoveL target=["<<pose[0]<<","<<pose[1]<<","<<pose[2]<<","<<pose[3]<<","<<pose[4]<<","<<pose[5]<<"], work_object_active="<<user_coordinates_active_.load();
|
||||
const int ret = motion_control->moveLine(
|
||||
pose,
|
||||
options.acceleration > 0.0 ? options.acceleration : 0.5,
|
||||
@ -1651,7 +1321,7 @@ Result AuboArm::speedL(const CartesianVelocity& velocity, double acceleration, d
|
||||
velocity.vx, velocity.vy, velocity.vz, 0.0, 0.0, 0.0};
|
||||
std::vector<double> angular_velocity{
|
||||
velocity.wx, velocity.wy, velocity.wz, 0.0, 0.0, 0.0};
|
||||
if (frame == FrameType::Tool || builtin_tool_reference_.load()) {
|
||||
if (frame == FrameType::Tool) {
|
||||
if (!robot_interface->getRobotState()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
@ -1880,25 +1550,6 @@ Result AuboArm::connect(const std::string& ip, const int port)
|
||||
sdk_->rpc_client->setRequestTimeout(1000);
|
||||
sdk_->rpc_client->connect(ip, port > 0 ? port : 30004);
|
||||
sdk_->rpc_client->login(username_, password_);
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (!robot_names.empty()) {
|
||||
const auto robot_config =
|
||||
sdk_->rpc_client->getRobotInterface(robot_names.front())->getRobotConfig();
|
||||
const std::string sdk_model = robot_config->getRobotType();
|
||||
const std::string sdk_subtype = robot_config->getRobotSubType();
|
||||
if (!sdk_model.empty()) {
|
||||
model_.name = sdk_model;
|
||||
CMVR_LOG(INFO) << "[AuboArm] SDK detected model, id=" << id_
|
||||
<< ", model=" << model_.name
|
||||
<< ", subtype=" << sdk_subtype;
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(WARNING) << "[AuboArm] SDK model detection failed, id=" << id_
|
||||
<< ", using configured model=" << model_.name
|
||||
<< ": " << e.what();
|
||||
}
|
||||
ip_ = ip;
|
||||
port_ = port > 0 ? port : 30004;
|
||||
{
|
||||
@ -1933,13 +1584,6 @@ Result AuboArm::connect(const std::string& ip, const int port)
|
||||
|
||||
Result AuboArm::disconnect()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(user_coordinate_mutex_);
|
||||
user_coordinates_active_.store(false);builtin_tool_reference_.store(false);
|
||||
applied_user_coordinate_name_.clear();applied_user_coordinate_revision_=0;
|
||||
applied_base_user_pose_.clear();applied_tcp_offset_.clear();
|
||||
}
|
||||
(void)stopTrajectoryRecording();
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
if (sdk_) {
|
||||
sdk_->monitor_running.store(false);
|
||||
@ -2281,103 +1925,6 @@ Result AuboArm::stopProgram()
|
||||
return unsupported_("stopProgram");
|
||||
}
|
||||
|
||||
Result AuboArm::enterTeachingMode()
|
||||
{
|
||||
const auto ready = ensureConnected_("enterTeachingMode");
|
||||
if (!ready.ok()) {
|
||||
return ready;
|
||||
}
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] robot name list is empty");
|
||||
}
|
||||
const auto robot_interface =
|
||||
sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface || !robot_interface->getRobotManage()) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] robot manage interface is unavailable");
|
||||
}
|
||||
const std::vector<int> free_axes(model_.dof, 1);
|
||||
const int ret = robot_interface->getRobotManage()->handguideMode(
|
||||
free_axes, {});
|
||||
if (ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
"[AuboArm] handguideMode failed: sdk ret=" +
|
||||
std::to_string(ret));
|
||||
}
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
std::string("[AuboArm] enterTeachingMode failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("enterTeachingMode");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::startTrajectoryRecording(const std::string& file_name)
|
||||
{
|
||||
return startTrajectoryRecording(file_name, 100);
|
||||
}
|
||||
|
||||
Result AuboArm::exitTeachingMode()
|
||||
{
|
||||
const auto ready = ensureConnected_("exitTeachingMode");
|
||||
if (!ready.ok()) {
|
||||
return ready;
|
||||
}
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] robot name list is empty");
|
||||
}
|
||||
const auto robot_interface =
|
||||
sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface || !robot_interface->getRobotManage()) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] robot manage interface is unavailable");
|
||||
}
|
||||
const int ret =
|
||||
robot_interface->getRobotManage()->exitHandguideMode();
|
||||
if (ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
"[AuboArm] exitHandguideMode failed: sdk ret=" +
|
||||
std::to_string(ret));
|
||||
}
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
std::string("[AuboArm] exitTeachingMode failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("exitTeachingMode");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::completeTeaching()
|
||||
{
|
||||
const auto stop_result = stopTrajectoryRecording();
|
||||
const auto exit_result = exitTeachingMode();
|
||||
if (!stop_result.ok() && !exit_result.ok()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
stop_result.message + "; " + exit_result.message);
|
||||
}
|
||||
if (!stop_result.ok()) {
|
||||
return stop_result;
|
||||
}
|
||||
return exit_result;
|
||||
}
|
||||
|
||||
std::vector<double> AuboArm::ik(const std::string& base_link,
|
||||
const std::string& ee_link,
|
||||
const CartesianPose& pose)
|
||||
@ -2389,53 +1936,11 @@ std::vector<double> AuboArm::ik(const std::string& base_link,
|
||||
return {};
|
||||
}
|
||||
|
||||
bool AuboArm::isBaseReference(const std::string& name) const
|
||||
{
|
||||
return name.empty() || name=="base" || name=="__builtin_base__" ||
|
||||
(!vendor_cfg_.base_frame().empty() && name==vendor_cfg_.base_frame());
|
||||
}
|
||||
|
||||
CartesianPose AuboArm::fk(const std::string& base_link, const std::string& ee_link)
|
||||
{
|
||||
if(!isBaseReference(base_link))throw std::invalid_argument("GetPose: unsupported native reference: "+base_link);
|
||||
if(ee_link=="flange" || ee_link=="tool0")return fk(false);
|
||||
if(ee_link.empty() || ee_link=="tcp" ||
|
||||
(!vendor_cfg_.tool_frame().empty() && ee_link==vendor_cfg_.tool_frame()))return fk(true);
|
||||
throw std::invalid_argument("GetPose: unsupported end frame: "+ee_link);
|
||||
}
|
||||
|
||||
Result AuboArm::getPoseInCoordinate(const std::string& name,const std::vector<double>& base_reference,
|
||||
const std::string& end_frame,CartesianPose& pose)
|
||||
{
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
const auto connected=ensureConnected_("GetPose");if(!connected.ok())return connected;
|
||||
auto reference=base_reference;
|
||||
const bool tool=name=="__builtin_tool__";
|
||||
if(tool){
|
||||
std::lock_guard<std::mutex> lock(user_coordinate_mutex_);
|
||||
if(!user_coordinates_active_.load() || applied_user_coordinate_name_!=name)
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,"GetPose: apply the tool reference first; its origin is captured at Apply");
|
||||
reference=applied_base_user_pose_;
|
||||
}
|
||||
try {
|
||||
const auto actual=fk("base",end_frame);
|
||||
auto math=sdk_->rpc_client->getMath();
|
||||
if(!math)return Result::failure(ArmErrorCode::CommandFailed,"GetPose: SDK Math is unavailable");
|
||||
const auto result=coordinateFeedbackPose(reference,
|
||||
std::vector<double>{actual.x,actual.y,actual.z,actual.rx,actual.ry,actual.rz},
|
||||
[&math](const auto& p){return math->poseInverse(p);},
|
||||
[&math](const auto& a,const auto& b){return math->poseTrans(a,b);});
|
||||
if(tool){
|
||||
std::lock_guard<std::mutex> lock(user_coordinate_mutex_);
|
||||
if(!user_coordinates_active_.load() || applied_user_coordinate_name_!=name || applied_base_user_pose_!=reference)
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,"GetPose: tool reference changed during query; query again");
|
||||
}
|
||||
pose=auboPoseFromVector(result,"SDK Math selected-frame GetPose");return Result::success();
|
||||
} catch(const std::invalid_argument& e){return Result::failure(ArmErrorCode::InvalidArgument,e.what());}
|
||||
catch(const std::exception& e){return Result::failure(ArmErrorCode::CommandFailed,e.what());}
|
||||
#else
|
||||
return unsupported_("GetPose in selected coordinate");
|
||||
#endif
|
||||
(void)base_link;
|
||||
(void)ee_link;
|
||||
return fk(true);
|
||||
}
|
||||
|
||||
CartesianPose AuboArm::fk(bool is_tcp)
|
||||
|
||||
@ -1,366 +0,0 @@
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
#include "devices/arm/aubo_arm/include/joint_trajectory_csv.h"
|
||||
#include "algorithms/smoother/bspline/include/bspline_smoother.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <iomanip>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
#include "aubo_sdk/rpc.h"
|
||||
#include "aubo_sdk/rtde.h"
|
||||
#endif
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
Result csvError(const std::exception& e)
|
||||
{
|
||||
return Result::failure(ArmErrorCode::CommandFailed, std::string("[AuboArm CSV] ") + e.what());
|
||||
}
|
||||
void require(bool condition, const std::string& error)
|
||||
{
|
||||
if (!condition) throw std::runtime_error(error);
|
||||
}
|
||||
}
|
||||
|
||||
struct AuboArm::CsvRecording {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
std::ofstream output;
|
||||
std::filesystem::path path;
|
||||
std::string file_name, error;
|
||||
std::size_t samples{}, dof{};
|
||||
double first_time{}, last_time{}, frequency{};
|
||||
std::chrono::steady_clock::time_point last_received{};
|
||||
bool active{};
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
std::shared_ptr<arcs::aubo_sdk::RtdeClient> rtde;
|
||||
int topic{-1};
|
||||
#endif
|
||||
};
|
||||
|
||||
Result AuboArm::startTrajectoryRecording(const std::string& name, double hz)
|
||||
{
|
||||
const auto ready = ensureConnected_("startTrajectoryRecording");
|
||||
if (!ready.ok()) return ready;
|
||||
std::lock_guard<std::mutex> guard(trajectory_mutex_);
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
auto session = std::make_shared<CsvRecording>();
|
||||
try {
|
||||
require(!busy(), "arm motion is active");
|
||||
require(!csv_recording_, "stop the previous recording before starting another");
|
||||
hz = hz == 0 ? 100 : hz;
|
||||
require(std::isfinite(hz) && hz >= 1 && hz <= 100, "sample frequency must be 1~100 Hz");
|
||||
session->file_name = aubo_csv::fileName(name);
|
||||
session->frequency = hz;
|
||||
session->dof = model_.dof;
|
||||
const auto dir = aubo_csv::directory(id_);
|
||||
std::filesystem::create_directories(dir);
|
||||
const auto final_path = dir / session->file_name;
|
||||
require(!std::filesystem::exists(final_path), "CSV already exists; choose another name");
|
||||
session->path = final_path.string() + ".partial";
|
||||
// Exclusive creation prevents accidental overwrites, including partial files.
|
||||
const int fd = ::open(session->path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0644);
|
||||
require(fd >= 0, "cannot create CSV; a partial file may already exist");
|
||||
::close(fd);
|
||||
session->output.open(session->path);
|
||||
require(session->output.good(), "cannot open CSV for writing");
|
||||
session->output << std::setprecision(17) << "# cmvr_joint_trajectory_v1\n# device_id=" << id_
|
||||
<< "\n# frequency_hz=" << hz << '\n' << aubo_csv::columns(model_.joint_names) << '\n';
|
||||
session->rtde = std::make_shared<arcs::aubo_sdk::RtdeClient>();
|
||||
require(session->rtde->connect(ip_, 30010) == 0, "RTDE connection failed (port 30010)");
|
||||
require(session->rtde->login(username_, password_) == 0, "RTDE login failed");
|
||||
session->topic = session->rtde->setTopic(false, {"timestamp", "R1_actual_q"}, hz, 0);
|
||||
require(session->topic >= 0, "RTDE joint subscription is unsupported");
|
||||
session->active = true;
|
||||
require(session->rtde->subscribe(session->topic, [session](arcs::aubo_sdk::InputParser& parser) {
|
||||
std::lock_guard<std::mutex> lock(session->mutex);
|
||||
if (!session->active) return;
|
||||
try {
|
||||
const double now = parser.popDouble();
|
||||
const auto q = parser.popVectorDouble();
|
||||
require(std::isfinite(now) && q.size() == session->dof, "invalid RTDE joint sample");
|
||||
for (double value : q) require(std::isfinite(value), "non-finite RTDE joint position");
|
||||
if (session->samples == 0) session->first_time = now;
|
||||
else require(now > session->last_time &&
|
||||
now - session->last_time <= std::max(0.1, 3.0 / session->frequency),
|
||||
"RTDE timestamp reset or missing samples; recording stopped");
|
||||
require(now - session->first_time <= 1800 && session->samples < aubo_csv::maxSamples,
|
||||
"recording reached 30 minute limit; stop to save");
|
||||
session->output << now - session->first_time;
|
||||
for (double value : q) session->output << ',' << value;
|
||||
session->output << '\n';
|
||||
require(session->output.good(), "CSV write failed (disk full or storage error)");
|
||||
session->last_time = now;
|
||||
session->last_received = std::chrono::steady_clock::now();
|
||||
++session->samples;
|
||||
} catch (const std::exception& e) {
|
||||
session->error = e.what();
|
||||
session->active = false;
|
||||
}
|
||||
session->changed.notify_all();
|
||||
}) == 0, "RTDE subscribe failed");
|
||||
csv_recording_ = session;
|
||||
std::unique_lock<std::mutex> lock(session->mutex);
|
||||
require(session->changed.wait_for(lock, std::chrono::seconds(3), [&] {
|
||||
return session->samples > 0 || !session->error.empty(); }), "no RTDE samples received");
|
||||
require(session->error.empty(), session->error);
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
{ std::lock_guard<std::mutex> lock(session->mutex); session->active = false; }
|
||||
if (session->rtde) { try { session->rtde->disconnect(); } catch (...) {} }
|
||||
session->rtde.reset();
|
||||
session->output.close();
|
||||
if (csv_recording_ == session) csv_recording_.reset();
|
||||
// Failed recordings remain .partial for diagnosis; never offered for playback.
|
||||
return csvError(e);
|
||||
}
|
||||
#else
|
||||
(void)name; (void)hz;
|
||||
return unsupported_("CSV recording");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::stopTrajectoryRecording()
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(trajectory_mutex_);
|
||||
auto session = csv_recording_;
|
||||
if (!session) return Result::success();
|
||||
{ std::lock_guard<std::mutex> lock(session->mutex);
|
||||
if (session->samples && std::chrono::duration<double>(std::chrono::steady_clock::now() -
|
||||
session->last_received).count() > std::max(1.0, 3.0 / session->frequency))
|
||||
session->error = "RTDE feedback lost; incomplete recording retained as .partial";
|
||||
session->active = false; }
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
if (session->rtde) session->rtde->disconnect();
|
||||
} catch (const std::exception& e) {
|
||||
std::lock_guard<std::mutex> lock(session->mutex);
|
||||
session->error = e.what();
|
||||
}
|
||||
session->rtde.reset(); // disconnect releases the subscription callback.
|
||||
#endif
|
||||
std::lock_guard<std::mutex> lock(session->mutex);
|
||||
csv_recording_.reset();
|
||||
try {
|
||||
session->output.flush();
|
||||
const bool written = session->output.good();
|
||||
session->output.close();
|
||||
require(written && !session->output.fail(), "CSV flush/close failed");
|
||||
require(session->error.empty(), session->error);
|
||||
(void)aubo_csv::load(session->path, id_, model_.joint_names);
|
||||
const auto final_path = session->path.parent_path() / session->file_name;
|
||||
// Atomic publication without overwriting an existing saved trajectory.
|
||||
require(::link(session->path.c_str(), final_path.c_str()) == 0, "cannot publish CSV (name exists?)");
|
||||
std::filesystem::remove(session->path);
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return csvError(e);
|
||||
}
|
||||
}
|
||||
|
||||
Result AuboArm::listRecordedTrajectories(std::vector<RecordedTrajectoryInfo>& files,
|
||||
TrajectoryRecordingStatus& status) const
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(trajectory_mutex_);
|
||||
try {
|
||||
files.clear();
|
||||
status = {};
|
||||
const auto dir = aubo_csv::directory(id_);
|
||||
status.directory = dir.string();
|
||||
if (csv_recording_) {
|
||||
std::lock_guard<std::mutex> lock(csv_recording_->mutex);
|
||||
if (csv_recording_->active && csv_recording_->samples &&
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() -
|
||||
csv_recording_->last_received).count() > std::max(1.0, 3.0 / csv_recording_->frequency)) {
|
||||
csv_recording_->error = "RTDE feedback lost; stop recording to close the partial file";
|
||||
csv_recording_->active = false;
|
||||
}
|
||||
status.recording = csv_recording_->active;
|
||||
status.samples = csv_recording_->samples;
|
||||
status.file_name = csv_recording_->file_name;
|
||||
status.error = csv_recording_->error;
|
||||
}
|
||||
if (std::filesystem::exists(dir)) for (const auto& entry : std::filesystem::directory_iterator(dir)) {
|
||||
if (entry.path().extension() != ".csv" || entry.is_symlink()) continue;
|
||||
try {
|
||||
const auto trajectory = aubo_csv::load(entry.path(), id_, model_.joint_names);
|
||||
files.push_back({entry.path().filename().string(), trajectory.points.size(),
|
||||
trajectory.times.back(), trajectory.frequency});
|
||||
} catch (...) { /* Incomplete/foreign files are not replay candidates. */ }
|
||||
}
|
||||
std::sort(files.begin(), files.end(), [](const auto& a, const auto& b) { return a.file_name < b.file_name; });
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) { return csvError(e); }
|
||||
}
|
||||
|
||||
Result AuboArm::replayRecordedTrajectory(const std::string& name, double ratio, bool to_start,
|
||||
const MotionOptions& options)
|
||||
{
|
||||
const auto ready = ensureMotionReady_("replayRecordedTrajectory");
|
||||
if (!ready.ok()) return ready;
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
std::uint64_t token{};
|
||||
if (!tryBeginMotion_(ActiveMotion::Joint, token))
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy");
|
||||
std::shared_ptr<arcs::aubo_sdk::RpcClient> rpc;
|
||||
arcs::aubo_sdk::RobotInterfacePtr robot;
|
||||
std::string buffer;
|
||||
bool submitted = false;
|
||||
Result result = Result::success();
|
||||
try {
|
||||
aubo_csv::Trajectory source;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(trajectory_mutex_);
|
||||
require(!csv_recording_, "stop recording before replay");
|
||||
source = aubo_csv::load(aubo_csv::directory(id_) / aubo_csv::fileName(name), id_, model_.joint_names);
|
||||
}
|
||||
ratio = ratio == 0 ? 1 : ratio;
|
||||
require(std::isfinite(ratio) && ratio >= 0.1 && ratio <= 1, "speed ratio must be 0.1~1");
|
||||
auto trajectory = source;
|
||||
rpc = std::make_shared<arcs::aubo_sdk::RpcClient>();
|
||||
rpc->setRequestTimeout(2000);
|
||||
require(rpc->connect(ip_, port_) == 0, "replay RPC connection failed");
|
||||
require(rpc->login(username_, password_) == 0, "replay RPC login failed");
|
||||
const auto names = rpc->getRobotNames();
|
||||
require(!names.empty(), "robot name unavailable");
|
||||
robot = rpc->getRobotInterface(names.front());
|
||||
const auto check = [&] {
|
||||
require(!motionCanceled_(token) && !(options.cancellation_requested && options.cancellation_requested()),
|
||||
"trajectory operation canceled");
|
||||
require(robot->getRobotState()->getRobotModeType() == arcs::common_interface::RobotModeType::Running,
|
||||
"robot must be enabled and out of teaching mode");
|
||||
const auto safety = robot->getRobotState()->getSafetyModeType();
|
||||
require(safety == arcs::common_interface::SafetyModeType::Normal ||
|
||||
safety == arcs::common_interface::SafetyModeType::ReducedMode, "robot safety state does not allow replay");
|
||||
};
|
||||
check();
|
||||
if (to_start) {
|
||||
// Plan a new rest-to-rest transfer from real feedback to the CSV
|
||||
// start. Recording duration and replay percentage do not govern it.
|
||||
const auto current = robot->getRobotState()->getJointPositions();
|
||||
require(current.size() == model_.dof, "current joint positions unavailable");
|
||||
const auto target = source.points.front();
|
||||
source.points = {current, target};
|
||||
source.times = {0.0, 0.02};
|
||||
source.frequency = 100;
|
||||
trajectory = source;
|
||||
}
|
||||
const auto lower = robot->getRobotConfig()->getJointMinPositions();
|
||||
const auto upper = robot->getRobotConfig()->getJointMaxPositions();
|
||||
require(lower.size() == model_.dof && upper.size() == model_.dof, "joint limits unavailable");
|
||||
for (const auto& q : trajectory.points) for (std::size_t j = 0; j < q.size(); ++j)
|
||||
require(std::isfinite(lower[j]) && std::isfinite(upper[j]) && lower[j] < upper[j] &&
|
||||
q[j] >= lower[j] && q[j] <= upper[j], "trajectory exceeds controller joint limits");
|
||||
auto motion = robot->getMotionControl();
|
||||
{
|
||||
MotionOptions limits = options;
|
||||
const auto vmax = robot->getRobotConfig()->getJointMaxSpeeds();
|
||||
const auto amax = robot->getRobotConfig()->getJointMaxAccelerations();
|
||||
require(vmax.size() == model_.dof && amax.size() == model_.dof, "controller motion limits unavailable");
|
||||
require(std::isfinite(limits.velocity) && limits.velocity > 0 &&
|
||||
std::isfinite(limits.acceleration) && limits.acceleration > 0 &&
|
||||
std::isfinite(limits.jerk) && limits.jerk > 0, "invalid smoothing limits");
|
||||
limits.joint_velocity_limits = vmax;
|
||||
for (double a : amax) {
|
||||
require(std::isfinite(a) && a > 0, "invalid controller acceleration limit");
|
||||
limits.acceleration = std::min(limits.acceleration, a);
|
||||
}
|
||||
limits.cancellation_requested = [&, external = options.cancellation_requested] {
|
||||
return motionCanceled_(token) || (external && external());
|
||||
};
|
||||
BSplineSmoother smoother(0.05);
|
||||
JointTrajectory smoothed;
|
||||
require(smoother.init() && smoother.smooth(source.points, limits, 0.01, smoothed),
|
||||
"BSplineSmoother planning failed or canceled");
|
||||
require(smoothed.size() >= 2 && smoothed.back().time_s <= 1800,
|
||||
"smoothed trajectory exceeds the 30 minute planning limit");
|
||||
aubo_csv::Trajectory timed;
|
||||
timed.frequency = 100;
|
||||
// Never shorten the overall recorded duration. Slowing time also
|
||||
// decreases velocity, acceleration and jerk; no extra speed-up.
|
||||
for (const auto& point : smoothed) {
|
||||
timed.times.push_back(point.time_s);
|
||||
timed.points.push_back(point.position);
|
||||
}
|
||||
// A stationary spline may only contain its two endpoint samples.
|
||||
// Retain a valid constant path rather than inventing any motion.
|
||||
if (timed.times.back() < 0.02) {
|
||||
const auto last = timed.points.back();
|
||||
timed.times = {0.0, 0.01, 0.02};
|
||||
timed.points = {timed.points.front(), last, last};
|
||||
}
|
||||
const double stretch = to_start ? 1.0 : std::max(1.0, source.times.back() / timed.times.back());
|
||||
const double time_scale = stretch / (to_start ? 1.0 : ratio);
|
||||
trajectory = aubo_csv::resample(timed, 1.0);
|
||||
trajectory.frequency /= time_scale;
|
||||
for (auto& t : trajectory.times) t *= time_scale;
|
||||
// The B-spline may round corners: recheck generated positions, not
|
||||
// merely the source samples. SDK evaluates the final path too.
|
||||
for (const auto& q : trajectory.points) for (std::size_t j = 0; j < q.size(); ++j)
|
||||
require(q[j] >= lower[j] && q[j] <= upper[j], "smoothed trajectory exceeds joint limits");
|
||||
}
|
||||
const auto near = [&](const std::vector<double>& target) {
|
||||
const auto q = robot->getRobotState()->getJointPositions();
|
||||
if (q.size() != target.size()) return false;
|
||||
for (std::size_t j = 0; j < q.size(); ++j)
|
||||
if (!std::isfinite(q[j]) || std::abs(q[j] - target[j]) > 0.01) return false;
|
||||
return true;
|
||||
};
|
||||
const double expected_duration = trajectory.times.back() + 30;
|
||||
{
|
||||
require(near(trajectory.points.front()), to_start
|
||||
? "robot moved while planning move to start; retry from standstill"
|
||||
: "not at trajectory start; use MoveToTrajectoryStart first");
|
||||
// A unique, service-owned buffer never overwrites a user SDK buffer.
|
||||
buffer = "cmvr_csv_" + std::to_string(::getpid()) + "_" + std::to_string(token);
|
||||
require(motion->pathBufferAlloc(buffer, 2, static_cast<int>(trajectory.points.size())) == 0,
|
||||
"pathBufferAlloc failed");
|
||||
for (std::size_t begin = 0; begin < trajectory.points.size(); begin += 100) {
|
||||
check();
|
||||
const auto end = std::min(begin + 100, trajectory.points.size());
|
||||
require(motion->pathBufferAppend(buffer, {trajectory.points.begin() + begin,
|
||||
trajectory.points.begin() + end}) == 0, "pathBufferAppend failed");
|
||||
}
|
||||
require(motion->pathBufferEval(buffer, {}, {}, 1.0 / trajectory.frequency) == 0, "pathBufferEval failed");
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);
|
||||
while (!motion->pathBufferValid(buffer)) {
|
||||
check();
|
||||
require(std::chrono::steady_clock::now() < deadline, "path evaluation timed out");
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
check();
|
||||
require(near(trajectory.points.front()), "robot moved away from trajectory start");
|
||||
submitted = true;
|
||||
require(motion->movePathBuffer(buffer) == 0, "movePathBuffer rejected");
|
||||
}
|
||||
const auto started = std::chrono::steady_clock::now();
|
||||
bool observed_motion = false;
|
||||
while (true) {
|
||||
check();
|
||||
const int exec = motion->getExecId();
|
||||
observed_motion = observed_motion || exec >= 0;
|
||||
const double elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - started).count();
|
||||
const auto& target = trajectory.points.back();
|
||||
if (exec < 0 && (observed_motion || elapsed >= trajectory.times.back()) && near(target)) break;
|
||||
require(elapsed < expected_duration, "trajectory motion did not complete within deadline");
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
result = csvError(e);
|
||||
if (submitted && robot) {
|
||||
try { (void)robot->getMotionControl()->stopJoint(2.0); } catch (...) {}
|
||||
}
|
||||
}
|
||||
if (robot && !buffer.empty()) {
|
||||
try { (void)robot->getMotionControl()->pathBufferFree(buffer); } catch (...) {}
|
||||
}
|
||||
if (rpc) { try { rpc->logout(); rpc->disconnect(); } catch (...) {} }
|
||||
releaseMotion_(ActiveMotion::Joint, token);
|
||||
return result;
|
||||
#else
|
||||
(void)name; (void)ratio; (void)to_start; (void)options;
|
||||
return unsupported_("CSV replay");
|
||||
#endif
|
||||
}
|
||||
} // namespace cmvr::device
|
||||
@ -1,49 +0,0 @@
|
||||
#include "devices/arm/aubo_arm/include/three_point_frame.h"
|
||||
#include <Eigen/Geometry>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
using Pose=std::vector<double>;
|
||||
using namespace cmvr::device;
|
||||
#define CHECK(x) do{if(!(x)){std::cerr<<"FAIL "<<__LINE__<<": "<<#x<<"\n";return 1;}}while(false)
|
||||
Eigen::Isometry3d matrix(const Pose& p){
|
||||
Eigen::Isometry3d t=Eigen::Isometry3d::Identity();
|
||||
t.translation()=Eigen::Vector3d(p[0],p[1],p[2]);
|
||||
t.linear()=(Eigen::AngleAxisd(p[5],Eigen::Vector3d::UnitZ())*
|
||||
Eigen::AngleAxisd(p[4],Eigen::Vector3d::UnitY())*
|
||||
Eigen::AngleAxisd(p[3],Eigen::Vector3d::UnitX())).toRotationMatrix();
|
||||
return t;
|
||||
}
|
||||
Pose compose(const Pose& a,const Pose& b){
|
||||
const auto t=matrix(a)*matrix(b);const auto rpy=t.rotation().eulerAngles(2,1,0);
|
||||
return {t.translation().x(),t.translation().y(),t.translation().z(),rpy[2],rpy[1],rpy[0]};
|
||||
}
|
||||
bool close(const Pose& a,const Eigen::Isometry3d& b){return (matrix(a).matrix()-b.matrix()).norm()<1e-10;}
|
||||
int main(){
|
||||
const double pi=std::acos(-1.0);
|
||||
const Pose reference{1,2,3,0,0,pi/2},target{.2,.3,.4,.1,.2,.3};
|
||||
auto result=coordinateAbsoluteTarget(reference,target,compose);
|
||||
CHECK(std::abs(result[0]-.7)<1e-10&&std::abs(result[1]-2.2)<1e-10&&std::abs(result[2]-3.4)<1e-10);
|
||||
CHECK(close(result,matrix(reference)*matrix(target)));
|
||||
auto again=coordinateAbsoluteTarget(reference,target,compose);
|
||||
CHECK(close(again,matrix(result))); // Repeated absolute goal never accumulates.
|
||||
CHECK(close(coordinateAbsoluteTarget(reference,Pose(6,0),compose),matrix(reference)));
|
||||
CHECK(close(coordinateAbsoluteTarget(Pose(6,0),target,compose),matrix(target)));
|
||||
auto otherOrientation=target;otherOrientation[3]=-.7;otherOrientation[4]=.8;otherOrientation[5]=-.9;
|
||||
const auto changed=coordinateAbsoluteTarget(reference,otherOrientation,compose);
|
||||
for(int i=0;i<3;++i)CHECK(std::abs(changed[i]-result[i])<1e-10);
|
||||
CHECK(close(changed,matrix(reference)*matrix(otherOrientation)));
|
||||
const Pose tilted{-.72109,.30847,.78155,-1.5701438912895,-.0038997188954,.681738622814};
|
||||
CHECK(close(coordinateAbsoluteTarget(tilted,target,compose),matrix(tilted)*matrix(target)));
|
||||
const auto inverse=[](const Pose& p){
|
||||
const auto t=matrix(p).inverse();const auto rpy=t.rotation().eulerAngles(2,1,0);
|
||||
return Pose{t.translation().x(),t.translation().y(),t.translation().z(),rpy[2],rpy[1],rpy[0]};
|
||||
};
|
||||
CHECK(close(coordinateFeedbackPose(reference,result,inverse,compose),matrix(target)));
|
||||
CHECK(close(coordinateFeedbackPose(tilted,coordinateAbsoluteTarget(tilted,target,compose),inverse,compose),matrix(target)));
|
||||
CHECK(close(coordinateFeedbackPose(reference,reference,inverse,compose),Eigen::Isometry3d::Identity()));
|
||||
CHECK(close(coordinateFeedbackPose(Pose(6,0),target,inverse,compose),matrix(target)));
|
||||
bool rejected=false;try{auto bad=target;bad[3]=std::numeric_limits<double>::quiet_NaN();coordinateAbsoluteTarget(reference,bad,compose);}catch(const std::invalid_argument&){rejected=true;}CHECK(rejected);
|
||||
rejected=false;try{coordinateAbsoluteTarget(Pose{0},target,compose);}catch(const std::invalid_argument&){rejected=true;}CHECK(rejected);
|
||||
rejected=false;try{coordinateAbsoluteTarget(reference,target,[](const auto&,const auto&){return Pose{0};});}catch(const std::runtime_error&){rejected=true;}CHECK(rejected);
|
||||
std::cout<<"PASS: absolute XYZ and orientation, fixed reference, no accumulation, zero target, invalid inputs; no SDK or hardware calls\n";
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
#include "devices/arm/aubo_arm/include/user_coordinate_store.h"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
using namespace cmvr::device;
|
||||
#define CHECK(x) do{if(!(x)){std::cerr<<"FAIL line "<<__LINE__<<": "<<#x<<'\n';return 1;}}while(false)
|
||||
template<class F>bool rejects(F f,CoordinateStoreError::Kind kind){try{f();}catch(const CoordinateStoreError& e){return e.kind==kind;}return false;}
|
||||
int main(){
|
||||
char pattern[]="/tmp/cmvr-user-coordinates-test.XXXXXX";const char* directory=::mkdtemp(pattern);CHECK(directory);
|
||||
const std::filesystem::path path(directory);UserCoordinateStore store(path);
|
||||
CHECK(store.list().empty());
|
||||
UserCoordinateProfile p;p.name=u8"正方形";p.user_pose.assign(6,0);p.tcp_offset.assign(6,0);p.calibration_points={{0,0,0,0,0,0},{.1,0,0,0,0,0},{0,.1,0,0,0,0}};
|
||||
p=store.mutate("create",p);CHECK(p.revision>0&&store.list().size()==1);
|
||||
CHECK(rejects([&]{store.mutate("create",p);},CoordinateStoreError::Exists));
|
||||
auto changed=p;changed.user_pose[0]=.1;for(auto& point:changed.calibration_points)point[0]+=.1;changed=store.mutate("update",changed,p.revision);
|
||||
CHECK(changed.revision>p.revision&&store.get(p.name).user_pose[0]==.1);
|
||||
CHECK(rejects([&]{store.mutate("update",p,p.revision);},CoordinateStoreError::Conflict));
|
||||
CHECK(rejects([&]{store.mutate("delete",p,p.revision);},CoordinateStoreError::Conflict));
|
||||
CHECK(rejects([&]{store.get(p.name,p.revision);},CoordinateStoreError::Conflict));
|
||||
auto invalid=p;invalid.user_pose[0]=std::numeric_limits<double>::quiet_NaN();
|
||||
CHECK(rejects([&]{store.mutate("create",invalid);},CoordinateStoreError::Invalid));
|
||||
CHECK(rejects([&]{UserCoordinateStore::forArm("../../etc");},CoordinateStoreError::Invalid));
|
||||
std::atomic<bool> good{true};
|
||||
const auto create=[&](int id){try{auto other=p;other.name="parallel_"+std::to_string(id);store.mutate("create",other);}catch(...){good=false;}};
|
||||
std::thread one(create,1),two(create,2);one.join();two.join();CHECK(good&&store.list().size()==3);
|
||||
CHECK(UserCoordinateStore(path/"other_arm").list().empty());
|
||||
store.mutate("delete",changed,changed.revision);CHECK(store.list().size()==2);
|
||||
CHECK(rejects([&]{store.get(p.name);},CoordinateStoreError::Missing));
|
||||
{std::ofstream file(path/"coordinates.json");file<<"{\"version\":1,\"next_revision\":100,\"coordinates\":[]}";}
|
||||
CHECK(store.list().empty());const auto fresh=store.mutate("create",p);CHECK(fresh.revision==100);
|
||||
{std::ofstream file(path/"coordinates.json");file<<"{broken";}
|
||||
CHECK(rejects([&]{store.mutate("create",p);},CoordinateStoreError::Storage));
|
||||
std::ifstream file(path/"coordinates.json");std::string content((std::istreambuf_iterator<char>(file)),{});CHECK(content=="{broken");
|
||||
std::cout<<"PASS: CRUD, revisions, concurrency, isolation, invalid input and corrupted-file preservation\n";
|
||||
}
|
||||
@ -1,32 +0,0 @@
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#define CHECK(x) do {if(!(x)){std::cerr<<"FAIL line "<<__LINE__<<": "<<#x<<'\n';return 1;}}while(false)
|
||||
int main() {
|
||||
cmvr::config::RobotArmConfig config;config.set_id("offline_test");
|
||||
cmvr::device::AuboArm arm(config); // Never init/connect or send hardware commands.
|
||||
cmvr::device::MotionOptions limits;limits.velocity=.05;limits.acceleration=.1;
|
||||
cmvr::device::CartesianPose target{};std::vector<double> zero(6,0);
|
||||
CHECK(!arm.isConnected());
|
||||
std::vector<std::string> frames{"stale"};
|
||||
auto unsupported=arm.listBaseFrame(frames);
|
||||
CHECK(!unsupported.ok()&&unsupported.code==cmvr::device::ArmErrorCode::UnsupportedCommand&&frames.empty());
|
||||
frames={"stale"};unsupported=arm.listTCPFrame(frames);
|
||||
CHECK(!unsupported.ok()&&unsupported.code==cmvr::device::ArmErrorCode::UnsupportedCommand&&frames.empty());
|
||||
auto r=arm.moveLInUserFrame(target,limits,{0},zero);
|
||||
CHECK(!r.ok()&&r.code==cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
r=arm.moveLInUserFrame(target,limits,zero,{0});
|
||||
CHECK(!r.ok()&&r.code==cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
auto nan=zero;nan[3]=std::numeric_limits<double>::quiet_NaN();
|
||||
r=arm.moveLInUserFrame(target,limits,nan,zero);
|
||||
CHECK(!r.ok()&&r.code==cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
limits.velocity=-1;r=arm.moveLInUserFrame(target,limits,zero,zero);
|
||||
CHECK(!r.ok()&&r.code==cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
limits.velocity=.05;r=arm.moveLInUserFrame(target,limits,zero,zero);
|
||||
CHECK(!r.ok()&&r.code!=cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
std::string response;
|
||||
CHECK(!arm.executeJsonCommand("{\"command\":\"apply_user_coordinates\",\"user_pose\":[0],\"tcp_offset\":[0,0,0,0,0,0]}",response));
|
||||
CHECK(response.find("invalid_argument")!=std::string::npos);
|
||||
CHECK(!arm.isConnected());
|
||||
std::cout<<"PASS: explicit-frame validation and disconnected rejection, no SDK initialization\n";
|
||||
}
|
||||
@ -1,43 +0,0 @@
|
||||
#include "devices/arm/aubo_arm/include/joint_trajectory_csv.h"
|
||||
#ifdef NDEBUG
|
||||
#undef NDEBUG
|
||||
#endif
|
||||
#include <cassert>
|
||||
#include <unistd.h>
|
||||
using namespace cmvr::device::aubo_csv;
|
||||
int main()
|
||||
{
|
||||
const auto path = std::filesystem::temp_directory_path() / ("cmvr_csv_test_" + std::to_string(getpid()));
|
||||
const std::vector<std::string> joints{"joint_1", "joint_2"};
|
||||
const auto write = [&](const std::string& rows) {
|
||||
std::ofstream out(path);
|
||||
out << "# cmvr_joint_trajectory_v1\n# device_id=arm\n# frequency_hz=100\n"
|
||||
<< columns(joints) << '\n' << rows;
|
||||
};
|
||||
const auto rejects = [&](const std::string& rows) {
|
||||
write(rows);
|
||||
bool failed = false;
|
||||
try { (void)load(path, "arm", joints); } catch (...) { failed = true; }
|
||||
assert(failed);
|
||||
};
|
||||
write("0,0,1\n0.009,0.9,1\n0.021,2.1,1\n0.03,3,1\n");
|
||||
const auto raw = load(path, "arm", joints);
|
||||
const auto slow = resample(raw, 0.5);
|
||||
assert(slow.points.size() == 4);
|
||||
assert(std::abs(slow.points[1][0] - 1) < 1e-9);
|
||||
assert(std::abs(slow.times.back() - 0.06) < 1e-9);
|
||||
assert(slow.points.front() == raw.points.front() && slow.points.back() == raw.points.back());
|
||||
bool badName = false;
|
||||
try { fileName("../other.csv"); } catch (...) { badName = true; }
|
||||
assert(badName && fileName("test") == "test.csv");
|
||||
rejects("0,0,1\n0.01,nan,1\n0.02,2,1\n");
|
||||
rejects("0,0,1\n0.01,1,1\n0.01,2,1\n");
|
||||
rejects("0,0,1\n0.01,1,1\n0.5,2,1\n");
|
||||
rejects("0,0,1\n0.01,1,1\n");
|
||||
rejects("0,0,1\n0.01,1\n0.02,2,1\n");
|
||||
write("0,0,1\n0.01,1,1\n0.02,2,1\n");
|
||||
bool mismatch = false;
|
||||
try { load(path, "another_arm", joints); } catch (...) { mismatch = true; }
|
||||
assert(mismatch);
|
||||
std::filesystem::remove(path);
|
||||
}
|
||||
@ -21,7 +21,6 @@ target_link_libraries(huayan_arm
|
||||
cmvr_es::proto
|
||||
PRIVATE
|
||||
HR_Pro
|
||||
jsoncpp
|
||||
glog
|
||||
Threads::Threads
|
||||
)
|
||||
@ -30,10 +29,3 @@ add_library(cmvr_es::device::huayan_arm ALIAS huayan_arm)
|
||||
|
||||
install(TARGETS huayan_arm LIBRARY DESTINATION lib)
|
||||
install(FILES ${HUAYAN_ARM_SDK_DIR}/lib/libHR_Pro.so DESTINATION lib)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_executable(huayan_cabinet_io_test tests/huayan_cabinet_io_test.cpp)
|
||||
set_target_properties(huayan_cabinet_io_test PROPERTIES ENABLE_EXPORTS ON)
|
||||
target_link_libraries(huayan_cabinet_io_test PRIVATE cmvr_es::device::huayan_arm jsoncpp gtest gtest_main)
|
||||
add_test(NAME huayan_cabinet_io_test COMMAND huayan_cabinet_io_test)
|
||||
endif()
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
# Cabinet CI/CO IO
|
||||
|
||||
Use `cmvr.api.ArmService.ExecuteJsonCommand`, with the same parameter names as Aubo.
|
||||
The request header selects the Huayan arm device. The following object is serialized
|
||||
as the `request_json` string:
|
||||
|
||||
```json
|
||||
{"command":"cabinet_io","operation":"set_do","index":0,"value":true}
|
||||
```
|
||||
|
||||
`index: 0` selects **CO0**, not DO0. `true` writes 1, `false` writes 0.
|
||||
Writing calls `HRIF_SetBoxCO`; reading uses `HRIF_ReadBoxCO`.
|
||||
For readback, use:
|
||||
|
||||
```json
|
||||
{"command":"cabinet_io","operation":"get_do","index":0}
|
||||
```
|
||||
|
||||
`get_di` reads the corresponding configurable **CI** input.
|
||||
The SDK supplies the available CI/CO count; channel numbers start at zero.
|
||||
`value` must be a JSON boolean for writes. No motion enable is performed.
|
||||
|
||||
The gRPC response uses the existing `header` and `response_json` fields.
|
||||
The JSON response contains `success`, `command`, `operation`, `index`, `count`,
|
||||
`io_type` (CI or CO), and `sdk_return_code`. Reads return `value`; successful
|
||||
writes return `requested_value`, which indicates SDK command success and does not
|
||||
claim physical readback. Failures return `error_code` and `error_message`.
|
||||
Aubo-specific `runstate` fields are not fabricated for Huayan.
|
||||
|
||||
Build `huayan_cabinet_io_test` with `BUILD_TESTING=ON` for offline verification.
|
||||
The test executable replaces the IO SDK symbols and does not connect to hardware.
|
||||
@ -1,8 +1,6 @@
|
||||
#include "huayan_arm.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <json/json.h>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
@ -114,88 +112,6 @@ HuayanRobot::~HuayanRobot()
|
||||
(void)disconnect();
|
||||
}
|
||||
|
||||
|
||||
bool HuayanRobot::executeJsonCommand(const std::string& request_json, std::string& response_json)
|
||||
{
|
||||
Json::Value response(Json::objectValue);
|
||||
const auto put = [&](const char* key) -> Json::Value& {
|
||||
return *response.demand(key, key + std::char_traits<char>::length(key));
|
||||
};
|
||||
const auto serialize = [&]() {
|
||||
Json::StreamWriterBuilder writer;
|
||||
writer[std::string("indentation")] = "";
|
||||
response_json = Json::writeString(writer, response);
|
||||
};
|
||||
put("success") = false;
|
||||
const auto fail = [&](const std::string& code, const std::string& message) {
|
||||
put("error_code") = code; put("error_message") = message; serialize();
|
||||
CMVR_LOG(ERROR) << "[HuayanRobot] cabinet_io: " << message;
|
||||
return false;
|
||||
};
|
||||
Json::Value root; Json::CharReaderBuilder builder;
|
||||
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
|
||||
std::string error;
|
||||
if (!reader->parse(request_json.data(), request_json.data() + request_json.size(), &root, &error))
|
||||
return fail("invalid_json", "invalid json: " + error);
|
||||
if (!root.isObject()) return fail("invalid_json", "invalid json: root must be an object");
|
||||
const auto member = [&](const char* key) { return root.find(key, key + std::char_traits<char>::length(key)); };
|
||||
const auto text = [&](const char* key) {
|
||||
const auto* v = member(key);
|
||||
std::string value = v && v->isString() ? v->asString() : std::string{};
|
||||
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); });
|
||||
return value;
|
||||
};
|
||||
const auto command = text("command");
|
||||
if (command.empty()) return fail("invalid_argument", "field 'command' is required and must be a non-empty string");
|
||||
if (command != "cabinet_io") return fail("unsupported_command", "unsupported json command: " + command);
|
||||
put("command") = command;
|
||||
const auto operation = text("operation");
|
||||
if (operation.empty()) return fail("invalid_argument", "field 'operation' is required and must be a non-empty string");
|
||||
if (operation != "get_di" && operation != "get_do" && operation != "set_do")
|
||||
return fail("invalid_operation", "unsupported cabinet_io operation: " + operation);
|
||||
put("operation") = operation;
|
||||
const auto* index_value = member("index");
|
||||
if (!index_value || !index_value->isInt() || index_value->asInt() < 0)
|
||||
return fail("invalid_argument", "field 'index' is required and must be a non-negative JSON integer");
|
||||
const int index = index_value->asInt(); put("index") = index;
|
||||
const auto* value = member("value");
|
||||
if (operation == "set_do" && (!value || !value->isBool()))
|
||||
return fail("invalid_argument", "field 'value' is required for set_do and must be a JSON boolean");
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
const auto ready = ensureConnected_("cabinet_io");
|
||||
if (!ready.ok()) return fail("not_connected", ready.message);
|
||||
try {
|
||||
// Same request shape as Aubo; Huayan configurable cabinet ports are CI/CO.
|
||||
// CO0 is index 0, not the separate general-purpose DO0 terminal.
|
||||
std::vector<int> ports;
|
||||
const bool input = operation == "get_di";
|
||||
int ret = input ? HRIF_ReadAllBoxCI(box_id_, ports) : HRIF_ReadAllBoxCO(box_id_, ports);
|
||||
put("io_type") = input ? "CI" : "CO"; put("sdk_return_code") = ret;
|
||||
if (ret != 0) return fail("sdk_command_failed", "failed to read IO count: sdk ret=" + std::to_string(ret));
|
||||
put("count") = static_cast<int>(ports.size());
|
||||
if (static_cast<std::size_t>(index) >= ports.size())
|
||||
return fail("index_out_of_range", "cabinet_io index out of range: index=" + std::to_string(index) + ", count=" + std::to_string(ports.size()));
|
||||
if (operation == "set_do") {
|
||||
ret = HRIF_SetBoxCO(box_id_, index, value->asBool() ? 1 : 0);
|
||||
put("sdk_return_code") = ret;
|
||||
if (ret != 0) return fail("sdk_command_failed", "cabinet_io set_do failed: sdk ret=" + std::to_string(ret));
|
||||
put("requested_value") = value->asBool();
|
||||
} else {
|
||||
int actual = -1;
|
||||
ret = input ? HRIF_ReadBoxCI(box_id_, index, actual) : HRIF_ReadBoxCO(box_id_, index, actual);
|
||||
put("sdk_return_code") = ret;
|
||||
if (ret != 0) return fail("sdk_command_failed", "cabinet_io read failed: sdk ret=" + std::to_string(ret));
|
||||
if (actual != 0 && actual != 1) return fail("invalid_io_value", "cabinet_io returned a non-digital value");
|
||||
put("value") = actual != 0;
|
||||
}
|
||||
put("success") = true; serialize();
|
||||
CMVR_LOG(INFO) << "[HuayanRobot] cabinet_io: operation=" << operation << ", index=" << index << ", sdk ret=" << ret;
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
return fail("sdk_exception", std::string("[HuayanRobot] cabinet_io failed: ") + e.what());
|
||||
}
|
||||
}
|
||||
|
||||
bool HuayanRobot::init()
|
||||
{
|
||||
if (ip_.empty()) {
|
||||
@ -364,34 +280,6 @@ Result HuayanRobot::setSpeedScaling(const double scaling)
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
ControlMode HuayanRobot::getControlMode() const
|
||||
{
|
||||
if (!isConnected()) {
|
||||
return ControlMode::None;
|
||||
}
|
||||
|
||||
int tri_stage_enabled = 0;
|
||||
int tri_stage_mode = 1;
|
||||
int force_control_state = 0;
|
||||
int tri_stage_result = -1;
|
||||
int force_state_result = -1;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
tri_stage_result = HRIF_ReadTriStageSwitch(
|
||||
box_id_, robot_id_, tri_stage_enabled, tri_stage_mode);
|
||||
force_state_result = HRIF_ReadForceControlState(
|
||||
box_id_, robot_id_, force_control_state);
|
||||
}
|
||||
const bool tri_stage_freedrive =
|
||||
tri_stage_result == 0 && tri_stage_enabled != 0 && tri_stage_mode == 0;
|
||||
const bool force_freedrive =
|
||||
force_state_result == 0 && force_control_state == 3;
|
||||
if (tri_stage_freedrive || force_freedrive) {
|
||||
return ControlMode::Freedrive;
|
||||
}
|
||||
return servo_mode_.load() ? ControlMode::Servo : ControlMode::Position;
|
||||
}
|
||||
|
||||
bool HuayanRobot::isProtectiveStopped() const
|
||||
{
|
||||
const auto state = readHrState_();
|
||||
@ -725,17 +613,6 @@ Result HuayanRobot::connect(const std::string& ip, const int port)
|
||||
connected_.store(false);
|
||||
return result;
|
||||
}
|
||||
std::string sdk_model;
|
||||
const int model_result = HRIF_ReadRobotModel(box_id_, sdk_model);
|
||||
if (model_result == 0 && !sdk_model.empty()) {
|
||||
model_.name = sdk_model;
|
||||
CMVR_LOG(INFO) << "[HuayanRobot] SDK detected model, id=" << id_
|
||||
<< ", model=" << model_.name;
|
||||
} else {
|
||||
CMVR_LOG(WARNING) << "[HuayanRobot] SDK model detection failed, id=" << id_
|
||||
<< ", code=" << model_result
|
||||
<< ", using configured model=" << model_.name;
|
||||
}
|
||||
ip_ = ip;
|
||||
port_ = use_port;
|
||||
connected_.store(true);
|
||||
|
||||
@ -28,7 +28,6 @@ public:
|
||||
~HuayanRobot() override;
|
||||
|
||||
std::string typeName() const override { return "HuayanRobot"; }
|
||||
bool executeJsonCommand(const std::string& request_json, std::string& response_json) override;
|
||||
bool init() override;
|
||||
bool stop() override;
|
||||
|
||||
@ -39,7 +38,7 @@ public:
|
||||
CartesianPose getTcpPose(FrameType frame = FrameType::Base) const override;
|
||||
RobotMode getRobotMode() const override;
|
||||
SafetyMode getSafetyMode() const override;
|
||||
ControlMode getControlMode() const override;
|
||||
ControlMode getControlMode() const override { return servo_mode_.load() ? ControlMode::Servo : ControlMode::Position; }
|
||||
bool supportsActionQueueMotion() const noexcept override { return true; }
|
||||
Result listBaseFrame(std::vector<std::string>& frame_names) const override;
|
||||
Result listTCPFrame(std::vector<std::string>& frame_names) const override;
|
||||
@ -108,7 +107,6 @@ public:
|
||||
bool busy() const override { return busy_.load(); }
|
||||
|
||||
private:
|
||||
friend struct HuayanIoTestAccess;
|
||||
struct HrState {
|
||||
int moving{0};
|
||||
int enabled{0};
|
||||
|
||||
@ -1,53 +0,0 @@
|
||||
// Executable SDK symbol overrides: no connection to hardware and no physical IO writes.
|
||||
#include "huayan_arm.h"
|
||||
#include <gtest/gtest.h>
|
||||
#include <json/json.h>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
namespace { int calls=0, written=-1, channel=-1, result=0, actual=1; }
|
||||
extern "C" bool HRIF_IsConnected(unsigned int) { return true; }
|
||||
extern "C" int HRIF_ReadAllBoxCO(unsigned int,std::vector<int>& v) { ++calls;v={0,0,0,0};return result; }
|
||||
extern "C" int HRIF_ReadAllBoxCI(unsigned int,std::vector<int>& v) { ++calls;v={0,0};return result; }
|
||||
extern "C" int HRIF_SetBoxCO(unsigned int,int bit,int value) { ++calls;channel=bit;written=value;return result; }
|
||||
extern "C" int HRIF_ReadBoxCO(unsigned int,int bit,int& value) { ++calls;channel=bit;value=actual;return result; }
|
||||
extern "C" int HRIF_ReadBoxCI(unsigned int,int bit,int& value) { ++calls;channel=bit;value=actual;return result; }
|
||||
namespace cmvr::device {
|
||||
const Json::Value& get(const Json::Value& r,const char* key) {const auto* p=r.find(key,key+std::char_traits<char>::length(key));if(!p)throw std::runtime_error("missing response field");return *p;}
|
||||
struct HuayanIoTestAccess {static void connected(HuayanRobot& arm,bool value){arm.connected_=value;}};
|
||||
class HuayanCabinetIo : public ::testing::Test {
|
||||
protected:
|
||||
config::RobotArmConfig cfg;
|
||||
std::unique_ptr<HuayanRobot> arm;
|
||||
void SetUp()override {calls=0;written=-1;channel=-1;result=0;actual=1;cfg.set_id("fake_huayan");arm=std::make_unique<HuayanRobot>(cfg);HuayanIoTestAccess::connected(*arm,true);}
|
||||
void TearDown()override {HuayanIoTestAccess::connected(*arm,false);arm.reset();}
|
||||
Json::Value invoke(const std::string& request,bool success) {std::string response;EXPECT_EQ(arm->executeJsonCommand(request,response),success);Json::Value value;Json::CharReaderBuilder reader;std::string error;std::istringstream in(response);EXPECT_TRUE(Json::parseFromStream(reader,in,&value,&error));return value;}
|
||||
};
|
||||
TEST_F(HuayanCabinetIo, SameAuboParametersSetCO0HighAndLow) {
|
||||
auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",true);
|
||||
EXPECT_EQ(channel,0);EXPECT_EQ(written,1);EXPECT_TRUE(get(r,"requested_value").asBool());EXPECT_EQ(get(r,"io_type").asString(),"CO");
|
||||
invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":false})",true);EXPECT_EQ(written,0);
|
||||
}
|
||||
TEST_F(HuayanCabinetIo, ReadActualCOAndCI) {
|
||||
auto r=invoke(R"({"command":"cabinet_io","operation":"get_do","index":0})",true);EXPECT_TRUE(get(r,"value").asBool());EXPECT_EQ(channel,0);
|
||||
actual=0;r=invoke(R"({"command":"cabinet_io","operation":"get_di","index":1})",true);EXPECT_FALSE(get(r,"value").asBool());EXPECT_EQ(get(r,"io_type").asString(),"CI");
|
||||
}
|
||||
TEST_F(HuayanCabinetIo, RejectInvalidWithoutSdkCalls) {
|
||||
for(auto request:{"{","[]",R"({"command":"other"})",R"({"command":"cabinet_io","operation":"set_do","index":0,"value":1})",R"({"command":"cabinet_io","operation":"set_do","index":-1,"value":true})",R"({"command":"cabinet_io","operation":"get_do","index":0.5})"})invoke(request,false);
|
||||
EXPECT_EQ(calls,0);
|
||||
}
|
||||
TEST_F(HuayanCabinetIo, RejectOutOfRangeWithoutWriting) {
|
||||
auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":4,"value":true})",false);
|
||||
EXPECT_EQ(get(r,"error_code").asString(),"index_out_of_range");EXPECT_EQ(written,-1);
|
||||
}
|
||||
TEST_F(HuayanCabinetIo, PropagateSdkFailure) {
|
||||
result=123;auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",false);
|
||||
EXPECT_EQ(get(r,"sdk_return_code").asInt(),123);EXPECT_EQ(written,-1);
|
||||
}
|
||||
TEST_F(HuayanCabinetIo, DisconnectedNeverCallsSdk) {
|
||||
HuayanIoTestAccess::connected(*arm,false);auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",false);
|
||||
EXPECT_EQ(get(r,"error_code").asString(),"not_connected");EXPECT_EQ(calls,0);
|
||||
}
|
||||
TEST_F(HuayanCabinetIo, InvalidFeedbackIsNotReportedAsTrue) {
|
||||
actual=7;auto r=invoke(R"({"command":"cabinet_io","operation":"get_do","index":0})",false);EXPECT_EQ(get(r,"error_code").asString(),"invalid_io_value");
|
||||
}
|
||||
}
|
||||
@ -74,6 +74,3 @@ target_link_libraries(motor_robot_arm_gen2_mujoco_test
|
||||
gtest_main
|
||||
pthread
|
||||
)
|
||||
|
||||
add_executable(lingkong_arm_diagnostics_test src/lingkong_arm_diagnostics_test.cpp)
|
||||
target_link_libraries(lingkong_arm_diagnostics_test PRIVATE cmvr_es::device::motor_robot_arm cmvr_es::device::motor_core gtest gtest_main pthread)
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include "common/types/arm/arm_types.h"
|
||||
#include "motor/abstract_motor.h"
|
||||
namespace cmvr::device::detail {
|
||||
// Only a group containing Lingkong drives opts in; other backends retain their
|
||||
// own semantics. Never infer enabled state from supply power or command success.
|
||||
inline void applyLingkongArmDiagnostics(ArmState& state,
|
||||
const std::vector<std::shared_ptr<AbstractMotor>>& motors) {
|
||||
if (!std::any_of(motors.begin(), motors.end(), [](const auto& motor) {
|
||||
return motor && motor->typeName() == "LingkongMotor";
|
||||
})) return;
|
||||
bool all_read = true, all_enabled = true, any_fault = false;
|
||||
for (const auto& motor : motors) {
|
||||
uint16_t status=0, error=0; bool enabled=false, fault=false, ok=false;
|
||||
try { ok = motor && motor->readDiagnosticState(status,error,enabled,fault); }
|
||||
catch (...) { ok = false; }
|
||||
all_read &= ok;
|
||||
all_enabled &= ok && enabled && !fault && error == 0;
|
||||
any_fault |= !ok || fault || error != 0;
|
||||
}
|
||||
state.connected = state.connected && all_read;
|
||||
state.powered_on = all_read && all_enabled;
|
||||
state.fault = state.fault || any_fault;
|
||||
if (!all_read) state.robot_mode = RobotMode::Disconnected;
|
||||
else if (state.fault) state.robot_mode = RobotMode::Fault;
|
||||
else if (!all_enabled) state.robot_mode = RobotMode::PowerOff;
|
||||
if (state.fault && !state.emergency_stopped && !state.protective_stopped)
|
||||
state.safety_mode = SafetyMode::Fault;
|
||||
}
|
||||
}
|
||||
@ -35,12 +35,13 @@ public:
|
||||
bool stop() override;
|
||||
|
||||
RobotModel getRobotModel() const override { return model_; }
|
||||
RobotModel queryRobotModel() const override;
|
||||
std::size_t getDof() const override { return static_cast<std::size_t>(dof_); }
|
||||
ArmState getRobotState() const override;
|
||||
JointGroupState getJointState() const override;
|
||||
CartesianPose getTcpPose(FrameType frame = FrameType::Base) const override;
|
||||
RobotMode getRobotMode() const override { return getRobotState().robot_mode; }
|
||||
RobotMode getRobotMode() const override {
|
||||
return isFault() ? RobotMode::Fault : (busy() ? RobotMode::Running : RobotMode::Idle);
|
||||
}
|
||||
SafetyMode getSafetyMode() const override;
|
||||
ControlMode getControlMode() const override { return ControlMode::Position; }
|
||||
|
||||
@ -178,8 +179,6 @@ private:
|
||||
int move_j_stable_sample_count_{3};
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
// Last successful arm-level enable/disable result; not live drive feedback.
|
||||
std::atomic<bool> powered_on_{false};
|
||||
std::atomic<bool> busy_{false};
|
||||
std::atomic<std::uint64_t> joint_motion_stop_generation_{0};
|
||||
std::atomic<double> speed_scaling_{1.0};
|
||||
|
||||
@ -1,43 +0,0 @@
|
||||
#include "arm/motor_robot_arm/include/lingkong_arm_diagnostics.h"
|
||||
#include <gtest/gtest.h>
|
||||
#include <stdexcept>
|
||||
using namespace cmvr::device;
|
||||
namespace {
|
||||
class Drive final : public AbstractMotor {
|
||||
public:
|
||||
bool enabled=false, fault=false, ok=true, throws=false; uint16_t error=0;
|
||||
std::string typeName() const override { return "LingkongMotor"; }
|
||||
bool setLimitQ(double,double) override{return true;}
|
||||
bool setLimitQd(double) override{return true;}
|
||||
bool brakeRelease() override{return true;}
|
||||
bool calibrateZeroQ() override{return true;}
|
||||
bool readDiagnosticState(uint16_t& s,uint16_t& e,bool& on,bool& f) override {
|
||||
if(throws)throw std::runtime_error("timeout");
|
||||
s=enabled?0x30:0x20;e=error;on=enabled;f=fault;return ok;
|
||||
}
|
||||
};
|
||||
ArmState initial(){ArmState s;s.connected=true;s.powered_on=true;s.robot_mode=RobotMode::Idle;return s;}
|
||||
TEST(LingkongArmDiagnostics, AllDisabledOverridesPreviouslyEnabledState){
|
||||
auto a=std::make_shared<Drive>();auto b=std::make_shared<Drive>();auto c=std::make_shared<Drive>();auto s=initial();
|
||||
detail::applyLingkongArmDiagnostics(s,{a,b,c});EXPECT_TRUE(s.connected);EXPECT_FALSE(s.powered_on);EXPECT_FALSE(s.fault);EXPECT_EQ(s.robot_mode,RobotMode::PowerOff);
|
||||
}
|
||||
TEST(LingkongArmDiagnostics, OnlyAllEnabledReportsEnabled){
|
||||
auto a=std::make_shared<Drive>();auto b=std::make_shared<Drive>();a->enabled=true;auto s=initial();
|
||||
detail::applyLingkongArmDiagnostics(s,{a,b});EXPECT_FALSE(s.powered_on);
|
||||
b->enabled=true;s=initial();detail::applyLingkongArmDiagnostics(s,{a,b});EXPECT_TRUE(s.powered_on);EXPECT_FALSE(s.fault);
|
||||
}
|
||||
TEST(LingkongArmDiagnostics, FaultAndHighErrorAreNotHealthy){
|
||||
auto a=std::make_shared<Drive>();a->enabled=true;a->error=0x200;auto s=initial();detail::applyLingkongArmDiagnostics(s,{a});
|
||||
EXPECT_FALSE(s.powered_on);EXPECT_TRUE(s.fault);EXPECT_EQ(s.robot_mode,RobotMode::Fault);EXPECT_EQ(s.safety_mode,SafetyMode::Fault);
|
||||
}
|
||||
TEST(LingkongArmDiagnostics, MissingReplyAndExceptionsNeverKeepEnabled){
|
||||
auto a=std::make_shared<Drive>();a->enabled=true;
|
||||
for(bool raises:{false,true}){a->throws=raises;a->ok=false;auto s=initial();EXPECT_NO_THROW(detail::applyLingkongArmDiagnostics(s,{a}));EXPECT_FALSE(s.connected);EXPECT_FALSE(s.powered_on);EXPECT_TRUE(s.fault);EXPECT_EQ(s.robot_mode,RobotMode::Disconnected);}
|
||||
}
|
||||
TEST(LingkongArmDiagnostics, MissingAxisIsNotAllEnabled){
|
||||
auto a=std::make_shared<Drive>();a->enabled=true;auto s=initial();detail::applyLingkongArmDiagnostics(s,{a,nullptr});EXPECT_FALSE(s.powered_on);EXPECT_FALSE(s.connected);
|
||||
}
|
||||
TEST(LingkongArmDiagnostics, EmptyGroupKeepsOtherBackendBehavior){
|
||||
auto s=initial();detail::applyLingkongArmDiagnostics(s,{});EXPECT_TRUE(s.powered_on);EXPECT_TRUE(s.connected);
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,4 @@
|
||||
#include "arm/motor_robot_arm/include/motor_robot_arm.h"
|
||||
#include "arm/motor_robot_arm/include/lingkong_arm_diagnostics.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@ -157,54 +156,22 @@ bool MotorRobotArm::stop()
|
||||
return shutdown().ok();
|
||||
}
|
||||
|
||||
RobotModel MotorRobotArm::queryRobotModel() const
|
||||
{
|
||||
auto model = model_;
|
||||
if (!ik_solver_) return model;
|
||||
|
||||
const auto pinocchio = std::dynamic_pointer_cast<cmvr::PinocchioIKBase>(ik_solver_);
|
||||
Eigen::VectorXd lower, upper;
|
||||
const auto count = static_cast<Eigen::Index>(model.joint_names.size());
|
||||
// Model metadata retains the URDF bounds. Report the effective solver
|
||||
// bounds, which already resolve the configured source and joint order.
|
||||
if ((pinocchio && !pinocchio->jointLimitPolicy().limits().enable()) ||
|
||||
!ik_solver_->getJointPositionLimits(lower, upper) ||
|
||||
lower.size() != count || upper.size() != count ||
|
||||
model.joint_limits.size() != model.joint_names.size()) {
|
||||
model.joint_limits.clear();
|
||||
return model;
|
||||
}
|
||||
for (Eigen::Index i = 0; i < count; ++i) {
|
||||
if (!std::isfinite(lower[i]) || !std::isfinite(upper[i]) || lower[i] >= upper[i]) {
|
||||
model.joint_limits.clear();
|
||||
return model;
|
||||
}
|
||||
model.joint_limits[static_cast<std::size_t>(i)].lower = lower[i];
|
||||
model.joint_limits[static_cast<std::size_t>(i)].upper = upper[i];
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
ArmState MotorRobotArm::getRobotState() const
|
||||
{
|
||||
const bool protective_stopped = protective_stopped_.load();
|
||||
const bool emergency_stopped = emergency_stopped_.load();
|
||||
ArmState state;
|
||||
state.connected = motor_manager_ != nullptr;
|
||||
state.powered_on = powered_on_.load();
|
||||
state.brake_released = powered_on_.load() && !emergency_stopped;
|
||||
state.powered_on = true;
|
||||
state.brake_released = !emergency_stopped;
|
||||
state.moving = busy();
|
||||
state.protective_stopped = protective_stopped;
|
||||
state.emergency_stopped = emergency_stopped;
|
||||
state.speed_scaling = speed_scaling_.load();
|
||||
state.robot_mode = !state.connected ? RobotMode::Disconnected
|
||||
: isFault() ? RobotMode::Fault : (state.moving ? RobotMode::Running : RobotMode::Idle);
|
||||
state.robot_mode = getRobotMode();
|
||||
state.fault = isFault();
|
||||
state.safety_mode = getSafetyMode();
|
||||
state.control_mode = ControlMode::Position;
|
||||
std::vector<std::shared_ptr<AbstractMotor>> diagnostic_motors;
|
||||
for (const auto& name : joint_names_) diagnostic_motors.push_back(getMotor_(name));
|
||||
detail::applyLingkongArmDiagnostics(state, diagnostic_motors);
|
||||
state.actual_joint_state = getJointState();
|
||||
const auto& q = state.actual_joint_state.position;
|
||||
const auto& qd = state.actual_joint_state.velocity;
|
||||
@ -212,7 +179,7 @@ ArmState MotorRobotArm::getRobotState() const
|
||||
!std::all_of(q.begin(), q.end(), [](double v) { return std::isfinite(v); }) ||
|
||||
!std::all_of(qd.begin(), qd.end(), [](double v) { return std::isfinite(v); })) {
|
||||
state.fault = true;
|
||||
state.robot_mode = state.connected ? RobotMode::Fault : RobotMode::Disconnected;
|
||||
state.robot_mode = RobotMode::Fault;
|
||||
return state;
|
||||
}
|
||||
if (!ik_solver_) {
|
||||
@ -249,10 +216,6 @@ JointGroupState MotorRobotArm::getJointState() const
|
||||
if (!motor_manager_ || !motor_manager_->readFeedbacksAtomic(motors, state.position, state.velocity))
|
||||
return {};
|
||||
state.effort.assign(motors.size(), 0.0);
|
||||
state.current.reserve(motors.size());
|
||||
for (const auto& motor : motors) {
|
||||
state.current.push_back(static_cast<double>(motor->getCurrent()));
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
@ -301,7 +264,6 @@ Result MotorRobotArm::torqueOn()
|
||||
}
|
||||
}
|
||||
emergency_stopped_.store(false);
|
||||
powered_on_.store(true);
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
@ -317,7 +279,6 @@ Result MotorRobotArm::torqueOff()
|
||||
"failed to torque off motor for joint: " + joint_name);
|
||||
}
|
||||
}
|
||||
powered_on_.store(false);
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
@ -347,10 +308,7 @@ Result MotorRobotArm::calibrateZeroQ(const std::string& joint_name)
|
||||
if (!motor) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name);
|
||||
}
|
||||
if (!motor->calibrateZeroQ()) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"failed to set zero for joint: " + joint_name);
|
||||
}
|
||||
motor->calibrateZeroQ();
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
|
||||
@ -895,103 +895,3 @@ TEST_F(MotorRobotArmGen2MujocoTest, SpeedL)
|
||||
|
||||
} // namespace
|
||||
} // namespace cmvr::device
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
TEST(MotorRobotArmPowerState, StartsDisabledAndFailedEnableStaysDisabled) {
|
||||
config::RobotArmConfig cfg;
|
||||
cfg.set_id("uninitialized_power_test");
|
||||
cfg.mutable_motor()->set_motor_system_id("missing_power_test");
|
||||
cfg.mutable_motor()->set_dof(1);
|
||||
cfg.mutable_motor()->add_joint_names("missing_joint");
|
||||
MotorRobotArm arm(cfg);
|
||||
EXPECT_FALSE(arm.getRobotState().powered_on);
|
||||
EXPECT_FALSE(arm.torqueOn().ok());
|
||||
EXPECT_FALSE(arm.getRobotState().powered_on);
|
||||
}
|
||||
TEST_F(MotorRobotArmGen2MujocoTest, PowerStateTracksSuccessfulCommands) {
|
||||
EXPECT_TRUE(arm_->getRobotState().powered_on);
|
||||
const auto off = arm_->torqueOff();
|
||||
ASSERT_TRUE(off.ok()) << off.message;
|
||||
EXPECT_FALSE(arm_->getRobotState().powered_on);
|
||||
const auto on = arm_->torqueOn();
|
||||
ASSERT_TRUE(on.ok()) << on.message;
|
||||
EXPECT_TRUE(arm_->getRobotState().powered_on);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace cmvr::device
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
TEST_F(MotorRobotArmGen2MujocoTest, QueryModelReportsEffectiveConfiguredLimits)
|
||||
{
|
||||
config::ArmRootConfig root;
|
||||
ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(
|
||||
(project_root_ / "cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt").string(), &root));
|
||||
for (const bool use_qp : {false, true}) {
|
||||
auto cfg = root.arm().robot_arms(0);
|
||||
auto* dls = cfg.mutable_kinematics()->mutable_pinocchio_dls_ik_solver();
|
||||
dls->set_urdf_path((project_root_ / "model/gen2/robot.urdf").string());
|
||||
auto* limits = dls->mutable_joint_limit_policy()->mutable_limits();
|
||||
limits->set_enable(true);
|
||||
limits->set_source(config::JOINT_LIMIT_SOURCE_CUSTOM);
|
||||
limits->clear_joints();
|
||||
// Reverse configuration order to catch index-based rather than name-based mapping.
|
||||
for (int i = 6; i >= 0; --i) {
|
||||
auto* limit = limits->add_joints();
|
||||
limit->set_joint_name(cfg.motor().joint_names(i));
|
||||
limit->set_q_lb(-1.0 - 0.1 * i);
|
||||
limit->set_q_ub(0.2 + 0.1 * i);
|
||||
limit->set_qd(2.0);
|
||||
limit->set_qdd(10.0);
|
||||
}
|
||||
if (use_qp) {
|
||||
const auto saved = *dls;
|
||||
cfg.clear_kinematics();
|
||||
auto* qp = cfg.mutable_kinematics()->mutable_pinocchio_qp_ik_solver();
|
||||
qp->set_urdf_path(saved.urdf_path());
|
||||
qp->set_base_frame_name(saved.base_frame_name());
|
||||
qp->set_flange_frame_name(saved.flange_frame_name());
|
||||
*qp->mutable_joint_limit_policy() = saved.joint_limit_policy();
|
||||
}
|
||||
MotorRobotArm arm(cfg);
|
||||
ASSERT_TRUE(arm.init()) << "use_qp=" << use_qp;
|
||||
const auto model = arm.queryRobotModel();
|
||||
ASSERT_EQ(model.joint_limits.size(), 7u);
|
||||
EXPECT_EQ(model.joint_names, arm.getRobotModel().joint_names);
|
||||
for (std::size_t i = 0; i < 7; ++i) {
|
||||
EXPECT_DOUBLE_EQ(model.joint_limits[i].lower, -1.0 - 0.1 * i);
|
||||
EXPECT_DOUBLE_EQ(model.joint_limits[i].upper, 0.2 + 0.1 * i);
|
||||
}
|
||||
// Querying API metadata must not mutate the shared URDF model.
|
||||
EXPECT_NEAR(arm.getRobotModel().joint_limits[1].lower, -M_PI, 1e-10);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(MotorRobotArmGen2MujocoTest, QueryModelRespectsUrdfSourceAndDisabledLimits)
|
||||
{
|
||||
config::ArmRootConfig root;
|
||||
ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(
|
||||
(project_root_ / "cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt").string(), &root));
|
||||
for (const bool enabled : {true, false}) {
|
||||
auto cfg = root.arm().robot_arms(0);
|
||||
auto* solver = cfg.mutable_kinematics()->mutable_pinocchio_dls_ik_solver();
|
||||
solver->set_urdf_path((project_root_ / "model/gen2/robot.urdf").string());
|
||||
auto* limits = solver->mutable_joint_limit_policy()->mutable_limits();
|
||||
limits->set_enable(enabled);
|
||||
limits->set_source(config::JOINT_LIMIT_SOURCE_URDF);
|
||||
MotorRobotArm arm(cfg);
|
||||
ASSERT_TRUE(arm.init());
|
||||
const auto model = arm.queryRobotModel();
|
||||
if (enabled) {
|
||||
ASSERT_EQ(model.joint_limits.size(), 7u);
|
||||
EXPECT_DOUBLE_EQ(model.joint_limits[1].lower, arm.getRobotModel().joint_limits[1].lower);
|
||||
EXPECT_DOUBLE_EQ(model.joint_limits[1].upper, arm.getRobotModel().joint_limits[1].upper);
|
||||
} else {
|
||||
EXPECT_TRUE(model.joint_limits.empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
} // namespace cmvr::device
|
||||
|
||||
@ -330,13 +330,11 @@ 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()) {
|
||||
computation_result = false;
|
||||
status.message += "; " + zero_result.message;
|
||||
}
|
||||
if (!zero_result.ok()) status.message += "; " + zero_result.message;
|
||||
};
|
||||
try {
|
||||
if (begin_cycle_) {
|
||||
@ -404,12 +402,10 @@ 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 = true;
|
||||
computation_result = false;
|
||||
planning_result = false;
|
||||
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;
|
||||
|
||||
@ -646,16 +646,13 @@ TEST(SpeedLExecutor, FailedCycleBrakesBeforeReleaseAndKeepsOriginalFaultUntilSto
|
||||
}
|
||||
|
||||
TEST(SpeedLExecutor, FailedBrakeOrBrakeOutputSendsEmergencyZeroWithoutCommitting) {
|
||||
for (const std::string_view failure : {"braking limit", "brake output", "emergency zero"}) {
|
||||
SCOPED_TRACE(failure);
|
||||
for (const bool fail_output : {false, true}) {
|
||||
SCOPED_TRACE(fail_output);
|
||||
auto planner = std::make_shared<Planner>();
|
||||
std::atomic<bool> reject_step{true};
|
||||
planner->check = [&](std::string_view operation) {
|
||||
return operation != "step" || !reject_step.load();
|
||||
};
|
||||
planner->check = [](std::string_view operation) { return operation != "step"; };
|
||||
planner->brake = [&](double, const auto&, const auto&) {
|
||||
CartesianVelocityStep result;
|
||||
result.status = failure == "brake output" ? Result::success()
|
||||
result.status = fail_output ? Result::success()
|
||||
: Result::failure(ArmErrorCode::OutOfJointLimit, "braking distance exhausted");
|
||||
result.joint_velocity.velocity = {.02};
|
||||
return result;
|
||||
@ -665,16 +662,10 @@ 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 failure == "brake output"
|
||||
? Result::failure(ArmErrorCode::CommandFailed, "brake send rejected")
|
||||
: Result::success();
|
||||
}
|
||||
if (command.velocity.front() != 0)
|
||||
return Result::failure(ArmErrorCode::CommandFailed, "brake send rejected");
|
||||
++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;
|
||||
@ -687,23 +678,8 @@ 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(
|
||||
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());
|
||||
}
|
||||
fail_output ? "brake send rejected" : "braking distance exhausted"), std::string::npos);
|
||||
EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault);
|
||||
EXPECT_TRUE(executor.shutdown().ok());
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
#define CMVR_ES_ROBOT_ARM_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
@ -14,18 +13,6 @@
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
struct RecordedTrajectoryInfo {
|
||||
std::string file_name;
|
||||
std::size_t samples{};
|
||||
double duration_s{};
|
||||
double sampling_frequency_hz{};
|
||||
};
|
||||
struct TrajectoryRecordingStatus {
|
||||
std::string directory, file_name, error;
|
||||
bool recording{};
|
||||
std::size_t samples{};
|
||||
};
|
||||
|
||||
class RobotArm : public AbstractDevice {
|
||||
public:
|
||||
~RobotArm() override = default;
|
||||
@ -33,7 +20,6 @@ public:
|
||||
DeviceKind kind() const noexcept override { return DeviceKind::Arm; }
|
||||
|
||||
virtual RobotModel getRobotModel() const = 0;
|
||||
virtual RobotModel queryRobotModel() const { return getRobotModel(); }
|
||||
virtual std::size_t getDof() const = 0;
|
||||
virtual ArmState getRobotState() const = 0;
|
||||
virtual JointGroupState getJointState() const = 0;
|
||||
@ -66,13 +52,6 @@ public:
|
||||
return false;
|
||||
}
|
||||
|
||||
// Queue-safe coordinate selection: caller already owns the control lease.
|
||||
// Unsupported backends must fail rather than silently execute in another frame.
|
||||
virtual Result applyUserCoordinateSystem(const std::string&, std::uint64_t)
|
||||
{
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"user coordinate selection is not supported by this arm");
|
||||
}
|
||||
virtual Result torqueOn() = 0;
|
||||
virtual Result torqueOff() = 0;
|
||||
virtual Result calibrateZeroQ(const std::string& joint_name) = 0;
|
||||
@ -182,39 +161,6 @@ public:
|
||||
virtual Result pauseProgram() = 0;
|
||||
virtual Result stopProgram() = 0;
|
||||
|
||||
// Preserve optional vendor teaching capabilities from linbo_dev.
|
||||
virtual Result enterTeachingMode() {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "teaching mode is not supported by this robot arm");
|
||||
}
|
||||
virtual Result startTrajectoryRecording(const std::string&) {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "trajectory recording is not supported by this robot arm");
|
||||
}
|
||||
virtual Result completeTeaching() {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "complete teaching is not supported by this robot arm");
|
||||
}
|
||||
virtual Result startTrajectoryRecording(const std::string& name, double frequency_hz)
|
||||
{
|
||||
if (frequency_hz == 0 || frequency_hz == 100)
|
||||
return startTrajectoryRecording(name);
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "configurable CSV recording unsupported");
|
||||
}
|
||||
virtual Result listRecordedTrajectories(std::vector<RecordedTrajectoryInfo>&,
|
||||
TrajectoryRecordingStatus&) const
|
||||
{
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "CSV trajectories unsupported");
|
||||
}
|
||||
virtual Result replayRecordedTrajectory(const std::string&, double, bool,
|
||||
const MotionOptions&)
|
||||
{
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "CSV replay unsupported");
|
||||
}
|
||||
virtual Result stopTrajectoryRecording() {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "trajectory recording is not supported by this robot arm");
|
||||
}
|
||||
virtual Result exitTeachingMode() {
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, "teaching mode is not supported by this robot arm");
|
||||
}
|
||||
|
||||
virtual std::vector<double> ik(const std::string& base_link,
|
||||
const std::string& ee_link,
|
||||
const CartesianPose& pose) = 0;
|
||||
|
||||
@ -1,2 +1 @@
|
||||
add_subdirectory(biohead_esp32)
|
||||
add_subdirectory(biohead_usb)
|
||||
add_subdirectory(biohead_esp32)
|
||||
@ -1,100 +0,0 @@
|
||||
#ifndef CMVR_ES_ABSTRACT_JOINT_HEAD_H
|
||||
#define CMVR_ES_ABSTRACT_JOINT_HEAD_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "abstract_biohead.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
enum class HeadMotionMode : int32_t { Immediate = 0, SCurve = 1, Follow = 2 };
|
||||
enum class HeadCommandOutcome : uint32_t {
|
||||
None = 0, Acknowledged = 1, Rejected = 2, Unknown = 3
|
||||
};
|
||||
|
||||
struct HeadJointInfo {
|
||||
std::string id;
|
||||
double min_position_rad{0.0};
|
||||
double max_position_rad{0.0};
|
||||
double home_position_rad{0.0};
|
||||
};
|
||||
|
||||
struct HeadJointTarget {
|
||||
std::string id;
|
||||
double position_rad{0.0};
|
||||
};
|
||||
|
||||
struct HeadExpressionPreset {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::vector<HeadJointTarget> targets;
|
||||
};
|
||||
|
||||
struct HeadJointState {
|
||||
std::string id;
|
||||
double target_position_rad{0.0};
|
||||
bool target_valid{false};
|
||||
};
|
||||
|
||||
struct HeadJointSnapshot {
|
||||
bool connected{false};
|
||||
bool expression_baseline_ready{false};
|
||||
HeadCommandOutcome last_command_outcome{HeadCommandOutcome::None};
|
||||
std::string last_error;
|
||||
// Last acknowledged command targets, never measured mechanical positions.
|
||||
std::vector<HeadJointState> joints;
|
||||
};
|
||||
|
||||
class AbstractJointHead : public AbstractBiohead {
|
||||
public:
|
||||
~AbstractJointHead() override = default;
|
||||
|
||||
virtual const std::vector<HeadJointInfo>& jointInfo() const = 0;
|
||||
virtual HeadJointSnapshot jointState() const = 0;
|
||||
virtual void moveJoints(const std::vector<HeadJointTarget>& targets) = 0;
|
||||
virtual void home(const std::function<bool()>& cancelled = {}) = 0;
|
||||
virtual void setMotionMode(HeadMotionMode mode) = 0;
|
||||
virtual void setMotionConstraints(const std::string& id, double velocity_rad_s,
|
||||
double acceleration_rad_s2, double jerk_rad_s3) = 0;
|
||||
virtual void setPositionGain(const std::string& id, double gain) = 0;
|
||||
virtual void setUpdatePeriodMs(uint32_t period_ms) = 0;
|
||||
virtual const std::vector<HeadExpressionPreset>& expressions() const = 0;
|
||||
virtual void setExpression(const std::vector<HeadJointTarget>& targets,
|
||||
double transition_duration_s,
|
||||
const std::function<bool()>& cancelled) = 0;
|
||||
virtual HeadExpressionPreset playExpression(const std::string& selector, bool by_name,
|
||||
double transition_duration_s,
|
||||
const std::function<bool()>& cancelled) = 0;
|
||||
virtual void reconnect() = 0;
|
||||
// Stops future host frames only; this is not a firmware or hardware stop.
|
||||
virtual void cancelExpression() noexcept = 0;
|
||||
|
||||
void getState(RobotState&) override { unsupported("measured joint state"); }
|
||||
void eStop() override { unsupported("hardware emergency stop"); }
|
||||
void setExpressionPose(FacialExpressionState&, double = 0, double = 0) override
|
||||
{ unsupported("legacy normalized facial expression"); }
|
||||
void streamFacialPose(FacialExpressionState&, double, double) override
|
||||
{ unsupported("legacy normalized expression stream"); }
|
||||
void speakstart() override { unsupported("SpeakStart"); }
|
||||
void speakstop() override { unsupported("SpeakStop"); }
|
||||
void expressionHappy() override { unsupported("Happy"); }
|
||||
void expressionSurprised() override { unsupported("Surprise"); }
|
||||
void expressionTired() override { unsupported("ExpressionTired"); }
|
||||
void expressionAngry() override { unsupported("ExpressionAngry"); }
|
||||
void expressionSadness() override { unsupported("ExpressionSadness"); }
|
||||
void expressionYawn() override { unsupported("ExpressionYawn"); }
|
||||
|
||||
private:
|
||||
[[noreturn]] static void unsupported(const char* operation)
|
||||
{
|
||||
throw std::runtime_error(std::string("Joint head does not support ") + operation);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_ABSTRACT_JOINT_HEAD_H
|
||||
@ -1,24 +0,0 @@
|
||||
#ifndef CMVR_ES_BIOHEAD_FACTORY_H
|
||||
#define CMVR_ES_BIOHEAD_FACTORY_H
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "cmvr/config/biohead_config/biohead_config.pb.h"
|
||||
#include "abstract_biohead.h"
|
||||
#include "biohead_esp32/include/biohead_esp32.h"
|
||||
#include "biohead_usb/include/usb_biohead.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class BioHeadFactory {
|
||||
public:
|
||||
static std::shared_ptr<AbstractBiohead> create(const config::BioHeadRobotConfig& config)
|
||||
{
|
||||
if (config.has_usb_erpc()) return std::make_shared<UsbBioHead>(config);
|
||||
return std::make_shared<BioHeadRobot>(config);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_BIOHEAD_FACTORY_H
|
||||
@ -1,84 +0,0 @@
|
||||
option(CMVR_HEAD_BUILD_TESTING "Build head-only offline tests" OFF)
|
||||
|
||||
set(CMVR_HEAD_ERPC_ROOT
|
||||
"${PROJECT_SOURCE_DIR}/dependency/${ARCH}/third_party/erpc/v1.14.0"
|
||||
CACHE PATH "Official eRPC 1.14.0 SDK prefix")
|
||||
|
||||
foreach(required lib/liberpc.a include/erpc/erpc_version.h)
|
||||
if(NOT EXISTS "${CMVR_HEAD_ERPC_ROOT}/${required}")
|
||||
message(FATAL_ERROR
|
||||
"Missing eRPC SDK file: ${CMVR_HEAD_ERPC_ROOT}/${required}")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
add_library(cmvr_head_erpc_sdk STATIC IMPORTED)
|
||||
|
||||
set_target_properties(cmvr_head_erpc_sdk PROPERTIES
|
||||
IMPORTED_LOCATION "${CMVR_HEAD_ERPC_ROOT}/lib/liberpc.a"
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${CMVR_HEAD_ERPC_ROOT}/include/erpc"
|
||||
INTERFACE_LINK_LIBRARIES Threads::Threads)
|
||||
|
||||
add_library(head_usb SHARED
|
||||
src/usb_head_erpc_client.cpp
|
||||
src/usb_head_serial_transport.cpp
|
||||
src/usb_biohead.cpp)
|
||||
|
||||
target_include_directories(head_usb
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
target_link_libraries(head_usb PRIVATE
|
||||
cmvr_es::hardware
|
||||
cmvr_es::proto
|
||||
cmvr_es::logging
|
||||
cmvr_head_erpc_sdk)
|
||||
|
||||
add_library(cmvr::device::head_usb ALIAS head_usb)
|
||||
|
||||
install(TARGETS head_usb LIBRARY DESTINATION lib)
|
||||
|
||||
if(BUILD_TESTING OR CMVR_HEAD_BUILD_TESTING)
|
||||
enable_testing()
|
||||
|
||||
add_executable(usb_head_erpc_client_test
|
||||
tests/usb_head_erpc_client_test.cpp)
|
||||
|
||||
target_link_libraries(usb_head_erpc_client_test PRIVATE
|
||||
cmvr::device::head_usb pthread)
|
||||
|
||||
add_test(
|
||||
NAME usb_head_erpc_client_test
|
||||
COMMAND usb_head_erpc_client_test)
|
||||
|
||||
add_executable(usb_head_serial_transport_test
|
||||
tests/usb_head_serial_transport_test.cpp)
|
||||
|
||||
target_link_libraries(usb_head_serial_transport_test PRIVATE
|
||||
cmvr::device::head_usb pthread)
|
||||
|
||||
add_test(
|
||||
NAME usb_head_serial_transport_test
|
||||
COMMAND usb_head_serial_transport_test)
|
||||
|
||||
add_executable(usb_biohead_test
|
||||
tests/usb_biohead_test.cpp)
|
||||
|
||||
target_link_libraries(usb_biohead_test PRIVATE
|
||||
cmvr::device::head_usb
|
||||
cmvr_es::proto
|
||||
gtest
|
||||
gtest_main
|
||||
pthread)
|
||||
|
||||
add_test(
|
||||
NAME usb_biohead_test
|
||||
COMMAND usb_biohead_test)
|
||||
|
||||
set_tests_properties(
|
||||
usb_head_erpc_client_test
|
||||
usb_head_serial_transport_test
|
||||
usb_biohead_test
|
||||
PROPERTIES ENVIRONMENT
|
||||
"LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}:${CMAKE_SOURCE_DIR}/output/lib:${CMAKE_SOURCE_DIR}/dependency/${ARCH}/third_party/grpc/v1.76.0/lib")
|
||||
endif()
|
||||
@ -1,100 +0,0 @@
|
||||
USB 头部设备与表情 gRPC
|
||||
=====================
|
||||
|
||||
本模块沿用 cmvr_es 的 BioHeadService、DeviceManager、设备工厂、配置、日志和控制仲裁。
|
||||
USB eRPC 与 Linux 串口实现均位于本头部目录,不修改公共 hardware 实现。
|
||||
|
||||
数据来源
|
||||
--------
|
||||
六个预设来自上位机 data/usb_cdc/expressions.json 的冻结快照:
|
||||
中立、微笑、疲倦、惊讶、生气、当前姿态。
|
||||
SHA256: 419d7dd7f8dcbd8da49708eade3efeedf3d739dfceb75479be36e9464602093f
|
||||
完整 UUID、中文名称和原始 double 保存在 include/head_expression_presets.h。
|
||||
“当前姿态”是一个已保存预设名称,不是实时机械测量。
|
||||
|
||||
通道映射与单位
|
||||
--------------
|
||||
G1H1 / 鼻子嘴角 -> eye_l_up
|
||||
G1H2 / 眼球左右 -> eye_l_lower
|
||||
G1H3 / 眼皮上下 -> eye_l_v
|
||||
G1H4 / 眼球上下 -> eye_l_h
|
||||
G3H1 / 嘴巴 -> pwm8_local
|
||||
所有位置单位 rad;速度 rad/s,加速度 rad/s^2,jerk rad/s^3,更新周期 ms。
|
||||
|
||||
启动、离线与恢复
|
||||
----------------
|
||||
设备 ID 为 usb_head;配置位于 devices/biohead/bio_head_usb.pb.txt。
|
||||
串口使用 /dev/serial/by-id/usb-CherryUSB_RTT_CDC_ACM_FS_000000000001-if00。
|
||||
init 只进行空 move([]) 协议探测,预期返回 -22;不自动下发位置或 home。
|
||||
配置有效但连接失败时仍注册离线设备,可以查询预设和错误信息。
|
||||
start 不自动重试;使用 reconnect 显式恢复,重连会清除表情起始基线。
|
||||
同一串口须由一个控制程序独占;TIOCEXCL 不能撤销此前已经打开的 GUI 句柄。
|
||||
运行 cmvr_es 的账户需要对该 tty 设备具有读写权限。
|
||||
|
||||
gRPC 方法(服务名 cmvr.api.BioHeadService)
|
||||
----------------------------------------
|
||||
1. GetHeadJointState:查询连接、错误、最近 ACK 目标、6 个预设与能力标记。
|
||||
2. ControlHeadJoints:单路/批量目标、模式、约束、增益、周期、home、重连、主机取消。
|
||||
3. SetHeadExpression:调用方提供完整五路目标和 0.2~5.0 秒过渡时间。
|
||||
4. PlayHeadExpression:按预设 ID 或名称调用,明确提供 0.2~5.0 秒过渡时间。
|
||||
|
||||
状态请求:
|
||||
{"header":{"device_id":"usb_head"}}
|
||||
|
||||
显式重连(无位置动作):
|
||||
{"header":{"device_id":"usb_head"},"reconnect":{}}
|
||||
|
||||
建立表情基线(会将五路移动到配置原位,必须由调用方明确执行):
|
||||
{"header":{"device_id":"usb_head"},"home":{}}
|
||||
|
||||
调用预设微笑:
|
||||
{"header":{"device_id":"usb_head"},"expression_name":"微笑","transition_duration_s":0.4}
|
||||
|
||||
自定义五路表情示例(会产生动作,请按实际标定设置):
|
||||
{
|
||||
"header":{"device_id":"usb_head"},
|
||||
"targets":[
|
||||
{"id":"eye_l_up","position_rad":0.0},
|
||||
{"id":"eye_l_lower","position_rad":0.0},
|
||||
{"id":"eye_l_v","position_rad":0.0},
|
||||
{"id":"eye_l_h","position_rad":0.0},
|
||||
{"id":"pwm8_local","position_rad":-1.0}
|
||||
],
|
||||
"transition_duration_s":0.4
|
||||
}
|
||||
|
||||
请求停止后续主机表情帧:
|
||||
{"header":{"device_id":"usb_head"},"cancel_expression":{}}
|
||||
|
||||
执行语义
|
||||
--------
|
||||
表情以本次连接中已获得 ACK 的完整五路 Immediate 目标作为起点。
|
||||
home 会显式设置 Immediate、20 ms 周期,再发送完整五路原位;启动不会自动 home。
|
||||
过渡使用 20 ms、五次 minimum-jerk,先验证全部帧,慢 ACK 后跳过过期中间帧。
|
||||
正常成功必须收到实际发送各帧的 ACK,包括最终目标帧;不表示机械实际到位。
|
||||
上下文取消/deadline、主机 cancel、stop 会阻止后续帧;已经发送的板端动作不能撤销。
|
||||
取消、断线、未知或失败结果会清除基线;没有基线时表情 RPC 明确失败,不猜测起始位置。
|
||||
模式、周期属于设备全局参数;一次请求内完整操作互斥,忙时拒绝,不在锁后排队晚发动作。
|
||||
|
||||
旧快捷 Happy/Surprise/ExpressionTired/ExpressionAngry 分别调用微笑/惊讶/疲倦/生气,
|
||||
使用 0.6 秒默认过渡并经过同一执行器、取消检查和基线检查。
|
||||
旧归一化 SetExpression/StreamExpression 与这套五路 rad 语义不同,USB 后端明确拒绝。
|
||||
没有来源参数的 Sadness/Yawn 不回退为其他表情。
|
||||
|
||||
停止与反馈边界
|
||||
--------------
|
||||
服务 1 没有位置测量或硬件停止/急停命令。
|
||||
connected 只表示串口句柄状态,target_valid 表示缓存目标有效,不代表机械测量。
|
||||
EmergencyStop 对 USB 会请求停止后续主机帧,但明确报告不支持硬件急停。
|
||||
stop 关闭本头部连接并返回 false,表示无法确认硬件已停止。
|
||||
公共 SystemService/StopAll 保持原项目实现,没有在本次修改中改变;不能据其通用成功标志
|
||||
推断本头部已完成硬件急停,应使用头部能力标记和独立的物理安全机制。
|
||||
|
||||
构建与离线测试
|
||||
--------------
|
||||
启用头部专用选项 CMVR_HEAD_BUILD_TESTING=ON,无需开启其他模块的 BUILD_TESTING。
|
||||
构建目标:cmvr_es、usb_head_erpc_client_test、usb_head_serial_transport_test、
|
||||
usb_biohead_test、grpc_head_joint_service_test。
|
||||
三个设备测试位于构建目录 cmvr-es/devices/biohead/biohead_usb;
|
||||
真实 loopback gRPC 测试位于构建目录 cmvr-es/service,仅使用 mock 设备。
|
||||
所有自动化测试均不执行真实舵机运动。
|
||||
@ -1,62 +0,0 @@
|
||||
#ifndef CMVR_ES_HEAD_EXPRESSION_PRESETS_H
|
||||
#define CMVR_ES_HEAD_EXPRESSION_PRESETS_H
|
||||
|
||||
#include "devices/biohead/abstract_joint_head.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
// Frozen cmvr-head-client expressions.json; do not substitute package defaults.
|
||||
// SHA256: 419d7dd7f8dcbd8da49708eade3efeedf3d739dfceb75479be36e9464602093f
|
||||
// updated_at: 2026-11-10T10:15:47+08:00
|
||||
inline const std::vector<HeadExpressionPreset>& headExpressionPresets()
|
||||
{
|
||||
static const std::vector<HeadExpressionPreset> presets{
|
||||
{"0de8a527543e423abab593484926dd1c", u8"中立", {
|
||||
{"eye_l_up", 0.0},
|
||||
{"eye_l_lower", 0.0},
|
||||
{"eye_l_v", 0.0},
|
||||
{"eye_l_h", 0.0},
|
||||
{"pwm8_local", -1.0},
|
||||
}},
|
||||
{"ad8f669a78d54d30a2356512b0802c1d", u8"微笑", {
|
||||
{"eye_l_up", 0.2329999953508377},
|
||||
{"eye_l_lower", -0.00041940261144191027},
|
||||
{"eye_l_v", -0.00041940261144191027},
|
||||
{"eye_l_h", -0.00041940261144191027},
|
||||
{"pwm8_local", -1.121000051498413},
|
||||
}},
|
||||
{"516bc0f0e76647109411cbf92e5c86fc", u8"疲倦", {
|
||||
{"eye_l_up", -0.991},
|
||||
{"eye_l_lower", 0.322},
|
||||
{"eye_l_v", -1.015},
|
||||
{"eye_l_h", 0.004},
|
||||
{"pwm8_local", -0.537},
|
||||
}},
|
||||
{"5e68f9b26f4d4f8580dead7777c6501b", u8"惊讶", {
|
||||
{"eye_l_up", -1.0},
|
||||
{"eye_l_lower", -0.0004194026121000505},
|
||||
{"eye_l_v", 0.999890384765},
|
||||
{"eye_l_h", -0.0004194026121000505},
|
||||
{"pwm8_local", -0.0004194026121000505},
|
||||
}},
|
||||
{"44821d9fa6df4fc78558666db32656e1", u8"生气", {
|
||||
{"eye_l_up", -1.0},
|
||||
{"eye_l_lower", 0.5497252979258},
|
||||
{"eye_l_v", 0.999890384765},
|
||||
{"eye_l_h", 0.6999468312800001},
|
||||
{"pwm8_local", -1.400129282005},
|
||||
}},
|
||||
{"8f97ed10b5b44012b004183ba61c839c", u8"当前姿态", {
|
||||
{"eye_l_up", -0.0004194026121000505},
|
||||
{"eye_l_lower", -0.0004194026121000505},
|
||||
{"eye_l_v", -0.0004194026121000505},
|
||||
{"eye_l_h", -0.65},
|
||||
{"pwm8_local", -1.0},
|
||||
}},
|
||||
};
|
||||
return presets;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_HEAD_EXPRESSION_PRESETS_H
|
||||
@ -1,87 +0,0 @@
|
||||
#ifndef CMVR_ES_USB_BIOHEAD_H
|
||||
#define CMVR_ES_USB_BIOHEAD_H
|
||||
|
||||
#include <functional>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "cmvr/config/biohead_config/biohead_config.pb.h"
|
||||
#include "devices/biohead/abstract_joint_head.h"
|
||||
#include "usb_head_erpc_client.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class UsbBioHead final : public AbstractJointHead {
|
||||
public:
|
||||
explicit UsbBioHead(const config::BioHeadRobotConfig& config);
|
||||
UsbBioHead(const config::BioHeadRobotConfig& config,
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> transport);
|
||||
~UsbBioHead() override;
|
||||
|
||||
std::string typeName() const override { return "UsbBioHead"; }
|
||||
// Configuration was validated by construction. init() makes one no-target
|
||||
// connection attempt but returns true even offline so DeviceManager keeps
|
||||
// this device registered. Query connected/last_error for hardware readiness.
|
||||
bool init() override;
|
||||
// Lifecycle activation never implicitly reconnects or sends motion targets.
|
||||
bool start() override;
|
||||
// Closes host transport. Returns false because firmware cannot confirm a stop.
|
||||
bool stop() override;
|
||||
|
||||
const std::vector<HeadJointInfo>& jointInfo() const override;
|
||||
HeadJointSnapshot jointState() const override;
|
||||
void moveJoints(const std::vector<HeadJointTarget>& targets) override;
|
||||
void home(const std::function<bool()>& cancelled = {}) override;
|
||||
void setMotionMode(HeadMotionMode mode) override;
|
||||
void setMotionConstraints(const std::string& id, double velocity_rad_s,
|
||||
double acceleration_rad_s2, double jerk_rad_s3) override;
|
||||
void setPositionGain(const std::string& id, double gain) override;
|
||||
void setUpdatePeriodMs(uint32_t period_ms) override;
|
||||
const std::vector<HeadExpressionPreset>& expressions() const override;
|
||||
void setExpression(const std::vector<HeadJointTarget>& targets, double transition_duration_s,
|
||||
const std::function<bool()>& cancelled) override;
|
||||
HeadExpressionPreset playExpression(const std::string& selector, bool by_name,
|
||||
double transition_duration_s,
|
||||
const std::function<bool()>& cancelled) override;
|
||||
void reconnect() override;
|
||||
void cancelExpression() noexcept override;
|
||||
void eStop() override;
|
||||
void expressionHappy() override;
|
||||
void expressionSurprised() override;
|
||||
void expressionTired() override;
|
||||
void expressionAngry() override;
|
||||
|
||||
private:
|
||||
std::unique_lock<std::mutex> lockCommand();
|
||||
size_t indexOf(const std::string& id) const;
|
||||
float checkedPosition(const HeadJointInfo& joint, double position_rad) const;
|
||||
void executeLocked(const char* operation, const std::function<int32_t()>& execute);
|
||||
void invalidateTargetsLocked();
|
||||
void connectLocked();
|
||||
bool expressionReadyLocked() const;
|
||||
using EncodedTargets = std::vector<std::pair<std::string, float>>;
|
||||
EncodedTargets encodeTargetsLocked(const std::vector<HeadJointTarget>& targets,
|
||||
bool complete) const;
|
||||
void rememberTargetsLocked(const EncodedTargets& targets);
|
||||
void checkCancelled(uint64_t generation, const std::function<bool()>& cancelled) const;
|
||||
|
||||
std::string port_name_;
|
||||
int baud_rate_{115200};
|
||||
std::vector<HeadJointInfo> joints_;
|
||||
std::unordered_map<std::string, size_t> joint_index_;
|
||||
mutable std::mutex operation_mutex_;
|
||||
UsbHeadErpcClient client_;
|
||||
HeadJointSnapshot snapshot_;
|
||||
std::vector<bool> immediate_targets_;
|
||||
std::optional<HeadMotionMode> motion_mode_;
|
||||
std::atomic<uint64_t> cancel_generation_{0};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_USB_BIOHEAD_H
|
||||
@ -1,71 +0,0 @@
|
||||
#ifndef CMVR_ES_USB_HEAD_ERPC_CLIENT_H
|
||||
#define CMVR_ES_USB_HEAD_ERPC_CLIENT_H
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "hardware/include/abstract_serial_transport.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class UsbHeadErpcClient final {
|
||||
public:
|
||||
using Target = std::pair<std::string, float>;
|
||||
|
||||
explicit UsbHeadErpcClient(
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> serial,
|
||||
std::chrono::milliseconds timeout =
|
||||
std::chrono::milliseconds(2000));
|
||||
|
||||
UsbHeadErpcClient(
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> serial,
|
||||
std::chrono::milliseconds timeout,
|
||||
std::uint32_t sequence_seed);
|
||||
|
||||
~UsbHeadErpcClient();
|
||||
|
||||
UsbHeadErpcClient(const UsbHeadErpcClient&) = delete;
|
||||
|
||||
UsbHeadErpcClient& operator=(
|
||||
const UsbHeadErpcClient&) = delete;
|
||||
|
||||
void open(
|
||||
const std::string& port_name,
|
||||
int baud_rate = 115200);
|
||||
|
||||
void close();
|
||||
|
||||
bool isOpen() const;
|
||||
|
||||
bool setConstraints(
|
||||
const std::string& id,
|
||||
float velocity_rad_s,
|
||||
float acceleration_rad_s2,
|
||||
float jerk_rad_s3);
|
||||
|
||||
bool setPositionGain(
|
||||
const std::string& id,
|
||||
float gain);
|
||||
|
||||
bool setMode(std::int32_t mode);
|
||||
|
||||
bool setUpdatePeriodMs(std::uint32_t period_ms);
|
||||
|
||||
std::int32_t move(const std::vector<Target>& targets);
|
||||
|
||||
std::int32_t moveJ(const std::vector<float>& angles_rad);
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_USB_HEAD_ERPC_CLIENT_H
|
||||
@ -1,47 +0,0 @@
|
||||
#ifndef CMVR_ES_USB_HEAD_SERIAL_TRANSPORT_H
|
||||
#define CMVR_ES_USB_HEAD_SERIAL_TRANSPORT_H
|
||||
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include "hardware/include/abstract_serial_transport.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
// Head-local Linux transport. It does not change the shared serial interface or
|
||||
// the behavior of other device drivers. Only the configured port is opened.
|
||||
class UsbHeadSerialTransport final : public ::cmvr::AbstractSerialTransport {
|
||||
public:
|
||||
explicit UsbHeadSerialTransport(
|
||||
std::chrono::milliseconds io_timeout = std::chrono::milliseconds(2000));
|
||||
~UsbHeadSerialTransport() override;
|
||||
|
||||
bool open(const Config& config) override;
|
||||
bool close() noexcept override;
|
||||
bool isOpen() const override;
|
||||
bool flushInput() override;
|
||||
bool write(const std::vector<std::uint8_t>& data) override;
|
||||
// The smaller of timeout and the constructor's I/O budget is used. One
|
||||
// fixed deadline covers all fragments and interrupted poll/read calls.
|
||||
bool read(std::size_t min_size, std::chrono::milliseconds timeout,
|
||||
std::vector<std::uint8_t>& out_buffer) override;
|
||||
std::string lastError() const override;
|
||||
|
||||
private:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
bool closeUnlocked() noexcept;
|
||||
bool waitReady(short events, Clock::time_point deadline);
|
||||
void setSystemError(const char* operation, int error_number);
|
||||
|
||||
const std::chrono::milliseconds io_timeout_;
|
||||
int fd_{-1};
|
||||
bool exclusive_{false};
|
||||
std::string last_error_;
|
||||
mutable std::mutex io_mutex_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_USB_HEAD_SERIAL_TRANSPORT_H
|
||||
@ -1,485 +0,0 @@
|
||||
#include "../include/usb_biohead.h"
|
||||
#include "../include/head_expression_presets.h"
|
||||
#include "../include/usb_head_serial_transport.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
|
||||
class ExpressionCancelled final : public std::runtime_error {
|
||||
public:
|
||||
ExpressionCancelled() : std::runtime_error(
|
||||
"Expression cancelled; future host frames stopped, not a hardware emergency stop") {}
|
||||
};
|
||||
|
||||
std::chrono::milliseconds responseTimeout(const config::BioHeadRobotConfig& config)
|
||||
{
|
||||
const auto timeout = config.usb_erpc().response_timeout_ms();
|
||||
if (timeout > 30000) {
|
||||
throw std::invalid_argument("USB head response_timeout_ms must be <= 30000");
|
||||
}
|
||||
return std::chrono::milliseconds(timeout == 0 ? 2000 : timeout);
|
||||
}
|
||||
|
||||
float positiveFloat(double value, const char* name)
|
||||
{
|
||||
const float encoded = static_cast<float>(value);
|
||||
if (!std::isfinite(value) || value <= 0 || !std::isfinite(encoded) || encoded <= 0) {
|
||||
throw std::invalid_argument(std::string(name) + " must be a positive finite float32");
|
||||
}
|
||||
return encoded;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
UsbBioHead::UsbBioHead(const config::BioHeadRobotConfig& config)
|
||||
: UsbBioHead(config, std::make_unique<UsbHeadSerialTransport>(responseTimeout(config))) {}
|
||||
|
||||
UsbBioHead::UsbBioHead(const config::BioHeadRobotConfig& config,
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> transport)
|
||||
: port_name_(config.serial_port()),
|
||||
baud_rate_(config.baud_rate() == 0 ? 115200 : config.baud_rate()),
|
||||
client_(std::move(transport), responseTimeout(config))
|
||||
{
|
||||
id_ = config.id();
|
||||
if (id_.empty() || port_name_.empty() || baud_rate_ <= 0 || !config.has_usb_erpc()) {
|
||||
throw std::invalid_argument("USB head requires id, serial_port, baud_rate and usb_erpc");
|
||||
}
|
||||
if (!config.servo_groups().empty()) {
|
||||
throw std::invalid_argument("USB head cannot use legacy ESP32 servo_groups");
|
||||
}
|
||||
if (config.usb_erpc().joints_size() < 1 || config.usb_erpc().joints_size() > 5) {
|
||||
throw std::invalid_argument("USB eRPC service 1 requires 1..5 configured joints");
|
||||
}
|
||||
for (const auto& cfg : config.usb_erpc().joints()) {
|
||||
HeadJointInfo joint{cfg.id(), cfg.min_position_rad(), cfg.max_position_rad(),
|
||||
cfg.home_position_rad()};
|
||||
if (joint.id.empty() || joint.id.size() > 64 || joint.id.find('\0') != std::string::npos
|
||||
|| joint_index_.count(joint.id)
|
||||
|| !std::isfinite(joint.min_position_rad)
|
||||
|| !std::isfinite(joint.max_position_rad)
|
||||
|| joint.min_position_rad >= joint.max_position_rad
|
||||
|| joint.min_position_rad < -1.5707963 || joint.max_position_rad > 1.5707963) {
|
||||
throw std::invalid_argument("Invalid or duplicate USB head joint: " + joint.id);
|
||||
}
|
||||
checkedPosition(joint, joint.home_position_rad);
|
||||
joint_index_.emplace(joint.id, joints_.size());
|
||||
joints_.push_back(joint);
|
||||
snapshot_.joints.push_back({joint.id, 0.0, false});
|
||||
immediate_targets_.push_back(false);
|
||||
}
|
||||
}
|
||||
|
||||
UsbBioHead::~UsbBioHead()
|
||||
{
|
||||
try { client_.close(); } catch (...) {}
|
||||
}
|
||||
|
||||
bool UsbBioHead::init()
|
||||
{
|
||||
std::lock_guard lock(operation_mutex_);
|
||||
if (client_.isOpen()) return true;
|
||||
try {
|
||||
connectLocked();
|
||||
return true;
|
||||
} catch (const std::exception& error) {
|
||||
try { client_.close(); } catch (...) {}
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Unknown;
|
||||
snapshot_.last_error = error.what();
|
||||
CMVR_LOG(WARNING) << "[UsbBioHead] (init): registered offline; explicit reconnect required: "
|
||||
<< error.what() << ", id=" << id_;
|
||||
// Keep the strictly validated device available for queries and an
|
||||
// explicit reconnect RPC after hot-plug or external permission repair.
|
||||
// This is object initialization success, not hardware readiness.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void UsbBioHead::connectLocked()
|
||||
{
|
||||
invalidateTargetsLocked();
|
||||
try {
|
||||
client_.open(port_name_, baud_rate_);
|
||||
if (client_.move({}) != -22) {
|
||||
throw std::runtime_error("Unexpected USB eRPC service-1 no-target probe result");
|
||||
}
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::None;
|
||||
snapshot_.last_error.clear();
|
||||
CMVR_LOG(INFO) << "[UsbBioHead] (connect): connected without motion, id=" << id_;
|
||||
} catch (const std::exception& error) {
|
||||
try { client_.close(); } catch (...) {}
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Unknown;
|
||||
snapshot_.last_error = error.what();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void UsbBioHead::reconnect()
|
||||
{
|
||||
cancelExpression();
|
||||
auto lock = lockCommand();
|
||||
invalidateTargetsLocked();
|
||||
try {
|
||||
client_.close();
|
||||
connectLocked();
|
||||
} catch (const std::exception& error) {
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Unknown;
|
||||
snapshot_.last_error = error.what();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
bool UsbBioHead::start() { return true; }
|
||||
|
||||
bool UsbBioHead::stop()
|
||||
{
|
||||
cancelExpression();
|
||||
std::lock_guard lock(operation_mutex_);
|
||||
try { client_.close(); } catch (...) {}
|
||||
invalidateTargetsLocked();
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Unknown;
|
||||
snapshot_.last_error = "Host link closed; eRPC service 1 has no device-side stop command";
|
||||
CMVR_LOG(WARNING) << "[UsbBioHead] (stop): " << snapshot_.last_error << ", id=" << id_;
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::vector<HeadJointInfo>& UsbBioHead::jointInfo() const { return joints_; }
|
||||
|
||||
HeadJointSnapshot UsbBioHead::jointState() const
|
||||
{
|
||||
std::unique_lock lock(operation_mutex_, std::try_to_lock);
|
||||
if (!lock.owns_lock()) throw std::runtime_error("USB head is busy; retry state query");
|
||||
auto result = snapshot_;
|
||||
result.connected = client_.isOpen();
|
||||
result.expression_baseline_ready = result.connected && expressionReadyLocked();
|
||||
return result;
|
||||
}
|
||||
|
||||
std::unique_lock<std::mutex> UsbBioHead::lockCommand()
|
||||
{
|
||||
std::unique_lock lock(operation_mutex_, std::try_to_lock);
|
||||
if (!lock.owns_lock()) throw std::runtime_error("USB head is busy; command was not sent");
|
||||
return lock;
|
||||
}
|
||||
|
||||
size_t UsbBioHead::indexOf(const std::string& id) const
|
||||
{
|
||||
const auto it = joint_index_.find(id);
|
||||
if (it == joint_index_.end()) throw std::invalid_argument("Unknown head joint: " + id);
|
||||
return it->second;
|
||||
}
|
||||
|
||||
float UsbBioHead::checkedPosition(const HeadJointInfo& joint, double position_rad) const
|
||||
{
|
||||
if (!std::isfinite(position_rad) || position_rad < joint.min_position_rad
|
||||
|| position_rad > joint.max_position_rad) {
|
||||
throw std::invalid_argument("Position outside configured limits: " + joint.id);
|
||||
}
|
||||
float encoded = static_cast<float>(position_rad);
|
||||
if (!std::isfinite(encoded) || (position_rad != 0 && encoded == 0)) {
|
||||
throw std::invalid_argument("Position is not representable as a non-underflowing float32");
|
||||
}
|
||||
// Quantize boundary values inward by one ULP instead of crossing a soft limit.
|
||||
if (encoded < joint.min_position_rad) {
|
||||
encoded = std::nextafter(encoded, std::numeric_limits<float>::infinity());
|
||||
}
|
||||
if (encoded > joint.max_position_rad) {
|
||||
encoded = std::nextafter(encoded, -std::numeric_limits<float>::infinity());
|
||||
}
|
||||
if (!std::isfinite(encoded) || encoded < joint.min_position_rad
|
||||
|| encoded > joint.max_position_rad) {
|
||||
throw std::invalid_argument("Joint limits contain no usable float32 target: " + joint.id);
|
||||
}
|
||||
return encoded;
|
||||
}
|
||||
|
||||
void UsbBioHead::executeLocked(const char* operation,
|
||||
const std::function<int32_t()>& execute)
|
||||
{
|
||||
if (!client_.isOpen()) throw std::runtime_error("USB head is disconnected; command not sent");
|
||||
int32_t result;
|
||||
try {
|
||||
result = execute();
|
||||
} catch (const std::exception& error) {
|
||||
try { client_.close(); } catch (...) {}
|
||||
invalidateTargetsLocked();
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Unknown;
|
||||
snapshot_.last_error = std::string(operation) + ": result unknown: " + error.what();
|
||||
throw std::runtime_error(snapshot_.last_error);
|
||||
}
|
||||
if (result != 0) {
|
||||
invalidateTargetsLocked();
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Rejected;
|
||||
snapshot_.last_error = std::string(operation) + ": firmware rejected, result="
|
||||
+ std::to_string(result) + "; partial execution is possible";
|
||||
throw std::runtime_error(snapshot_.last_error);
|
||||
}
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Acknowledged;
|
||||
snapshot_.last_error.clear();
|
||||
}
|
||||
|
||||
void UsbBioHead::invalidateTargetsLocked()
|
||||
{
|
||||
for (auto& state : snapshot_.joints) state.target_valid = false;
|
||||
std::fill(immediate_targets_.begin(), immediate_targets_.end(), false);
|
||||
motion_mode_.reset();
|
||||
snapshot_.expression_baseline_ready = false;
|
||||
}
|
||||
|
||||
UsbBioHead::EncodedTargets UsbBioHead::encodeTargetsLocked(
|
||||
const std::vector<HeadJointTarget>& targets, bool complete) const
|
||||
{
|
||||
if (targets.empty() || targets.size() > joints_.size()) {
|
||||
throw std::invalid_argument("Expected a nonempty subset of configured joints");
|
||||
}
|
||||
std::set<size_t> selected;
|
||||
std::vector<std::pair<std::string, float>> encoded;
|
||||
encoded.reserve(targets.size());
|
||||
for (const auto& target : targets) {
|
||||
const auto index = indexOf(target.id);
|
||||
if (!selected.insert(index).second) throw std::invalid_argument("Duplicate joint: " + target.id);
|
||||
encoded.emplace_back(target.id, checkedPosition(joints_[index], target.position_rad));
|
||||
}
|
||||
if (complete && (joints_.size() != 5 || selected.size() != 5)) {
|
||||
throw std::invalid_argument("Timed expression requires all five configured joints");
|
||||
}
|
||||
return encoded;
|
||||
}
|
||||
|
||||
void UsbBioHead::rememberTargetsLocked(const EncodedTargets& encoded)
|
||||
{
|
||||
for (const auto& target : encoded) {
|
||||
const auto index = indexOf(target.first);
|
||||
auto& state = snapshot_.joints[index];
|
||||
state.target_position_rad = target.second;
|
||||
state.target_valid = true;
|
||||
immediate_targets_[index] = motion_mode_ && *motion_mode_ == HeadMotionMode::Immediate;
|
||||
}
|
||||
}
|
||||
|
||||
void UsbBioHead::moveJoints(const std::vector<HeadJointTarget>& targets)
|
||||
{
|
||||
auto lock = lockCommand();
|
||||
const auto encoded = encodeTargetsLocked(targets, false);
|
||||
executeLocked("move", [&] { return client_.move(encoded); });
|
||||
rememberTargetsLocked(encoded);
|
||||
}
|
||||
|
||||
void UsbBioHead::home(const std::function<bool()>& cancelled)
|
||||
{
|
||||
auto lock = lockCommand();
|
||||
const auto generation = cancel_generation_.load();
|
||||
std::vector<HeadJointTarget> targets;
|
||||
for (const auto& joint : joints_) targets.push_back({joint.id, joint.home_position_rad});
|
||||
const auto encoded = encodeTargetsLocked(targets, false);
|
||||
try {
|
||||
checkCancelled(generation, cancelled);
|
||||
executeLocked("home.setMode", [&] { return client_.setMode(0) ? 0 : -1; });
|
||||
motion_mode_ = HeadMotionMode::Immediate;
|
||||
checkCancelled(generation, cancelled);
|
||||
executeLocked("home.setUpdatePeriodMs", [&] { return client_.setUpdatePeriodMs(20) ? 0 : -1; });
|
||||
checkCancelled(generation, cancelled);
|
||||
executeLocked("home.move", [&] { return client_.move(encoded); });
|
||||
rememberTargetsLocked(encoded);
|
||||
checkCancelled(generation, cancelled);
|
||||
} catch (const ExpressionCancelled& error) {
|
||||
invalidateTargetsLocked();
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Unknown;
|
||||
snapshot_.last_error = error.what();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void UsbBioHead::setMotionMode(HeadMotionMode mode)
|
||||
{
|
||||
auto lock = lockCommand();
|
||||
const auto value = static_cast<int32_t>(mode);
|
||||
if (value < 0 || value > 2) throw std::invalid_argument("Unsupported head motion mode");
|
||||
executeLocked("setMode", [&] { return client_.setMode(value) ? 0 : -1; });
|
||||
if (mode != HeadMotionMode::Immediate) invalidateTargetsLocked();
|
||||
motion_mode_ = mode;
|
||||
}
|
||||
|
||||
void UsbBioHead::setMotionConstraints(const std::string& id, double velocity_rad_s,
|
||||
double acceleration_rad_s2, double jerk_rad_s3)
|
||||
{
|
||||
auto lock = lockCommand();
|
||||
indexOf(id);
|
||||
const auto velocity = positiveFloat(velocity_rad_s, "velocity_rad_s");
|
||||
const auto acceleration = positiveFloat(acceleration_rad_s2, "acceleration_rad_s2");
|
||||
const auto jerk = positiveFloat(jerk_rad_s3, "jerk_rad_s3");
|
||||
executeLocked("setConstraints", [&] {
|
||||
return client_.setConstraints(id, velocity, acceleration, jerk) ? 0 : -1;
|
||||
});
|
||||
}
|
||||
|
||||
void UsbBioHead::setPositionGain(const std::string& id, double gain)
|
||||
{
|
||||
auto lock = lockCommand();
|
||||
indexOf(id);
|
||||
const auto encoded = static_cast<float>(gain);
|
||||
if (!std::isfinite(gain) || gain < 0 || !std::isfinite(encoded)
|
||||
|| (gain != 0 && encoded == 0)) {
|
||||
throw std::invalid_argument("position_gain must be a nonnegative finite float32");
|
||||
}
|
||||
executeLocked("setPositionGain", [&] { return client_.setPositionGain(id, encoded) ? 0 : -1; });
|
||||
}
|
||||
|
||||
void UsbBioHead::setUpdatePeriodMs(uint32_t period_ms)
|
||||
{
|
||||
auto lock = lockCommand();
|
||||
if (period_ms == 0 || period_ms > 100) {
|
||||
throw std::invalid_argument("update period must be in [1, 100] ms");
|
||||
}
|
||||
executeLocked("setUpdatePeriodMs", [&] { return client_.setUpdatePeriodMs(period_ms) ? 0 : -1; });
|
||||
}
|
||||
|
||||
bool UsbBioHead::expressionReadyLocked() const
|
||||
{
|
||||
if (!motion_mode_ || *motion_mode_ != HeadMotionMode::Immediate || joints_.size() != 5) return false;
|
||||
for (const char* id : {"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"}) {
|
||||
const auto found = joint_index_.find(id);
|
||||
if (found == joint_index_.end() || !snapshot_.joints[found->second].target_valid
|
||||
|| !immediate_targets_[found->second]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::vector<HeadExpressionPreset>& UsbBioHead::expressions() const
|
||||
{
|
||||
return headExpressionPresets();
|
||||
}
|
||||
|
||||
void UsbBioHead::cancelExpression() noexcept { cancel_generation_.fetch_add(1); }
|
||||
|
||||
void UsbBioHead::eStop()
|
||||
{
|
||||
cancelExpression();
|
||||
throw std::runtime_error("Future host expression frames cancelled; eRPC service 1 has no hardware emergency stop");
|
||||
}
|
||||
|
||||
void UsbBioHead::checkCancelled(uint64_t generation, const std::function<bool()>& cancelled) const
|
||||
{
|
||||
if (cancel_generation_.load() != generation || (cancelled && cancelled())) throw ExpressionCancelled();
|
||||
}
|
||||
|
||||
void UsbBioHead::setExpression(const std::vector<HeadJointTarget>& targets, double duration_s,
|
||||
const std::function<bool()>& cancelled)
|
||||
{
|
||||
auto lock = lockCommand();
|
||||
const auto generation = cancel_generation_.load();
|
||||
bool changed_settings = false;
|
||||
try {
|
||||
checkCancelled(generation, cancelled);
|
||||
if (!std::isfinite(duration_s) || duration_s < 0.2 || duration_s > 5.0) {
|
||||
throw std::invalid_argument("Expression duration must be finite and in [0.2, 5] seconds");
|
||||
}
|
||||
const auto destination = encodeTargetsLocked(targets, true);
|
||||
if (!client_.isOpen() || !expressionReadyLocked()) {
|
||||
throw std::runtime_error("Expression requires a full five-joint Immediate ACK baseline; call home first");
|
||||
}
|
||||
const auto count = static_cast<size_t>(std::ceil(duration_s * 1000.0 / 20.0));
|
||||
std::vector<EncodedTargets> frames;
|
||||
frames.reserve(count);
|
||||
// Validate and encode every frame before changing any firmware settings.
|
||||
for (size_t frame_index = 1; frame_index <= count; ++frame_index) {
|
||||
checkCancelled(generation, cancelled);
|
||||
const double progress = static_cast<double>(frame_index) / static_cast<double>(count);
|
||||
const double blend = progress * progress * progress * (10.0 + progress * (-15.0 + 6.0 * progress));
|
||||
EncodedTargets frame;
|
||||
frame.reserve(destination.size());
|
||||
for (const auto& target : destination) {
|
||||
const auto joint_index = indexOf(target.first);
|
||||
const double start = snapshot_.joints[joint_index].target_position_rad;
|
||||
const double end = target.second;
|
||||
const double value = frame_index == count ? end : start + (end - start) * blend;
|
||||
frame.emplace_back(target.first, checkedPosition(joints_[joint_index], value));
|
||||
}
|
||||
frames.push_back(std::move(frame));
|
||||
}
|
||||
checkCancelled(generation, cancelled);
|
||||
changed_settings = true;
|
||||
executeLocked("expression.setMode", [&] { return client_.setMode(0) ? 0 : -1; });
|
||||
motion_mode_ = HeadMotionMode::Immediate;
|
||||
checkCancelled(generation, cancelled);
|
||||
executeLocked("expression.setUpdatePeriodMs", [&] { return client_.setUpdatePeriodMs(20) ? 0 : -1; });
|
||||
using Clock = std::chrono::steady_clock;
|
||||
const auto started = Clock::now();
|
||||
size_t index = 1;
|
||||
while (index <= count) {
|
||||
checkCancelled(generation, cancelled);
|
||||
const auto due = started + std::chrono::duration_cast<Clock::duration>(
|
||||
std::chrono::duration<double>(duration_s * static_cast<double>(index) / count));
|
||||
while (Clock::now() < due) {
|
||||
checkCancelled(generation, cancelled);
|
||||
std::this_thread::sleep_for(std::min(due - Clock::now(),
|
||||
std::chrono::duration_cast<Clock::duration>(std::chrono::milliseconds(5))));
|
||||
}
|
||||
checkCancelled(generation, cancelled);
|
||||
const auto elapsed = std::chrono::duration<double>(Clock::now() - started).count();
|
||||
// Skip expired intermediate frames after delayed scheduling; never burst them.
|
||||
const auto latest_due = static_cast<size_t>(std::floor(elapsed * count / duration_s));
|
||||
index = std::min(count, std::max(index, latest_due));
|
||||
const auto& frame = frames[index - 1];
|
||||
checkCancelled(generation, cancelled);
|
||||
executeLocked("expression.move", [&] { return client_.move(frame); });
|
||||
rememberTargetsLocked(frame);
|
||||
checkCancelled(generation, cancelled);
|
||||
if (index == count) break; // The exact final frame must receive an ACK.
|
||||
const auto after_ack = std::chrono::duration<double>(Clock::now() - started).count();
|
||||
index = std::min(count, std::max(index + 1,
|
||||
static_cast<size_t>(std::floor(after_ack * count / duration_s)) + 1));
|
||||
}
|
||||
} catch (const ExpressionCancelled& error) {
|
||||
invalidateTargetsLocked();
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Unknown;
|
||||
snapshot_.last_error = error.what();
|
||||
throw;
|
||||
} catch (const std::exception& error) {
|
||||
if (changed_settings) {
|
||||
invalidateTargetsLocked();
|
||||
if (snapshot_.last_command_outcome != HeadCommandOutcome::Rejected
|
||||
&& snapshot_.last_command_outcome != HeadCommandOutcome::Unknown) {
|
||||
snapshot_.last_command_outcome = HeadCommandOutcome::Unknown;
|
||||
snapshot_.last_error = error.what();
|
||||
}
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
HeadExpressionPreset UsbBioHead::playExpression(const std::string& selector, bool by_name,
|
||||
double duration_s,
|
||||
const std::function<bool()>& cancelled)
|
||||
{
|
||||
const auto& presets = expressions();
|
||||
if (selector.empty()) throw std::invalid_argument("Head expression selector must not be empty");
|
||||
const auto matches = std::count_if(presets.begin(), presets.end(), [&](const auto& preset) {
|
||||
return (by_name ? preset.name : preset.id) == selector;
|
||||
});
|
||||
if (matches != 1) {
|
||||
throw std::invalid_argument(matches == 0 ? "Unknown head expression: " + selector
|
||||
: "Ambiguous head expression: " + selector);
|
||||
}
|
||||
const auto found = std::find_if(presets.begin(), presets.end(), [&](const auto& preset) {
|
||||
return (by_name ? preset.name : preset.id) == selector;
|
||||
});
|
||||
setExpression(found->targets, duration_s, cancelled);
|
||||
return *found;
|
||||
}
|
||||
|
||||
void UsbBioHead::expressionHappy() { playExpression(u8"微笑", true, 0.6, {}); }
|
||||
void UsbBioHead::expressionSurprised() { playExpression(u8"惊讶", true, 0.6, {}); }
|
||||
void UsbBioHead::expressionTired() { playExpression(u8"疲倦", true, 0.6, {}); }
|
||||
void UsbBioHead::expressionAngry() { playExpression(u8"生气", true, 0.6, {}); }
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -1,914 +0,0 @@
|
||||
#include "../include/usb_head_erpc_client.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <type_traits>
|
||||
|
||||
#include "erpc_basic_codec.hpp"
|
||||
#include "erpc_client_manager.h"
|
||||
#include "erpc_crc16.hpp"
|
||||
#include "erpc_framed_transport.hpp"
|
||||
#include "erpc_version.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
|
||||
static_assert(
|
||||
ERPC_VERSION_NUMBER == 11400,
|
||||
"USB head requires eRPC 1.14.0");
|
||||
|
||||
// 将项目串口接入官方 FramedTransport。
|
||||
// 帧封装、CRC 和类型编解码由官方 SDK 处理。
|
||||
class SdkFramedSerialTransport final : public erpc::FramedTransport {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
static constexpr std::size_t kFrameHeaderSize = 6;
|
||||
static constexpr std::size_t kMaxBodySize = 4096;
|
||||
|
||||
explicit SdkFramedSerialTransport(
|
||||
::cmvr::AbstractSerialTransport& serial);
|
||||
|
||||
~SdkFramedSerialTransport() override = default;
|
||||
|
||||
SdkFramedSerialTransport(
|
||||
const SdkFramedSerialTransport&) = delete;
|
||||
|
||||
SdkFramedSerialTransport& operator=(
|
||||
const SdkFramedSerialTransport&) = delete;
|
||||
|
||||
void beginTransaction(
|
||||
Clock::time_point deadline,
|
||||
std::size_t expected_reply_body_size);
|
||||
|
||||
void endTransaction() noexcept;
|
||||
void reset() noexcept;
|
||||
|
||||
const std::string& lastError() const noexcept
|
||||
{
|
||||
return last_error_;
|
||||
}
|
||||
|
||||
erpc_status_t send(erpc::MessageBuffer* message) override;
|
||||
erpc_status_t receive(erpc::MessageBuffer* message) override;
|
||||
|
||||
protected:
|
||||
erpc_status_t underlyingSend(
|
||||
const std::uint8_t* data,
|
||||
std::uint32_t size) override;
|
||||
|
||||
erpc_status_t underlyingReceive(
|
||||
std::uint8_t* data,
|
||||
std::uint32_t size) override;
|
||||
|
||||
erpc_status_t underlyingReceive(
|
||||
erpc::MessageBuffer* message,
|
||||
std::uint32_t size,
|
||||
std::uint32_t offset) override;
|
||||
|
||||
private:
|
||||
erpc_status_t checkReady();
|
||||
|
||||
erpc_status_t fail(
|
||||
erpc_status_t status,
|
||||
std::string message);
|
||||
|
||||
erpc_status_t sdkFailure(
|
||||
erpc_status_t status,
|
||||
const char* operation);
|
||||
|
||||
::cmvr::AbstractSerialTransport& serial_;
|
||||
|
||||
// 官方 CRC 实现,初始值与现有控制板一致。
|
||||
erpc::Crc16 crc_{0xEF4A};
|
||||
|
||||
Clock::time_point deadline_{};
|
||||
std::size_t expected_reply_body_size_{0};
|
||||
bool transaction_active_{false};
|
||||
|
||||
std::vector<std::uint8_t> pending_;
|
||||
std::string last_error_;
|
||||
};
|
||||
|
||||
SdkFramedSerialTransport::SdkFramedSerialTransport(
|
||||
::cmvr::AbstractSerialTransport& serial)
|
||||
: serial_(serial)
|
||||
{
|
||||
setCrc16(&crc_);
|
||||
}
|
||||
|
||||
void SdkFramedSerialTransport::beginTransaction(
|
||||
Clock::time_point deadline,
|
||||
std::size_t expected_reply_body_size)
|
||||
{
|
||||
if (transaction_active_) {
|
||||
throw std::logic_error(
|
||||
"An eRPC transaction is already active");
|
||||
}
|
||||
|
||||
if (expected_reply_body_size < 8
|
||||
|| expected_reply_body_size > kMaxBodySize) {
|
||||
throw std::invalid_argument(
|
||||
"Invalid expected eRPC reply body size");
|
||||
}
|
||||
|
||||
if (!pending_.empty()) {
|
||||
throw std::runtime_error(
|
||||
"Unexpected bytes remain before eRPC request");
|
||||
}
|
||||
|
||||
last_error_.clear();
|
||||
deadline_ = deadline;
|
||||
expected_reply_body_size_ = expected_reply_body_size;
|
||||
transaction_active_ = true;
|
||||
}
|
||||
|
||||
void SdkFramedSerialTransport::endTransaction() noexcept
|
||||
{
|
||||
transaction_active_ = false;
|
||||
deadline_ = {};
|
||||
expected_reply_body_size_ = 0;
|
||||
}
|
||||
|
||||
void SdkFramedSerialTransport::reset() noexcept
|
||||
{
|
||||
endTransaction();
|
||||
pending_.clear();
|
||||
last_error_.clear();
|
||||
}
|
||||
|
||||
erpc_status_t SdkFramedSerialTransport::fail(
|
||||
erpc_status_t status,
|
||||
std::string message)
|
||||
{
|
||||
last_error_ = std::move(message);
|
||||
return status;
|
||||
}
|
||||
|
||||
erpc_status_t SdkFramedSerialTransport::checkReady()
|
||||
{
|
||||
if (!transaction_active_) {
|
||||
return fail(
|
||||
kErpcStatus_InvalidArgument,
|
||||
"eRPC transaction deadline is not established");
|
||||
}
|
||||
|
||||
if (Clock::now() >= deadline_) {
|
||||
return fail(
|
||||
kErpcStatus_Timeout,
|
||||
"USB head transaction deadline exceeded");
|
||||
}
|
||||
|
||||
if (!serial_.isOpen()) {
|
||||
return fail(
|
||||
kErpcStatus_ConnectionClosed,
|
||||
"USB head serial transport is not open");
|
||||
}
|
||||
|
||||
return kErpcStatus_Success;
|
||||
}
|
||||
|
||||
erpc_status_t SdkFramedSerialTransport::sdkFailure(
|
||||
erpc_status_t status,
|
||||
const char* operation)
|
||||
{
|
||||
if (status != kErpcStatus_Success && last_error_.empty()) {
|
||||
last_error_ =
|
||||
std::string("Official eRPC ") + operation
|
||||
+ " failed, status="
|
||||
+ std::to_string(static_cast<int>(status));
|
||||
|
||||
if (status == kErpcStatus_CrcCheckFailed) {
|
||||
last_error_ += " (frame CRC mismatch)";
|
||||
}
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
erpc_status_t SdkFramedSerialTransport::send(
|
||||
erpc::MessageBuffer* message)
|
||||
{
|
||||
try {
|
||||
const auto ready = checkReady();
|
||||
|
||||
if (ready != kErpcStatus_Success) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
if (!message
|
||||
|| !message->get()
|
||||
|| message->getUsed() < kFrameHeaderSize + 8
|
||||
|| message->getUsed() > message->getLength()
|
||||
|| message->getUsed() - kFrameHeaderSize > kMaxBodySize) {
|
||||
return fail(
|
||||
kErpcStatus_InvalidArgument,
|
||||
"Invalid or oversized eRPC request buffer");
|
||||
}
|
||||
|
||||
return sdkFailure(
|
||||
erpc::FramedTransport::send(message),
|
||||
"send");
|
||||
} catch (const std::exception& error) {
|
||||
return fail(
|
||||
kErpcStatus_SendFailed,
|
||||
std::string("USB head send failed: ") + error.what());
|
||||
} catch (...) {
|
||||
return fail(
|
||||
kErpcStatus_SendFailed,
|
||||
"Unknown USB head send failure");
|
||||
}
|
||||
}
|
||||
|
||||
erpc_status_t SdkFramedSerialTransport::receive(
|
||||
erpc::MessageBuffer* message)
|
||||
{
|
||||
try {
|
||||
const auto ready = checkReady();
|
||||
|
||||
if (ready != kErpcStatus_Success) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
const auto required =
|
||||
kFrameHeaderSize + expected_reply_body_size_;
|
||||
|
||||
if (!message
|
||||
|| !message->get()
|
||||
|| message->getLength() < required) {
|
||||
return fail(
|
||||
kErpcStatus_MemoryError,
|
||||
"eRPC reply buffer is too small");
|
||||
}
|
||||
|
||||
erpc::MessageBuffer bounded(
|
||||
message->get(),
|
||||
static_cast<std::uint16_t>(required));
|
||||
|
||||
const auto status =
|
||||
erpc::FramedTransport::receive(&bounded);
|
||||
|
||||
if (status != kErpcStatus_Success) {
|
||||
message->setUsed(0);
|
||||
return sdkFailure(status, "receive");
|
||||
}
|
||||
|
||||
if (bounded.getUsed() != required) {
|
||||
message->setUsed(0);
|
||||
return fail(
|
||||
kErpcStatus_ReceiveFailed,
|
||||
"USB head reply length mismatch");
|
||||
}
|
||||
|
||||
if (!pending_.empty()) {
|
||||
message->setUsed(0);
|
||||
return fail(
|
||||
kErpcStatus_ReceiveFailed,
|
||||
"USB head received unexpected trailing bytes");
|
||||
}
|
||||
|
||||
const auto after_receive = checkReady();
|
||||
|
||||
if (after_receive != kErpcStatus_Success) {
|
||||
message->setUsed(0);
|
||||
return after_receive;
|
||||
}
|
||||
|
||||
message->setUsed(bounded.getUsed());
|
||||
return kErpcStatus_Success;
|
||||
} catch (const std::exception& error) {
|
||||
if (message) {
|
||||
message->setUsed(0);
|
||||
}
|
||||
|
||||
return fail(
|
||||
kErpcStatus_ReceiveFailed,
|
||||
std::string("USB head receive failed: ") + error.what());
|
||||
} catch (...) {
|
||||
if (message) {
|
||||
message->setUsed(0);
|
||||
}
|
||||
|
||||
return fail(
|
||||
kErpcStatus_ReceiveFailed,
|
||||
"Unknown USB head receive failure");
|
||||
}
|
||||
}
|
||||
|
||||
erpc_status_t SdkFramedSerialTransport::underlyingSend(
|
||||
const std::uint8_t* data,
|
||||
std::uint32_t size)
|
||||
{
|
||||
const auto ready = checkReady();
|
||||
|
||||
if (ready != kErpcStatus_Success) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
if (!data
|
||||
|| size < kFrameHeaderSize
|
||||
|| size > kFrameHeaderSize + kMaxBodySize) {
|
||||
return fail(
|
||||
kErpcStatus_InvalidArgument,
|
||||
"Invalid eRPC frame write size");
|
||||
}
|
||||
|
||||
const std::vector<std::uint8_t> bytes(data, data + size);
|
||||
|
||||
if (!serial_.write(bytes)) {
|
||||
return fail(
|
||||
Clock::now() >= deadline_
|
||||
? kErpcStatus_Timeout
|
||||
: kErpcStatus_SendFailed,
|
||||
"USB head write failed: " + serial_.lastError());
|
||||
}
|
||||
|
||||
return checkReady();
|
||||
}
|
||||
|
||||
erpc_status_t SdkFramedSerialTransport::underlyingReceive(
|
||||
erpc::MessageBuffer* message,
|
||||
std::uint32_t size,
|
||||
std::uint32_t offset)
|
||||
{
|
||||
if (!message
|
||||
|| !message->get()
|
||||
|| offset > message->getLength()
|
||||
|| size > message->getLength() - offset) {
|
||||
return fail(
|
||||
kErpcStatus_MemoryError,
|
||||
"Invalid eRPC receive buffer bounds");
|
||||
}
|
||||
|
||||
if (offset == 0) {
|
||||
if (size != kFrameHeaderSize) {
|
||||
return fail(
|
||||
kErpcStatus_ReceiveFailed,
|
||||
"Unexpected eRPC frame header size");
|
||||
}
|
||||
} else if (offset != kFrameHeaderSize
|
||||
|| size != expected_reply_body_size_) {
|
||||
return fail(
|
||||
kErpcStatus_ReceiveFailed,
|
||||
"USB head reply length mismatch");
|
||||
}
|
||||
|
||||
return erpc::FramedTransport::underlyingReceive(
|
||||
message, size, offset);
|
||||
}
|
||||
|
||||
erpc_status_t SdkFramedSerialTransport::underlyingReceive(
|
||||
std::uint8_t* data,
|
||||
std::uint32_t size)
|
||||
{
|
||||
if (!data || size > kMaxBodySize) {
|
||||
return fail(
|
||||
kErpcStatus_InvalidArgument,
|
||||
"Invalid eRPC receive size");
|
||||
}
|
||||
|
||||
while (pending_.size() < size) {
|
||||
const auto ready = checkReady();
|
||||
|
||||
if (ready != kErpcStatus_Success) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
const auto remaining = deadline_ - Clock::now();
|
||||
|
||||
if (remaining <= Clock::duration::zero()) {
|
||||
return fail(
|
||||
kErpcStatus_Timeout,
|
||||
"USB head reply deadline exceeded");
|
||||
}
|
||||
|
||||
auto wait =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
remaining);
|
||||
|
||||
if (wait.count() == 0) {
|
||||
wait = std::chrono::milliseconds(1);
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> chunk;
|
||||
|
||||
if (!serial_.read(size - pending_.size(), wait, chunk)
|
||||
|| chunk.empty()) {
|
||||
return fail(
|
||||
Clock::now() >= deadline_
|
||||
? kErpcStatus_Timeout
|
||||
: kErpcStatus_ReceiveFailed,
|
||||
"USB head reply incomplete: " + serial_.lastError());
|
||||
}
|
||||
|
||||
if (pending_.size() > kMaxBodySize + kFrameHeaderSize
|
||||
|| chunk.size()
|
||||
> kMaxBodySize + kFrameHeaderSize - pending_.size()) {
|
||||
return fail(
|
||||
kErpcStatus_ReceiveFailed,
|
||||
"USB head reply exceeds receive limit");
|
||||
}
|
||||
|
||||
pending_.insert(
|
||||
pending_.end(), chunk.begin(), chunk.end());
|
||||
}
|
||||
|
||||
const auto ready = checkReady();
|
||||
|
||||
if (ready != kErpcStatus_Success) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
std::memcpy(data, pending_.data(), size);
|
||||
pending_.erase(pending_.begin(), pending_.begin() + size);
|
||||
|
||||
return kErpcStatus_Success;
|
||||
}
|
||||
|
||||
// 官方 Codec 负责类型编解码;这里保留严格的 bool ACK 检查。
|
||||
class StrictCodec final : public erpc::BasicCodec {
|
||||
public:
|
||||
using erpc::BasicCodec::read;
|
||||
|
||||
void read(bool& value) override
|
||||
{
|
||||
std::uint8_t encoded{0};
|
||||
erpc::BasicCodec::read(encoded);
|
||||
|
||||
if (isStatusOk() && encoded > 1) {
|
||||
updateStatus(kErpcStatus_InvalidArgument);
|
||||
}
|
||||
|
||||
value = encoded == 1;
|
||||
}
|
||||
};
|
||||
|
||||
class CodecFactory final : public erpc::CodecFactory {
|
||||
public:
|
||||
erpc::Codec* create() override
|
||||
{
|
||||
return new (std::nothrow) StrictCodec;
|
||||
}
|
||||
|
||||
void dispose(erpc::Codec* codec) override
|
||||
{
|
||||
delete codec;
|
||||
}
|
||||
};
|
||||
|
||||
class BufferFactory final : public erpc::MessageBufferFactory {
|
||||
public:
|
||||
erpc::MessageBuffer create() override
|
||||
{
|
||||
auto* data = new (std::nothrow) std::uint8_t[4102];
|
||||
return erpc::MessageBuffer(data, data ? 4102 : 0);
|
||||
}
|
||||
|
||||
void dispose(erpc::MessageBuffer* buffer) override
|
||||
{
|
||||
delete[] buffer->get();
|
||||
}
|
||||
};
|
||||
|
||||
class ClientManager final : public erpc::ClientManager {
|
||||
public:
|
||||
explicit ClientManager(std::uint32_t seed)
|
||||
{
|
||||
m_sequence = seed;
|
||||
}
|
||||
|
||||
void begin(std::uint8_t method)
|
||||
{
|
||||
method_ = method;
|
||||
}
|
||||
|
||||
erpc::RequestContext createRequest(bool oneway) override
|
||||
{
|
||||
if (m_sequence
|
||||
== std::numeric_limits<std::uint32_t>::max()) {
|
||||
m_sequence = 0;
|
||||
}
|
||||
|
||||
return erpc::ClientManager::createRequest(oneway);
|
||||
}
|
||||
|
||||
protected:
|
||||
void verifyReply(erpc::RequestContext& request) override
|
||||
{
|
||||
auto* codec = request.getCodec();
|
||||
|
||||
codec->reset(m_transport->reserveHeaderSize());
|
||||
|
||||
erpc::message_type_t type{};
|
||||
std::uint32_t service{};
|
||||
std::uint32_t method{};
|
||||
std::uint32_t sequence{};
|
||||
|
||||
codec->startReadMessage(
|
||||
type, service, method, sequence);
|
||||
|
||||
if (codec->isStatusOk()
|
||||
&& (type != erpc::message_type_t::kReplyMessage
|
||||
|| service != 1
|
||||
|| method != method_
|
||||
|| sequence != request.getSequence())) {
|
||||
codec->updateStatus(kErpcStatus_ExpectedReply);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::uint8_t method_{0};
|
||||
};
|
||||
|
||||
void checkId(const std::string& id)
|
||||
{
|
||||
if (id.empty()
|
||||
|| id.size() > 64
|
||||
|| id.find('\0') != std::string::npos) {
|
||||
throw std::invalid_argument(
|
||||
"USB head servo ID must contain 1..64 non-NUL bytes");
|
||||
}
|
||||
}
|
||||
|
||||
void checkFinite(float value)
|
||||
{
|
||||
if (!std::isfinite(value)) {
|
||||
throw std::invalid_argument(
|
||||
"USB head arguments must be finite float32 values");
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct UsbHeadErpcClient::Impl {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> serial;
|
||||
std::chrono::milliseconds timeout;
|
||||
mutable std::mutex mutex;
|
||||
|
||||
std::string port;
|
||||
int baud{0};
|
||||
|
||||
SdkFramedSerialTransport transport;
|
||||
CodecFactory codec_factory;
|
||||
BufferFactory buffer_factory;
|
||||
ClientManager manager;
|
||||
|
||||
Impl(
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> wire,
|
||||
std::chrono::milliseconds budget,
|
||||
std::uint32_t seed)
|
||||
: serial(std::move(wire)),
|
||||
timeout(budget),
|
||||
transport(*serial),
|
||||
manager(seed)
|
||||
{
|
||||
manager.setTransport(&transport);
|
||||
manager.setCodecFactory(&codec_factory);
|
||||
manager.setMessageBufferFactory(&buffer_factory);
|
||||
}
|
||||
|
||||
void failClosed() noexcept
|
||||
{
|
||||
transport.reset();
|
||||
|
||||
try {
|
||||
serial->close();
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
|
||||
void checkStatus(erpc::Codec& codec)
|
||||
{
|
||||
if (!codec.isStatusOk()) {
|
||||
throw std::runtime_error(
|
||||
"Official eRPC status="
|
||||
+ std::to_string(
|
||||
static_cast<int>(codec.getStatus()))
|
||||
+ ": " + transport.lastError());
|
||||
}
|
||||
}
|
||||
|
||||
template<typename Result, typename EncodeArguments>
|
||||
Result invoke(
|
||||
std::uint8_t method,
|
||||
EncodeArguments encode_arguments)
|
||||
{
|
||||
static_assert(
|
||||
std::is_same_v<Result, bool>
|
||||
|| std::is_same_v<Result, std::int32_t>,
|
||||
"Head service returns only bool or int32");
|
||||
|
||||
std::lock_guard lock(mutex);
|
||||
|
||||
if (!serial->isOpen()) {
|
||||
throw std::runtime_error(
|
||||
"USB head is not connected");
|
||||
}
|
||||
|
||||
const auto deadline = Clock::now() + timeout;
|
||||
|
||||
try {
|
||||
transport.beginTransaction(
|
||||
deadline, method <= 4 ? 9 : 12);
|
||||
|
||||
manager.begin(method);
|
||||
|
||||
Result result{};
|
||||
|
||||
{
|
||||
auto request = manager.createRequest(false);
|
||||
|
||||
struct ReleaseRequest {
|
||||
ClientManager& manager;
|
||||
erpc::RequestContext& request;
|
||||
|
||||
~ReleaseRequest()
|
||||
{
|
||||
manager.releaseRequest(request);
|
||||
}
|
||||
} release{manager, request};
|
||||
|
||||
auto* codec = request.getCodec();
|
||||
|
||||
if (!codec) {
|
||||
throw std::runtime_error(
|
||||
"Cannot allocate eRPC request buffer/codec");
|
||||
}
|
||||
|
||||
codec->startWriteMessage(
|
||||
erpc::message_type_t::kInvocationMessage,
|
||||
1,
|
||||
method,
|
||||
request.getSequence());
|
||||
|
||||
encode_arguments(*codec);
|
||||
checkStatus(*codec);
|
||||
|
||||
manager.performRequest(request);
|
||||
checkStatus(*codec);
|
||||
|
||||
codec->read(result);
|
||||
checkStatus(*codec);
|
||||
}
|
||||
|
||||
if (Clock::now() >= deadline) {
|
||||
throw std::runtime_error(
|
||||
"USB head reply deadline exceeded");
|
||||
}
|
||||
|
||||
transport.endTransaction();
|
||||
return result;
|
||||
} catch (const std::exception& error) {
|
||||
const std::string reason = error.what();
|
||||
|
||||
failClosed();
|
||||
|
||||
throw std::runtime_error(
|
||||
"USB head method " + std::to_string(method)
|
||||
+ " result unconfirmed; disconnected without retry. "
|
||||
"Command may already have taken effect: "
|
||||
+ reason);
|
||||
} catch (...) {
|
||||
failClosed();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
UsbHeadErpcClient::UsbHeadErpcClient(
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> serial,
|
||||
std::chrono::milliseconds timeout)
|
||||
: UsbHeadErpcClient(
|
||||
std::move(serial),
|
||||
timeout,
|
||||
std::random_device{}())
|
||||
{
|
||||
}
|
||||
|
||||
UsbHeadErpcClient::UsbHeadErpcClient(
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> serial,
|
||||
std::chrono::milliseconds timeout,
|
||||
std::uint32_t seed)
|
||||
{
|
||||
if (!serial || timeout.count() <= 0) {
|
||||
throw std::invalid_argument(
|
||||
"USB head transport and positive timeout are required");
|
||||
}
|
||||
|
||||
impl_ = std::make_unique<Impl>(
|
||||
std::move(serial), timeout, seed);
|
||||
}
|
||||
|
||||
UsbHeadErpcClient::~UsbHeadErpcClient()
|
||||
{
|
||||
try {
|
||||
close();
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
|
||||
void UsbHeadErpcClient::open(
|
||||
const std::string& port,
|
||||
int baud)
|
||||
{
|
||||
if (port.empty() || baud <= 0) {
|
||||
throw std::invalid_argument(
|
||||
"USB head serial port and positive baud rate are required");
|
||||
}
|
||||
|
||||
std::lock_guard lock(impl_->mutex);
|
||||
|
||||
if (impl_->serial->isOpen()) {
|
||||
if (port != impl_->port || baud != impl_->baud) {
|
||||
throw std::logic_error(
|
||||
"Close USB head before changing serial configuration");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
impl_->transport.reset();
|
||||
|
||||
try {
|
||||
if (!impl_->serial->open({port, baud})) {
|
||||
throw std::runtime_error(
|
||||
"Cannot open USB head port: "
|
||||
+ impl_->serial->lastError());
|
||||
}
|
||||
|
||||
if (!impl_->serial->flushInput()) {
|
||||
throw std::runtime_error(
|
||||
"Cannot clear USB head input: "
|
||||
+ impl_->serial->lastError());
|
||||
}
|
||||
|
||||
impl_->port = port;
|
||||
impl_->baud = baud;
|
||||
} catch (...) {
|
||||
impl_->failClosed();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void UsbHeadErpcClient::close()
|
||||
{
|
||||
std::lock_guard lock(impl_->mutex);
|
||||
|
||||
impl_->transport.reset();
|
||||
|
||||
if (impl_->serial->isOpen()
|
||||
&& !impl_->serial->close()) {
|
||||
throw std::runtime_error(
|
||||
"Cannot close USB head port: "
|
||||
+ impl_->serial->lastError());
|
||||
}
|
||||
}
|
||||
|
||||
bool UsbHeadErpcClient::isOpen() const
|
||||
{
|
||||
std::lock_guard lock(impl_->mutex);
|
||||
return impl_->serial->isOpen();
|
||||
}
|
||||
|
||||
bool UsbHeadErpcClient::setConstraints(
|
||||
const std::string& id,
|
||||
float velocity,
|
||||
float acceleration,
|
||||
float jerk)
|
||||
{
|
||||
checkId(id);
|
||||
checkFinite(velocity);
|
||||
checkFinite(acceleration);
|
||||
checkFinite(jerk);
|
||||
|
||||
if (velocity <= 0 || acceleration <= 0 || jerk <= 0) {
|
||||
throw std::invalid_argument(
|
||||
"USB head motion limits must be positive");
|
||||
}
|
||||
|
||||
return impl_->invoke<bool>(1, [&](erpc::Codec& codec) {
|
||||
codec.writeString(
|
||||
static_cast<std::uint32_t>(id.size()),
|
||||
id.c_str());
|
||||
|
||||
codec.write(velocity);
|
||||
codec.write(acceleration);
|
||||
codec.write(jerk);
|
||||
});
|
||||
}
|
||||
|
||||
bool UsbHeadErpcClient::setPositionGain(
|
||||
const std::string& id,
|
||||
float gain)
|
||||
{
|
||||
checkId(id);
|
||||
checkFinite(gain);
|
||||
|
||||
if (gain < 0) {
|
||||
throw std::invalid_argument(
|
||||
"USB head position gain must be nonnegative");
|
||||
}
|
||||
|
||||
return impl_->invoke<bool>(2, [&](erpc::Codec& codec) {
|
||||
codec.writeString(
|
||||
static_cast<std::uint32_t>(id.size()),
|
||||
id.c_str());
|
||||
|
||||
codec.write(gain);
|
||||
});
|
||||
}
|
||||
|
||||
bool UsbHeadErpcClient::setMode(std::int32_t mode)
|
||||
{
|
||||
if (mode < 0 || mode > 2) {
|
||||
throw std::invalid_argument(
|
||||
"USB head mode must be 0, 1 or 2");
|
||||
}
|
||||
|
||||
return impl_->invoke<bool>(3, [&](erpc::Codec& codec) {
|
||||
codec.write(mode);
|
||||
});
|
||||
}
|
||||
|
||||
bool UsbHeadErpcClient::setUpdatePeriodMs(
|
||||
std::uint32_t period)
|
||||
{
|
||||
if (period < 1 || period > 100) {
|
||||
throw std::invalid_argument(
|
||||
"USB head update period must be 1..100 ms");
|
||||
}
|
||||
|
||||
return impl_->invoke<bool>(4, [&](erpc::Codec& codec) {
|
||||
codec.write(period);
|
||||
});
|
||||
}
|
||||
|
||||
std::int32_t UsbHeadErpcClient::move(
|
||||
const std::vector<Target>& targets)
|
||||
{
|
||||
if (targets.size() > 5) {
|
||||
throw std::invalid_argument(
|
||||
"USB head supports at most five targets");
|
||||
}
|
||||
|
||||
std::set<std::string> seen;
|
||||
|
||||
for (const auto& target : targets) {
|
||||
checkId(target.first);
|
||||
checkFinite(target.second);
|
||||
|
||||
if (!seen.insert(target.first).second) {
|
||||
throw std::invalid_argument(
|
||||
"USB head servo ID repeated in target batch");
|
||||
}
|
||||
}
|
||||
|
||||
return impl_->invoke<std::int32_t>(
|
||||
5,
|
||||
[&](erpc::Codec& codec) {
|
||||
codec.startWriteList(
|
||||
static_cast<std::uint32_t>(targets.size()));
|
||||
|
||||
for (const auto& target : targets) {
|
||||
codec.writeString(
|
||||
static_cast<std::uint32_t>(
|
||||
target.first.size()),
|
||||
target.first.c_str());
|
||||
|
||||
codec.write(target.second);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
std::int32_t UsbHeadErpcClient::moveJ(
|
||||
const std::vector<float>& angles)
|
||||
{
|
||||
if (angles.size() > 5) {
|
||||
throw std::invalid_argument(
|
||||
"USB head supports at most five joint targets");
|
||||
}
|
||||
|
||||
for (const auto value : angles) {
|
||||
checkFinite(value);
|
||||
}
|
||||
|
||||
return impl_->invoke<std::int32_t>(
|
||||
6,
|
||||
[&](erpc::Codec& codec) {
|
||||
codec.startWriteList(
|
||||
static_cast<std::uint32_t>(angles.size()));
|
||||
|
||||
for (const auto value : angles) {
|
||||
codec.write(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -1,266 +0,0 @@
|
||||
#include "../include/usb_head_serial_transport.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <stdexcept>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
#include <asm/termbits.h>
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
template <typename Operation>
|
||||
int retryInterrupted(Operation operation, Clock::time_point deadline)
|
||||
{
|
||||
for (;;) {
|
||||
if (Clock::now() >= deadline) {
|
||||
errno = ETIMEDOUT;
|
||||
return -1;
|
||||
}
|
||||
const int result = operation();
|
||||
if (result >= 0 || errno != EINTR) return result;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
UsbHeadSerialTransport::UsbHeadSerialTransport(std::chrono::milliseconds io_timeout)
|
||||
: io_timeout_(io_timeout)
|
||||
{
|
||||
if (io_timeout_.count() <= 0 ||
|
||||
io_timeout_ > std::chrono::duration_cast<std::chrono::milliseconds>(Clock::duration::max() / 2)) {
|
||||
throw std::invalid_argument("USB head I/O timeout is invalid");
|
||||
}
|
||||
}
|
||||
|
||||
UsbHeadSerialTransport::~UsbHeadSerialTransport()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
void UsbHeadSerialTransport::setSystemError(const char* operation, int error_number)
|
||||
{
|
||||
last_error_ = std::string(operation) + ": " + std::strerror(error_number);
|
||||
}
|
||||
|
||||
bool UsbHeadSerialTransport::open(const Config& config)
|
||||
{
|
||||
std::lock_guard lock(io_mutex_);
|
||||
last_error_.clear();
|
||||
if (config.port_name.empty() || config.port_name.find('\0') != std::string::npos ||
|
||||
config.baud_rate <= 0) {
|
||||
last_error_ = "USB head requires a nonempty serial port and positive baud rate";
|
||||
return false;
|
||||
}
|
||||
if (!closeUnlocked()) return false;
|
||||
|
||||
const auto deadline = Clock::now() + io_timeout_;
|
||||
fd_ = retryInterrupted([&] {
|
||||
return ::open(config.port_name.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
|
||||
}, deadline);
|
||||
if (fd_ < 0) {
|
||||
setSystemError("Cannot open USB head serial port", errno);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
auto fail = [&](const char* operation) {
|
||||
const int saved_errno = errno;
|
||||
closeUnlocked();
|
||||
setSystemError(operation, saved_errno);
|
||||
return false;
|
||||
};
|
||||
if (retryInterrupted([&] { return ::ioctl(fd_, TIOCEXCL); }, deadline) != 0) {
|
||||
return fail("Cannot acquire exclusive USB head serial access");
|
||||
}
|
||||
exclusive_ = true;
|
||||
termios2 options{};
|
||||
if (retryInterrupted([&] { return ::ioctl(fd_, TCGETS2, &options); }, deadline) != 0) {
|
||||
return fail("Cannot query USB head serial attributes");
|
||||
}
|
||||
|
||||
options.c_iflag = 0;
|
||||
options.c_oflag = 0;
|
||||
options.c_lflag = 0;
|
||||
options.c_cflag &= ~(CSIZE | PARENB | PARODD | CSTOPB | CRTSCTS | CBAUD | CIBAUD);
|
||||
options.c_cflag |= CS8 | CLOCAL | CREAD | BOTHER;
|
||||
options.c_cc[VMIN] = 0;
|
||||
options.c_cc[VTIME] = 0;
|
||||
options.c_ispeed = static_cast<speed_t>(config.baud_rate);
|
||||
options.c_ospeed = static_cast<speed_t>(config.baud_rate);
|
||||
if (retryInterrupted([&] { return ::ioctl(fd_, TCSETS2, &options); }, deadline) != 0) {
|
||||
return fail("Cannot apply USB head raw 8N1 attributes");
|
||||
}
|
||||
if (retryInterrupted([&] { return ::ioctl(fd_, TCFLSH, TCIOFLUSH); }, deadline) != 0) {
|
||||
return fail("Cannot flush USB head serial buffers");
|
||||
}
|
||||
return true;
|
||||
} catch (...) {
|
||||
closeUnlocked();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
bool UsbHeadSerialTransport::close() noexcept
|
||||
{
|
||||
try {
|
||||
std::lock_guard lock(io_mutex_);
|
||||
last_error_.clear();
|
||||
return closeUnlocked();
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool UsbHeadSerialTransport::closeUnlocked() noexcept
|
||||
{
|
||||
if (fd_ < 0) return true;
|
||||
const int owned_fd = fd_;
|
||||
const bool release_exclusive = exclusive_;
|
||||
fd_ = -1;
|
||||
exclusive_ = false;
|
||||
|
||||
int release_error = 0;
|
||||
if (release_exclusive && retryInterrupted([&] {
|
||||
return ::ioctl(owned_fd, TIOCNXCL);
|
||||
}, Clock::now() + io_timeout_) != 0 && errno != EIO && errno != ENODEV) {
|
||||
release_error = errno;
|
||||
}
|
||||
// On Linux close() releases the descriptor even for EINTR. Retrying could
|
||||
// close an unrelated descriptor subsequently reused by another thread.
|
||||
const int result = ::close(owned_fd);
|
||||
const int close_error = result == 0 ? 0 : errno;
|
||||
try {
|
||||
if (close_error) setSystemError("Cannot close USB head serial port", close_error);
|
||||
else if (release_error) setSystemError("Cannot release USB head serial exclusive mode", release_error);
|
||||
} catch (...) { }
|
||||
return close_error == 0 && release_error == 0;
|
||||
}
|
||||
|
||||
bool UsbHeadSerialTransport::isOpen() const
|
||||
{
|
||||
std::lock_guard lock(io_mutex_);
|
||||
return fd_ >= 0;
|
||||
}
|
||||
|
||||
bool UsbHeadSerialTransport::flushInput()
|
||||
{
|
||||
std::lock_guard lock(io_mutex_);
|
||||
last_error_.clear();
|
||||
if (fd_ < 0) {
|
||||
last_error_ = "USB head serial port is not open";
|
||||
return false;
|
||||
}
|
||||
if (retryInterrupted([&] { return ::ioctl(fd_, TCFLSH, TCIFLUSH); },
|
||||
Clock::now() + io_timeout_) != 0) {
|
||||
setSystemError("Cannot flush USB head serial input", errno);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool UsbHeadSerialTransport::waitReady(short events, Clock::time_point deadline)
|
||||
{
|
||||
for (;;) {
|
||||
const auto now = Clock::now();
|
||||
if (now >= deadline) {
|
||||
last_error_ = "USB head serial I/O deadline exceeded";
|
||||
return false;
|
||||
}
|
||||
const auto remaining = std::chrono::ceil<std::chrono::milliseconds>(deadline - now);
|
||||
const int wait_ms = static_cast<int>(std::min<long long>(remaining.count(), INT_MAX));
|
||||
pollfd descriptor{fd_, events, 0};
|
||||
const int result = ::poll(&descriptor, 1, wait_ms);
|
||||
if (result < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
setSystemError("USB head serial poll failed", errno);
|
||||
return false;
|
||||
}
|
||||
if (result == 0) continue;
|
||||
if (descriptor.revents & (POLLERR | POLLHUP | POLLNVAL)) {
|
||||
last_error_ = "USB head serial port disconnected or invalid";
|
||||
return false;
|
||||
}
|
||||
if (descriptor.revents & events) return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool UsbHeadSerialTransport::write(const std::vector<std::uint8_t>& data)
|
||||
{
|
||||
std::lock_guard lock(io_mutex_);
|
||||
last_error_.clear();
|
||||
if (fd_ < 0) {
|
||||
last_error_ = "USB head serial port is not open";
|
||||
return false;
|
||||
}
|
||||
const auto deadline = Clock::now() + io_timeout_;
|
||||
std::size_t offset = 0;
|
||||
while (offset < data.size()) {
|
||||
if (Clock::now() >= deadline) {
|
||||
last_error_ = "USB head serial write deadline exceeded; bytes may already have been sent";
|
||||
return false;
|
||||
}
|
||||
const auto written = ::write(fd_, data.data() + offset, data.size() - offset);
|
||||
if (written > 0) {
|
||||
offset += static_cast<std::size_t>(written);
|
||||
continue;
|
||||
}
|
||||
if (written < 0 && errno == EINTR) continue;
|
||||
if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
|
||||
if (!waitReady(POLLOUT, deadline)) return false;
|
||||
continue;
|
||||
}
|
||||
if (written == 0) last_error_ = "USB head serial write made no progress";
|
||||
else setSystemError("USB head serial write failed", errno);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool UsbHeadSerialTransport::read(std::size_t min_size, std::chrono::milliseconds timeout,
|
||||
std::vector<std::uint8_t>& out_buffer)
|
||||
{
|
||||
std::lock_guard lock(io_mutex_);
|
||||
last_error_.clear();
|
||||
out_buffer.clear();
|
||||
if (fd_ < 0) {
|
||||
last_error_ = "USB head serial port is not open";
|
||||
return false;
|
||||
}
|
||||
if (timeout.count() <= 0 || min_size > 65536) {
|
||||
last_error_ = "USB head serial read requires positive timeout and at most 65536 bytes";
|
||||
return false;
|
||||
}
|
||||
const auto deadline = Clock::now() + std::min(timeout, io_timeout_);
|
||||
out_buffer.reserve(min_size);
|
||||
std::array<std::uint8_t, 256> bytes{};
|
||||
while (out_buffer.size() < min_size) {
|
||||
if (!waitReady(POLLIN, deadline)) return false;
|
||||
const auto count = ::read(fd_, bytes.data(), bytes.size());
|
||||
if (count > 0) {
|
||||
out_buffer.insert(out_buffer.end(), bytes.begin(), bytes.begin() + count);
|
||||
continue;
|
||||
}
|
||||
if (count < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) continue;
|
||||
if (count == 0) last_error_ = "USB head serial peer closed or read made no progress";
|
||||
else setSystemError("USB head serial read failed", errno);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string UsbHeadSerialTransport::lastError() const
|
||||
{
|
||||
std::lock_guard lock(io_mutex_);
|
||||
return last_error_;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -1,120 +0,0 @@
|
||||
"""Regenerate fixed C++ vectors with the source NXP eRPC Python SDK oracle.
|
||||
|
||||
Usage: python generate_erpc_vectors.py --sdk-dir /path/to/runtime_deps
|
||||
The C++ test consumes the checked-in output; Python/serial are not runtime deps.
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--sdk-dir", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path,
|
||||
default=Path(__file__).with_name("usb_head_erpc_vectors.h"))
|
||||
args = parser.parse_args()
|
||||
sys.path.insert(0, str(args.sdk_dir))
|
||||
|
||||
from erpc.basic_codec import BasicCodec
|
||||
from erpc.codec import MessageInfo, MessageType
|
||||
from erpc.transport import FramedTransport
|
||||
|
||||
|
||||
class OracleTransport(FramedTransport):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.packet = b""
|
||||
|
||||
def _base_send(self, packet):
|
||||
self.packet = bytes(packet)
|
||||
|
||||
|
||||
def frame(body):
|
||||
transport = OracleTransport()
|
||||
transport.send(body)
|
||||
return transport.packet.hex()
|
||||
|
||||
|
||||
def message(method, sequence, values, *, reply=False):
|
||||
codec = BasicCodec()
|
||||
codec.start_write_message(MessageInfo(
|
||||
MessageType.kReplyMessage if reply else MessageType.kInvocationMessage,
|
||||
1, method, sequence))
|
||||
for kind, value in values:
|
||||
if kind == "targets":
|
||||
codec.start_write_list(len(value))
|
||||
for name, angle in value:
|
||||
codec.write_string(name)
|
||||
codec.write_float(angle)
|
||||
elif kind == "angles":
|
||||
codec.start_write_list(len(value))
|
||||
for angle in value:
|
||||
codec.write_float(angle)
|
||||
else:
|
||||
getattr(codec, "write_" + kind)(value)
|
||||
return bytes(codec.buffer)
|
||||
|
||||
|
||||
cases = [
|
||||
(1, [("string", "eye_l_h"), ("float", 2.5), ("float", 20), ("float", 80)], True),
|
||||
(2, [("string", "eye_l_h"), ("float", 3.5)], True),
|
||||
(3, [("int32", 2)], True),
|
||||
(4, [("uint32", 17)], True),
|
||||
(5, [("targets", [("eye_l_h", 0.1), ("pwm8_local", -0.8)])], 0),
|
||||
(6, [("angles", [0.1, -0.2, 0.3, -0.4, -0.8])], 0),
|
||||
(5, [("targets", [])], -22),
|
||||
]
|
||||
|
||||
|
||||
def pair(method, sequence, values, result):
|
||||
request = frame(message(method, sequence, values))
|
||||
reply = frame(message(method, sequence,
|
||||
[("bool" if method < 5 else "int32", result)], reply=True))
|
||||
return request, reply
|
||||
|
||||
|
||||
lines = [
|
||||
"// Generated by generate_erpc_vectors.py with the NXP eRPC Python SDK.",
|
||||
"// Fixed wire vectors, independent of the C++ implementation under test.",
|
||||
"#ifndef CMVR_ES_USB_HEAD_ERPC_VECTORS_H",
|
||||
"#define CMVR_ES_USB_HEAD_ERPC_VECTORS_H",
|
||||
"namespace cmvr::device::test {",
|
||||
"struct RpcVector { const char* request; const char* reply; };",
|
||||
"inline constexpr RpcVector kCalls[] = {",
|
||||
]
|
||||
for sequence, (method, values, result) in enumerate(cases, 1):
|
||||
request, reply = pair(method, sequence, values, result)
|
||||
lines.append(f' {{"{request}", "{reply}"}},')
|
||||
lines.append("};")
|
||||
|
||||
mode_request, mode_reply = pair(3, 1, [("int32", 2)], True)
|
||||
lines.append(f'inline constexpr RpcVector kMode = {{"{mode_request}", "{mode_reply}"}};')
|
||||
false_request, false_reply = pair(3, 1, [("int32", 2)], False)
|
||||
lines.append(f'inline constexpr RpcVector kRejected = {{"{false_request}", "{false_reply}"}};')
|
||||
lines.append("inline constexpr RpcVector kBadReplies[] = {")
|
||||
reply_body = message(3, 1, [("bool", True)], reply=True)
|
||||
for field, offset in [("type", 0), ("method", 1), ("service", 2), ("version", 3),
|
||||
("sequence", 4), ("boolean", 8)]:
|
||||
body = bytearray(reply_body)
|
||||
body[offset] = 2 if field == "boolean" else body[offset] ^ 1
|
||||
lines.append(f' {{"{mode_request}", "{frame(body)}"}}, // {field}')
|
||||
lines.append(f' {{"{mode_request}", "{frame(reply_body + bytes([0]))}"}}, // length')
|
||||
for field, index in [("header CRC", 0), ("body CRC", -1)]:
|
||||
packet = bytearray.fromhex(mode_reply)
|
||||
packet[index] ^= 1
|
||||
lines.append(f' {{"{mode_request}", "{packet.hex()}"}}, // {field}')
|
||||
lines.append(f' {{"{mode_request}", "{mode_reply[:6]}"}}, // truncated header')
|
||||
lines.append(f' {{"{mode_request}", "{mode_reply[:-2]}"}}, // truncated body')
|
||||
lines.append("};")
|
||||
|
||||
lines.append("inline constexpr RpcVector kWrap[] = {")
|
||||
for sequence in [0xFFFFFFFF, 1]:
|
||||
request, reply = pair(3, sequence, [("int32", 2)], True)
|
||||
lines.append(f' {{"{request}", "{reply}"}},')
|
||||
lines.append("};")
|
||||
lines.append("inline constexpr RpcVector kConcurrent[] = {")
|
||||
for sequence in range(1, 41):
|
||||
request, reply = pair(3, sequence, [("int32", 2)], True)
|
||||
lines.append(f' {{"{request}", "{reply}"}},')
|
||||
lines += ["};", "} // namespace cmvr::device::test", "#endif", ""]
|
||||
args.output.write_text("\n".join(lines), encoding="utf-8")
|
||||
print(f"Wrote independent NXP SDK vectors: {args.output}")
|
||||
@ -1,544 +0,0 @@
|
||||
#include "../include/usb_biohead.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <future>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace {
|
||||
|
||||
using cmvr::device::HeadCommandOutcome;
|
||||
using cmvr::device::UsbBioHead;
|
||||
|
||||
void append16(std::vector<uint8_t>& bytes, uint16_t value)
|
||||
{
|
||||
bytes.push_back(static_cast<uint8_t>(value));
|
||||
bytes.push_back(static_cast<uint8_t>(value >> 8));
|
||||
}
|
||||
|
||||
void append32(std::vector<uint8_t>& bytes, uint32_t value)
|
||||
{
|
||||
for (unsigned shift = 0; shift < 32; shift += 8) bytes.push_back(value >> shift);
|
||||
}
|
||||
|
||||
uint32_t read32(const std::vector<uint8_t>& bytes, size_t at)
|
||||
{
|
||||
uint32_t value = 0;
|
||||
for (size_t index = 0; index < 4; ++index) value |= uint32_t(bytes.at(at + index)) << (8 * index);
|
||||
return value;
|
||||
}
|
||||
|
||||
uint16_t crc(const std::vector<uint8_t>& bytes)
|
||||
{
|
||||
uint16_t value = 0xEF4A;
|
||||
for (auto byte : bytes) {
|
||||
value ^= uint16_t(byte) << 8;
|
||||
for (int bit = 0; bit < 8; ++bit) {
|
||||
value = static_cast<uint16_t>((value & 0x8000) ? (value << 1) ^ 0x1021 : value << 1);
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Firmware stand-in for backend behavior tests. Protocol byte correctness is
|
||||
// independently checked against Python-generated vectors in the protocol tests.
|
||||
class ReplyTransport final : public cmvr::AbstractSerialTransport {
|
||||
public:
|
||||
bool open(const Config&) override { ++open_attempts; opened = !fail_open; return opened; }
|
||||
bool close() override { opened = false; return true; }
|
||||
bool isOpen() const override { return opened; }
|
||||
bool flushInput() override { pending.clear(); return true; }
|
||||
std::string lastError() const override { return "injected read failure"; }
|
||||
|
||||
bool write(const std::vector<uint8_t>& request) override
|
||||
{
|
||||
writes.push_back(request);
|
||||
writes_seen.store(writes.size());
|
||||
std::vector<uint8_t> body(request.begin() + 6, request.begin() + 14);
|
||||
body[0] = 2;
|
||||
const auto method = request.at(7);
|
||||
if (method == 5 || method == 6) {
|
||||
const auto result = read32(request, 14) == 0 ? -22 : move_result;
|
||||
append32(body, static_cast<uint32_t>(result));
|
||||
} else {
|
||||
body.push_back(boolean_result ? 1 : 0);
|
||||
}
|
||||
const auto length = static_cast<uint16_t>(body.size());
|
||||
const auto checksum = crc(body);
|
||||
std::vector<uint8_t> length_bytes, checksum_bytes;
|
||||
append16(length_bytes, length);
|
||||
append16(checksum_bytes, checksum);
|
||||
pending.clear();
|
||||
append16(pending, static_cast<uint16_t>(crc(length_bytes) + crc(checksum_bytes)));
|
||||
append16(pending, length);
|
||||
append16(pending, checksum);
|
||||
pending.insert(pending.end(), body.begin(), body.end());
|
||||
if ((method == 5 || method == 6) && read32(request, 14) != 0) {
|
||||
if (on_move) on_move();
|
||||
if (move_delay.count()) std::this_thread::sleep_for(move_delay);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read(size_t minimum, std::chrono::milliseconds, std::vector<uint8_t>& output) override
|
||||
{
|
||||
if (fail_read || pending.empty()) return false;
|
||||
const auto count = std::min(minimum, pending.size());
|
||||
output.assign(pending.begin(), pending.begin() + count);
|
||||
pending.erase(pending.begin(), pending.begin() + count);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool opened{false};
|
||||
bool fail_open{false};
|
||||
size_t open_attempts{0};
|
||||
bool boolean_result{true};
|
||||
bool fail_read{false};
|
||||
int32_t move_result{0};
|
||||
std::function<void()> on_move;
|
||||
std::chrono::milliseconds move_delay{0};
|
||||
std::atomic<size_t> writes_seen{0};
|
||||
std::vector<std::vector<uint8_t>> writes;
|
||||
std::vector<uint8_t> pending;
|
||||
};
|
||||
|
||||
cmvr::config::BioHeadRobotConfig configuration()
|
||||
{
|
||||
cmvr::config::BioHeadRobotConfig config;
|
||||
config.set_id("usb_head");
|
||||
config.set_serial_port("offline_fake");
|
||||
auto* first = config.mutable_usb_erpc()->add_joints();
|
||||
first->set_id("eye_l_lower");
|
||||
first->set_min_position_rad(-0.35);
|
||||
first->set_max_position_rad(0.55);
|
||||
first->set_home_position_rad(0);
|
||||
auto* second = config.mutable_usb_erpc()->add_joints();
|
||||
second->set_id("pwm8_local");
|
||||
second->set_min_position_rad(-1.5);
|
||||
second->set_max_position_rad(0.393);
|
||||
second->set_home_position_rad(-1);
|
||||
for (const auto& joint : std::vector<cmvr::device::HeadJointInfo>{
|
||||
{"eye_l_up", -1, 1, 0}, {"eye_l_v", -1.5, 1, 0}, {"eye_l_h", -0.65, 0.70, 0}}) {
|
||||
auto* next = config.mutable_usb_erpc()->add_joints();
|
||||
next->set_id(joint.id);
|
||||
next->set_min_position_rad(joint.min_position_rad);
|
||||
next->set_max_position_rad(joint.max_position_rad);
|
||||
next->set_home_position_rad(joint.home_position_rad);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
float firstWirePosition(const std::vector<uint8_t>& request)
|
||||
{
|
||||
const auto name_size = read32(request, 18);
|
||||
const auto bits = read32(request, 22 + name_size);
|
||||
float value;
|
||||
std::memcpy(&value, &bits, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
std::vector<cmvr::device::HeadJointTarget> wireTargets(const std::vector<uint8_t>& request)
|
||||
{
|
||||
std::vector<cmvr::device::HeadJointTarget> result;
|
||||
size_t cursor = 18;
|
||||
for (size_t index = 0; index < read32(request, 14); ++index) {
|
||||
const auto size = read32(request, cursor);
|
||||
cursor += 4;
|
||||
const std::string id(request.begin() + cursor, request.begin() + cursor + size);
|
||||
cursor += size;
|
||||
const auto bits = read32(request, cursor);
|
||||
cursor += 4;
|
||||
float position;
|
||||
std::memcpy(&position, &bits, sizeof(position));
|
||||
result.push_back({id, position});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<size_t> movementWrites(const ReplyTransport& wire, size_t first = 0)
|
||||
{
|
||||
std::vector<size_t> result;
|
||||
for (size_t index = first; index < wire.writes.size(); ++index) {
|
||||
if (wire.writes[index][7] == 5 && read32(wire.writes[index], 14) > 0) result.push_back(index);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, InitProbesWithoutSendingTargetsOrHome)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
EXPECT_TRUE(wire->writes.empty());
|
||||
ASSERT_TRUE(head.init());
|
||||
ASSERT_EQ(wire->writes.size(), 1);
|
||||
EXPECT_EQ(wire->writes[0][7], 5);
|
||||
EXPECT_EQ(read32(wire->writes[0], 14), 0);
|
||||
auto state = head.jointState();
|
||||
EXPECT_TRUE(state.connected);
|
||||
EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::None);
|
||||
EXPECT_FALSE(state.joints[0].target_valid);
|
||||
EXPECT_FALSE(state.joints[1].target_valid);
|
||||
EXPECT_FALSE(state.expression_baseline_ready);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, RejectsEntireInvalidBatchBeforeAnyWrite)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
const auto count = wire->writes.size();
|
||||
EXPECT_THROW(head.moveJoints({{"eye_l_lower", 0.2}, {"pwm8_local", 0.5}}), std::invalid_argument);
|
||||
EXPECT_THROW(head.moveJoints({{"eye_l_lower", 0.2}, {"eye_l_lower", 0.3}}), std::invalid_argument);
|
||||
EXPECT_THROW(head.moveJoints({{"missing", 0.2}}), std::invalid_argument);
|
||||
EXPECT_THROW(head.moveJoints({{"eye_l_lower", std::numeric_limits<double>::quiet_NaN()}}), std::invalid_argument);
|
||||
EXPECT_THROW(head.moveJoints({{"eye_l_lower", 1e-100}}), std::invalid_argument);
|
||||
EXPECT_EQ(wire->writes.size(), count);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, QuantizesBoundariesInwardAndCachesOnlyAcknowledgedTargets)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.moveJoints({{"eye_l_lower", 0.55}});
|
||||
const float encoded = firstWirePosition(wire->writes.back());
|
||||
EXPECT_LE(encoded, 0.55);
|
||||
EXPECT_GE(encoded, -0.35);
|
||||
EXPECT_EQ(encoded, std::nextafter(0.55f, -std::numeric_limits<float>::infinity()));
|
||||
auto state = head.jointState();
|
||||
EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Acknowledged);
|
||||
ASSERT_TRUE(state.joints[0].target_valid);
|
||||
EXPECT_DOUBLE_EQ(state.joints[0].target_position_rad, encoded);
|
||||
EXPECT_FALSE(state.joints[1].target_valid);
|
||||
head.home();
|
||||
state = head.jointState();
|
||||
EXPECT_DOUBLE_EQ(state.joints[0].target_position_rad, 0);
|
||||
EXPECT_DOUBLE_EQ(state.joints[1].target_position_rad, -1);
|
||||
EXPECT_TRUE(state.expression_baseline_ready);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, FirmwareRejectionMayPartiallyExecuteAndInvalidatesCachedTargets)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.moveJoints({{"eye_l_lower", 0.2}});
|
||||
wire->move_result = -88;
|
||||
EXPECT_THROW(head.moveJoints({{"eye_l_lower", 0.3}}), std::runtime_error);
|
||||
const auto state = head.jointState();
|
||||
EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Rejected);
|
||||
EXPECT_FALSE(state.joints[0].target_valid);
|
||||
EXPECT_NE(state.last_error.find("partial execution"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, UnknownReplyDisconnectsWithoutRetryOrTargetSuccess)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.moveJoints({{"eye_l_lower", 0.2}});
|
||||
wire->fail_read = true;
|
||||
const auto count = wire->writes.size();
|
||||
EXPECT_THROW(head.moveJoints({{"eye_l_lower", 0.3}}), std::runtime_error);
|
||||
EXPECT_EQ(wire->writes.size(), count + 1);
|
||||
const auto state = head.jointState();
|
||||
EXPECT_FALSE(state.connected);
|
||||
EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Unknown);
|
||||
EXPECT_FALSE(state.joints[0].target_valid);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, StopDoesNotClaimHardwareStoppedAndLegacyCommandsAreUnsupported)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
const auto count = wire->writes.size();
|
||||
EXPECT_THROW(head.eStop(), std::runtime_error);
|
||||
EXPECT_THROW(head.speakstart(), std::runtime_error);
|
||||
EXPECT_FALSE(head.stop());
|
||||
EXPECT_FALSE(head.jointState().connected);
|
||||
EXPECT_EQ(wire->writes.size(), count);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, RejectsInvalidSettingsBeforeTransportWrite)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
const auto count = wire->writes.size();
|
||||
EXPECT_THROW(head.setMotionConstraints("eye_l_lower", 0, 2, 3), std::invalid_argument);
|
||||
EXPECT_THROW(head.setPositionGain("eye_l_lower", -1), std::invalid_argument);
|
||||
EXPECT_THROW(head.setUpdatePeriodMs(101), std::invalid_argument);
|
||||
EXPECT_EQ(wire->writes.size(), count);
|
||||
EXPECT_NO_THROW(head.setPositionGain("eye_l_lower", 0));
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, FrozenPresetsPreserveSixIdsNamesAndOriginalDoubleValues)
|
||||
{
|
||||
UsbBioHead head(configuration(), std::make_unique<ReplyTransport>());
|
||||
const auto& presets = head.expressions();
|
||||
const char* ids[]{"0de8a527543e423abab593484926dd1c", "ad8f669a78d54d30a2356512b0802c1d",
|
||||
"516bc0f0e76647109411cbf92e5c86fc", "5e68f9b26f4d4f8580dead7777c6501b",
|
||||
"44821d9fa6df4fc78558666db32656e1", "8f97ed10b5b44012b004183ba61c839c"};
|
||||
const char* names[]{u8"中立", u8"微笑", u8"疲倦", u8"惊讶", u8"生气", u8"当前姿态"};
|
||||
const char* joints[]{"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"};
|
||||
const double expected[][5]{
|
||||
{0, 0, 0, 0, -1},
|
||||
{0.2329999953508377, -0.00041940261144191027, -0.00041940261144191027,
|
||||
-0.00041940261144191027, -1.121000051498413},
|
||||
{-0.991, 0.322, -1.015, 0.004, -0.537},
|
||||
{-1, -0.0004194026121000505, 0.999890384765, -0.0004194026121000505, -0.0004194026121000505},
|
||||
{-1, 0.5497252979258, 0.999890384765, 0.6999468312800001, -1.400129282005},
|
||||
{-0.0004194026121000505, -0.0004194026121000505, -0.0004194026121000505, -0.65, -1}
|
||||
};
|
||||
ASSERT_EQ(presets.size(), 6);
|
||||
for (size_t pose = 0; pose < 6; ++pose) {
|
||||
EXPECT_EQ(presets[pose].id, ids[pose]);
|
||||
EXPECT_EQ(presets[pose].name, names[pose]);
|
||||
ASSERT_EQ(presets[pose].targets.size(), 5);
|
||||
for (size_t joint = 0; joint < 5; ++joint) {
|
||||
EXPECT_EQ(presets[pose].targets[joint].id, joints[joint]);
|
||||
EXPECT_EQ(presets[pose].targets[joint].position_rad, expected[pose][joint]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, ExpressionRequiresAllFiveImmediateTargetsInCurrentConnection)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
const auto before = wire->writes.size();
|
||||
EXPECT_THROW(head.playExpression(u8"疲倦", true, .2, {}), std::runtime_error);
|
||||
EXPECT_EQ(wire->writes.size(), before);
|
||||
head.home();
|
||||
EXPECT_TRUE(head.jointState().expression_baseline_ready);
|
||||
head.setMotionMode(cmvr::device::HeadMotionMode::SCurve);
|
||||
EXPECT_FALSE(head.jointState().expression_baseline_ready);
|
||||
head.setMotionMode(cmvr::device::HeadMotionMode::Immediate);
|
||||
EXPECT_FALSE(head.jointState().expression_baseline_ready);
|
||||
const auto current = wire->writes.size();
|
||||
EXPECT_THROW(head.playExpression(u8"疲倦", true, .2, {}), std::runtime_error);
|
||||
EXPECT_EQ(wire->writes.size(), current);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, MinimumJerkExpressionUsesCompleteFramesAndAcknowledgedFinalTarget)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.home();
|
||||
const auto before = wire->writes.size();
|
||||
const auto pose = head.playExpression(u8"疲倦", true, .2, {});
|
||||
EXPECT_EQ(pose.id, "516bc0f0e76647109411cbf92e5c86fc");
|
||||
ASSERT_GE(wire->writes.size(), before + 3);
|
||||
EXPECT_EQ(wire->writes[before][7], 3);
|
||||
EXPECT_EQ(read32(wire->writes[before], 14), 0);
|
||||
EXPECT_EQ(wire->writes[before + 1][7], 4);
|
||||
EXPECT_EQ(read32(wire->writes[before + 1], 14), 20);
|
||||
const auto frames = movementWrites(*wire, before);
|
||||
ASSERT_FALSE(frames.empty());
|
||||
EXPECT_LE(frames.size(), 10);
|
||||
for (const auto index : frames) {
|
||||
const auto positions = wireTargets(wire->writes[index]);
|
||||
ASSERT_EQ(positions.size(), 5);
|
||||
// Each emitted frame is one of the prevalidated quintic samples;
|
||||
// host scheduling is allowed to skip samples, never replay them.
|
||||
const double up = positions[0].position_rad;
|
||||
bool is_planned = false;
|
||||
for (int frame = 1; frame <= 10; ++frame) {
|
||||
const double u = frame / 10.0;
|
||||
const double blend = u * u * u * (10 + u * (-15 + 6 * u));
|
||||
const float target = static_cast<float>(-0.991);
|
||||
const float expected = frame == 10 ? target : static_cast<float>(target * blend);
|
||||
if (up == expected) is_planned = true;
|
||||
}
|
||||
EXPECT_TRUE(is_planned);
|
||||
}
|
||||
const auto final = wireTargets(wire->writes[frames.back()]);
|
||||
EXPECT_DOUBLE_EQ(final[0].position_rad, static_cast<float>(-0.991));
|
||||
EXPECT_DOUBLE_EQ(final[4].position_rad, static_cast<float>(-0.537));
|
||||
const auto state = head.jointState();
|
||||
EXPECT_TRUE(state.expression_baseline_ready);
|
||||
EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Acknowledged);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, InvalidDurationOrIncompleteExpressionDoesNotWrite)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.home();
|
||||
const auto before = wire->writes.size();
|
||||
EXPECT_THROW(head.setExpression({{"eye_l_up", .1}}, .2, {}), std::invalid_argument);
|
||||
EXPECT_THROW(head.playExpression(u8"微笑", true, .19, {}), std::invalid_argument);
|
||||
EXPECT_THROW(head.playExpression(u8"微笑", true, 5.01, {}), std::invalid_argument);
|
||||
EXPECT_THROW(head.playExpression(u8"微笑", true, std::numeric_limits<double>::quiet_NaN(), {}), std::invalid_argument);
|
||||
EXPECT_THROW(head.playExpression("missing", false, .2, {}), std::invalid_argument);
|
||||
EXPECT_EQ(wire->writes.size(), before);
|
||||
EXPECT_TRUE(head.jointState().expression_baseline_ready);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, SlowAcknowledgementsSkipExpiredFramesButStillSendExactFinalFrame)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.home();
|
||||
const auto before = wire->writes.size();
|
||||
wire->move_delay = std::chrono::milliseconds(60);
|
||||
head.playExpression(u8"疲倦", true, .2, {});
|
||||
const auto frames = movementWrites(*wire, before);
|
||||
ASSERT_FALSE(frames.empty());
|
||||
EXPECT_LT(frames.size(), 10);
|
||||
const auto final = wireTargets(wire->writes[frames.back()]);
|
||||
EXPECT_DOUBLE_EQ(final[0].position_rad, static_cast<float>(-0.991));
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, CancellationStopsFutureFramesAndConcurrentControlIsBusy)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.home();
|
||||
std::mutex mutex;
|
||||
std::condition_variable condition;
|
||||
bool entered = false, release = false;
|
||||
std::atomic<int> calls{0};
|
||||
wire->on_move = [&] {
|
||||
++calls;
|
||||
std::unique_lock lock(mutex);
|
||||
entered = true;
|
||||
condition.notify_all();
|
||||
condition.wait_for(lock, std::chrono::seconds(2), [&] { return release; });
|
||||
};
|
||||
const auto before = wire->writes.size();
|
||||
auto work = std::async(std::launch::async, [&] { head.playExpression(u8"疲倦", true, .5, {}); });
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
ASSERT_TRUE(condition.wait_for(lock, std::chrono::seconds(2), [&] { return entered; }));
|
||||
}
|
||||
const auto writes = wire->writes_seen.load();
|
||||
EXPECT_THROW(head.moveJoints({{"eye_l_up", .1}}), std::runtime_error);
|
||||
EXPECT_EQ(wire->writes_seen.load(), writes);
|
||||
head.cancelExpression();
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
release = true;
|
||||
}
|
||||
condition.notify_all();
|
||||
EXPECT_THROW(work.get(), std::runtime_error);
|
||||
EXPECT_EQ(calls.load(), 1);
|
||||
EXPECT_EQ(movementWrites(*wire, before).size(), 1);
|
||||
EXPECT_FALSE(head.jointState().expression_baseline_ready);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, DeadlineCancellationAndReconnectNeverSendHomeAutomatically)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.home();
|
||||
auto before = wire->writes.size();
|
||||
EXPECT_THROW(head.playExpression(u8"微笑", true, .2, [] { return true; }), std::runtime_error);
|
||||
EXPECT_EQ(wire->writes.size(), before);
|
||||
EXPECT_FALSE(head.jointState().expression_baseline_ready);
|
||||
before = wire->writes.size();
|
||||
head.reconnect();
|
||||
ASSERT_EQ(wire->writes.size(), before + 1);
|
||||
EXPECT_EQ(read32(wire->writes.back(), 14), 0);
|
||||
EXPECT_TRUE(head.jointState().connected);
|
||||
EXPECT_FALSE(head.jointState().expression_baseline_ready);
|
||||
EXPECT_THROW(head.playExpression(u8"微笑", true, .2, {}), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, HomeCancellationAfterSettingsDoesNotSendPositionTargets)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
const auto before = wire->writes.size();
|
||||
// Expire once setMode and setUpdatePeriodMs have both been acknowledged.
|
||||
EXPECT_THROW(head.home([&] { return wire->writes.size() >= before + 2; }), std::runtime_error);
|
||||
EXPECT_EQ(wire->writes.size(), before + 2);
|
||||
EXPECT_TRUE(movementWrites(*wire, before).empty());
|
||||
EXPECT_FALSE(head.jointState().expression_baseline_ready);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, OfflineInitRemainsRegisteredAndOnlyExplicitReconnectAttemptsRecovery)
|
||||
{
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
wire->fail_open = true;
|
||||
UsbBioHead head(configuration(), std::move(transport));
|
||||
EXPECT_TRUE(head.init()); // Object/configuration initialized; hardware is offline.
|
||||
EXPECT_EQ(wire->open_attempts, 1);
|
||||
EXPECT_TRUE(wire->writes.empty());
|
||||
auto state = head.jointState();
|
||||
EXPECT_FALSE(state.connected);
|
||||
EXPECT_FALSE(state.expression_baseline_ready);
|
||||
EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Unknown);
|
||||
EXPECT_FALSE(state.last_error.empty());
|
||||
EXPECT_EQ(head.expressions().size(), 6);
|
||||
EXPECT_THROW(head.moveJoints({{"eye_l_up", .1}}), std::runtime_error);
|
||||
wire->fail_open = false;
|
||||
EXPECT_TRUE(head.start());
|
||||
EXPECT_EQ(wire->open_attempts, 1); // start() must not silently reconnect.
|
||||
EXPECT_TRUE(wire->writes.empty());
|
||||
head.reconnect();
|
||||
EXPECT_EQ(wire->open_attempts, 2);
|
||||
ASSERT_EQ(wire->writes.size(), 1);
|
||||
EXPECT_EQ(wire->writes[0][7], 5);
|
||||
EXPECT_EQ(read32(wire->writes[0], 14), 0); // Only a no-target service probe.
|
||||
state = head.jointState();
|
||||
EXPECT_TRUE(state.connected);
|
||||
EXPECT_FALSE(state.expression_baseline_ready);
|
||||
EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::None);
|
||||
for (const auto& joint : state.joints) EXPECT_FALSE(joint.target_valid);
|
||||
}
|
||||
|
||||
TEST(UsbBioHead, HomeSupportsConfiguredSubsetWithoutClaimingFiveJointBaseline)
|
||||
{
|
||||
auto config = configuration();
|
||||
config.mutable_usb_erpc()->mutable_joints()->DeleteSubrange(2, 3);
|
||||
auto transport = std::make_unique<ReplyTransport>();
|
||||
auto* wire = transport.get();
|
||||
UsbBioHead head(config, std::move(transport));
|
||||
ASSERT_TRUE(head.init());
|
||||
head.home();
|
||||
const auto movements = movementWrites(*wire);
|
||||
ASSERT_EQ(movements.size(), 1);
|
||||
const auto targets = wireTargets(wire->writes[movements.front()]);
|
||||
ASSERT_EQ(targets.size(), 2);
|
||||
EXPECT_EQ(targets[0].id, "eye_l_lower");
|
||||
EXPECT_EQ(targets[1].id, "pwm8_local");
|
||||
EXPECT_FALSE(head.jointState().expression_baseline_ready);
|
||||
const auto writes = wire->writes.size();
|
||||
EXPECT_THROW(head.setExpression(targets, 0.2, {}), std::invalid_argument);
|
||||
EXPECT_EQ(wire->writes.size(), writes);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@ -1,253 +0,0 @@
|
||||
#include "../include/usb_head_erpc_client.h"
|
||||
#include "usb_head_erpc_vectors.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
|
||||
using cmvr::device::UsbHeadErpcClient;
|
||||
using cmvr::device::test::RpcVector;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
void require(bool condition, const char* message)
|
||||
{
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> unhex(const char* text)
|
||||
{
|
||||
std::vector<std::uint8_t> result;
|
||||
const std::string value(text);
|
||||
require(value.size() % 2 == 0, "Invalid test vector");
|
||||
for (std::size_t index = 0; index < value.size(); index += 2) {
|
||||
result.push_back(static_cast<std::uint8_t>(std::stoul(value.substr(index, 2), nullptr, 16)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
class ScriptedTransport final : public cmvr::AbstractSerialTransport {
|
||||
public:
|
||||
ScriptedTransport(const RpcVector* entries, std::size_t size)
|
||||
: entries_(entries), size_(size) { }
|
||||
|
||||
bool open(const Config& config) override
|
||||
{
|
||||
port_seen = config.port_name;
|
||||
baud_rate_seen = config.baud_rate;
|
||||
opened_ = !fail_open;
|
||||
return opened_;
|
||||
}
|
||||
bool close() override { opened_ = false; ++closes; return true; }
|
||||
bool isOpen() const override { return opened_; }
|
||||
bool flushInput() override { pending_.clear(); return !fail_flush; }
|
||||
std::string lastError() const override { return "injected transport fault"; }
|
||||
|
||||
bool write(const std::vector<std::uint8_t>& data) override
|
||||
{
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
require(opened_, "Write after close");
|
||||
require(pending_.empty(), "Concurrent requests interleaved");
|
||||
require(writes < size_, "Unexpected retry or extra request");
|
||||
require(data == unhex(entries_[writes].request), "Request disagrees with Python SDK oracle");
|
||||
pending_ = unhex(entries_[writes].reply);
|
||||
++writes;
|
||||
if (fail_write) return false;
|
||||
}
|
||||
// Forces a scheduling opportunity while a complete RPC is outstanding.
|
||||
if (schedule_delay) std::this_thread::sleep_for(1ms);
|
||||
if (write_delay.count()) std::this_thread::sleep_for(write_delay);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read(std::size_t, std::chrono::milliseconds,
|
||||
std::vector<std::uint8_t>& output) override
|
||||
{
|
||||
if (read_delay.count()) std::this_thread::sleep_for(read_delay);
|
||||
std::lock_guard lock(mutex_);
|
||||
++reads;
|
||||
if (fail_read || pending_.empty()) return false;
|
||||
const auto count = std::min(chunk_size, pending_.size());
|
||||
output.assign(pending_.begin(), pending_.begin() + count);
|
||||
pending_.erase(pending_.begin(), pending_.begin() + count);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::size_t writes{0};
|
||||
std::size_t reads{0};
|
||||
int closes{0};
|
||||
std::size_t chunk_size{2};
|
||||
std::chrono::milliseconds read_delay{0};
|
||||
std::chrono::milliseconds write_delay{0};
|
||||
std::string port_seen;
|
||||
int baud_rate_seen{0};
|
||||
bool fail_open{false};
|
||||
bool fail_flush{false};
|
||||
bool fail_write{false};
|
||||
bool fail_read{false};
|
||||
bool schedule_delay{false};
|
||||
|
||||
private:
|
||||
const RpcVector* entries_;
|
||||
std::size_t size_;
|
||||
std::vector<std::uint8_t> pending_;
|
||||
std::atomic<bool> opened_{false};
|
||||
std::mutex mutex_;
|
||||
};
|
||||
|
||||
void testGoldenMethodsAndFragmentedReads()
|
||||
{
|
||||
using namespace cmvr::device::test;
|
||||
auto wire = std::make_unique<ScriptedTransport>(kCalls, std::size(kCalls));
|
||||
auto* observed = wire.get();
|
||||
UsbHeadErpcClient client(std::move(wire), 2000ms, 0);
|
||||
client.open("fake");
|
||||
require(observed->writes == 0, "Opening must not send any target");
|
||||
require(observed->port_seen == "fake" && observed->baud_rate_seen == 115200,
|
||||
"Protocol must use the original serial transport Config");
|
||||
require(client.setConstraints("eye_l_h", 2.5f, 20.f, 80.f), "constraints");
|
||||
require(client.setPositionGain("eye_l_h", 3.5f), "gain");
|
||||
require(client.setMode(2), "mode");
|
||||
require(client.setUpdatePeriodMs(17), "period");
|
||||
require(client.move({{"eye_l_h", .1f}, {"pwm8_local", -.8f}}) == 0, "move");
|
||||
require(client.moveJ({.1f, -.2f, .3f, -.4f, -.8f}) == 0, "moveJ method ID must be 6");
|
||||
require(client.move({}) == -22, "signed no-target probe result");
|
||||
require(observed->writes == 7, "Expected exactly one frame per operation");
|
||||
require(client.isOpen(), "Known firmware result must not be misreported as transport failure");
|
||||
client.close();
|
||||
require(observed->closes == 1, "close");
|
||||
}
|
||||
|
||||
void testCoalescedReplyAndKnownRejection()
|
||||
{
|
||||
using namespace cmvr::device::test;
|
||||
for (const auto* entry : {&kMode, &kRejected}) {
|
||||
auto wire = std::make_unique<ScriptedTransport>(entry, 1);
|
||||
wire->chunk_size = 4096;
|
||||
UsbHeadErpcClient client(std::move(wire), 2000ms, 0);
|
||||
client.open("fake");
|
||||
require(client.setMode(2) == (entry == &kMode), "Preserve boolean ACK result");
|
||||
require(client.isOpen(), "Well-formed false ACK has a confirmed result");
|
||||
}
|
||||
}
|
||||
|
||||
void testCorruptionDisconnectsWithoutRetry()
|
||||
{
|
||||
using namespace cmvr::device::test;
|
||||
for (const auto& entry : kBadReplies) {
|
||||
auto wire = std::make_unique<ScriptedTransport>(&entry, 1);
|
||||
auto* observed = wire.get();
|
||||
UsbHeadErpcClient client(std::move(wire), 2000ms, 0);
|
||||
client.open("fake");
|
||||
bool failed = false;
|
||||
try { client.setMode(2); } catch (const std::runtime_error&) { failed = true; }
|
||||
require(failed, "Malformed frame was accepted");
|
||||
require(!client.isOpen(), "Malformed or incomplete frame must disconnect");
|
||||
require(observed->writes == 1, "Unconfirmed commands must not be retried");
|
||||
require(observed->closes == 1, "Failure must close port");
|
||||
}
|
||||
}
|
||||
|
||||
void testTransportFaultsAndWholeReplyDeadline()
|
||||
{
|
||||
using namespace cmvr::device::test;
|
||||
for (int fault = 0; fault < 4; ++fault) {
|
||||
auto wire = std::make_unique<ScriptedTransport>(&kMode, 1);
|
||||
auto* observed = wire.get();
|
||||
wire->fail_write = fault == 0;
|
||||
wire->fail_read = fault == 1;
|
||||
if (fault == 2) {
|
||||
wire->read_delay = 12ms;
|
||||
wire->chunk_size = 1;
|
||||
}
|
||||
if (fault == 3) wire->write_delay = 25ms;
|
||||
UsbHeadErpcClient client(std::move(wire), fault >= 2 ? 20ms : 2000ms, 0);
|
||||
client.open("fake");
|
||||
bool failed = false;
|
||||
try { client.setMode(2); } catch (const std::runtime_error&) { failed = true; }
|
||||
require(failed && !client.isOpen(), "Transport failure must disconnect");
|
||||
require(observed->writes == 1, "No automatic retry after write/read/deadline fault");
|
||||
if (fault == 2) require(observed->reads <= 2, "Deadline must not restart for each fragment");
|
||||
if (fault == 3) require(observed->reads == 0, "The RPC deadline must start before write");
|
||||
}
|
||||
}
|
||||
|
||||
void testValidationHasNoSideEffects()
|
||||
{
|
||||
using namespace cmvr::device::test;
|
||||
auto wire = std::make_unique<ScriptedTransport>(&kMode, 1);
|
||||
auto* observed = wire.get();
|
||||
UsbHeadErpcClient client(std::move(wire), 2000ms, 0);
|
||||
client.open("fake");
|
||||
auto invalid = [&](auto operation) {
|
||||
bool failed = false;
|
||||
try { operation(); } catch (const std::invalid_argument&) { failed = true; }
|
||||
require(failed, "Invalid input accepted");
|
||||
require(observed->writes == 0 && client.isOpen(), "Validation sent an RPC or closed connection");
|
||||
};
|
||||
invalid([&] { client.setMode(3); });
|
||||
invalid([&] { client.setUpdatePeriodMs(0); });
|
||||
invalid([&] { client.setConstraints("eye_l_h", 0, 1, 1); });
|
||||
invalid([&] { client.setPositionGain("eye_l_h", -1); });
|
||||
invalid([&] { client.move({{"eye_l_h", 0}, {"eye_l_h", 1}}); });
|
||||
invalid([&] { client.move({{"eye_l_h", std::numeric_limits<float>::quiet_NaN()}}); });
|
||||
invalid([&] { client.move({{std::string(65, 'x'), 0}}); });
|
||||
invalid([&] { client.moveJ(std::vector<float>(6)); });
|
||||
require(client.setMode(2), "Invalid requests must not consume sequence numbers");
|
||||
}
|
||||
|
||||
void testSequenceWrapAndConcurrentTransactions()
|
||||
{
|
||||
using namespace cmvr::device::test;
|
||||
{
|
||||
auto wire = std::make_unique<ScriptedTransport>(kWrap, std::size(kWrap));
|
||||
UsbHeadErpcClient client(std::move(wire), 2000ms, 0xFFFFFFFEu);
|
||||
client.open("fake");
|
||||
require(client.setMode(2) && client.setMode(2), "Sequence must wrap and skip zero");
|
||||
}
|
||||
auto wire = std::make_unique<ScriptedTransport>(kConcurrent, std::size(kConcurrent));
|
||||
auto* observed = wire.get();
|
||||
wire->schedule_delay = true;
|
||||
UsbHeadErpcClient client(std::move(wire), 2000ms, 0);
|
||||
client.open("fake");
|
||||
std::atomic<int> errors{0};
|
||||
auto worker = [&] {
|
||||
try {
|
||||
for (int count = 0; count < 20; ++count) {
|
||||
if (!client.setMode(2)) ++errors;
|
||||
}
|
||||
} catch (...) { ++errors; }
|
||||
};
|
||||
std::thread first(worker);
|
||||
std::thread second(worker);
|
||||
first.join();
|
||||
second.join();
|
||||
require(errors == 0 && observed->writes == 40, "Request/reply transaction interleaving");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
try {
|
||||
testGoldenMethodsAndFragmentedReads();
|
||||
testCoalescedReplyAndKnownRejection();
|
||||
testCorruptionDisconnectsWithoutRetry();
|
||||
testTransportFaultsAndWholeReplyDeadline();
|
||||
testValidationHasNoSideEffects();
|
||||
testSequenceWrapAndConcurrentTransactions();
|
||||
std::cout << "USB head eRPC offline tests passed\n";
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user