Compare commits
40 Commits
f088c5f2b9
...
55736f58ff
| Author | SHA1 | Date | |
|---|---|---|---|
| 55736f58ff | |||
| 877d4d6378 | |||
| f46f65fb53 | |||
| cdf8596c11 | |||
| e714f73601 | |||
| 70237a9559 | |||
| d6a1635b1b | |||
| bbcc716195 | |||
| 403c194f74 | |||
| 52f9fc376f | |||
| 2a5ef98649 | |||
| c2720956af | |||
| cf6b07c677 | |||
| 02d5141444 | |||
| 021ccfb085 | |||
| 250775970c | |||
| 89091dc435 | |||
| 392281fe06 | |||
| 52166f2402 | |||
| 048cea580d | |||
| de124daa8a | |||
| 2ecd74b044 | |||
| 3b14ca97e6 | |||
| 696d198801 | |||
| f89d5b383f | |||
| c571b476a1 | |||
| 10c1c891e1 | |||
| 4afa72729a | |||
| fa3f70a975 | |||
| dcf89b34d6 | |||
| b7e51afec4 | |||
| e5feff7a28 | |||
| 1360746edb | |||
| 45883d6ded | |||
| 8e2a8615dd | |||
| 69b06d80c6 | |||
| fbd67dab6a | |||
| 0103067c3a | |||
| 07fec735d5 | |||
| 8051206d91 |
@ -118,6 +118,7 @@ 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
|
||||
@ -158,7 +159,7 @@ sudo scripts/ethercat/start_ethercat.sh eno1
|
||||
$IGH_ETHERCAT_ROOT/etc/ethercat.conf
|
||||
```
|
||||
|
||||
脚本会把该网卡的 MAC 写到 `MASTER0_DEVICE`,使用 `DEVICE_MODULES="generic"`,把网卡从 NetworkManager 断开,并通过 `ethercatctl -c` 启动 IgH master。
|
||||
脚本会把该网卡的 MAC 写到 `MASTER0_DEVICE`,使用 `DEVICE_MODULES="igc"`,把网卡从 NetworkManager 断开,并通过 `ethercatctl -c` 启动 IgH master。
|
||||
|
||||
查看状态:
|
||||
|
||||
|
||||
@ -1,11 +1,10 @@
|
||||
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)
|
||||
|
||||
@ -10,6 +10,8 @@
|
||||
#include "environment/include/robot_model.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
using ::cmvr::JointLimit;
|
||||
using ::cmvr::RobotModel;
|
||||
|
||||
enum class ArmErrorCode {
|
||||
OK = 0,
|
||||
@ -102,12 +104,14 @@ 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);
|
||||
(effort.empty() || effort.size() == model.dof) &&
|
||||
(current.empty() || current.size() == model.dof);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@ -1,351 +1,63 @@
|
||||
# Joint-only minimal configuration; MoveJ follows joint_names order.
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "right_ethercat_arm"
|
||||
|
||||
motor {
|
||||
motor_system_id: "right_arm_ethercat_motors"
|
||||
motor_group_ids: "right_arm_ethercat_motors"
|
||||
motor_system_id: "dual_arm_ethercat_motors"
|
||||
motor_group_ids: "dual_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"
|
||||
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: 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
|
||||
control_point_spacing_rad: 0.1
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
id: "left_ethercat_arm"
|
||||
motor {
|
||||
motor_system_id: "dual_arm_ethercat_motors"
|
||||
motor_group_ids: "dual_arm_ethercat_motors"
|
||||
dof: 7
|
||||
joint_names: "left_arm_J1"
|
||||
joint_names: "left_arm_J2"
|
||||
joint_names: "left_arm_J3"
|
||||
joint_names: "left_arm_J4"
|
||||
joint_names: "left_arm_J5"
|
||||
joint_names: "left_arm_J6"
|
||||
joint_names: "left_arm_J7"
|
||||
upd_freq: 1000
|
||||
}
|
||||
motion {
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
160
cmvr-es/config/devices/arm/ethercat_single_arm.pb.txt
Normal file
160
cmvr-es/config/devices/arm/ethercat_single_arm.pb.txt
Normal file
@ -0,0 +1,160 @@
|
||||
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: "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: 1.0
|
||||
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: 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: "right_arm_J1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J2" q_lb: -1.64 q_ub: 1.64 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J4" q_lb: -1.60 q_ub: 1.60 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J6" q_lb: -0.37 q_ub: 0.79 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J7" q_lb: -0.61 q_ub: 0.58 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 {
|
||||
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
|
||||
toppra_joint_motion_planner {
|
||||
path_type: TOPPRA_PATH_TYPE_QUINTIC
|
||||
sample_period_s: 0.001
|
||||
grid_size: 150
|
||||
high_grid_size: 300
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
linear_reverse_cos_threshold: -0.8660254037844386
|
||||
linear_reverse_switch_speed_threshold: 1e-3
|
||||
enforce_joint_acceleration_limits: true
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
29
cmvr-es/config/devices/arm/lingkong_arm.pb.txt
Normal file
29
cmvr-es/config/devices/arm/lingkong_arm.pb.txt
Normal file
@ -0,0 +1,29 @@
|
||||
# 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
30
cmvr-es/config/devices/arm/lingkong_mixed_arm.pb.txt
Normal file
30
cmvr-es/config/devices/arm/lingkong_mixed_arm.pb.txt
Normal file
@ -0,0 +1,30 @@
|
||||
# Joint-only minimal configuration; MoveJ follows joint_names order.
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "lingkong_mixed_arm"
|
||||
motor {
|
||||
motor_system_id: "lingkong_mixed_motors"
|
||||
motor_group_ids: "lingkong_mixed_v236"
|
||||
motor_group_ids: "lingkong_mixed_v238"
|
||||
dof: 3
|
||||
joint_names: "LINGKONG_MIXED_AXIS_1"
|
||||
joint_names: "LINGKONG_MIXED_AXIS_2"
|
||||
joint_names: "LINGKONG_MIXED_AXIS_3"
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -6,13 +6,14 @@ arm {
|
||||
motor {
|
||||
motor_system_id: "tchl_joint_motors"
|
||||
motor_group_ids: "tchl_joint_motors"
|
||||
dof: 6
|
||||
dof: 7
|
||||
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"
|
||||
joint_names: "TCHL_AXIS_7"
|
||||
upd_freq: 1000
|
||||
}
|
||||
|
||||
@ -20,7 +21,7 @@ arm {
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
quintic_bspline {
|
||||
control_point_spacing_rad: 0.05
|
||||
control_point_spacing_rad: 0.1
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
63
cmvr-es/config/devices/arm/tchl_dual_arm.pb.txt
Normal file
63
cmvr-es/config/devices/arm/tchl_dual_arm.pb.txt
Normal file
@ -0,0 +1,63 @@
|
||||
# Joint-only minimal configuration; MoveJ follows joint_names order.
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "right_tchl_arm"
|
||||
motor {
|
||||
motor_system_id: "tchl_dual_arm_motors"
|
||||
motor_group_ids: "tchl_dual_arm_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
|
||||
}
|
||||
motion {
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
robot_arms {
|
||||
id: "left_tchl_arm"
|
||||
motor {
|
||||
motor_system_id: "tchl_dual_arm_motors"
|
||||
motor_group_ids: "tchl_dual_arm_motors"
|
||||
dof: 7
|
||||
joint_names: "left_arm_J1"
|
||||
joint_names: "left_arm_J2"
|
||||
joint_names: "left_arm_J3"
|
||||
joint_names: "left_arm_J4"
|
||||
joint_names: "left_arm_J5"
|
||||
joint_names: "left_arm_J6"
|
||||
joint_names: "left_arm_J7"
|
||||
upd_freq: 1000
|
||||
}
|
||||
motion {
|
||||
joint_trajectory_smoother {
|
||||
sample_period_s: 0.001
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -262,4 +262,26 @@ 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,6 +1,36 @@
|
||||
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 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: "can0"
|
||||
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
|
||||
@ -10,10 +40,45 @@ dexhand {
|
||||
|
||||
dexhands {
|
||||
id: "hand2"
|
||||
model: "RH56D"
|
||||
has_tactile_feedback: true
|
||||
rh56dftp {
|
||||
ip: "192.168.1.224"
|
||||
port: 6000
|
||||
poll_interval_ms: 10
|
||||
}
|
||||
}
|
||||
|
||||
dexhands {
|
||||
id: "paxini_tip_1"
|
||||
model: "PX-6AX Gen3"
|
||||
has_tactile_feedback: true
|
||||
px_6ax_gen3 {
|
||||
serial_port: "/dev/ttyACM1"
|
||||
sensor_model: "S1813_core"
|
||||
module_id: 2
|
||||
baud_rate: 921600
|
||||
distributed_length: 153
|
||||
resultant_length: 3
|
||||
poll_interval_ms: 5
|
||||
response_timeout_ms: 200
|
||||
# 触觉数据最大有效期;超过此时间报不可用,不继续返回旧力值。
|
||||
max_sample_age_ms: 50
|
||||
response_header_bytes: 14
|
||||
tactile_rows: 1
|
||||
tactile_cols: 51
|
||||
tactile_finger: "INDEX"
|
||||
tactile_region: "TIP"
|
||||
sensor_name: "Paxini Gen3末端压力"
|
||||
polling_read_mode: LEGACY_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=XFMDPV0018,DEV=0"
|
||||
input_device: "plughw:CARD=Newmine,DEV=0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
93
cmvr-es/config/devices/motor/dual_arm_ethercat_motors.pb.txt
Normal file
93
cmvr-es/config/devices/motor/dual_arm_ethercat_motors.pb.txt
Normal file
@ -0,0 +1,93 @@
|
||||
motor {
|
||||
id: "dual_arm_ethercat_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "dual_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: 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 }
|
||||
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 }
|
||||
}
|
||||
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "right_arm_J1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J2" q_lb: -1.64 q_ub: 1.64 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J4" q_lb: -1.60 q_ub: 1.60 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J6" q_lb: -0.37 q_ub: 0.79 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J7" q_lb: -0.61 q_ub: 0.58 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J2" q_lb: -1.64 q_ub: 1.64 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J4" q_lb: -1.60 q_ub: 1.60 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J6" q_lb: -0.37 q_ub: 0.79 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J7" q_lb: -0.61 q_ub: 0.58 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "right_arm_J1" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 2 joint_name: "right_arm_J2" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 3 joint_name: "right_arm_J3" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 4 joint_name: "right_arm_J4" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 5 joint_name: "right_arm_J5" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 6 joint_name: "right_arm_J6" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 7 joint_name: "right_arm_J7" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 8 joint_name: "left_arm_J1" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 9 joint_name: "left_arm_J2" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 10 joint_name: "left_arm_J3" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 11 joint_name: "left_arm_J4" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 12 joint_name: "left_arm_J5" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 13 joint_name: "left_arm_J6" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 14 joint_name: "left_arm_J7" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -51,7 +51,7 @@ motor {
|
||||
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_R" q_lb: -1.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 }
|
||||
|
||||
@ -0,0 +1,72 @@
|
||||
motor {
|
||||
id: "right_arm_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: "right_arm_J1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J2" q_lb: -1.64 q_ub: 1.64 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J4" q_lb: -1.60 q_ub: 1.60 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J6" q_lb: -0.37 q_ub: 0.79 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J7" q_lb: -0.61 q_ub: 0.58 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "right_arm_J1" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 2 joint_name: "right_arm_J2" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 3 joint_name: "right_arm_J3" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 4 joint_name: "right_arm_J4" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 5 joint_name: "right_arm_J5" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 6 joint_name: "right_arm_J6" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 7 joint_name: "right_arm_J7" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
62
cmvr-es/config/devices/motor/lingkong_mixed_motors.pb.txt
Normal file
62
cmvr-es/config/devices/motor/lingkong_mixed_motors.pb.txt
Normal file
@ -0,0 +1,62 @@
|
||||
# Alternative deployment: do not enable together with the original can3 IDs 1/2/3.
|
||||
# Both groups are loaded by the MotorConfig.id below, with unique motor IDs.
|
||||
motor {
|
||||
id: "lingkong_mixed_motors"
|
||||
motor_groups {
|
||||
id: "lingkong_mixed_v236"
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_LINGKONG
|
||||
protocol: MOTOR_PROTOCOL_LINGKONG_CAN
|
||||
can { channel_id: 3 }
|
||||
motors {
|
||||
motors {
|
||||
id: 1
|
||||
joint_name: "LINGKONG_MIXED_AXIS_1"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -3.14
|
||||
limit_q_ub: 3.14
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
response_timeout_ms: 100
|
||||
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: 3 }
|
||||
motors {
|
||||
motors {
|
||||
id: 2
|
||||
joint_name: "LINGKONG_MIXED_AXIS_2"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -3.14
|
||||
limit_q_ub: 3.14
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
response_timeout_ms: 100
|
||||
reached_position_tolerance_rad: 0.001
|
||||
# Iq conversion intentionally unspecified until confirmed for this motor.
|
||||
}
|
||||
}
|
||||
motors {
|
||||
id: 3
|
||||
joint_name: "LINGKONG_MIXED_AXIS_3"
|
||||
gear_ratio: 10
|
||||
limit_q_lb: -3.14
|
||||
limit_q_ub: 3.14
|
||||
limit_qd: 10
|
||||
lingkong {
|
||||
response_timeout_ms: 100
|
||||
reached_position_tolerance_rad: 0.001
|
||||
# Iq conversion intentionally unspecified until confirmed for this motor.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
57
cmvr-es/config/devices/motor/lingkong_motors.pb.txt
Normal file
57
cmvr-es/config/devices/motor/lingkong_motors.pb.txt
Normal file
@ -0,0 +1,57 @@
|
||||
# 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.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
95
cmvr-es/config/devices/motor/tchl_dual_arm_motors.pb.txt
Normal file
95
cmvr-es/config/devices/motor/tchl_dual_arm_motors.pb.txt
Normal file
@ -0,0 +1,95 @@
|
||||
motor {
|
||||
id: "tchl_dual_arm_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "tchl_dual_arm_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
|
||||
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
|
||||
}
|
||||
|
||||
# Junction position 0: Port 1 -> right arm J1-J7 (positions 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 }
|
||||
# Junction Port 2 -> left arm J1-J7 (positions 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 }
|
||||
}
|
||||
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "right_arm_J1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J2" q_lb: -1.96 q_ub: 2.02 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J4" q_lb: -2.04 q_ub: 1.10 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J6" q_lb: -3.14 q_ub: 0.21 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "right_arm_J7" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J2" q_lb: -2.02 q_ub: 1.96 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J4" q_lb: -1.10 q_ub: 2.04 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J6" q_lb: -0.21 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "left_arm_J7" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "right_arm_J1" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 2 joint_name: "right_arm_J2" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 3 joint_name: "right_arm_J3" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 4 joint_name: "right_arm_J4" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 5 joint_name: "right_arm_J5" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 6 joint_name: "right_arm_J6" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 7 joint_name: "right_arm_J7" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 8 joint_name: "left_arm_J1" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 9 joint_name: "left_arm_J2" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 10 joint_name: "left_arm_J3" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 11 joint_name: "left_arm_J4" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 12 joint_name: "left_arm_J5" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 13 joint_name: "left_arm_J6" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
motors { id: 14 joint_name: "left_arm_J7" encoder_counts_per_rev: 131072 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,5 @@
|
||||
# 同川 TC600E TR 单轴模板;未注册为活动设备。
|
||||
# prepareInit 会检查 PrD.00=0;关闭全闭环并保存后需给驱动器断电再上电。
|
||||
# 按非全闭环、电子齿轮 1:1 配置:电机端编码器每圈 131072 计数,减速比 101。
|
||||
# 当前按实机 PrD.00=0、电子齿轮1:1配置;减速比需读取实机3D06后填写。
|
||||
motor {
|
||||
id: "tchl_motors"
|
||||
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
# 同川 TC600E TR 六轴模板;设备管理器默认不启用。
|
||||
# 同川 TC600E TR 七轴模板;设备管理器默认不启用。
|
||||
# 各轴按实机确认 PrD.00、电子齿轮、编码器分辨率和减速比。
|
||||
# prepareInit 会统一检查 PrD.00=0,关闭全闭环并保存后,统一给驱动器断电再上电。
|
||||
# 按非全闭环、电子齿轮 1:1 配置:电机端编码器每圈 131072 计数,减速比按各轴实机填写。
|
||||
# 以下 131072 / 101 仅为 PrD.00=0、电子齿轮 1:1 的配置示例。
|
||||
motor {
|
||||
id: "tchl_motors"
|
||||
|
||||
@ -32,6 +31,7 @@ motor {
|
||||
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 }
|
||||
|
||||
}
|
||||
|
||||
@ -40,12 +40,13 @@ motor {
|
||||
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 }
|
||||
joints { joint_name: "TCHL_AXIS_1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_2" q_lb: -1.96 q_ub: 2.02 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_4" q_lb: -2.04 q_ub: 1.10 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_6" q_lb: -3.14 q_ub: 0.21 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "TCHL_AXIS_7" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
|
||||
}
|
||||
|
||||
@ -56,6 +57,7 @@ motor {
|
||||
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 }
|
||||
motors { id: 7 joint_name: "TCHL_AXIS_7" encoder_counts_per_rev: 131072 gear_ratio: 101 }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,49 +7,49 @@ device_manager {
|
||||
id: "mujoco_world"
|
||||
type: DEVICE_TYPE_MUJOCO_WORLD
|
||||
config_file: "devices/mujoco/xiaozhao_world.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_left_arm_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/xiaozhao_motors.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_right_arm_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/xiaozhao_motors.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_head_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/xiaozhao_motors.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_left_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/xiaozhao_arm.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_right_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/xiaozhao_arm.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "xiaozhao_head"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/xiaozhao_head.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
@ -70,21 +70,21 @@ device_manager {
|
||||
id: "mujoco_viewer"
|
||||
type: DEVICE_TYPE_MUJOCO_VIEWER
|
||||
config_file: "devices/mujoco/mujoco_viewer.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_hand_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/xiaozhao_camera.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_external_touch_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/xiaozhao_camera.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
@ -102,6 +102,20 @@ device_manager {
|
||||
}
|
||||
|
||||
|
||||
devices {
|
||||
id: "right_hand_ap001"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_hand_lites001"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "hand2"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
@ -120,7 +134,7 @@ device_manager {
|
||||
id: "mujoco_zero_touch"
|
||||
type: DEVICE_TYPE_TOUCH
|
||||
config_file: "devices/touch/touch.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
@ -154,7 +168,7 @@ device_manager {
|
||||
devices {
|
||||
id: "right_arm_ethercat_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/ethercat_motors.pb.txt"
|
||||
config_file: "devices/motor/ethercat_single_arm_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
@ -236,33 +250,57 @@ device_manager {
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "dual_arm_ethercat_motors"
|
||||
id: "usb_cam2"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/camera.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "tchl_dual_arm_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/dual_arm_ethercat_motors.pb.txt"
|
||||
config_file: "devices/motor/tchl_dual_arm_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_ethercat_arm"
|
||||
id: "right_tchl_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/ethercat_dual_arm.pb.txt"
|
||||
config_file: "devices/arm/tchl_dual_arm.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "left_ethercat_arm"
|
||||
id: "left_tchl_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/ethercat_dual_arm.pb.txt"
|
||||
config_file: "devices/arm/tchl_dual_arm.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "tchl_single_axis"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/tchl_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
devices {
|
||||
id: "lingkong_can_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/lingkong_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
devices {
|
||||
id: "lingkong_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/lingkong_arm.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
devices {
|
||||
id: "tchl_joint_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/tchl_multi_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "tchl_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
@ -270,11 +308,23 @@ device_manager {
|
||||
enable: false
|
||||
}
|
||||
|
||||
|
||||
# Alternative hardware deployment; enable only on the matching device.
|
||||
devices {
|
||||
id: "lingkong_mixed_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/lingkong_mixed_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
devices {
|
||||
id: "lingkong_mixed_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/lingkong_mixed_arm.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
devices {
|
||||
id: "usb_head"
|
||||
type: DEVICE_TYPE_BIO_HEAD_ROBOT
|
||||
config_file: "devices/biohead/bio_head_usb.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
grpc_server {
|
||||
id: "grpc_server"
|
||||
host: "0.0.0.0"
|
||||
port: "50053"
|
||||
port: "50052"
|
||||
enable_reflection: true
|
||||
}
|
||||
|
||||
@ -7,7 +7,7 @@ quic_edge {
|
||||
server_port: 4433
|
||||
alpn: "cmvr-quic-edge/1"
|
||||
node_id: "cmvr-edge"
|
||||
robot_id: "CN-CMVR-MBLRV1-AIMA-20260806-001"
|
||||
robot_id: "CN-CMVR-MBLRV1-AIMA-20260806-002"
|
||||
software_version: "0.1"
|
||||
|
||||
# The existing cmvr-es gRPC server remains the robot-control endpoint. "auto"
|
||||
@ -44,6 +44,18 @@ quic_edge {
|
||||
# }
|
||||
# }
|
||||
|
||||
platforms {
|
||||
id: "platform_199"
|
||||
server_host: "192.168.0.199"
|
||||
server_port: 4433
|
||||
enable_media: false
|
||||
tls {
|
||||
ca_file: "certs/cmvr-quic-ca.crt"
|
||||
server_name: "192.168.0.199"
|
||||
allow_insecure: false
|
||||
}
|
||||
}
|
||||
|
||||
reconnect {
|
||||
initial_delay_ms: 500
|
||||
maximum_delay_ms: 30000
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
add_library(aubo_arm SHARED
|
||||
src/aubo_arm.cpp
|
||||
src/aubo_trajectory_csv.cpp
|
||||
)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
@ -16,7 +17,9 @@ 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")
|
||||
target_compile_definitions(aubo_arm PRIVATE CMVR_HAS_AUBO_SDK)
|
||||
# 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_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})
|
||||
@ -33,12 +36,27 @@ 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,6 +18,16 @@ 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;
|
||||
|
||||
@ -28,6 +38,7 @@ 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;
|
||||
@ -61,6 +72,9 @@ 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;
|
||||
@ -92,6 +106,16 @@ 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,
|
||||
@ -99,10 +123,18 @@ 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,
|
||||
@ -144,6 +176,17 @@ 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_;
|
||||
|
||||
124
cmvr-es/devices/arm/aubo_arm/include/joint_trajectory_csv.h
Normal file
124
cmvr-es/devices/arm/aubo_arm/include/joint_trajectory_csv.h
Normal file
@ -0,0 +1,124 @@
|
||||
#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
|
||||
56
cmvr-es/devices/arm/aubo_arm/include/three_point_frame.h
Normal file
56
cmvr-es/devices/arm/aubo_arm/include/three_point_frame.h
Normal file
@ -0,0 +1,56 @@
|
||||
#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;
|
||||
}
|
||||
}
|
||||
153
cmvr-es/devices/arm/aubo_arm/include/user_coordinate_store.h
Normal file
153
cmvr-es/devices/arm/aubo_arm/include/user_coordinate_store.h
Normal file
@ -0,0 +1,153 @@
|
||||
#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,4 +1,6 @@
|
||||
#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>
|
||||
@ -290,26 +292,6 @@ 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)
|
||||
{
|
||||
@ -324,14 +306,6 @@ 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)
|
||||
{
|
||||
@ -451,6 +425,139 @@ 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)
|
||||
{
|
||||
@ -481,6 +588,76 @@ 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);
|
||||
@ -624,21 +801,103 @@ ArmState AuboArm::getRobotState() const
|
||||
{
|
||||
ArmState state;
|
||||
state.connected = connected_.load();
|
||||
state.powered_on = state.connected;
|
||||
state.brake_released = state.connected;
|
||||
// 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.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;
|
||||
@ -719,7 +978,35 @@ RobotMode AuboArm::getRobotMode() const
|
||||
if (isEmergencyStopped()) {
|
||||
return RobotMode::Stopped;
|
||||
}
|
||||
return busy_.load() ? RobotMode::Running : RobotMode::Idle;
|
||||
#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
|
||||
}
|
||||
|
||||
SafetyMode AuboArm::getSafetyMode() const
|
||||
@ -776,104 +1063,15 @@ bool AuboArm::isFault() const
|
||||
Result AuboArm::listBaseFrame(std::vector<std::string>& frame_names) const
|
||||
{
|
||||
frame_names.clear();
|
||||
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
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"ListBaseFrame/frameGetChildren is not supported for AUBO");
|
||||
}
|
||||
|
||||
Result AuboArm::listTCPFrame(std::vector<std::string>& frame_names) const
|
||||
{
|
||||
frame_names.clear();
|
||||
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
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"ListTCPFrame/frameGetChildren is not supported for AUBO");
|
||||
}
|
||||
|
||||
Result AuboArm::torqueOn()
|
||||
@ -901,16 +1099,54 @@ Result AuboArm::torqueOn()
|
||||
std::vector<double> inertia(6, 0.0);
|
||||
robot_interface->getRobotConfig()->setPayload(mass, cog, aom, inertia);
|
||||
|
||||
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));
|
||||
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));
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
};
|
||||
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) {
|
||||
const int startup_ret = robot_interface->getRobotManage()->startup();
|
||||
if (startup_ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(
|
||||
@ -919,6 +1155,10 @@ 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
|
||||
@ -1168,6 +1408,29 @@ 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,
|
||||
@ -1198,7 +1461,7 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
auto motion_control = robot_interface->getMotionControl();
|
||||
motion_control->setSpeedFraction(speed_scaling_);
|
||||
|
||||
const std::string selected_base_frame = base_frame.empty()
|
||||
const std::string selected_base_frame = (user_pose || user_coordinates_active_.load()) ? std::string{"base"} : base_frame.empty()
|
||||
? (vendor_cfg_.base_frame().empty()
|
||||
? std::string{"base"}
|
||||
: vendor_cfg_.base_frame())
|
||||
@ -1210,6 +1473,8 @@ Result AuboArm::moveL(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(
|
||||
@ -1219,7 +1484,11 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
}
|
||||
|
||||
std::vector<double> tcp_offset;
|
||||
if (selected_tcp_frame == "tool0" ||
|
||||
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" ||
|
||||
selected_tcp_frame == "flange") {
|
||||
tcp_offset.assign(6, 0.0);
|
||||
} else if (selected_tcp_frame == "tcp") {
|
||||
@ -1241,7 +1510,10 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
"[AuboArm] moveL failed: invalid tcp_frame pose: " +
|
||||
selected_tcp_frame);
|
||||
}
|
||||
const int tcp_ret = robot_config->setTcpOffset(tcp_offset);
|
||||
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);
|
||||
if (tcp_ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
@ -1251,6 +1523,22 @@ Result AuboArm::moveL(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");
|
||||
@ -1271,6 +1559,14 @@ Result AuboArm::moveL(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,
|
||||
@ -1355,7 +1651,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) {
|
||||
if (frame == FrameType::Tool || builtin_tool_reference_.load()) {
|
||||
if (!robot_interface->getRobotState()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
@ -1637,6 +1933,13 @@ 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);
|
||||
@ -1978,6 +2281,103 @@ 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)
|
||||
@ -1989,11 +2389,53 @@ 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)
|
||||
{
|
||||
(void)base_link;
|
||||
(void)ee_link;
|
||||
return fk(true);
|
||||
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
|
||||
}
|
||||
|
||||
CartesianPose AuboArm::fk(bool is_tcp)
|
||||
|
||||
366
cmvr-es/devices/arm/aubo_arm/src/aubo_trajectory_csv.cpp
Normal file
366
cmvr-es/devices/arm/aubo_arm/src/aubo_trajectory_csv.cpp
Normal file
@ -0,0 +1,366 @@
|
||||
#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
|
||||
@ -0,0 +1,49 @@
|
||||
#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";
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
#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";
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
#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";
|
||||
}
|
||||
@ -0,0 +1,43 @@
|
||||
#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);
|
||||
}
|
||||
@ -74,3 +74,6 @@ 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)
|
||||
|
||||
@ -0,0 +1,33 @@
|
||||
#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,13 +35,12 @@ 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 isFault() ? RobotMode::Fault : (busy() ? RobotMode::Running : RobotMode::Idle);
|
||||
}
|
||||
RobotMode getRobotMode() const override { return getRobotState().robot_mode; }
|
||||
SafetyMode getSafetyMode() const override;
|
||||
ControlMode getControlMode() const override { return ControlMode::Position; }
|
||||
|
||||
@ -172,13 +171,15 @@ private:
|
||||
|
||||
// Joint-motion position-limit tolerance and post-trajectory settling criteria. These defaults preserve the
|
||||
// historical behavior when the optional arm configuration fields are absent.
|
||||
double move_j_joint_limit_tolerance_rad_{1e-4};
|
||||
double move_j_joint_limit_tolerance_rad_{1e-5};
|
||||
double move_j_settle_timeout_s_{2.0};
|
||||
double move_j_position_tolerance_rad_{2e-3};
|
||||
double move_j_velocity_tolerance_rad_s_{2e-2};
|
||||
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};
|
||||
|
||||
@ -0,0 +1,43 @@
|
||||
#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,4 +1,5 @@
|
||||
#include "arm/motor_robot_arm/include/motor_robot_arm.h"
|
||||
#include "arm/motor_robot_arm/include/lingkong_arm_diagnostics.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@ -156,22 +157,54 @@ 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 = true;
|
||||
state.brake_released = !emergency_stopped;
|
||||
state.powered_on = powered_on_.load();
|
||||
state.brake_released = powered_on_.load() && !emergency_stopped;
|
||||
state.moving = busy();
|
||||
state.protective_stopped = protective_stopped;
|
||||
state.emergency_stopped = emergency_stopped;
|
||||
state.speed_scaling = speed_scaling_.load();
|
||||
state.robot_mode = getRobotMode();
|
||||
state.robot_mode = !state.connected ? RobotMode::Disconnected
|
||||
: isFault() ? RobotMode::Fault : (state.moving ? RobotMode::Running : RobotMode::Idle);
|
||||
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;
|
||||
@ -179,7 +212,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 = RobotMode::Fault;
|
||||
state.robot_mode = state.connected ? RobotMode::Fault : RobotMode::Disconnected;
|
||||
return state;
|
||||
}
|
||||
if (!ik_solver_) {
|
||||
@ -216,6 +249,13 @@ 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()));
|
||||
}
|
||||
if (!motor_manager_ || !motor_manager_->readFeedbacksAtomic(motors, state.position, state.velocity))
|
||||
return {};
|
||||
state.effort.assign(motors.size(), 0.0);
|
||||
return state;
|
||||
}
|
||||
|
||||
@ -264,6 +304,7 @@ Result MotorRobotArm::torqueOn()
|
||||
}
|
||||
}
|
||||
emergency_stopped_.store(false);
|
||||
powered_on_.store(true);
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
@ -279,6 +320,7 @@ Result MotorRobotArm::torqueOff()
|
||||
"failed to torque off motor for joint: " + joint_name);
|
||||
}
|
||||
}
|
||||
powered_on_.store(false);
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
@ -308,7 +350,10 @@ Result MotorRobotArm::calibrateZeroQ(const std::string& joint_name)
|
||||
if (!motor) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name);
|
||||
}
|
||||
motor->calibrateZeroQ();
|
||||
if (!motor->calibrateZeroQ()) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"failed to set zero for joint: " + joint_name);
|
||||
}
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
|
||||
@ -895,3 +895,103 @@ 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
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
#define CMVR_ES_ROBOT_ARM_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
@ -13,6 +14,18 @@
|
||||
|
||||
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;
|
||||
@ -20,6 +33,7 @@ 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;
|
||||
@ -52,6 +66,13 @@ 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;
|
||||
@ -161,6 +182,39 @@ 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;
|
||||
|
||||
@ -100,6 +100,8 @@ namespace cmvr::device {
|
||||
// safely while another thread mutates it.
|
||||
virtual void getState(CameraState &state) = 0;
|
||||
virtual void getRGBImage(cv::Mat &color, Rs2Intrinsics& intrinsics) {}
|
||||
virtual bool supportsDepthImage() const { return false; }
|
||||
virtual bool supportsDepthStream() const { return false; }
|
||||
virtual void getDepthImage(cv::Mat &depth, Rs2Intrinsics& intrinsics) {}
|
||||
virtual void getRGBDImages(cv::Mat &color, cv::Mat &depth, Rs2Intrinsics& intrinsics) {}
|
||||
virtual void startRecording(const std::string &video_path) {}
|
||||
|
||||
@ -261,6 +261,7 @@ HikvisionCamera::HikvisionCamera(const config::HikvisionCameraConfig& camera)
|
||||
height_ = camera_.height();
|
||||
buffer_size_ = camera_.buffer_size() > 0 ? static_cast<size_t>(camera_.buffer_size()) : 30;
|
||||
codec_ = camera_.codec().empty() ? "H264" : camera_.codec();
|
||||
state_.codec = codec_;
|
||||
sdk_path_ = normalizeSdkPath(
|
||||
camera_.sdk_path().empty() ? defaultRuntimeSdkPath() : camera_.sdk_path());
|
||||
// Keep the shared_ptr itself immutable after construction. Readers and the
|
||||
|
||||
@ -32,6 +32,8 @@ namespace cmvr::device
|
||||
bool stop() override;
|
||||
void getState(CameraState& state) override;
|
||||
void getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) override;
|
||||
bool supportsDepthImage() const override { return true; }
|
||||
bool supportsDepthStream() const override { return false; }
|
||||
void getDepthImage(cv::Mat& depth, Rs2Intrinsics& intrinsics) override;
|
||||
void getRGBDImages(cv::Mat &color, cv::Mat &depth, Rs2Intrinsics& intrinsics) override;
|
||||
void startRecording(const std::string &video_path) override;
|
||||
|
||||
@ -50,6 +50,8 @@ public:
|
||||
void setConsumeNewFrameOnly(bool enable);
|
||||
|
||||
void getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) override;
|
||||
bool supportsDepthImage() const override { return true; }
|
||||
bool supportsDepthStream() const override { return true; }
|
||||
void getDepthImage(cv::Mat& depth, Rs2Intrinsics& intrinsics) override;
|
||||
void getRGBDImages(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& intrinsics) override;
|
||||
bool startStreaming() override;
|
||||
|
||||
@ -50,6 +50,7 @@ MujocoCamera::MujocoCamera(config::MujocoCameraConfig config)
|
||||
encode_width_ = positiveOrDefault(encoder.width(), width_);
|
||||
encode_height_ = positiveOrDefault(encoder.height(), height_);
|
||||
codec_ = encoder.codec().empty() ? "H264" : encoder.codec();
|
||||
state_.codec = codec_;
|
||||
enable_stream_timestamp_ = encoder.enable_stream_timestamp();
|
||||
consume_new_frame_only_ = config_.consume_new_frame_only();
|
||||
}
|
||||
|
||||
@ -26,6 +26,8 @@ namespace cmvr::device{
|
||||
bool stop() override;
|
||||
void getState(CameraState& state) override;
|
||||
void getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) override;
|
||||
bool supportsDepthImage() const override { return stream_mode_ != COLOR_MODE; }
|
||||
bool supportsDepthStream() const override { return stream_mode_ != COLOR_MODE; }
|
||||
void getDepthImage(cv::Mat& depth, Rs2Intrinsics& intrinsics) override;
|
||||
void getRGBDImages(cv::Mat &color, cv::Mat &depth, Rs2Intrinsics& intrinsics) override;
|
||||
void startRecording(const std::string &video_path) override;
|
||||
|
||||
@ -132,6 +132,7 @@ RealsenseCamera::RealsenseCamera(const config::RealSenseCameraConfig& camera):ca
|
||||
}
|
||||
|
||||
codec_ = encoder.codec().empty() ? "H264" : encoder.codec();
|
||||
state_.codec = codec_;
|
||||
}
|
||||
|
||||
RealsenseCamera::~RealsenseCamera() {
|
||||
@ -820,10 +821,18 @@ void RealsenseCamera::streaming_worker_() {
|
||||
}
|
||||
CameraStreamEncodeOptions encode_options;
|
||||
encode_options.draw_timestamp = enable_stream_timestamp_;
|
||||
encode_options.overlay = streamOverlay();
|
||||
const Rs2Intrinsics encode_intrinsics = scaleIntrinsics(
|
||||
frame_data.intrinsics,
|
||||
frame_data.rgbImage.cols,
|
||||
frame_data.rgbImage.rows,
|
||||
rgb_to_encode.cols,
|
||||
rgb_to_encode.rows);
|
||||
success = CameraStreamEncoder::encode(rgbEncoder_,
|
||||
rgb_to_encode,
|
||||
frame_data.rgbFrame,
|
||||
frame_data.bKey,
|
||||
encode_intrinsics,
|
||||
encode_options);
|
||||
}
|
||||
if (needs_depth && frame_data.depthFrame.empty())
|
||||
|
||||
@ -153,6 +153,7 @@ UVCCamera::UVCCamera(const config::UVCCameraConfig& camera):camera_(camera)
|
||||
}
|
||||
|
||||
codec_ = encoder.codec().empty() ? "H264" : encoder.codec();
|
||||
state_.codec = codec_;
|
||||
}
|
||||
UVCCamera::~UVCCamera() {
|
||||
stop();
|
||||
|
||||
@ -1,44 +1,95 @@
|
||||
#include "common/base/logging/logger.h"
|
||||
//
|
||||
// Created by lgv on 2025/7/16.
|
||||
//
|
||||
#include "cmvr/msgs/error_code.pb.h"
|
||||
#include "cmvr/msgs/can_card_parameter.pb.h"
|
||||
#include "canbus/can_client/socket/socket_can_client_raw.h"
|
||||
#include "canbus/can_comm/can_receiver.h"
|
||||
#include "cmvr/msgs/robot_detail.pb.h"
|
||||
#include "gtest/gtest.h"
|
||||
namespace cmvr {
|
||||
namespace device {
|
||||
using cmvr::msgs::ErrorCode;
|
||||
using cmvr::msgs::CANCardParameter;
|
||||
|
||||
TEST(SocketCanClientRawTest, simple_test) {
|
||||
CANCardParameter param;
|
||||
param.set_brand(CANCardParameter::SOCKET_CAN_RAW);
|
||||
param.set_channel_id(CANCardParameter::CHANNEL_ID_ZERO);
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
cmvr::config::SocketCanConfig cfg;
|
||||
cfg.set_channel_id(0);
|
||||
SocketCanClientRaw socket_can_client(cfg);
|
||||
namespace cmvr::device {
|
||||
|
||||
// EXPECT_EQ(socket_can_client.start(), ErrorCode::CAN_CLIENT_ERROR_BASE);
|
||||
socket_can_client.start();
|
||||
std::vector<CanFrame> frames;
|
||||
int32_t num = 0;
|
||||
EXPECT_EQ(socket_can_client.send(frames, &num),
|
||||
ErrorCode::OK);
|
||||
++num;
|
||||
EXPECT_EQ(socket_can_client.receive(&frames, &num),
|
||||
ErrorCode::OK);
|
||||
CMVR_LOG(INFO) << frames.at(0).CanFrameString();
|
||||
CanFrame can_frame;
|
||||
can_frame.id = 0x123;
|
||||
can_frame.len = 8;
|
||||
memset(can_frame.data, 0xA3, sizeof(can_frame.data));
|
||||
frames.clear();
|
||||
frames.push_back(can_frame);
|
||||
EXPECT_EQ(socket_can_client.sendSingleFrame(frames),
|
||||
ErrorCode::OK);
|
||||
socket_can_client.stop();
|
||||
// Test the production receive/timeout/stop paths without a CAN adapter,
|
||||
// motor commands, or privileged vcan configuration.
|
||||
class SocketCanClientRawTestPeer {
|
||||
public:
|
||||
static bool attach(SocketCanClientRaw& client, int fd) {
|
||||
if (!client.configureReceiveTimeout(fd)) return false;
|
||||
client.dev_handler_ = fd;
|
||||
client.is_started_ = true;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
class SocketCanReceiveTest : public testing::Test {
|
||||
protected:
|
||||
config::SocketCanConfig config;
|
||||
SocketCanClientRaw client{config};
|
||||
int peer = -1;
|
||||
void SetUp() override {
|
||||
int sockets[2];
|
||||
ASSERT_EQ(::socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets), 0);
|
||||
peer = sockets[1];
|
||||
ASSERT_TRUE(SocketCanClientRawTestPeer::attach(client, sockets[0]));
|
||||
}
|
||||
void TearDown() override {
|
||||
client.stop();
|
||||
if (peer >= 0) ::close(peer);
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(SocketCanReceiveTest, IdleReceiveReturnsZeroWithoutAnError) {
|
||||
std::vector<CanFrame> frames(1);
|
||||
int32_t count = MAX_CAN_RECV_FRAME_LEN;
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
EXPECT_EQ(client.receive(&frames, &count), msgs::ErrorCode::OK);
|
||||
EXPECT_EQ(count, 0);
|
||||
EXPECT_TRUE(frames.empty());
|
||||
EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::milliseconds(500));
|
||||
}
|
||||
|
||||
TEST_F(SocketCanReceiveTest, ReceivedFrameIsReturnedWithActualCount) {
|
||||
can_frame input{};
|
||||
input.can_id = 0x141;
|
||||
input.can_dlc = 8;
|
||||
input.data[0] = 0x9A;
|
||||
ASSERT_EQ(::write(peer, &input, sizeof(input)), sizeof(input));
|
||||
std::vector<CanFrame> frames;
|
||||
int32_t count = MAX_CAN_RECV_FRAME_LEN;
|
||||
ASSERT_EQ(client.receive(&frames, &count), msgs::ErrorCode::OK);
|
||||
ASSERT_EQ(count, 1);
|
||||
ASSERT_EQ(frames.size(), 1U);
|
||||
EXPECT_EQ(frames[0].id, 0x141);
|
||||
EXPECT_EQ(frames[0].len, 8);
|
||||
EXPECT_EQ(frames[0].data[0], 0x9A);
|
||||
}
|
||||
|
||||
TEST_F(SocketCanReceiveTest, ReceiverStopsOnAnIdleBusAndCanRestart) {
|
||||
MessageManager<msgs::RobotDetail> manager;
|
||||
CanReceiver<msgs::RobotDetail> receiver;
|
||||
ASSERT_EQ(receiver.Init(&client, &manager, false), msgs::ErrorCode::OK);
|
||||
for (int attempt = 0; attempt < 3; ++attempt) {
|
||||
ASSERT_EQ(receiver.Start(), msgs::ErrorCode::OK);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
receiver.Stop();
|
||||
EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::milliseconds(500));
|
||||
EXPECT_FALSE(receiver.IsRunning());
|
||||
receiver.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(SocketCanReceiveTest, ShortFrameIsRejectedAndStopIsIdempotent) {
|
||||
const char byte = 0;
|
||||
ASSERT_EQ(::write(peer, &byte, 1), 1);
|
||||
std::vector<CanFrame> frames;
|
||||
int32_t count = 1;
|
||||
EXPECT_EQ(client.receive(&frames, &count), msgs::ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED);
|
||||
EXPECT_EQ(count, 0);
|
||||
EXPECT_TRUE(client.stop());
|
||||
EXPECT_TRUE(client.stop());
|
||||
count = 1;
|
||||
EXPECT_EQ(client.receive(&frames, &count), msgs::ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED);
|
||||
EXPECT_EQ(count, 0);
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
@ -136,7 +136,6 @@ namespace cmvr {
|
||||
}
|
||||
|
||||
int32_t receive_error_count = 0;
|
||||
int32_t receive_none_count = 0;
|
||||
const int32_t ERROR_COUNT_MAX = 10;
|
||||
auto default_period = 10 * 1000; // 10 ms
|
||||
|
||||
@ -160,13 +159,11 @@ namespace cmvr {
|
||||
}
|
||||
|
||||
if (frame_num == 0) {
|
||||
CMVR_LOG_IF_EVERY_N(ERROR, receive_none_count++ > ERROR_COUNT_MAX,
|
||||
ERROR_COUNT_MAX)
|
||||
<< "Received " << receive_none_count << " empty messages.";
|
||||
// A bounded receive timeout on a silent bus is normal,
|
||||
// not a transport error. Return to the stop-flag check.
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(default_period));
|
||||
continue;
|
||||
}
|
||||
receive_none_count = 0;
|
||||
|
||||
for (const auto &frame: buf) {
|
||||
uint8_t len = frame.len;
|
||||
|
||||
@ -1,4 +1,7 @@
|
||||
add_subdirectory(rh56dftp_dexhand)
|
||||
add_subdirectory(px_6ax_gen3)
|
||||
add_subdirectory(zero_sim_touch_dexhand)
|
||||
add_subdirectory(oymotion_ap001)
|
||||
|
||||
add_library(dexhand INTERFACE)
|
||||
|
||||
@ -7,6 +10,9 @@ target_include_directories(dexhand INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(dexhand
|
||||
INTERFACE
|
||||
cmvr_es::device::rh56dftp_dexhand
|
||||
cmvr_es::device::legacy_px_6ax_gen3
|
||||
cmvr_es::device::zero_sim_touch_dexhand
|
||||
cmvr_es::device::oymotion_ap001
|
||||
cmvr_es::proto
|
||||
)
|
||||
|
||||
|
||||
@ -90,6 +90,18 @@ namespace cmvr::device {
|
||||
AbstractDexHand() = default;
|
||||
~AbstractDexHand() override = default;
|
||||
|
||||
bool hasTactileFeedback() const noexcept {
|
||||
return has_tactile_feedback_;
|
||||
}
|
||||
|
||||
void setTactileFeedbackCapability(bool supported) noexcept {
|
||||
has_tactile_feedback_ = supported;
|
||||
}
|
||||
|
||||
const std::string& model() const noexcept { return model_; }
|
||||
|
||||
void setModel(std::string model) { model_ = std::move(model); }
|
||||
|
||||
virtual Status state() const = 0;
|
||||
virtual std::string lastError() const = 0;
|
||||
|
||||
@ -107,6 +119,12 @@ namespace cmvr::device {
|
||||
}
|
||||
|
||||
virtual void setTactilePollingRegions(const std::vector<TactileRegionKey>& regions) = 0;
|
||||
// Streaming services acquire/release sensor acquisition explicitly so
|
||||
// hardware polling does not outlive all connected clients.
|
||||
virtual bool acquireSensorDataStream() {
|
||||
return hasTactileFeedback();
|
||||
}
|
||||
virtual void releaseSensorDataStream() {}
|
||||
virtual std::vector<TactileRegionData> getSensorData() = 0;
|
||||
virtual TactileRegionData getSensorData(FingerType finger, TactileRegion region) = 0;
|
||||
virtual ResultantForce getResultantForce(FingerType finger, TactileRegion region) = 0;
|
||||
@ -135,6 +153,10 @@ namespace cmvr::device {
|
||||
virtual void setForce(const std::vector<int>&) {
|
||||
CMVR_LOG(ERROR) << "[AbstractDexHand] setForce is not supported by this dexhand abstraction.";
|
||||
}
|
||||
|
||||
private:
|
||||
bool has_tactile_feedback_{false};
|
||||
std::string model_;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -8,7 +8,10 @@
|
||||
#include "cmvr/config/dexhand_config/dexhand_config.pb.h"
|
||||
#include "common/base/logging/logger.h"
|
||||
#include "devices/dexhand/abstract_dexhand.h"
|
||||
#include "devices/dexhand/px_6ax_gen3/include/px_6ax_gen3.h"
|
||||
#include "devices/dexhand/rh56dftp_dexhand/include/rh56dftp_dexhand.h"
|
||||
#include "devices/dexhand/zero_sim_touch_dexhand/include/zero_sim_touch_dexhand.h"
|
||||
#include "devices/dexhand/oymotion_ap001/include/oymotion_ap001.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
@ -22,10 +25,27 @@ public:
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::shared_ptr<AbstractDexHand> device;
|
||||
switch (cfg.backend_case()) {
|
||||
case config::DexHandDeviceConfig::kRh56Dftp:
|
||||
return std::make_shared<RH56DFTPDexhand>(
|
||||
device = std::make_shared<RH56DFTPDexhand>(
|
||||
backendWithId_(cfg.id(), cfg.rh56dftp()));
|
||||
break;
|
||||
|
||||
case config::DexHandDeviceConfig::kPx6AxGen3:
|
||||
device = std::make_shared<LegacyPX6AXGen3>(
|
||||
backendWithId_(cfg.id(), cfg.px_6ax_gen3()));
|
||||
break;
|
||||
|
||||
case config::DexHandDeviceConfig::kZeroSimTouch:
|
||||
device = std::make_shared<ZeroSimTouchDexHand>(
|
||||
backendWithId_(cfg.id(), cfg.zero_sim_touch()));
|
||||
break;
|
||||
|
||||
case config::DexHandDeviceConfig::kOymotionAp001:
|
||||
device = std::make_shared<OYMotionAP001>(
|
||||
backendWithId_(cfg.id(), cfg.oymotion_ap001()));
|
||||
break;
|
||||
|
||||
case config::DexHandDeviceConfig::BACKEND_NOT_SET:
|
||||
default:
|
||||
@ -36,6 +56,17 @@ public:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
const bool default_tactile_capability =
|
||||
cfg.backend_case() == config::DexHandDeviceConfig::kRh56Dftp ||
|
||||
cfg.backend_case() == config::DexHandDeviceConfig::kPx6AxGen3 ||
|
||||
cfg.backend_case() == config::DexHandDeviceConfig::kZeroSimTouch ||
|
||||
cfg.backend_case() == config::DexHandDeviceConfig::kOymotionAp001;
|
||||
device->setTactileFeedbackCapability(
|
||||
cfg.has_has_tactile_feedback()
|
||||
? cfg.has_tactile_feedback()
|
||||
: default_tactile_capability);
|
||||
device->setModel(cfg.model().empty() ? device->typeName() : cfg.model());
|
||||
return device;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
12
cmvr-es/devices/dexhand/oymotion_ap001/CMakeLists.txt
Normal file
12
cmvr-es/devices/dexhand/oymotion_ap001/CMakeLists.txt
Normal file
@ -0,0 +1,12 @@
|
||||
add_library(oymotion_ap001 STATIC src/oymotion_ap001.cpp)
|
||||
|
||||
set(OHAND_SDK_ROOT "${PROJECT_SOURCE_DIR}/dependency/x86/third_party/ohand_serial_sdk")
|
||||
add_library(ohand_serial_sdk STATIC IMPORTED)
|
||||
set_target_properties(ohand_serial_sdk PROPERTIES
|
||||
IMPORTED_LOCATION "${OHAND_SDK_ROOT}/lib/libROHSerialAPIStatic.a"
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${OHAND_SDK_ROOT}/include")
|
||||
|
||||
target_include_directories(oymotion_ap001 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(oymotion_ap001 PRIVATE cmvr_es::hardware cmvr_es::proto ohand_serial_sdk pthread)
|
||||
|
||||
add_library(cmvr_es::device::oymotion_ap001 ALIAS oymotion_ap001)
|
||||
@ -0,0 +1,97 @@
|
||||
#ifndef CMVR_ES_OYMOTION_AP001_H
|
||||
#define CMVR_ES_OYMOTION_AP001_H
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "cmvr/config/dexhand_config/dexhand_config.pb.h"
|
||||
#include "devices/dexhand/abstract_dexhand.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class OYMotionAP001 : public AbstractDexHand {
|
||||
public:
|
||||
static constexpr size_t MOTOR_COUNT = 6;
|
||||
|
||||
explicit OYMotionAP001(const config::OYMotionAP001Config& config);
|
||||
~OYMotionAP001() override;
|
||||
|
||||
std::string typeName() const override { return type_name_; }
|
||||
bool init() override;
|
||||
bool start() override;
|
||||
bool stop() override;
|
||||
|
||||
Status state() const override;
|
||||
std::string lastError() const override;
|
||||
void getState(DexHandState& state) override;
|
||||
|
||||
void setAngles(const std::vector<int>& values) override;
|
||||
void setPositions(const std::vector<int>& values) override;
|
||||
void setVelocities(const std::vector<int>& values) override;
|
||||
void setForce(const std::vector<int>& values) override;
|
||||
|
||||
void setTactilePollingRegions(const std::vector<TactileRegionKey>& regions) override;
|
||||
bool acquireSensorDataStream() override;
|
||||
void releaseSensorDataStream() override;
|
||||
|
||||
std::vector<TactileRegionData> getSensorData() override;
|
||||
TactileRegionData getSensorData(FingerType finger, TactileRegion region) override;
|
||||
ResultantForce getResultantForce(FingerType finger, TactileRegion region) override;
|
||||
ForceNewtons getResultantForceNewtons(FingerType finger, TactileRegion region) override;
|
||||
|
||||
protected:
|
||||
OYMotionAP001(std::string id, std::string can_interface,
|
||||
uint32_t hand_id, uint32_t master_id,
|
||||
uint32_t command_timeout_ms, std::string type_name);
|
||||
|
||||
private:
|
||||
static uint32_t sdkMillis();
|
||||
static void sdkDelay(uint32_t milliseconds);
|
||||
static void sdkSend(uint8_t address, uint8_t* data, uint8_t size, void* context);
|
||||
static void sdkReceive(void* context);
|
||||
static OYMotionAP001* fromSdkContext(void* context);
|
||||
bool openSocket();
|
||||
bool checkSdkResult(uint8_t result, uint8_t remote_error, const char* operation);
|
||||
void startTactilePolling();
|
||||
void stopTactilePolling();
|
||||
void tactilePollingLoop();
|
||||
void setFault(const std::string& message);
|
||||
void setState(Status state);
|
||||
std::array<uint16_t, MOTOR_COUNT> normalizedPositions(const std::vector<int>& values, int maximum) const;
|
||||
|
||||
std::string type_name_{"OYMotionAP001"};
|
||||
std::string can_interface_;
|
||||
uint32_t command_timeout_ms_{255};
|
||||
uint8_t hand_id_{2};
|
||||
uint8_t master_id_{1};
|
||||
int socket_fd_{-1};
|
||||
void* sdk_context_{nullptr};
|
||||
|
||||
mutable std::mutex state_mutex_;
|
||||
mutable std::mutex io_mutex_;
|
||||
Status lifecycle_state_{Status::CREATED};
|
||||
std::string last_error_;
|
||||
|
||||
std::array<uint8_t, MOTOR_COUNT> speeds_{{255, 255, 255, 255, 255, 255}};
|
||||
std::array<uint16_t, MOTOR_COUNT> current_positions_{};
|
||||
// OHand SDK reports the physical joint angle in degrees * 100.
|
||||
std::array<int16_t, MOTOR_COUNT> current_angles_{};
|
||||
|
||||
std::vector<TactileRegionKey> tactile_regions_;
|
||||
static constexpr size_t INDEX_TACTILE_COUNT = 60;
|
||||
std::atomic<bool> tactile_running_{false};
|
||||
std::mutex tactile_subscription_mutex_;
|
||||
size_t tactile_subscriber_count_{0};
|
||||
std::thread tactile_thread_;
|
||||
mutable std::mutex tactile_mutex_;
|
||||
std::array<TactilePoint, INDEX_TACTILE_COUNT> index_tactile_{};
|
||||
bool index_tactile_valid_{false};
|
||||
uint64_t index_tactile_sequence_{0};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
#endif // CMVR_ES_OYMOTION_AP001_H
|
||||
544
cmvr-es/devices/dexhand/oymotion_ap001/src/oymotion_ap001.cpp
Normal file
544
cmvr-es/devices/dexhand/oymotion_ap001/src/oymotion_ap001.cpp
Normal file
@ -0,0 +1,544 @@
|
||||
#include "devices/dexhand/oymotion_ap001/include/oymotion_ap001.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <linux/can.h>
|
||||
#include <linux/can/raw.h>
|
||||
#include <net/if.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include "OHandSerialAPI.h"
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
constexpr int kPositionInputMaximum = 2000;
|
||||
constexpr int kAngleInputMaximum = 1000;
|
||||
constexpr int kVelocityInputMaximum = 1000;
|
||||
constexpr int kForceInputMaximum = 3000;
|
||||
constexpr uint8_t kIndexTactileSensorId = 1;
|
||||
constexpr int kIndexTactileRows = 12;
|
||||
constexpr int kIndexTactileCols = 5;
|
||||
constexpr auto kTactilePollingPeriod = std::chrono::microseconds(6667);
|
||||
|
||||
// cmvr-es exposes dex-hand joints as:
|
||||
// pinky, ring, middle, index, thumb flexion, thumb rotation.
|
||||
// OHand SDK uses:
|
||||
// thumb flexion, index, middle, ring, pinky, thumb rotation.
|
||||
constexpr std::array<size_t, OYMotionAP001::MOTOR_COUNT> kApiToSdkMotor{
|
||||
4, 3, 2, 1, 0, 5};
|
||||
|
||||
template <typename T>
|
||||
std::array<T, OYMotionAP001::MOTOR_COUNT> apiToSdkMotorOrder(
|
||||
const std::array<T, OYMotionAP001::MOTOR_COUNT>& api_values) {
|
||||
std::array<T, OYMotionAP001::MOTOR_COUNT> sdk_values{};
|
||||
for (size_t api_index = 0; api_index < kApiToSdkMotor.size(); ++api_index) {
|
||||
sdk_values[kApiToSdkMotor[api_index]] = api_values[api_index];
|
||||
}
|
||||
return sdk_values;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::array<T, OYMotionAP001::MOTOR_COUNT> sdkToApiMotorOrder(
|
||||
const std::array<T, OYMotionAP001::MOTOR_COUNT>& sdk_values) {
|
||||
std::array<T, OYMotionAP001::MOTOR_COUNT> api_values{};
|
||||
for (size_t api_index = 0; api_index < kApiToSdkMotor.size(); ++api_index) {
|
||||
api_values[api_index] = sdk_values[kApiToSdkMotor[api_index]];
|
||||
}
|
||||
return api_values;
|
||||
}
|
||||
|
||||
struct TactileSnapshot {
|
||||
std::array<AbstractDexHand::TactilePoint,
|
||||
static_cast<size_t>(kIndexTactileRows * kIndexTactileCols)>
|
||||
values{};
|
||||
};
|
||||
}
|
||||
|
||||
OYMotionAP001::OYMotionAP001(const config::OYMotionAP001Config& config)
|
||||
: OYMotionAP001(config.id(), config.can_interface(), config.hand_id(),
|
||||
config.master_id(), config.command_timeout_ms(),
|
||||
"OYMotionAP001") {}
|
||||
|
||||
OYMotionAP001::OYMotionAP001(std::string id, std::string can_interface,
|
||||
uint32_t hand_id, uint32_t master_id,
|
||||
uint32_t command_timeout_ms, std::string type_name)
|
||||
: type_name_(std::move(type_name)),
|
||||
can_interface_(can_interface.empty() ? "can0" : std::move(can_interface)),
|
||||
command_timeout_ms_(command_timeout_ms == 0 ? 255 : command_timeout_ms) {
|
||||
id_ = std::move(id);
|
||||
if (hand_id > 0 && hand_id <= 0xff) {
|
||||
hand_id_ = static_cast<uint8_t>(hand_id);
|
||||
}
|
||||
if (master_id > 0 && master_id <= 0xff) {
|
||||
master_id_ = static_cast<uint8_t>(master_id);
|
||||
}
|
||||
}
|
||||
|
||||
OYMotionAP001::~OYMotionAP001() {
|
||||
stop();
|
||||
}
|
||||
|
||||
uint32_t OYMotionAP001::sdkMillis() {
|
||||
static const auto start = std::chrono::steady_clock::now();
|
||||
return static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - start).count());
|
||||
}
|
||||
|
||||
void OYMotionAP001::sdkDelay(uint32_t milliseconds) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
|
||||
}
|
||||
|
||||
OYMotionAP001* OYMotionAP001::fromSdkContext(void* context) {
|
||||
return context ? *static_cast<OYMotionAP001**>(context) : nullptr;
|
||||
}
|
||||
|
||||
void OYMotionAP001::sdkSend(uint8_t address, uint8_t* data, uint8_t size, void* context) {
|
||||
auto* self = fromSdkContext(context);
|
||||
if (!self || self->socket_fd_ < 0) {
|
||||
return;
|
||||
}
|
||||
for (uint8_t offset = 0; offset < size; offset += CAN_MAX_DLEN) {
|
||||
can_frame frame{};
|
||||
frame.can_id = address;
|
||||
frame.can_dlc = static_cast<__u8>(std::min<int>(CAN_MAX_DLEN, size - offset));
|
||||
std::memcpy(frame.data, data + offset, frame.can_dlc);
|
||||
if (write(self->socket_fd_, &frame, sizeof(frame)) != sizeof(frame)) {
|
||||
self->setFault("[OYMotionAP001] failed to write CAN frame on " + self->can_interface_);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void OYMotionAP001::sdkReceive(void* context) {
|
||||
auto* self = fromSdkContext(context);
|
||||
if (!self || self->socket_fd_ < 0) {
|
||||
return;
|
||||
}
|
||||
can_frame frame{};
|
||||
while (read(self->socket_fd_, &frame, sizeof(frame)) == sizeof(frame)) {
|
||||
if ((frame.can_id & CAN_EFF_FLAG) || (frame.can_id & CAN_RTR_FLAG)) {
|
||||
continue;
|
||||
}
|
||||
for (uint8_t i = 0; i < frame.can_dlc; ++i) {
|
||||
HAND_OnData(context, frame.data[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool OYMotionAP001::openSocket() {
|
||||
socket_fd_ = socket(PF_CAN, SOCK_RAW, CAN_RAW);
|
||||
if (socket_fd_ < 0) {
|
||||
return false;
|
||||
}
|
||||
ifreq request{};
|
||||
std::strncpy(request.ifr_name, can_interface_.c_str(), IFNAMSIZ - 1);
|
||||
if (ioctl(socket_fd_, SIOCGIFINDEX, &request) < 0) {
|
||||
return false;
|
||||
}
|
||||
sockaddr_can address{};
|
||||
address.can_family = AF_CAN;
|
||||
address.can_ifindex = request.ifr_ifindex;
|
||||
if (bind(socket_fd_, reinterpret_cast<sockaddr*>(&address), sizeof(address)) < 0) {
|
||||
return false;
|
||||
}
|
||||
const int flags = fcntl(socket_fd_, F_GETFL, 0);
|
||||
return flags >= 0 && fcntl(socket_fd_, F_SETFL, flags | O_NONBLOCK) == 0;
|
||||
}
|
||||
|
||||
bool OYMotionAP001::init() {
|
||||
std::lock_guard<std::mutex> io_lock(io_mutex_);
|
||||
if (sdk_context_) {
|
||||
return true;
|
||||
}
|
||||
if (!openSocket()) {
|
||||
setFault("[OYMotionAP001] cannot open " + can_interface_ + "; ensure it is UP at 1 Mbps");
|
||||
return false;
|
||||
}
|
||||
HAND_SetTimerFunction(sdkMillis, sdkDelay);
|
||||
sdk_context_ = HAND_CreateContext(this, HAND_PROTOCOL_UART, master_id_, sdkSend, sdkReceive);
|
||||
if (!sdk_context_) {
|
||||
setFault("[OYMotionAP001] HAND_CreateContext failed");
|
||||
return false;
|
||||
}
|
||||
HAND_SetCommandTimeOut(sdk_context_, static_cast<uint16_t>(
|
||||
std::min<uint32_t>(command_timeout_ms_, 65535)));
|
||||
uint8_t major = 0, minor = 0, remote_error = 0;
|
||||
if (!checkSdkResult(
|
||||
HAND_GetProtocolVersion(
|
||||
sdk_context_, hand_id_, &major, &minor, &remote_error),
|
||||
remote_error, "HAND_GetProtocolVersion")) {
|
||||
return false;
|
||||
}
|
||||
CMVR_LOG(INFO) << "[OYMotionAP001] connected: id=" << id_
|
||||
<< ", interface=" << can_interface_
|
||||
<< ", hand_id=" << static_cast<int>(hand_id_)
|
||||
<< ", protocol=" << static_cast<int>(major) << "." << static_cast<int>(minor);
|
||||
setState(Status::INITIALIZED);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OYMotionAP001::start() {
|
||||
if (!init()) {
|
||||
return false;
|
||||
}
|
||||
setState(Status::STREAMING);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OYMotionAP001::stop() {
|
||||
{
|
||||
std::lock_guard<std::mutex> subscription_lock(
|
||||
tactile_subscription_mutex_);
|
||||
tactile_subscriber_count_ = 0;
|
||||
stopTactilePolling();
|
||||
}
|
||||
std::lock_guard<std::mutex> io_lock(io_mutex_);
|
||||
if (sdk_context_) {
|
||||
HAND_FreeContext(sdk_context_);
|
||||
sdk_context_ = nullptr;
|
||||
}
|
||||
if (socket_fd_ >= 0) {
|
||||
close(socket_fd_);
|
||||
socket_fd_ = -1;
|
||||
}
|
||||
if (state() != Status::FAULT) {
|
||||
setState(Status::STOPPED);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
AbstractDexHand::Status OYMotionAP001::state() const {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
return lifecycle_state_;
|
||||
}
|
||||
|
||||
std::string OYMotionAP001::lastError() const {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
return last_error_;
|
||||
}
|
||||
|
||||
void OYMotionAP001::getState(DexHandState& output) {
|
||||
DexHandState next{};
|
||||
next.is_initialized = state() == Status::INITIALIZED || state() == Status::STREAMING;
|
||||
std::lock_guard<std::mutex> io_lock(io_mutex_);
|
||||
if (sdk_context_) {
|
||||
std::array<uint16_t, MOTOR_COUNT> target_positions{};
|
||||
std::array<uint16_t, MOTOR_COUNT> current_positions{};
|
||||
// The SDK treats motor_cnt as an in/out buffer-capacity parameter.
|
||||
uint8_t position_count = static_cast<uint8_t>(MOTOR_COUNT);
|
||||
uint8_t position_remote_error = 0;
|
||||
const uint8_t position_result = HAND_GetFingerPosAll(
|
||||
sdk_context_, hand_id_, target_positions.data(), current_positions.data(),
|
||||
&position_count, &position_remote_error);
|
||||
|
||||
if (position_result != HAND_RESP_SUCCESS) {
|
||||
CMVR_LOG(ERROR) << "[OYMotionAP001] HAND_GetFingerPosAll failed: result="
|
||||
<< static_cast<int>(position_result)
|
||||
<< ", remote_error=" << static_cast<int>(position_remote_error);
|
||||
} else if (position_count != MOTOR_COUNT) {
|
||||
CMVR_LOG(ERROR) << "[OYMotionAP001] HAND_GetFingerPosAll returned unexpected motor count: expected="
|
||||
<< MOTOR_COUNT << ", actual=" << static_cast<int>(position_count);
|
||||
} else {
|
||||
current_positions_ = sdkToApiMotorOrder(current_positions);
|
||||
}
|
||||
|
||||
std::array<int16_t, MOTOR_COUNT> target_angles{};
|
||||
std::array<int16_t, MOTOR_COUNT> current_angles{};
|
||||
// The SDK treats motor_cnt as an in/out buffer-capacity parameter.
|
||||
uint8_t angle_count = static_cast<uint8_t>(MOTOR_COUNT);
|
||||
uint8_t angle_remote_error = 0;
|
||||
const uint8_t angle_result = HAND_GetFingerAngleAll(
|
||||
sdk_context_, hand_id_, target_angles.data(), current_angles.data(),
|
||||
&angle_count, &angle_remote_error);
|
||||
|
||||
if (angle_result != HAND_RESP_SUCCESS) {
|
||||
CMVR_LOG(ERROR) << "[OYMotionAP001] HAND_GetFingerAngleAll failed: result="
|
||||
<< static_cast<int>(angle_result)
|
||||
<< ", remote_error=" << static_cast<int>(angle_remote_error);
|
||||
} else if (angle_count != MOTOR_COUNT) {
|
||||
CMVR_LOG(ERROR) << "[OYMotionAP001] HAND_GetFingerAngleAll returned unexpected motor count: expected="
|
||||
<< MOTOR_COUNT << ", actual=" << static_cast<int>(angle_count);
|
||||
} else {
|
||||
current_angles_ = sdkToApiMotorOrder(current_angles);
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < MOTOR_COUNT; ++i) {
|
||||
next.hands[i].position = static_cast<int>(current_positions_[i]) * kPositionInputMaximum / 65535;
|
||||
next.hands[i].angle = current_angles_[i];
|
||||
next.hands[i].speed = static_cast<int>(speeds_[i]) * kVelocityInputMaximum / 255;
|
||||
}
|
||||
const auto error = lastError();
|
||||
if (!error.empty()) {
|
||||
next.hands[0].error_message.push_back(error);
|
||||
}
|
||||
output = std::move(next);
|
||||
}
|
||||
|
||||
std::array<uint16_t, OYMotionAP001::MOTOR_COUNT> OYMotionAP001::normalizedPositions(
|
||||
const std::vector<int>& values, int maximum) const {
|
||||
if (values.size() != MOTOR_COUNT) {
|
||||
throw std::invalid_argument("OYMotionAP001 expects exactly 6 values");
|
||||
}
|
||||
std::array<uint16_t, MOTOR_COUNT> output{};
|
||||
for (size_t i = 0; i < MOTOR_COUNT; ++i) {
|
||||
output[i] = static_cast<uint16_t>(
|
||||
static_cast<uint32_t>(std::clamp(values[i], 0, maximum)) * 65535U / maximum);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
void OYMotionAP001::setPositions(const std::vector<int>& values) {
|
||||
auto positions = apiToSdkMotorOrder(
|
||||
normalizedPositions(values, kPositionInputMaximum));
|
||||
std::lock_guard<std::mutex> lock(io_mutex_);
|
||||
auto speeds = apiToSdkMotorOrder(speeds_);
|
||||
uint8_t remote_error = 0;
|
||||
checkSdkResult(
|
||||
HAND_SetFingerPosAll(
|
||||
sdk_context_, hand_id_, positions.data(), speeds.data(),
|
||||
MOTOR_COUNT, &remote_error),
|
||||
remote_error, "HAND_SetFingerPosAll");
|
||||
}
|
||||
|
||||
void OYMotionAP001::setAngles(const std::vector<int>& values) {
|
||||
auto positions = apiToSdkMotorOrder(
|
||||
normalizedPositions(values, kAngleInputMaximum));
|
||||
std::lock_guard<std::mutex> lock(io_mutex_);
|
||||
auto speeds = apiToSdkMotorOrder(speeds_);
|
||||
uint8_t remote_error = 0;
|
||||
checkSdkResult(
|
||||
HAND_SetFingerPosAll(
|
||||
sdk_context_, hand_id_, positions.data(), speeds.data(),
|
||||
MOTOR_COUNT, &remote_error),
|
||||
remote_error, "HAND_SetFingerPosAll(angle normalization)");
|
||||
}
|
||||
|
||||
void OYMotionAP001::setVelocities(const std::vector<int>& values) {
|
||||
if (values.size() != MOTOR_COUNT) {
|
||||
throw std::invalid_argument("OYMotionAP001 expects exactly 6 velocities");
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(io_mutex_);
|
||||
for (size_t i = 0; i < MOTOR_COUNT; ++i) {
|
||||
speeds_[i] = static_cast<uint8_t>(
|
||||
std::clamp(values[i], 0, kVelocityInputMaximum) * 255 / kVelocityInputMaximum);
|
||||
}
|
||||
}
|
||||
|
||||
void OYMotionAP001::setForce(const std::vector<int>& values) {
|
||||
if (values.size() != MOTOR_COUNT) {
|
||||
throw std::invalid_argument("OYMotionAP001 expects exactly 6 force values");
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(io_mutex_);
|
||||
for (size_t api_index = 0; api_index < MOTOR_COUNT; ++api_index) {
|
||||
uint8_t remote_error = 0;
|
||||
if (!checkSdkResult(
|
||||
HAND_SetFingerForceTarget(
|
||||
sdk_context_, hand_id_,
|
||||
static_cast<uint8_t>(kApiToSdkMotor[api_index]),
|
||||
static_cast<uint16_t>(std::clamp(
|
||||
values[api_index], 0, kForceInputMaximum)),
|
||||
&remote_error),
|
||||
remote_error, "HAND_SetFingerForceTarget")) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void OYMotionAP001::setTactilePollingRegions(
|
||||
const std::vector<TactileRegionKey>& regions) {
|
||||
if (!hasTactileFeedback()) {
|
||||
return;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(io_mutex_);
|
||||
tactile_regions_ = regions;
|
||||
}
|
||||
|
||||
bool OYMotionAP001::acquireSensorDataStream() {
|
||||
if (!hasTactileFeedback()) {
|
||||
return false;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(tactile_subscription_mutex_);
|
||||
++tactile_subscriber_count_;
|
||||
if (tactile_subscriber_count_ == 1) {
|
||||
{
|
||||
std::lock_guard<std::mutex> tactile_lock(tactile_mutex_);
|
||||
index_tactile_valid_ = false;
|
||||
}
|
||||
startTactilePolling();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void OYMotionAP001::releaseSensorDataStream() {
|
||||
std::lock_guard<std::mutex> lock(tactile_subscription_mutex_);
|
||||
if (tactile_subscriber_count_ == 0) {
|
||||
return;
|
||||
}
|
||||
--tactile_subscriber_count_;
|
||||
if (tactile_subscriber_count_ == 0) {
|
||||
stopTactilePolling();
|
||||
}
|
||||
}
|
||||
|
||||
void OYMotionAP001::startTactilePolling() {
|
||||
if (!hasTactileFeedback()) {
|
||||
return;
|
||||
}
|
||||
bool expected = false;
|
||||
if (!tactile_running_.compare_exchange_strong(expected, true)) {
|
||||
return;
|
||||
}
|
||||
tactile_thread_ = std::thread(&OYMotionAP001::tactilePollingLoop, this);
|
||||
}
|
||||
|
||||
void OYMotionAP001::stopTactilePolling() {
|
||||
tactile_running_.store(false);
|
||||
if (tactile_thread_.joinable()) {
|
||||
tactile_thread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void OYMotionAP001::tactilePollingLoop() {
|
||||
auto next_poll = std::chrono::steady_clock::now();
|
||||
auto stats_start = next_poll;
|
||||
uint64_t successful_reads = 0;
|
||||
uint64_t failed_reads = 0;
|
||||
|
||||
while (tactile_running_.load()) {
|
||||
std::array<uint8_t, INDEX_TACTILE_COUNT> raw_force{};
|
||||
uint8_t entry_count = static_cast<uint8_t>(raw_force.size());
|
||||
uint8_t remote_error = 0;
|
||||
uint8_t result = HAND_RESP_TIMEOUT;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(io_mutex_);
|
||||
if (sdk_context_) {
|
||||
result = HAND_GetFingerForce(
|
||||
sdk_context_, hand_id_, kIndexTactileSensorId, &entry_count,
|
||||
raw_force.data(), &remote_error);
|
||||
}
|
||||
}
|
||||
|
||||
if (result == HAND_RESP_SUCCESS && entry_count == raw_force.size()) {
|
||||
std::lock_guard<std::mutex> lock(tactile_mutex_);
|
||||
for (size_t point = 0; point < raw_force.size(); ++point) {
|
||||
index_tactile_[point] = TactilePoint::fromFz(raw_force[point]);
|
||||
}
|
||||
index_tactile_valid_ = true;
|
||||
++index_tactile_sequence_;
|
||||
++successful_reads;
|
||||
} else {
|
||||
++failed_reads;
|
||||
}
|
||||
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const auto stats_elapsed = now - stats_start;
|
||||
if (stats_elapsed >= std::chrono::seconds(5)) {
|
||||
const double seconds =
|
||||
std::chrono::duration<double>(stats_elapsed).count();
|
||||
CMVR_LOG(INFO) << "[OYMotionAP001] index tactile acquisition: rate="
|
||||
<< successful_reads / seconds << " Hz, successful="
|
||||
<< successful_reads << ", failed=" << failed_reads;
|
||||
stats_start = now;
|
||||
successful_reads = 0;
|
||||
failed_reads = 0;
|
||||
}
|
||||
|
||||
next_poll += kTactilePollingPeriod;
|
||||
if (next_poll > now) {
|
||||
std::this_thread::sleep_until(next_poll);
|
||||
} else {
|
||||
next_poll = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<AbstractDexHand::TactileRegionData> OYMotionAP001::getSensorData() {
|
||||
if (!hasTactileFeedback()) {
|
||||
return {};
|
||||
}
|
||||
auto snapshot = std::make_shared<TactileSnapshot>();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(tactile_mutex_);
|
||||
if (!index_tactile_valid_) {
|
||||
return {};
|
||||
}
|
||||
snapshot->values = index_tactile_;
|
||||
}
|
||||
return {TactileRegionData{
|
||||
FingerType::INDEX, TactileRegion::PAD,
|
||||
TactileMatrixView{snapshot->values.data(), kIndexTactileRows,
|
||||
kIndexTactileCols},
|
||||
"食指触觉", snapshot}};
|
||||
}
|
||||
|
||||
AbstractDexHand::TactileRegionData OYMotionAP001::getSensorData(
|
||||
FingerType finger, TactileRegion region) {
|
||||
if (finger != FingerType::INDEX || region != TactileRegion::PAD) {
|
||||
return {};
|
||||
}
|
||||
auto regions = getSensorData();
|
||||
return regions.empty() ? TactileRegionData{} : regions.front();
|
||||
}
|
||||
|
||||
AbstractDexHand::ResultantForce OYMotionAP001::getResultantForce(
|
||||
FingerType finger, TactileRegion region) {
|
||||
const auto tactile_data = getSensorData(finger, region);
|
||||
if (!tactile_data.valid()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
ResultantForce resultant{};
|
||||
for (int row = 0; row < tactile_data.view.rows; ++row) {
|
||||
const auto* values = tactile_data.view.rowData(row);
|
||||
for (int col = 0; col < tactile_data.view.cols; ++col) {
|
||||
resultant.fx += values[col].fx;
|
||||
resultant.fy += values[col].fy;
|
||||
resultant.fz += values[col].fz;
|
||||
}
|
||||
}
|
||||
return resultant;
|
||||
}
|
||||
|
||||
AbstractDexHand::ForceNewtons OYMotionAP001::getResultantForceNewtons(
|
||||
FingerType, TactileRegion) {
|
||||
throw std::runtime_error(
|
||||
"OYMotionAP001 tactile values are raw sensor counts; no newton calibration is available.");
|
||||
}
|
||||
|
||||
bool OYMotionAP001::checkSdkResult(uint8_t result, uint8_t remote_error, const char* operation) {
|
||||
if (result == HAND_RESP_SUCCESS) {
|
||||
return true;
|
||||
}
|
||||
setFault("[OYMotionAP001] " + std::string(operation) + " failed: result="
|
||||
+ std::to_string(result) + ", remote_error="
|
||||
+ std::to_string(remote_error));
|
||||
return false;
|
||||
}
|
||||
|
||||
void OYMotionAP001::setFault(const std::string& message) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
lifecycle_state_ = Status::FAULT;
|
||||
last_error_ = message;
|
||||
}
|
||||
CMVR_LOG(ERROR) << message;
|
||||
}
|
||||
|
||||
void OYMotionAP001::setState(Status next) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex_);
|
||||
lifecycle_state_ = next;
|
||||
if (next == Status::INITIALIZED || next == Status::STREAMING) {
|
||||
last_error_.clear();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
23
cmvr-es/devices/dexhand/px_6ax_gen3/CMakeLists.txt
Normal file
23
cmvr-es/devices/dexhand/px_6ax_gen3/CMakeLists.txt
Normal file
@ -0,0 +1,23 @@
|
||||
add_library(legacy_px_6ax_gen3 SHARED src/px_6ax_gen3.cpp)
|
||||
|
||||
target_include_directories(legacy_px_6ax_gen3 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
add_library(cmvr_es::device::legacy_px_6ax_gen3 ALIAS legacy_px_6ax_gen3)
|
||||
|
||||
target_link_libraries(legacy_px_6ax_gen3
|
||||
PUBLIC cmvr_es::hardware
|
||||
PRIVATE
|
||||
cmvr_es::proto
|
||||
glog
|
||||
)
|
||||
|
||||
install(TARGETS legacy_px_6ax_gen3 LIBRARY DESTINATION lib)
|
||||
|
||||
# Sensor-only executable: no DeviceManager, arm initialization or calibration.
|
||||
add_executable(legacy_px_6ax_gen3_real_test src/px_6ax_gen3_real_test.cpp)
|
||||
target_link_libraries(legacy_px_6ax_gen3_real_test PRIVATE
|
||||
legacy_px_6ax_gen3 cmvr_es::proto cmvr_es::logging pthread)
|
||||
|
||||
add_executable(legacy_px_6ax_gen3_test src/px_6ax_gen3_test.cpp)
|
||||
target_link_libraries(legacy_px_6ax_gen3_test PRIVATE
|
||||
legacy_px_6ax_gen3 cmvr_es::proto cmvr_es::logging gtest gtest_main pthread)
|
||||
55
cmvr-es/devices/dexhand/px_6ax_gen3/README.md
Normal file
55
cmvr-es/devices/dexhand/px_6ax_gen3/README.md
Normal file
@ -0,0 +1,55 @@
|
||||
# PX-6AX GEN3 传感器读取与真实 USB 测试
|
||||
|
||||
真实测试只创建 PX6AXGen3 和 POSIX 串口,不初始化机械臂或 DeviceManager;禁用自动标定,传输层只允许 `0xFB` 读取命令。
|
||||
|
||||
在仓库根目录运行:
|
||||
|
||||
```bash
|
||||
./scripts/build.sh Debug
|
||||
export LD_LIBRARY_PATH="$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
||||
px6_test="$PWD/build/Debug/cmvr-es/devices/dexhand/px_6ax_gen3/px_6ax_gen3_real_test"
|
||||
|
||||
# 每次读取都发起一个真实请求:检查串口应答耗时和按压力值。
|
||||
"$px6_test" --port /dev/ttyACM0 --module-id 2 \
|
||||
--mode sync --duration-s 30 --csv /tmp/paxini-sync.csv --raw-log /tmp/paxini-frames.log
|
||||
|
||||
# 与触屏任务相同:后台轮询,前台读取最新有效缓存。
|
||||
"$px6_test" --port /dev/ttyACM0 --module-id 2 \
|
||||
--mode stream --duration-s 30 --csv /tmp/paxini-stream.csv
|
||||
```
|
||||
|
||||
也可把 `--port` 指定为 `/dev/serial/by-id/` 下的稳定设备链接。设备端口取决于连接顺序;测试参数不会更改机器人部署配置里的串口。`module-id=2` 对应协议设备地址 3。
|
||||
|
||||
先确认构建和安装成功,再运行测试,确保 `output/lib` 中的驱动和 protobuf 与测试程序属于同一次构建。串口应可读写,运行测试前退出占用同一串口的程序。
|
||||
|
||||
测试期间可用手轻按、松开传感器,终端每 100 ms 显示一次力值,CSV 记录每次 getter 调用。按 Ctrl-C 可结束。CSV 的无效读数留空,不能当作零力。进程在初始化失败、没有有效数据或存在读取失败时返回非零退出码。
|
||||
|
||||
- `sync` 的 `read_ms` 是一次驱动请求/应答调用的耗时;默认每 5 ms 请求一次。
|
||||
- `stream` 的 `read_ms` 是读取缓存耗时,成功次数包含重复快照,不能据此推算传感器实际更新频率。
|
||||
- `force_N`、`fz_N` 和 CSV 中的三个力分量均由驱动直接返回,单位为 N;例如原始值 1 对应 0.1 N、108 对应 10.8 N。传感器标称输出频率 83.3 Hz;请求频率可以高于内部测量更新频率。
|
||||
- 串口往返时间不包含“物理接触到传感器产生非零输出”的全部时间。需要按压试验或外部同步信号才能测量接触检测延迟。
|
||||
- `--raw-log` 会记录原始 TX/RX 和单调时钟时间,用于对照手册定位帧问题;写日志会给时间测量带来少量开销。
|
||||
|
||||
## 驱动行为
|
||||
|
||||
`getResultantForceNewtons()` 将合力寄存器的三个原始分量各乘以 0.1,返回以 N 为单位的浮点力值;原有 `getResultantForce()` 保留原始整数。触屏任务和 USB 测试使用牛顿接口,不再额外换算。触屏任务的 `force_threshold`、力值日志和 `lastTouchPressureSum()` 均使用 N;阈值 `0.1` 与旧版原始值阈值 `1.0` 对应相同力度。FZ 判据比较法向力,MAGNITUDE 判据比较三轴合力大小,多区域按原逻辑累加。
|
||||
|
||||
MuJoCo 零值触觉后端也实现牛顿接口。尚无确定换算系数的其他后端(如 RH56DFTP)调用该接口会明确报错,不会把原始压力计数当成 N。
|
||||
|
||||
合力应答按 `14 字节头部 + 3 字节数据 + 1 字节 LRC` 完整读取。验证帧长度、设备地址、预留位、功能码、寄存器地址、字节数及 LRC,并支持分片、请求回显和噪声后的重新定位。
|
||||
|
||||
读状态字节属于内部调试信息(手册 5.3.5);实测正常读应答为 `0x01`,不能套用写应答 `0x00=成功` 的规则。自动标定的写应答要求完整 15 字节并且状态为 0。
|
||||
|
||||
`max_sample_age_ms` 默认 50 ms,可在设备配置中调整。每类数据分别记录请求开始时间:较晚返回的旧请求不能被重新标记为新数据。此值独立于 `response_timeout_ms`(默认 200 ms)。后台读取接口遇到过期或失效快照会抛出异常,不等待串口补读、不返回旧力值或伪造零值;触屏任务现有的异常捕获会将其识别为触觉不可用。
|
||||
|
||||
通信失败会使快照失效,后台继续尝试恢复,只有通过验证的新应答才能恢复有效数据。`stop()` 清除缓存;停止或故障状态下的 getter 报错,显式 `init()` / `start()` 后才能恢复。初始化重试失败会返回 false。
|
||||
|
||||
## 自动回归测试
|
||||
|
||||
真实设备无法稳定制造的坏帧和超时,用可注入的串口实现验证:
|
||||
|
||||
```bash
|
||||
cmake --build cmake-build-debug --target px_6ax_gen3_test -j 4
|
||||
LD_LIBRARY_PATH="$PWD/cmake-build-debug:$PWD/cmake-build-debug/cmvr-es/devices/dexhand/px_6ax_gen3:$PWD/cmake-build-debug/cmvr-es/hardware:$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
|
||||
./cmake-build-debug/cmvr-es/devices/dexhand/px_6ax_gen3/px_6ax_gen3_test
|
||||
```
|
||||
141
cmvr-es/devices/dexhand/px_6ax_gen3/include/px_6ax_gen3.h
Normal file
141
cmvr-es/devices/dexhand/px_6ax_gen3/include/px_6ax_gen3.h
Normal file
@ -0,0 +1,141 @@
|
||||
//
|
||||
// Created by Codex on 2026/4/3.
|
||||
//
|
||||
|
||||
#ifndef PX_6AX_GEN3_DEXHAND_H
|
||||
#define PX_6AX_GEN3_DEXHAND_H
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "cmvr/config/dexhand_config/dexhand_config.pb.h"
|
||||
#include "hardware/include/abstract_serial_transport.h"
|
||||
#include "../../abstract_dexhand.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class LegacyPX6AXGen3 final : public AbstractDexHand {
|
||||
public:
|
||||
using FingerType = AbstractDexHand::FingerType;
|
||||
using ResultantForce = AbstractDexHand::ResultantForce;
|
||||
using TactilePoint = AbstractDexHand::TactilePoint;
|
||||
using TactileRegion = AbstractDexHand::TactileRegion;
|
||||
using TactileRegionKey = AbstractDexHand::TactileRegionKey;
|
||||
using TactileRegionData = AbstractDexHand::TactileRegionData;
|
||||
using Status = AbstractDexHand::Status;
|
||||
|
||||
enum class PollingReadMode {
|
||||
DISTRIBUTED_FORCE,
|
||||
RESULTANT_FORCE,
|
||||
DISTRIBUTED_AND_RESULTANT_FORCE
|
||||
};
|
||||
|
||||
explicit LegacyPX6AXGen3(const config::LegacyPX6AXGen3& cfg);
|
||||
LegacyPX6AXGen3(const config::LegacyPX6AXGen3& cfg,
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> serial);
|
||||
~LegacyPX6AXGen3() override;
|
||||
|
||||
std::string typeName() const override { return "LegacyPX6AXGen3"; }
|
||||
bool init() override;
|
||||
bool start() override;
|
||||
bool stop() override;
|
||||
|
||||
Status state() const override;
|
||||
std::string lastError() const override;
|
||||
void getState(DexHandState& state) override;
|
||||
|
||||
void setAngles(const std::vector<int>& finger_joint_angles) override;
|
||||
void setTactilePollingRegions(const std::vector<TactileRegionKey>& regions) override;
|
||||
std::vector<TactileRegionData> getSensorData() override;
|
||||
TactileRegionData getSensorData(FingerType finger, TactileRegion region) override;
|
||||
// Throws when no fresh, validated sample is available. A failed read is
|
||||
// never represented as a zero force (which would mean no contact).
|
||||
ResultantForce getResultantForce(FingerType finger, TactileRegion region) override;
|
||||
ForceNewtons getResultantForceNewtons(FingerType finger, TactileRegion region) override;
|
||||
|
||||
private:
|
||||
struct SensorSnapshot {
|
||||
std::vector<TactilePoint> tactile_points;
|
||||
std::array<int, 3> resultant_force_tenths{};
|
||||
int rows{0};
|
||||
int cols{0};
|
||||
bool tactile_valid{false};
|
||||
bool resultant_valid{false};
|
||||
std::chrono::steady_clock::time_point tactile_request_time{};
|
||||
std::chrono::steady_clock::time_point resultant_request_time{};
|
||||
};
|
||||
|
||||
static PollingReadMode parsePollingReadMode(config::LegacyPX6AXGen3PollingReadMode mode);
|
||||
static PollingReadMode parsePollingReadModeName(std::string value);
|
||||
|
||||
void initializeSnapshot();
|
||||
void ensureConnected();
|
||||
void closeConnection();
|
||||
void calibrateIfRequested();
|
||||
void refreshSensorData();
|
||||
void refreshSensorData(bool read_distributed, bool read_resultant);
|
||||
void refreshSensorDataWithRetry(int max_attempts, std::chrono::milliseconds retry_interval);
|
||||
void pollingLoop();
|
||||
void ensureSensorReady(bool allow_background, bool require_tactile, bool require_resultant);
|
||||
|
||||
bool isSupportedRegion(FingerType finger, TactileRegion region) const;
|
||||
bool isSnapshotReady(bool require_tactile, bool require_resultant) const;
|
||||
bool isSampleFresh(std::chrono::steady_clock::time_point request_time) const;
|
||||
TactileRegionData buildSupportedRegionSnapshot() const;
|
||||
std::pair<bool, bool> resolvePollingReadSelection() const;
|
||||
|
||||
void clearOperationalError();
|
||||
void handleRefreshFailure(const std::string& error);
|
||||
void transitionTo(Status next_state);
|
||||
void enterFault(const std::string& error);
|
||||
bool isOperationalState(Status lifecycle) const;
|
||||
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> serial_;
|
||||
config::LegacyPX6AXGen3 config_;
|
||||
bool config_valid_{false};
|
||||
|
||||
mutable std::mutex lifecycle_mutex_;
|
||||
Status lifecycle_state_{Status::CREATED};
|
||||
std::string last_error_;
|
||||
|
||||
std::string port_name_;
|
||||
std::string sensor_model_{"S1813_elite"};
|
||||
std::string sensor_name_{"PX-6AX GEN3末端压力"};
|
||||
int module_id_{0};
|
||||
int device_address_{1};
|
||||
int baud_rate_{921600};
|
||||
int distributed_length_{0};
|
||||
int resultant_length_{3};
|
||||
int response_header_bytes_{14};
|
||||
int tactile_rows_{1};
|
||||
int tactile_cols_{0};
|
||||
int response_timeout_ms_{200};
|
||||
std::chrono::milliseconds max_sample_age_{50};
|
||||
FingerType tactile_finger_{FingerType::INDEX};
|
||||
TactileRegion tactile_region_{TactileRegion::TIP};
|
||||
PollingReadMode polling_read_mode_{PollingReadMode::DISTRIBUTED_AND_RESULTANT_FORCE};
|
||||
bool auto_calibrate_{false};
|
||||
bool calibration_performed_{false};
|
||||
|
||||
mutable std::mutex refresh_mutex_;
|
||||
mutable std::mutex snapshot_mutex_;
|
||||
SensorSnapshot latest_snapshot_;
|
||||
|
||||
mutable std::mutex polling_mutex_;
|
||||
std::condition_variable polling_cv_;
|
||||
bool requested_polling_{true};
|
||||
std::thread polling_thread_;
|
||||
std::atomic<bool> polling_thread_running_{false};
|
||||
std::chrono::milliseconds poll_interval_{10};
|
||||
};
|
||||
}
|
||||
|
||||
#endif //PX_6AX_GEN3_DEXHAND_H
|
||||
838
cmvr-es/devices/dexhand/px_6ax_gen3/src/px_6ax_gen3.cpp
Normal file
838
cmvr-es/devices/dexhand/px_6ax_gen3/src/px_6ax_gen3.cpp
Normal file
@ -0,0 +1,838 @@
|
||||
#include "common/base/logging/logger.h"
|
||||
//
|
||||
// Created by Codex on 2026/4/3.
|
||||
//
|
||||
|
||||
#include "../include/px_6ax_gen3.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <tuple>
|
||||
|
||||
#include "hardware/include/posix_serial_transport.h"
|
||||
|
||||
using namespace cmvr::device;
|
||||
|
||||
namespace {
|
||||
using FingerType = AbstractDexHand::FingerType;
|
||||
using TactilePoint = AbstractDexHand::TactilePoint;
|
||||
using TactileRegion = AbstractDexHand::TactileRegion;
|
||||
using TactileRegionKey = AbstractDexHand::TactileRegionKey;
|
||||
using TactileRegionData = AbstractDexHand::TactileRegionData;
|
||||
using Status = AbstractDexHand::Status;
|
||||
|
||||
enum class CommandType {
|
||||
CALIBRATION,
|
||||
RESULTANT_FORCE,
|
||||
DISTRIBUTED_FORCE
|
||||
};
|
||||
|
||||
uint8_t calculateLrc(const std::vector<uint8_t>& data) {
|
||||
uint8_t lrc = 0;
|
||||
for (const uint8_t byte : data) {
|
||||
lrc = static_cast<uint8_t>((lrc + byte) & 0xFFU);
|
||||
}
|
||||
return static_cast<uint8_t>((~lrc + 1U) & 0xFFU);
|
||||
}
|
||||
|
||||
FingerType parseFingerTypeName(std::string value) {
|
||||
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char ch) {
|
||||
return static_cast<char>(std::toupper(ch));
|
||||
});
|
||||
|
||||
if (value == "PINKY") {
|
||||
return FingerType::PINKY;
|
||||
}
|
||||
if (value == "RING") {
|
||||
return FingerType::RING;
|
||||
}
|
||||
if (value == "MIDDLE" || value == "MIDDLE_FINGER") {
|
||||
return FingerType::MIDDLE;
|
||||
}
|
||||
if (value == "INDEX") {
|
||||
return FingerType::INDEX;
|
||||
}
|
||||
if (value == "THUMB") {
|
||||
return FingerType::THUMB;
|
||||
}
|
||||
if (value == "PALM") {
|
||||
return FingerType::PALM;
|
||||
}
|
||||
CMVR_LOG(ERROR) << "[LegacyPX6AXGen3] Unsupported tactile finger type: " << value;
|
||||
return FingerType::INDEX;
|
||||
}
|
||||
|
||||
TactileRegion parseTactileRegionName(std::string value) {
|
||||
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char ch) {
|
||||
return static_cast<char>(std::toupper(ch));
|
||||
});
|
||||
|
||||
if (value == "TIP") {
|
||||
return TactileRegion::TIP;
|
||||
}
|
||||
if (value == "FINGER") {
|
||||
return TactileRegion::FINGER;
|
||||
}
|
||||
if (value == "PAD") {
|
||||
return TactileRegion::PAD;
|
||||
}
|
||||
if (value == "THUMB_MIDDLE") {
|
||||
return TactileRegion::THUMB_MIDDLE;
|
||||
}
|
||||
if (value == "PALM_PAD") {
|
||||
return TactileRegion::PALM_PAD;
|
||||
}
|
||||
CMVR_LOG(ERROR) << "[LegacyPX6AXGen3] Unsupported tactile region type: " << value;
|
||||
return TactileRegion::TIP;
|
||||
}
|
||||
|
||||
int parseSignedByte(const uint8_t byte) {
|
||||
return byte <= 127U ? static_cast<int>(byte) : static_cast<int>(byte) - 256;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> buildCommandFrame(const CommandType command,
|
||||
const int device_address,
|
||||
const int distributed_length) {
|
||||
std::vector<uint8_t> frame;
|
||||
switch (command) {
|
||||
case CommandType::CALIBRATION:
|
||||
frame = {
|
||||
0x55, 0xAA, 0x0A, 0x00,
|
||||
static_cast<uint8_t>(device_address),
|
||||
0x00, 0x79, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01
|
||||
};
|
||||
break;
|
||||
case CommandType::RESULTANT_FORCE:
|
||||
frame = {
|
||||
0x55, 0xAA, 0x09, 0x00,
|
||||
static_cast<uint8_t>(device_address),
|
||||
0x00, 0xFB, 0xF0, 0x03, 0x00, 0x00, 0x03, 0x00
|
||||
};
|
||||
break;
|
||||
case CommandType::DISTRIBUTED_FORCE:
|
||||
frame = {
|
||||
0x55, 0xAA, 0x09, 0x00,
|
||||
static_cast<uint8_t>(device_address),
|
||||
0x00, 0xFB, 0x0E, 0x04, 0x00, 0x00,
|
||||
static_cast<uint8_t>(distributed_length & 0xFF),
|
||||
static_cast<uint8_t>((distributed_length >> 8) & 0xFF)
|
||||
};
|
||||
break;
|
||||
}
|
||||
|
||||
frame.push_back(calculateLrc(frame));
|
||||
return frame;
|
||||
}
|
||||
|
||||
// UART read reply: 14-byte header, N payload bytes, one LRC byte.
|
||||
constexpr size_t kResponseHeaderBytes = 14U;
|
||||
constexpr size_t kResponseOverheadBytes = kResponseHeaderBytes + 1U;
|
||||
|
||||
uint16_t readLe16(const std::vector<uint8_t>& bytes, const size_t offset) {
|
||||
return static_cast<uint16_t>(bytes[offset]) |
|
||||
static_cast<uint16_t>(static_cast<uint16_t>(bytes[offset + 1U]) << 8U);
|
||||
}
|
||||
|
||||
std::string previewBytesHex(const std::vector<uint8_t>& data, const size_t max_bytes = 32U) {
|
||||
std::ostringstream stream;
|
||||
const size_t preview_size = std::min(max_bytes, data.size());
|
||||
for (size_t i = 0; i < preview_size; ++i) {
|
||||
if (i > 0) {
|
||||
stream << ' ';
|
||||
}
|
||||
stream << std::hex << std::uppercase;
|
||||
stream.width(2);
|
||||
stream.fill('0');
|
||||
stream << static_cast<int>(data[i]);
|
||||
}
|
||||
if (data.size() > preview_size) {
|
||||
stream << " ...";
|
||||
}
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
std::vector<uint8_t> transact(cmvr::AbstractSerialTransport& serial,
|
||||
const std::vector<uint8_t>& request,
|
||||
const size_t payload_length,
|
||||
const std::chrono::milliseconds timeout) {
|
||||
if (!serial.flushInput()) {
|
||||
throw std::runtime_error("Failed to flush LegacyPX6AXGen3 input: " + serial.lastError());
|
||||
}
|
||||
if (!serial.write(request)) {
|
||||
throw std::runtime_error("Failed to send LegacyPX6AXGen3 request: " + serial.lastError());
|
||||
}
|
||||
|
||||
const size_t expected_size = kResponseOverheadBytes + payload_length;
|
||||
// Permit a request echo/noisy prefix, but bound resynchronization work.
|
||||
const size_t max_response_bytes = expected_size + 4096U;
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
std::vector<uint8_t> response;
|
||||
size_t offset = 0;
|
||||
std::string error = "Incomplete LegacyPX6AXGen3 response";
|
||||
while (response.size() < max_response_bytes) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now >= deadline) {
|
||||
break;
|
||||
}
|
||||
std::vector<uint8_t> chunk;
|
||||
const auto remaining = std::max(std::chrono::milliseconds(1),
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now));
|
||||
// Read available bytes; never wait for a guessed length before
|
||||
// identifying the header. This also handles split headers/echoes.
|
||||
const bool read_ok = serial.read(1U, remaining, chunk);
|
||||
if (chunk.size() > max_response_bytes - response.size()) {
|
||||
throw std::runtime_error("LegacyPX6AXGen3 response exceeds resynchronization limit");
|
||||
}
|
||||
response.insert(response.end(), chunk.begin(), chunk.end());
|
||||
while (offset + kResponseHeaderBytes <= response.size()) {
|
||||
if (response[offset] != 0xAA || response[offset + 1U] != 0x55) {
|
||||
++offset;
|
||||
continue;
|
||||
}
|
||||
// Frame length counts data[4] through data[N+13], excluding LRC.
|
||||
if (readLe16(response, offset + 2U) != payload_length + 10U ||
|
||||
response[offset + 4U] != request[4] ||
|
||||
response[offset + 5U] != 0x00 ||
|
||||
!std::equal(request.begin() + 6, request.begin() + 13,
|
||||
response.begin() + static_cast<std::ptrdiff_t>(offset + 6U))) {
|
||||
error = "LegacyPX6AXGen3 response does not match request (length/address/function)";
|
||||
++offset;
|
||||
continue;
|
||||
}
|
||||
if (response.size() - offset < expected_size) {
|
||||
break;
|
||||
}
|
||||
uint8_t sum = 0;
|
||||
for (size_t i = offset; i < offset + expected_size; ++i) {
|
||||
sum = static_cast<uint8_t>(sum + response[i]);
|
||||
}
|
||||
if (sum != 0U) {
|
||||
error = "Invalid LegacyPX6AXGen3 response LRC";
|
||||
++offset;
|
||||
continue;
|
||||
}
|
||||
// Manual 5.3.5: read status is internal/debug information;
|
||||
// hardware returns 0x01 on normal force reads. Only write ACKs
|
||||
// define 0x00 as success (5.4.2), so do not apply it to reads.
|
||||
if (request[6] == 0x79 && response[offset + 13U] != 0x00) {
|
||||
throw std::runtime_error("LegacyPX6AXGen3 returned status " +
|
||||
std::to_string(response[offset + 13U]));
|
||||
}
|
||||
return std::vector<uint8_t>(
|
||||
response.begin() + static_cast<std::ptrdiff_t>(offset + kResponseHeaderBytes),
|
||||
response.begin() + static_cast<std::ptrdiff_t>(offset + kResponseHeaderBytes + payload_length));
|
||||
}
|
||||
if (!read_ok || chunk.empty()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw std::runtime_error(error + "; " + serial.lastError() +
|
||||
", raw=" + previewBytesHex(response));
|
||||
}
|
||||
|
||||
std::array<int, 3> parseResultantPayload(const std::vector<uint8_t>& payload) {
|
||||
if (payload.size() < 3) {
|
||||
CMVR_LOG(ERROR) << "PX-6AX GEN3 resultant payload must contain at least 3 bytes.";
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
parseSignedByte(payload[0]),
|
||||
parseSignedByte(payload[1]),
|
||||
static_cast<int>(payload[2])
|
||||
};
|
||||
}
|
||||
|
||||
std::vector<TactilePoint> parseDistributedPayload(const std::vector<uint8_t>& payload) {
|
||||
const size_t point_count = payload.size() / 3;
|
||||
std::vector<TactilePoint> points;
|
||||
points.reserve(point_count);
|
||||
|
||||
for (size_t i = 0; i < point_count; ++i) {
|
||||
points.push_back(TactilePoint{
|
||||
parseSignedByte(payload[i * 3]),
|
||||
parseSignedByte(payload[i * 3 + 1]),
|
||||
static_cast<int>(payload[i * 3 + 2])
|
||||
});
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
std::pair<int, int> resolveMatrixShape(const int configured_rows,
|
||||
const int configured_cols,
|
||||
const size_t point_count) {
|
||||
if (point_count == 0U) {
|
||||
return {0, 0};
|
||||
}
|
||||
|
||||
if (configured_rows > 0 && configured_cols > 0 &&
|
||||
static_cast<size_t>(configured_rows * configured_cols) == point_count) {
|
||||
return {configured_rows, configured_cols};
|
||||
}
|
||||
|
||||
if (configured_rows > 0 && configured_cols <= 0 &&
|
||||
point_count % static_cast<size_t>(configured_rows) == 0U) {
|
||||
return {configured_rows, static_cast<int>(point_count / static_cast<size_t>(configured_rows))};
|
||||
}
|
||||
|
||||
if (configured_cols > 0 && configured_rows <= 0 &&
|
||||
point_count % static_cast<size_t>(configured_cols) == 0U) {
|
||||
return {static_cast<int>(point_count / static_cast<size_t>(configured_cols)), configured_cols};
|
||||
}
|
||||
|
||||
return {1, static_cast<int>(point_count)};
|
||||
}
|
||||
}
|
||||
|
||||
LegacyPX6AXGen3::PollingReadMode LegacyPX6AXGen3::parsePollingReadMode(const config::LegacyPX6AXGen3PollingReadMode mode) {
|
||||
switch (mode) {
|
||||
case config::LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE:
|
||||
return PollingReadMode::DISTRIBUTED_FORCE;
|
||||
case config::LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE:
|
||||
return PollingReadMode::RESULTANT_FORCE;
|
||||
case config::LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_AND_RESULTANT_FORCE:
|
||||
return PollingReadMode::DISTRIBUTED_AND_RESULTANT_FORCE;
|
||||
default:
|
||||
CMVR_LOG(ERROR) << "Unsupported LegacyPX6AXGen3 polling_read_mode enum value: "
|
||||
<< static_cast<int>(mode);
|
||||
return PollingReadMode::DISTRIBUTED_AND_RESULTANT_FORCE;
|
||||
}
|
||||
}
|
||||
|
||||
LegacyPX6AXGen3::PollingReadMode LegacyPX6AXGen3::parsePollingReadModeName(std::string value) {
|
||||
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char ch) {
|
||||
if (ch == '-' || ch == ' ' || ch == '+') {
|
||||
return '_';
|
||||
}
|
||||
return static_cast<char>(std::toupper(ch));
|
||||
});
|
||||
|
||||
if (value == "DISTRIBUTED_FORCE" ||
|
||||
value == "LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE") {
|
||||
return PollingReadMode::DISTRIBUTED_FORCE;
|
||||
}
|
||||
if (value == "RESULTANT_FORCE" ||
|
||||
value == "LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE") {
|
||||
return PollingReadMode::RESULTANT_FORCE;
|
||||
}
|
||||
if (value == "DISTRIBUTED_AND_RESULTANT_FORCE" ||
|
||||
value == "RESULTANT_AND_DISTRIBUTED_FORCE" ||
|
||||
value == "BOTH" ||
|
||||
value == "LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_AND_RESULTANT_FORCE") {
|
||||
return PollingReadMode::DISTRIBUTED_AND_RESULTANT_FORCE;
|
||||
}
|
||||
|
||||
CMVR_LOG(ERROR) << "Unsupported LegacyPX6AXGen3 polling_read_mode: " << value;
|
||||
return PollingReadMode::DISTRIBUTED_AND_RESULTANT_FORCE;
|
||||
}
|
||||
|
||||
LegacyPX6AXGen3::LegacyPX6AXGen3(const config::LegacyPX6AXGen3& cfg)
|
||||
: LegacyPX6AXGen3(cfg, std::make_unique<::cmvr::PosixSerialTransport>()) {}
|
||||
|
||||
LegacyPX6AXGen3::LegacyPX6AXGen3(const config::LegacyPX6AXGen3& cfg,
|
||||
std::unique_ptr<::cmvr::AbstractSerialTransport> serial)
|
||||
: serial_(std::move(serial)), config_(cfg) {
|
||||
id_ = config_.id();
|
||||
port_name_ = config_.serial_port();
|
||||
if (!config_.sensor_model().empty()) {
|
||||
sensor_model_ = config_.sensor_model();
|
||||
}
|
||||
module_id_ = config_.module_id();
|
||||
if (!serial_ || module_id_ < 0 || module_id_ > 254) {
|
||||
enterFault("LegacyPX6AXGen3 requires a serial transport and module_id in [0, 254].");
|
||||
return;
|
||||
}
|
||||
device_address_ = module_id_ + 1;
|
||||
if (config_.baud_rate() > 0) {
|
||||
baud_rate_ = config_.baud_rate();
|
||||
}
|
||||
distributed_length_ = config_.distributed_length();
|
||||
if (distributed_length_ <= 0 || distributed_length_ > 65525 || distributed_length_ % 3 != 0) {
|
||||
enterFault("LegacyPX6AXGen3 distributed_length must be a positive multiple of 3 fitting the UART frame.");
|
||||
return;
|
||||
}
|
||||
if (config_.resultant_length() > 0) {
|
||||
resultant_length_ = config_.resultant_length();
|
||||
}
|
||||
if (config_.response_header_bytes() > 0) {
|
||||
response_header_bytes_ = config_.response_header_bytes();
|
||||
}
|
||||
if (resultant_length_ != 3 || response_header_bytes_ != kResponseHeaderBytes ||
|
||||
config_.resultant_length() < 0 || config_.response_header_bytes() < 0 ||
|
||||
config_.max_sample_age_ms() < 0) {
|
||||
enterFault("LegacyPX6AXGen3 requires resultant_length=3, response_header_bytes=14 and a nonnegative max_sample_age_ms.");
|
||||
return;
|
||||
}
|
||||
if (config_.max_sample_age_ms() > 0) {
|
||||
max_sample_age_ = std::chrono::milliseconds(config_.max_sample_age_ms());
|
||||
}
|
||||
if (config_.tactile_rows() > 0) {
|
||||
tactile_rows_ = config_.tactile_rows();
|
||||
}
|
||||
if (config_.tactile_cols() > 0) {
|
||||
tactile_cols_ = config_.tactile_cols();
|
||||
}
|
||||
if (config_.response_timeout_ms() > 0) {
|
||||
response_timeout_ms_ = config_.response_timeout_ms();
|
||||
}
|
||||
if (!config_.tactile_finger().empty()) {
|
||||
tactile_finger_ = parseFingerTypeName(config_.tactile_finger());
|
||||
}
|
||||
if (!config_.tactile_region().empty()) {
|
||||
tactile_region_ = parseTactileRegionName(config_.tactile_region());
|
||||
}
|
||||
if (!config_.sensor_name().empty()) {
|
||||
sensor_name_ = config_.sensor_name();
|
||||
}
|
||||
polling_read_mode_ = parsePollingReadMode(config_.polling_read_mode());
|
||||
auto_calibrate_ = config_.auto_calibrate();
|
||||
if (config_.poll_interval_ms() > 0) {
|
||||
poll_interval_ = std::chrono::milliseconds(config_.poll_interval_ms());
|
||||
}
|
||||
initializeSnapshot();
|
||||
config_valid_ = true;
|
||||
}
|
||||
|
||||
LegacyPX6AXGen3::~LegacyPX6AXGen3() {
|
||||
stop();
|
||||
}
|
||||
|
||||
bool LegacyPX6AXGen3::init() {
|
||||
if (!config_valid_) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
refreshSensorDataWithRetry(
|
||||
5,
|
||||
std::chrono::milliseconds(std::max(10, response_timeout_ms_ / 2)));
|
||||
const auto [tactile, resultant] = resolvePollingReadSelection();
|
||||
return isOperationalState(state()) && isSnapshotReady(tactile, resultant);
|
||||
} catch (const std::exception& e) {
|
||||
enterFault("[LegacyPX6AXGen3](init): " + std::string(e.what()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool LegacyPX6AXGen3::start() {
|
||||
if (!config_valid_) {
|
||||
return false;
|
||||
}
|
||||
if (polling_thread_running_.exchange(true, std::memory_order_acq_rel)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
if (polling_thread_.joinable()) {
|
||||
polling_thread_.join();
|
||||
}
|
||||
|
||||
bool requested_polling;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(polling_mutex_);
|
||||
requested_polling = requested_polling_;
|
||||
}
|
||||
if (requested_polling) {
|
||||
refreshSensorDataWithRetry(
|
||||
5,
|
||||
std::chrono::milliseconds(std::max(10, response_timeout_ms_ / 2)));
|
||||
} else {
|
||||
std::lock_guard<std::mutex> lock(refresh_mutex_);
|
||||
ensureConnected();
|
||||
}
|
||||
|
||||
transitionTo(Status::STREAMING);
|
||||
polling_thread_ = std::thread(&LegacyPX6AXGen3::pollingLoop, this);
|
||||
polling_cv_.notify_all();
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
polling_thread_running_.store(false, std::memory_order_release);
|
||||
enterFault("[LegacyPX6AXGen3](start): " + std::string(e.what()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool LegacyPX6AXGen3::stop() {
|
||||
polling_thread_running_.store(false, std::memory_order_release);
|
||||
polling_cv_.notify_all();
|
||||
|
||||
if (polling_thread_.joinable() && polling_thread_.get_id() != std::this_thread::get_id()) {
|
||||
polling_thread_.join();
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(refresh_mutex_);
|
||||
initializeSnapshot();
|
||||
closeConnection();
|
||||
|
||||
if (state() != Status::FAULT) {
|
||||
transitionTo(Status::STOPPED);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
LegacyPX6AXGen3::Status LegacyPX6AXGen3::state() const {
|
||||
std::lock_guard<std::mutex> lock(lifecycle_mutex_);
|
||||
return lifecycle_state_;
|
||||
}
|
||||
|
||||
std::string LegacyPX6AXGen3::lastError() const {
|
||||
std::lock_guard<std::mutex> lock(lifecycle_mutex_);
|
||||
return last_error_;
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::getState(DexHandState& state_out) {
|
||||
DexHandState next_state{};
|
||||
next_state.is_initialized = isOperationalState(state());
|
||||
const auto [tactile, resultant] = resolvePollingReadSelection();
|
||||
const bool ready = isSnapshotReady(tactile, resultant);
|
||||
next_state.is_initialized = next_state.is_initialized && ready;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(snapshot_mutex_);
|
||||
if (latest_snapshot_.resultant_valid && isSampleFresh(latest_snapshot_.resultant_request_time)) {
|
||||
next_state.hands[0].force = latest_snapshot_.resultant_force_tenths[2];
|
||||
}
|
||||
}
|
||||
|
||||
const auto error = lastError();
|
||||
if (!error.empty()) {
|
||||
next_state.hands[0].error_message.push_back(error);
|
||||
} else if (!ready) {
|
||||
next_state.hands[0].error_message.push_back("LegacyPX6AXGen3 sample is unavailable or stale.");
|
||||
}
|
||||
|
||||
state_out = std::move(next_state);
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::setAngles(const std::vector<int>&) {
|
||||
CMVR_LOG(ERROR) << "LegacyPX6AXGen3 is a tactile sensor only and does not support setAngles.";
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::setTactilePollingRegions(const std::vector<TactileRegionKey>& regions) {
|
||||
for (const auto& region : regions) {
|
||||
if (!isSupportedRegion(region.first, region.second)) {
|
||||
CMVR_LOG(ERROR) << "LegacyPX6AXGen3 only exposes INDEX/TIP tactile data.";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(polling_mutex_);
|
||||
requested_polling_ = !regions.empty();
|
||||
}
|
||||
polling_cv_.notify_all();
|
||||
|
||||
if (!regions.empty() && isOperationalState(state()) &&
|
||||
!polling_thread_running_.load(std::memory_order_acquire)) {
|
||||
refreshSensorData();
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<TactileRegionData> LegacyPX6AXGen3::getSensorData() {
|
||||
ensureSensorReady(true, true, false);
|
||||
std::vector<TactileRegionData> regions;
|
||||
regions.push_back(buildSupportedRegionSnapshot());
|
||||
return regions;
|
||||
}
|
||||
|
||||
TactileRegionData LegacyPX6AXGen3::getSensorData(FingerType finger, TactileRegion region) {
|
||||
if (!isSupportedRegion(finger, region)) {
|
||||
throw std::invalid_argument("LegacyPX6AXGen3 requested tactile region is not configured.");
|
||||
}
|
||||
|
||||
ensureSensorReady(true, true, false);
|
||||
return buildSupportedRegionSnapshot();
|
||||
}
|
||||
|
||||
LegacyPX6AXGen3::ResultantForce LegacyPX6AXGen3::getResultantForce(FingerType finger, TactileRegion region) {
|
||||
if (!isSupportedRegion(finger, region)) {
|
||||
throw std::invalid_argument("LegacyPX6AXGen3 requested resultant-force region is not configured.");
|
||||
}
|
||||
|
||||
ensureSensorReady(true, false, true);
|
||||
|
||||
std::lock_guard<std::mutex> lock(snapshot_mutex_);
|
||||
if (!latest_snapshot_.resultant_valid || !isSampleFresh(latest_snapshot_.resultant_request_time)) {
|
||||
throw std::runtime_error("LegacyPX6AXGen3 resultant-force sample is unavailable or stale.");
|
||||
}
|
||||
|
||||
return ResultantForce{
|
||||
latest_snapshot_.resultant_force_tenths[0],
|
||||
latest_snapshot_.resultant_force_tenths[1],
|
||||
latest_snapshot_.resultant_force_tenths[2]
|
||||
};
|
||||
}
|
||||
|
||||
LegacyPX6AXGen3::ForceNewtons LegacyPX6AXGen3::getResultantForceNewtons(FingerType finger, TactileRegion region) {
|
||||
const auto raw = getResultantForce(finger, region);
|
||||
// PX-6AX GEN3 manual 5.6.2: one resultant-force LSB is 0.1 N.
|
||||
constexpr double kNewtonsPerCount = 0.1;
|
||||
return {raw.fx * kNewtonsPerCount, raw.fy * kNewtonsPerCount, raw.fz * kNewtonsPerCount};
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::initializeSnapshot() {
|
||||
std::lock_guard<std::mutex> lock(snapshot_mutex_);
|
||||
latest_snapshot_ = SensorSnapshot{};
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::ensureConnected() {
|
||||
if (!config_valid_ || port_name_.empty()) {
|
||||
throw std::runtime_error("LegacyPX6AXGen3 serial/configuration is invalid.");
|
||||
}
|
||||
if (!serial_->isOpen()) {
|
||||
if (!serial_->open(::cmvr::AbstractSerialTransport::Config{port_name_, baud_rate_})) {
|
||||
throw std::runtime_error("Failed to open LegacyPX6AXGen3 serial transport: " + serial_->lastError());
|
||||
}
|
||||
calibration_performed_ = false;
|
||||
}
|
||||
calibrateIfRequested();
|
||||
if (!isOperationalState(state())) {
|
||||
transitionTo(Status::INITIALIZED);
|
||||
}
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::closeConnection() {
|
||||
if (serial_) {
|
||||
if (!serial_->close()) {
|
||||
CMVR_LOG(WARNING) << "[LegacyPX6AXGen3] Failed to close serial transport: " << serial_->lastError();
|
||||
}
|
||||
}
|
||||
calibration_performed_ = false;
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::calibrateIfRequested() {
|
||||
if (!auto_calibrate_ || calibration_performed_) {
|
||||
return;
|
||||
}
|
||||
const auto frame = buildCommandFrame(CommandType::CALIBRATION, device_address_, distributed_length_);
|
||||
// Write acknowledgment has a complete 14-byte header and LRC, no payload.
|
||||
transact(*serial_, frame, 0U, std::chrono::milliseconds(response_timeout_ms_));
|
||||
calibration_performed_ = true;
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::refreshSensorData() {
|
||||
const auto [read_distributed, read_resultant] = resolvePollingReadSelection();
|
||||
refreshSensorData(read_distributed, read_resultant);
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::refreshSensorData(const bool read_distributed, const bool read_resultant) {
|
||||
if (!read_distributed && !read_resultant) {
|
||||
throw std::invalid_argument("LegacyPX6AXGen3 refresh requires at least one data type.");
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> refresh_lock(refresh_mutex_);
|
||||
try {
|
||||
ensureConnected();
|
||||
// Publish force first: a slower distributed read must not postpone a
|
||||
// contact measurement. Each channel has its own request timestamp.
|
||||
if (read_resultant) {
|
||||
const auto frame = buildCommandFrame(CommandType::RESULTANT_FORCE, device_address_, distributed_length_);
|
||||
const auto request_time = std::chrono::steady_clock::now();
|
||||
const auto payload = transact(*serial_, frame, resultant_length_,
|
||||
std::chrono::milliseconds(response_timeout_ms_));
|
||||
if (!isSampleFresh(request_time)) {
|
||||
throw std::runtime_error("LegacyPX6AXGen3 resultant-force response arrived too late.");
|
||||
}
|
||||
const auto force = parseResultantPayload(payload);
|
||||
std::lock_guard<std::mutex> lock(snapshot_mutex_);
|
||||
latest_snapshot_.resultant_force_tenths = force;
|
||||
latest_snapshot_.resultant_request_time = request_time;
|
||||
latest_snapshot_.resultant_valid = true;
|
||||
}
|
||||
if (read_distributed) {
|
||||
const auto frame = buildCommandFrame(CommandType::DISTRIBUTED_FORCE, device_address_, distributed_length_);
|
||||
const auto request_time = std::chrono::steady_clock::now();
|
||||
const auto payload = transact(*serial_, frame, distributed_length_,
|
||||
std::chrono::milliseconds(response_timeout_ms_));
|
||||
if (!isSampleFresh(request_time)) {
|
||||
throw std::runtime_error("LegacyPX6AXGen3 distributed-force response arrived too late.");
|
||||
}
|
||||
auto points = parseDistributedPayload(payload);
|
||||
const auto [rows, cols] = resolveMatrixShape(tactile_rows_, tactile_cols_, points.size());
|
||||
std::lock_guard<std::mutex> lock(snapshot_mutex_);
|
||||
latest_snapshot_.tactile_points = std::move(points);
|
||||
latest_snapshot_.rows = rows;
|
||||
latest_snapshot_.cols = cols;
|
||||
latest_snapshot_.tactile_request_time = request_time;
|
||||
latest_snapshot_.tactile_valid = true;
|
||||
}
|
||||
clearOperationalError();
|
||||
} catch (const std::exception& e) {
|
||||
handleRefreshFailure(e.what());
|
||||
// Let initialization retries and synchronous callers see the failure.
|
||||
// The polling thread catches it and continues reconnecting in background.
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::refreshSensorDataWithRetry(const int max_attempts,
|
||||
const std::chrono::milliseconds retry_interval) {
|
||||
std::string last_error;
|
||||
|
||||
for (int attempt = 0; attempt < max_attempts; ++attempt) {
|
||||
try {
|
||||
refreshSensorData();
|
||||
return;
|
||||
} catch (const std::exception& e) {
|
||||
last_error = e.what();
|
||||
}
|
||||
|
||||
if (attempt + 1 < max_attempts) {
|
||||
std::this_thread::sleep_for(retry_interval);
|
||||
}
|
||||
}
|
||||
|
||||
throw std::runtime_error(last_error.empty() ? "LegacyPX6AXGen3 refresh retries exhausted." : last_error);
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::pollingLoop() {
|
||||
auto next_poll_deadline = std::chrono::steady_clock::now();
|
||||
std::unique_lock<std::mutex> lock(polling_mutex_);
|
||||
while (polling_thread_running_.load(std::memory_order_acquire)) {
|
||||
if (!requested_polling_) {
|
||||
polling_cv_.wait(lock, [this]() {
|
||||
return !polling_thread_running_.load(std::memory_order_acquire) || requested_polling_;
|
||||
});
|
||||
next_poll_deadline = std::chrono::steady_clock::now();
|
||||
continue;
|
||||
}
|
||||
|
||||
lock.unlock();
|
||||
try {
|
||||
refreshSensorData();
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << e.what();
|
||||
}
|
||||
lock.lock();
|
||||
|
||||
next_poll_deadline += poll_interval_;
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (next_poll_deadline <= now) {
|
||||
next_poll_deadline = now;
|
||||
continue;
|
||||
}
|
||||
|
||||
polling_cv_.wait_until(lock, next_poll_deadline, [this]() {
|
||||
return !polling_thread_running_.load(std::memory_order_acquire);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::ensureSensorReady(const bool allow_background,
|
||||
const bool require_tactile,
|
||||
const bool require_resultant) {
|
||||
const auto lifecycle = state();
|
||||
if (!config_valid_ || lifecycle == Status::STOPPED || lifecycle == Status::FAULT) {
|
||||
throw std::runtime_error("LegacyPX6AXGen3 is not operational: " + lastError());
|
||||
}
|
||||
const auto [polls_tactile, polls_resultant] = resolvePollingReadSelection();
|
||||
const bool background_covers_request =
|
||||
(!require_tactile || polls_tactile) &&
|
||||
(!require_resultant || polls_resultant);
|
||||
if (allow_background && background_covers_request &&
|
||||
polling_thread_running_.load(std::memory_order_acquire)) {
|
||||
// The getter checks freshness while copying under snapshot_mutex_.
|
||||
// Never block the control loop on serial I/O to replace a stale sample.
|
||||
return;
|
||||
}
|
||||
refreshSensorData(require_tactile, require_resultant);
|
||||
}
|
||||
|
||||
bool LegacyPX6AXGen3::isSupportedRegion(const FingerType finger, const TactileRegion region) const {
|
||||
return finger == tactile_finger_ && region == tactile_region_;
|
||||
}
|
||||
|
||||
bool LegacyPX6AXGen3::isSnapshotReady(const bool require_tactile, const bool require_resultant) const {
|
||||
std::lock_guard<std::mutex> lock(snapshot_mutex_);
|
||||
return (!require_tactile || (latest_snapshot_.tactile_valid &&
|
||||
isSampleFresh(latest_snapshot_.tactile_request_time))) &&
|
||||
(!require_resultant || (latest_snapshot_.resultant_valid &&
|
||||
isSampleFresh(latest_snapshot_.resultant_request_time)));
|
||||
}
|
||||
|
||||
bool LegacyPX6AXGen3::isSampleFresh(const std::chrono::steady_clock::time_point request_time) const {
|
||||
return request_time != std::chrono::steady_clock::time_point{} &&
|
||||
std::chrono::steady_clock::now() - request_time <= max_sample_age_;
|
||||
}
|
||||
|
||||
TactileRegionData LegacyPX6AXGen3::buildSupportedRegionSnapshot() const {
|
||||
auto snapshot = std::make_shared<std::vector<TactilePoint>>();
|
||||
int rows = 0;
|
||||
int cols = 0;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(snapshot_mutex_);
|
||||
if (!latest_snapshot_.tactile_valid || !isSampleFresh(latest_snapshot_.tactile_request_time)) {
|
||||
throw std::runtime_error("LegacyPX6AXGen3 tactile sample is unavailable or stale.");
|
||||
}
|
||||
*snapshot = latest_snapshot_.tactile_points;
|
||||
rows = latest_snapshot_.rows;
|
||||
cols = latest_snapshot_.cols;
|
||||
}
|
||||
|
||||
return TactileRegionData(
|
||||
tactile_finger_,
|
||||
tactile_region_,
|
||||
AbstractDexHand::TactileMatrixView{snapshot->data(), rows, cols},
|
||||
sensor_name_.c_str(),
|
||||
snapshot);
|
||||
}
|
||||
|
||||
std::pair<bool, bool> LegacyPX6AXGen3::resolvePollingReadSelection() const {
|
||||
switch (polling_read_mode_) {
|
||||
case PollingReadMode::DISTRIBUTED_FORCE:
|
||||
return {true, false};
|
||||
case PollingReadMode::RESULTANT_FORCE:
|
||||
return {false, true};
|
||||
case PollingReadMode::DISTRIBUTED_AND_RESULTANT_FORCE:
|
||||
return {true, true};
|
||||
}
|
||||
|
||||
CMVR_LOG(ERROR) << "Unsupported LegacyPX6AXGen3 polling read mode.";
|
||||
return {true, true};
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::clearOperationalError() {
|
||||
std::lock_guard<std::mutex> lock(lifecycle_mutex_);
|
||||
if (lifecycle_state_ == Status::INITIALIZED || lifecycle_state_ == Status::STREAMING) {
|
||||
last_error_.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::handleRefreshFailure(const std::string& error) {
|
||||
// Invalidate before any close/reconnect work. Keep the worker alive so a
|
||||
// subsequent valid transaction can restore service, but never expose old data.
|
||||
initializeSnapshot();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(lifecycle_mutex_);
|
||||
last_error_ = error;
|
||||
}
|
||||
closeConnection();
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::transitionTo(const Status next_state) {
|
||||
std::lock_guard<std::mutex> lock(lifecycle_mutex_);
|
||||
lifecycle_state_ = next_state;
|
||||
if (next_state == Status::INITIALIZED || next_state == Status::STREAMING) {
|
||||
last_error_.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void LegacyPX6AXGen3::enterFault(const std::string& error) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(lifecycle_mutex_);
|
||||
lifecycle_state_ = Status::FAULT;
|
||||
last_error_ = error;
|
||||
}
|
||||
|
||||
polling_thread_running_.store(false, std::memory_order_release);
|
||||
polling_cv_.notify_all();
|
||||
initializeSnapshot();
|
||||
closeConnection();
|
||||
|
||||
CMVR_LOG(ERROR) << error;
|
||||
}
|
||||
|
||||
bool LegacyPX6AXGen3::isOperationalState(const Status lifecycle) const {
|
||||
return lifecycle == Status::INITIALIZED || lifecycle == Status::STREAMING;
|
||||
}
|
||||
@ -0,0 +1,201 @@
|
||||
#include "../include/px_6ax_gen3.h"
|
||||
#include "hardware/include/posix_serial_transport.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
volatile std::sig_atomic_t interrupted = 0;
|
||||
void interrupt(int) { interrupted = 1; }
|
||||
|
||||
// Wrap the actual POSIX serial transport; optionally capture every transmitted
|
||||
// and received byte to diagnose framing/USB latency without a second reader.
|
||||
class TraceTransport final : public cmvr::AbstractSerialTransport {
|
||||
public:
|
||||
explicit TraceTransport(const std::string& path) {
|
||||
if (!path.empty()) {
|
||||
trace_.open(path);
|
||||
if (!trace_) throw std::runtime_error("Cannot open raw log: " + path);
|
||||
}
|
||||
}
|
||||
bool open(const Config& cfg) override { return serial_.open(cfg); }
|
||||
bool close() override { return serial_.close(); }
|
||||
bool isOpen() const override { return serial_.isOpen(); }
|
||||
bool flushInput() override { return serial_.flushInput(); }
|
||||
bool write(const std::vector<uint8_t>& data) override {
|
||||
// Only permit sensor read requests, even if driver defaults change.
|
||||
if (data.size() != 14 || data[6] != 0xFB) {
|
||||
throw std::runtime_error("Real test only permits force read commands.");
|
||||
}
|
||||
const bool ok = serial_.write(data);
|
||||
record(ok ? "TX" : "TX_FAILED", data);
|
||||
return ok;
|
||||
}
|
||||
bool read(size_t n, std::chrono::milliseconds timeout, std::vector<uint8_t>& data) override {
|
||||
const bool ok = serial_.read(n, timeout, data);
|
||||
record(ok ? "RX" : "RX_FAILED", data);
|
||||
return ok;
|
||||
}
|
||||
std::string lastError() const override { return serial_.lastError(); }
|
||||
private:
|
||||
void record(const char* direction, const std::vector<uint8_t>& data) {
|
||||
if (!trace_.is_open()) return;
|
||||
trace_ << std::fixed << std::setprecision(3)
|
||||
<< std::chrono::duration<double, std::milli>(Clock::now() - begin_).count()
|
||||
<< " ms " << direction;
|
||||
for (const auto byte : data) {
|
||||
trace_ << ' ' << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byte);
|
||||
}
|
||||
trace_ << std::dec << std::setfill(' ') << '\n';
|
||||
trace_.flush();
|
||||
}
|
||||
cmvr::PosixSerialTransport serial_;
|
||||
std::ofstream trace_;
|
||||
Clock::time_point begin_{Clock::now()};
|
||||
};
|
||||
|
||||
struct Options {
|
||||
std::string port{"/dev/ttyACM0"};
|
||||
std::string mode{"sync"};
|
||||
std::string csv;
|
||||
std::string raw_log;
|
||||
int module_id{2};
|
||||
int poll_ms{5};
|
||||
int max_age_ms{50};
|
||||
int timeout_ms{200};
|
||||
double duration_s{10.0};
|
||||
};
|
||||
|
||||
void usage() {
|
||||
std::cout << "Usage: px_6ax_gen3_real_test [--port /dev/ttyACM0] [--module-id 2]\n"
|
||||
" [--duration-s 10] [--mode sync|stream] [--poll-ms 5]\n"
|
||||
" [--max-age-ms 50] [--timeout-ms 200] [--csv samples.csv]\n"
|
||||
" [--raw-log frames.log]\n"
|
||||
"sync: each read sends a new force request; latency is request/response time.\n"
|
||||
"stream: exercise background polling and cached getters used by the task;\n"
|
||||
" getter counts include repeated samples, not sensor update frequency.\n"
|
||||
"Only reads the sensor. No calibration or robot commands. Ctrl-C stops.\n";
|
||||
}
|
||||
|
||||
Options parseOptions(int argc, char** argv) {
|
||||
Options o;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string arg = argv[i];
|
||||
if (arg == "--help") { usage(); std::exit(0); }
|
||||
if (++i >= argc) throw std::invalid_argument("Missing value for " + arg);
|
||||
const std::string value = argv[i];
|
||||
if (arg == "--port") o.port = value;
|
||||
else if (arg == "--mode") o.mode = value;
|
||||
else if (arg == "--module-id") o.module_id = std::stoi(value);
|
||||
else if (arg == "--duration-s") o.duration_s = std::stod(value);
|
||||
else if (arg == "--poll-ms") o.poll_ms = std::stoi(value);
|
||||
else if (arg == "--max-age-ms") o.max_age_ms = std::stoi(value);
|
||||
else if (arg == "--timeout-ms") o.timeout_ms = std::stoi(value);
|
||||
else if (arg == "--csv") o.csv = value;
|
||||
else if (arg == "--raw-log") o.raw_log = value;
|
||||
else throw std::invalid_argument("Unknown option: " + arg);
|
||||
}
|
||||
if ((o.mode != "sync" && o.mode != "stream") || !std::isfinite(o.duration_s) ||
|
||||
o.duration_s <= 0 || o.poll_ms <= 0 || o.max_age_ms <= 0 || o.timeout_ms <= 0) {
|
||||
throw std::invalid_argument("Invalid mode, duration or timing option");
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
double percentile(const std::vector<double>& sorted, double fraction) {
|
||||
return sorted.empty() ? 0.0 : sorted[static_cast<size_t>((sorted.size() - 1) * fraction)];
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
try {
|
||||
const auto options = parseOptions(argc, argv);
|
||||
std::signal(SIGINT, interrupt);
|
||||
std::signal(SIGTERM, interrupt);
|
||||
cmvr::config::LegacyPX6AXGen3 cfg;
|
||||
cfg.set_serial_port(options.port);
|
||||
cfg.set_module_id(options.module_id);
|
||||
cfg.set_baud_rate(921600);
|
||||
cfg.set_distributed_length(153);
|
||||
cfg.set_resultant_length(3);
|
||||
cfg.set_poll_interval_ms(options.poll_ms);
|
||||
cfg.set_response_timeout_ms(options.timeout_ms);
|
||||
cfg.set_max_sample_age_ms(options.max_age_ms);
|
||||
cfg.set_polling_read_mode(cmvr::config::LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE);
|
||||
cfg.set_auto_calibrate(false);
|
||||
cmvr::device::LegacyPX6AXGen3 sensor(cfg, std::make_unique<TraceTransport>(options.raw_log));
|
||||
std::ofstream csv;
|
||||
if (!options.csv.empty()) {
|
||||
csv.open(options.csv);
|
||||
if (!csv) throw std::runtime_error("Cannot open CSV: " + options.csv);
|
||||
csv << "elapsed_ms,read_ms,valid,fx_N,fy_N,fz_N\n";
|
||||
}
|
||||
std::cout << "port=" << options.port << " module_id=" << options.module_id
|
||||
<< " device_address=" << options.module_id + 1 << " mode=" << options.mode
|
||||
<< " max_sample_age_ms=" << options.max_age_ms << '\n';
|
||||
if (!sensor.init()) throw std::runtime_error("Sensor init failed: " + sensor.lastError());
|
||||
if (options.mode == "stream" && !sensor.start()) {
|
||||
throw std::runtime_error("Sensor start failed: " + sensor.lastError());
|
||||
}
|
||||
const auto begin = Clock::now();
|
||||
auto next = begin;
|
||||
auto next_print = begin;
|
||||
std::vector<double> durations;
|
||||
size_t failures = 0;
|
||||
double max_fz = 0.0;
|
||||
while (!interrupted && std::chrono::duration<double>(Clock::now() - begin).count() < options.duration_s) {
|
||||
const auto read_begin = Clock::now();
|
||||
cmvr::device::AbstractDexHand::ForceNewtons force;
|
||||
bool valid = true;
|
||||
std::string error;
|
||||
try {
|
||||
force = sensor.getResultantForceNewtons(cmvr::device::AbstractDexHand::FingerType::INDEX,
|
||||
cmvr::device::AbstractDexHand::TactileRegion::TIP);
|
||||
} catch (const std::exception& e) {
|
||||
valid = false;
|
||||
error = e.what();
|
||||
++failures;
|
||||
}
|
||||
const auto now = Clock::now();
|
||||
const double read_ms = std::chrono::duration<double, std::milli>(now - read_begin).count();
|
||||
const double elapsed_ms = std::chrono::duration<double, std::milli>(now - begin).count();
|
||||
if (valid) { durations.push_back(read_ms); max_fz = std::max(max_fz, force.fz); }
|
||||
if (csv.is_open()) {
|
||||
csv << std::fixed << std::setprecision(3) << elapsed_ms << ',' << read_ms << ',' << valid;
|
||||
if (valid) csv << ',' << force.fx << ',' << force.fy << ',' << force.fz;
|
||||
else csv << ",,,";
|
||||
csv << '\n';
|
||||
}
|
||||
if (now >= next_print) {
|
||||
std::cout << std::fixed << std::setprecision(3) << "t_ms=" << elapsed_ms
|
||||
<< " read_ms=" << read_ms;
|
||||
if (valid) std::cout << " force_N=[" << force.fx << ',' << force.fy << ',' << force.fz
|
||||
<< "] fz_N=" << force.fz;
|
||||
else std::cout << " UNAVAILABLE: " << error;
|
||||
std::cout << std::endl;
|
||||
next_print = now + std::chrono::milliseconds(100);
|
||||
}
|
||||
next += std::chrono::milliseconds(options.poll_ms);
|
||||
if (next < now) next = now;
|
||||
std::this_thread::sleep_until(next);
|
||||
}
|
||||
const double elapsed_s = std::chrono::duration<double>(Clock::now() - begin).count();
|
||||
sensor.stop();
|
||||
std::sort(durations.begin(), durations.end());
|
||||
std::cout << "SUMMARY mode=" << options.mode << " valid_reads=" << durations.size()
|
||||
<< " unavailable_reads=" << failures << " valid_reads_per_s=" << durations.size() / elapsed_s
|
||||
<< " p50_ms=" << percentile(durations, .5) << " p95_ms=" << percentile(durations, .95)
|
||||
<< " max_ms=" << percentile(durations, 1) << " max_fz_N=" << max_fz << '\n';
|
||||
return durations.empty() || failures != 0 ? 1 : 0;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << e.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
318
cmvr-es/devices/dexhand/px_6ax_gen3/src/px_6ax_gen3_test.cpp
Normal file
318
cmvr-es/devices/dexhand/px_6ax_gen3/src/px_6ax_gen3_test.cpp
Normal file
@ -0,0 +1,318 @@
|
||||
#include "../include/px_6ax_gen3.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
using Sensor = cmvr::device::LegacyPX6AXGen3;
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
void checksum(Bytes& frame) {
|
||||
unsigned sum = 0;
|
||||
for (size_t i = 0; i + 1 < frame.size(); ++i) sum += frame[i];
|
||||
frame.back() = static_cast<uint8_t>(-sum);
|
||||
}
|
||||
|
||||
Bytes reply(const Bytes& request) {
|
||||
const bool is_write = request[6] == 0x79;
|
||||
const size_t n = is_write ? 0U : request[11] | (size_t(request[12]) << 8U);
|
||||
Bytes frame{0xAA, 0x55, static_cast<uint8_t>((n + 10U) & 0xffU),
|
||||
static_cast<uint8_t>((n + 10U) >> 8U)};
|
||||
frame.insert(frame.end(), request.begin() + 4, request.begin() + 13);
|
||||
// Real device returns status=1 on reads; zero is only the write ACK status.
|
||||
frame.push_back(is_write ? 0 : 1);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
frame.push_back(i % 3U == 0 ? 0x80 : (i % 3U == 1 ? 0x7f : 10));
|
||||
}
|
||||
frame.push_back(0);
|
||||
checksum(frame);
|
||||
return frame;
|
||||
}
|
||||
|
||||
class ScriptedTransport final : public cmvr::AbstractSerialTransport {
|
||||
public:
|
||||
bool open(const Config&) override { opened = true; return true; }
|
||||
bool close() override { opened = false; return true; }
|
||||
bool isOpen() const override { return opened; }
|
||||
bool flushInput() override { pending.clear(); return true; }
|
||||
bool write(const Bytes& request) override {
|
||||
++writes;
|
||||
unsigned sum = 0;
|
||||
for (auto byte : request) sum += byte;
|
||||
EXPECT_EQ(sum % 256, 0U);
|
||||
pending = dropping.load() ? Bytes{} : make_reply(request);
|
||||
return true;
|
||||
}
|
||||
bool read(size_t, std::chrono::milliseconds timeout, Bytes& out) override {
|
||||
out.clear();
|
||||
if (pending.empty()) {
|
||||
waiting.store(true);
|
||||
std::this_thread::sleep_for(timeout);
|
||||
waiting.store(false);
|
||||
return false;
|
||||
}
|
||||
const size_t n = std::min(chunk_size, pending.size());
|
||||
out.assign(pending.begin(), pending.begin() + n);
|
||||
pending.erase(pending.begin(), pending.begin() + n);
|
||||
return true;
|
||||
}
|
||||
std::string lastError() const override { return "scripted timeout"; }
|
||||
std::function<Bytes(const Bytes&)> make_reply{reply};
|
||||
size_t chunk_size{256};
|
||||
std::atomic<int> writes{0};
|
||||
std::atomic<bool> dropping{false};
|
||||
std::atomic<bool> waiting{false};
|
||||
private:
|
||||
bool opened{false};
|
||||
Bytes pending;
|
||||
};
|
||||
|
||||
cmvr::config::LegacyPX6AXGen3 config() {
|
||||
cmvr::config::LegacyPX6AXGen3 cfg;
|
||||
cfg.set_serial_port("scripted");
|
||||
cfg.set_module_id(2);
|
||||
cfg.set_distributed_length(153);
|
||||
cfg.set_poll_interval_ms(5);
|
||||
cfg.set_response_timeout_ms(5);
|
||||
cfg.set_max_sample_age_ms(50);
|
||||
cfg.set_polling_read_mode(cmvr::config::LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE);
|
||||
return cfg;
|
||||
}
|
||||
|
||||
Sensor::ResultantForce force(Sensor& sensor) {
|
||||
return sensor.getResultantForce(Sensor::FingerType::INDEX, Sensor::TactileRegion::TIP);
|
||||
}
|
||||
|
||||
Sensor::ForceNewtons forceNewtons(cmvr::device::AbstractDexHand& sensor) {
|
||||
return sensor.getResultantForceNewtons(Sensor::FingerType::INDEX, Sensor::TactileRegion::TIP);
|
||||
}
|
||||
|
||||
bool waitFor(const std::function<bool()>& predicate) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + 1s;
|
||||
do {
|
||||
if (predicate()) return true;
|
||||
std::this_thread::sleep_for(1ms);
|
||||
} while (std::chrono::steady_clock::now() < deadline);
|
||||
return predicate();
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, ParsesRealReadStatusAndSignedForcesAcrossByteFragments) {
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
serial->chunk_size = 1;
|
||||
Sensor sensor(config(), std::move(serial));
|
||||
ASSERT_TRUE(sensor.init());
|
||||
const auto f = force(sensor);
|
||||
EXPECT_EQ(f.fx, -128);
|
||||
EXPECT_EQ(f.fy, 127);
|
||||
EXPECT_EQ(f.fz, 10);
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, NewtonInterfacePreservesSignsAndComputesPhysicalMagnitude) {
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
auto* transport = serial.get();
|
||||
serial->make_reply = [](const Bytes& request) {
|
||||
auto frame = reply(request);
|
||||
frame[14] = 0xfd; // -3 raw = -0.3 N
|
||||
frame[15] = 4;
|
||||
frame[16] = 12;
|
||||
checksum(frame);
|
||||
return frame;
|
||||
};
|
||||
Sensor sensor(config(), std::move(serial));
|
||||
ASSERT_TRUE(sensor.init());
|
||||
const auto writes_before = transport->writes.load();
|
||||
const auto f = forceNewtons(sensor);
|
||||
EXPECT_EQ(transport->writes.load(), writes_before + 1);
|
||||
EXPECT_DOUBLE_EQ(f.fx, -0.3);
|
||||
EXPECT_DOUBLE_EQ(f.fy, 0.4);
|
||||
EXPECT_DOUBLE_EQ(f.fz, 1.2);
|
||||
EXPECT_DOUBLE_EQ(f.magnitude(), 1.3);
|
||||
EXPECT_EQ(force(sensor).fz, 12); // Raw interface remains unchanged.
|
||||
}
|
||||
|
||||
class NewtonForce : public testing::TestWithParam<int> {};
|
||||
TEST_P(NewtonForce, ConvertsRawFzOnceAndPreservesPointOneNewtonTrigger) {
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
const int raw_fz = GetParam();
|
||||
serial->make_reply = [raw_fz](const Bytes& request) {
|
||||
auto frame = reply(request);
|
||||
frame[14] = 0;
|
||||
frame[15] = 0;
|
||||
frame[16] = static_cast<uint8_t>(raw_fz);
|
||||
checksum(frame);
|
||||
return frame;
|
||||
};
|
||||
Sensor sensor(config(), std::move(serial));
|
||||
ASSERT_TRUE(sensor.init());
|
||||
const auto f = forceNewtons(sensor);
|
||||
EXPECT_DOUBLE_EQ(f.fz, static_cast<double>(raw_fz) / 10.0);
|
||||
EXPECT_DOUBLE_EQ(f.magnitude(), f.fz);
|
||||
EXPECT_EQ(f.fz >= 0.1, raw_fz >= 1);
|
||||
EXPECT_EQ(force(sensor).fz, raw_fz);
|
||||
}
|
||||
INSTANTIATE_TEST_SUITE_P(PhysicalUnits, NewtonForce, testing::Values(0, 1, 10, 108, 255));
|
||||
|
||||
TEST(LegacyPX6AXGen3, ResynchronizesAfterEchoNoiseAndInvalidFrame) {
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
serial->chunk_size = 7;
|
||||
serial->make_reply = [](const Bytes& request) {
|
||||
auto bad = reply(request);
|
||||
bad.back() ^= 1;
|
||||
Bytes frames{0xAA, 0x00};
|
||||
frames.insert(frames.end(), request.begin(), request.end());
|
||||
frames.insert(frames.end(), bad.begin(), bad.end());
|
||||
const auto valid = reply(request);
|
||||
frames.insert(frames.end(), valid.begin(), valid.end());
|
||||
return frames;
|
||||
};
|
||||
Sensor sensor(config(), std::move(serial));
|
||||
ASSERT_TRUE(sensor.init());
|
||||
EXPECT_EQ(force(sensor).fz, 10);
|
||||
}
|
||||
|
||||
class InvalidFrame : public testing::TestWithParam<int> {};
|
||||
TEST_P(InvalidFrame, RejectsResponseAndFailsInitializationAfterRetries) {
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
auto* transport = serial.get();
|
||||
const int kind = GetParam();
|
||||
serial->make_reply = [kind](const Bytes& request) {
|
||||
auto frame = reply(request);
|
||||
if (kind == 0) { frame.pop_back(); return frame; } // missing LRC
|
||||
if (kind == 1) { frame.back() ^= 1; return frame; } // bad LRC
|
||||
// Frame size, device, reserved, function, register, returned byte count.
|
||||
const int offsets[]{2, 4, 5, 6, 7, 11};
|
||||
frame[offsets[kind - 2]] ^= 1;
|
||||
checksum(frame); // Valid LRC must not bypass request matching.
|
||||
return frame;
|
||||
};
|
||||
Sensor sensor(config(), std::move(serial));
|
||||
EXPECT_FALSE(sensor.init());
|
||||
EXPECT_EQ(transport->writes.load(), 5);
|
||||
EXPECT_EQ(sensor.state(), Sensor::Status::FAULT);
|
||||
EXPECT_FALSE(sensor.lastError().empty());
|
||||
EXPECT_THROW(force(sensor), std::runtime_error);
|
||||
}
|
||||
INSTANTIATE_TEST_SUITE_P(ProtocolValidation, InvalidFrame, testing::Range(0, 8));
|
||||
|
||||
TEST(LegacyPX6AXGen3, RetriesTransientStartupFailure) {
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
int count = 0;
|
||||
serial->make_reply = [&count](const Bytes& request) {
|
||||
++count;
|
||||
return count < 3 ? Bytes{} : reply(request);
|
||||
};
|
||||
Sensor sensor(config(), std::move(serial));
|
||||
ASSERT_TRUE(sensor.init());
|
||||
EXPECT_EQ(count, 3);
|
||||
EXPECT_TRUE(sensor.lastError().empty());
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, StaleGetterFailsWithoutWaitingForSerialAndRecovers) {
|
||||
auto cfg = config();
|
||||
cfg.set_response_timeout_ms(200);
|
||||
cfg.set_max_sample_age_ms(30);
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
auto* transport = serial.get();
|
||||
Sensor sensor(cfg, std::move(serial));
|
||||
ASSERT_TRUE(sensor.init());
|
||||
ASSERT_TRUE(sensor.start());
|
||||
ASSERT_EQ(force(sensor).fz, 10);
|
||||
transport->dropping.store(true);
|
||||
ASSERT_TRUE(waitFor([&] { return transport->waiting.load(); }));
|
||||
std::this_thread::sleep_for(40ms);
|
||||
const auto begin = std::chrono::steady_clock::now();
|
||||
EXPECT_THROW(force(sensor), std::runtime_error);
|
||||
EXPECT_THROW(forceNewtons(sensor), std::runtime_error);
|
||||
EXPECT_LT(std::chrono::steady_clock::now() - begin, 50ms);
|
||||
cmvr::device::DexHandState state;
|
||||
sensor.getState(state);
|
||||
EXPECT_FALSE(state.is_initialized);
|
||||
EXPECT_FALSE(state.hands[0].error_message.empty());
|
||||
transport->dropping.store(false);
|
||||
ASSERT_TRUE(waitFor([&] {
|
||||
try { return force(sensor).fz == 10; }
|
||||
catch (const std::exception&) { return false; }
|
||||
}));
|
||||
sensor.stop();
|
||||
const auto writes = transport->writes.load();
|
||||
EXPECT_THROW(force(sensor), std::runtime_error);
|
||||
EXPECT_THROW(forceNewtons(sensor), std::runtime_error);
|
||||
EXPECT_EQ(transport->writes.load(), writes);
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, ReadFailureInvalidatesPreviouslyValidSample) {
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
auto* transport = serial.get();
|
||||
Sensor sensor(config(), std::move(serial));
|
||||
ASSERT_TRUE(sensor.init());
|
||||
transport->dropping.store(true);
|
||||
EXPECT_THROW(force(sensor), std::runtime_error);
|
||||
cmvr::device::DexHandState state;
|
||||
sensor.getState(state);
|
||||
EXPECT_FALSE(state.is_initialized);
|
||||
transport->dropping.store(false);
|
||||
EXPECT_EQ(force(sensor).fz, 10);
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, RejectsLateResponseEvenWithValidChecksum) {
|
||||
auto cfg = config();
|
||||
cfg.set_max_sample_age_ms(2);
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
serial->make_reply = [](const Bytes& request) {
|
||||
std::this_thread::sleep_for(5ms);
|
||||
return reply(request);
|
||||
};
|
||||
Sensor sensor(cfg, std::move(serial));
|
||||
EXPECT_FALSE(sensor.init());
|
||||
EXPECT_NE(sensor.lastError().find("too late"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, DistributedDataIsValidatedAndParsed) {
|
||||
auto cfg = config();
|
||||
cfg.set_polling_read_mode(cmvr::config::LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE);
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
serial->chunk_size = 5;
|
||||
Sensor sensor(cfg, std::move(serial));
|
||||
ASSERT_TRUE(sensor.init());
|
||||
auto data = sensor.getSensorData(Sensor::FingerType::INDEX, Sensor::TactileRegion::TIP);
|
||||
ASSERT_TRUE(data.valid());
|
||||
ASSERT_EQ(data.view.pointCount(), 51);
|
||||
EXPECT_EQ(data.view.at(0, 50).fx, -128);
|
||||
EXPECT_EQ(data.view.at(0, 50).fz, 10);
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, CalibrationRequiresFullSuccessfulWriteAcknowledgment) {
|
||||
auto cfg = config();
|
||||
cfg.set_auto_calibrate(true);
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
serial->make_reply = [](const Bytes& request) {
|
||||
if (request[6] == 0x79) return Bytes{0xAA, 0x55};
|
||||
return reply(request);
|
||||
};
|
||||
Sensor sensor(cfg, std::move(serial));
|
||||
EXPECT_FALSE(sensor.init());
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, CalibrationAcceptsFullWriteAcknowledgment) {
|
||||
auto cfg = config();
|
||||
cfg.set_auto_calibrate(true);
|
||||
Sensor sensor(cfg, std::make_unique<ScriptedTransport>());
|
||||
ASSERT_TRUE(sensor.init());
|
||||
EXPECT_EQ(force(sensor).fz, 10);
|
||||
}
|
||||
|
||||
TEST(LegacyPX6AXGen3, InvalidConfigurationCannotBeResurrectedByInitOrStart) {
|
||||
auto cfg = config();
|
||||
cfg.set_response_header_bytes(15);
|
||||
auto serial = std::make_unique<ScriptedTransport>();
|
||||
auto* transport = serial.get();
|
||||
Sensor sensor(cfg, std::move(serial));
|
||||
EXPECT_FALSE(sensor.init());
|
||||
EXPECT_FALSE(sensor.start());
|
||||
EXPECT_EQ(transport->writes.load(), 0);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,13 @@
|
||||
add_library(zero_sim_touch_dexhand SHARED src/zero_sim_touch_dexhand.cpp)
|
||||
|
||||
target_include_directories(zero_sim_touch_dexhand PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
add_library(cmvr_es::device::zero_sim_touch_dexhand ALIAS zero_sim_touch_dexhand)
|
||||
|
||||
target_link_libraries(zero_sim_touch_dexhand
|
||||
PRIVATE
|
||||
cmvr_es::proto
|
||||
glog
|
||||
)
|
||||
|
||||
install(TARGETS zero_sim_touch_dexhand LIBRARY DESTINATION lib)
|
||||
@ -0,0 +1,58 @@
|
||||
#ifndef CMVR_ES_ZERO_SIM_TOUCH_DEXHAND_H
|
||||
#define CMVR_ES_ZERO_SIM_TOUCH_DEXHAND_H
|
||||
|
||||
#include <array>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "cmvr/config/dexhand_config/dexhand_config.pb.h"
|
||||
#include "../../abstract_dexhand.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class ZeroSimTouchDexHand final : public AbstractDexHand {
|
||||
public:
|
||||
using FingerType = AbstractDexHand::FingerType;
|
||||
using ResultantForce = AbstractDexHand::ResultantForce;
|
||||
using TactilePoint = AbstractDexHand::TactilePoint;
|
||||
using TactileRegion = AbstractDexHand::TactileRegion;
|
||||
using TactileRegionKey = AbstractDexHand::TactileRegionKey;
|
||||
using TactileRegionData = AbstractDexHand::TactileRegionData;
|
||||
using Status = AbstractDexHand::Status;
|
||||
|
||||
explicit ZeroSimTouchDexHand(const config::ZeroSimTouchDexHand& cfg);
|
||||
~ZeroSimTouchDexHand() override = default;
|
||||
|
||||
std::string typeName() const override { return "ZeroSimTouchDexHand"; }
|
||||
bool init() override;
|
||||
bool start() override;
|
||||
bool stop() override;
|
||||
|
||||
Status state() const override;
|
||||
std::string lastError() const override;
|
||||
void getState(DexHandState& state) override;
|
||||
|
||||
void setAngles(const std::vector<int>& finger_joint_angles) override;
|
||||
void setTactilePollingRegions(const std::vector<TactileRegionKey>& regions) override;
|
||||
std::vector<TactileRegionData> getSensorData() override;
|
||||
TactileRegionData getSensorData(FingerType finger, TactileRegion region) override;
|
||||
ResultantForce getResultantForce(FingerType finger, TactileRegion region) override;
|
||||
ForceNewtons getResultantForceNewtons(FingerType finger, TactileRegion region) override;
|
||||
|
||||
private:
|
||||
TactileRegionData makeRegionData(FingerType finger, TactileRegion region);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<TactileRegionKey> polling_regions_;
|
||||
std::array<TactilePoint, 1> tactile_points_{};
|
||||
Status lifecycle_state_{Status::CREATED};
|
||||
std::string last_error_;
|
||||
};
|
||||
|
||||
// Keep the historical spelling available to callers that used the test double.
|
||||
using ZeroSImTouchDexHand = ZeroSimTouchDexHand;
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_ZERO_SIM_TOUCH_DEXHAND_H
|
||||
@ -0,0 +1,101 @@
|
||||
#include "../include/zero_sim_touch_dexhand.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
ZeroSimTouchDexHand::ZeroSimTouchDexHand(const config::ZeroSimTouchDexHand& cfg) {
|
||||
id_ = cfg.id();
|
||||
}
|
||||
|
||||
bool ZeroSimTouchDexHand::init() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
lifecycle_state_ = Status::STREAMING;
|
||||
last_error_.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ZeroSimTouchDexHand::start() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
lifecycle_state_ = Status::STREAMING;
|
||||
last_error_.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ZeroSimTouchDexHand::stop() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
lifecycle_state_ = Status::STOPPED;
|
||||
return true;
|
||||
}
|
||||
|
||||
ZeroSimTouchDexHand::Status ZeroSimTouchDexHand::state() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return lifecycle_state_;
|
||||
}
|
||||
|
||||
std::string ZeroSimTouchDexHand::lastError() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return last_error_;
|
||||
}
|
||||
|
||||
void ZeroSimTouchDexHand::getState(DexHandState& state) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
state = DexHandState{};
|
||||
state.is_initialized = lifecycle_state_ == Status::INITIALIZED ||
|
||||
lifecycle_state_ == Status::STREAMING;
|
||||
if (!last_error_.empty()) {
|
||||
state.hands[0].error_message.push_back(last_error_);
|
||||
}
|
||||
}
|
||||
|
||||
void ZeroSimTouchDexHand::setAngles(const std::vector<int>&) {
|
||||
// The simulation has no finger actuators; commands are intentionally ignored.
|
||||
}
|
||||
|
||||
void ZeroSimTouchDexHand::setTactilePollingRegions(
|
||||
const std::vector<TactileRegionKey>& regions) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
polling_regions_ = regions;
|
||||
}
|
||||
|
||||
std::vector<ZeroSimTouchDexHand::TactileRegionData> ZeroSimTouchDexHand::getSensorData() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (polling_regions_.empty()) {
|
||||
polling_regions_.push_back({FingerType::INDEX, TactileRegion::TIP});
|
||||
}
|
||||
|
||||
std::vector<TactileRegionData> data;
|
||||
data.reserve(polling_regions_.size());
|
||||
for (const auto& region : polling_regions_) {
|
||||
data.push_back(makeRegionData(region.first, region.second));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
ZeroSimTouchDexHand::TactileRegionData ZeroSimTouchDexHand::getSensorData(
|
||||
const FingerType finger, const TactileRegion region) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return makeRegionData(finger, region);
|
||||
}
|
||||
|
||||
ZeroSimTouchDexHand::ResultantForce ZeroSimTouchDexHand::getResultantForce(
|
||||
const FingerType, const TactileRegion) {
|
||||
return TactilePoint::fromFz(0);
|
||||
}
|
||||
|
||||
ZeroSimTouchDexHand::ForceNewtons ZeroSimTouchDexHand::getResultantForceNewtons(
|
||||
const FingerType, const TactileRegion) {
|
||||
return {};
|
||||
}
|
||||
|
||||
ZeroSimTouchDexHand::TactileRegionData ZeroSimTouchDexHand::makeRegionData(
|
||||
const FingerType finger, const TactileRegion region) {
|
||||
tactile_points_[0] = TactilePoint::fromFz(0);
|
||||
TactileMatrixView view;
|
||||
view.data = tactile_points_.data();
|
||||
view.rows = 1;
|
||||
view.cols = 1;
|
||||
return {finger, region, view, "mujoco_touch_tip"};
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -17,4 +17,5 @@ add_subdirectory(drivers/ti5_canopen)
|
||||
add_subdirectory(drivers/mujoco)
|
||||
add_subdirectory(bus_runtime)
|
||||
add_subdirectory(drivers/ethercat_motor)
|
||||
add_subdirectory(drivers/lingkong_can)
|
||||
add_subdirectory(manager)
|
||||
|
||||
@ -6,6 +6,7 @@
|
||||
#define CMVR_ES_ABSTRACT_MOTOR_H
|
||||
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
#include "devices/abstract_device.h"
|
||||
#include "common/base/logging/logger.h"
|
||||
@ -202,6 +203,9 @@ namespace cmvr::device{
|
||||
return protocol_->getQd(node_id_);
|
||||
}
|
||||
|
||||
// Keep the existing arm-current telemetry contract alongside torque.
|
||||
virtual std::int16_t getCurrent() { return 0; }
|
||||
|
||||
// Per mille of rated torque; NaN when unavailable.
|
||||
virtual double getTau() {
|
||||
std::scoped_lock lock(mtx_);
|
||||
@ -235,6 +239,17 @@ namespace cmvr::device{
|
||||
std::scoped_lock lock(mtx_);
|
||||
return info_;
|
||||
}
|
||||
// Optional diagnostic status; unsupported drivers must not report a fake zero.
|
||||
virtual bool readDriveStatus(std::uint16_t&, std::uint16_t&) { return false; }
|
||||
// Default CiA402 interpretation; non-CiA402 drivers override using their
|
||||
// real native status, rather than fabricating a CiA402 status word.
|
||||
virtual bool readDiagnosticState(std::uint16_t& status, std::uint16_t& error,
|
||||
bool& enabled, bool& fault) {
|
||||
if (!readDriveStatus(status, error)) return false;
|
||||
enabled = (status & 0x006f) == 0x0027;
|
||||
fault = (status & 0x0008) != 0;
|
||||
return true;
|
||||
}
|
||||
protected:
|
||||
mutable std::mutex mtx_;
|
||||
MotorInfo info_{};
|
||||
|
||||
@ -27,6 +27,7 @@ public:
|
||||
void stop() override;
|
||||
config::MotorBusType busType() const override { return config::MOTOR_BUS_CAN; }
|
||||
|
||||
std::shared_ptr<AbstractCanbus> client() const { return client_; }
|
||||
const std::string& id() const { return id_; }
|
||||
std::shared_ptr<CanSender<msgs::RobotDetail>> sender() const { return sender_; }
|
||||
std::shared_ptr<MessageManager<msgs::RobotDetail>> messageManager() const { return message_manager_; }
|
||||
|
||||
19
cmvr-es/devices/motor/drivers/lingkong_can/CMakeLists.txt
Normal file
19
cmvr-es/devices/motor/drivers/lingkong_can/CMakeLists.txt
Normal file
@ -0,0 +1,19 @@
|
||||
add_library(lingkong_can_motor_driver SHARED
|
||||
src/protocol/lingkong_motor_request.cpp
|
||||
src/protocol/lingkong_motor_response.cpp
|
||||
src/lingkong_can_protocol.cpp
|
||||
src/lingkong_motor.cpp
|
||||
)
|
||||
target_include_directories(lingkong_can_motor_driver PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
target_link_libraries(lingkong_can_motor_driver
|
||||
PUBLIC cmvr_es::device::motor_core
|
||||
PRIVATE cmvr_es::device::canbus cmvr_es::proto glog pthread
|
||||
)
|
||||
add_library(cmvr_es::device::lingkong_can_motor_driver ALIAS lingkong_can_motor_driver)
|
||||
install(TARGETS lingkong_can_motor_driver LIBRARY DESTINATION lib)
|
||||
|
||||
# Fake transport only: these tests never open CAN or send commands to hardware.
|
||||
add_executable(lingkong_motor_protocol_test tests/lingkong_motor_protocol_test.cpp)
|
||||
target_link_libraries(lingkong_motor_protocol_test PRIVATE
|
||||
cmvr_es::device::lingkong_can_motor_driver
|
||||
cmvr_es::device::canbus gtest gtest_main pthread glog)
|
||||
24
cmvr-es/devices/motor/drivers/lingkong_can/MANUAL_AUDIT.md
Normal file
24
cmvr-es/devices/motor/drivers/lingkong_can/MANUAL_AUDIT.md
Normal file
@ -0,0 +1,24 @@
|
||||
# In-use command audit: supplied V2.36 and V2.38 manuals
|
||||
|
||||
Scope: all commands emitted by LingkongCanProtocol, response correlation, diagnostics, and group shutdown. Unused calibration/reset commands are deliberately not added.
|
||||
|
||||
| Commands | V2.36 | V2.38 | Implementation |
|
||||
| --- | --- | --- | --- |
|
||||
| CAN framing | Standard ID 0x140+node; 8 bytes, LE | Same | Shared request/response transport |
|
||||
| 80 / 88 | Echo acknowledgement; OFF=10, ON=00 | Echo acknowledgement; OFF=20, ON=30 | Verify 9A using selected version, never treat ACK as motion completion |
|
||||
| 81 | Stop, without closing | Stop, preserves prior control state | Group all-zero stop uses 81 on every axis, including already-OFF drives; exceptions/failures cannot bypass later axes |
|
||||
| 8C | Byte 1 brake command/state | Same | Shared release command and response matching |
|
||||
| 9A / 9B | Byte 6 state, byte 7 8-bit error; bus voltage/current 0.01 | State=byte6 high nibble; error=byte6 low nibble + byte7, 12 bits; manual says mV/mA | Selected scaling, full error checks, ERROR state blocks initialization even with zero error bits |
|
||||
| 9C | int16 Iq, int16 speed in dps | Same layout; Iq A/LSB unspecified | Signed feedback; explicit current conversion only |
|
||||
| 92 | Signed 56-bit payload, 0.01 degree | Same | Sign extend bit 55, use configured gear ratio |
|
||||
| A1 | int16 Iq bytes4..5, documented +/-2048 | int16 Iq same bytes; no physical conversion/range stated | Signed frame and explicit rated-current/Iq conversion; retain existing conservative +/-2048 software bound (do not expand physical outputs based on field width) |
|
||||
| A2 | Bytes2..3 NULL, speed int32 bytes4..7 in 0.01dps | Bytes2..3 torque limit int16, speed unchanged | V2.38 reads C0/30 limit and embeds it; old path leaves NULL |
|
||||
| A3 / A4 | int32 multi-turn target in 0.01 degree; A4 uint16 speed dps | Same | Shared position conversion/range/limit checks; A4 current-position hold on enable |
|
||||
| B0/B1 vs C0/C1 | Scalar indices10 torque,12 acceleration,14 speed | Scalar30 torque,32 speed,34 angle,36 current ramp,38 speed ramp; PID triplets10/11/12 | Versioned command/index/width/range checks; parameter reply index matching; scalar API rejects PID triplets |
|
||||
| Speed limit API | B1/14, explicit unit conversion | C1/32, 0.01 dps | Versioned native speed conversion |
|
||||
| Acceleration API | B1/12, units not specified | C1/38 ramp, physical units not specified | Requires explicit confirmed conversion; never send V2.38 PID index12 as acceleration; profile qdd retains drive settings as before |
|
||||
| 19 permanent zero | uint16 offset bytes6..7; repower explicitly required | uint32 offset bytes4..7; encoder type in byte3 (manual gives 0 for single encoder; observed type1 is preserved and accepted); activation timing unspecified | Unsigned decode, version-specific log; ACK only, no immediate position readback, automatic reboot, or zero writes during init |
|
||||
|
||||
Protocol selection remains the EXISTING group `protocol` field: MOTOR_PROTOCOL_LINGKONG_CAN or MOTOR_PROTOCOL_LINGKONG_CAN_V2_38. No new configuration fields. The old enum now selects strict V2.36 ON=00/OFF=10, replacing the earlier permissive site policy. The permissive historical mode has been removed. V2.38 production selection is strict ON=30/OFF=20 and rejects INIT/ERROR/CALIBRATION as enabled. Never select a protocol by voltage or model label alone.
|
||||
|
||||
Unresolved manual/firmware facts: V2.38 manual specifies millivolts, while previously captured approximately 48V device samples (raw about 4800) would decode as approximately 4.8V under that specification. The implementation follows the supplied document without silent rescaling. Confirm this discrepancy with the drive vendor before relying on voltage telemetry. Iq A/LSB and speed-ramp physical units also require firmware-specific confirmation; no default conversion is invented. No hardware motion or ROM writes are used for this audit.
|
||||
@ -0,0 +1,8 @@
|
||||
# Lingkong CAN protocol versions
|
||||
Existing configuration files remain unchanged. Use the existing group `protocol` field: `MOTOR_PROTOCOL_LINGKONG_CAN` selects strict V2.36 behavior; `MOTOR_PROTOCOL_LINGKONG_CAN_V2_38` selects V2.38. No new configuration fields. Mixed versions use distinct motor groups with the same CAN device/channel and unique motor IDs. Both production selections use the documented version-specific states. V2_36: ON=0x00, OFF=0x10. V2_38: ON=0x30, OFF=0x20, INIT/ERROR/CALIBRATION never count as enabled; 12-bit errors include the low nibble of byte 6. Diagnostics preserve the state in its high-nibble representation.
|
||||
|
||||
V2_38 status voltage/current follow the supplied manual units mV/mA (0.001). Earlier observed firmware used different scaling; verify actual firmware against the manual before relying on telemetry.
|
||||
|
||||
Scalar parameter API takes native indices: V2_36 B0/B1 10/12/14; V2_38 C0/C1 30/32/34/36/38. V2_38 PID triplets 10/11/12 are rejected by the scalar API. setLimitQd uses C1/32 with 0.01 dps units. Acceleration uses C1/38 ONLY with an explicitly confirmed acceleration_deg_s2_per_lsb conversion; the supplied V2.38 manual does not define ramp physical units. Profile motion retains drive acceleration as before. Current/Iq conversion remains explicitly configured because V2.38 does not specify its A/LSB conversion. A1/A3/A4 motion and 92 angle layouts are shared. A2 speed units are shared, but V2.38 adds a torque limit, which is read from C0/30 and included in the command.
|
||||
|
||||
Permanent zero uses 19 in both versions, no immediate position readback, reboot or motion. Reply zero-offset bytes are 6..7 in V2.36 and 4..7 in V2.38. Restart/power-cycle requirements follow the drive firmware. No automatic protocol probing or firmware writes are performed.
|
||||
@ -0,0 +1,107 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
#include "canbus/abstract_canbus.h"
|
||||
#include "canbus/can_comm/message_manager.h"
|
||||
#include "cmvr/config/motor_config/motor_config.pb.h"
|
||||
#include "cmvr/msgs/robot_detail.pb.h"
|
||||
#include "motor/motor_protocol_interface.h"
|
||||
#include "motor/drivers/lingkong_can/include/protocol/lingkong_motor_response.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class LingkongCanProtocol final : public MotorProtocolInterface {
|
||||
public:
|
||||
using Payload = motor::LingkongMotorRequest::Payload;
|
||||
using Send = std::function<bool(const CanFrame&)>;
|
||||
enum ProtocolVersion { V2_36 = 1, V2_38 = 2 };
|
||||
struct Status {
|
||||
double temperature{0}, voltage{0}, bus_current{0};
|
||||
uint8_t motor_state{0};
|
||||
uint16_t error{0};
|
||||
ProtocolVersion protocol_version{V2_36};
|
||||
bool isClosed() const {
|
||||
return motor_state == (protocol_version == V2_38 ? 0x20 : 0x10) && error == 0;
|
||||
}
|
||||
bool isFault() const {
|
||||
return error != 0 || (protocol_version == V2_38 && motor_state == 0x10);
|
||||
}
|
||||
// Explicitly selected protocol defines the enabled state; faults block motion.
|
||||
// Preserve raw state/error bytes for diagnostics.
|
||||
bool isRunning() const {
|
||||
if (protocol_version == V2_38) return motor_state == 0x30 && error == 0;
|
||||
if (protocol_version == V2_36) return motor_state == 0x00 && error == 0;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
LingkongCanProtocol(Send send, std::shared_ptr<MessageManager<msgs::RobotDetail>> manager, ProtocolVersion version = V2_36);
|
||||
bool initNode(uint8_t node_id) override;
|
||||
bool configureNode(uint8_t node_id, const config::MotorConfigItem& config);
|
||||
bool probe(uint8_t node_id);
|
||||
// Compatibility selection only: no standalone native mode command exists.
|
||||
// Native protocol has no mode readback: getMode returns UNSPECIFIED.
|
||||
// A* commands still select the native loop when an explicit target is sent.
|
||||
bool setMode(uint8_t node_id, msgs::RunMode mode) override;
|
||||
msgs::RunMode getMode(uint8_t node_id) override;
|
||||
void setMotorConversion(uint8_t node_id, double counts, double gear_ratio) override;
|
||||
bool setLimitQ(uint8_t node_id, double upper, double lower);
|
||||
bool setLimitQd(uint8_t node_id, double value);
|
||||
void setLimitQdd(uint8_t node_id, double upper, double lower) override;
|
||||
// Open and capture/hold the current position; roll back to closed on failure.
|
||||
bool torqueOn(uint8_t node_id) override;
|
||||
bool torqueOff(uint8_t node_id) override;
|
||||
// Native stop command has no configurable deceleration argument.
|
||||
bool quickStop(uint8_t node_id, double deceleration = 5.0) override;
|
||||
bool brakeRelease(uint8_t node_id);
|
||||
// Explicit API writes permanent zero via 0x19; initialization never writes ROM.
|
||||
bool calibrateZeroQ(uint8_t node_id);
|
||||
bool reachedTargetQ(uint8_t node_id) override;
|
||||
double getQ(uint8_t node_id) override;
|
||||
double getQd(uint8_t node_id) override;
|
||||
double getTau(uint8_t node_id) override;
|
||||
bool readFeedback(uint8_t node_id, double& q, double& qd);
|
||||
bool readStatus(uint8_t node_id, Status& status);
|
||||
bool readCurrent(uint8_t node_id, double& amps);
|
||||
bool commandProfilePosition(uint8_t node_id, double q, double qd, double qdd) override;
|
||||
bool commandProfileVelocity(uint8_t node_id, double qd, double qdd) override;
|
||||
// Vendor setpoints, NOT synchronized CiA402 PDOs; no host trajectory planner.
|
||||
bool commandCyclicPosition(uint8_t node_id, double q, double qd) override;
|
||||
bool commandCyclicVelocity(uint8_t node_id, double qd) override;
|
||||
bool commandCyclicTorque(uint8_t node_id, double tau) override;
|
||||
// B0/B1 raw values, kept explicit because parameter units are firmware-specific.
|
||||
bool readControlParameter(uint8_t node_id, uint8_t index, int32_t& value);
|
||||
bool writeControlParameter(uint8_t node_id, uint8_t index, int32_t value);
|
||||
bool clearError(uint8_t node_id);
|
||||
private:
|
||||
struct Node {
|
||||
motor::LingkongMotorResponse* response{nullptr};
|
||||
config::MotorConfigItem config;
|
||||
double target_q{0};
|
||||
bool target_valid{false};
|
||||
};
|
||||
bool exchange(uint8_t node_id, const Payload& request, Payload& response);
|
||||
bool simple(uint8_t node_id, uint8_t command);
|
||||
void requireRunning(uint8_t node_id);
|
||||
bool position(uint8_t node_id, double q, double qd);
|
||||
bool velocity(uint8_t node_id, double qd);
|
||||
bool acceleration(uint8_t node_id, double qdd);
|
||||
bool parameter(uint8_t node_id, uint8_t command, uint8_t index, int32_t& value);
|
||||
double scale(uint8_t node_id) const;
|
||||
static int64_t signedLe(const uint8_t* data, unsigned bytes);
|
||||
static void putLe(Payload& data, unsigned offset, uint32_t value, unsigned bytes);
|
||||
static bool toInt32(double value, int32_t& raw);
|
||||
Node* node(uint8_t node_id);
|
||||
ProtocolVersion version_;
|
||||
Send send_;
|
||||
std::shared_ptr<MessageManager<msgs::RobotDetail>> manager_;
|
||||
std::map<uint8_t, Node> nodes_;
|
||||
// Serializes complete transactions, including multi-frame parameter+command
|
||||
// operations. No retries: the wire protocol has no transaction sequence ID.
|
||||
mutable std::recursive_mutex mutex_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "motor/abstract_motor.h"
|
||||
#include "lingkong_can_protocol.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class LingkongMotor final : public AbstractMotor {
|
||||
public:
|
||||
explicit LingkongMotor(const config::MotorConfigItem& config);
|
||||
std::string typeName() const override { return "LingkongMotor"; }
|
||||
bool init() override;
|
||||
bool setLimitQ(double upper, double lower) override;
|
||||
bool setLimitQd(double value) override;
|
||||
void setLimitQdd(double upper, double lower) override;
|
||||
bool brakeRelease() override;
|
||||
bool calibrateZeroQ() override;
|
||||
bool readDiagnosticState(std::uint16_t& status, std::uint16_t& error,
|
||||
bool& enabled, bool& fault) override;
|
||||
bool readFeedback(double& q, double& qd);
|
||||
bool readCurrent(double& amps);
|
||||
private:
|
||||
std::shared_ptr<LingkongCanProtocol> nativeProtocol() const;
|
||||
config::MotorConfigItem config_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include "canbus/abstract_canbus.h"
|
||||
#include "canbus/can_comm/protocol_data.h"
|
||||
#include "cmvr/msgs/robot_detail.pb.h"
|
||||
|
||||
namespace cmvr::device::motor {
|
||||
|
||||
class LingkongMotorRequest final : public ProtocolData<msgs::RobotDetail> {
|
||||
public:
|
||||
using Payload = std::array<uint8_t, 8>;
|
||||
static constexpr uint32_t BASE_ID = 0x140U;
|
||||
static uint32_t ID(uint8_t node_id) { return BASE_ID + node_id; }
|
||||
uint32_t ID() const { return ID(node_id_); }
|
||||
explicit LingkongMotorRequest(uint8_t node_id) : node_id_(node_id) {}
|
||||
void SetFrameData(const Payload& payload);
|
||||
void UpdateData(uint8_t* data) override;
|
||||
void Reset() override;
|
||||
CanFrame frame();
|
||||
private:
|
||||
uint8_t node_id_{0};
|
||||
Payload payload_{};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device::motor
|
||||
@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include "motor/drivers/lingkong_can/include/protocol/lingkong_motor_request.h"
|
||||
|
||||
namespace cmvr::device::motor {
|
||||
|
||||
// Request and response share one CAN ID. Register only the response parser in
|
||||
// MessageManager; a second registration would overwrite its ID mapping.
|
||||
class LingkongMotorResponse final : public ProtocolData<msgs::RobotDetail> {
|
||||
public:
|
||||
using Payload = LingkongMotorRequest::Payload;
|
||||
static constexpr uint32_t BASE_ID = LingkongMotorRequest::BASE_ID;
|
||||
static uint32_t ID(uint8_t node_id) { return BASE_ID + node_id; }
|
||||
uint32_t ID() const { return ID(node_id_); }
|
||||
explicit LingkongMotorResponse(uint8_t node_id) : node_id_(node_id) {}
|
||||
// Configured before receiver startup. V2.38 byte 3 is encoder type,
|
||||
// whereas the old protocol reserves it as zero.
|
||||
void setExtendedZeroReply(bool enabled) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
extended_zero_reply_ = enabled;
|
||||
}
|
||||
void Parse(const uint8_t* bytes, int32_t length, msgs::RobotDetail*) const override;
|
||||
bool exchange(const Payload& request, Payload& response,
|
||||
std::chrono::milliseconds timeout, const std::function<bool()>& send);
|
||||
private:
|
||||
uint8_t node_id_{0};
|
||||
bool extended_zero_reply_{false};
|
||||
mutable std::mutex mutex_;
|
||||
mutable std::condition_variable changed_;
|
||||
mutable bool waiting_{false}, received_{false};
|
||||
mutable Payload request_{}, response_{};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device::motor
|
||||
@ -0,0 +1,579 @@
|
||||
#include "lingkong_can_protocol.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
constexpr double kRadToDeg = 180.0 / 3.14159265358979323846;
|
||||
constexpr double kUnavailable = std::numeric_limits<double>::quiet_NaN();
|
||||
bool parameterIndex(uint8_t index) { return index == 10 || index == 12 || index == 14; }
|
||||
std::string hexFrame(const LingkongCanProtocol::Payload& bytes) {
|
||||
std::ostringstream out;
|
||||
out << std::hex << std::setfill('0');
|
||||
for (auto byte : bytes) out << std::setw(2) << unsigned(byte);
|
||||
return out.str();
|
||||
}
|
||||
}
|
||||
|
||||
LingkongCanProtocol::LingkongCanProtocol(
|
||||
Send send, std::shared_ptr<MessageManager<msgs::RobotDetail>> manager, ProtocolVersion version)
|
||||
: version_(version), send_(std::move(send)), manager_(std::move(manager))
|
||||
{
|
||||
comm_proto = CommProto::CUSTOM;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::initNode(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
if ((version_ != V2_36 && version_ != V2_38) || !send_ || !manager_ || id < 1 || id > 32 || nodes_.count(id) ||
|
||||
manager_->GetMutableProtocolDataById(motor::LingkongMotorResponse::ID(id))) return false;
|
||||
// Registration happens before CanMotorBusRuntime::start(), like TI5.
|
||||
manager_->AddRecvProtocolData<motor::LingkongMotorResponse, false>(id);
|
||||
auto* response = dynamic_cast<motor::LingkongMotorResponse*>(
|
||||
manager_->GetMutableProtocolDataById(motor::LingkongMotorResponse::ID(id)));
|
||||
if (!response) return false;
|
||||
response->setExtendedZeroReply(version_ == V2_38);
|
||||
nodes_[id].response = response;
|
||||
return true;
|
||||
}
|
||||
|
||||
LingkongCanProtocol::Node* LingkongCanProtocol::node(uint8_t id)
|
||||
{
|
||||
auto it = nodes_.find(id);
|
||||
return it == nodes_.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::configureNode(uint8_t id, const config::MotorConfigItem& cfg)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
const auto& c = cfg.lingkong();
|
||||
if (!n || cfg.id() != id || !std::isfinite(cfg.gear_ratio()) || cfg.gear_ratio() <= 0 ||
|
||||
!std::isfinite(kRadToDeg * cfg.gear_ratio()) ||
|
||||
!std::isfinite(cfg.limit_q_lb()) || !std::isfinite(cfg.limit_q_ub()) ||
|
||||
cfg.limit_q_lb() >= cfg.limit_q_ub()) return false;
|
||||
for (double value : {cfg.limit_qd(), cfg.limit_qdd(), c.current_amp_per_lsb(),
|
||||
c.rated_torque_current_a(), c.acceleration_deg_s2_per_lsb(),
|
||||
c.speed_limit_deg_s_per_lsb(), c.reached_position_tolerance_rad()}) {
|
||||
if (!std::isfinite(value) || value < 0) return false;
|
||||
}
|
||||
n->config = cfg;
|
||||
return true;
|
||||
}
|
||||
|
||||
double LingkongCanProtocol::scale(uint8_t id) const
|
||||
{
|
||||
const auto it = nodes_.find(id);
|
||||
return it == nodes_.end() ? kUnavailable : kRadToDeg * it->second.config.gear_ratio();
|
||||
}
|
||||
|
||||
int64_t LingkongCanProtocol::signedLe(const uint8_t* data, unsigned bytes)
|
||||
{
|
||||
uint64_t value = 0;
|
||||
for (unsigned i = 0; i < bytes; ++i) value |= uint64_t(data[i]) << (8U * i);
|
||||
// 0x92 uses SEVEN payload bytes: sign extend bit 55, not bit 63.
|
||||
if (data[bytes - 1] & 0x80) return -1 - static_cast<int64_t>((uint64_t(1) << (bytes * 8)) - 1 - value);
|
||||
return static_cast<int64_t>(value);
|
||||
}
|
||||
|
||||
void LingkongCanProtocol::putLe(Payload& data, unsigned offset, uint32_t value, unsigned bytes)
|
||||
{
|
||||
for (unsigned i = 0; i < bytes; ++i) data[offset + i] = (value >> (i * 8)) & 0xff;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::toInt32(double value, int32_t& raw)
|
||||
{
|
||||
if (!std::isfinite(value)) return false;
|
||||
const double rounded = std::round(value);
|
||||
if (rounded < std::numeric_limits<int32_t>::min() ||
|
||||
rounded > std::numeric_limits<int32_t>::max()) return false;
|
||||
raw = static_cast<int32_t>(rounded);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::exchange(uint8_t id, const Payload& request, Payload& response)
|
||||
{
|
||||
auto* n = node(id);
|
||||
if (!n || !n->response || !(n->config.gear_ratio() > 0)) return false;
|
||||
motor::LingkongMotorRequest command(id);
|
||||
command.SetFrameData(request);
|
||||
const CanFrame frame = command.frame();
|
||||
const auto timeout = n->config.lingkong().response_timeout_ms();
|
||||
const bool ok = n->response->exchange(request, response,
|
||||
std::chrono::milliseconds(timeout ? timeout : 100), [&] { return send_(frame); });
|
||||
if (!ok) CMVR_LOG(ERROR) << "[LingkongCanProtocol] send/reply failed: node=" << int(id)
|
||||
<< ", command=" << int(request[0])
|
||||
<< ", tx=" << hexFrame(request) << ", timeout_ms=" << (timeout ? timeout : 100);
|
||||
else if (request[0] == 0x88 || request[0] == 0x80 || request[0] == 0x81 ||
|
||||
request[0] == 0xB1 || request[0] == 0xC1 || (request[0] >= 0xA1 && request[0] <= 0xAD))
|
||||
CMVR_LOG(INFO) << "[LingkongCanProtocol] node=" << int(id)
|
||||
<< ", tx=" << hexFrame(request) << ", rx=" << hexFrame(response)
|
||||
<< "; reply is not proof of target completion";
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::simple(uint8_t id, uint8_t command)
|
||||
{
|
||||
Payload request{}, response{};
|
||||
request[0] = command;
|
||||
return exchange(id, request, response);
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::probe(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
Status status;
|
||||
double q, qd;
|
||||
// Read-only initialization: no NMT, PDO setup, enabling or ROM writes.
|
||||
return readStatus(id, status) && !status.isFault() && readFeedback(id, q, qd);
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::setMode(uint8_t id, msgs::RunMode mode)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
if (!n) return false;
|
||||
switch (mode) {
|
||||
case msgs::RUN_MODE_PROFILE_POSITION:
|
||||
case msgs::RUN_MODE_PROFILE_VELOCITY:
|
||||
case msgs::RUN_MODE_CYCLIC_SYNC_POSITION:
|
||||
case msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY:
|
||||
case msgs::RUN_MODE_CYCLIC_SYNC_CURRENT:
|
||||
CMVR_LOG(INFO) << "[LingkongCanProtocol] accepted compatibility mode=" << int(mode)
|
||||
<< ", node=" << int(id)
|
||||
<< "; no CAN mode command sent, native loop changes on target command";
|
||||
return true;
|
||||
default:
|
||||
CMVR_LOG(ERROR) << "[LingkongCanProtocol] unsupported mode=" << int(mode)
|
||||
<< ", node=" << int(id)
|
||||
<< "; supports position/velocity setpoints and cyclic torque; no native profile-torque ramp";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
msgs::RunMode LingkongCanProtocol::getMode(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
// Never present a host-side selection as measured drive state.
|
||||
(void)id;
|
||||
return msgs::RUN_MODE_UNSPECIFIED;
|
||||
}
|
||||
|
||||
void LingkongCanProtocol::setMotorConversion(uint8_t id, double, double gear)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
if (auto* n = node(id); n && std::isfinite(gear) && gear > 0) n->config.set_gear_ratio(gear);
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::setLimitQ(uint8_t id, double upper, double lower)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
if (!n || !std::isfinite(upper) || !std::isfinite(lower) || upper <= lower) return false;
|
||||
// No angle-limit write command is specified: these are software limits only.
|
||||
n->config.set_limit_q_ub(upper);
|
||||
n->config.set_limit_q_lb(lower);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::parameter(uint8_t id, uint8_t command, uint8_t index, int32_t& value)
|
||||
{
|
||||
auto* n = node(id);
|
||||
if (!n) return false;
|
||||
const bool modern = version_ == V2_38;
|
||||
const bool write = command == 0xB1;
|
||||
const bool valid = modern ? (index == 30 || index == 32 || index == 34 || index == 36 || index == 38) : parameterIndex(index);
|
||||
// PID indices 10/11/12 on V2.38 carry three values, not a scalar.
|
||||
if (!valid) return false;
|
||||
const unsigned width = (modern ? index == 30 : index == 10) ? 2 : 4;
|
||||
if (write && width == 2 && (value < -32768 || value > 32767)) return false;
|
||||
if (modern && write) {
|
||||
const int32_t limit = index == 30 ? 2000 : index == 32 ? 3000000 : index == 36 ? 30000 : index == 38 ? 600000 : std::numeric_limits<int32_t>::max();
|
||||
if (value < 0 || value > limit) return false;
|
||||
}
|
||||
Payload request{}, response{};
|
||||
request[0] = modern ? (write ? 0xC1 : 0xC0) : command;
|
||||
request[1] = index;
|
||||
if (write) putLe(request, 4, static_cast<uint32_t>(value), width);
|
||||
if (!exchange(id, request, response)) return false;
|
||||
value = static_cast<int32_t>(signedLe(response.data() + 4, width));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::readControlParameter(uint8_t id, uint8_t index, int32_t& value)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
return parameter(id, 0xB0, index, value);
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::writeControlParameter(uint8_t id, uint8_t index, int32_t value)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
const int32_t requested = value;
|
||||
if (!parameter(id, 0xB1, index, value)) return false;
|
||||
if (value != requested) {
|
||||
CMVR_LOG(ERROR) << "[LingkongCanProtocol] parameter not applied exactly: index="
|
||||
<< int(index) << ", requested=" << requested << ", effective=" << value;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::setLimitQd(uint8_t id, double value)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
int32_t raw;
|
||||
if (n && version_ == V2_38) {
|
||||
if (!std::isfinite(value) || value <= 0 || !toInt32(value * scale(id) * 100.0, raw) || raw <= 0 || !writeControlParameter(id, 32, raw)) return false;
|
||||
n->config.set_limit_qd(value);
|
||||
return true;
|
||||
}
|
||||
if (!n || !std::isfinite(value) || value <= 0 ||
|
||||
n->config.lingkong().speed_limit_deg_s_per_lsb() <= 0 ||
|
||||
!toInt32(value * scale(id) / n->config.lingkong().speed_limit_deg_s_per_lsb(), raw) ||
|
||||
raw <= 0 || !writeControlParameter(id, version_ == V2_38 ? 32 : 14, raw)) return false;
|
||||
n->config.set_limit_qd(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::acceleration(uint8_t id, double value)
|
||||
{
|
||||
auto* n = node(id);
|
||||
if (!n || !std::isfinite(value) || value < 0) return false;
|
||||
if (value == 0) return true; // Explicitly keep the drive's existing acceleration.
|
||||
// V2.38 calls index 38 a speed ramp but does not specify physical units.
|
||||
// Require an explicitly confirmed conversion; never send old index 12 (PID).
|
||||
int32_t raw;
|
||||
if (n->config.lingkong().acceleration_deg_s2_per_lsb() <= 0 ||
|
||||
!toInt32(value * scale(id) / n->config.lingkong().acceleration_deg_s2_per_lsb(), raw) ||
|
||||
raw <= 0) {
|
||||
CMVR_LOG(ERROR) << "[LingkongCanProtocol] acceleration parameter units are not configured";
|
||||
return false;
|
||||
}
|
||||
return writeControlParameter(id, version_ == V2_38 ? 38 : 12, raw);
|
||||
}
|
||||
|
||||
void LingkongCanProtocol::setLimitQdd(uint8_t id, double upper, double lower)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
if (!std::isfinite(upper) || !std::isfinite(lower) || upper <= 0 || lower >= 0 ||
|
||||
std::abs(upper + lower) > 1e-9 || !acceleration(id, upper)) {
|
||||
// B1 has one symmetric limit; do not silently drop asymmetric input.
|
||||
throw std::runtime_error("Lingkong acceleration limit failed: verify symmetric input, firmware units and CAN reply");
|
||||
}
|
||||
node(id)->config.set_limit_qdd(upper);
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::torqueOn(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
if (!n) return false;
|
||||
n->target_valid = false;
|
||||
auto currentAngle = [&]() {
|
||||
Payload request{}, response{};
|
||||
request[0] = 0x92;
|
||||
if (!exchange(id, request, response))
|
||||
throw std::runtime_error("Lingkong hold-enable: cannot read current position (92)");
|
||||
const int64_t angle = signedLe(response.data() + 1, 7);
|
||||
if (angle < std::numeric_limits<int32_t>::min() || angle > std::numeric_limits<int32_t>::max())
|
||||
throw std::runtime_error("Lingkong hold-enable: current position exceeds native A4 target range");
|
||||
return static_cast<int32_t>(angle);
|
||||
};
|
||||
// Fail before enabling if no valid position is available. Never zero the
|
||||
// encoder, reset multi-turn position, or reuse a previous motion target.
|
||||
currentAngle();
|
||||
try {
|
||||
if (!simple(id, 0x88)) throw std::runtime_error("88 run command received no valid reply");
|
||||
requireRunning(id);
|
||||
// Capture again after opening, so holding does not use a stale position.
|
||||
const int32_t angle = currentAngle();
|
||||
Payload request{}, response{};
|
||||
request[0] = 0xA4;
|
||||
putLe(request, 2, 1, 2); // Low motor-side speed ceiling for any capture error.
|
||||
putLe(request, 4, static_cast<uint32_t>(angle), 4);
|
||||
if (!exchange(id, request, response))
|
||||
throw std::runtime_error("A4 current-position hold received no valid reply");
|
||||
requireRunning(id);
|
||||
n->target_q = angle / (100.0 * scale(id));
|
||||
n->target_valid = true;
|
||||
CMVR_LOG(INFO) << "[LingkongCanProtocol] enabled with current-position hold: node="
|
||||
<< int(id) << ", q=" << n->target_q;
|
||||
return true;
|
||||
} catch (const std::exception& error) {
|
||||
const std::string reason = error.what();
|
||||
try {
|
||||
if (!torqueOff(id)) throw std::runtime_error("80 close received no valid reply");
|
||||
} catch (const std::exception& close_error) {
|
||||
throw std::runtime_error("Lingkong hold-enable failed: " + reason +
|
||||
"; rollback also failed: " + close_error.what());
|
||||
}
|
||||
throw std::runtime_error("Lingkong hold-enable failed: " + reason + "; drive closed");
|
||||
}
|
||||
}
|
||||
bool LingkongCanProtocol::torqueOff(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
if (auto* n = node(id)) n->target_valid = false; // Invalidate any previous target after closing.
|
||||
if (!simple(id, 0x80)) return false;
|
||||
Status status;
|
||||
if (!readStatus(id, status)) {
|
||||
CMVR_LOG(ERROR) << "[LingkongCanProtocol] close unconfirmed: node=" << int(id)
|
||||
<< "; 80 acknowledged but 9A status read failed";
|
||||
return false;
|
||||
}
|
||||
if (!status.isClosed()) {
|
||||
CMVR_LOG(ERROR) << "[LingkongCanProtocol] close unconfirmed: node=" << int(id)
|
||||
<< ", motor_state=" << int(status.motor_state)
|
||||
<< ", error=" << int(status.error)
|
||||
<< "; 80 acknowledged; expected protocol-specific OFF state, error=0";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::quickStop(uint8_t id, double /*deceleration*/)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
if (auto* n = node(id)) n->target_valid = false;
|
||||
return simple(id, 0x81);
|
||||
}
|
||||
bool LingkongCanProtocol::brakeRelease(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
Payload request{}, response{};
|
||||
request[0] = 0x8C;
|
||||
request[1] = 1;
|
||||
return exchange(id, request, response);
|
||||
}
|
||||
bool LingkongCanProtocol::calibrateZeroQ(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
if (auto* n = node(id)) n->target_valid = false;
|
||||
Payload request{}, response{};
|
||||
request[0] = 0x19; // Save current position as the permanent power-on zero.
|
||||
if (!exchange(id, request, response)) return false;
|
||||
CMVR_LOG(INFO) << "[LingkongCanProtocol] permanent zero acknowledged: node="
|
||||
<< int(id) << ", encoder_type=" << (version_ == V2_38 ? int(response[3]) : 0)
|
||||
<< ", encoder_offset=" << (version_ == V2_38 ? static_cast<uint32_t>(signedLe(response.data() + 4, 4)) : static_cast<uint16_t>(signedLe(response.data() + 6, 2)))
|
||||
<< (version_ == V2_38
|
||||
? "; saved to ROM; V2.38 manual does not specify activation timing"
|
||||
: "; power-cycle motor to apply")
|
||||
<< "; no immediate position readback, automatic reboot or motion";
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::clearError(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
Payload request{}, response{};
|
||||
request[0] = 0x9B;
|
||||
if (!exchange(id, request, response)) return false;
|
||||
auto* n = node(id);
|
||||
const bool modern = n && version_ == V2_38;
|
||||
return response[7] == 0 && (!modern || ((response[6] & 0x0f) == 0 && (response[6] & 0xf0) != 0x10));
|
||||
}
|
||||
|
||||
double LingkongCanProtocol::getQ(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
Payload request{}, response{};
|
||||
request[0] = 0x92;
|
||||
return exchange(id, request, response) ? signedLe(response.data() + 1, 7) / (100.0 * scale(id)) : kUnavailable;
|
||||
}
|
||||
double LingkongCanProtocol::getQd(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
Payload request{}, response{};
|
||||
request[0] = 0x9C;
|
||||
return exchange(id, request, response) ? signedLe(response.data() + 4, 2) / scale(id) : kUnavailable;
|
||||
}
|
||||
bool LingkongCanProtocol::readFeedback(uint8_t id, double& q, double& qd)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
// Separate replies, not a simultaneous/atomic hardware sample.
|
||||
const double position = getQ(id), velocity = getQd(id);
|
||||
if (!std::isfinite(position) || !std::isfinite(velocity)) return false;
|
||||
q = position;
|
||||
qd = velocity;
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::readStatus(uint8_t id, Status& status)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
Payload request{}, response{};
|
||||
request[0] = 0x9A;
|
||||
if (!exchange(id, request, response)) return false;
|
||||
status.temperature = signedLe(response.data() + 1, 1);
|
||||
status.protocol_version = version_;
|
||||
const bool modern = status.protocol_version == V2_38;
|
||||
status.voltage = signedLe(response.data() + 2, 2) * (modern ? 0.001 : 0.01);
|
||||
status.bus_current = signedLe(response.data() + 4, 2) * (modern ? 0.001 : 0.01);
|
||||
status.motor_state = modern ? (response[6] & 0xf0) : response[6];
|
||||
status.error = response[7] | (modern ? ((response[6] & 0x0f) << 8) : 0);
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::readCurrent(uint8_t id, double& amps)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
if (!n || n->config.lingkong().current_amp_per_lsb() <= 0) return false;
|
||||
Payload request{}, response{};
|
||||
request[0] = 0x9C;
|
||||
if (!exchange(id, request, response)) return false;
|
||||
amps = signedLe(response.data() + 2, 2) * n->config.lingkong().current_amp_per_lsb();
|
||||
return true;
|
||||
}
|
||||
double LingkongCanProtocol::getTau(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
double current;
|
||||
if (!n || n->config.lingkong().rated_torque_current_a() <= 0 || !readCurrent(id, current)) return kUnavailable;
|
||||
return current * 1000.0 / n->config.lingkong().rated_torque_current_a();
|
||||
}
|
||||
|
||||
void LingkongCanProtocol::requireRunning(uint8_t id)
|
||||
{
|
||||
Status status;
|
||||
if (!readStatus(id, status)) throw std::runtime_error("Lingkong: cannot verify drive state (9A read failed); no motion command sent");
|
||||
if (status.isFault()) throw std::runtime_error("Lingkong: drive fault, errorState=" + std::to_string(status.error) + "; inspect 9A before motion");
|
||||
if (!status.isRunning()) throw std::runtime_error("Lingkong: drive is not enabled (protocol-specific 9A state); call torqueOn explicitly before motion");
|
||||
}
|
||||
|
||||
bool LingkongCanProtocol::position(uint8_t id, double q, double qd)
|
||||
{
|
||||
auto* n = node(id);
|
||||
int32_t angle;
|
||||
if (!n || !std::isfinite(qd) || qd < 0 ||
|
||||
q < n->config.limit_q_lb() || q > n->config.limit_q_ub() ||
|
||||
!toInt32(q * scale(id) * 100.0, angle)) return false;
|
||||
if (n->config.limit_qd() > 0 && (qd == 0 || qd > n->config.limit_qd())) qd = n->config.limit_qd();
|
||||
Payload request{}, response{};
|
||||
request[0] = qd > 0 ? 0xA4 : 0xA3;
|
||||
if (qd > 0) {
|
||||
// Never round a speed ceiling UP (or send zero and rely on firmware).
|
||||
const double speed = std::floor(qd * scale(id));
|
||||
if (speed < 1 || speed > 65535) return false;
|
||||
putLe(request, 2, static_cast<uint32_t>(speed), 2);
|
||||
}
|
||||
putLe(request, 4, static_cast<uint32_t>(angle), 4);
|
||||
n->target_valid = false;
|
||||
requireRunning(id);
|
||||
if (!exchange(id, request, response))
|
||||
throw std::runtime_error("Lingkong position command received no valid CAN reply: tx=" + hexFrame(request));
|
||||
n->target_q = q;
|
||||
n->target_valid = true;
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::velocity(uint8_t id, double qd)
|
||||
{
|
||||
auto* n = node(id);
|
||||
int32_t raw;
|
||||
if (!n || !std::isfinite(qd) ||
|
||||
(n->config.limit_qd() > 0 && std::abs(qd) > n->config.limit_qd()) ||
|
||||
!toInt32(qd * scale(id) * 100.0, raw)) return false;
|
||||
Payload request{}, response{};
|
||||
request[0] = 0xA2;
|
||||
if (version_ == V2_38) {
|
||||
// V2.38 A2 adds an Iq limit. Preserve the configured drive limit rather
|
||||
// than accidentally requesting zero torque with the legacy NULL bytes.
|
||||
int32_t torque_limit = 0;
|
||||
if (!readControlParameter(id, 30, torque_limit) || torque_limit < 0 || torque_limit > 2000) return false;
|
||||
putLe(request, 2, static_cast<uint32_t>(torque_limit), 2);
|
||||
}
|
||||
putLe(request, 4, static_cast<uint32_t>(raw), 4);
|
||||
n->target_valid = false;
|
||||
requireRunning(id);
|
||||
if (!exchange(id, request, response))
|
||||
throw std::runtime_error("Lingkong velocity command received no valid CAN reply: tx=" + hexFrame(request));
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::commandProfilePosition(uint8_t id, double q, double qd, double qdd)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
// A4 carries position and a speed ceiling, not acceleration. Keep parameter
|
||||
// writes separate: B1 support must not be a prerequisite for native motion.
|
||||
auto* n = node(id);
|
||||
int32_t raw;
|
||||
if (!n || !std::isfinite(qdd) || qdd < 0 || !std::isfinite(qd) || qd < 0 || !toInt32(q * scale(id) * 100, raw) ||
|
||||
q < n->config.limit_q_lb() || q > n->config.limit_q_ub()) return false;
|
||||
if (qdd != 0) CMVR_LOG(WARNING) << "[LingkongCanProtocol] A3/A4 has no acceleration field; qdd is not sent, retaining drive acceleration";
|
||||
if (!position(id, q, qd)) return false;
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::commandProfileVelocity(uint8_t id, double qd, double qdd)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
int32_t raw;
|
||||
if (!n || !std::isfinite(qdd) || qdd < 0 || !toInt32(qd * scale(id) * 100, raw) ||
|
||||
(n->config.limit_qd() > 0 && std::abs(qd) > n->config.limit_qd())) return false;
|
||||
// A2 carries only target speed. Do not implicitly issue B1/index 12.
|
||||
if (qdd != 0) CMVR_LOG(WARNING) << "[LingkongCanProtocol] A2 has no acceleration field; qdd is not sent, retaining drive acceleration";
|
||||
if (!velocity(id, qd)) return false;
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::commandCyclicPosition(uint8_t id, double q, double qd)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
// Native A4 accepts a speed CEILING, not signed velocity feed-forward.
|
||||
auto* n = node(id);
|
||||
if (!n || !std::isfinite(q) || !std::isfinite(qd)) return false;
|
||||
const double conversion = scale(id);
|
||||
if (!std::isfinite(conversion) || conversion <= 0) return false;
|
||||
|
||||
// A4's smallest non-zero ceiling is 1 motor degree/s. Keep the planned
|
||||
// position reference even below that resolution; never pass zero to
|
||||
// position(), where it selects the configured maximum speed. In particular
|
||||
// the final zero-velocity sample must remain an A4 position hold, not A3,
|
||||
// a maximum-speed catch-up, a torque-off, or a new measured-position target.
|
||||
// This is a software cyclic-position adapter, not hardware-synchronized CSP.
|
||||
const double minimum_speed = 1.0 / conversion;
|
||||
const double requested_speed = std::max(std::abs(qd), minimum_speed);
|
||||
if (n->config.limit_qd() > 0 && requested_speed > n->config.limit_qd()) return false;
|
||||
// Avoid rounding the exact one-unit lower bound down to zero in position().
|
||||
const double speed = std::max(requested_speed,
|
||||
std::nextafter(minimum_speed, std::numeric_limits<double>::infinity()));
|
||||
if (!position(id, q, speed)) return false;
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::commandCyclicVelocity(uint8_t id, double qd)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
if (!velocity(id, qd)) return false;
|
||||
return true;
|
||||
}
|
||||
bool LingkongCanProtocol::commandCyclicTorque(uint8_t id, double tau)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
if (!n || n->config.lingkong().rated_torque_current_a() <= 0 ||
|
||||
n->config.lingkong().current_amp_per_lsb() <= 0) return false;
|
||||
int32_t raw;
|
||||
if (!toInt32(tau * n->config.lingkong().rated_torque_current_a() /
|
||||
(1000.0 * n->config.lingkong().current_amp_per_lsb()), raw) ||
|
||||
raw < -2048 || raw > 2048) return false;
|
||||
Payload request{}, response{};
|
||||
request[0] = 0xA1;
|
||||
putLe(request, 4, static_cast<uint32_t>(raw), 2);
|
||||
n->target_valid = false;
|
||||
requireRunning(id);
|
||||
const bool acknowledged = exchange(id, request, response);
|
||||
return acknowledged;
|
||||
}
|
||||
bool LingkongCanProtocol::reachedTargetQ(uint8_t id)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mutex_);
|
||||
auto* n = node(id);
|
||||
if (!n || !n->target_valid || n->config.lingkong().reached_position_tolerance_rad() <= 0) return false;
|
||||
const double q = getQ(id);
|
||||
return std::isfinite(q) && std::abs(q - n->target_q) <= n->config.lingkong().reached_position_tolerance_rad();
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -0,0 +1,96 @@
|
||||
#include "lingkong_motor.h"
|
||||
#include <stdexcept>
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
LingkongMotor::LingkongMotor(const config::MotorConfigItem& config) : config_(config)
|
||||
{
|
||||
node_id_ = static_cast<uint8_t>(config.id());
|
||||
info_ = {config.id(), config.joint_name(), config.limit_q_lb(), config.limit_q_ub(),
|
||||
config.limit_qd(), config.limit_qdd()};
|
||||
}
|
||||
|
||||
std::shared_ptr<LingkongCanProtocol> LingkongMotor::nativeProtocol() const
|
||||
{
|
||||
return std::dynamic_pointer_cast<LingkongCanProtocol>(protocol_);
|
||||
}
|
||||
|
||||
bool LingkongMotor::init()
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
return p && !info_.joint_name.empty() && config_.id() >= 1 && config_.id() <= 32 &&
|
||||
p->configureNode(node_id_, config_) && p->probe(node_id_);
|
||||
}
|
||||
|
||||
bool LingkongMotor::setLimitQ(double upper, double lower)
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
if (!p || !p->setLimitQ(node_id_, upper, lower)) return false;
|
||||
info_.limit_q_ub = upper;
|
||||
info_.limit_q_lb = lower;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LingkongMotor::setLimitQd(double value)
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
if (!p || !p->setLimitQd(node_id_, value)) return false;
|
||||
info_.limit_qd = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
void LingkongMotor::setLimitQdd(double upper, double lower)
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
if (!p) throw std::runtime_error("Lingkong protocol is not configured");
|
||||
p->setLimitQdd(node_id_, upper, lower);
|
||||
info_.limit_qdd = upper;
|
||||
}
|
||||
|
||||
bool LingkongMotor::brakeRelease()
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
return p && p->brakeRelease(node_id_);
|
||||
}
|
||||
|
||||
bool LingkongMotor::calibrateZeroQ()
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
return p && p->calibrateZeroQ(node_id_);
|
||||
}
|
||||
|
||||
bool LingkongMotor::readDiagnosticState(std::uint16_t& status, std::uint16_t& error,
|
||||
bool& enabled, bool& fault)
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
LingkongCanProtocol::Status native;
|
||||
if (!p || !p->readStatus(node_id_, native)) return false;
|
||||
status = native.motor_state; // Preserve native state, including HV V3 0x30.
|
||||
error = native.error;
|
||||
enabled = native.isRunning();
|
||||
fault = native.isFault();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LingkongMotor::readFeedback(double& q, double& qd)
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
return p && p->readFeedback(node_id_, q, qd);
|
||||
}
|
||||
|
||||
bool LingkongMotor::readCurrent(double& amps)
|
||||
{
|
||||
std::scoped_lock lock(mtx_);
|
||||
auto p = nativeProtocol();
|
||||
return p && p->readCurrent(node_id_, amps);
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -0,0 +1,31 @@
|
||||
#include "motor/drivers/lingkong_can/include/protocol/lingkong_motor_request.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace cmvr::device::motor {
|
||||
|
||||
void LingkongMotorRequest::SetFrameData(const Payload& payload)
|
||||
{
|
||||
payload_ = payload;
|
||||
}
|
||||
|
||||
void LingkongMotorRequest::UpdateData(uint8_t* data)
|
||||
{
|
||||
if (data) std::copy(payload_.begin(), payload_.end(), data);
|
||||
}
|
||||
|
||||
void LingkongMotorRequest::Reset()
|
||||
{
|
||||
payload_.fill(0);
|
||||
}
|
||||
|
||||
CanFrame LingkongMotorRequest::frame()
|
||||
{
|
||||
CanFrame result;
|
||||
result.id = ID();
|
||||
result.len = GetLength();
|
||||
UpdateData(result.data);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::motor
|
||||
@ -0,0 +1,56 @@
|
||||
#include "motor/drivers/lingkong_can/include/protocol/lingkong_motor_response.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace cmvr::device::motor {
|
||||
|
||||
void LingkongMotorResponse::Parse(const uint8_t* bytes, int32_t length, msgs::RobotDetail*) const
|
||||
{
|
||||
if (!bytes || length != 8) return;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!waiting_ || bytes[0] != request_[0]) return;
|
||||
if ((bytes[0] == 0xB0 || bytes[0] == 0xB1 || bytes[0] == 0xC0 || bytes[0] == 0xC1) && bytes[1] != request_[1]) return;
|
||||
if ((bytes[0] == 0x80 || bytes[0] == 0x81 || bytes[0] == 0x88 ||
|
||||
bytes[0] == 0x95) &&
|
||||
!std::equal(bytes, bytes + 8, request_.begin())) return;
|
||||
// 0x19 returns a uint32 encoder offset in bytes 4..7, not a request echo.
|
||||
if (bytes[0] == 0x19 && (bytes[1] != 0 || bytes[2] != 0 ||
|
||||
(!extended_zero_reply_ && (bytes[3] != 0 || bytes[4] != 0 || bytes[5] != 0)))) return;
|
||||
if (bytes[0] == 0x8C && request_[1] != 0x10 && bytes[1] != request_[1]) return;
|
||||
std::copy(bytes, bytes + 8, response_.begin());
|
||||
received_ = true;
|
||||
waiting_ = false;
|
||||
changed_.notify_one();
|
||||
}
|
||||
|
||||
bool LingkongMotorResponse::exchange(const Payload& request, Payload& response,
|
||||
std::chrono::milliseconds timeout,
|
||||
const std::function<bool()>& send)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
request_ = request;
|
||||
received_ = false;
|
||||
waiting_ = true;
|
||||
}
|
||||
// Never hold the receive lock across send: fake transports can reply inline.
|
||||
try {
|
||||
if (!send()) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
waiting_ = false;
|
||||
return false;
|
||||
}
|
||||
} catch (...) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
waiting_ = false;
|
||||
received_ = false;
|
||||
throw;
|
||||
}
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
const bool ok = changed_.wait_for(lock, timeout, [&] { return received_; });
|
||||
waiting_ = false;
|
||||
if (ok) response = response_;
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::motor
|
||||
@ -0,0 +1,861 @@
|
||||
#include "lingkong_motor.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
using namespace cmvr;
|
||||
using namespace cmvr::device;
|
||||
namespace {
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
using Payload = LingkongCanProtocol::Payload;
|
||||
void put(Payload& p, unsigned offset, int64_t value, unsigned length)
|
||||
{
|
||||
const auto bits = static_cast<uint64_t>(value);
|
||||
for (unsigned i = 0; i < length; ++i) p[offset + i] = (bits >> (8 * i)) & 0xff;
|
||||
}
|
||||
|
||||
class LingkongTest : public testing::Test {
|
||||
protected:
|
||||
std::shared_ptr<MessageManager<msgs::RobotDetail>> manager =
|
||||
std::make_shared<MessageManager<msgs::RobotDetail>>();
|
||||
std::shared_ptr<LingkongCanProtocol> protocol;
|
||||
std::vector<CanFrame> sent;
|
||||
bool respond = true, transport_ok = true;
|
||||
int32_t velocity = -60, current = -409;
|
||||
int64_t angle = -36000;
|
||||
uint8_t state = 0, error = 0;
|
||||
std::function<void(Payload&)> mutate;
|
||||
config::MotorConfigItem config;
|
||||
|
||||
LingkongCanProtocol::ProtocolVersion version = LingkongCanProtocol::V2_36;
|
||||
LingkongCanProtocol::Send fake_send;
|
||||
void SetUp() override {
|
||||
manager = std::make_shared<MessageManager<msgs::RobotDetail>>();
|
||||
sent.clear();
|
||||
config.set_id(1);
|
||||
config.set_joint_name("MG6010E_AXIS_1");
|
||||
config.set_gear_ratio(6);
|
||||
config.set_limit_q_lb(-4);
|
||||
config.set_limit_q_ub(4);
|
||||
config.set_limit_qd(1);
|
||||
config.mutable_lingkong()->set_current_amp_per_lsb(66.0 / 4096.0);
|
||||
config.mutable_lingkong()->set_response_timeout_ms(2);
|
||||
config.mutable_lingkong()->set_reached_position_tolerance_rad(0.001);
|
||||
fake_send = [this](const CanFrame& frame) {
|
||||
sent.push_back(frame);
|
||||
if (!transport_ok) return false;
|
||||
if (!respond) return true;
|
||||
Payload reply{};
|
||||
std::copy(frame.data, frame.data + 8, reply.begin());
|
||||
if (reply[0] == 0x88) state = version == LingkongCanProtocol::V2_38 ? 0x30 : 0;
|
||||
if (reply[0] == 0x80) state = version == LingkongCanProtocol::V2_38 ? 0x20 : 0x10;
|
||||
if (reply[0] == 0x92) put(reply, 1, angle, 7);
|
||||
if (reply[0] == 0x9C || (reply[0] >= 0xA1 && reply[0] <= 0xA8)) {
|
||||
reply[1] = uint8_t(-12);
|
||||
put(reply, 2, current, 2);
|
||||
put(reply, 4, velocity, 2);
|
||||
put(reply, 6, 12345, 2);
|
||||
}
|
||||
if (reply[0] == 0x9A || reply[0] == 0x9B) {
|
||||
reply[1] = uint8_t(-12);
|
||||
put(reply, 2, 4800, 2);
|
||||
put(reply, 4, -125, 2);
|
||||
reply[6] = state;
|
||||
reply[7] = error;
|
||||
}
|
||||
if (reply[0] == 0xB0) put(reply, 4, reply[1] == 10 ? -123 : 123456, reply[1] == 10 ? 2 : 4);
|
||||
if (mutate) mutate(reply);
|
||||
manager->Parse(frame.id, reply.data(), reply.size());
|
||||
return true;
|
||||
};
|
||||
protocol = std::make_shared<LingkongCanProtocol>(fake_send, manager, version);
|
||||
ASSERT_TRUE(protocol->initNode(1));
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LingkongTest, StandardCanIdAndReadOnlyInit) {
|
||||
LingkongMotor motor(config);
|
||||
// Use a fresh protocol to exercise the full setProtocol/init lifecycle.
|
||||
auto other_manager = std::make_shared<MessageManager<msgs::RobotDetail>>();
|
||||
auto p = std::make_shared<LingkongCanProtocol>([&](const CanFrame& f) {
|
||||
sent.push_back(f);
|
||||
Payload r{}; r[0] = f.data[0];
|
||||
if (r[0] == 0x9A) r[6] = 0x10;
|
||||
other_manager->Parse(f.id, r.data(), r.size());
|
||||
return true;
|
||||
}, other_manager);
|
||||
ASSERT_TRUE(motor.setProtocol(p));
|
||||
ASSERT_TRUE(motor.init());
|
||||
ASSERT_EQ(sent.size(), 3);
|
||||
EXPECT_EQ(sent[0].data[0], 0x9A);
|
||||
EXPECT_EQ(sent[1].data[0], 0x92);
|
||||
EXPECT_EQ(sent[2].data[0], 0x9C);
|
||||
for (const auto& f : sent) { EXPECT_EQ(f.id, 0x141); EXPECT_EQ(f.len, 8); }
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, RequestProtocolCopiesAndResetsAllEightBytes) {
|
||||
motor::LingkongMotorRequest request(32);
|
||||
Payload data{0xA4, 0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc};
|
||||
request.SetFrameData(data);
|
||||
auto frame = request.frame();
|
||||
EXPECT_EQ(request.ID(), 0x160);
|
||||
EXPECT_EQ(frame.id, 0x160);
|
||||
EXPECT_EQ(frame.len, 8);
|
||||
for (unsigned i = 0; i < data.size(); ++i) EXPECT_EQ(frame.data[i], data[i]);
|
||||
request.Reset();
|
||||
frame = request.frame();
|
||||
for (auto byte : frame.data) EXPECT_EQ(byte, 0);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, SignedMultiTurnAndVelocityUseGearRatio) {
|
||||
EXPECT_NEAR(protocol->getQ(1), -kPi / 3, 1e-12);
|
||||
EXPECT_NEAR(protocol->getQd(1), -kPi / 18, 1e-12);
|
||||
angle = -(int64_t(1) << 40); // Seven-byte sign extension, not int32 truncation.
|
||||
EXPECT_NEAR(protocol->getQ(1), angle * kPi / (18000.0 * 6), 1e-6);
|
||||
angle = (int64_t(1) << 45);
|
||||
EXPECT_NEAR(protocol->getQ(1), angle * kPi / (18000.0 * 6), 1e-4);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, StatusAndCurrentAreNativeValues) {
|
||||
state = 0x10;
|
||||
LingkongCanProtocol::Status s;
|
||||
ASSERT_TRUE(protocol->readStatus(1, s));
|
||||
EXPECT_EQ(s.motor_state, 0x10);
|
||||
EXPECT_EQ(s.temperature, -12);
|
||||
EXPECT_DOUBLE_EQ(s.voltage, 48);
|
||||
EXPECT_DOUBLE_EQ(s.bus_current, -1.25);
|
||||
double amps;
|
||||
ASSERT_TRUE(protocol->readCurrent(1, amps));
|
||||
EXPECT_DOUBLE_EQ(amps, -409 * 66.0 / 4096);
|
||||
EXPECT_TRUE(std::isnan(protocol->getTau(1))); // No fake rated torque/current.
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, NativeStatusIsNotDecodedAsCia402) {
|
||||
state = 0x10;
|
||||
LingkongMotor motor(config);
|
||||
// A second node uses the same bus and its own response parser.
|
||||
auto second = config; second.set_id(2);
|
||||
LingkongMotor other(second);
|
||||
ASSERT_TRUE(other.setProtocol(protocol));
|
||||
ASSERT_TRUE(other.init());
|
||||
uint16_t sw, ec; bool enabled, fault;
|
||||
ASSERT_TRUE(other.readDiagnosticState(sw, ec, enabled, fault));
|
||||
EXPECT_EQ(sw, 0x10); EXPECT_FALSE(enabled); EXPECT_FALSE(fault);
|
||||
state = 0; error = 8;
|
||||
ASSERT_TRUE(other.readDiagnosticState(sw, ec, enabled, fault));
|
||||
EXPECT_FALSE(enabled); EXPECT_TRUE(fault); EXPECT_EQ(ec, 8);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, PositionAndNegativeSpeedPackets) {
|
||||
ASSERT_TRUE(protocol->commandProfilePosition(1, -kPi / 6, 0.5, 0));
|
||||
auto p = sent.back();
|
||||
EXPECT_EQ(p.data[0], 0xA4);
|
||||
EXPECT_EQ(p.data[2], 171); // floor(0.5 * 180/pi * 6) dps.
|
||||
EXPECT_EQ(p.data[3], 0);
|
||||
Payload expected{}; put(expected, 4, -18000, 4);
|
||||
for (int i = 4; i < 8; ++i) EXPECT_EQ(p.data[i], expected[i]);
|
||||
ASSERT_TRUE(protocol->commandCyclicVelocity(1, -kPi / 36));
|
||||
expected = {}; put(expected, 4, -3000, 4);
|
||||
EXPECT_EQ(sent.back().data[0], 0xA2);
|
||||
for (int i = 4; i < 8; ++i) EXPECT_EQ(sent.back().data[i], expected[i]);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, EnableHoldsCurrentPositionAndOtherOperationsStayExplicit) {
|
||||
ASSERT_TRUE(protocol->torqueOn(1)); EXPECT_EQ(sent[0].data[0], 0x92); EXPECT_EQ(sent[1].data[0], 0x88); EXPECT_EQ(sent.back().data[0], 0x9A);
|
||||
ASSERT_EQ(sent.size(), 6);
|
||||
EXPECT_EQ(sent[4].data[0], 0xA4);
|
||||
ASSERT_TRUE(protocol->torqueOff(1)); EXPECT_EQ(sent[6].data[0], 0x80); EXPECT_EQ(sent.back().data[0], 0x9A);
|
||||
ASSERT_TRUE(protocol->quickStop(1)); EXPECT_EQ(sent.back().data[0], 0x81);
|
||||
ASSERT_TRUE(protocol->brakeRelease(1)); EXPECT_EQ(sent.back().data[0], 0x8C); EXPECT_EQ(sent.back().data[1], 1);
|
||||
ASSERT_TRUE(protocol->calibrateZeroQ(1)); EXPECT_EQ(sent.back().data[0], 0x19);
|
||||
ASSERT_TRUE(protocol->clearError(1)); EXPECT_EQ(sent.back().data[0], 0x9B);
|
||||
EXPECT_EQ(sent.size(), 12);
|
||||
EXPECT_TRUE(protocol->setMode(1, msgs::RUN_MODE_CYCLIC_SYNC_POSITION));
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
EXPECT_EQ(sent.size(), 12);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ModeSelectionIsLocalAndNeverEnablesOrMoves) {
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
for (const auto mode : {msgs::RUN_MODE_PROFILE_POSITION, msgs::RUN_MODE_PROFILE_VELOCITY,
|
||||
msgs::RUN_MODE_CYCLIC_SYNC_POSITION, msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY,
|
||||
msgs::RUN_MODE_CYCLIC_SYNC_CURRENT}) {
|
||||
ASSERT_TRUE(protocol->setMode(1, mode));
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
EXPECT_TRUE(sent.empty());
|
||||
}
|
||||
EXPECT_FALSE(protocol->setMode(0, msgs::RUN_MODE_PROFILE_POSITION));
|
||||
EXPECT_FALSE(protocol->setMode(1, msgs::RUN_MODE_UNSPECIFIED));
|
||||
EXPECT_FALSE(protocol->setMode(1, msgs::RUN_MODE_TORQUE)); // No native torque ramp.
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
EXPECT_EQ(protocol->getMode(0), msgs::RUN_MODE_UNSPECIFIED);
|
||||
EXPECT_TRUE(sent.empty());
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, CommandsNeverInventHardwareModeReadback) {
|
||||
ASSERT_TRUE(protocol->commandProfilePosition(1, 0.5, 0.1, 0));
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
ASSERT_TRUE(protocol->commandCyclicPosition(1, 0.5, 0.1));
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
ASSERT_TRUE(protocol->commandProfileVelocity(1, -0.1, 0));
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
respond = false;
|
||||
EXPECT_THROW(protocol->commandCyclicVelocity(1, 0.1), std::runtime_error);
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
respond = true;
|
||||
ASSERT_TRUE(protocol->commandCyclicVelocity(1, 0.1));
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, NativePositionDoesNotWriteAccelerationEvenWhenUnitsConfigured) {
|
||||
config.mutable_lingkong()->set_acceleration_deg_s2_per_lsb(1);
|
||||
config.mutable_lingkong()->set_speed_limit_deg_s_per_lsb(1);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
ASSERT_TRUE(protocol->setMode(1, msgs::RUN_MODE_PROFILE_POSITION));
|
||||
ASSERT_TRUE(protocol->commandProfilePosition(1, 1.0, 0.1, 0.5));
|
||||
ASSERT_EQ(sent.size(), 2);
|
||||
EXPECT_EQ(sent[0].data[0], 0x9A);
|
||||
EXPECT_EQ(sent[1].data[0], 0xA4);
|
||||
EXPECT_EQ(sent[1].data[2], 34); EXPECT_EQ(sent[1].data[3], 0);
|
||||
Payload expected{}; put(expected, 4, 34377, 4);
|
||||
for (int i = 4; i < 8; ++i) EXPECT_EQ(sent[1].data[i], expected[i]);
|
||||
ASSERT_TRUE(protocol->setLimitQd(1, 0.5));
|
||||
EXPECT_EQ(sent.back().data[0], 0xB1); EXPECT_EQ(sent.back().data[1], 14);
|
||||
EXPECT_EQ(sent.back().data[4], 172);
|
||||
EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ParameterOffsetsAndUnknownUnits) {
|
||||
EXPECT_FALSE(protocol->setLimitQd(1, 0.5));
|
||||
EXPECT_THROW(protocol->setLimitQdd(1, 1, -1), std::runtime_error);
|
||||
EXPECT_TRUE(sent.empty());
|
||||
ASSERT_TRUE(protocol->commandProfilePosition(1, 0.5, 0.5, 1));
|
||||
ASSERT_EQ(sent.size(), 2); EXPECT_EQ(sent.back().data[0], 0xA4);
|
||||
ASSERT_TRUE(protocol->commandProfileVelocity(1, 0.1, 1));
|
||||
ASSERT_EQ(sent.size(), 4); EXPECT_EQ(sent.back().data[0], 0xA2);
|
||||
int32_t value;
|
||||
ASSERT_TRUE(protocol->readControlParameter(1, 10, value)); EXPECT_EQ(value, -123);
|
||||
ASSERT_TRUE(protocol->readControlParameter(1, 12, value)); EXPECT_EQ(value, 123456);
|
||||
ASSERT_TRUE(protocol->writeControlParameter(1, 14, 123456));
|
||||
EXPECT_EQ(sent.back().data[2], 0); EXPECT_EQ(sent.back().data[3], 0);
|
||||
EXPECT_EQ(sent.back().data[4], 0x40); EXPECT_EQ(sent.back().data[5], 0xe2);
|
||||
EXPECT_EQ(sent.back().data[6], 1); EXPECT_EQ(sent.back().data[7], 0);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ExplicitParameterUnitsAndTorqueCalibration) {
|
||||
config.mutable_lingkong()->set_acceleration_deg_s2_per_lsb(1);
|
||||
config.mutable_lingkong()->set_speed_limit_deg_s_per_lsb(0.01);
|
||||
config.mutable_lingkong()->set_rated_torque_current_a(5);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
ASSERT_TRUE(protocol->commandProfileVelocity(1, 0.25, 1));
|
||||
ASSERT_EQ(sent.size(), 2); EXPECT_EQ(sent[1].data[0], 0xA2);
|
||||
ASSERT_TRUE(protocol->commandCyclicTorque(1, -1000));
|
||||
Payload expected{}; put(expected, 4, -310, 2);
|
||||
EXPECT_EQ(sent.back().data[0], 0xA1);
|
||||
EXPECT_EQ(sent.back().data[4], expected[4]); EXPECT_EQ(sent.back().data[5], expected[5]);
|
||||
EXPECT_DOUBLE_EQ(protocol->getTau(1), (-409 * 66.0 / 4096) * 1000 / 5);
|
||||
EXPECT_FALSE(protocol->commandCyclicTorque(1, 100000));
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, MissingRepliesNeverReuseOldData) {
|
||||
EXPECT_TRUE(std::isfinite(protocol->getQ(1)));
|
||||
respond = false;
|
||||
EXPECT_TRUE(std::isnan(protocol->getQ(1)));
|
||||
EXPECT_THROW(protocol->torqueOn(1), std::runtime_error);
|
||||
double q = 42, qd = 43;
|
||||
EXPECT_FALSE(protocol->readFeedback(1, q, qd));
|
||||
EXPECT_EQ(q, 42); EXPECT_EQ(qd, 43);
|
||||
transport_ok = false;
|
||||
EXPECT_FALSE(protocol->quickStop(1));
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, WrongCommandAndParameterRepliesAreRejected) {
|
||||
mutate = [](Payload& p) { p[0] = 0x9C; };
|
||||
EXPECT_TRUE(std::isnan(protocol->getQ(1)));
|
||||
mutate = [](Payload& p) { p[1] = 10; };
|
||||
int32_t value = 0;
|
||||
EXPECT_FALSE(protocol->readControlParameter(1, 12, value));
|
||||
mutate = [](Payload& p) { p[4] ^= 1; };
|
||||
EXPECT_FALSE(protocol->writeControlParameter(1, 12, 123));
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, InvalidNodeConfigAndTargetsDoNotSend) {
|
||||
EXPECT_FALSE(protocol->initNode(0)); EXPECT_FALSE(protocol->initNode(33));
|
||||
EXPECT_FALSE(protocol->initNode(1)); EXPECT_TRUE(protocol->initNode(32));
|
||||
EXPECT_FALSE(protocol->commandProfilePosition(1, 100, 0.5, 0));
|
||||
EXPECT_FALSE(protocol->commandProfileVelocity(1, 2, 0));
|
||||
EXPECT_FALSE(protocol->commandCyclicPosition(1, std::numeric_limits<double>::quiet_NaN(), 0));
|
||||
EXPECT_FALSE(protocol->commandCyclicVelocity(1, std::numeric_limits<double>::infinity()));
|
||||
EXPECT_FALSE(protocol->commandCyclicTorque(1, 0)); // Missing rated current.
|
||||
EXPECT_TRUE(sent.empty());
|
||||
auto bad = config; bad.set_gear_ratio(0);
|
||||
EXPECT_FALSE(protocol->configureNode(1, bad));
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ReachedTargetUsesRealMultiTurnPosition) {
|
||||
EXPECT_FALSE(protocol->reachedTargetQ(1));
|
||||
ASSERT_TRUE(protocol->commandCyclicPosition(1, -kPi / 3, 0.5));
|
||||
EXPECT_TRUE(protocol->reachedTargetQ(1));
|
||||
angle = 0; EXPECT_FALSE(protocol->reachedTargetQ(1));
|
||||
ASSERT_TRUE(protocol->quickStop(1)); EXPECT_FALSE(protocol->reachedTargetQ(1));
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, CyclicLowSpeedAndEndpointKeepExplicitMinimumCeiling) {
|
||||
config.set_gear_ratio(10);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
for (double speed : {1e-10, -1e-10, 0.0, -0.0}) {
|
||||
sent.clear();
|
||||
ASSERT_TRUE(protocol->commandCyclicPosition(1, 0.5, speed));
|
||||
ASSERT_EQ(sent.size(), 2);
|
||||
EXPECT_EQ(sent.front().data[0], 0x9A);
|
||||
EXPECT_EQ(sent.back().data[0], 0xA4);
|
||||
EXPECT_EQ(sent.back().data[2], 1);
|
||||
EXPECT_EQ(sent.back().data[3], 0);
|
||||
Payload expected{}; put(expected, 4, std::llround(0.5 * 10 * 18000 / kPi), 4);
|
||||
for (int i = 4; i < 8; ++i) EXPECT_EQ(sent.back().data[i], expected[i]);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, CyclicPositionPreservesDirectionAndRepresentableSpeed) {
|
||||
for (double speed : {0.1, -0.1}) {
|
||||
sent.clear();
|
||||
ASSERT_TRUE(protocol->commandCyclicPosition(1, -0.5, speed));
|
||||
ASSERT_EQ(sent.size(), 2);
|
||||
EXPECT_EQ(sent.back().data[0], 0xA4);
|
||||
EXPECT_EQ(sent.back().data[2], 34);
|
||||
EXPECT_EQ(sent.back().data[3], 0);
|
||||
Payload expected{}; put(expected, 4, std::llround(-0.5 * 6 * 18000 / kPi), 4);
|
||||
for (int i = 4; i < 8; ++i) EXPECT_EQ(sent.back().data[i], expected[i]);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, CyclicPositionRejectsUnrepresentableLimitAndInvalidSpeed) {
|
||||
EXPECT_FALSE(protocol->commandCyclicPosition(1, 0.1, std::numeric_limits<double>::quiet_NaN()));
|
||||
EXPECT_FALSE(protocol->commandCyclicPosition(1, 0.1, std::numeric_limits<double>::infinity()));
|
||||
EXPECT_FALSE(protocol->commandCyclicPosition(1, 0.1, 2.0));
|
||||
config.set_limit_qd(0.0001);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
EXPECT_FALSE(protocol->commandCyclicPosition(1, 0.1, 0));
|
||||
EXPECT_TRUE(sent.empty());
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ThreeCyclicAxesRetainIndependentEndpointTargets) {
|
||||
for (int id = 1; id <= 3; ++id) {
|
||||
if (id != 1) ASSERT_TRUE(protocol->initNode(id));
|
||||
auto axis = config;
|
||||
axis.set_id(id);
|
||||
axis.set_gear_ratio(10);
|
||||
ASSERT_TRUE(protocol->configureNode(id, axis));
|
||||
}
|
||||
for (int id = 1; id <= 3; ++id) {
|
||||
sent.clear();
|
||||
const double target = (id - 2) * 0.5;
|
||||
ASSERT_TRUE(protocol->commandCyclicPosition(id, target, 0));
|
||||
ASSERT_EQ(sent.size(), 2);
|
||||
EXPECT_EQ(sent.back().id, 0x140 + id);
|
||||
EXPECT_EQ(sent.back().data[0], 0xA4);
|
||||
EXPECT_EQ(sent.back().data[2], 1);
|
||||
Payload expected{}; put(expected, 4, std::llround(target * 10 * 18000 / kPi), 4);
|
||||
for (int i = 4; i < 8; ++i) EXPECT_EQ(sent.back().data[i], expected[i]);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ShortAndUnsolicitedPacketsAreIgnored) {
|
||||
auto* parser = manager->GetMutableProtocolDataById(0x141);
|
||||
Payload old{}; old[0] = 0x92;
|
||||
parser->Parse(old.data(), 8, nullptr);
|
||||
mutate = [&](Payload& p) { parser->Parse(p.data(), 7, nullptr); p[0] = 0; };
|
||||
EXPECT_TRUE(std::isnan(protocol->getQ(1)));
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ClosedDriveAndFaultNeverDispatchOrAutomaticallyEnable) {
|
||||
state = 0x10;
|
||||
EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 1), std::runtime_error);
|
||||
EXPECT_THROW(protocol->commandProfileVelocity(1, 0.1, 1), std::runtime_error);
|
||||
state = 0; error = 8;
|
||||
EXPECT_THROW(protocol->commandCyclicPosition(1, 0.1, 0.1), std::runtime_error);
|
||||
config.mutable_lingkong()->set_rated_torque_current_a(5);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
EXPECT_THROW(protocol->commandCyclicTorque(1, 0), std::runtime_error);
|
||||
ASSERT_EQ(sent.size(), 4);
|
||||
for (const auto& frame : sent) EXPECT_EQ(frame.data[0], 0x9A);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, RunAndCloseEchoMustBeConfirmedByRealStatus) {
|
||||
mutate = [](Payload& p) { if (p[0] == 0x9A) p[6] = 0x10; };
|
||||
EXPECT_THROW(protocol->torqueOn(1), std::runtime_error);
|
||||
mutate = [](Payload& p) { if (p[0] == 0x9A) p[6] = 0; };
|
||||
EXPECT_FALSE(protocol->torqueOff(1));
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, NativeA3AndA4DoNotRequireModeSelectionOrB1) {
|
||||
config.set_limit_qd(0);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
ASSERT_TRUE(protocol->commandProfilePosition(1, 0.1, 0, 1));
|
||||
ASSERT_EQ(sent.size(), 2);
|
||||
EXPECT_EQ(sent[0].data[0], 0x9A); EXPECT_EQ(sent[1].data[0], 0xA3);
|
||||
sent.clear();
|
||||
ASSERT_TRUE(protocol->commandProfilePosition(1, 0.1, 0.1, 1));
|
||||
ASSERT_EQ(sent.size(), 2);
|
||||
EXPECT_EQ(sent[0].data[0], 0x9A); EXPECT_EQ(sent[1].data[0], 0xA4);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ParameterReplyIsEffectiveValueNotAnEcho) {
|
||||
mutate = [](Payload& p) { if (p[0] == 0xB1) p[2] = 0x55; };
|
||||
EXPECT_TRUE(protocol->writeControlParameter(1, 12, 123));
|
||||
mutate = [](Payload& p) { if (p[0] == 0xB1) put(p, 4, 124, 4); };
|
||||
EXPECT_FALSE(protocol->writeControlParameter(1, 12, 123));
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, MissingMotionReplyPropagatesAndNeverMarksTargetValid) {
|
||||
mutate = [](Payload& p) { if (p[0] == 0xA4 || p[0] == 0xA2) p[0] = 0; };
|
||||
EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 0), std::runtime_error);
|
||||
EXPECT_FALSE(protocol->reachedTargetQ(1));
|
||||
EXPECT_THROW(protocol->commandProfileVelocity(1, 0.1, 0), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, HoldUsesFreshRawAngleWithoutZeroingOrParameterWrites) {
|
||||
int reads = 0;
|
||||
mutate = [&](Payload& p) { if (p[0] == 0x92) put(p, 1, ++reads == 1 ? -100 : -12345, 7); };
|
||||
ASSERT_TRUE(protocol->torqueOn(1));
|
||||
ASSERT_EQ(sent.size(), 6);
|
||||
Payload expected{}; put(expected, 4, -12345, 4);
|
||||
EXPECT_EQ(sent[4].data[2], 1); EXPECT_EQ(sent[4].data[3], 0);
|
||||
for (int i = 4; i < 8; ++i) EXPECT_EQ(sent[4].data[i], expected[i]);
|
||||
for (const auto& frame : sent) {
|
||||
EXPECT_NE(frame.data[0], 0x95); EXPECT_NE(frame.data[0], 0x19);
|
||||
EXPECT_NE(frame.data[0], 0x91); EXPECT_NE(frame.data[0], 0xB1);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, MissingPositionAndOutOfRangeNeverEnable) {
|
||||
respond = false;
|
||||
EXPECT_THROW(protocol->torqueOn(1), std::runtime_error);
|
||||
ASSERT_EQ(sent.size(), 1); EXPECT_EQ(sent[0].data[0], 0x92);
|
||||
respond = true; sent.clear(); angle = int64_t(1) << 40;
|
||||
EXPECT_THROW(protocol->torqueOn(1), std::runtime_error);
|
||||
ASSERT_EQ(sent.size(), 1); EXPECT_EQ(sent[0].data[0], 0x92);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, FailedHoldRollsBackToClosedAndInvalidatesTarget) {
|
||||
mutate = [](Payload& p) { if (p[0] == 0xA4) p[0] = 0; };
|
||||
EXPECT_THROW(protocol->torqueOn(1), std::runtime_error);
|
||||
EXPECT_EQ(state, 0x10);
|
||||
ASSERT_GE(sent.size(), 2);
|
||||
EXPECT_EQ(sent[sent.size()-2].data[0], 0x80);
|
||||
EXPECT_EQ(sent.back().data[0], 0x9A);
|
||||
EXPECT_FALSE(protocol->reachedTargetQ(1));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_F(LingkongTest, HvState30WithoutFaultInitializesAndReportsRawEnabledState) {
|
||||
version = LingkongCanProtocol::V2_38; SetUp();
|
||||
state = 0x30;
|
||||
auto second = config; second.set_id(2);
|
||||
LingkongMotor motor(second);
|
||||
ASSERT_TRUE(motor.setProtocol(protocol));
|
||||
ASSERT_TRUE(motor.init());
|
||||
uint16_t sw, ec; bool enabled, fault;
|
||||
ASSERT_TRUE(motor.readDiagnosticState(sw, ec, enabled, fault));
|
||||
EXPECT_EQ(sw, 0x30); EXPECT_EQ(ec, 0);
|
||||
EXPECT_TRUE(enabled); EXPECT_FALSE(fault);
|
||||
for (const auto& frame : sent)
|
||||
EXPECT_TRUE(frame.data[0] == 0x9A || frame.data[0] == 0x92 || frame.data[0] == 0x9C);
|
||||
sent.clear();
|
||||
EXPECT_TRUE(protocol->commandProfilePosition(1, 0.1, 0.1, 1));
|
||||
ASSERT_EQ(sent.size(), 2); EXPECT_EQ(sent.back().data[0], 0xA4);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, HvState30WithAnyFaultNeverDispatchesMotion) {
|
||||
version = LingkongCanProtocol::V2_38; SetUp();
|
||||
state = 0x30;
|
||||
for (unsigned bit = 0; bit < 8; ++bit) {
|
||||
error = uint8_t(1u << bit);
|
||||
EXPECT_FALSE(protocol->probe(1));
|
||||
EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 1), std::runtime_error);
|
||||
}
|
||||
for (const auto& frame : sent) EXPECT_EQ(frame.data[0], 0x9A);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, AllV236StatesRequireExactOnWithoutFault) {
|
||||
auto second = config; second.set_id(2);
|
||||
LingkongMotor motor(second);
|
||||
ASSERT_TRUE(motor.setProtocol(protocol));
|
||||
for (unsigned value = 0; value <= 255; ++value) {
|
||||
state = uint8_t(value); error = 0;
|
||||
ASSERT_TRUE(motor.init()) << value;
|
||||
uint16_t raw, ec; bool enabled, fault;
|
||||
ASSERT_TRUE(motor.readDiagnosticState(raw, ec, enabled, fault));
|
||||
EXPECT_EQ(raw, value); EXPECT_EQ(ec, 0);
|
||||
EXPECT_EQ(enabled, value == 0x00); EXPECT_FALSE(fault);
|
||||
if (value != 0x00) {
|
||||
EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 1), std::runtime_error);
|
||||
} else {
|
||||
EXPECT_TRUE(protocol->commandProfilePosition(1, 0.1, 0.1, 1)) << value;
|
||||
}
|
||||
for (unsigned bit = 0; bit < 8; ++bit) {
|
||||
error = uint8_t(1u << bit);
|
||||
EXPECT_FALSE(protocol->probe(1));
|
||||
ASSERT_TRUE(motor.readDiagnosticState(raw, ec, enabled, fault));
|
||||
EXPECT_EQ(raw, value); EXPECT_EQ(ec, error);
|
||||
EXPECT_FALSE(enabled); EXPECT_TRUE(fault);
|
||||
sent.clear();
|
||||
EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 1), std::runtime_error);
|
||||
ASSERT_EQ(sent.size(), 1); EXPECT_EQ(sent[0].data[0], 0x9A);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, PermanentZeroWritesRomOnceAndAcceptsReturnedOffset) {
|
||||
ASSERT_TRUE(protocol->commandProfilePosition(1, 0.1, 0.1, 0));
|
||||
sent.clear();
|
||||
mutate = [](Payload& p) { if (p[0] == 0x19) put(p, 6, 0xBA98u, 2); };
|
||||
ASSERT_TRUE(protocol->calibrateZeroQ(1));
|
||||
ASSERT_EQ(sent.size(), 1);
|
||||
EXPECT_EQ(sent[0].data[0], 0x19);
|
||||
for (unsigned i = 1; i < 8; ++i) EXPECT_EQ(sent[0].data[i], 0);
|
||||
EXPECT_FALSE(protocol->reachedTargetQ(1));
|
||||
EXPECT_EQ(sent.size(), 1); // No reboot, motion, retries or redundant ROM writes.
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, PermanentZeroRequiresValidAcknowledgement) {
|
||||
respond = false;
|
||||
EXPECT_FALSE(protocol->calibrateZeroQ(1));
|
||||
respond = true;
|
||||
mutate = [](Payload& p) { if (p[0] == 0x19) p[0] = 0x95; };
|
||||
EXPECT_FALSE(protocol->calibrateZeroQ(1));
|
||||
for (unsigned byte = 1; byte <= 3; ++byte) {
|
||||
mutate = [byte](Payload& p) { if (p[0] == 0x19) p[byte] = 1; };
|
||||
EXPECT_FALSE(protocol->calibrateZeroQ(1));
|
||||
}
|
||||
ASSERT_EQ(sent.size(), 5);
|
||||
for (const auto& frame : sent) EXPECT_EQ(frame.data[0], 0x19);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, CloseFailuresReturnFalseWithoutThrowingOrSendingMoreCommands) {
|
||||
for (const uint8_t returned : {0x00, 0x20, 0x30, 0xFF}) {
|
||||
mutate = [returned](Payload& p) { if (p[0] == 0x9A) p[6] = returned; };
|
||||
sent.clear();
|
||||
EXPECT_FALSE(protocol->torqueOff(1));
|
||||
ASSERT_EQ(sent.size(), 2);
|
||||
EXPECT_EQ(sent[0].data[0], 0x80); EXPECT_EQ(sent[1].data[0], 0x9A);
|
||||
}
|
||||
mutate = [](Payload& p) { if (p[0] == 0x9A) p[0] = 0; };
|
||||
EXPECT_FALSE(protocol->torqueOff(1));
|
||||
mutate = {}; error = 8;
|
||||
EXPECT_FALSE(protocol->torqueOff(1));
|
||||
error = 0;
|
||||
EXPECT_TRUE(protocol->torqueOff(1));
|
||||
respond = false; sent.clear();
|
||||
EXPECT_FALSE(protocol->torqueOff(1));
|
||||
ASSERT_EQ(sent.size(), 1); EXPECT_EQ(sent[0].data[0], 0x80);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, V238PackedStatusAndMillivoltUnits) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
state = 0x32; error = 0;
|
||||
LingkongCanProtocol::Status s;
|
||||
ASSERT_TRUE(protocol->readStatus(1, s));
|
||||
EXPECT_EQ(s.motor_state, 0x30);
|
||||
EXPECT_EQ(s.error, 0x200);
|
||||
EXPECT_FALSE(s.isRunning());
|
||||
EXPECT_TRUE(s.isFault());
|
||||
EXPECT_DOUBLE_EQ(s.voltage, 4.8);
|
||||
EXPECT_DOUBLE_EQ(s.bus_current, -0.125);
|
||||
for (auto raw : {0x00, 0x10, 0x20, 0x40, 0x50}) {
|
||||
state = raw;
|
||||
ASSERT_TRUE(protocol->readStatus(1, s));
|
||||
EXPECT_FALSE(s.isRunning());
|
||||
}
|
||||
state = 0x30;
|
||||
ASSERT_TRUE(protocol->readStatus(1, s));
|
||||
EXPECT_TRUE(s.isRunning());
|
||||
state = 0x20;
|
||||
ASSERT_TRUE(protocol->readStatus(1, s));
|
||||
EXPECT_TRUE(s.isClosed());
|
||||
}
|
||||
TEST_F(LingkongTest, V238UsesCParametersAndRejectsScalarPid) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
int32_t value = 0;
|
||||
EXPECT_TRUE(protocol->readControlParameter(1, 32, value));
|
||||
EXPECT_EQ(sent.back().data[0], 0xC0);
|
||||
EXPECT_TRUE(protocol->writeControlParameter(1, 38, 100));
|
||||
EXPECT_EQ(sent.back().data[0], 0xC1);
|
||||
EXPECT_EQ(sent.back().data[1], 38);
|
||||
EXPECT_FALSE(protocol->writeControlParameter(1, 12, 100));
|
||||
EXPECT_FALSE(protocol->writeControlParameter(1, 30, 2001));
|
||||
EXPECT_FALSE(protocol->writeControlParameter(1, 32, 3000001));
|
||||
EXPECT_TRUE(protocol->setLimitQd(1, 1));
|
||||
EXPECT_EQ(sent.back().data[1], 32);
|
||||
config.mutable_lingkong()->set_acceleration_deg_s2_per_lsb(1);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
EXPECT_NO_THROW(protocol->setLimitQdd(1, 1, -1));
|
||||
EXPECT_EQ(sent.back().data[0], 0xC1);
|
||||
EXPECT_EQ(sent.back().data[1], 38);
|
||||
}
|
||||
TEST_F(LingkongTest, V238OffAndClearVerifyHighErrorBits) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
mutate = [](Payload& r) { if (r[0] == 0x9A) r[6] = 0x20; };
|
||||
EXPECT_TRUE(protocol->torqueOff(1));
|
||||
mutate = [](Payload& r) { if (r[0] == 0x9A || r[0] == 0x9B) r[6] = 0x22; };
|
||||
EXPECT_FALSE(protocol->torqueOff(1));
|
||||
EXPECT_FALSE(protocol->clearError(1));
|
||||
}
|
||||
TEST_F(LingkongTest, ExplicitV236RejectsUndocumentedRunningStates) {
|
||||
version = LingkongCanProtocol::V2_36;
|
||||
SetUp();
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
LingkongCanProtocol::Status s;
|
||||
state = 0x30;
|
||||
ASSERT_TRUE(protocol->readStatus(1, s));
|
||||
EXPECT_FALSE(s.isRunning());
|
||||
state = 0;
|
||||
ASSERT_TRUE(protocol->readStatus(1, s));
|
||||
EXPECT_TRUE(s.isRunning());
|
||||
}
|
||||
TEST_F(LingkongTest, MixedVersionsUseSeparateProtocolInstances) {
|
||||
auto second = config;
|
||||
second.set_id(2);
|
||||
auto modern_protocol = std::make_shared<LingkongCanProtocol>(fake_send, manager, LingkongCanProtocol::V2_38);
|
||||
ASSERT_TRUE(modern_protocol->initNode(2));
|
||||
ASSERT_TRUE(modern_protocol->configureNode(2, second));
|
||||
state = 0x20;
|
||||
LingkongCanProtocol::Status old, modern;
|
||||
ASSERT_TRUE(protocol->readStatus(1, old));
|
||||
ASSERT_TRUE(modern_protocol->readStatus(2, modern));
|
||||
EXPECT_FALSE(old.isRunning()); // 0x20 is not an enabled V2.36 state.
|
||||
EXPECT_TRUE(modern.isClosed());
|
||||
EXPECT_DOUBLE_EQ(old.voltage, 48);
|
||||
EXPECT_DOUBLE_EQ(modern.voltage, 4.8);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, V238EnableAndVelocityPreserveDriveTorqueLimit) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
mutate = [](Payload& r) {
|
||||
if (r[0] == 0x9A) r[6] = 0x30;
|
||||
if (r[0] == 0xC0 && r[1] == 30) put(r, 4, 1000, 2);
|
||||
};
|
||||
ASSERT_TRUE(protocol->torqueOn(1));
|
||||
sent.clear();
|
||||
ASSERT_TRUE(protocol->commandCyclicVelocity(1, 0.1));
|
||||
ASSERT_EQ(sent.size(), 3);
|
||||
EXPECT_EQ(sent[0].data[0], 0xC0);
|
||||
EXPECT_EQ(sent[0].data[1], 30);
|
||||
EXPECT_EQ(sent[2].data[0], 0xA2);
|
||||
EXPECT_EQ(sent[2].data[2], 0xE8);
|
||||
EXPECT_EQ(sent[2].data[3], 0x03);
|
||||
}
|
||||
TEST_F(LingkongTest, V238ParameterReplyMustMatchIndex) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
mutate = [](Payload& r) { if (r[0] == 0xC0 || r[0] == 0xC1) ++r[1]; };
|
||||
int32_t raw = 0;
|
||||
EXPECT_FALSE(protocol->readControlParameter(1, 32, raw));
|
||||
EXPECT_FALSE(protocol->writeControlParameter(1, 38, 100));
|
||||
}
|
||||
TEST_F(LingkongTest, V238PermanentZeroSendsOnly19) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
mutate = [](Payload& r) { if (r[0] == 0x19) put(r, 4, 0x89abcdef, 4); };
|
||||
sent.clear();
|
||||
EXPECT_TRUE(protocol->calibrateZeroQ(1));
|
||||
ASSERT_EQ(sent.size(), 1);
|
||||
EXPECT_EQ(sent[0].data[0], 0x19);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, BothManualsCommonControlAndFeedbackFrames) {
|
||||
for (auto selected : {LingkongCanProtocol::V2_36, LingkongCanProtocol::V2_38}) {
|
||||
version = selected;
|
||||
SetUp();
|
||||
state = version == LingkongCanProtocol::V2_38 ? 0x20 : 0x10;
|
||||
ASSERT_TRUE(protocol->torqueOn(1));
|
||||
sent.clear();
|
||||
ASSERT_TRUE(protocol->commandProfilePosition(1, kPi/3, kPi/180, 0));
|
||||
const auto& f = sent.back();
|
||||
EXPECT_EQ(f.data[0], 0xA4);
|
||||
EXPECT_EQ(f.data[2], 6);
|
||||
EXPECT_EQ(f.data[3], 0);
|
||||
EXPECT_EQ(f.data[4], 0xA0);
|
||||
EXPECT_EQ(f.data[5], 0x8C);
|
||||
EXPECT_EQ(f.data[6], 0);
|
||||
EXPECT_EQ(f.data[7], 0);
|
||||
sent.clear();
|
||||
ASSERT_TRUE(protocol->quickStop(1));
|
||||
ASSERT_EQ(sent.size(), 1);
|
||||
EXPECT_EQ(sent[0].data[0], 0x81);
|
||||
ASSERT_TRUE(protocol->brakeRelease(1));
|
||||
EXPECT_EQ(sent.back().data[0], 0x8C);
|
||||
EXPECT_EQ(sent.back().data[1], 1);
|
||||
ASSERT_TRUE(protocol->torqueOff(1));
|
||||
LingkongCanProtocol::Status status;
|
||||
ASSERT_TRUE(protocol->readStatus(1, status));
|
||||
EXPECT_TRUE(status.isClosed());
|
||||
EXPECT_FALSE(status.isRunning());
|
||||
EXPECT_NEAR(protocol->getQ(1), -kPi/3, 1e-12);
|
||||
EXPECT_NEAR(protocol->getQd(1), -kPi/18, 1e-12);
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, V238ErrorStateBlocksInitializationEvenWithoutErrorBits) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
state = 0x10;
|
||||
EXPECT_FALSE(protocol->probe(1));
|
||||
}
|
||||
TEST_F(LingkongTest, V238EveryHighFaultBitBlocksMotionAndClearSuccess) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
for (int bit=0; bit<4; ++bit) {
|
||||
state = 0x30 | (1 << bit);
|
||||
EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 0), std::runtime_error);
|
||||
EXPECT_FALSE(protocol->clearError(1));
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, V238RampRequiresExplicitUnitsAndNeverWritesPid12) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
sent.clear();
|
||||
EXPECT_THROW(protocol->setLimitQdd(1, 1, -1), std::runtime_error);
|
||||
EXPECT_TRUE(sent.empty());
|
||||
}
|
||||
TEST_F(LingkongTest, V238IqConversionRemainsExplicitAndSigned) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
config.mutable_lingkong()->set_current_amp_per_lsb(0);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
double amps;
|
||||
EXPECT_FALSE(protocol->readCurrent(1, amps));
|
||||
config.mutable_lingkong()->set_current_amp_per_lsb(0.002);
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
EXPECT_TRUE(protocol->readCurrent(1, amps));
|
||||
EXPECT_DOUBLE_EQ(amps, -409 * 0.002);
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, V238AcceptsCapturedEncoderTypeOneZeroReplyWithoutReadback) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
mutate = [](Payload& r) {
|
||||
if (r[0] == 0x19) r = Payload{0x19,0,0,1,0xCC,0x9A,0,0};
|
||||
};
|
||||
sent.clear();
|
||||
EXPECT_TRUE(protocol->calibrateZeroQ(1));
|
||||
ASSERT_EQ(sent.size(),1);
|
||||
EXPECT_EQ(sent[0].data[0],0x19);
|
||||
}
|
||||
TEST_F(LingkongTest, V236StillRejectsNonzeroReservedByteInZeroReply) {
|
||||
version = LingkongCanProtocol::V2_36;
|
||||
SetUp();
|
||||
mutate = [](Payload& r) { if (r[0] == 0x19) r[3] = 1; };
|
||||
EXPECT_FALSE(protocol->calibrateZeroQ(1));
|
||||
}
|
||||
TEST_F(LingkongTest, V238ZeroReplyStillValidatesReservedBytes) {
|
||||
version = LingkongCanProtocol::V2_38;
|
||||
SetUp();
|
||||
for (int byte : {1,2}) {
|
||||
mutate = [byte](Payload& r) { if (r[0] == 0x19) r[byte] = 1; };
|
||||
EXPECT_FALSE(protocol->calibrateZeroQ(1));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LingkongTest, ProductionDefaultIsStrictV236NotHistoricalSitePolicy) {
|
||||
protocol = std::make_shared<LingkongCanProtocol>(fake_send, manager);
|
||||
// A fresh manager is required because registration owns response parsers.
|
||||
manager = std::make_shared<MessageManager<msgs::RobotDetail>>();
|
||||
protocol = std::make_shared<LingkongCanProtocol>(fake_send, manager);
|
||||
ASSERT_TRUE(protocol->initNode(1));
|
||||
ASSERT_TRUE(protocol->configureNode(1, config));
|
||||
state = 0x30;
|
||||
EXPECT_THROW(protocol->commandProfilePosition(1,0.1,0.1,0),std::runtime_error);
|
||||
state = 0;
|
||||
EXPECT_TRUE(protocol->commandProfilePosition(1,0.1,0.1,0));
|
||||
}
|
||||
TEST_F(LingkongTest, BothVersionsRejectInvalidProfileAccelerationBeforeCan) {
|
||||
for(auto selected:{LingkongCanProtocol::V2_36,LingkongCanProtocol::V2_38}) {
|
||||
version=selected;SetUp();sent.clear();
|
||||
for(double invalid:{-1.0,std::numeric_limits<double>::quiet_NaN(),std::numeric_limits<double>::infinity()}) {
|
||||
EXPECT_FALSE(protocol->commandProfilePosition(1,0.1,0.1,invalid));
|
||||
EXPECT_FALSE(protocol->commandProfileVelocity(1,0.1,invalid));
|
||||
}
|
||||
EXPECT_TRUE(sent.empty());
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, V236RejectsAllFiveReservedBytesInZeroAcknowledgement) {
|
||||
version=LingkongCanProtocol::V2_36;SetUp();
|
||||
for(int byte=1;byte<=5;++byte) {
|
||||
mutate=[byte](Payload& r){if(r[0]==0x19)r[byte]=1;};
|
||||
EXPECT_FALSE(protocol->calibrateZeroQ(1));
|
||||
}
|
||||
mutate=[](Payload& r){if(r[0]==0x19)put(r,6,65535,2);};
|
||||
EXPECT_TRUE(protocol->calibrateZeroQ(1));
|
||||
}
|
||||
TEST_F(LingkongTest, V238AcceptsEncoderTypeAsDataNotReservedByte) {
|
||||
version=LingkongCanProtocol::V2_38;SetUp();
|
||||
for(auto type:{0,1,2,255}) {
|
||||
mutate=[type](Payload& r){if(r[0]==0x19){r[3]=type;put(r,4,0xffffffffu,4);}};
|
||||
EXPECT_TRUE(protocol->calibrateZeroQ(1));
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, BothVersionsRecoverAfterTransportThrowsWithoutAutoRetry) {
|
||||
for(auto selected:{LingkongCanProtocol::V2_36,LingkongCanProtocol::V2_38}) {
|
||||
version=selected;SetUp();
|
||||
mutate=[](Payload&){throw std::runtime_error("fake transport failure");};
|
||||
sent.clear();EXPECT_THROW(protocol->getQ(1),std::runtime_error);
|
||||
EXPECT_EQ(sent.size(),1);
|
||||
mutate={};EXPECT_NEAR(protocol->getQ(1),-kPi/3,1e-12);
|
||||
EXPECT_EQ(sent.size(),2);
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, BothVersionsSigned56BitAngleExtremes) {
|
||||
for(auto selected:{LingkongCanProtocol::V2_36,LingkongCanProtocol::V2_38}) {
|
||||
version=selected;SetUp();
|
||||
for(int64_t value:{-(int64_t(1)<<55),(int64_t(1)<<55)-1,int64_t(-1),int64_t(0)}) {
|
||||
angle=value;
|
||||
EXPECT_DOUBLE_EQ(protocol->getQ(1),double(value)/(100.0*(180.0/kPi*6)));
|
||||
}
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, V238EveryErrorBitIsPreservedAndRejectsClearSuccess) {
|
||||
version=LingkongCanProtocol::V2_38;SetUp();
|
||||
for(int bit=0;bit<12;++bit) {
|
||||
int mask=1<<bit;state=0x30|((mask>>8)&15);error=mask&255;
|
||||
LingkongCanProtocol::Status s;ASSERT_TRUE(protocol->readStatus(1,s));
|
||||
EXPECT_EQ(s.error,mask);EXPECT_FALSE(s.isRunning());EXPECT_TRUE(s.isFault());
|
||||
EXPECT_FALSE(protocol->clearError(1));
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, V238AllStateNibblesOnlyOnAndOffAreRecognized) {
|
||||
version=LingkongCanProtocol::V2_38;SetUp();
|
||||
for(int code=0;code<16;++code) {
|
||||
state=code<<4;error=0;LingkongCanProtocol::Status s;
|
||||
ASSERT_TRUE(protocol->readStatus(1,s));
|
||||
EXPECT_EQ(s.isRunning(),code==3);EXPECT_EQ(s.isClosed(),code==2);
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, BothVersionsParameterCommandsCannotCrossVersions) {
|
||||
for(auto selected:{LingkongCanProtocol::V2_36,LingkongCanProtocol::V2_38}) {
|
||||
version=selected;SetUp();sent.clear();
|
||||
int32_t value=0;bool modern=version==LingkongCanProtocol::V2_38;
|
||||
EXPECT_TRUE(protocol->readControlParameter(1,modern?30:10,value));
|
||||
EXPECT_EQ(sent.back().data[0],modern?0xC0:0xB0);
|
||||
EXPECT_TRUE(protocol->writeControlParameter(1,modern?30:10,1000));
|
||||
EXPECT_EQ(sent.back().data[0],modern?0xC1:0xB1);
|
||||
EXPECT_FALSE(protocol->writeControlParameter(1,modern?14:32,1000));
|
||||
}
|
||||
}
|
||||
TEST_F(LingkongTest, InvalidProtocolSelectionAndOverflowGearAreRejected) {
|
||||
auto mgr=std::make_shared<MessageManager<msgs::RobotDetail>>();
|
||||
auto p=std::make_shared<LingkongCanProtocol>(fake_send,mgr,static_cast<LingkongCanProtocol::ProtocolVersion>(999));
|
||||
EXPECT_FALSE(p->initNode(1));
|
||||
config.set_gear_ratio(std::numeric_limits<double>::max());
|
||||
EXPECT_FALSE(protocol->configureNode(1,config));
|
||||
}
|
||||
@ -10,6 +10,7 @@ target_link_libraries(motor_manager
|
||||
cmvr_es::device::motor_core
|
||||
cmvr_es::device::motor_bus_runtime
|
||||
PRIVATE
|
||||
cmvr_es::device::lingkong_can_motor_driver
|
||||
cmvr_es::device::ti5_canopen_motor_driver
|
||||
cmvr_es::device::mujoco_motor_driver
|
||||
cmvr_es::device::ethercat_motor_driver
|
||||
|
||||
@ -39,6 +39,9 @@ public:
|
||||
DeviceKind kind() const noexcept override { return DeviceKind::MotorSystem; }
|
||||
std::string typeName() const override { return "MotorManager"; }
|
||||
|
||||
static std::vector<const config::MotorGroupConfig*> selectGroups(
|
||||
const config::MotorConfig& config, const std::string& selected_id);
|
||||
std::vector<std::shared_ptr<AbstractMotor>> motorsSnapshot() const;
|
||||
bool init() override;
|
||||
bool stop() override;
|
||||
|
||||
|
||||
@ -25,7 +25,9 @@
|
||||
#include "devices/motor/drivers/mujoco/include/mujoco_motor.h"
|
||||
#include "devices/motor/drivers/ti5_canopen/include/ti5_motor.h"
|
||||
#include "devices/motor/drivers/ti5_canopen/include/ti5_motor_canopen_protocol.h"
|
||||
#include <unordered_set>
|
||||
#include "environment/include/robot_model.h"
|
||||
#include "devices/motor/drivers/lingkong_can/include/lingkong_motor.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
@ -44,6 +46,31 @@ MotorManager::MotorManager(std::string id,
|
||||
|
||||
MotorManager::~MotorManager() = default;
|
||||
|
||||
std::vector<const config::MotorGroupConfig*> MotorManager::selectGroups(
|
||||
const config::MotorConfig& cfg, const std::string& selected_id)
|
||||
{
|
||||
if (selected_id.empty()) return {};
|
||||
std::vector<const config::MotorGroupConfig*> exact;
|
||||
for (const auto& group : cfg.motor_groups())
|
||||
if (group.id() == selected_id) exact.push_back(&group);
|
||||
if (exact.size() > 1) return {};
|
||||
if (exact.size() == 1) return exact; // Existing single-group semantics win.
|
||||
if (cfg.id() != selected_id || cfg.motor_groups().empty()) return {};
|
||||
std::vector<const config::MotorGroupConfig*> selected;
|
||||
std::unordered_set<std::string> groups, joints;
|
||||
std::unordered_set<int> ids;
|
||||
for (const auto& group : cfg.motor_groups()) {
|
||||
if (group.id().empty() || !groups.insert(group.id()).second ||
|
||||
!group.has_motors() || group.motors().motors().empty()) return {};
|
||||
for (const auto& motor : group.motors().motors()) {
|
||||
if (motor.id() <= 0 || motor.joint_name().empty() ||
|
||||
!ids.insert(motor.id()).second || !joints.insert(motor.joint_name()).second) return {};
|
||||
}
|
||||
selected.push_back(&group);
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
bool MotorManager::init()
|
||||
{
|
||||
if (initialized_) {
|
||||
@ -75,11 +102,13 @@ bool MotorManager::init()
|
||||
motors_by_joint_.clear();
|
||||
}
|
||||
|
||||
const auto selected_groups = selectGroups(cfg_, selected_group_id_);
|
||||
if (selected_groups.empty()) return false;
|
||||
bool all_ok = true;
|
||||
std::size_t selected_group_count = 0;
|
||||
for (const auto& motor_group_cfg : cfg_.motor_groups()) {
|
||||
const auto& group_name = motor_group_cfg.id();
|
||||
if (group_name != selected_group_id_) {
|
||||
if (std::find(selected_groups.begin(), selected_groups.end(), &motor_group_cfg) == selected_groups.end()) {
|
||||
continue;
|
||||
}
|
||||
++selected_group_count;
|
||||
@ -200,7 +229,7 @@ bool MotorManager::init()
|
||||
bus_runtimes_.push_back(std::move(bus_runtime));
|
||||
}
|
||||
|
||||
if (selected_group_count != 1) {
|
||||
if (selected_group_count != selected_groups.size()) {
|
||||
CMVR_LOG(ERROR) << "[MotorManager] selected motor group '" << selected_group_id_
|
||||
<< "' must occur exactly once in config: " << id_;
|
||||
all_ok = false;
|
||||
@ -324,6 +353,17 @@ bool MotorManager::commandCyclicPositionsAtomic(
|
||||
if (std::dynamic_pointer_cast<MujocoMotor>(motors.front())) {
|
||||
return MujocoMotor::commandCyclicPositionsAtomic(motors, positions, velocities);
|
||||
}
|
||||
if (std::dynamic_pointer_cast<LingkongMotor>(motors.front())) {
|
||||
for (std::size_t i = 0; i < motors.size(); ++i) {
|
||||
if (!std::dynamic_pointer_cast<LingkongMotor>(motors[i]) ||
|
||||
!std::isfinite(positions[i]) || !std::isfinite(velocities[i])) return false;
|
||||
}
|
||||
// Vendor CAN requests are per motor, not synchronized/atomic PDOs.
|
||||
for (std::size_t i = 0; i < motors.size(); ++i) {
|
||||
if (!motors[i]->commandCyclicPosition(positions[i], velocities[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (std::dynamic_pointer_cast<Ti5Motor>(motors.front())) {
|
||||
// TI5 currently exposes only a per-motor RPDO command. Keep the
|
||||
// fallback here so callers retain one manager-level entry point.
|
||||
@ -373,6 +413,44 @@ bool MotorManager::commandCyclicVelocitiesAtomic(
|
||||
if (std::dynamic_pointer_cast<MujocoMotor>(motors.front())) {
|
||||
return MujocoMotor::commandCyclicVelocitiesAtomic(motors, velocities);
|
||||
}
|
||||
if (std::dynamic_pointer_cast<LingkongMotor>(motors.front())) {
|
||||
for (const auto& motor : motors) {
|
||||
if (!std::dynamic_pointer_cast<LingkongMotor>(motor)) return false;
|
||||
}
|
||||
auto stop_all = [&]() {
|
||||
bool ok = true;
|
||||
for (const auto& motor : motors) {
|
||||
try {
|
||||
if (!motor->quickStop()) ok = false;
|
||||
} catch (const std::exception& error) {
|
||||
CMVR_LOG(ERROR) << "[MotorManager] Lingkong stop failed: node="
|
||||
<< int(motor->id()) << ", " << error.what();
|
||||
ok = false;
|
||||
} catch (...) {
|
||||
CMVR_LOG(ERROR) << "[MotorManager] Lingkong stop failed: node=" << int(motor->id());
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
return ok;
|
||||
};
|
||||
if (std::all_of(velocities.begin(), velocities.end(), [](double v) { return v == 0.0; }))
|
||||
return stop_all(); // Both manuals specify 0x81; no mode/enable prerequisite.
|
||||
try {
|
||||
for (std::size_t i = 0; i < motors.size(); ++i) {
|
||||
if (!motors[i]->commandCyclicVelocity(velocities[i])) {
|
||||
(void)stop_all();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (const std::exception& error) {
|
||||
CMVR_LOG(ERROR) << "[MotorManager] Lingkong velocity group failed: " << error.what();
|
||||
} catch (...) {
|
||||
CMVR_LOG(ERROR) << "[MotorManager] Lingkong velocity group failed with unknown exception";
|
||||
}
|
||||
(void)stop_all();
|
||||
return false;
|
||||
}
|
||||
if (std::dynamic_pointer_cast<Ti5Motor>(motors.front())) {
|
||||
for (const auto& motor : motors) {
|
||||
if (!std::dynamic_pointer_cast<Ti5Motor>(motor)) {
|
||||
@ -443,6 +521,16 @@ bool MotorManager::readFeedbacksAtomic(
|
||||
if (std::dynamic_pointer_cast<MujocoMotor>(motors.front())) {
|
||||
return MujocoMotor::readFeedbacksAtomic(motors, positions, velocities);
|
||||
}
|
||||
if (std::dynamic_pointer_cast<LingkongMotor>(motors.front())) {
|
||||
std::vector<double> q(motors.size()), qd(motors.size());
|
||||
for (std::size_t i = 0; i < motors.size(); ++i) {
|
||||
auto motor = std::dynamic_pointer_cast<LingkongMotor>(motors[i]);
|
||||
if (!motor || !motor->readFeedback(q[i], qd[i])) return false;
|
||||
}
|
||||
positions = std::move(q);
|
||||
velocities = std::move(qd);
|
||||
return true;
|
||||
}
|
||||
if (std::dynamic_pointer_cast<Ti5Motor>(motors.front())) {
|
||||
for (const auto& motor : motors) {
|
||||
if (!std::dynamic_pointer_cast<Ti5Motor>(motor)) {
|
||||
@ -666,6 +754,33 @@ std::vector<std::shared_ptr<AbstractMotor>> MotorManager::createCanMotors_(
|
||||
CMVR_LOG(ERROR) << "[MotorManager] missing CAN config: " << group_cfg.id();
|
||||
return {};
|
||||
}
|
||||
if (group_cfg.vendor() == config::MOTOR_VENDOR_LINGKONG &&
|
||||
(group_cfg.protocol() == config::MOTOR_PROTOCOL_LINGKONG_CAN ||
|
||||
group_cfg.protocol() == config::MOTOR_PROTOCOL_LINGKONG_CAN_V2_38)) {
|
||||
auto client = can_bus_runtime->client();
|
||||
if (!client) return {};
|
||||
auto protocol = std::make_shared<LingkongCanProtocol>(
|
||||
[client](const CanFrame& frame) {
|
||||
return client->sendSingleFrame({frame}) == msgs::ErrorCode::OK;
|
||||
}, can_bus_runtime->messageManager(),
|
||||
group_cfg.protocol() == config::MOTOR_PROTOCOL_LINGKONG_CAN_V2_38
|
||||
? LingkongCanProtocol::V2_38 : LingkongCanProtocol::V2_36);
|
||||
CMVR_LOG(INFO) << "[MotorManager] Lingkong protocol selected: group=" << group_cfg.id()
|
||||
<< ", protocol=" << config::MotorProtocol_Name(group_cfg.protocol())
|
||||
<< ", channel=" << group_cfg.can().channel_id();
|
||||
std::vector<std::shared_ptr<AbstractMotor>> motors;
|
||||
motors.reserve(motor_cfgs.size());
|
||||
for (const auto& cfg : motor_cfgs) {
|
||||
if (cfg.id() < 1 || cfg.id() > 32) {
|
||||
CMVR_LOG(ERROR) << "[MotorManager] Lingkong CAN ID must be in [1, 32]";
|
||||
return {};
|
||||
}
|
||||
auto motor = std::make_shared<LingkongMotor>(cfg);
|
||||
if (!motor->setProtocol(protocol)) return {};
|
||||
motors.push_back(std::move(motor));
|
||||
}
|
||||
return motors;
|
||||
}
|
||||
if (group_cfg.vendor() != config::MOTOR_VENDOR_TI5 ||
|
||||
group_cfg.protocol() != config::MOTOR_PROTOCOL_CANOPEN) {
|
||||
CMVR_LOG(ERROR) << "[MotorManager] unsupported CAN motor: vendor="
|
||||
@ -786,4 +901,12 @@ std::vector<std::shared_ptr<AbstractMotor>> MotorManager::createEthercatMotors_(
|
||||
return motors;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<AbstractMotor>> MotorManager::motorsSnapshot() const
|
||||
{
|
||||
std::lock_guard lock(motors_mutex_);
|
||||
std::vector<std::shared_ptr<AbstractMotor>> result;
|
||||
for (const auto& entry:motors_by_id_) if (entry.second) result.push_back(entry.second);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
@ -122,6 +122,7 @@ namespace cmvr::device{
|
||||
int fps;
|
||||
int width;
|
||||
int height;
|
||||
std::string codec; ///< 当前配置或正在使用的视频编码器
|
||||
};
|
||||
|
||||
/// @brief 从 XML 或其他配置中读取的相机网络参数
|
||||
|
||||
@ -41,11 +41,18 @@ struct JointLimit {
|
||||
// immutable and shared when this object is copied; live robot state is external.
|
||||
struct RobotModel {
|
||||
std::string name;
|
||||
// Preserve linbo_dev's vendor metadata alongside the shared model.
|
||||
std::string subtype;
|
||||
std::string description_id;
|
||||
std::string default_base_frame;
|
||||
std::string default_tcp_frame;
|
||||
bool detected_from_sdk{false};
|
||||
std::string manufacturer;
|
||||
std::string serial_number;
|
||||
std::size_t dof{0};
|
||||
std::vector<std::string> joint_names;
|
||||
std::vector<JointLimit> joint_limits;
|
||||
std::string joint_limits_source;
|
||||
double max_tcp_speed{0.0};
|
||||
double max_tcp_acceleration{0.0};
|
||||
double max_payload{0.0};
|
||||
|
||||
@ -253,21 +253,8 @@ DeviceFactory::DeviceFactory()
|
||||
return DeviceRecord{};
|
||||
}
|
||||
|
||||
const config::MotorGroupConfig* selected_group = nullptr;
|
||||
for (const auto& group_cfg : root_cfg.motor().motor_groups()) {
|
||||
if (group_cfg.id() != entry.id()) {
|
||||
continue;
|
||||
}
|
||||
if (selected_group != nullptr) {
|
||||
CMVR_LOG(ERROR) << "[DeviceFactory]: Duplicate motor group id '"
|
||||
<< entry.id() << "' in config: " << entry.config_file();
|
||||
return DeviceRecord{};
|
||||
}
|
||||
selected_group = &group_cfg;
|
||||
}
|
||||
if (selected_group == nullptr) {
|
||||
CMVR_LOG(ERROR) << "[DeviceFactory]: Motor group id '" << entry.id()
|
||||
<< "' not found in config: " << entry.config_file();
|
||||
if (MotorManager::selectGroups(root_cfg.motor(), entry.id()).empty()) {
|
||||
CMVR_LOG(ERROR) << "[DeviceFactory]: Invalid motor group/system selection: " << entry.id();
|
||||
return DeviceRecord{};
|
||||
}
|
||||
CMVR_LOG(INFO) << "[DeviceFactory]: Read device config success";
|
||||
|
||||
@ -10,6 +10,7 @@ add_library(service
|
||||
grpc/src/grpc_head_joint_service.cpp
|
||||
grpc/src/grpc_dexhand_service.cpp
|
||||
grpc/src/grpc_arm_service.cpp
|
||||
grpc/src/grpc_motor_service.cpp
|
||||
grpc/src/grpc_agv_service.cpp
|
||||
grpc/src/grpc_hlc_service.cpp
|
||||
../task/grpc_server_task/src/grpc_server_task.cpp
|
||||
@ -18,9 +19,11 @@ add_library(service
|
||||
target_include_directories(service PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
target_link_libraries(service PRIVATE
|
||||
cmvr_es::device::ethercat_motor_driver
|
||||
cmvr_es::proto
|
||||
osqp
|
||||
cmvr_es::device_manager
|
||||
cmvr_es::device::oymotion_ap001
|
||||
cmvr_es::task_manager
|
||||
cmvr_es::algorithms::controller
|
||||
cmvr_es::task
|
||||
@ -32,7 +35,17 @@ target_link_libraries(service PRIVATE
|
||||
add_library(cmvr_es::service ALIAS service)
|
||||
install(TARGETS service LIBRARY DESTINATION lib)
|
||||
|
||||
add_executable(grpc_shutdown_test grpc/tests/grpc_shutdown_test.cpp)
|
||||
target_include_directories(grpc_shutdown_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es/manager/device_manager)
|
||||
target_link_libraries(grpc_shutdown_test PRIVATE cmvr_es::service gtest gtest_main pthread)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_test(NAME grpc_shutdown_test COMMAND grpc_shutdown_test)
|
||||
set_tests_properties(grpc_shutdown_test PROPERTIES TIMEOUT 20)
|
||||
add_executable(motor_service_test grpc/tests/motor_service_test.cpp)
|
||||
target_include_directories(motor_service_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es/manager/device_manager)
|
||||
target_link_libraries(motor_service_test PRIVATE cmvr_es::service cmvr_es::device::motor_manager gtest gtest_main pthread)
|
||||
add_test(NAME motor_service_test COMMAND motor_service_test)
|
||||
enable_testing()
|
||||
add_executable(action_queue_test
|
||||
grpc/action/tests/action_queue_test.cpp
|
||||
|
||||
@ -40,6 +40,8 @@ bool finiteNonNegative(const double value)
|
||||
const char* actionCommandName(const api::ActionStep::CommandCase command)
|
||||
{
|
||||
switch (command) {
|
||||
case api::ActionStep::kArmApplyUserCoordinate:
|
||||
return "ApplyUserCoordinateSystem";
|
||||
case api::ActionStep::kArmMoveJ:
|
||||
return "MoveJ";
|
||||
case api::ActionStep::kArmMoveL:
|
||||
@ -162,6 +164,30 @@ struct ActionQueue::Impl {
|
||||
|
||||
void registerCommands()
|
||||
{
|
||||
handlers.emplace(
|
||||
api::ActionStep::kArmApplyUserCoordinate,
|
||||
CommandHandler{
|
||||
[this](const api::ActionStep& step,const std::size_t index,
|
||||
PreparedStep& prepared,std::string& error){
|
||||
const auto& command=step.arm_apply_user_coordinate();
|
||||
return prepareArmStep(step,command.header().device_id(),index,
|
||||
api::MotionOptions{},prepared,error,[&command,&error](const device::RobotArm&){
|
||||
if(command.name().empty()){
|
||||
error="coordinate name is required";return false;
|
||||
}
|
||||
if(command.has_coordinate()){
|
||||
error="queue coordinate selection accepts only name and expected_revision; save the coordinate before submitting";return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
},
|
||||
[](const PreparedStep& prepared,const std::function<bool()>& canceled){
|
||||
if(canceled())return device::Result::failure(device::ArmErrorCode::CommandRejected,"coordinate selection canceled before execution");
|
||||
const auto& command=prepared.source.arm_apply_user_coordinate();
|
||||
// Do not reacquire the arbiter: the queue owns the lease for its full duration.
|
||||
return prepared.arm->applyUserCoordinateSystem(command.name(),command.expected_revision());
|
||||
}});
|
||||
|
||||
handlers.emplace(
|
||||
api::ActionStep::kArmMoveJ,
|
||||
CommandHandler{
|
||||
|
||||
@ -45,6 +45,14 @@ public:
|
||||
}
|
||||
bool supportsActionQueueMotion() const noexcept override { return true; }
|
||||
|
||||
bool fail_coordinate=false;
|
||||
device::Result applyUserCoordinateSystem(const std::string& name,std::uint64_t revision) override {
|
||||
std::lock_guard lock(mutex_);
|
||||
calls_.push_back("Apply:"+name);
|
||||
if(fail_coordinate || revision==999)return device::Result::failure(device::ArmErrorCode::InvalidArgument,"coordinate missing or revision changed");
|
||||
selected_coordinate_=name;return device::Result::success();
|
||||
}
|
||||
std::vector<std::string> motionCoordinates() const {std::lock_guard lock(mutex_);return motion_coordinates_;}
|
||||
device::Result torqueOn() override { return device::Result::success(); }
|
||||
device::Result torqueOff() override { return device::Result::success(); }
|
||||
device::Result calibrateZeroQ(const std::string&) override { return device::Result::success(); }
|
||||
@ -78,6 +86,7 @@ public:
|
||||
const device::MotionOptions& options,
|
||||
device::FrameType) override
|
||||
{
|
||||
{std::lock_guard lock(mutex_);motion_coordinates_.push_back(selected_coordinate_);}
|
||||
return runMotion("MoveL", options);
|
||||
}
|
||||
device::Result moveL(const device::CartesianPose&,
|
||||
@ -170,6 +179,8 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
std::string selected_coordinate_;
|
||||
std::vector<std::string> motion_coordinates_;
|
||||
device::Result runMotion(const std::string& name,
|
||||
const device::MotionOptions& options)
|
||||
{
|
||||
@ -241,6 +252,43 @@ api::ActionQueueCommand_Request twoStepRequest(const std::string& device_id)
|
||||
return request;
|
||||
}
|
||||
|
||||
TEST(ActionQueueTest, AppliesCoordinatesBeforeEachMoveL)
|
||||
{
|
||||
auto arm=std::make_shared<FakeActionQueueArm>("coordinate_queue");auto queue=makeQueue(arm);
|
||||
api::ActionQueueCommand_Request request;
|
||||
for(const auto* name:{"fixture_a","__builtin_base__"}){
|
||||
auto* apply=request.add_steps()->mutable_arm_apply_user_coordinate();
|
||||
apply->mutable_header()->set_device_id(arm->id());apply->set_name(name);apply->set_expected_revision(1);
|
||||
auto* move=request.add_steps()->mutable_arm_move_l();move->mutable_header()->set_device_id(arm->id());
|
||||
}
|
||||
api::ActionQueueCommand_Feedback result;queue.execute(request,result);
|
||||
EXPECT_TRUE(result.header().success())<<result.header().error_message();EXPECT_EQ(result.completed_steps(),4U);
|
||||
EXPECT_EQ(arm->calls(),(std::vector<std::string>{"Apply:fixture_a","MoveL","Apply:__builtin_base__","MoveL"}));
|
||||
EXPECT_EQ(arm->motionCoordinates(),(std::vector<std::string>{"fixture_a","__builtin_base__"}));
|
||||
}
|
||||
|
||||
TEST(ActionQueueTest, FailedCoordinateDoesNotRunFollowingMotion)
|
||||
{
|
||||
for(bool fail:{false,true}){
|
||||
auto arm=std::make_shared<FakeActionQueueArm>("coordinate_failure");arm->fail_coordinate=fail;auto queue=makeQueue(arm);
|
||||
api::ActionQueueCommand_Request request;
|
||||
auto* apply=request.add_steps()->mutable_arm_apply_user_coordinate();apply->mutable_header()->set_device_id(arm->id());
|
||||
apply->set_name("fixture");apply->set_expected_revision(fail?1:999);
|
||||
request.add_steps()->mutable_arm_move_l()->mutable_header()->set_device_id(arm->id());
|
||||
api::ActionQueueCommand_Feedback result;queue.execute(request,result);
|
||||
EXPECT_EQ(result.result(),api::ACTION_RESULT_CODE_FAILED);EXPECT_EQ(result.completed_steps(),0U);EXPECT_EQ(result.failed_step_index(),0U);
|
||||
EXPECT_EQ(arm->calls(),(std::vector<std::string>{"Apply:fixture"}));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ActionQueueTest, InvalidCoordinateStepRejectsWholeQueue)
|
||||
{
|
||||
auto arm=std::make_shared<FakeActionQueueArm>("coordinate_invalid");auto queue=makeQueue(arm);
|
||||
auto request=twoStepRequest(arm->id());request.add_steps()->mutable_arm_apply_user_coordinate()->mutable_header()->set_device_id(arm->id());
|
||||
api::ActionQueueCommand_Feedback result;queue.execute(request,result);
|
||||
EXPECT_EQ(result.result(),api::ACTION_RESULT_CODE_REJECTED);EXPECT_TRUE(arm->calls().empty());
|
||||
}
|
||||
|
||||
TEST(ActionQueueTest, ExecutesMoveJAndNamedFrameMoveLInOrder)
|
||||
{
|
||||
auto arm = std::make_shared<FakeActionQueueArm>("action_arm_order");
|
||||
|
||||
@ -69,8 +69,44 @@ public:
|
||||
grpc::ServerContext* context,
|
||||
const api::JsonDeviceCommand_Request* request,
|
||||
api::JsonDeviceCommand_Feedback* response) override;
|
||||
grpc::Status EnterTeachingMode(
|
||||
grpc::ServerContext* context,
|
||||
const api::CommandHeader_Request* request,
|
||||
api::CommandHeader_Feedback* response) override;
|
||||
grpc::Status StartTrajectoryRecording(
|
||||
grpc::ServerContext* context,
|
||||
const api::StartTrajectoryRecording_Request* request,
|
||||
api::StartTrajectoryRecording_Response* response) override;
|
||||
grpc::Status CompleteTeaching(
|
||||
grpc::ServerContext* context,
|
||||
const api::CommandHeader_Request* request,
|
||||
api::CommandHeader_Feedback* response) override;
|
||||
grpc::Status StopTrajectoryRecording(
|
||||
grpc::ServerContext* context,
|
||||
const api::CommandHeader_Request* request,
|
||||
api::CommandHeader_Feedback* response) override;
|
||||
grpc::Status ExitTeachingMode(
|
||||
grpc::ServerContext* context,
|
||||
const api::CommandHeader_Request* request,
|
||||
api::CommandHeader_Feedback* response) override;
|
||||
|
||||
private:
|
||||
grpc::Status CalibrateUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status CreateUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status GetUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status ListUserCoordinateSystems(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status UpdateUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status DeleteUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status ApplyUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status coordinateCommand(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*, const std::string& operation);
|
||||
grpc::Status ListRecordedTrajectories(grpc::ServerContext*,
|
||||
const api::ListRecordedTrajectories_Request*, api::ListRecordedTrajectories_Response*) override;
|
||||
grpc::Status MoveToTrajectoryStart(grpc::ServerContext*,
|
||||
const api::ReplayRecordedTrajectory_Request*, api::ReplayRecordedTrajectory_Response*) override;
|
||||
grpc::Status ReplayRecordedTrajectory(grpc::ServerContext*,
|
||||
const api::ReplayRecordedTrajectory_Request*, api::ReplayRecordedTrajectory_Response*) override;
|
||||
grpc::Status replayTrajectory(grpc::ServerContext*, const api::ReplayRecordedTrajectory_Request*,
|
||||
api::ReplayRecordedTrajectory_Response*, bool to_start);
|
||||
device::DeviceManager& dmgr_;
|
||||
};
|
||||
|
||||
|
||||
94
cmvr-es/service/grpc/include/grpc_motor_service.h
Normal file
94
cmvr-es/service/grpc/include/grpc_motor_service.h
Normal file
@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
|
||||
#include "cmvr/api/motor_service.grpc.pb.h"
|
||||
#include "devices/motor/abstract_motor.h"
|
||||
#include "manager/device_manager/include/device_manager.h"
|
||||
|
||||
#include <mutex>
|
||||
|
||||
namespace cmvr::service {
|
||||
|
||||
class gRPCMotorServiceImpl final : public api::MotorService::Service {
|
||||
public:
|
||||
gRPCMotorServiceImpl();
|
||||
~gRPCMotorServiceImpl() override = default;
|
||||
|
||||
grpc::Status ListMotors(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorListResponse* response) override;
|
||||
grpc::Status GetInfo(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status GetState(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status getMode(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status getQ(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status getQd(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status getTau(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status reachedTargetQ(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status setMode(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status torqueOn(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status torqueOff(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status brakeRelease(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status quickStop(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status calibrateZeroQ(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status commandProfilePosition(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status commandProfileVelocity(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status commandProfileTorque(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status commandCyclicPosition(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status commandCyclicVelocity(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status commandCyclicTorque(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status setLimitQ(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status setLimitQd(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
grpc::Status setLimitQdd(grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response) override;
|
||||
|
||||
private:
|
||||
std::shared_ptr<device::AbstractMotor> getMotor(const api::MotorRequest* request);
|
||||
|
||||
device::DeviceManager& dmgr_;
|
||||
// Driver getters and setters share cached data; serialize RPC access only.
|
||||
std::mutex motor_mutex_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::service
|
||||
@ -1,6 +1,9 @@
|
||||
#include "service/grpc/include/grpc_arm_service.h"
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
#include "devices/arm/aubo_arm/include/user_coordinate_store.h"
|
||||
|
||||
#include <google/protobuf/util/time_util.h>
|
||||
#include <cmath>
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
#include "service/grpc/action/include/control_command_arbiter.h"
|
||||
@ -25,6 +28,17 @@ grpc::Status resultToStatus(const device::Result& result)
|
||||
if (result.ok()) {
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
if (result.code == device::ArmErrorCode::UnsupportedCommand) {
|
||||
return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, result.message);
|
||||
}
|
||||
if (result.code == device::ArmErrorCode::InvalidArgument) {
|
||||
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, result.message);
|
||||
}
|
||||
if (result.code == device::ArmErrorCode::NotConnected ||
|
||||
result.code == device::ArmErrorCode::RobotNotReady) {
|
||||
return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
|
||||
result.message);
|
||||
}
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, result.message);
|
||||
}
|
||||
|
||||
@ -102,6 +116,7 @@ void fillJointState(api::JointState* dst,
|
||||
for (const double value : src.position) dst->add_position(value);
|
||||
for (const double value : src.velocity) dst->add_velocity(value);
|
||||
for (const double value : src.effort) dst->add_effort(value);
|
||||
for (const double value : src.current) dst->add_current(value);
|
||||
dst->set_timestamp(timestamp);
|
||||
}
|
||||
|
||||
@ -315,17 +330,37 @@ grpc::Status gRPCArmServiceImpl::moveL(grpc::ServerContext* context,
|
||||
const api::MoveL_Request* request,
|
||||
api::MoveL_Response* response)
|
||||
{
|
||||
const char* stage="control_acquire";
|
||||
const auto log_failure=[request](const char* failure_stage,const std::string& error) {
|
||||
CMVR_LOG(ERROR) << "[gRPCArmServiceImpl] (moveL): failed, id=" << request->header().device_id()
|
||||
<< ", stage=" << failure_stage
|
||||
<< ", coordinate=" << request->user_coordinate_name()
|
||||
<< ", requested_revision=" << request->user_coordinate_revision()
|
||||
<< ", relative_translation=" << request->coordinate_relative_translation()
|
||||
<< ", frame=" << request->frame()
|
||||
<< ", base_frame=" << request->base_frame()
|
||||
<< ", tcp_frame=" << request->tcp_frame()
|
||||
<< ", error=" << error;
|
||||
};
|
||||
const auto finish_result=[&](const device::Result& result) {
|
||||
if(!result.ok())log_failure(stage,result.message);
|
||||
return setResponseResult(response,result);
|
||||
};
|
||||
auto control_lease =
|
||||
ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if (!control_lease) {
|
||||
log_failure(stage,"control command rejected while ActionQueue or StopAll is active");
|
||||
return setControlBusy(response);
|
||||
}
|
||||
try {
|
||||
const std::string device_id = request->header().device_id();
|
||||
stage="device_lookup";
|
||||
auto arm = dmgr_.getDevice<device::RobotArm>(device_id);
|
||||
if (!arm) {
|
||||
log_failure(stage,"device not found");
|
||||
return setDeviceNotFound(response, device_id);
|
||||
}
|
||||
stage="parameter_validation";
|
||||
const bool has_named_frame =
|
||||
(request->has_base_frame() && !request->base_frame().empty()) ||
|
||||
(request->has_tcp_frame() && !request->tcp_frame().empty());
|
||||
@ -338,7 +373,41 @@ grpc::Status gRPCArmServiceImpl::moveL(grpc::ServerContext* context,
|
||||
<< ", velocity=" << options.velocity
|
||||
<< ", acceleration=" << options.acceleration
|
||||
<< ", frame=" << request->frame();
|
||||
const auto result = has_named_frame
|
||||
const bool explicit_user_frame = request->user_frame_pose_size() || request->tcp_offset_size();
|
||||
device::Result result;
|
||||
if(request->coordinate_relative_translation())return finish_result(device::Result::failure(device::ArmErrorCode::UnsupportedCommand,"incremental MoveL is not supported; send an absolute XYZ/RX/RY/RZ target in the selected coordinate system and omit coordinate_relative_translation or set it false"));
|
||||
if (!request->user_coordinate_name().empty()) {
|
||||
auto aubo=std::dynamic_pointer_cast<device::AuboArm>(arm);
|
||||
if(!aubo || has_named_frame || explicit_user_frame)
|
||||
return finish_result(device::Result::failure(device::ArmErrorCode::InvalidArgument,"saved user coordinates cannot combine with explicit frame parameters and require AUBO"));
|
||||
stage="coordinate_lookup";
|
||||
const auto profile=device::UserCoordinateStore::forArm(device_id).get(request->user_coordinate_name(),request->user_coordinate_revision());
|
||||
stage="coordinate_application_check";
|
||||
if(!aubo->currentUserCoordinateMatches(profile.name,profile.revision)) {
|
||||
std::string applied_name;std::uint64_t applied_revision{};
|
||||
const bool known=aubo->lastAppliedUserCoordinate(applied_name,applied_revision);
|
||||
const auto failure=device::Result::failure(device::ArmErrorCode::CommandRejected,
|
||||
"requested coordinate is not currently applied; call ApplyUserCoordinateSystem first");
|
||||
log_failure(stage,failure.message+"; applied_name="+applied_name+
|
||||
", applied_revision="+std::to_string(applied_revision)+", application_known="+(known?"true":"false"));
|
||||
return setResponseResult(response,failure);
|
||||
}
|
||||
stage="execute";
|
||||
result=arm->moveL(toCartesianPose(request->target()),options,device::FrameType::Base);
|
||||
} else if (explicit_user_frame) {
|
||||
stage="execute_inline_frame";
|
||||
auto aubo = std::dynamic_pointer_cast<device::AuboArm>(arm);
|
||||
if (!aubo || has_named_frame) {
|
||||
result = device::Result::failure(device::ArmErrorCode::InvalidArgument,
|
||||
"explicit user frames require AUBO and cannot combine with named frames");
|
||||
} else {
|
||||
result = aubo->moveLInUserFrame(toCartesianPose(request->target()), options,
|
||||
std::vector<double>(request->user_frame_pose().begin(),request->user_frame_pose().end()),
|
||||
std::vector<double>(request->tcp_offset().begin(),request->tcp_offset().end()));
|
||||
}
|
||||
} else {
|
||||
stage="execute";
|
||||
result = has_named_frame
|
||||
? arm->moveL(toCartesianPose(request->target()),
|
||||
options,
|
||||
request->has_base_frame()
|
||||
@ -350,6 +419,7 @@ grpc::Status gRPCArmServiceImpl::moveL(grpc::ServerContext* context,
|
||||
: arm->moveL(toCartesianPose(request->target()),
|
||||
options,
|
||||
toFrameType(request->frame()));
|
||||
}
|
||||
if (result.ok()) {
|
||||
CMVR_LOG(DEBUG) << "[gRPCArmServiceImpl] (moveL): success, id=" << device_id
|
||||
<< ", frame=" << request->frame()
|
||||
@ -361,12 +431,15 @@ grpc::Status gRPCArmServiceImpl::moveL(grpc::ServerContext* context,
|
||||
<< (request->has_tcp_frame()
|
||||
? request->tcp_frame()
|
||||
: "<default>");
|
||||
} else {
|
||||
CMVR_LOG(DEBUG) << "[gRPCArmServiceImpl] (moveL): finished, id="
|
||||
<< device_id << ", error=" << result.message;
|
||||
}
|
||||
return setResponseResult(response, result);
|
||||
return finish_result(result);
|
||||
} catch (const device::CoordinateStoreError& e) {
|
||||
log_failure(stage,e.what());
|
||||
fillFeedback(response->mutable_header(),false,e.what());
|
||||
return grpc::Status(e.kind==device::CoordinateStoreError::Missing?grpc::StatusCode::NOT_FOUND:
|
||||
e.kind==device::CoordinateStoreError::Conflict?grpc::StatusCode::ABORTED:grpc::StatusCode::INVALID_ARGUMENT,e.what());
|
||||
} catch (const std::exception& e) {
|
||||
log_failure(stage,e.what());
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
}
|
||||
@ -550,17 +623,25 @@ grpc::Status gRPCArmServiceImpl::GetArmInfo(grpc::ServerContext*,
|
||||
if (!arm) {
|
||||
return setDeviceNotFound(response, device_id);
|
||||
}
|
||||
const auto model = arm->getRobotModel();
|
||||
const auto model = arm->queryRobotModel();
|
||||
response->set_device_id(device_id);
|
||||
response->set_manufacturer(model.manufacturer);
|
||||
response->set_model(model.name);
|
||||
response->set_dof(static_cast<std::uint32_t>(model.dof));
|
||||
for (const auto& name : model.joint_names) response->add_joint_names(name);
|
||||
response->set_driver_type(arm->typeName());
|
||||
for(std::size_t i=0;i<model.joint_names.size();++i){
|
||||
auto* limit=response->add_joint_limits();limit->set_joint_name(model.joint_names[i]);
|
||||
limit->set_source(model.joint_limits_source.empty()?"driver_model":model.joint_limits_source);
|
||||
if(model.joint_limits.size()!=model.joint_names.size())continue;
|
||||
const auto& value=model.joint_limits[i];
|
||||
if(!std::isfinite(value.lower)||!std::isfinite(value.upper)||value.lower>=value.upper)continue;
|
||||
limit->set_position_limits_available(true);limit->set_lower(value.lower);limit->set_upper(value.upper);
|
||||
}
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCArmServiceImpl] (GetArmInfo): success, id=" << device_id
|
||||
<< ", manufacturer=" << model.manufacturer
|
||||
<< ", model=" << model.name << ", dof=" << model.dof;
|
||||
// CMVR_LOG(DEBUG) << "[gRPCArmServiceImpl] (GetArmInfo): success, id=" << device_id
|
||||
// << ", manufacturer=" << model.manufacturer
|
||||
// << ", model=" << model.name << ", dof=" << model.dof;
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
@ -587,6 +668,10 @@ grpc::Status gRPCArmServiceImpl::getJointState(grpc::ServerContext*,
|
||||
for (double v : state.position) msg->add_position(v);
|
||||
for (double v : state.velocity) msg->add_velocity(v);
|
||||
for (double v : state.effort) msg->add_effort(v);
|
||||
for (double v : state.current) msg->add_current(v);
|
||||
// JointGroupState has no controller sample timestamp; report host read time.
|
||||
const auto received_at = TimeUtil::GetCurrentTime();
|
||||
msg->set_timestamp(static_cast<double>(received_at.seconds()) + received_at.nanos() * 1e-9);
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
// CMVR_LOG(DEBUG) << "[gRPCArmServiceImpl] (getJointState): success, id=" << device_id
|
||||
// << ", joints=" << msg->name_size()
|
||||
@ -629,15 +714,36 @@ grpc::Status gRPCArmServiceImpl::getPose(grpc::ServerContext*,
|
||||
if (!arm) {
|
||||
return setDeviceNotFound(response, device_id);
|
||||
}
|
||||
const auto pose = request->base_link().empty() || request->ee_link().empty()
|
||||
? arm->fk(true)
|
||||
: arm->fk(request->base_link(), request->ee_link());
|
||||
const auto aubo=std::dynamic_pointer_cast<device::AuboArm>(arm);
|
||||
device::CartesianPose pose;
|
||||
std::string reference="base";
|
||||
if(aubo && !aubo->isBaseReference(request->base_link())){
|
||||
const auto profile=device::UserCoordinateStore::forArm(device_id).get(request->base_link(),0);
|
||||
const auto result=aubo->getPoseInCoordinate(profile.name,profile.user_pose,request->ee_link(),pose);
|
||||
if(!result.ok())return setResponseResult(response,result);
|
||||
reference=profile.name;
|
||||
}else{
|
||||
pose=aubo ? aubo->fk(request->base_link(),request->ee_link())
|
||||
: request->base_link().empty() || request->ee_link().empty()
|
||||
? arm->fk(true) : arm->fk(request->base_link(),request->ee_link());
|
||||
}
|
||||
*response->mutable_pose() = toApiCartesianPose(pose);
|
||||
if(aubo){
|
||||
response->set_reference_frame(reference);
|
||||
response->set_end_frame(request->ee_link()=="flange"||request->ee_link()=="tool0"?"flange":"tcp");
|
||||
}
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCArmServiceImpl] (getPose): success, id=" << device_id
|
||||
<< ", pose=(" << pose.x << ", " << pose.y << ", " << pose.z
|
||||
<< ", " << pose.rx << ", " << pose.ry << ", " << pose.rz << ")";
|
||||
return grpc::Status::OK;
|
||||
} catch(const device::CoordinateStoreError& e){
|
||||
fillFeedback(response->mutable_header(),false,e.what());
|
||||
return grpc::Status(e.kind==device::CoordinateStoreError::Missing?grpc::StatusCode::NOT_FOUND:
|
||||
e.kind==device::CoordinateStoreError::Invalid?grpc::StatusCode::INVALID_ARGUMENT:grpc::StatusCode::INTERNAL,e.what());
|
||||
} catch (const std::invalid_argument& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what());
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
@ -722,4 +828,251 @@ grpc::Status gRPCArmServiceImpl::ExecuteJsonCommand(
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::EnterTeachingMode(
|
||||
grpc::ServerContext*,
|
||||
const api::CommandHeader_Request* request,
|
||||
api::CommandHeader_Feedback* response)
|
||||
{
|
||||
auto control_lease = ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if (!control_lease) return setControlBusy(response);
|
||||
try {
|
||||
const std::string device_id = request->device_id();
|
||||
auto arm = dmgr_.getDevice<device::RobotArm>(device_id);
|
||||
if (!arm) return setDeviceNotFound(response, device_id);
|
||||
const auto result = arm->enterTeachingMode();
|
||||
fillFeedback(response, result.ok(), result.ok() ? "" : result.message);
|
||||
if (result.ok()) logRpcSuccess("EnterTeachingMode", device_id);
|
||||
return resultToStatus(result);
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response, false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::StartTrajectoryRecording(
|
||||
grpc::ServerContext*,
|
||||
const api::StartTrajectoryRecording_Request* request,
|
||||
api::StartTrajectoryRecording_Response* response)
|
||||
{
|
||||
auto control_lease = ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if (!control_lease) return setControlBusy(response);
|
||||
try {
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto arm = dmgr_.getDevice<device::RobotArm>(device_id);
|
||||
if (!arm) return setDeviceNotFound(response, device_id);
|
||||
const auto result = arm->startTrajectoryRecording(request->file_name(), request->sampling_frequency_hz());
|
||||
if (result.ok()) logRpcSuccess("StartTrajectoryRecording", device_id);
|
||||
return setResponseResult(response, result);
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::CompleteTeaching(
|
||||
grpc::ServerContext*,
|
||||
const api::CommandHeader_Request* request,
|
||||
api::CommandHeader_Feedback* response)
|
||||
{
|
||||
auto control_lease = ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if (!control_lease) return setControlBusy(response);
|
||||
try {
|
||||
const std::string device_id = request->device_id();
|
||||
auto arm = dmgr_.getDevice<device::RobotArm>(device_id);
|
||||
if (!arm) return setDeviceNotFound(response, device_id);
|
||||
const auto result = arm->completeTeaching();
|
||||
fillFeedback(response, result.ok(), result.ok() ? "" : result.message);
|
||||
if (result.ok()) logRpcSuccess("CompleteTeaching", device_id);
|
||||
return resultToStatus(result);
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response, false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::StopTrajectoryRecording(
|
||||
grpc::ServerContext*,
|
||||
const api::CommandHeader_Request* request,
|
||||
api::CommandHeader_Feedback* response)
|
||||
{
|
||||
auto control_lease = ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if (!control_lease) return setControlBusy(response);
|
||||
try {
|
||||
const std::string device_id = request->device_id();
|
||||
auto arm = dmgr_.getDevice<device::RobotArm>(device_id);
|
||||
if (!arm) return setDeviceNotFound(response, device_id);
|
||||
const auto result = arm->stopTrajectoryRecording();
|
||||
fillFeedback(response, result.ok(), result.ok() ? "" : result.message);
|
||||
if (result.ok()) logRpcSuccess("StopTrajectoryRecording", device_id);
|
||||
return resultToStatus(result);
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response, false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::ExitTeachingMode(
|
||||
grpc::ServerContext*,
|
||||
const api::CommandHeader_Request* request,
|
||||
api::CommandHeader_Feedback* response)
|
||||
{
|
||||
auto control_lease = ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if (!control_lease) return setControlBusy(response);
|
||||
try {
|
||||
const std::string device_id = request->device_id();
|
||||
auto arm = dmgr_.getDevice<device::RobotArm>(device_id);
|
||||
if (!arm) return setDeviceNotFound(response, device_id);
|
||||
const auto result = arm->exitTeachingMode();
|
||||
fillFeedback(response, result.ok(), result.ok() ? "" : result.message);
|
||||
if (result.ok()) logRpcSuccess("ExitTeachingMode", device_id);
|
||||
return resultToStatus(result);
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response, false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::ListRecordedTrajectories(grpc::ServerContext*,
|
||||
const api::ListRecordedTrajectories_Request* request, api::ListRecordedTrajectories_Response* response)
|
||||
{
|
||||
try {
|
||||
const auto& id = request->header().device_id();
|
||||
auto arm = dmgr_.getDevice<device::RobotArm>(id);
|
||||
if (!arm) return setDeviceNotFound(response, id);
|
||||
std::vector<device::RecordedTrajectoryInfo> files;
|
||||
device::TrajectoryRecordingStatus state;
|
||||
const auto result = arm->listRecordedTrajectories(files, state);
|
||||
for (const auto& file : files) {
|
||||
auto* item = response->add_trajectories();
|
||||
item->set_file_name(file.file_name);
|
||||
item->set_samples(file.samples);
|
||||
item->set_duration_s(file.duration_s);
|
||||
item->set_sampling_frequency_hz(file.sampling_frequency_hz);
|
||||
}
|
||||
response->set_directory(state.directory);
|
||||
response->set_recording(state.recording);
|
||||
response->set_recording_file(state.file_name);
|
||||
response->set_recorded_samples(state.samples);
|
||||
response->set_recording_error(state.error);
|
||||
return setResponseResult(response, result);
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::MoveToTrajectoryStart(grpc::ServerContext* context,
|
||||
const api::ReplayRecordedTrajectory_Request* request, api::ReplayRecordedTrajectory_Response* response)
|
||||
{
|
||||
return replayTrajectory(context, request, response, true);
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::ReplayRecordedTrajectory(grpc::ServerContext* context,
|
||||
const api::ReplayRecordedTrajectory_Request* request, api::ReplayRecordedTrajectory_Response* response)
|
||||
{
|
||||
return replayTrajectory(context, request, response, false);
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::replayTrajectory(grpc::ServerContext* context,
|
||||
const api::ReplayRecordedTrajectory_Request* request, api::ReplayRecordedTrajectory_Response* response, bool to_start)
|
||||
{
|
||||
auto control_lease = ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if (!control_lease) return setControlBusy(response);
|
||||
try {
|
||||
const auto& id = request->header().device_id();
|
||||
auto arm = dmgr_.getDevice<device::RobotArm>(id);
|
||||
if (!arm) return setDeviceNotFound(response, id);
|
||||
device::MotionOptions limits;
|
||||
limits.velocity = request->max_velocity() == 0 ? 0.3 : request->max_velocity();
|
||||
limits.acceleration = request->max_acceleration() == 0 ? 0.5 : request->max_acceleration();
|
||||
limits.jerk = request->max_jerk() == 0 ? 2.0 : request->max_jerk();
|
||||
limits.cancellation_requested = [context] { return context->IsCancelled(); };
|
||||
const auto result = arm->replayRecordedTrajectory(request->file_name(), request->speed_ratio(), to_start, limits);
|
||||
if (result.ok()) logRpcSuccess(to_start ? "MoveToTrajectoryStart" : "ReplayRecordedTrajectory", id);
|
||||
return setResponseResult(response, result);
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::coordinateCommand(grpc::ServerContext* context,
|
||||
const api::UserCoordinateSystemCommand_Request* request,
|
||||
api::UserCoordinateSystemCommand_Response* response,const std::string& operation)
|
||||
{
|
||||
try {
|
||||
if(context && context->IsCancelled())return grpc::Status(grpc::StatusCode::CANCELLED,"request cancelled");
|
||||
const auto id=request->header().device_id();
|
||||
auto arm=dmgr_.getDevice<device::RobotArm>(id);
|
||||
if(!arm)return setDeviceNotFound(response,id);
|
||||
auto aubo=std::dynamic_pointer_cast<device::AuboArm>(arm);
|
||||
if(!aubo)return setResponseResult(response,device::Result::failure(device::ArmErrorCode::UnsupportedCommand,"user coordinate management requires AUBO"));
|
||||
auto store=device::UserCoordinateStore::forArm(id);
|
||||
const auto output=[](const device::UserCoordinateProfile& p,api::UserCoordinateSystem* value) {
|
||||
value->set_name(p.name);value->set_revision(p.revision);
|
||||
for(double x:p.user_pose)value->add_user_pose(x);
|
||||
for(double x:p.tcp_offset)value->add_tcp_offset(x);
|
||||
value->set_calibration_version(2);
|
||||
for(const auto& point:p.calibration_points){auto* v=value->add_calibration_points()->mutable_base_tcp_pose();v->set_x(point[0]);v->set_y(point[1]);v->set_z(point[2]);v->set_rx(point[3]);v->set_ry(point[4]);v->set_rz(point[5]);}
|
||||
};
|
||||
if(operation=="list") {
|
||||
output(device::UserCoordinateStore::builtin("__builtin_base__"),response->add_coordinates());
|
||||
output(device::UserCoordinateStore::builtin("__builtin_tool__"),response->add_coordinates());
|
||||
for(const auto& p:store.list())output(p,response->add_coordinates());
|
||||
}
|
||||
else {
|
||||
device::UserCoordinateProfile p;
|
||||
if(operation=="create"||operation=="update"||operation=="calibrate") {
|
||||
p.name=request->coordinate().name();
|
||||
p.user_pose.assign(request->coordinate().user_pose().begin(),request->coordinate().user_pose().end());
|
||||
p.tcp_offset.assign(request->coordinate().tcp_offset().begin(),request->coordinate().tcp_offset().end());
|
||||
for(const auto& v:request->coordinate().calibration_points()){
|
||||
if(!v.has_base_tcp_pose())return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,"calibration point is missing base_tcp_pose");
|
||||
const auto& x=v.base_tcp_pose();p.calibration_points.push_back({x.x(),x.y(),x.z(),x.rx(),x.ry(),x.rz()});
|
||||
}
|
||||
if(request->coordinate().calibration_version()!=2)return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,"three-point coordinate API version 2 required; retired manual records are not accepted");
|
||||
const auto calibrated=aubo->calibrateUserCoordinate(p.calibration_points,p.user_pose);
|
||||
if(!calibrated.ok())return setResponseResult(response,calibrated);
|
||||
if(operation!="calibrate")p=store.mutate(operation,p,request->expected_revision());
|
||||
} else if(operation=="delete") {
|
||||
p.name=request->name();p=store.mutate(operation,p,request->expected_revision());
|
||||
} else {
|
||||
p=store.get(request->name(),request->expected_revision());
|
||||
if(operation=="apply") {
|
||||
auto lease=ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if(!lease)return setControlBusy(response);
|
||||
std::vector<double> actual;
|
||||
const auto result=device::UserCoordinateStore::isBuiltin(p.name)
|
||||
? aubo->applyBuiltinCoordinate(p.name,actual)
|
||||
: aubo->applyUserCoordinates(p.user_pose,p.tcp_offset,actual,p.name,p.revision);
|
||||
if(!result.ok())return setResponseResult(response,result);
|
||||
for(double x:actual)response->add_actual_tcp_offset(x);
|
||||
response->set_work_object_acknowledged(true);
|
||||
}
|
||||
}
|
||||
output(p,response->mutable_coordinate());
|
||||
}
|
||||
std::string applied;std::uint64_t revision{};
|
||||
response->set_application_known(aubo->lastAppliedUserCoordinate(applied,revision));
|
||||
response->set_last_applied_name(applied);response->set_last_applied_revision(revision);
|
||||
CMVR_LOG(DEBUG)<<"[gRPCArmServiceImpl] ("<<operation<<"UserCoordinateSystem): success, id="<<id;
|
||||
fillFeedback(response->mutable_header(),true);return grpc::Status::OK;
|
||||
}catch(const device::CoordinateStoreError& e){
|
||||
fillFeedback(response->mutable_header(),false,e.what());
|
||||
const auto code=e.kind==device::CoordinateStoreError::Missing?grpc::StatusCode::NOT_FOUND:
|
||||
e.kind==device::CoordinateStoreError::Exists?grpc::StatusCode::ALREADY_EXISTS:
|
||||
e.kind==device::CoordinateStoreError::Conflict?grpc::StatusCode::ABORTED:
|
||||
e.kind==device::CoordinateStoreError::Invalid?grpc::StatusCode::INVALID_ARGUMENT:grpc::StatusCode::INTERNAL;
|
||||
return grpc::Status(code,e.what());
|
||||
}catch(const std::exception& e){fillFeedback(response->mutable_header(),false,e.what());return grpc::Status(grpc::StatusCode::INTERNAL,e.what());}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::CalibrateUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"calibrate");}
|
||||
grpc::Status gRPCArmServiceImpl::CreateUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"create");}
|
||||
grpc::Status gRPCArmServiceImpl::GetUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"get");}
|
||||
grpc::Status gRPCArmServiceImpl::ListUserCoordinateSystems(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"list");}
|
||||
grpc::Status gRPCArmServiceImpl::UpdateUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"update");}
|
||||
grpc::Status gRPCArmServiceImpl::DeleteUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"delete");}
|
||||
grpc::Status gRPCArmServiceImpl::ApplyUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"apply");}
|
||||
|
||||
} // namespace cmvr::service
|
||||
|
||||
@ -132,6 +132,14 @@ grpc::Status gRPCCameraServiceImpl::GetStatus(grpc::ServerContext* context,
|
||||
response->mutable_state()->set_fps(state.fps);
|
||||
response->mutable_state()->set_width(state.width);
|
||||
response->mutable_state()->set_height(state.height);
|
||||
response->mutable_state()->set_codec(state.codec);
|
||||
// Report driver capabilities without starting or capturing the camera.
|
||||
auto* capabilities = response->mutable_state()->mutable_capabilities();
|
||||
capabilities->set_version(1);
|
||||
capabilities->set_driver(dev->typeName());
|
||||
capabilities->set_depth_image(dev->supportsDepthImage());
|
||||
capabilities->set_depth_stream(dev->supportsDepthStream());
|
||||
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
catch(const exception &e) {
|
||||
@ -260,6 +268,9 @@ grpc::Status gRPCCameraServiceImpl::GetDepthImage(grpc::ServerContext* context,
|
||||
if (!dev) {
|
||||
return failResponse(response, "Camera device not found: " + dev_id);
|
||||
}
|
||||
if (!dev->supportsDepthImage()) {
|
||||
return failResponse(response, "Depth capture is not supported by camera: " + dev_id);
|
||||
}
|
||||
Rs2Intrinsics intrinsics = {0};
|
||||
dev->getDepthImage(image,intrinsics);
|
||||
if (image.empty()) {
|
||||
@ -319,6 +330,9 @@ grpc::Status gRPCCameraServiceImpl::GetRGBDImages(grpc::ServerContext* context,
|
||||
if (!dev) {
|
||||
return failResponse(response, "Camera device not found: " + dev_id);
|
||||
}
|
||||
if (!dev->supportsDepthImage()) {
|
||||
return failResponse(response, "Depth capture is not supported by camera: " + dev_id);
|
||||
}
|
||||
Rs2Intrinsics intrinsics = {0};
|
||||
dev->getRGBDImages(color_image,depth_image, intrinsics);
|
||||
if (color_image.empty()) {
|
||||
@ -497,6 +511,12 @@ grpc::Status gRPCCameraServiceImpl::GetDepthImageStream(grpc::ServerContext* con
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
if (!dev->supportsDepthStream()) {
|
||||
api::GetDepthImageStreamCommand_Feedback response;
|
||||
failResponse(&response, "Depth streaming is not supported by camera: " + dev_id);
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
CameraStreamingLease stream_lease(dev);
|
||||
if (!stream_lease) {
|
||||
api::GetDepthImageStreamCommand_Feedback response;
|
||||
@ -577,6 +597,12 @@ grpc::Status gRPCCameraServiceImpl::GetRGBDImagesStream(grpc::ServerContext* con
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
if (!dev->supportsDepthStream()) {
|
||||
api::GetRGBDImagesStreamCommand_Feedback response;
|
||||
failResponse(&response, "Depth streaming is not supported by camera: " + dev_id);
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
CameraStreamingLease stream_lease(dev);
|
||||
if (!stream_lease) {
|
||||
api::GetRGBDImagesStreamCommand_Feedback response;
|
||||
|
||||
@ -12,6 +12,7 @@
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "devices/dexhand/oymotion_ap001/include/oymotion_ap001.h"
|
||||
#include "devices/dexhand/rh56dftp_dexhand/include/rh56dftp_dexhand.h"
|
||||
#include "devices/touch/abstract_touch.h"
|
||||
#include "service/grpc/action/include/control_command_arbiter.h"
|
||||
@ -27,6 +28,25 @@ using namespace cmvr::device;
|
||||
#define DEXHAND_MAX_SPEED 1000
|
||||
|
||||
namespace {
|
||||
class SensorDataStreamLease {
|
||||
public:
|
||||
explicit SensorDataStreamLease(
|
||||
const std::shared_ptr<AbstractDevice>& device)
|
||||
: device_(std::dynamic_pointer_cast<AbstractDexHand>(device)),
|
||||
acquired_(device_ ? device_->acquireSensorDataStream()
|
||||
: bool(std::dynamic_pointer_cast<AbstractTouch>(device))) {}
|
||||
|
||||
~SensorDataStreamLease() {
|
||||
if (acquired_ && device_) device_->releaseSensorDataStream();
|
||||
}
|
||||
|
||||
bool acquired() const noexcept { return acquired_; }
|
||||
|
||||
private:
|
||||
std::shared_ptr<AbstractDexHand> device_;
|
||||
bool acquired_{false};
|
||||
};
|
||||
|
||||
|
||||
constexpr int kDexHandDofCount = 6;
|
||||
|
||||
@ -234,6 +254,9 @@ grpc::Status gRPCDexHandServiceImpl::GetStatus(grpc::ServerContext* context,
|
||||
DexHandState state{};
|
||||
dev->getState(state);
|
||||
response->mutable_state()->set_is_initialized(state.is_initialized);
|
||||
response->mutable_state()->set_has_tactile_feedback(
|
||||
dev->hasTactileFeedback());
|
||||
response->mutable_state()->set_model(dev->model());
|
||||
for (int i = 0; i < kDexHandDofCount; i++) {
|
||||
auto hand = response->mutable_state()->add_hands();
|
||||
hand->set_dof_id(i);
|
||||
@ -469,6 +492,18 @@ grpc::Status gRPCDexHandServiceImpl::GetSensorData(grpc::ServerContext* context
|
||||
if (!dev) {
|
||||
return failResponse(response, "Tactile device not found: " + dev_id);
|
||||
}
|
||||
if (const auto hand = std::dynamic_pointer_cast<AbstractDexHand>(dev);
|
||||
hand && !hand->hasTactileFeedback()) {
|
||||
return failResponse(response,
|
||||
"DexHand device does not support tactile feedback: " + dev_id);
|
||||
}
|
||||
SensorDataStreamLease sensor_lease(dev);
|
||||
if (!sensor_lease.acquired()) {
|
||||
return failResponse(response,
|
||||
"Failed to start tactile acquisition: " + dev_id);
|
||||
}
|
||||
if (std::dynamic_pointer_cast<OYMotionAP001>(dev))
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
maybeConfigureRh56FullTactilePolling(dev);
|
||||
appendSensorData(dev, response);
|
||||
response->mutable_header()->set_success(true);
|
||||
@ -505,8 +540,34 @@ grpc::Status gRPCDexHandServiceImpl::GetSensorDataStream(grpc::ServerContext* co
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
if (const auto hand = std::dynamic_pointer_cast<AbstractDexHand>(dev);
|
||||
hand && !hand->hasTactileFeedback()) {
|
||||
api::GetSensorDataStreamCommand_Feedback response;
|
||||
response.mutable_header()->set_success(false);
|
||||
response.mutable_header()->set_error_message(
|
||||
"DexHand device does not support tactile feedback: " + dev_id);
|
||||
setCurrentTimestamp(response.mutable_header()->mutable_timestamp());
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
SensorDataStreamLease sensor_lease(dev);
|
||||
if (!sensor_lease.acquired()) {
|
||||
api::GetSensorDataStreamCommand_Feedback response;
|
||||
response.mutable_header()->set_success(false);
|
||||
response.mutable_header()->set_error_message(
|
||||
"Failed to start tactile acquisition: " + dev_id);
|
||||
setCurrentTimestamp(response.mutable_header()->mutable_timestamp());
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
if (std::dynamic_pointer_cast<OYMotionAP001>(dev))
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
maybeConfigureRh56FullTactilePolling(dev);
|
||||
CMVR_LOG(DEBUG) << "[gRPCDexHandServiceImpl] (GetSensorDataStream): streaming success, id=" << dev_id;
|
||||
const auto stream_interval =
|
||||
std::dynamic_pointer_cast<OYMotionAP001>(dev)
|
||||
? std::chrono::microseconds(6667)
|
||||
: std::chrono::microseconds(33000);
|
||||
|
||||
while (!context->IsCancelled())
|
||||
{
|
||||
@ -520,7 +581,7 @@ grpc::Status gRPCDexHandServiceImpl::GetSensorDataStream(grpc::ServerContext* co
|
||||
break;
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(33));
|
||||
std::this_thread::sleep_for(stream_interval);
|
||||
}
|
||||
CMVR_LOG(DEBUG) << "[gRPCDexHandServiceImpl] (GetSensorDataStream): finished, id=" << dev_id;
|
||||
return grpc::Status::OK;
|
||||
|
||||
879
cmvr-es/service/grpc/src/grpc_motor_service.cpp
Normal file
879
cmvr-es/service/grpc/src/grpc_motor_service.cpp
Normal file
@ -0,0 +1,879 @@
|
||||
#include "service/grpc/include/grpc_motor_service.h"
|
||||
|
||||
#include <google/protobuf/util/time_util.h>
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
#include "devices/motor/drivers/ethercat_motor/include/ethercat_motor.h"
|
||||
#include "devices/motor/manager/include/motor_manager.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
using google::protobuf::util::TimeUtil;
|
||||
|
||||
namespace cmvr::service {
|
||||
|
||||
namespace {
|
||||
|
||||
void fillFeedback(api::CommandHeader_Feedback* feedback,
|
||||
const bool success,
|
||||
const std::string& message = {})
|
||||
{
|
||||
feedback->set_success(success);
|
||||
feedback->set_error_message(message);
|
||||
*feedback->mutable_timestamp() = TimeUtil::GetCurrentTime();
|
||||
}
|
||||
|
||||
void fillMotorInfo(const std::string& device_id,
|
||||
const std::shared_ptr<device::AbstractMotor>& motor,
|
||||
api::MotorInfo* response)
|
||||
{
|
||||
const auto info = motor->motorInfo();
|
||||
response->set_manager_id(device_id);
|
||||
response->set_node_id(motor->id());
|
||||
response->set_joint_name(motor->jointName());
|
||||
response->set_driver(motor->typeName());
|
||||
response->set_limit_q_lb(info.limit_q_lb);
|
||||
response->set_limit_q_ub(info.limit_q_ub);
|
||||
response->set_limit_qd(info.limit_qd);
|
||||
response->set_limit_qdd(info.limit_qdd);
|
||||
}
|
||||
|
||||
void fillMotorState(const std::shared_ptr<device::MotorManager>& manager,
|
||||
const std::shared_ptr<device::AbstractMotor>& motor,
|
||||
api::MotorDebugState* response)
|
||||
{
|
||||
std::vector<double> positions, velocities, torques;
|
||||
bool valid = false;
|
||||
if (std::dynamic_pointer_cast<device::EthercatMotor>(motor)) {
|
||||
valid = manager->readFeedbacksAtomic({motor}, positions, velocities, torques);
|
||||
} else {
|
||||
valid = manager->readFeedbacksAtomic({motor}, positions, velocities);
|
||||
torques.push_back(motor->getTau());
|
||||
}
|
||||
valid = valid && positions.size() == 1 && velocities.size() == 1
|
||||
&& std::isfinite(positions[0]) && std::isfinite(velocities[0]);
|
||||
response->set_feedback_valid(valid);
|
||||
if (valid) {
|
||||
response->set_position(positions[0]);
|
||||
response->set_velocity(velocities[0]);
|
||||
}
|
||||
response->set_torque_valid(valid && torques.size() == 1 && std::isfinite(torques[0]));
|
||||
if (response->torque_valid()) {
|
||||
response->set_torque(torques[0]);
|
||||
}
|
||||
response->set_torque_unit("per_mille_rated");
|
||||
response->set_mode(motor->getMode());
|
||||
|
||||
std::uint16_t status_word = 0, error_code = 0;
|
||||
bool enabled = false, fault = false;
|
||||
response->set_status_valid(motor->readDiagnosticState(status_word, error_code, enabled, fault));
|
||||
if (response->status_valid()) {
|
||||
response->set_status_word(status_word);
|
||||
response->set_error_code(error_code);
|
||||
response->set_enabled(enabled);
|
||||
response->set_fault(fault);
|
||||
}
|
||||
response->set_sampled_at_s(std::chrono::duration<double>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count());
|
||||
}
|
||||
|
||||
void validateParameters(const api::MotorRequest* request)
|
||||
{
|
||||
for (double value : {request->q(), request->qd(), request->qdd(),
|
||||
request->tau(), request->upper(), request->lower()}) {
|
||||
if (!std::isfinite(value)) {
|
||||
throw std::runtime_error("Motor parameters must be finite");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
gRPCMotorServiceImpl::gRPCMotorServiceImpl()
|
||||
: dmgr_(device::DeviceManager::getInstance())
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<device::AbstractMotor> gRPCMotorServiceImpl::getMotor(
|
||||
const api::MotorRequest* request)
|
||||
{
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto manager = dmgr_.getDevice<device::MotorManager>(device_id);
|
||||
if (!manager) {
|
||||
throw std::runtime_error("MotorManager not found: " + device_id);
|
||||
}
|
||||
if (request->node_id() > 255) {
|
||||
throw std::runtime_error("motor node_id exceeds uint8 range");
|
||||
}
|
||||
auto motor = request->joint_name().empty()
|
||||
? manager->getMotor(static_cast<std::uint8_t>(request->node_id()))
|
||||
: manager->getMotor(request->joint_name());
|
||||
if (!motor) {
|
||||
throw std::runtime_error("Motor not found in selected MotorManager");
|
||||
}
|
||||
return motor;
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::ListMotors(
|
||||
grpc::ServerContext*,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorListResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (ListMotors): request, id="
|
||||
<< request->header().device_id();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto manager = dmgr_.getDevice<device::MotorManager>(device_id);
|
||||
if (!manager) {
|
||||
throw std::runtime_error("MotorManager not found: " + device_id);
|
||||
}
|
||||
auto motors = manager->motorsSnapshot();
|
||||
std::sort(motors.begin(), motors.end(), [](const auto& lhs, const auto& rhs) {
|
||||
return lhs->id() < rhs->id();
|
||||
});
|
||||
for (const auto& motor : motors) {
|
||||
fillMotorInfo(device_id, motor, response->add_motors());
|
||||
}
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (ListMotors): success, id="
|
||||
<< device_id << ", count=" << motors.size();
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (ListMotors): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::GetInfo(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (GetInfo): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (GetInfo): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (GetInfo): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::GetState(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
auto manager = dmgr_.getDevice<device::MotorManager>(device_id);
|
||||
fillMotorState(manager, motor, response->mutable_state());
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (GetState): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::getMode(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (getMode): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
response->mutable_state()->set_mode(motor->getMode());
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (getMode): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (getMode): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::getQ(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (getQ): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
response->mutable_state()->set_position(motor->getQ());
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (getQ): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (getQ): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::getQd(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (getQd): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
response->mutable_state()->set_velocity(motor->getQd());
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (getQd): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (getQd): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::getTau(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (getTau): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
const double torque = motor->getTau();
|
||||
response->mutable_state()->set_torque_valid(std::isfinite(torque));
|
||||
if (std::isfinite(torque)) {
|
||||
response->mutable_state()->set_torque(torque);
|
||||
}
|
||||
response->mutable_state()->set_torque_unit("per_mille_rated");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (getTau): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (getTau): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::reachedTargetQ(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (reachedTargetQ): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
response->set_reached_target(motor->reachedTargetQ());
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (reachedTargetQ): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (reachedTargetQ): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::setMode(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (setMode): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", mode=" << request->mode();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->setMode(static_cast<msgs::RunMode>(request->mode()))) {
|
||||
throw std::runtime_error("setMode returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (setMode): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (setMode): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::torqueOn(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (torqueOn): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->torqueOn()) {
|
||||
throw std::runtime_error("torqueOn returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (torqueOn): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (torqueOn): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::torqueOff(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (torqueOff): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->torqueOff()) {
|
||||
throw std::runtime_error("torqueOff returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (torqueOff): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (torqueOff): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::brakeRelease(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (brakeRelease): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->brakeRelease()) {
|
||||
throw std::runtime_error("brakeRelease returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (brakeRelease): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (brakeRelease): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::quickStop(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (quickStop): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->quickStop()) {
|
||||
throw std::runtime_error("quickStop returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (quickStop): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (quickStop): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::calibrateZeroQ(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (calibrateZeroQ): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->calibrateZeroQ()) {
|
||||
throw std::runtime_error("calibrateZeroQ returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (calibrateZeroQ): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (calibrateZeroQ): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::commandProfilePosition(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandProfilePosition): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", q=" << request->q()
|
||||
<< ", qd=" << request->qd()
|
||||
<< ", qdd=" << request->qdd();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->commandProfilePosition(request->q(), request->qd(), request->qdd())) {
|
||||
throw std::runtime_error("commandProfilePosition returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandProfilePosition): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandProfilePosition): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::commandProfileVelocity(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandProfileVelocity): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", qd=" << request->qd()
|
||||
<< ", qdd=" << request->qdd();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->commandProfileVelocity(request->qd(), request->qdd())) {
|
||||
throw std::runtime_error("commandProfileVelocity returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandProfileVelocity): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandProfileVelocity): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::commandProfileTorque(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandProfileTorque): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", tau=" << request->tau()
|
||||
<< ", torque_slope=" << request->torque_slope();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->commandProfileTorque(request->tau(), request->torque_slope())) {
|
||||
throw std::runtime_error("commandProfileTorque returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandProfileTorque): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandProfileTorque): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::commandCyclicPosition(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandCyclicPosition): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", q=" << request->q()
|
||||
<< ", qd=" << request->qd();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->commandCyclicPosition(request->q(), request->qd())) {
|
||||
throw std::runtime_error("commandCyclicPosition returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandCyclicPosition): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandCyclicPosition): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::commandCyclicVelocity(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandCyclicVelocity): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", qd=" << request->qd();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->commandCyclicVelocity(request->qd())) {
|
||||
throw std::runtime_error("commandCyclicVelocity returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandCyclicVelocity): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandCyclicVelocity): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::commandCyclicTorque(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandCyclicTorque): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", tau=" << request->tau();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->commandCyclicTorque(request->tau())) {
|
||||
throw std::runtime_error("commandCyclicTorque returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandCyclicTorque): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandCyclicTorque): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::setLimitQ(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (setLimitQ): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", upper=" << request->upper()
|
||||
<< ", lower=" << request->lower();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->setLimitQ(request->upper(), request->lower())) {
|
||||
throw std::runtime_error("setLimitQ returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (setLimitQ): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (setLimitQ): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::setLimitQd(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (setLimitQd): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", qd=" << request->qd();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
if (!motor->setLimitQd(request->qd())) {
|
||||
throw std::runtime_error("setLimitQd returned false");
|
||||
}
|
||||
response->set_driver_acknowledged(true);
|
||||
response->set_detail("Motor API returned true; completion is not implied");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (setLimitQd): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (setLimitQd): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCMotorServiceImpl::setLimitQdd(
|
||||
grpc::ServerContext* context,
|
||||
const api::MotorRequest* request,
|
||||
api::MotorResponse* response)
|
||||
{
|
||||
CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (setLimitQdd): request, id="
|
||||
<< request->header().device_id()
|
||||
<< ", node_id=" << request->node_id()
|
||||
<< ", joint_name=" << request->joint_name()
|
||||
<< ", upper=" << request->upper()
|
||||
<< ", lower=" << request->lower();
|
||||
try {
|
||||
std::lock_guard<std::mutex> lock(motor_mutex_);
|
||||
if (context->IsCancelled()) {
|
||||
return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled");
|
||||
}
|
||||
const std::string device_id = request->header().device_id();
|
||||
auto motor = getMotor(request);
|
||||
fillMotorInfo(device_id, motor, response->mutable_info());
|
||||
validateParameters(request);
|
||||
motor->setLimitQdd(request->upper(), request->lower());
|
||||
response->set_driver_acknowledged(false);
|
||||
response->set_detail("Void motor API returned; hardware acknowledgement is unavailable");
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (setLimitQdd): success, id="
|
||||
<< device_id << ", node=" << static_cast<unsigned>(motor->id());
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (setLimitQdd): " << e.what();
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace cmvr::service
|
||||
@ -7,6 +7,7 @@
|
||||
#include "common/base/logging/logger.h"
|
||||
#include "service/grpc/action/include/action_queue.h"
|
||||
#include "service/grpc/action/include/control_command_arbiter.h"
|
||||
#include "manager/task_manager/include/task_manager.h"
|
||||
|
||||
using namespace cmvr::device;
|
||||
using namespace cmvr::service;
|
||||
@ -140,8 +141,8 @@ grpc::Status gRPCSystemServiceImpl::GetSystemStatus(grpc::ServerContext* context
|
||||
}
|
||||
response->mutable_header()->set_success(true);
|
||||
setCurrentTimestamp(response->mutable_header()->mutable_timestamp());
|
||||
CMVR_LOG(DEBUG) << "[gRPCSystemServiceImpl] (GetSystemStatus): success, devices="
|
||||
<< response->device_list_size();
|
||||
// CMVR_LOG(DEBUG) << "[gRPCSystemServiceImpl] (GetSystemStatus): success, devices="
|
||||
// << response->device_list_size();
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
catch (const std::exception &e) {
|
||||
@ -175,6 +176,9 @@ grpc::Status gRPCSystemServiceImpl::StopAll(grpc::ServerContext* context,
|
||||
}
|
||||
auto stop_lease = ControlCommandArbiter::instance().beginStop();
|
||||
action_queue_->cancelAndClear();
|
||||
if (auto touch_screen_task = cmvr::task::TaskManager::getInstance().getTouchScreenTask()) {
|
||||
touch_screen_task->stop();
|
||||
}
|
||||
dmgr_.stop();
|
||||
response->mutable_header()->set_success(true);
|
||||
setCurrentTimestamp(response->mutable_header()->mutable_timestamp());
|
||||
|
||||
78
cmvr-es/service/grpc/tests/grpc_shutdown_test.cpp
Normal file
78
cmvr-es/service/grpc/tests/grpc_shutdown_test.cpp
Normal file
@ -0,0 +1,78 @@
|
||||
#include "task/grpc_server_task/include/grpc_server_task.h"
|
||||
#include "cmvr/api/biohead_service.grpc.pb.h"
|
||||
#include "manager/device_manager/include/device_manager.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
class GrpcShutdown : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
cmvr::config::DeviceManagerConfig cfg;
|
||||
cfg.set_name("shutdown_test_no_hardware");
|
||||
cmvr::device::DeviceManager::getInstance(cfg);
|
||||
}
|
||||
void TearDown() override {
|
||||
cmvr::device::DeviceManager::destroyInstance();
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(GrpcShutdown, CancelsIdleClientStreamBeforeClientDeadline)
|
||||
{
|
||||
// Reserve an ephemeral loopback port without touching a deployed server.
|
||||
const int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
ASSERT_GE(fd, 0);
|
||||
sockaddr_in address{};
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
const int bound = bind(fd, reinterpret_cast<sockaddr*>(&address), sizeof(address));
|
||||
socklen_t length = sizeof(address);
|
||||
const int named = getsockname(fd, reinterpret_cast<sockaddr*>(&address), &length);
|
||||
close(fd);
|
||||
ASSERT_EQ(bound, 0);
|
||||
ASSERT_EQ(named, 0);
|
||||
|
||||
cmvr::config::GRPCServerConfig cfg;
|
||||
cfg.set_id("shutdown_test");
|
||||
cfg.set_host("127.0.0.1");
|
||||
cfg.set_port(std::to_string(ntohs(address.sin_port)));
|
||||
cmvr::task::GrpcServerTask task(cfg);
|
||||
ASSERT_TRUE(task.init());
|
||||
ASSERT_TRUE(task.start());
|
||||
|
||||
auto channel = grpc::CreateChannel(task.address(), grpc::InsecureChannelCredentials());
|
||||
ASSERT_TRUE(channel->WaitForConnected(std::chrono::system_clock::now() + std::chrono::seconds(2)));
|
||||
auto stub = cmvr::api::BioHeadService::NewStub(channel);
|
||||
grpc::ClientContext context;
|
||||
context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(6));
|
||||
auto stream = stub->StreamExpression(&context);
|
||||
// Send no command: the server stays in Read(), with no hardware accessed.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
task.stop();
|
||||
EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
|
||||
EXPECT_TRUE(task.isFinished());
|
||||
const auto status = stream->Finish();
|
||||
EXPECT_FALSE(status.ok());
|
||||
task.stop(); // Repeated stop must remain safe.
|
||||
}
|
||||
|
||||
TEST_F(GrpcShutdown, ImmediateAndRepeatedStopJoinsWaitThread)
|
||||
{
|
||||
cmvr::config::GRPCServerConfig cfg;
|
||||
cfg.set_id("immediate_shutdown_test");
|
||||
cfg.set_host("127.0.0.1");
|
||||
cfg.set_port("0");
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
cmvr::task::GrpcServerTask task(cfg);
|
||||
ASSERT_TRUE(task.init());
|
||||
ASSERT_TRUE(task.start());
|
||||
task.stop();
|
||||
task.stop();
|
||||
EXPECT_TRUE(task.isFinished());
|
||||
}
|
||||
}
|
||||
104
cmvr-es/service/grpc/tests/motor_service_test.cpp
Normal file
104
cmvr-es/service/grpc/tests/motor_service_test.cpp
Normal file
@ -0,0 +1,104 @@
|
||||
#include "service/grpc/include/grpc_motor_service.h"
|
||||
#include "service/grpc/include/grpc_system_service.h"
|
||||
#include "manager/device_manager/include/device_manager.h"
|
||||
#include "devices/motor/manager/include/motor_manager.h"
|
||||
#include <gtest/gtest.h>
|
||||
#include <grpcpp/grpcpp.h>
|
||||
using namespace cmvr;
|
||||
|
||||
class FakeDirectMotor final : public device::AbstractMotor {
|
||||
public:
|
||||
int writes=0;std::string last;double a=0,b=0,c=0;bool reject=false;
|
||||
bool native_status=false;
|
||||
explicit FakeDirectMotor(int id){node_id_=id;info_.id=id;info_.joint_name="fake_J"+std::to_string(id);info_.limit_q_lb=-1;info_.limit_q_ub=1;info_.limit_qd=1;info_.limit_qdd=2;}
|
||||
std::string typeName()const override{return "FakeDirectMotor";}
|
||||
double getQ()override{return 1.25;}
|
||||
double getQd()override{return -0.2;}
|
||||
double getTau()override{return 35;}
|
||||
msgs::RunMode getMode()override{return msgs::RUN_MODE_PROFILE_POSITION;}
|
||||
bool readDriveStatus(std::uint16_t& sw,std::uint16_t& error)override{sw=0x27;error=0;return true;}
|
||||
bool readDiagnosticState(std::uint16_t& sw,std::uint16_t& error,bool& enabled,bool& fault)override{
|
||||
if(!native_status)return AbstractMotor::readDiagnosticState(sw,error,enabled,fault);
|
||||
sw=0;error=8;enabled=true;fault=true;return true;
|
||||
}
|
||||
bool reachedTargetQ()override{return true;}
|
||||
bool record(const char* method,double x=0,double y=0,double z=0){++writes;last=method;a=x;b=y;c=z;return !reject;}
|
||||
bool setMode(msgs::RunMode mode)override{return record("setMode",mode);}
|
||||
bool torqueOn()override{return record("torqueOn");}
|
||||
bool torqueOff()override{return record("torqueOff");}
|
||||
bool brakeRelease()override{return record("brakeRelease");}
|
||||
bool quickStop(double = 5.0)override{return record("quickStop");}
|
||||
bool calibrateZeroQ()override{return record("calibrateZeroQ");}
|
||||
bool commandProfilePosition(double q,double qd,double qdd)override{return record("commandProfilePosition",q,qd,qdd);}
|
||||
bool commandProfileVelocity(double qd,double qdd)override{return record("commandProfileVelocity",qd,qdd);}
|
||||
bool commandProfileTorque(double tau,std::uint32_t slope)override{return record("commandProfileTorque",tau,slope);}
|
||||
bool commandCyclicPosition(double q,double qd)override{return record("commandCyclicPosition",q,qd);}
|
||||
bool commandCyclicVelocity(double qd)override{return record("commandCyclicVelocity",qd);}
|
||||
bool commandCyclicTorque(double tau)override{return record("commandCyclicTorque",tau);}
|
||||
bool setLimitQ(double upper,double lower)override{return record("setLimitQ",upper,lower);}
|
||||
bool setLimitQd(double qd)override{return record("setLimitQd",qd);}
|
||||
void setLimitQdd(double upper,double lower)override{record("setLimitQdd",upper,lower);}
|
||||
};
|
||||
TEST(MotorService, DirectInterfaceDispatchWithoutPlanningOrStatePreflight){
|
||||
config::DeviceManagerConfig cfg;auto& dm=device::DeviceManager::getInstance(cfg);
|
||||
auto manager=std::make_shared<device::MotorManager>("fake_manager",config::MotorConfig{},"fake");
|
||||
auto motor=std::make_shared<FakeDirectMotor>(0);ASSERT_TRUE(manager->addMotor(motor));
|
||||
ASSERT_TRUE(manager->addMotor(std::make_shared<FakeDirectMotor>(2)));dm.registerDevice(manager);
|
||||
{
|
||||
service::gRPCSystemServiceImpl system;
|
||||
grpc::ServerContext context;
|
||||
api::GetSystemStatusCommand::Request request;
|
||||
api::GetSystemStatusCommand::Feedback response;
|
||||
ASSERT_TRUE(system.GetSystemStatus(&context, &request, &response).ok());
|
||||
ASSERT_TRUE(response.header().success());
|
||||
ASSERT_EQ(response.device_list_size(), 1);
|
||||
EXPECT_EQ(response.device_list(0).device_id(), "fake_manager");
|
||||
EXPECT_EQ(response.device_list(0).device_type(), api::MotorSystem);
|
||||
}
|
||||
service::gRPCMotorServiceImpl service;grpc::ServerBuilder builder;int port=0;
|
||||
builder.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);builder.RegisterService(&service);
|
||||
auto server=builder.BuildAndStart();ASSERT_TRUE(server);
|
||||
auto stub=api::MotorService::NewStub(grpc::CreateChannel("127.0.0.1:"+std::to_string(port),grpc::InsecureChannelCredentials()));
|
||||
api::MotorRequest r;r.mutable_header()->set_device_id("fake_manager");r.set_node_id(0);
|
||||
r.set_mode(8);r.set_q(2.5);r.set_qd(-0.2);r.set_qdd(0.4);r.set_tau(12.5);r.set_torque_slope(150);r.set_upper(3);r.set_lower(-3);
|
||||
{grpc::ClientContext c;api::MotorListResponse s;ASSERT_TRUE(stub->ListMotors(&c,r,&s).ok());ASSERT_TRUE(s.header().success());ASSERT_EQ(s.motors_size(),2);EXPECT_EQ(s.motors(0).node_id(),0);}
|
||||
#define READ(name,check) {grpc::ClientContext c;api::MotorResponse s;ASSERT_TRUE(stub->name(&c,r,&s).ok());ASSERT_TRUE(s.header().success())<<s.header().error_message();check;}
|
||||
READ(GetInfo,EXPECT_EQ(s.info().joint_name(),"fake_J0"));
|
||||
READ(GetState,EXPECT_TRUE(s.state().enabled());EXPECT_FALSE(s.state().feedback_valid()));
|
||||
READ(getMode,EXPECT_EQ(s.state().mode(),1));
|
||||
READ(getQ,EXPECT_DOUBLE_EQ(s.state().position(),1.25));
|
||||
READ(getQd,EXPECT_DOUBLE_EQ(s.state().velocity(),-0.2));
|
||||
READ(getTau,EXPECT_DOUBLE_EQ(s.state().torque(),35));
|
||||
READ(reachedTargetQ,EXPECT_TRUE(s.reached_target()));
|
||||
#undef READ
|
||||
#define DIRECT(name,check) {const int before=motor->writes;grpc::ClientContext c;api::MotorResponse s;ASSERT_TRUE(stub->name(&c,r,&s).ok());ASSERT_TRUE(s.header().success())<<s.header().error_message();EXPECT_EQ(motor->writes,before+1);EXPECT_EQ(motor->last,#name);check;}
|
||||
// The fake reports enabled and moving. Dispatch still reaches its exact API;
|
||||
// no mode-switch heuristic or enable/calibration preflight is injected.
|
||||
DIRECT(setMode,EXPECT_DOUBLE_EQ(motor->a,8));
|
||||
DIRECT(torqueOn,EXPECT_TRUE(s.driver_acknowledged()));
|
||||
DIRECT(torqueOff,EXPECT_TRUE(s.driver_acknowledged()));
|
||||
DIRECT(brakeRelease,EXPECT_TRUE(s.driver_acknowledged()));
|
||||
DIRECT(quickStop,EXPECT_TRUE(s.driver_acknowledged()));
|
||||
DIRECT(calibrateZeroQ,EXPECT_TRUE(s.driver_acknowledged()));
|
||||
DIRECT(commandProfilePosition,EXPECT_DOUBLE_EQ(motor->a,2.5);EXPECT_DOUBLE_EQ(motor->b,-0.2);EXPECT_DOUBLE_EQ(motor->c,0.4));
|
||||
DIRECT(commandProfileVelocity,EXPECT_DOUBLE_EQ(motor->a,-0.2);EXPECT_DOUBLE_EQ(motor->b,0.4));
|
||||
DIRECT(commandProfileTorque,EXPECT_DOUBLE_EQ(motor->a,12.5);EXPECT_DOUBLE_EQ(motor->b,150));
|
||||
DIRECT(commandCyclicPosition,EXPECT_DOUBLE_EQ(motor->a,2.5);EXPECT_DOUBLE_EQ(motor->b,-0.2));
|
||||
DIRECT(commandCyclicVelocity,EXPECT_DOUBLE_EQ(motor->a,-0.2));
|
||||
DIRECT(commandCyclicTorque,EXPECT_DOUBLE_EQ(motor->a,12.5));
|
||||
DIRECT(setLimitQ,EXPECT_DOUBLE_EQ(motor->a,3);EXPECT_DOUBLE_EQ(motor->b,-3));
|
||||
DIRECT(setLimitQd,EXPECT_DOUBLE_EQ(motor->a,-0.2));
|
||||
DIRECT(setLimitQdd,EXPECT_DOUBLE_EQ(motor->a,3);EXPECT_DOUBLE_EQ(motor->b,-3);EXPECT_FALSE(s.driver_acknowledged()));
|
||||
#undef DIRECT
|
||||
motor->reject=true;
|
||||
{grpc::ClientContext c;api::MotorResponse s;stub->torqueOn(&c,r,&s);EXPECT_FALSE(s.header().success());EXPECT_EQ(s.header().error_message(),"torqueOn returned false");}
|
||||
r.set_node_id(256);
|
||||
{grpc::ClientContext c;api::MotorResponse s;stub->getQ(&c,r,&s);EXPECT_FALSE(s.header().success());}
|
||||
// A native CAN state byte of zero means enabled here, NOT CiA402 disabled.
|
||||
motor->native_status=true;r.set_node_id(0);
|
||||
{grpc::ClientContext c;api::MotorResponse s;ASSERT_TRUE(stub->GetState(&c,r,&s).ok());
|
||||
ASSERT_TRUE(s.header().success());EXPECT_TRUE(s.state().status_valid());
|
||||
EXPECT_TRUE(s.state().enabled());EXPECT_TRUE(s.state().fault());
|
||||
EXPECT_EQ(s.state().status_word(),0);EXPECT_EQ(s.state().error_code(),8);}
|
||||
server->Shutdown();device::DeviceManager::destroyInstance();
|
||||
}
|
||||
@ -19,6 +19,7 @@
|
||||
#include <arpa/inet.h>
|
||||
#include <ifaddrs.h>
|
||||
#include <net/if.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@ -191,24 +192,43 @@ std::vector<v1::NetworkInterfaceAddress> collectInterfaceAddresses(
|
||||
return addresses;
|
||||
}
|
||||
|
||||
std::string advertisedGrpcHost(
|
||||
const config::QuicEdgeConfig& config,
|
||||
const std::vector<v1::NetworkInterfaceAddress>& interfaces)
|
||||
// Ask the kernel which local source address routes to this platform. UDP connect
|
||||
// selects a route only; it does not transmit a datagram or establish a session.
|
||||
std::string advertisedGrpcHost(const config::QuicEdgeConfig& config)
|
||||
{
|
||||
if (!config.grpc_endpoint_host().empty() &&
|
||||
config.grpc_endpoint_host() != "auto") {
|
||||
if (!config.grpc_endpoint_host().empty() && config.grpc_endpoint_host() != "auto")
|
||||
return config.grpc_endpoint_host();
|
||||
}
|
||||
for (const auto& address : interfaces) {
|
||||
if (!address.loopback() &&
|
||||
address.family() == v1::NetworkInterfaceAddress::ADDRESS_FAMILY_IPV4) {
|
||||
return address.ip_address();
|
||||
// Match the destination name actually passed to MsQuic ConnectionStart.
|
||||
const auto& host = config.tls().allow_insecure() || config.tls().server_name().empty()
|
||||
? config.server_host() : config.tls().server_name();
|
||||
addrinfo hints{};hints.ai_family=AF_UNSPEC;hints.ai_socktype=SOCK_DGRAM;
|
||||
hints.ai_protocol=IPPROTO_UDP;
|
||||
addrinfo* addresses=nullptr;
|
||||
const auto port=std::to_string(config.server_port());
|
||||
if(::getaddrinfo(host.c_str(),port.c_str(),&hints,&addresses)!=0)return {};
|
||||
std::string result;
|
||||
for(const auto* address=addresses;address;address=address->ai_next){
|
||||
const int fd=::socket(address->ai_family,SOCK_DGRAM,IPPROTO_UDP);
|
||||
if(fd<0)continue;
|
||||
sockaddr_storage local{};socklen_t size=sizeof(local);
|
||||
const bool ok=::connect(fd,address->ai_addr,address->ai_addrlen)==0 &&
|
||||
::getsockname(fd,reinterpret_cast<sockaddr*>(&local),&size)==0;
|
||||
::close(fd);
|
||||
if(!ok)continue;
|
||||
const void* source=nullptr;int family=local.ss_family;
|
||||
if(family==AF_INET)source=&reinterpret_cast<const sockaddr_in*>(&local)->sin_addr;
|
||||
else if(family==AF_INET6){
|
||||
const auto* ipv6=&reinterpret_cast<const sockaddr_in6*>(&local)->sin6_addr;
|
||||
if(IN6_IS_ADDR_V4MAPPED(ipv6)){family=AF_INET;source=&ipv6->s6_addr[12];}
|
||||
else source=ipv6;
|
||||
}
|
||||
std::array<char,INET6_ADDRSTRLEN> text{};
|
||||
if(source && ::inet_ntop(family,source,text.data(),text.size()) &&
|
||||
std::strcmp(text.data(),"0.0.0.0")!=0 && std::strcmp(text.data(),"::")!=0){result=text.data();break;}
|
||||
}
|
||||
for (const auto& address : interfaces) {
|
||||
if (!address.loopback()) return address.ip_address();
|
||||
}
|
||||
return interfaces.empty() ? "127.0.0.1" : interfaces.front().ip_address();
|
||||
::freeaddrinfo(addresses);
|
||||
// Do not silently advertise an unrelated NIC when destination lookup fails.
|
||||
return result;
|
||||
}
|
||||
|
||||
void populateDescriptor(const config::QuicEdgeConfig& config,
|
||||
@ -228,7 +248,7 @@ void populateDescriptor(const config::QuicEdgeConfig& config,
|
||||
*descriptor->add_local_interfaces() = address;
|
||||
}
|
||||
auto* endpoint = descriptor->mutable_grpc_endpoint();
|
||||
endpoint->set_host(advertisedGrpcHost(config, interfaces));
|
||||
endpoint->set_host(advertisedGrpcHost(config));
|
||||
endpoint->set_port(config.grpc_endpoint_port());
|
||||
endpoint->set_tls(config.grpc_endpoint_tls());
|
||||
}
|
||||
@ -243,7 +263,7 @@ void populateHeartbeatNetwork(const config::QuicEdgeConfig& config,
|
||||
*heartbeat->add_local_interfaces() = address;
|
||||
}
|
||||
auto* endpoint = heartbeat->mutable_grpc_endpoint();
|
||||
endpoint->set_host(advertisedGrpcHost(config, interfaces));
|
||||
endpoint->set_host(advertisedGrpcHost(config));
|
||||
endpoint->set_port(config.grpc_endpoint_port());
|
||||
endpoint->set_tls(config.grpc_endpoint_tls());
|
||||
}
|
||||
@ -1161,6 +1181,10 @@ bool QuicEdgeService::sendNodeRegistration(std::string* error)
|
||||
auto* request = envelope.mutable_node_register_request();
|
||||
populateDescriptor(config_, node_id_, boot_id_, software_version_,
|
||||
request->mutable_node());
|
||||
if(request->node().grpc_endpoint().host().empty()){
|
||||
setError(error,"cannot select a local gRPC address routed to QUIC platform "+config_.server_host());
|
||||
return false;
|
||||
}
|
||||
request->set_sent_at_unix_ms(unixTimeMs());
|
||||
std::string serialized;
|
||||
if (!envelope.SerializeToString(&serialized)) {
|
||||
@ -1230,6 +1254,10 @@ bool QuicEdgeService::sendHeartbeat(const std::uint64_t sequence,
|
||||
heartbeat->set_sent_at_unix_ms(sent_at_unix_ms);
|
||||
heartbeat->set_software_version(software_version_);
|
||||
populateHeartbeatNetwork(config_, heartbeat);
|
||||
if(heartbeat->grpc_endpoint().host().empty()){
|
||||
setError(error,"cannot select a local gRPC address routed to QUIC platform "+config_.server_host());
|
||||
return false;
|
||||
}
|
||||
if (device_manager_snapshot.has_value()) {
|
||||
populateDeviceManagerSnapshot(
|
||||
*device_manager_snapshot, sent_at_unix_ms,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user