feat(touch): split tactile devices and add PX6AX GenX CAN support
This commit is contained in:
parent
0ca045d59b
commit
b7d0beec92
@ -16,33 +16,4 @@ dexhand {
|
||||
poll_interval_ms: 10
|
||||
}
|
||||
}
|
||||
|
||||
dexhands {
|
||||
id: "paxini_tip_1"
|
||||
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: PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE
|
||||
auto_calibrate: false
|
||||
}
|
||||
}
|
||||
|
||||
dexhands {
|
||||
id: "mujoco_zero_touch_dexhand"
|
||||
zero_sim_touch {}
|
||||
}
|
||||
}
|
||||
|
||||
17
cmvr-es/config/devices/touch/touch.pb.txt
Normal file
17
cmvr-es/config/devices/touch/touch.pb.txt
Normal file
@ -0,0 +1,17 @@
|
||||
touch {
|
||||
touches {
|
||||
id: "paxini_tip_1"
|
||||
px_6ax_genx_can {
|
||||
# 系统预先配置 can0 为 1 Mbps;设备以约 2 ms 为目标采读并主动发送有效值,非严格周期。
|
||||
channel_id: 0
|
||||
force_can_id: 0x600
|
||||
# 按主机本地接收时间计算的最大有效期;超过此时间无有效报文则报不可用。
|
||||
max_sample_age_ms: 300
|
||||
}
|
||||
}
|
||||
|
||||
touches {
|
||||
id: "mujoco_zero_touch"
|
||||
zero_sim {}
|
||||
}
|
||||
}
|
||||
@ -68,15 +68,15 @@ device_manager {
|
||||
|
||||
devices {
|
||||
id: "paxini_tip_1"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
type: DEVICE_TYPE_TOUCH
|
||||
config_file: "devices/touch/touch.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_zero_touch_dexhand"
|
||||
type: DEVICE_TYPE_DEXHAND
|
||||
config_file: "devices/dexhand/dexhand.pb.txt"
|
||||
id: "mujoco_zero_touch"
|
||||
type: DEVICE_TYPE_TOUCH
|
||||
config_file: "devices/touch/touch.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
|
||||
@ -7,7 +7,7 @@ touch_screen_task {
|
||||
|
||||
devices {
|
||||
arm_id: "right_arm"
|
||||
dexhand_id: "paxini_tip_1"
|
||||
touch_id: "paxini_tip_1"
|
||||
# 手部相机和外部相机的 DeviceManager ID。
|
||||
camera_id: "right_hand_cam"
|
||||
external_camera_id: "left_hand_cam"
|
||||
@ -103,8 +103,6 @@ touch_screen_task {
|
||||
max_distance_m: 0.03
|
||||
}
|
||||
tactile {
|
||||
finger: TOUCH_SCREEN_FINGER_TYPE_INDEX
|
||||
region: TOUCH_SCREEN_TACTILE_REGION_TIP
|
||||
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
|
||||
force_threshold: 0.1 # N
|
||||
}
|
||||
|
||||
@ -7,7 +7,7 @@ touch_screen_task {
|
||||
|
||||
devices {
|
||||
arm_id: "mujoco_right_arm"
|
||||
dexhand_id: "mujoco_zero_touch_dexhand"
|
||||
touch_id: "mujoco_zero_touch"
|
||||
# 手部相机和外部相机的 DeviceManager ID。
|
||||
camera_id: "mujoco_hand_cam"
|
||||
external_camera_id: "mujoco_external_touch_cam"
|
||||
@ -123,8 +123,6 @@ touch_screen_task {
|
||||
max_distance_m: 0.02
|
||||
}
|
||||
tactile {
|
||||
finger: TOUCH_SCREEN_FINGER_TYPE_INDEX
|
||||
region: TOUCH_SCREEN_TACTILE_REGION_TIP
|
||||
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
|
||||
force_threshold: 0.1 # N
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@ add_subdirectory(agv)
|
||||
add_subdirectory(speaker)
|
||||
add_subdirectory(microphone)
|
||||
add_subdirectory(dexhand)
|
||||
add_subdirectory(touch)
|
||||
add_subdirectory(biohead)
|
||||
add_subdirectory(arm)
|
||||
add_subdirectory(canbus)
|
||||
|
||||
@ -21,11 +21,16 @@ namespace cmvr::device {
|
||||
uint8_t data[8];
|
||||
/// Time stamp
|
||||
struct timeval timestamp;
|
||||
/// CAN frame flags, kept separately from the numeric message id.
|
||||
bool is_extended;
|
||||
bool is_remote;
|
||||
bool is_error;
|
||||
|
||||
/**
|
||||
* @brief Constructor
|
||||
*/
|
||||
CanFrame() : id(0), len(0), timestamp{0} {
|
||||
CanFrame() : id(0), len(0), timestamp{0},
|
||||
is_extended(false), is_remote(false), is_error(false) {
|
||||
std::memset(data, 0, sizeof(data));
|
||||
}
|
||||
|
||||
|
||||
@ -12,6 +12,11 @@
|
||||
#include "socket_can_client_raw.h"
|
||||
#include "absl/strings/str_cat.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <limits>
|
||||
#include <poll.h>
|
||||
|
||||
namespace cmvr {
|
||||
namespace device {
|
||||
#define CAN_ID_MASK 0x1FFFF800U // can_filter mask
|
||||
@ -49,9 +54,7 @@ namespace cmvr {
|
||||
}
|
||||
|
||||
SocketCanClientRaw::~SocketCanClientRaw() {
|
||||
if (dev_handler_) {
|
||||
stop();
|
||||
}
|
||||
stop();
|
||||
}
|
||||
|
||||
bool SocketCanClientRaw::start() {
|
||||
@ -59,8 +62,8 @@ namespace cmvr {
|
||||
status_ = ErrorCode::OK;
|
||||
return true;
|
||||
}
|
||||
struct sockaddr_can addr;
|
||||
struct ifreq ifr;
|
||||
struct sockaddr_can addr {};
|
||||
struct ifreq ifr {};
|
||||
|
||||
// open device
|
||||
// guss net is the device minor number, if one card is 0,1
|
||||
@ -73,6 +76,12 @@ namespace cmvr {
|
||||
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
|
||||
return false;
|
||||
}
|
||||
const auto fail_start = [this]() {
|
||||
::close(dev_handler_);
|
||||
dev_handler_ = -1;
|
||||
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
|
||||
return false;
|
||||
};
|
||||
|
||||
// init config and state
|
||||
int ret;
|
||||
@ -90,20 +99,12 @@ namespace cmvr {
|
||||
sizeof(filter));
|
||||
if (ret < 0) {
|
||||
CMVR_LOG(ERROR) << "add receive msg id filter error code: " << ret;
|
||||
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
|
||||
return false;
|
||||
return fail_start();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. enable reception of can frames.
|
||||
int enable = 1;
|
||||
ret = ::setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable,
|
||||
sizeof(enable));
|
||||
if (ret < 0) {
|
||||
CMVR_LOG(ERROR) << "enable reception of can frame error code: " << ret;
|
||||
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
|
||||
return false;
|
||||
}
|
||||
// CAN_RAW_FD_FRAMES is disabled by default. CanFrame holds only
|
||||
// classical CAN's eight data bytes, so never enable CAN FD here.
|
||||
|
||||
std::string interface_prefix;
|
||||
if (interface_ == CANCardParameter::VIRTUAL) {
|
||||
@ -116,11 +117,10 @@ namespace cmvr {
|
||||
}
|
||||
|
||||
const std::string can_name = absl::StrCat(interface_prefix, port_);
|
||||
std::strncpy(ifr.ifr_name, can_name.c_str(), IFNAMSIZ);
|
||||
std::strncpy(ifr.ifr_name, can_name.c_str(), IFNAMSIZ - 1);
|
||||
if (ioctl(dev_handler_, SIOCGIFINDEX, &ifr) < 0) {
|
||||
CMVR_LOG(ERROR) << "ioctl error";
|
||||
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
|
||||
return false;
|
||||
return fail_start();
|
||||
}
|
||||
|
||||
// bind socket to network interface
|
||||
@ -132,8 +132,7 @@ namespace cmvr {
|
||||
|
||||
if (ret < 0) {
|
||||
CMVR_LOG(ERROR) << "bind socket to network interface error code: " << ret;
|
||||
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
|
||||
return false;
|
||||
return fail_start();
|
||||
}
|
||||
|
||||
is_started_ = true;
|
||||
@ -142,10 +141,11 @@ namespace cmvr {
|
||||
}
|
||||
|
||||
bool SocketCanClientRaw::stop() {
|
||||
if (is_started_) {
|
||||
is_started_ = false;
|
||||
|
||||
int ret = close(dev_handler_);
|
||||
is_started_ = false;
|
||||
if (dev_handler_ >= 0) {
|
||||
const int fd = dev_handler_;
|
||||
dev_handler_ = -1;
|
||||
int ret = close(fd);
|
||||
if (ret < 0) {
|
||||
CMVR_LOG(ERROR) << "close error code:" << ret << ", " << getErrorString(ret);
|
||||
return false;
|
||||
@ -198,37 +198,107 @@ namespace cmvr {
|
||||
return ErrorCode::OK;
|
||||
}
|
||||
|
||||
// buf size must be 8 bytes, every time, we receive only one frame
|
||||
ErrorCode SocketCanClientRaw::receive(std::vector<CanFrame> *const frames,
|
||||
int32_t *const frame_num) {
|
||||
return receive(frames, frame_num, std::chrono::milliseconds{-1});
|
||||
}
|
||||
|
||||
ErrorCode SocketCanClientRaw::receive(std::vector<CanFrame> *const frames,
|
||||
int32_t *const frame_num,
|
||||
std::chrono::milliseconds timeout) {
|
||||
if (frame_num == nullptr) {
|
||||
return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
|
||||
}
|
||||
const int32_t requested = *frame_num;
|
||||
*frame_num = 0;
|
||||
if (frames == nullptr) {
|
||||
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
|
||||
}
|
||||
if (!is_started_) {
|
||||
CMVR_LOG(ERROR) << "Nvidia can client is not init! Please init first!";
|
||||
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
|
||||
}
|
||||
|
||||
if (*frame_num > MAX_CAN_RECV_FRAME_LEN || *frame_num < 0) {
|
||||
if (requested > MAX_CAN_RECV_FRAME_LEN || requested < 0) {
|
||||
CMVR_LOG(ERROR) << "recv can frame num not in range[0, " << MAX_CAN_RECV_FRAME_LEN
|
||||
<< "], frame_num:" << *frame_num;
|
||||
// TODO(Authors): check the difference of returning frame_num/error_code
|
||||
<< "], frame_num:" << requested;
|
||||
return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
|
||||
}
|
||||
|
||||
for (int32_t i = 0; i < *frame_num && i < MAX_CAN_RECV_FRAME_LEN; ++i) {
|
||||
CanFrame cf;
|
||||
auto ret = read(dev_handler_, &recv_frames_[i], sizeof(recv_frames_[i]));
|
||||
|
||||
if (ret < 0) {
|
||||
CMVR_LOG(ERROR) << "receive message failed, error code: " << ret;
|
||||
return ErrorCode::CAN_CLIENT_ERROR_BASE;
|
||||
const bool bounded = timeout.count() >= 0;
|
||||
const auto started = std::chrono::steady_clock::now();
|
||||
bool first_poll = true;
|
||||
while (*frame_num < requested) {
|
||||
int wait_ms = -1;
|
||||
if (bounded) {
|
||||
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - started);
|
||||
if (!first_poll && elapsed >= timeout) {
|
||||
return ErrorCode::OK;
|
||||
}
|
||||
const auto remaining = timeout > elapsed ? timeout - elapsed
|
||||
: std::chrono::milliseconds{0};
|
||||
wait_ms = static_cast<int>(std::min<int64_t>(
|
||||
remaining.count(), std::numeric_limits<int>::max()));
|
||||
}
|
||||
if (recv_frames_[i].can_dlc > CANBUS_MESSAGE_LENGTH ||
|
||||
recv_frames_[i].can_dlc < 0) {
|
||||
first_poll = false;
|
||||
struct pollfd descriptor {dev_handler_, POLLIN, 0};
|
||||
const int ready = ::poll(&descriptor, 1, wait_ms);
|
||||
if (ready < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
CMVR_LOG(ERROR) << "poll can socket failed: " << std::strerror(errno);
|
||||
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
|
||||
}
|
||||
if (ready == 0) {
|
||||
if (!bounded) {
|
||||
continue;
|
||||
}
|
||||
// A long timeout may need several poll calls (poll takes int).
|
||||
if (std::chrono::steady_clock::now() - started < timeout) {
|
||||
continue;
|
||||
}
|
||||
return ErrorCode::OK;
|
||||
}
|
||||
if (descriptor.revents & (POLLERR | POLLHUP | POLLNVAL)) {
|
||||
CMVR_LOG(ERROR) << "can socket poll error flags: " << descriptor.revents;
|
||||
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
|
||||
}
|
||||
if (!(descriptor.revents & POLLIN)) {
|
||||
continue;
|
||||
}
|
||||
const int32_t i = *frame_num;
|
||||
// Do not block after poll if another reader consumed the packet.
|
||||
// recvmsg also identifies truncated/FD packets even if the
|
||||
// socket reports only the length copied into our CAN buffer.
|
||||
struct iovec buffer {&recv_frames_[i], sizeof(recv_frames_[i])};
|
||||
struct msghdr message {};
|
||||
message.msg_iov = &buffer;
|
||||
message.msg_iovlen = 1;
|
||||
const auto ret = ::recvmsg(dev_handler_, &message, MSG_DONTWAIT);
|
||||
if (ret < 0) {
|
||||
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
continue;
|
||||
}
|
||||
CMVR_LOG(ERROR) << "receive message failed: " << std::strerror(errno);
|
||||
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
|
||||
}
|
||||
if (ret != CAN_MTU || (message.msg_flags & MSG_TRUNC)) {
|
||||
CMVR_LOG(ERROR) << "received non-classical or incomplete CAN frame: " << ret;
|
||||
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
|
||||
}
|
||||
if (recv_frames_[i].can_dlc > CANBUS_MESSAGE_LENGTH) {
|
||||
CMVR_LOG(ERROR) << "recv_frames_[" << i
|
||||
<< "].can_dlc = " << recv_frames_[i].can_dlc
|
||||
<< ", which is not equal to can message data length ("
|
||||
<< CANBUS_MESSAGE_LENGTH << ").";
|
||||
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
|
||||
}
|
||||
CanFrame cf;
|
||||
cf.is_extended = (recv_frames_[i].can_id & CAN_EFF_FLAG) != 0;
|
||||
cf.is_remote = (recv_frames_[i].can_id & CAN_RTR_FLAG) != 0;
|
||||
cf.is_error = (recv_frames_[i].can_id & CAN_ERR_FLAG) != 0;
|
||||
if (recv_frames_[i].can_id > CAN_STANDARD_MAX_ID) {
|
||||
cf.id = enable_can_err_check_
|
||||
? recv_frames_[i].can_id & CAN_EFF_MASK | CAN_ERR_FLAG
|
||||
@ -240,6 +310,7 @@ namespace cmvr {
|
||||
cf.len = recv_frames_[i].can_dlc;
|
||||
std::memcpy(cf.data, recv_frames_[i].data, recv_frames_[i].can_dlc);
|
||||
frames->push_back(cf);
|
||||
++*frame_num;
|
||||
}
|
||||
return ErrorCode::OK;
|
||||
}
|
||||
|
||||
@ -15,6 +15,7 @@
|
||||
#include <linux/can/raw.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
@ -61,13 +62,23 @@ namespace cmvr {
|
||||
cmvr::msgs::ErrorCode receive(std::vector<CanFrame> *const frames,
|
||||
int32_t *const frame_num) override;
|
||||
|
||||
/**
|
||||
* @brief Receive up to frame_num messages within one timeout.
|
||||
* @param frame_num Requested count on input, actual appended count on output.
|
||||
* @param timeout Maximum wait for the whole call; negative waits indefinitely.
|
||||
* @return OK on timeout, including when no frames were received.
|
||||
*/
|
||||
cmvr::msgs::ErrorCode receive(std::vector<CanFrame> *const frames,
|
||||
int32_t *const frame_num,
|
||||
std::chrono::milliseconds timeout);
|
||||
|
||||
/**
|
||||
* @brief Get the error string.
|
||||
* @param status The status to get the error string.
|
||||
*/
|
||||
std::string getErrorString(const int32_t status) override;
|
||||
private:
|
||||
int dev_handler_ = 0;
|
||||
int dev_handler_ = -1;
|
||||
cmvr::msgs::CANCardParameter::CANChannelId port_;
|
||||
cmvr::msgs::CANCardParameter::CANInterface interface_;
|
||||
can_frame send_frames_[MAX_CAN_SEND_FRAME_LEN];
|
||||
|
||||
@ -24,6 +24,7 @@ namespace cmvr::device {
|
||||
MujocoWorld,
|
||||
Robot,
|
||||
Speaker,
|
||||
Touch,
|
||||
};
|
||||
|
||||
inline std::string toString(DeviceKind kind) {
|
||||
@ -58,6 +59,8 @@ namespace cmvr::device {
|
||||
return "Robot";
|
||||
case DeviceKind::Speaker:
|
||||
return "Speaker";
|
||||
case DeviceKind::Touch:
|
||||
return "Touch";
|
||||
case DeviceKind::Unknown:
|
||||
default:
|
||||
return "Unknown";
|
||||
|
||||
@ -1,6 +1,4 @@
|
||||
add_subdirectory(rh56dftp_dexhand)
|
||||
add_subdirectory(px_6ax_gen3)
|
||||
add_subdirectory(zero_sim_touch_dexhand)
|
||||
|
||||
add_library(dexhand INTERFACE)
|
||||
|
||||
@ -9,8 +7,6 @@ target_include_directories(dexhand INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(dexhand
|
||||
INTERFACE
|
||||
cmvr_es::device::rh56dftp_dexhand
|
||||
cmvr_es::device::px_6ax_gen3
|
||||
cmvr_es::device::zero_sim_touch_dexhand
|
||||
cmvr_es::proto
|
||||
)
|
||||
|
||||
|
||||
@ -15,6 +15,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "devices/abstract_device.h"
|
||||
#include "devices/touch/touch_types.h"
|
||||
#include "common/base/logging/logger.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
@ -22,38 +23,10 @@ namespace cmvr::device {
|
||||
public:
|
||||
DeviceKind kind() const noexcept override { return DeviceKind::DexHand; }
|
||||
|
||||
struct TactilePoint {
|
||||
int32_t fx{0};
|
||||
int32_t fy{0};
|
||||
int32_t fz{0};
|
||||
|
||||
static TactilePoint fromFz(const int32_t value) {
|
||||
return TactilePoint{0, 0, value};
|
||||
}
|
||||
|
||||
double magnitude() const {
|
||||
return std::sqrt(static_cast<double>(fx) * static_cast<double>(fx) +
|
||||
static_cast<double>(fy) * static_cast<double>(fy) +
|
||||
static_cast<double>(fz) * static_cast<double>(fz));
|
||||
}
|
||||
|
||||
bool isZero() const {
|
||||
return fx == 0 && fy == 0 && fz == 0;
|
||||
}
|
||||
};
|
||||
|
||||
using TactilePoint = cmvr::device::TactilePoint;
|
||||
using ResultantForce = TactilePoint;
|
||||
|
||||
// Physical force, separate from device-specific integer tactile data.
|
||||
struct ForceNewtons {
|
||||
double fx{0.0};
|
||||
double fy{0.0};
|
||||
double fz{0.0};
|
||||
|
||||
double magnitude() const {
|
||||
return std::hypot(fx, fy, fz);
|
||||
}
|
||||
};
|
||||
using ForceNewtons = cmvr::device::ForceNewtons;
|
||||
using TactileMatrixView = cmvr::device::TactileMatrixView;
|
||||
|
||||
enum class FingerType {
|
||||
PINKY,
|
||||
@ -74,28 +47,6 @@ namespace cmvr::device {
|
||||
|
||||
using TactileRegionKey = std::pair<FingerType, TactileRegion>;
|
||||
|
||||
struct TactileMatrixView {
|
||||
const TactilePoint* data{nullptr};
|
||||
int rows{0};
|
||||
int cols{0};
|
||||
|
||||
bool valid() const {
|
||||
return data != nullptr && rows > 0 && cols > 0;
|
||||
}
|
||||
|
||||
int pointCount() const {
|
||||
return rows * cols;
|
||||
}
|
||||
|
||||
const TactilePoint* rowData(int row) const {
|
||||
return data + row * cols;
|
||||
}
|
||||
|
||||
TactilePoint at(int row, int col) const {
|
||||
return data[row * cols + col];
|
||||
}
|
||||
};
|
||||
|
||||
class TactileRegionData {
|
||||
public:
|
||||
TactileRegionData() = default;
|
||||
|
||||
@ -8,9 +8,7 @@
|
||||
#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"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
@ -29,14 +27,6 @@ public:
|
||||
return std::make_shared<RH56DFTPDexhand>(
|
||||
backendWithId_(cfg.id(), cfg.rh56dftp()));
|
||||
|
||||
case config::DexHandDeviceConfig::kPx6AxGen3:
|
||||
return std::make_shared<PX6AXGen3>(
|
||||
backendWithId_(cfg.id(), cfg.px_6ax_gen3()));
|
||||
|
||||
case config::DexHandDeviceConfig::kZeroSimTouch:
|
||||
return std::make_shared<ZeroSimTouchDexHand>(
|
||||
backendWithId_(cfg.id(), cfg.zero_sim_touch()));
|
||||
|
||||
case config::DexHandDeviceConfig::BACKEND_NOT_SET:
|
||||
default:
|
||||
{
|
||||
|
||||
@ -1,318 +0,0 @@
|
||||
#include "../include/px_6ax_gen3.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
using Sensor = cmvr::device::PX6AXGen3;
|
||||
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::PX6AXGen3 config() {
|
||||
cmvr::config::PX6AXGen3 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::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(PX6AXGen3, 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(PX6AXGen3, 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(PX6AXGen3, 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(PX6AXGen3, 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(PX6AXGen3, 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(PX6AXGen3, 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(PX6AXGen3, 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(PX6AXGen3, DistributedDataIsValidatedAndParsed) {
|
||||
auto cfg = config();
|
||||
cfg.set_polling_read_mode(cmvr::config::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(PX6AXGen3, 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(PX6AXGen3, 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(PX6AXGen3, 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);
|
||||
}
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
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)
|
||||
@ -1,58 +0,0 @@
|
||||
#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
|
||||
@ -1,101 +0,0 @@
|
||||
#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
|
||||
13
cmvr-es/devices/touch/CMakeLists.txt
Normal file
13
cmvr-es/devices/touch/CMakeLists.txt
Normal file
@ -0,0 +1,13 @@
|
||||
add_subdirectory(px_6ax_gen3)
|
||||
add_subdirectory(px_6ax_genx_can)
|
||||
add_subdirectory(zero_sim_touch)
|
||||
|
||||
add_library(touch INTERFACE)
|
||||
target_include_directories(touch INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(touch INTERFACE
|
||||
cmvr_es::device::px_6ax_gen3
|
||||
cmvr_es::device::px_6ax_genx_can
|
||||
cmvr_es::device::zero_sim_touch
|
||||
cmvr_es::proto
|
||||
)
|
||||
add_library(cmvr_es::device::touch ALIAS touch)
|
||||
26
cmvr-es/devices/touch/abstract_touch.h
Normal file
26
cmvr-es/devices/touch/abstract_touch.h
Normal file
@ -0,0 +1,26 @@
|
||||
#ifndef CMVR_ES_ABSTRACT_TOUCH_H
|
||||
#define CMVR_ES_ABSTRACT_TOUCH_H
|
||||
|
||||
#include "devices/abstract_device.h"
|
||||
#include "devices/touch/touch_types.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class AbstractTouch : public AbstractDevice {
|
||||
public:
|
||||
enum class Status { CREATED, INITIALIZED, STREAMING, STOPPED, FAULT };
|
||||
|
||||
DeviceKind kind() const noexcept override { return DeviceKind::Touch; }
|
||||
virtual Status state() const = 0;
|
||||
virtual std::string lastError() const = 0;
|
||||
|
||||
// Return false and clear the output when no valid, fresh sample is available.
|
||||
// Background receivers return cached samples with their original timestamps.
|
||||
// Other channels may issue a synchronous request to the sensor.
|
||||
virtual bool readForce(ForceSample& sample) = 0;
|
||||
virtual bool readTactile(TactileSample& sample) = 0;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_ABSTRACT_TOUCH_H
|
||||
@ -9,6 +9,7 @@ target_link_libraries(px_6ax_gen3
|
||||
PRIVATE
|
||||
cmvr_es::proto
|
||||
glog
|
||||
pthread
|
||||
)
|
||||
|
||||
install(TARGETS px_6ax_gen3 LIBRARY DESTINATION lib)
|
||||
@ -1,13 +1,28 @@
|
||||
# PX-6AX GEN3 传感器读取与真实 USB 测试
|
||||
# PX-6AX GEN3 USB 触觉驱动
|
||||
|
||||
真实测试只创建 PX6AXGen3 和 POSIX 串口,不初始化机械臂或 DeviceManager;禁用自动标定,传输层只允许 `0xFB` 读取命令。
|
||||
## 简洁串口测试
|
||||
|
||||
`px_6ax_gen3_test` 中的 `PX6AXGen3.PrintResultantForce` 连接真实串口 `/dev/ttyACM1`,模块 ID 为 2,波特率为 921600。循环读取 300 次,每次间隔 100 ms,打印 `Fx`、`Fy`、`Fz` 和 `magnitude`,单位均为 N;不使用模拟数据或断言。
|
||||
|
||||
在仓库根目录构建并运行:
|
||||
|
||||
```bash
|
||||
./scripts/build.sh Debug
|
||||
export LD_LIBRARY_PATH="$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
||||
./build/Debug/cmvr-es/devices/touch/px_6ax_gen3/px_6ax_gen3_test \
|
||||
--gtest_filter=PX6AXGen3.PrintResultantForce
|
||||
```
|
||||
|
||||
## USB 串口读取
|
||||
|
||||
`px_6ax_gen3_real_test` 只创建 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="$PWD/build/Debug/cmvr-es/devices/touch/px_6ax_gen3/px_6ax_gen3_real_test"
|
||||
|
||||
# 每次读取都发起一个真实请求:检查串口应答耗时和按压力值。
|
||||
"$px6_test" --port /dev/ttyACM0 --module-id 2 \
|
||||
@ -22,7 +37,7 @@ px6_test="$PWD/build/Debug/cmvr-es/devices/dexhand/px_6ax_gen3/px_6ax_gen3_real_
|
||||
|
||||
先确认构建和安装成功,再运行测试,确保 `output/lib` 中的驱动和 protobuf 与测试程序属于同一次构建。串口应可读写,运行测试前退出占用同一串口的程序。
|
||||
|
||||
测试期间可用手轻按、松开传感器,终端每 100 ms 显示一次力值,CSV 记录每次 getter 调用。按 Ctrl-C 可结束。CSV 的无效读数留空,不能当作零力。进程在初始化失败、没有有效数据或存在读取失败时返回非零退出码。
|
||||
测试期间可用手轻按、松开传感器,终端每 100 ms 显示一次力值,CSV 记录每次 `readForce()` 调用。按 Ctrl-C 可结束。CSV 的无效读数留空,不能当作零力。进程在初始化失败、没有有效数据或存在读取失败时返回非零退出码。
|
||||
|
||||
- `sync` 的 `read_ms` 是一次驱动请求/应答调用的耗时;默认每 5 ms 请求一次。
|
||||
- `stream` 的 `read_ms` 是读取缓存耗时,成功次数包含重复快照,不能据此推算传感器实际更新频率。
|
||||
@ -32,24 +47,16 @@ px6_test="$PWD/build/Debug/cmvr-es/devices/dexhand/px_6ax_gen3/px_6ax_gen3_real_
|
||||
|
||||
## 驱动行为
|
||||
|
||||
`getResultantForceNewtons()` 将合力寄存器的三个原始分量各乘以 0.1,返回以 N 为单位的浮点力值;原有 `getResultantForce()` 保留原始整数。触屏任务和 USB 测试使用牛顿接口,不再额外换算。触屏任务的 `force_threshold`、力值日志和 `lastTouchPressureSum()` 均使用 N;阈值 `0.1` 与旧版原始值阈值 `1.0` 对应相同力度。FZ 判据比较法向力,MAGNITUDE 判据比较三轴合力大小,多区域按原逻辑累加。
|
||||
`PX6AXGen3` 继承 `AbstractTouch`,配置位于 `devices/touch/touch.pb.txt`,设备类型为 `DEVICE_TYPE_TOUCH`。触屏任务通过 `touch_id` 选择设备,不需要手指或部位参数。
|
||||
|
||||
MuJoCo 零值触觉后端也实现牛顿接口。尚无确定换算系数的其他后端(如 RH56DFTP)调用该接口会明确报错,不会把原始压力计数当成 N。
|
||||
`readForce(ForceSample&)` 将合力寄存器的三个原始分量各乘以 0.1,在 `sample.force` 中返回以 N 为单位的浮点力值。`readTactile(TactileSample&)` 返回触觉阵列原始计数、行列尺寸和名称。串口驱动在 `sample_time` 中返回该类数据的请求开始时间;返回 `false` 时输出样本被清空,不能当作有效零力。
|
||||
|
||||
触屏任务和 USB 测试使用牛顿接口,不再额外换算。触屏任务的 `force_threshold`、力值日志和 `lastTouchPressureSum()` 均使用 N;阈值 `0.1` 与旧版原始值阈值 `1.0` 对应相同力度。FZ 判据比较法向力,MAGNITUDE 判据比较三轴合力大小。MuJoCo 的 `ZeroSimTouch` 也实现相同接口。
|
||||
|
||||
合力应答按 `14 字节头部 + 3 字节数据 + 1 字节 LRC` 完整读取。验证帧长度、设备地址、预留位、功能码、寄存器地址、字节数及 LRC,并支持分片、请求回显和噪声后的重新定位。
|
||||
|
||||
读状态字节属于内部调试信息(手册 5.3.5);实测正常读应答为 `0x01`,不能套用写应答 `0x00=成功` 的规则。自动标定的写应答要求完整 15 字节并且状态为 0。
|
||||
|
||||
`max_sample_age_ms` 默认 50 ms,可在设备配置中调整。每类数据分别记录请求开始时间:较晚返回的旧请求不能被重新标记为新数据。此值独立于 `response_timeout_ms`(默认 200 ms)。后台读取接口遇到过期或失效快照会抛出异常,不等待串口补读、不返回旧力值或伪造零值;触屏任务现有的异常捕获会将其识别为触觉不可用。
|
||||
`max_sample_age_ms` 默认 50 ms,可在设备配置中调整。每类数据分别记录请求开始时间:较晚返回的旧请求不能被重新标记为新数据。此值独立于 `response_timeout_ms`(默认 200 ms)。对于已开启后台轮询的通道,读取过期或失效快照会立即返回 `false`,不等待串口补读、不返回旧力值;`lastError()` 给出失败原因,触屏任务将其识别为触觉不可用。读取未轮询的通道时会同步请求,例如只轮询合力时调用 `readTactile()`。
|
||||
|
||||
通信失败会使快照失效,后台继续尝试恢复,只有通过验证的新应答才能恢复有效数据。`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
|
||||
```
|
||||
通信失败会使快照失效,后台继续尝试恢复,只有通过验证的新应答才能恢复有效数据。`stop()` 清除缓存;停止或故障状态下的读取返回 `false`,显式 `init()` / `start()` 后才能恢复。初始化重试失败会返回 false。
|
||||
@ -2,8 +2,8 @@
|
||||
// Created by Codex on 2026/4/3.
|
||||
//
|
||||
|
||||
#ifndef PX_6AX_GEN3_DEXHAND_H
|
||||
#define PX_6AX_GEN3_DEXHAND_H
|
||||
#ifndef PX_6AX_GEN3_TOUCH_H
|
||||
#define PX_6AX_GEN3_TOUCH_H
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
@ -16,22 +16,14 @@
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "cmvr/config/dexhand_config/dexhand_config.pb.h"
|
||||
#include "cmvr/config/touch_config/touch_config.pb.h"
|
||||
#include "hardware/include/abstract_serial_transport.h"
|
||||
#include "../../abstract_dexhand.h"
|
||||
#include "devices/touch/abstract_touch.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class PX6AXGen3 final : public AbstractDexHand {
|
||||
class PX6AXGen3 final : public AbstractTouch {
|
||||
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,
|
||||
@ -50,16 +42,8 @@ namespace cmvr::device {
|
||||
|
||||
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;
|
||||
bool readForce(ForceSample& sample) override;
|
||||
bool readTactile(TactileSample& sample) override;
|
||||
|
||||
private:
|
||||
struct SensorSnapshot {
|
||||
@ -74,7 +58,6 @@ namespace cmvr::device {
|
||||
};
|
||||
|
||||
static PollingReadMode parsePollingReadMode(config::PX6AXGen3PollingReadMode mode);
|
||||
static PollingReadMode parsePollingReadModeName(std::string value);
|
||||
|
||||
void initializeSnapshot();
|
||||
void ensureConnected();
|
||||
@ -86,10 +69,8 @@ namespace cmvr::device {
|
||||
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();
|
||||
@ -119,8 +100,6 @@ namespace cmvr::device {
|
||||
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};
|
||||
@ -131,11 +110,10 @@ namespace cmvr::device {
|
||||
|
||||
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
|
||||
#endif //PX_6AX_GEN3_TOUCH_H
|
||||
@ -15,12 +15,7 @@
|
||||
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;
|
||||
using Status = AbstractTouch::Status;
|
||||
|
||||
enum class CommandType {
|
||||
CALIBRATION,
|
||||
@ -36,57 +31,6 @@ namespace {
|
||||
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) << "[PX6AXGen3] 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) << "[PX6AXGen3] 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;
|
||||
}
|
||||
@ -300,33 +244,6 @@ PX6AXGen3::PollingReadMode PX6AXGen3::parsePollingReadMode(const config::PX6AXGe
|
||||
}
|
||||
}
|
||||
|
||||
PX6AXGen3::PollingReadMode PX6AXGen3::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 == "PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE") {
|
||||
return PollingReadMode::DISTRIBUTED_FORCE;
|
||||
}
|
||||
if (value == "RESULTANT_FORCE" ||
|
||||
value == "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 == "PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_AND_RESULTANT_FORCE") {
|
||||
return PollingReadMode::DISTRIBUTED_AND_RESULTANT_FORCE;
|
||||
}
|
||||
|
||||
CMVR_LOG(ERROR) << "Unsupported PX6AXGen3 polling_read_mode: " << value;
|
||||
return PollingReadMode::DISTRIBUTED_AND_RESULTANT_FORCE;
|
||||
}
|
||||
|
||||
PX6AXGen3::PX6AXGen3(const config::PX6AXGen3& cfg)
|
||||
: PX6AXGen3(cfg, std::make_unique<::cmvr::PosixSerialTransport>()) {}
|
||||
|
||||
@ -376,12 +293,6 @@ PX6AXGen3::PX6AXGen3(const config::PX6AXGen3& cfg,
|
||||
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();
|
||||
}
|
||||
@ -427,19 +338,9 @@ bool PX6AXGen3::start() {
|
||||
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();
|
||||
}
|
||||
refreshSensorDataWithRetry(
|
||||
5,
|
||||
std::chrono::milliseconds(std::max(10, response_timeout_ms_ / 2)));
|
||||
|
||||
transitionTo(Status::STREAMING);
|
||||
polling_thread_ = std::thread(&PX6AXGen3::pollingLoop, this);
|
||||
@ -480,94 +381,46 @@ std::string PX6AXGen3::lastError() const {
|
||||
return last_error_;
|
||||
}
|
||||
|
||||
void PX6AXGen3::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;
|
||||
|
||||
{
|
||||
bool PX6AXGen3::readForce(ForceSample& sample) {
|
||||
sample = {};
|
||||
try {
|
||||
ensureSensorReady(true, false, true);
|
||||
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];
|
||||
if (!latest_snapshot_.resultant_valid || !isSampleFresh(latest_snapshot_.resultant_request_time)) {
|
||||
throw std::runtime_error("PX6AXGen3 resultant-force sample is unavailable or stale.");
|
||||
}
|
||||
// PX-6AX GEN3 manual 5.6.2: one resultant-force LSB is 0.1 N.
|
||||
const auto& raw = latest_snapshot_.resultant_force_tenths;
|
||||
sample.force = {raw[0] * 0.1, raw[1] * 0.1, raw[2] * 0.1};
|
||||
sample.sample_time = latest_snapshot_.resultant_request_time;
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
std::lock_guard<std::mutex> lock(lifecycle_mutex_);
|
||||
if (lifecycle_state_ != Status::FAULT) last_error_ = e.what();
|
||||
return false;
|
||||
}
|
||||
|
||||
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("PX6AXGen3 sample is unavailable or stale.");
|
||||
}
|
||||
|
||||
state_out = std::move(next_state);
|
||||
}
|
||||
|
||||
void PX6AXGen3::setAngles(const std::vector<int>&) {
|
||||
CMVR_LOG(ERROR) << "PX6AXGen3 is a tactile sensor only and does not support setAngles.";
|
||||
}
|
||||
|
||||
void PX6AXGen3::setTactilePollingRegions(const std::vector<TactileRegionKey>& regions) {
|
||||
for (const auto& region : regions) {
|
||||
if (!isSupportedRegion(region.first, region.second)) {
|
||||
CMVR_LOG(ERROR) << "PX6AXGen3 only exposes INDEX/TIP tactile data.";
|
||||
return;
|
||||
bool PX6AXGen3::readTactile(TactileSample& sample) {
|
||||
sample = {};
|
||||
try {
|
||||
ensureSensorReady(true, true, false);
|
||||
std::lock_guard<std::mutex> lock(snapshot_mutex_);
|
||||
if (!latest_snapshot_.tactile_valid || !isSampleFresh(latest_snapshot_.tactile_request_time)) {
|
||||
throw std::runtime_error("PX6AXGen3 tactile sample is unavailable or stale.");
|
||||
}
|
||||
sample.points = latest_snapshot_.tactile_points;
|
||||
sample.rows = latest_snapshot_.rows;
|
||||
sample.cols = latest_snapshot_.cols;
|
||||
sample.name = sensor_name_;
|
||||
sample.sample_time = latest_snapshot_.tactile_request_time;
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
sample = {};
|
||||
std::lock_guard<std::mutex> lock(lifecycle_mutex_);
|
||||
if (lifecycle_state_ != Status::FAULT) last_error_ = e.what();
|
||||
return false;
|
||||
}
|
||||
|
||||
{
|
||||
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> PX6AXGen3::getSensorData() {
|
||||
ensureSensorReady(true, true, false);
|
||||
std::vector<TactileRegionData> regions;
|
||||
regions.push_back(buildSupportedRegionSnapshot());
|
||||
return regions;
|
||||
}
|
||||
|
||||
TactileRegionData PX6AXGen3::getSensorData(FingerType finger, TactileRegion region) {
|
||||
if (!isSupportedRegion(finger, region)) {
|
||||
throw std::invalid_argument("PX6AXGen3 requested tactile region is not configured.");
|
||||
}
|
||||
|
||||
ensureSensorReady(true, true, false);
|
||||
return buildSupportedRegionSnapshot();
|
||||
}
|
||||
|
||||
PX6AXGen3::ResultantForce PX6AXGen3::getResultantForce(FingerType finger, TactileRegion region) {
|
||||
if (!isSupportedRegion(finger, region)) {
|
||||
throw std::invalid_argument("PX6AXGen3 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("PX6AXGen3 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]
|
||||
};
|
||||
}
|
||||
|
||||
PX6AXGen3::ForceNewtons PX6AXGen3::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 PX6AXGen3::initializeSnapshot() {
|
||||
@ -689,14 +542,6 @@ void PX6AXGen3::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();
|
||||
@ -723,7 +568,7 @@ void PX6AXGen3::ensureSensorReady(const bool allow_background,
|
||||
const bool require_resultant) {
|
||||
const auto lifecycle = state();
|
||||
if (!config_valid_ || lifecycle == Status::STOPPED || lifecycle == Status::FAULT) {
|
||||
throw std::runtime_error("PX6AXGen3 is not operational: " + lastError());
|
||||
throw std::runtime_error("PX6AXGen3 is not operational.");
|
||||
}
|
||||
const auto [polls_tactile, polls_resultant] = resolvePollingReadSelection();
|
||||
const bool background_covers_request =
|
||||
@ -738,10 +583,6 @@ void PX6AXGen3::ensureSensorReady(const bool allow_background,
|
||||
refreshSensorData(require_tactile, require_resultant);
|
||||
}
|
||||
|
||||
bool PX6AXGen3::isSupportedRegion(const FingerType finger, const TactileRegion region) const {
|
||||
return finger == tactile_finger_ && region == tactile_region_;
|
||||
}
|
||||
|
||||
bool PX6AXGen3::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 &&
|
||||
@ -755,29 +596,6 @@ bool PX6AXGen3::isSampleFresh(const std::chrono::steady_clock::time_point reques
|
||||
std::chrono::steady_clock::now() - request_time <= max_sample_age_;
|
||||
}
|
||||
|
||||
TactileRegionData PX6AXGen3::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("PX6AXGen3 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> PX6AXGen3::resolvePollingReadSelection() const {
|
||||
switch (polling_read_mode_) {
|
||||
case PollingReadMode::DISTRIBUTED_FORCE:
|
||||
@ -79,8 +79,8 @@ void usage() {
|
||||
" [--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"
|
||||
"stream: exercise background polling and cached reads used by the task;\n"
|
||||
" read counts include repeated samples, not sensor update frequency.\n"
|
||||
"Only reads the sensor. No calibration or robot commands. Ctrl-C stops.\n";
|
||||
}
|
||||
|
||||
@ -152,17 +152,11 @@ int main(int argc, char** argv) {
|
||||
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;
|
||||
}
|
||||
cmvr::device::ForceSample sample;
|
||||
const bool valid = sensor.readForce(sample);
|
||||
const auto& force = sample.force;
|
||||
const std::string error = valid ? std::string{} : sensor.lastError();
|
||||
if (!valid) ++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();
|
||||
35
cmvr-es/devices/touch/px_6ax_gen3/src/px_6ax_gen3_test.cpp
Normal file
35
cmvr-es/devices/touch/px_6ax_gen3/src/px_6ax_gen3_test.cpp
Normal file
@ -0,0 +1,35 @@
|
||||
#include "../include/px_6ax_gen3.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
TEST(PX6AXGen3, PrintResultantForce) {
|
||||
cmvr::config::PX6AXGen3 config;
|
||||
config.set_serial_port("/dev/ttyACM1");
|
||||
config.set_module_id(2);
|
||||
config.set_baud_rate(921600);
|
||||
config.set_distributed_length(153);
|
||||
config.set_polling_read_mode(cmvr::config::PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE);
|
||||
config.set_auto_calibrate(false);
|
||||
|
||||
cmvr::device::PX6AXGen3 sensor(config);
|
||||
if (!sensor.init()) {
|
||||
throw std::runtime_error(sensor.lastError());
|
||||
}
|
||||
|
||||
for (int i = 0; i < 300; ++i) {
|
||||
cmvr::device::ForceSample sample;
|
||||
if (sensor.readForce(sample)) {
|
||||
const auto& force = sample.force;
|
||||
std::cout << "Fx=" << force.fx << " N, Fy=" << force.fy
|
||||
<< " N, Fz=" << force.fz
|
||||
<< " N, |F|=" << force.magnitude() << " N" << std::endl;
|
||||
} else {
|
||||
std::cerr << "Read force failed: " << sensor.lastError() << std::endl;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{100});
|
||||
}
|
||||
}
|
||||
18
cmvr-es/devices/touch/px_6ax_genx_can/CMakeLists.txt
Normal file
18
cmvr-es/devices/touch/px_6ax_genx_can/CMakeLists.txt
Normal file
@ -0,0 +1,18 @@
|
||||
add_library(px_6ax_genx_can SHARED src/px_6ax_genx_can.cpp)
|
||||
|
||||
target_include_directories(px_6ax_genx_can PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
add_library(cmvr_es::device::px_6ax_genx_can ALIAS px_6ax_genx_can)
|
||||
|
||||
target_link_libraries(px_6ax_genx_can PRIVATE
|
||||
cmvr_es::device::canbus
|
||||
cmvr_es::proto
|
||||
cmvr_es::logging
|
||||
glog
|
||||
pthread
|
||||
)
|
||||
|
||||
install(TARGETS px_6ax_genx_can LIBRARY DESTINATION lib)
|
||||
|
||||
add_executable(px_6ax_genx_can_test src/px_6ax_genx_can_test.cpp)
|
||||
target_link_libraries(px_6ax_genx_can_test PRIVATE
|
||||
px_6ax_genx_can cmvr_es::proto cmvr_es::logging gtest gtest_main pthread)
|
||||
71
cmvr-es/devices/touch/px_6ax_genx_can/README.md
Normal file
71
cmvr-es/devices/touch/px_6ax_genx_can/README.md
Normal file
@ -0,0 +1,71 @@
|
||||
# PX-6AX GENX CAN 触觉驱动
|
||||
|
||||
`PX6AXGenXCan` 继承 `AbstractTouch`,通过独立的 SocketCAN 客户端接收 STM32 合力报文,库目标为 `px_6ax_genx_can`。系统需提前将对应 `canN` 接口配置为 1 Mbps 并启动;驱动不修改接口速率。
|
||||
|
||||
## 配置与协议
|
||||
|
||||
`devices/touch/touch.pb.txt` 中的 `paxini_tip_1` 默认使用 CAN:
|
||||
|
||||
```protobuf
|
||||
px_6ax_genx_can {
|
||||
channel_id: 0
|
||||
force_can_id: 0x600
|
||||
max_sample_age_ms: 300
|
||||
}
|
||||
```
|
||||
|
||||
协议采用 11 位标准 ID 的经典 CAN 数据帧,默认 ID 为 `0x600`、DLC=8,排除扩展帧、远程帧、错误帧和 CAN FD 帧。单片机主动上报,无需发送读取命令。载荷布局如下:
|
||||
|
||||
| 字节偏移 | 字段 | 编码 |
|
||||
|---|---|---|
|
||||
| 0 | SEQ | `uint8` 包序号 |
|
||||
| 1–2 | Fx | 小端 `int16`,单位 mN |
|
||||
| 3–4 | Fy | 小端 `int16`,单位 mN |
|
||||
| 5–6 | Fz | 小端 `int16`,单位 mN |
|
||||
| 7 | CRC8 | 对字节 0–6(含序号)计算 |
|
||||
|
||||
三轴均按有符号 16 位补码解析,再除以 `1000.0` 得到 N;即使当前传感器的 Fz 非负,也按 `int16` 解析。协议单位为 1 mN;当前 GEN3 固件的有效值以 100 mN 为步长,传感器分辨率仍为 0.1 N。
|
||||
|
||||
CRC 初值为 `0xFF`,无最终异或,沿用 PX6AX 厂商查表算法。下列实现与固件等价;每处理一个字节都取中间结果的高 8 位,不能对整帧计算标准 CRC16 后再截取,也不能使用旧的多项式 `0x07` 算法:
|
||||
|
||||
```python
|
||||
def crc8_px6ax(data):
|
||||
crc = 0xFF
|
||||
for byte in data:
|
||||
word = crc ^ byte
|
||||
for _ in range(8):
|
||||
word = (word >> 1) ^ (0xA001 if word & 1 else 0)
|
||||
crc = (word >> 8) & 0xFF
|
||||
return crc
|
||||
|
||||
# 验收条件:crc8_px6ax(data[:7]) == data[7]
|
||||
```
|
||||
|
||||
以下均为 ID `0x600`、DLC=8 的完整载荷:
|
||||
|
||||
| 数据区(十六进制) | SEQ | Fx(N) | Fy(N) | Fz(N) |
|
||||
|---|---:|---:|---:|---:|
|
||||
| `00 B0 04 D4 FE C4 09 81` | 0 | 1.2 | -0.3 | 2.5 |
|
||||
| `00 00 00 00 00 00 00 54` | 0 | 0.0 | 0.0 | 0.0 |
|
||||
| `01 00 00 00 00 00 00 57` | 1 | 0.0 | 0.0 | 0.0 |
|
||||
|
||||
STM32 以 2 ms 为目标周期进行 SPI 读取,读取和传感器 CRC 校验通过后交给 CAN 发送线程,发送线程没有额外的定时等待。正常发送节奏可接近 500 帧/s,但受读取耗时、调度、队列和总线仲裁影响,不保证严格周期,也不表示每次读取都是新的传感器内部测量。发送端不缓存全部历史样本;处理不及时或硬件 FIFO 满时,样本可能被覆盖或跳过。相同力值可以连续上报,接收端不按力值去重。
|
||||
|
||||
SEQ 记录成功提交到 CAN 硬件发送队列的次数:启动后第一笔使用 0,每次成功入队后加 1,255 后回到 0,重启后重新从 0 开始。SPI 读取失败、传感器 CRC 错误、样本被覆盖、FIFO 满或入队失败都不递增序号。它不是传感器采样次数或总线 ACK 成功次数;当前固件关闭 CAN 自动重发,成功入队也不保证送达。期望下一序号为 `(last_seq + 1) & 0xFF`,可用于跳号诊断,但不能仅靠序号推算全部漏采样或丢帧。
|
||||
|
||||
接收线程丢弃错误 ID、类型、长度或 CRC 的报文,接受任意通过校验的包序号,包括 0、连续重复序号、跳号和 255→0 回绕;重复序号可能来自复位或整圈回绕,不作为拒收条件。每个有效报文都会更新缓存及接收时间。`readForce()` 只读取缓存,超过配置的 `max_sample_age_ms`(默认 300 ms)未收到有效报文时返回 false;后续有效报文可恢复读取。载荷不含时间戳、传感器状态或数据有效标志;`sample_time` 是主机本地接收时间,不是精确的传感器采样时间,读取缓存不会刷新它。
|
||||
|
||||
使用顺序为 `init()` → `start()` → `readForce()`。`stop()` 停止接收并清空缓存,接收采用最长 50 ms 的阻塞等待,有报文到达即可返回;50 ms 不是采样周期或发送周期。单纯接收等待超时会继续接收;底层接收错误则进入 FAULT 并退出接收线程,需要显式 `init()` → `start()` 恢复。该协议只包含合力,`readTactile()` 返回 false;当前 gRPC `GetSensorData` 是阵列接口,无法提供这条合力报文的数据。
|
||||
|
||||
## 简单合力打印测试
|
||||
|
||||
`src/px_6ax_genx_can_test.cpp` 只包含一个 CAN 实机测试 `PX6AXGenXCan.PrintResultantForce`,没有断言或模拟串口。使用文件中的 `channel_id=0`(can0)、`force_can_id=0x600`、300 ms 有效期初始化并启动驱动,打印 `Fx/Fy/Fz` 和合力大小,单位为 N。当前代码共读取 3,000,000 次,每次读取后等待 10 ms;读取失败时打印错误。打印循环读取的是最新缓存,不保证打印每一帧,也不决定传感器采读或 CAN 发送周期。
|
||||
|
||||
先确保 `can0` 已配置为 1 Mbps 且处于 UP 状态,再在仓库根目录构建、安装并运行。CAN 通道和报文 ID 可直接在测试文件中修改:
|
||||
|
||||
```bash
|
||||
./scripts/build.sh Debug
|
||||
export LD_LIBRARY_PATH="$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
||||
./build/Debug/cmvr-es/devices/touch/px_6ax_genx_can/px_6ax_genx_can_test \
|
||||
--gtest_filter=PX6AXGenXCan.PrintResultantForce
|
||||
```
|
||||
@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
#include "cmvr/config/touch_config/touch_config.pb.h"
|
||||
#include "devices/touch/abstract_touch.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class SocketCanClientRaw;
|
||||
|
||||
class PX6AXGenXCan final : public AbstractTouch {
|
||||
public:
|
||||
explicit PX6AXGenXCan(const config::PX6AXGenXCan& config);
|
||||
~PX6AXGenXCan() override;
|
||||
|
||||
std::string typeName() const override { return "PX6AXGenXCan"; }
|
||||
bool init() override;
|
||||
bool start() override;
|
||||
bool stop() override;
|
||||
Status state() const override;
|
||||
std::string lastError() const override;
|
||||
bool readForce(ForceSample& sample) override;
|
||||
bool readTactile(TactileSample& sample) override;
|
||||
|
||||
private:
|
||||
void receiveLoop_();
|
||||
void setFault_(const std::string& error);
|
||||
|
||||
config::PX6AXGenXCan config_;
|
||||
std::uint32_t force_can_id_{0x600};
|
||||
std::chrono::milliseconds max_sample_age_{300};
|
||||
std::unique_ptr<SocketCanClientRaw> can_;
|
||||
std::mutex lifecycle_mutex_;
|
||||
std::atomic<bool> running_{false};
|
||||
std::thread receiver_;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
Status status_{Status::CREATED};
|
||||
std::string last_error_;
|
||||
ForceSample latest_sample_;
|
||||
// Last accepted CAN transmission sequence, not a sensor sample counter.
|
||||
std::uint8_t last_sequence_{0};
|
||||
bool have_sequence_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
196
cmvr-es/devices/touch/px_6ax_genx_can/src/px_6ax_genx_can.cpp
Normal file
196
cmvr-es/devices/touch/px_6ax_genx_can/src/px_6ax_genx_can.cpp
Normal file
@ -0,0 +1,196 @@
|
||||
#include "../include/px_6ax_genx_can.h"
|
||||
|
||||
#include <exception>
|
||||
#include <vector>
|
||||
|
||||
#include "canbus/can_client/socket/socket_can_client_raw.h"
|
||||
#include "common/base/logging/logger.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
|
||||
std::uint8_t crc8Px6ax(const std::uint8_t* data) {
|
||||
std::uint8_t crc = 0xFF;
|
||||
for (int i = 0; i < 7; ++i) {
|
||||
std::uint16_t word = crc ^ data[i];
|
||||
for (int bit = 0; bit < 8; ++bit) {
|
||||
word = static_cast<std::uint16_t>((word >> 1) ^ ((word & 1) ? 0xA001 : 0));
|
||||
}
|
||||
// The vendor CRC keeps the high byte after EACH input byte.
|
||||
crc = static_cast<std::uint8_t>(word >> 8);
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
std::uint16_t readUnsigned16(const std::uint8_t* data) {
|
||||
return static_cast<std::uint16_t>(data[0]) |
|
||||
(static_cast<std::uint16_t>(data[1]) << 8);
|
||||
}
|
||||
|
||||
int readSigned16(const std::uint8_t* data) {
|
||||
const auto value = readUnsigned16(data);
|
||||
return value >= 0x8000 ? static_cast<int>(value) - 0x10000 : value;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
PX6AXGenXCan::PX6AXGenXCan(const config::PX6AXGenXCan& config) : config_(config) {
|
||||
id_ = config.id();
|
||||
if (config.has_force_can_id()) force_can_id_ = config.force_can_id();
|
||||
if (config.max_sample_age_ms() > 0) {
|
||||
max_sample_age_ = std::chrono::milliseconds{config.max_sample_age_ms()};
|
||||
}
|
||||
}
|
||||
|
||||
PX6AXGenXCan::~PX6AXGenXCan() {
|
||||
stop();
|
||||
}
|
||||
|
||||
bool PX6AXGenXCan::init() {
|
||||
std::lock_guard<std::mutex> lifecycle_lock(lifecycle_mutex_);
|
||||
if (running_) return true;
|
||||
if (receiver_.joinable()) receiver_.join();
|
||||
if (can_) can_->stop();
|
||||
if (config_.channel_id() < 0 || force_can_id_ > 0x7FF || config_.max_sample_age_ms() < 0) {
|
||||
setFault_("Invalid CAN channel, standard frame ID or sample timeout.");
|
||||
return false;
|
||||
}
|
||||
|
||||
config::SocketCanConfig can_config;
|
||||
can_config.set_channel_id(config_.channel_id());
|
||||
can_ = std::make_unique<SocketCanClientRaw>(can_config);
|
||||
if (!can_->init()) {
|
||||
setFault_("Failed to initialize touch CAN client.");
|
||||
return false;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
latest_sample_ = {};
|
||||
have_sequence_ = false;
|
||||
last_error_.clear();
|
||||
status_ = Status::INITIALIZED;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PX6AXGenXCan::start() {
|
||||
std::lock_guard<std::mutex> lifecycle_lock(lifecycle_mutex_);
|
||||
if (running_) return true;
|
||||
if (receiver_.joinable()) receiver_.join();
|
||||
if (!can_ || state() == Status::FAULT) {
|
||||
setFault_("Initialize the touch CAN device before starting it.");
|
||||
return false;
|
||||
}
|
||||
if (!can_->start()) {
|
||||
setFault_("Failed to open can" + std::to_string(config_.channel_id()) +
|
||||
"; check the interface and its 1 Mbps bitrate.");
|
||||
return false;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
latest_sample_ = {};
|
||||
have_sequence_ = false;
|
||||
last_error_.clear();
|
||||
status_ = Status::STREAMING;
|
||||
}
|
||||
running_ = true;
|
||||
try {
|
||||
receiver_ = std::thread(&PX6AXGenXCan::receiveLoop_, this);
|
||||
} catch (const std::exception& e) {
|
||||
running_ = false;
|
||||
can_->stop();
|
||||
setFault_(e.what());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PX6AXGenXCan::stop() {
|
||||
std::lock_guard<std::mutex> lifecycle_lock(lifecycle_mutex_);
|
||||
running_ = false;
|
||||
if (receiver_.joinable()) receiver_.join();
|
||||
const bool stopped = !can_ || can_->stop();
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
latest_sample_ = {};
|
||||
have_sequence_ = false;
|
||||
status_ = Status::STOPPED;
|
||||
return stopped;
|
||||
}
|
||||
|
||||
PX6AXGenXCan::Status PX6AXGenXCan::state() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return status_;
|
||||
}
|
||||
|
||||
std::string PX6AXGenXCan::lastError() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return last_error_;
|
||||
}
|
||||
|
||||
void PX6AXGenXCan::setFault_(const std::string& error) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
latest_sample_ = {};
|
||||
status_ = Status::FAULT;
|
||||
last_error_ = error;
|
||||
}
|
||||
|
||||
bool PX6AXGenXCan::readForce(ForceSample& sample) {
|
||||
sample = {};
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (status_ != Status::STREAMING) {
|
||||
if (status_ != Status::FAULT) last_error_ = "Touch CAN receiver is not running.";
|
||||
return false;
|
||||
}
|
||||
if (!have_sequence_) {
|
||||
last_error_ = "No valid touch force frame received yet.";
|
||||
return false;
|
||||
}
|
||||
if (std::chrono::steady_clock::now() - latest_sample_.sample_time > max_sample_age_) {
|
||||
last_error_ = "Touch CAN force sample timed out.";
|
||||
return false;
|
||||
}
|
||||
sample = latest_sample_;
|
||||
last_error_.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PX6AXGenXCan::readTactile(TactileSample& sample) {
|
||||
sample = {};
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
last_error_ = "STM32 CAN protocol provides resultant force only; no tactile array.";
|
||||
return false;
|
||||
}
|
||||
|
||||
void PX6AXGenXCan::receiveLoop_() {
|
||||
while (running_) {
|
||||
std::vector<CanFrame> frames;
|
||||
std::int32_t count = 1;
|
||||
const auto result = can_->receive(&frames, &count, std::chrono::milliseconds{50});
|
||||
if (!running_) break;
|
||||
if (result != msgs::ErrorCode::OK) {
|
||||
setFault_("Touch CAN receive failed.");
|
||||
running_ = false;
|
||||
break;
|
||||
}
|
||||
for (const auto& frame : frames) {
|
||||
if (frame.is_extended || frame.is_remote || frame.is_error ||
|
||||
frame.id != force_can_id_ || frame.len != 8 || crc8Px6ax(frame.data) != frame.data[7]) {
|
||||
continue;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
// Reset, loss or a full wrap can change the expected sequence; accept the frame.
|
||||
if (have_sequence_ && frame.data[0] != static_cast<std::uint8_t>(last_sequence_ + 1)) {
|
||||
CMVR_LOG(DEBUG) << "[PX6AXGenXCan] CAN sequence discontinuity: previous="
|
||||
<< static_cast<unsigned>(last_sequence_)
|
||||
<< ", received=" << static_cast<unsigned>(frame.data[0]);
|
||||
}
|
||||
latest_sample_.force = {readSigned16(frame.data + 1) / 1000.0,
|
||||
readSigned16(frame.data + 3) / 1000.0,
|
||||
readSigned16(frame.data + 5) / 1000.0};
|
||||
latest_sample_.sample_time = std::chrono::steady_clock::now();
|
||||
last_sequence_ = frame.data[0];
|
||||
have_sequence_ = true;
|
||||
last_error_.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -0,0 +1,32 @@
|
||||
#include "../include/px_6ax_genx_can.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
TEST(PX6AXGenXCan, PrintResultantForce) {
|
||||
cmvr::config::PX6AXGenXCan config;
|
||||
config.set_channel_id(0);
|
||||
config.set_force_can_id(0x600);
|
||||
config.set_max_sample_age_ms(300);
|
||||
|
||||
cmvr::device::PX6AXGenXCan sensor(config);
|
||||
if (!sensor.init() || !sensor.start()) {
|
||||
throw std::runtime_error(sensor.lastError());
|
||||
}
|
||||
|
||||
for (int i = 0; i < 3000000; ++i) {
|
||||
cmvr::device::ForceSample sample;
|
||||
if (sensor.readForce(sample)) {
|
||||
const auto& force = sample.force;
|
||||
std::cout << "Fx=" << force.fx << " N, Fy=" << force.fy
|
||||
<< " N, Fz=" << force.fz
|
||||
<< " N, |F|=" << force.magnitude() << " N" << std::endl;
|
||||
} else {
|
||||
std::cerr << "Read force failed: " << sensor.lastError() << std::endl;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{10});
|
||||
}
|
||||
}
|
||||
47
cmvr-es/devices/touch/touch_factory.h
Normal file
47
cmvr-es/devices/touch/touch_factory.h
Normal file
@ -0,0 +1,47 @@
|
||||
#ifndef CMVR_ES_TOUCH_FACTORY_H
|
||||
#define CMVR_ES_TOUCH_FACTORY_H
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "cmvr/config/touch_config/touch_config.pb.h"
|
||||
#include "devices/touch/px_6ax_gen3/include/px_6ax_gen3.h"
|
||||
#include "devices/touch/px_6ax_genx_can/include/px_6ax_genx_can.h"
|
||||
#include "devices/touch/zero_sim_touch/include/zero_sim_touch.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class TouchFactory {
|
||||
public:
|
||||
static std::shared_ptr<AbstractTouch> create(const config::TouchDeviceConfig& cfg) {
|
||||
if (cfg.id().empty()) {
|
||||
CMVR_LOG(ERROR) << "[TouchFactory] Touch id is empty";
|
||||
return nullptr;
|
||||
}
|
||||
switch (cfg.backend_case()) {
|
||||
case config::TouchDeviceConfig::kPx6AxGen3:
|
||||
return createBackend_<PX6AXGen3>(cfg.id(), cfg.px_6ax_gen3());
|
||||
case config::TouchDeviceConfig::kZeroSim:
|
||||
return createBackend_<ZeroSimTouch>(cfg.id(), cfg.zero_sim());
|
||||
case config::TouchDeviceConfig::kPx6AxGenxCan:
|
||||
return createBackend_<PX6AXGenXCan>(cfg.id(), cfg.px_6ax_genx_can());
|
||||
default:
|
||||
CMVR_LOG(ERROR) << "[TouchFactory] Touch backend is not configured: " << cfg.id();
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Device, typename Config>
|
||||
static std::shared_ptr<AbstractTouch> createBackend_(const std::string& id, Config cfg) {
|
||||
if (!cfg.id().empty() && cfg.id() != id) {
|
||||
CMVR_LOG(ERROR) << "[TouchFactory] Touch id does not match backend id: " << id;
|
||||
return nullptr;
|
||||
}
|
||||
cfg.set_id(id);
|
||||
return std::make_shared<Device>(cfg);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_TOUCH_FACTORY_H
|
||||
69
cmvr-es/devices/touch/touch_types.h
Normal file
69
cmvr-es/devices/touch/touch_types.h
Normal file
@ -0,0 +1,69 @@
|
||||
#ifndef CMVR_ES_TOUCH_TYPES_H
|
||||
#define CMVR_ES_TOUCH_TYPES_H
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
// Raw device counts. Their scale is defined by each sensor's protocol.
|
||||
struct TactilePoint {
|
||||
std::int32_t fx{0};
|
||||
std::int32_t fy{0};
|
||||
std::int32_t fz{0};
|
||||
|
||||
static TactilePoint fromFz(std::int32_t value) { return {0, 0, value}; }
|
||||
double magnitude() const {
|
||||
return std::hypot(static_cast<double>(fx), static_cast<double>(fy),
|
||||
static_cast<double>(fz));
|
||||
}
|
||||
bool isZero() const { return fx == 0 && fy == 0 && fz == 0; }
|
||||
};
|
||||
|
||||
struct ForceNewtons {
|
||||
double fx{0.0};
|
||||
double fy{0.0};
|
||||
double fz{0.0};
|
||||
double magnitude() const { return std::hypot(fx, fy, fz); }
|
||||
};
|
||||
|
||||
struct TactileMatrixView {
|
||||
const TactilePoint* data{nullptr};
|
||||
int rows{0};
|
||||
int cols{0};
|
||||
|
||||
bool valid() const { return data != nullptr && rows > 0 && cols > 0; }
|
||||
int pointCount() const { return rows * cols; }
|
||||
const TactilePoint* rowData(int row) const { return data + row * cols; }
|
||||
TactilePoint at(int row, int col) const { return data[row * cols + col]; }
|
||||
};
|
||||
|
||||
struct ForceSample {
|
||||
ForceNewtons force;
|
||||
// Host monotonic time when a serial request was sent or a valid CAN frame
|
||||
// was received; not the sensor's sampling time or the getter's time.
|
||||
std::chrono::steady_clock::time_point sample_time{};
|
||||
};
|
||||
|
||||
struct TactileSample {
|
||||
std::vector<TactilePoint> points;
|
||||
int rows{0};
|
||||
int cols{0};
|
||||
std::string name;
|
||||
// Host monotonic time when a serial request was sent or a valid CAN frame
|
||||
// was received; not the sensor's sampling time or the getter's time.
|
||||
std::chrono::steady_clock::time_point sample_time{};
|
||||
|
||||
bool valid() const {
|
||||
return rows > 0 && cols > 0 &&
|
||||
points.size() == static_cast<std::size_t>(rows) * static_cast<std::size_t>(cols) &&
|
||||
sample_time != std::chrono::steady_clock::time_point{};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_TOUCH_TYPES_H
|
||||
13
cmvr-es/devices/touch/zero_sim_touch/CMakeLists.txt
Normal file
13
cmvr-es/devices/touch/zero_sim_touch/CMakeLists.txt
Normal file
@ -0,0 +1,13 @@
|
||||
add_library(zero_sim_touch SHARED src/zero_sim_touch.cpp)
|
||||
|
||||
target_include_directories(zero_sim_touch PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
add_library(cmvr_es::device::zero_sim_touch ALIAS zero_sim_touch)
|
||||
|
||||
target_link_libraries(zero_sim_touch
|
||||
PRIVATE
|
||||
cmvr_es::proto
|
||||
glog
|
||||
)
|
||||
|
||||
install(TARGETS zero_sim_touch LIBRARY DESTINATION lib)
|
||||
@ -0,0 +1,32 @@
|
||||
#ifndef CMVR_ES_ZERO_SIM_TOUCH_H
|
||||
#define CMVR_ES_ZERO_SIM_TOUCH_H
|
||||
|
||||
#include <mutex>
|
||||
|
||||
#include "cmvr/config/touch_config/touch_config.pb.h"
|
||||
#include "devices/touch/abstract_touch.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class ZeroSimTouch final : public AbstractTouch {
|
||||
public:
|
||||
explicit ZeroSimTouch(const config::ZeroSimTouch& cfg);
|
||||
|
||||
std::string typeName() const override { return "ZeroSimTouch"; }
|
||||
bool init() override;
|
||||
bool start() override;
|
||||
bool stop() override;
|
||||
Status state() const override;
|
||||
std::string lastError() const override;
|
||||
bool readForce(ForceSample& sample) override;
|
||||
bool readTactile(TactileSample& sample) override;
|
||||
|
||||
private:
|
||||
bool ready_() const;
|
||||
mutable std::mutex mutex_;
|
||||
Status lifecycle_state_{Status::CREATED};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_ZERO_SIM_TOUCH_H
|
||||
61
cmvr-es/devices/touch/zero_sim_touch/src/zero_sim_touch.cpp
Normal file
61
cmvr-es/devices/touch/zero_sim_touch/src/zero_sim_touch.cpp
Normal file
@ -0,0 +1,61 @@
|
||||
#include "../include/zero_sim_touch.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
ZeroSimTouch::ZeroSimTouch(const config::ZeroSimTouch& cfg) {
|
||||
id_ = cfg.id();
|
||||
}
|
||||
|
||||
bool ZeroSimTouch::init() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
lifecycle_state_ = Status::INITIALIZED;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ZeroSimTouch::start() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
lifecycle_state_ = Status::STREAMING;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ZeroSimTouch::stop() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
lifecycle_state_ = Status::STOPPED;
|
||||
return true;
|
||||
}
|
||||
|
||||
ZeroSimTouch::Status ZeroSimTouch::state() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return lifecycle_state_;
|
||||
}
|
||||
|
||||
bool ZeroSimTouch::ready_() const {
|
||||
return lifecycle_state_ == Status::INITIALIZED || lifecycle_state_ == Status::STREAMING;
|
||||
}
|
||||
|
||||
std::string ZeroSimTouch::lastError() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return ready_() ? "" : "ZeroSimTouch is not initialized or has stopped.";
|
||||
}
|
||||
|
||||
bool ZeroSimTouch::readForce(ForceSample& sample) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
sample = {};
|
||||
if (!ready_()) return false;
|
||||
sample.sample_time = std::chrono::steady_clock::now();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ZeroSimTouch::readTactile(TactileSample& sample) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
sample = {};
|
||||
if (!ready_()) return false;
|
||||
sample.points.resize(1);
|
||||
sample.rows = 1;
|
||||
sample.cols = 1;
|
||||
sample.name = "mujoco_touch_tip";
|
||||
sample.sample_time = std::chrono::steady_clock::now();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -12,6 +12,7 @@ target_link_libraries(device_manager PRIVATE
|
||||
cmvr_es::device::speaker
|
||||
cmvr_es::device::microphone
|
||||
cmvr_es::device::dexhand
|
||||
cmvr_es::device::touch
|
||||
cmvr::device::head_esp32
|
||||
cmvr_es::device::motor_manager
|
||||
cmvr_es::device::arm
|
||||
|
||||
@ -9,6 +9,7 @@
|
||||
#include "devices/arm/robot_arm_factory.h"
|
||||
#include "devices/camera/camera_factory.h"
|
||||
#include "devices/dexhand/dexhand_factory.h"
|
||||
#include "devices/touch/touch_factory.h"
|
||||
#include "devices/microphone/microphone_factory.h"
|
||||
#include "devices/motor/manager/include/motor_manager.h"
|
||||
#include "devices/speaker/speaker_factory.h"
|
||||
@ -19,6 +20,7 @@
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
#include "cmvr/config/camera_config/camera_config.pb.h"
|
||||
#include "cmvr/config/dexhand_config/dexhand_config.pb.h"
|
||||
#include "cmvr/config/touch_config/touch_config.pb.h"
|
||||
#include "cmvr/config/microphone_config/microphone_config.pb.h"
|
||||
#include "cmvr/config/motor_config/motor_config.pb.h"
|
||||
#include "cmvr/config/mujoco_config/mujoco_world_config.pb.h"
|
||||
@ -205,6 +207,16 @@ DeviceFactory::DeviceFactory()
|
||||
[](const auto& cfg) { return DexHandFactory::create(cfg); });
|
||||
});
|
||||
|
||||
registerCreator(config::DeviceConfigEntry::DEVICE_TYPE_TOUCH,
|
||||
[](const auto& entry) {
|
||||
return createFactoryRecordFromCollection<config::TouchRootConfig>(
|
||||
entry,
|
||||
[](const auto& root) -> decltype(auto) {
|
||||
return (root.touch().touches());
|
||||
},
|
||||
[](const auto& cfg) { return TouchFactory::create(cfg); });
|
||||
});
|
||||
|
||||
registerCreator(config::DeviceConfigEntry::DEVICE_TYPE_MICROPHONE,
|
||||
[](const auto& entry) {
|
||||
return createFactoryRecordFromCollection<config::MicroPhoneRootConfig>(
|
||||
|
||||
@ -14,6 +14,7 @@
|
||||
#include "devices/camera/abstract_camera.h"
|
||||
#include "devices/camera/mujoco_camera/include/mujoco_camera.h"
|
||||
#include "devices/dexhand/abstract_dexhand.h"
|
||||
#include "devices/touch/abstract_touch.h"
|
||||
#include "devices/gripper/abstract_gripper.h"
|
||||
#include "devices/microphone/abstract_microphone.h"
|
||||
#include "devices/motor/manager/include/motor_manager.h"
|
||||
@ -44,6 +45,8 @@ const char* deviceTypeToString(const cmvr::config::DeviceConfigEntry::DeviceType
|
||||
return "DEVICE_TYPE_CAMERA";
|
||||
case cmvr::config::DeviceConfigEntry::DEVICE_TYPE_DEXHAND:
|
||||
return "DEVICE_TYPE_DEXHAND";
|
||||
case cmvr::config::DeviceConfigEntry::DEVICE_TYPE_TOUCH:
|
||||
return "DEVICE_TYPE_TOUCH";
|
||||
case cmvr::config::DeviceConfigEntry::DEVICE_TYPE_MICROPHONE:
|
||||
return "DEVICE_TYPE_MICROPHONE";
|
||||
case cmvr::config::DeviceConfigEntry::DEVICE_TYPE_SPEAKER:
|
||||
@ -62,11 +65,13 @@ const char* deviceTypeToString(const cmvr::config::DeviceConfigEntry::DeviceType
|
||||
|
||||
} // namespace
|
||||
|
||||
template std::shared_ptr<AbstractDevice> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<AbstractAGV> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<RobotArm> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<AbstractBattery> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<AbstractCamera> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<AbstractDexHand> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<AbstractTouch> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<AbstractGripper> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<AbstractMicrophone> DeviceManager::getDevice(const std::string& device_id);
|
||||
template std::shared_ptr<AbstractSpeaker> DeviceManager::getDevice(const std::string& device_id);
|
||||
|
||||
@ -8,10 +8,12 @@
|
||||
#include <cmath>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "devices/dexhand/rh56dftp_dexhand/include/rh56dftp_dexhand.h"
|
||||
#include "devices/touch/abstract_touch.h"
|
||||
#include "service/grpc/action/include/control_command_arbiter.h"
|
||||
#include "service/grpc/action/include/control_command_guard.h"
|
||||
|
||||
@ -80,14 +82,49 @@ void fillSensorData(const AbstractDexHand::TactileRegionData& tactile_data,
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ResponseT>
|
||||
void appendSensorData(const std::vector<AbstractDexHand::TactileRegionData>& tactile_regions,
|
||||
ResponseT* response) {
|
||||
for (const auto& tactile_region : tactile_regions) {
|
||||
if (!tactile_region.valid()) {
|
||||
continue;
|
||||
void fillSensorData(const TactileSample& sample, cmvr::api::SensorData* sensor_data) {
|
||||
sensor_data->set_rows(sample.rows);
|
||||
sensor_data->set_cols(sample.cols);
|
||||
sensor_data->set_finger_type(cmvr::api::SensorData::FINGER_UNSPECIFIED);
|
||||
sensor_data->set_part_type(cmvr::api::SensorData::PART_UNSPECIFIED);
|
||||
sensor_data->set_sensor_name(sample.name);
|
||||
|
||||
for (int row = 0; row < sample.rows; ++row) {
|
||||
auto* row_data = sensor_data->add_data();
|
||||
for (int col = 0; col < sample.cols; ++col) {
|
||||
// Preserve the existing scalar wire format for standalone sensors.
|
||||
row_data->add_values(sample.points[static_cast<size_t>(row) * sample.cols + col].fz);
|
||||
}
|
||||
fillSensorData(tactile_region, response->add_sensor());
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ResponseT>
|
||||
void appendSensorData(const std::shared_ptr<AbstractDevice>& device, ResponseT* response) {
|
||||
if (const auto touch = std::dynamic_pointer_cast<AbstractTouch>(device)) {
|
||||
TactileSample sample;
|
||||
if (!touch->readTactile(sample) || !sample.valid()) {
|
||||
const auto error = touch->lastError();
|
||||
throw std::runtime_error(error.empty() ? "Tactile sample is unavailable: " + device->id() : error);
|
||||
}
|
||||
fillSensorData(sample, response->add_sensor());
|
||||
return;
|
||||
}
|
||||
|
||||
const auto dexhand = std::dynamic_pointer_cast<AbstractDexHand>(device);
|
||||
if (!dexhand) {
|
||||
throw std::runtime_error("Device does not provide tactile data: " + device->id());
|
||||
}
|
||||
const auto regions = dexhand->getSensorData();
|
||||
if (regions.empty()) {
|
||||
throw std::runtime_error("Tactile data is unavailable: " + device->id());
|
||||
}
|
||||
for (const auto& region : regions) {
|
||||
if (!region.valid()) {
|
||||
throw std::runtime_error("Tactile region is unavailable: " + device->id());
|
||||
}
|
||||
}
|
||||
for (const auto& region : regions) {
|
||||
fillSensorData(region, response->add_sensor());
|
||||
}
|
||||
}
|
||||
|
||||
@ -173,7 +210,7 @@ std::vector<AbstractDexHand::TactileRegionKey> buildRh56AllTactileRegions() {
|
||||
};
|
||||
}
|
||||
|
||||
void maybeConfigureRh56FullTactilePolling(const std::shared_ptr<AbstractDexHand>& dev) {
|
||||
void maybeConfigureRh56FullTactilePolling(const std::shared_ptr<AbstractDevice>& dev) {
|
||||
auto rh56 = std::dynamic_pointer_cast<RH56DFTPDexhand>(dev);
|
||||
if (!rh56) {
|
||||
return;
|
||||
@ -428,12 +465,12 @@ grpc::Status gRPCDexHandServiceImpl::GetSensorData(grpc::ServerContext* context
|
||||
try {
|
||||
string dev_id = request->header().device_id();
|
||||
CMVR_LOG(INFO) << "[gRPCDexHandServiceImpl] (GetSensorData): id=" << dev_id;
|
||||
const auto dev = dmgr_.getDevice<AbstractDexHand>(dev_id);
|
||||
const auto dev = dmgr_.getDevice<AbstractDevice>(dev_id);
|
||||
if (!dev) {
|
||||
return failResponse(response, "DexHand device not found: " + dev_id);
|
||||
return failResponse(response, "Tactile device not found: " + dev_id);
|
||||
}
|
||||
maybeConfigureRh56FullTactilePolling(dev);
|
||||
appendSensorData(dev->getSensorData(), response);
|
||||
appendSensorData(dev, response);
|
||||
response->mutable_header()->set_success(true);
|
||||
setCurrentTimestamp(response->mutable_header()->mutable_timestamp());
|
||||
CMVR_LOG(DEBUG) << "[gRPCDexHandServiceImpl] (GetSensorData): success, id=" << dev_id
|
||||
@ -459,11 +496,11 @@ grpc::Status gRPCDexHandServiceImpl::GetSensorDataStream(grpc::ServerContext* co
|
||||
|
||||
string dev_id = request.header().device_id();
|
||||
CMVR_LOG(INFO) << "[gRPCDexHandServiceImpl] (GetSensorDataStream): start,id=" << dev_id;
|
||||
const auto dev = dmgr_.getDevice<AbstractDexHand>(dev_id);
|
||||
const auto dev = dmgr_.getDevice<AbstractDevice>(dev_id);
|
||||
if (!dev) {
|
||||
api::GetSensorDataStreamCommand_Feedback response;
|
||||
response.mutable_header()->set_success(false);
|
||||
response.mutable_header()->set_error_message("DexHand device not found: " + dev_id);
|
||||
response.mutable_header()->set_error_message("Tactile device not found: " + dev_id);
|
||||
setCurrentTimestamp(response.mutable_header()->mutable_timestamp());
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
@ -474,7 +511,7 @@ grpc::Status gRPCDexHandServiceImpl::GetSensorDataStream(grpc::ServerContext* co
|
||||
while (!context->IsCancelled())
|
||||
{
|
||||
api::GetSensorDataStreamCommand_Feedback response;
|
||||
appendSensorData(dev->getSensorData(), &response);
|
||||
appendSensorData(dev, &response);
|
||||
response.mutable_header()->set_success(true);
|
||||
setCurrentTimestamp(response.mutable_header()->mutable_timestamp());
|
||||
|
||||
@ -490,6 +527,11 @@ grpc::Status gRPCDexHandServiceImpl::GetSensorDataStream(grpc::ServerContext* co
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[gRPCDexHandServiceImpl] (GetSensorDataStream) exception: " << e.what();
|
||||
api::GetSensorDataStreamCommand_Feedback response;
|
||||
response.mutable_header()->set_success(false);
|
||||
response.mutable_header()->set_error_message(e.what());
|
||||
setCurrentTimestamp(response.mutable_header()->mutable_timestamp());
|
||||
stream->Write(response);
|
||||
return grpc::Status::OK;
|
||||
}
|
||||
|
||||
|
||||
@ -61,7 +61,11 @@ grpc::Status gRPCSystemServiceImpl::GetSystemStatus(grpc::ServerContext* context
|
||||
for (auto &pair: dev_list) {
|
||||
auto* dev = response->add_device_list();
|
||||
dev->set_device_id(pair.first);
|
||||
if (pair.second == "AGV") {
|
||||
const auto device = dmgr_.getDevice<AbstractDevice>(pair.first);
|
||||
if (device && device->kind() == DeviceKind::Touch) {
|
||||
dev->set_device_type(api::DeviceType::Touch);
|
||||
}
|
||||
else if (pair.second == "AGV") {
|
||||
dev->set_device_type(api::DeviceType::AGV);
|
||||
}
|
||||
else if (pair.second == "Battery") {
|
||||
|
||||
@ -265,6 +265,7 @@ v1::DeviceKind toProtoDeviceKind(const device::DeviceKind kind)
|
||||
return v1::DEVICE_KIND_MOTOR_SYSTEM;
|
||||
case device::DeviceKind::Robot: return v1::DEVICE_KIND_ROBOT;
|
||||
case device::DeviceKind::Speaker: return v1::DEVICE_KIND_SPEAKER;
|
||||
case device::DeviceKind::Touch: return v1::DEVICE_KIND_TOUCH;
|
||||
case device::DeviceKind::Unknown: break;
|
||||
}
|
||||
return v1::DEVICE_KIND_UNSPECIFIED;
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
#include "algorithms/perception/apriltag/include/tag_relative_target_3d.h"
|
||||
#include "algorithms/perception/apriltag/include/tag_relative_tcp_pose.h"
|
||||
#include "devices/camera/abstract_camera.h"
|
||||
#include "devices/dexhand/abstract_dexhand.h"
|
||||
#include "devices/touch/abstract_touch.h"
|
||||
#include "devices/arm/robot_arm.h"
|
||||
#include "task/task.h"
|
||||
|
||||
@ -75,10 +75,10 @@ public:
|
||||
|
||||
bool init() override;
|
||||
bool init(const std::shared_ptr<device::RobotArm>& arm,
|
||||
const std::shared_ptr<device::AbstractDexHand>& dexhand,
|
||||
const std::shared_ptr<device::AbstractTouch>& touch_sensor,
|
||||
const std::shared_ptr<device::AbstractCamera>& camera);
|
||||
bool init(const std::shared_ptr<device::RobotArm>& arm,
|
||||
const std::shared_ptr<device::AbstractDexHand>& dexhand,
|
||||
const std::shared_ptr<device::AbstractTouch>& touch_sensor,
|
||||
const std::shared_ptr<device::AbstractCamera>& camera,
|
||||
const std::shared_ptr<device::AbstractCamera>& external_camera);
|
||||
|
||||
@ -103,7 +103,7 @@ public:
|
||||
|
||||
int targetU() const;
|
||||
int targetV() const;
|
||||
// Selected force criterion summed over requested tactile regions, in N.
|
||||
// Selected force criterion from the touch sensor, in N.
|
||||
double lastTouchPressureSum() const;
|
||||
int lastTouchNonzeroCount() const;
|
||||
int lastActiveTagId() const;
|
||||
@ -179,7 +179,7 @@ private:
|
||||
bool coordinate_overlay_enabled_{true};
|
||||
std::string id_;
|
||||
std::shared_ptr<device::RobotArm> arm_{nullptr};
|
||||
std::shared_ptr<device::AbstractDexHand> dexhand_{nullptr};
|
||||
std::shared_ptr<device::AbstractTouch> touch_{nullptr};
|
||||
std::shared_ptr<device::AbstractCamera> camera_{nullptr};
|
||||
std::shared_ptr<device::AbstractCamera> external_camera_{nullptr};
|
||||
|
||||
@ -190,9 +190,6 @@ private:
|
||||
PbvsController pbvs_;
|
||||
const cmvr::config::TouchScreenTaskConfig config_;
|
||||
const bool config_valid_;
|
||||
device::AbstractDexHand::TactileRegionKey tactile_region_{
|
||||
device::AbstractDexHand::FingerType::INDEX,
|
||||
device::AbstractDexHand::TactileRegion::TIP};
|
||||
|
||||
Phase phase_{Phase::IDLE};
|
||||
Phase phase_after_retract_{Phase::DONE};
|
||||
|
||||
@ -104,7 +104,7 @@ bool isTouchTriggered(const TouchScreenTaskConfig& config,
|
||||
return resultant_force_value >= config.touch().tactile().force_threshold();
|
||||
}
|
||||
|
||||
double tactileForceValue(const device::AbstractDexHand::ForceNewtons& point,
|
||||
double tactileForceValue(const device::ForceNewtons& point,
|
||||
const cmvr::config::TouchScreenTactileCriterion criterion) {
|
||||
switch (criterion) {
|
||||
case cmvr::config::TOUCH_SCREEN_TACTILE_CRITERION_FZ:
|
||||
@ -155,22 +155,6 @@ bool extractProjectedYawAboutTargetNormal(const Eigen::Matrix3d& R_target,
|
||||
return std::isfinite(yaw_rad_out);
|
||||
}
|
||||
|
||||
bool isTactileRegionSupported(
|
||||
const device::AbstractDexHand::FingerType finger,
|
||||
const device::AbstractDexHand::TactileRegion region) {
|
||||
using Region = device::AbstractDexHand::TactileRegion;
|
||||
switch (region) {
|
||||
case Region::TIP:
|
||||
case Region::FINGER:
|
||||
case Region::PAD:
|
||||
return true;
|
||||
case Region::THUMB_MIDDLE:
|
||||
return finger == device::AbstractDexHand::FingerType::THUMB;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
perception::AprilTagPerception::DepthPolicy toDepthPolicy(
|
||||
const cmvr::config::TouchScreenDepthPolicy policy) {
|
||||
switch (policy) {
|
||||
@ -195,37 +179,6 @@ perception::TagRelativeTarget3D::TargetPointMethod toTargetPointMethod(
|
||||
return perception::TagRelativeTarget3D::TargetPointMethod::TAG_PLANE;
|
||||
}
|
||||
|
||||
device::AbstractDexHand::FingerType toFingerType(const cmvr::config::TouchScreenFingerType finger) {
|
||||
switch (finger) {
|
||||
case cmvr::config::TOUCH_SCREEN_FINGER_TYPE_PINKY:
|
||||
return device::AbstractDexHand::FingerType::PINKY;
|
||||
case cmvr::config::TOUCH_SCREEN_FINGER_TYPE_RING:
|
||||
return device::AbstractDexHand::FingerType::RING;
|
||||
case cmvr::config::TOUCH_SCREEN_FINGER_TYPE_MIDDLE:
|
||||
return device::AbstractDexHand::FingerType::MIDDLE;
|
||||
case cmvr::config::TOUCH_SCREEN_FINGER_TYPE_INDEX:
|
||||
return device::AbstractDexHand::FingerType::INDEX;
|
||||
case cmvr::config::TOUCH_SCREEN_FINGER_TYPE_THUMB:
|
||||
return device::AbstractDexHand::FingerType::THUMB;
|
||||
}
|
||||
return device::AbstractDexHand::FingerType::INDEX;
|
||||
}
|
||||
|
||||
device::AbstractDexHand::TactileRegion toTactileRegion(
|
||||
const cmvr::config::TouchScreenTactileRegion region) {
|
||||
switch (region) {
|
||||
case cmvr::config::TOUCH_SCREEN_TACTILE_REGION_TIP:
|
||||
return device::AbstractDexHand::TactileRegion::TIP;
|
||||
case cmvr::config::TOUCH_SCREEN_TACTILE_REGION_FINGER:
|
||||
return device::AbstractDexHand::TactileRegion::FINGER;
|
||||
case cmvr::config::TOUCH_SCREEN_TACTILE_REGION_PAD:
|
||||
return device::AbstractDexHand::TactileRegion::PAD;
|
||||
case cmvr::config::TOUCH_SCREEN_TACTILE_REGION_THUMB_MIDDLE:
|
||||
return device::AbstractDexHand::TactileRegion::THUMB_MIDDLE;
|
||||
}
|
||||
return device::AbstractDexHand::TactileRegion::TIP;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TouchScreenTask::TouchScreenTask(const cmvr::config::TouchScreenTaskConfig& cfg)
|
||||
@ -256,7 +209,7 @@ bool TouchScreenTask::init() {
|
||||
const auto& devices = config_.devices();
|
||||
auto& dm = device::DeviceManager::getInstance();
|
||||
auto arm = dm.getDevice<device::RobotArm>(devices.arm_id());
|
||||
auto dexhand = dm.getDevice<device::AbstractDexHand>(devices.dexhand_id());
|
||||
auto touch_sensor = dm.getDevice<device::AbstractTouch>(devices.touch_id());
|
||||
auto camera = dm.getDevice<device::AbstractCamera>(devices.camera_id());
|
||||
auto external_camera =
|
||||
dm.getDevice<device::AbstractCamera>(devices.external_camera_id());
|
||||
@ -269,22 +222,22 @@ bool TouchScreenTask::init() {
|
||||
<< devices.external_camera_id();
|
||||
return false;
|
||||
}
|
||||
return init(arm, dexhand, camera, external_camera);
|
||||
return init(arm, touch_sensor, camera, external_camera);
|
||||
}
|
||||
|
||||
bool TouchScreenTask::init(const std::shared_ptr<device::RobotArm>& arm,
|
||||
const std::shared_ptr<device::AbstractDexHand>& dexhand,
|
||||
const std::shared_ptr<device::AbstractTouch>& touch_sensor,
|
||||
const std::shared_ptr<device::AbstractCamera>& camera) {
|
||||
std::shared_ptr<device::AbstractCamera> external_camera;
|
||||
if (config_.has_devices() && config_.devices().has_external_camera_id()) {
|
||||
external_camera = device::DeviceManager::getInstance().getDevice<device::AbstractCamera>(
|
||||
config_.devices().external_camera_id());
|
||||
}
|
||||
return init(arm, dexhand, camera, external_camera);
|
||||
return init(arm, touch_sensor, camera, external_camera);
|
||||
}
|
||||
|
||||
bool TouchScreenTask::init(const std::shared_ptr<device::RobotArm>& arm,
|
||||
const std::shared_ptr<device::AbstractDexHand>& dexhand,
|
||||
const std::shared_ptr<device::AbstractTouch>& touch_sensor,
|
||||
const std::shared_ptr<device::AbstractCamera>& camera,
|
||||
const std::shared_ptr<device::AbstractCamera>& external_camera) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@ -292,7 +245,7 @@ bool TouchScreenTask::init(const std::shared_ptr<device::RobotArm>& arm,
|
||||
initialized_ = false;
|
||||
stopCoordinateOverlayWorker();
|
||||
arm_ = arm;
|
||||
dexhand_ = dexhand;
|
||||
touch_ = touch_sensor;
|
||||
camera_ = camera;
|
||||
external_camera_ = external_camera;
|
||||
|
||||
@ -406,7 +359,7 @@ bool TouchScreenTask::step(const double dt) {
|
||||
}
|
||||
|
||||
// TOUCHING reads and checks the same tactile sample together in stepTouching().
|
||||
if (dexhand_ && phase_ != Phase::TOUCHING) {
|
||||
if (touch_ && phase_ != Phase::TOUCHING) {
|
||||
updateTouchPressure();
|
||||
}
|
||||
|
||||
@ -797,7 +750,7 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig&
|
||||
if (!config.has_id() || config.id().empty() ||
|
||||
!config.has_devices() ||
|
||||
!config.devices().has_arm_id() || config.devices().arm_id().empty() ||
|
||||
!config.devices().has_dexhand_id() || config.devices().dexhand_id().empty() ||
|
||||
!config.devices().has_touch_id() || config.devices().touch_id().empty() ||
|
||||
!config.devices().has_camera_id() || config.devices().camera_id().empty() ||
|
||||
!config.devices().has_external_camera_id() ||
|
||||
config.devices().external_camera_id().empty() ||
|
||||
@ -861,8 +814,6 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig&
|
||||
!pbvs.has_amax6() ||
|
||||
!hasVec6(pbvs.amax6()) ||
|
||||
!pbvs.has_twist_filter_alpha() ||
|
||||
!tactile.has_finger() ||
|
||||
!tactile.has_region() ||
|
||||
!tactile.has_criterion() ||
|
||||
!tactile.has_force_threshold() ||
|
||||
!hasVec6(retract.twist_tool())) {
|
||||
@ -981,11 +932,6 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig&
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isTactileRegionSupported(toFingerType(tactile.finger()),
|
||||
toTactileRegion(tactile.region()))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (touch.motion_case()) {
|
||||
case cmvr::config::TouchScreenTaskTouchConfig::kSpeedL: {
|
||||
const auto& speed_l = touch.speed_l();
|
||||
@ -1051,16 +997,6 @@ bool TouchScreenTask::applyConfig() {
|
||||
? config_.initialization().skip_velocity_tolerance_rad_s()
|
||||
: 1e-2;
|
||||
|
||||
const auto& tactile = config_.touch().tactile();
|
||||
tactile_region_ = {toFingerType(tactile.finger()), toTactileRegion(tactile.region())};
|
||||
if (dexhand_) {
|
||||
try {
|
||||
dexhand_->setTactilePollingRegion(tactile_region_.first, tactile_region_.second);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const auto& perception = config_.perception();
|
||||
const auto& tags = perception.tags();
|
||||
const auto& hand_camera_config = perception.hand_camera();
|
||||
@ -2174,15 +2110,17 @@ bool TouchScreenTask::updateTouchPressure() {
|
||||
last_touch_pressure_sum_ = 0.0;
|
||||
last_touch_resultant_fz_ = 0.0;
|
||||
last_touch_nonzero_count_ = 0;
|
||||
if (!dexhand_) {
|
||||
if (!touch_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const auto force = dexhand_->getResultantForceNewtons(
|
||||
tactile_region_.first, tactile_region_.second);
|
||||
last_touch_pressure_sum_ = tactileForceValue(force, config_.touch().tactile().criterion());
|
||||
last_touch_resultant_fz_ = force.fz;
|
||||
device::ForceSample sample;
|
||||
if (!touch_->readForce(sample)) {
|
||||
return false;
|
||||
}
|
||||
last_touch_pressure_sum_ = tactileForceValue(sample.force, config_.touch().tactile().criterion());
|
||||
last_touch_resultant_fz_ = sample.force.fz;
|
||||
last_touch_nonzero_count_ = std::abs(last_touch_pressure_sum_) > 1e-9 ? 1 : 0;
|
||||
return true;
|
||||
} catch (...) {
|
||||
|
||||
@ -36,6 +36,8 @@
|
||||
#include "devices/motor/manager/include/motor_manager.h"
|
||||
#include "manager/device_manager/include/device_manager.h"
|
||||
#include "manager/task_manager/include/task_manager.h"
|
||||
#include "service/grpc/include/grpc_dexhand_service.h"
|
||||
#include "service/grpc/include/grpc_system_service.h"
|
||||
#include "simulate/mujoco/mujoco_viewer/include/mujoco_viewer.h"
|
||||
#include "simulate/mujoco/mujoco_world/include/mujoco_world.h"
|
||||
|
||||
@ -163,6 +165,20 @@ public:
|
||||
void getState(cmvr::device::CameraState& state) override { state = {}; }
|
||||
};
|
||||
|
||||
class ScriptedTouch final : public cmvr::device::AbstractTouch {
|
||||
public:
|
||||
std::string typeName() const override { return "ScriptedTouch"; }
|
||||
Status state() const override { return Status::STREAMING; }
|
||||
std::string lastError() const override { return {}; }
|
||||
bool readForce(cmvr::device::ForceSample& sample) override {
|
||||
sample.force = {0.0, 0.0, 2.5};
|
||||
sample.sample_time = std::chrono::steady_clock::now();
|
||||
return available;
|
||||
}
|
||||
bool readTactile(cmvr::device::TactileSample&) override { return false; }
|
||||
bool available{true};
|
||||
};
|
||||
|
||||
class FailureReturnArm final : public cmvr::device::RobotArm {
|
||||
public:
|
||||
using Result = cmvr::device::Result;
|
||||
@ -418,6 +434,77 @@ void run_touch_once(int u, int v) {
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(TouchSensorIntegrationTest, FactoryAndGrpcUseIndependentTouchDevice) {
|
||||
using cmvr::device::DeviceManager;
|
||||
struct ResetDeviceManager {
|
||||
~ResetDeviceManager() { DeviceManager::destroyInstance(); }
|
||||
} reset;
|
||||
DeviceManager::destroyInstance();
|
||||
|
||||
const auto project_root = findProjectRoot();
|
||||
ASSERT_FALSE(project_root.empty());
|
||||
cmvr::config::DeviceManagerConfig config;
|
||||
auto* entry = config.add_devices();
|
||||
entry->set_id("mujoco_zero_touch");
|
||||
entry->set_type(cmvr::config::DeviceConfigEntry::DEVICE_TYPE_TOUCH);
|
||||
entry->set_config_file(
|
||||
(project_root / "cmvr-es/config/devices/touch/touch.pb.txt").string());
|
||||
entry->set_enable(true);
|
||||
auto& manager = DeviceManager::getInstance(config);
|
||||
auto touch = manager.getDevice<cmvr::device::AbstractTouch>(entry->id());
|
||||
ASSERT_NE(touch, nullptr);
|
||||
EXPECT_EQ(touch->kind(), cmvr::device::DeviceKind::Touch);
|
||||
EXPECT_EQ(manager.getDevice<cmvr::device::AbstractDexHand>(entry->id()), nullptr);
|
||||
cmvr::device::ForceSample sample;
|
||||
ASSERT_TRUE(touch->readForce(sample));
|
||||
EXPECT_DOUBLE_EQ(sample.force.magnitude(), 0.0);
|
||||
EXPECT_NE(sample.sample_time, std::chrono::steady_clock::time_point{});
|
||||
|
||||
grpc::ServerContext context;
|
||||
cmvr::service::gRPCDexHandServiceImpl sensor_service;
|
||||
cmvr::api::GetSensorDataCommand_Request request;
|
||||
request.mutable_header()->set_device_id(entry->id());
|
||||
cmvr::api::GetSensorDataCommand_Feedback response;
|
||||
ASSERT_TRUE(sensor_service.GetSensorData(&context, &request, &response).ok());
|
||||
ASSERT_TRUE(response.header().success()) << response.header().error_message();
|
||||
ASSERT_EQ(response.sensor_size(), 1);
|
||||
EXPECT_EQ(response.sensor(0).rows(), 1);
|
||||
EXPECT_EQ(response.sensor(0).cols(), 1);
|
||||
EXPECT_EQ(response.sensor(0).finger_type(), cmvr::api::SensorData::FINGER_UNSPECIFIED);
|
||||
EXPECT_EQ(response.sensor(0).part_type(), cmvr::api::SensorData::PART_UNSPECIFIED);
|
||||
|
||||
cmvr::service::gRPCSystemServiceImpl system_service;
|
||||
cmvr::api::GetSystemStatusCommand_Request status_request;
|
||||
cmvr::api::GetSystemStatusCommand_Feedback status_response;
|
||||
ASSERT_TRUE(system_service.GetSystemStatus(&context, &status_request, &status_response).ok());
|
||||
ASSERT_TRUE(status_response.header().success());
|
||||
ASSERT_EQ(status_response.device_list_size(), 1);
|
||||
EXPECT_EQ(status_response.device_list(0).device_type(), cmvr::api::DeviceType::Touch);
|
||||
|
||||
ASSERT_TRUE(touch->stop());
|
||||
EXPECT_FALSE(touch->readForce(sample));
|
||||
response.Clear();
|
||||
ASSERT_TRUE(sensor_service.GetSensorData(&context, &request, &response).ok());
|
||||
EXPECT_FALSE(response.header().success());
|
||||
EXPECT_FALSE(response.header().error_message().empty());
|
||||
EXPECT_EQ(response.sensor_size(), 0);
|
||||
}
|
||||
|
||||
TEST_F(TouchScreenFailureReturnTest, ReadsTouchForceAndDiscardsFailedSample) {
|
||||
const auto sensor = std::make_shared<ScriptedTouch>();
|
||||
const auto camera = std::make_shared<FailureReturnCamera>();
|
||||
cmvr::task::TouchScreenTask task(config);
|
||||
ASSERT_TRUE(task.init(arm, sensor, camera, camera));
|
||||
ASSERT_TRUE(task.step(0.02));
|
||||
EXPECT_DOUBLE_EQ(task.lastTouchPressureSum(), 2.5);
|
||||
EXPECT_EQ(task.lastTouchNonzeroCount(), 1);
|
||||
|
||||
sensor->available = false;
|
||||
ASSERT_TRUE(task.step(0.02));
|
||||
EXPECT_DOUBLE_EQ(task.lastTouchPressureSum(), 0.0);
|
||||
EXPECT_EQ(task.lastTouchNonzeroCount(), 0);
|
||||
}
|
||||
|
||||
TEST_F(TouchScreenFailureReturnTest, FailureReturnIsOptionalAndIndependentOfSuccessReturn) {
|
||||
for (const bool explicitly_disabled : {false, true}) {
|
||||
SCOPED_TRACE(explicitly_disabled);
|
||||
@ -808,28 +895,15 @@ TEST(TouchScreenTaskTest, TouchSpeedLJerkIsOptionalAndMustBeFinitePositive) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST(TouchScreenTaskTest, TactileRegionMustMatchSelectedFinger) {
|
||||
TEST(TouchScreenTaskTest, TouchSensorIdIsRequired) {
|
||||
auto config = loadMujocoTouchConfig(findProjectRoot());
|
||||
for (const auto finger : {cmvr::config::TOUCH_SCREEN_FINGER_TYPE_PINKY,
|
||||
cmvr::config::TOUCH_SCREEN_FINGER_TYPE_RING,
|
||||
cmvr::config::TOUCH_SCREEN_FINGER_TYPE_MIDDLE,
|
||||
cmvr::config::TOUCH_SCREEN_FINGER_TYPE_INDEX,
|
||||
cmvr::config::TOUCH_SCREEN_FINGER_TYPE_THUMB}) {
|
||||
for (const auto region : {cmvr::config::TOUCH_SCREEN_TACTILE_REGION_TIP,
|
||||
cmvr::config::TOUCH_SCREEN_TACTILE_REGION_FINGER,
|
||||
cmvr::config::TOUCH_SCREEN_TACTILE_REGION_PAD,
|
||||
cmvr::config::TOUCH_SCREEN_TACTILE_REGION_THUMB_MIDDLE}) {
|
||||
SCOPED_TRACE(::testing::Message() << "finger=" << finger << ", region=" << region);
|
||||
config.mutable_touch()->mutable_tactile()->set_finger(finger);
|
||||
config.mutable_touch()->mutable_tactile()->set_region(region);
|
||||
const bool valid = region != cmvr::config::TOUCH_SCREEN_TACTILE_REGION_THUMB_MIDDLE ||
|
||||
finger == cmvr::config::TOUCH_SCREEN_FINGER_TYPE_THUMB;
|
||||
cmvr::task::TouchScreenTask task(config);
|
||||
EXPECT_EQ(task.lastStatus(), valid
|
||||
? cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED
|
||||
: cmvr::task::TouchScreenTask::Status::INVALID_CONFIG);
|
||||
}
|
||||
}
|
||||
EXPECT_EQ(config.devices().touch_id(), "mujoco_zero_touch");
|
||||
config.mutable_devices()->clear_touch_id();
|
||||
cmvr::task::TouchScreenTask missing(config);
|
||||
EXPECT_EQ(missing.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG);
|
||||
config.mutable_devices()->set_touch_id("");
|
||||
cmvr::task::TouchScreenTask empty(config);
|
||||
EXPECT_EQ(empty.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG);
|
||||
}
|
||||
|
||||
TEST(TouchScreenTaskTest, InitializationRequiresUniqueCompleteFiniteJointPositions) {
|
||||
@ -968,9 +1042,9 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) {
|
||||
add_device("mujoco_right_arm",
|
||||
cmvr::config::DeviceConfigEntry::DEVICE_TYPE_ROBOT_ARM,
|
||||
arm_entry->config_file().c_str());
|
||||
add_device("mujoco_zero_touch_dexhand",
|
||||
cmvr::config::DeviceConfigEntry::DEVICE_TYPE_DEXHAND,
|
||||
"devices/dexhand/dexhand.pb.txt");
|
||||
add_device("mujoco_zero_touch",
|
||||
cmvr::config::DeviceConfigEntry::DEVICE_TYPE_TOUCH,
|
||||
"devices/touch/touch.pb.txt");
|
||||
add_device("mujoco_hand_cam",
|
||||
cmvr::config::DeviceConfigEntry::DEVICE_TYPE_CAMERA,
|
||||
"devices/camera/camera.pb.txt");
|
||||
@ -1317,9 +1391,9 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) {
|
||||
auto* return_joint = timeout_config.mutable_initialization()->mutable_joint_positions(0);
|
||||
return_joint->set_rad(return_joint->rad() + 0.05);
|
||||
cmvr::task::TouchScreenTask timeout_task(timeout_config);
|
||||
auto dexhand = device_manager.getDevice<cmvr::device::AbstractDexHand>(
|
||||
touch_config.devices().dexhand_id());
|
||||
if (!timeout_task.init(arm, dexhand, hand_camera, external_camera) ||
|
||||
auto touch_sensor = device_manager.getDevice<cmvr::device::AbstractTouch>(
|
||||
touch_config.devices().touch_id());
|
||||
if (!timeout_task.init(arm, touch_sensor, hand_camera, external_camera) ||
|
||||
!timeout_task.touch(target_u, target_v)) {
|
||||
throw std::runtime_error("failed to start approach timeout scenario");
|
||||
}
|
||||
@ -1406,7 +1480,7 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) {
|
||||
EXPECT_TRUE(outcome.align_reached);
|
||||
EXPECT_GT(outcome.speedl_command_norm, 0.005);
|
||||
if (!touch_config.alignment().pause_when_reached()) {
|
||||
// ZeroSimTouchDexHand always reports zero force. This scenario must
|
||||
// ZeroSimTouch always reports zero force. This scenario must
|
||||
// reach the forward-distance limit, retract, and report no contact.
|
||||
EXPECT_DOUBLE_EQ(outcome.max_pressure, 0.0);
|
||||
EXPECT_TRUE(outcome.retracting_seen);
|
||||
@ -1444,11 +1518,11 @@ TEST(TouchScreenTaskTest, DISABLED_RunTouchOnceInMujoco) {
|
||||
arm_entry->set_type(cmvr::config::DeviceConfigEntry::DEVICE_TYPE_ROBOT_ARM);
|
||||
arm_entry->set_config_file("devices/arm/arm_mujoco.pb.txt");
|
||||
arm_entry->set_enable(true);
|
||||
auto* dexhand_entry = device_manager_config.add_devices();
|
||||
dexhand_entry->set_id("mujoco_zero_touch_dexhand");
|
||||
dexhand_entry->set_type(cmvr::config::DeviceConfigEntry::DEVICE_TYPE_DEXHAND);
|
||||
dexhand_entry->set_config_file("devices/dexhand/dexhand.pb.txt");
|
||||
dexhand_entry->set_enable(true);
|
||||
auto* touch_sensor_entry = device_manager_config.add_devices();
|
||||
touch_sensor_entry->set_id("mujoco_zero_touch");
|
||||
touch_sensor_entry->set_type(cmvr::config::DeviceConfigEntry::DEVICE_TYPE_TOUCH);
|
||||
touch_sensor_entry->set_config_file("devices/touch/touch.pb.txt");
|
||||
touch_sensor_entry->set_enable(true);
|
||||
|
||||
auto& device_manager = cmvr::device::DeviceManager::getInstance(device_manager_config);
|
||||
auto motor_system = device_manager.getDevice<cmvr::device::MotorManager>("right_arm_mujoco_motors");
|
||||
|
||||
@ -31,6 +31,7 @@ message SensorData {
|
||||
INDEX = 3; // 食指
|
||||
THUMB = 4; // 大拇指
|
||||
PALM = 5; // 掌心
|
||||
FINGER_UNSPECIFIED = 6; // 独立触觉传感器,不关联手指
|
||||
}
|
||||
|
||||
// 部位类型(指中改为THUMB_MIDDLE以避免冲突)
|
||||
@ -40,6 +41,7 @@ message SensorData {
|
||||
PAD = 2; // 指腹
|
||||
THUMB_MIDDLE = 3; // 大拇指指中(仅大拇指有)
|
||||
PALM_PAD = 4; // 掌心部位(对应PalmTactileData)
|
||||
PART_UNSPECIFIED = 5; // 独立触觉传感器,不关联手指部位
|
||||
}
|
||||
|
||||
FingerType finger_type = 4; // 手指类型(掌心使用PALM)
|
||||
@ -146,4 +148,4 @@ message GetSensorDataStreamCommand {
|
||||
CommandHeader.Feedback header = 1;
|
||||
repeated SensorData sensor = 2;//所有传感器的数据
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,6 +14,7 @@ enum DeviceType {
|
||||
Microphone = 5;
|
||||
Robot = 6;
|
||||
Speaker = 7;
|
||||
Touch = 8;
|
||||
Unknown = 20;
|
||||
}
|
||||
|
||||
|
||||
@ -21,6 +21,7 @@ message DeviceConfigEntry {
|
||||
DEVICE_TYPE_AGV = 17;
|
||||
DEVICE_TYPE_MUJOCO_WORLD = 18;
|
||||
DEVICE_TYPE_MUJOCO_VIEWER = 19;
|
||||
DEVICE_TYPE_TOUCH = 20;
|
||||
}
|
||||
|
||||
// For DEVICE_TYPE_MOTOR_SYSTEM, this is the motor_group id selected from config_file.
|
||||
|
||||
@ -10,51 +10,13 @@ message RH56DFTPDexHandConfig{
|
||||
int32 poll_interval_ms = 5;
|
||||
}
|
||||
|
||||
enum PX6AXGen3PollingReadMode {
|
||||
PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_AND_RESULTANT_FORCE = 0;
|
||||
PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE = 1;
|
||||
PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE = 2;
|
||||
}
|
||||
|
||||
message PX6AXGen3{
|
||||
reserved 10;
|
||||
|
||||
string id = 1;
|
||||
string serial_port = 2;
|
||||
string sensor_model = 3;
|
||||
int32 module_id = 4;
|
||||
int32 baud_rate = 5;
|
||||
int32 distributed_length = 6;
|
||||
int32 resultant_length = 7;
|
||||
int32 poll_interval_ms = 8;
|
||||
bool auto_calibrate = 9;
|
||||
int32 response_timeout_ms = 11;
|
||||
int32 tactile_rows = 12;
|
||||
int32 tactile_cols = 13;
|
||||
int32 response_header_bytes = 14;
|
||||
string tactile_finger = 15;
|
||||
string tactile_region = 16;
|
||||
string sensor_name = 17;
|
||||
PX6AXGen3PollingReadMode polling_read_mode = 18;
|
||||
// Maximum age since the sample's request was sent. 0 uses 50 ms.
|
||||
// Independent of response_timeout_ms: stale cached data must fail promptly.
|
||||
int32 max_sample_age_ms = 19;
|
||||
}
|
||||
|
||||
message ZeroSimTouchDexHand {
|
||||
string id = 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
message DexHandDeviceConfig {
|
||||
string id = 1;
|
||||
reserved 2;
|
||||
reserved 2, 11, 12;
|
||||
reserved "px_6ax_gen3", "zero_sim_touch";
|
||||
|
||||
oneof backend {
|
||||
RH56DFTPDexHandConfig rh56dftp = 10;
|
||||
PX6AXGen3 px_6ax_gen3 = 11;
|
||||
ZeroSimTouchDexHand zero_sim_touch = 12;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
63
protos/cmvr/config/touch_config/touch_config.proto
Normal file
63
protos/cmvr/config/touch_config/touch_config.proto
Normal file
@ -0,0 +1,63 @@
|
||||
syntax = "proto3";
|
||||
package cmvr.config;
|
||||
|
||||
enum PX6AXGen3PollingReadMode {
|
||||
PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_AND_RESULTANT_FORCE = 0;
|
||||
PX_6AX_GEN3_POLLING_READ_MODE_DISTRIBUTED_FORCE = 1;
|
||||
PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE = 2;
|
||||
}
|
||||
|
||||
message PX6AXGen3{
|
||||
reserved 10, 15, 16;
|
||||
reserved "tactile_finger", "tactile_region";
|
||||
|
||||
string id = 1;
|
||||
string serial_port = 2;
|
||||
string sensor_model = 3;
|
||||
int32 module_id = 4;
|
||||
int32 baud_rate = 5;
|
||||
int32 distributed_length = 6;
|
||||
int32 resultant_length = 7;
|
||||
int32 poll_interval_ms = 8;
|
||||
bool auto_calibrate = 9;
|
||||
int32 response_timeout_ms = 11;
|
||||
int32 tactile_rows = 12;
|
||||
int32 tactile_cols = 13;
|
||||
int32 response_header_bytes = 14;
|
||||
string sensor_name = 17;
|
||||
PX6AXGen3PollingReadMode polling_read_mode = 18;
|
||||
// Maximum age since the sample's request was sent. 0 uses 50 ms.
|
||||
// Independent of response_timeout_ms: stale cached data must fail promptly.
|
||||
int32 max_sample_age_ms = 19;
|
||||
}
|
||||
|
||||
message ZeroSimTouch {
|
||||
string id = 1;
|
||||
}
|
||||
|
||||
message PX6AXGenXCan {
|
||||
string id = 1;
|
||||
int32 channel_id = 2;
|
||||
// Unset uses the default standard CAN force frame ID, 0x600.
|
||||
optional uint32 force_can_id = 3;
|
||||
// Maximum age of the latest received sample. 0 uses 300 ms.
|
||||
int32 max_sample_age_ms = 4;
|
||||
}
|
||||
|
||||
message TouchDeviceConfig {
|
||||
string id = 1;
|
||||
|
||||
oneof backend {
|
||||
PX6AXGen3 px_6ax_gen3 = 10;
|
||||
ZeroSimTouch zero_sim = 11;
|
||||
PX6AXGenXCan px_6ax_genx_can = 12;
|
||||
}
|
||||
}
|
||||
|
||||
message TouchConfig {
|
||||
repeated TouchDeviceConfig touches = 1;
|
||||
}
|
||||
|
||||
message TouchRootConfig {
|
||||
TouchConfig touch = 1;
|
||||
}
|
||||
@ -12,13 +12,13 @@ message TouchScreenInitJointPoint {
|
||||
}
|
||||
|
||||
message TouchScreenTaskDevicesConfig {
|
||||
reserved 1;
|
||||
reserved "robot_id";
|
||||
reserved 1, 2;
|
||||
reserved "robot_id", "dexhand_id";
|
||||
|
||||
optional string camera_id = 3;
|
||||
optional string arm_id = 4;
|
||||
optional string external_camera_id = 5;
|
||||
optional string dexhand_id = 2;
|
||||
optional string touch_id = 6;
|
||||
}
|
||||
|
||||
message TouchScreenTaskInitializationConfig {
|
||||
@ -128,11 +128,11 @@ message TouchScreenTouchMoveLConfig {
|
||||
}
|
||||
|
||||
message TouchScreenTactileTriggerConfig {
|
||||
optional TouchScreenFingerType finger = 1;
|
||||
optional TouchScreenTactileRegion region = 2;
|
||||
reserved 1, 2;
|
||||
reserved "finger", "region";
|
||||
optional TouchScreenTactileCriterion criterion = 3;
|
||||
// Threshold in newtons (N), applied to the selected force criterion summed
|
||||
// over the requested tactile regions. Equality also triggers contact.
|
||||
// Threshold in newtons (N), applied to the selected sensor's force criterion.
|
||||
// Equality also triggers contact.
|
||||
optional double force_threshold = 4;
|
||||
}
|
||||
|
||||
|
||||
@ -63,6 +63,7 @@ enum DeviceKind {
|
||||
DEVICE_KIND_MOTOR_SYSTEM = 11;
|
||||
DEVICE_KIND_ROBOT = 12;
|
||||
DEVICE_KIND_SPEAKER = 13;
|
||||
DEVICE_KIND_TOUCH = 14;
|
||||
}
|
||||
|
||||
// DeviceManager's view of a configured entry. REGISTERED means that the
|
||||
|
||||
Loading…
Reference in New Issue
Block a user