feat(touch): update AprilTag sizing and camera preview overlays

This commit is contained in:
lgv 2026-11-26 17:06:06 +08:00
parent e22d86deb1
commit ef0fa4ee2c
13 changed files with 681 additions and 251 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,12 +6,10 @@
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <future>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <Eigen/Dense>
@ -166,25 +164,12 @@ private:
bool updateTouchPressure();
void logTouchPressure(bool force = false);
device::CameraStreamOverlay buildCoordinateOverlay(
const perception::AprilTagPerception* overlay_perception) const;
void publishCoordinateOverlay();
void startCoordinateOverlayWorker();
void stopCoordinateOverlayWorker();
void setCoordinateOverlayEnabled(bool enabled);
void coordinateOverlayLoop(std::shared_ptr<perception::AprilTagPerception> overlay_perception);
private:
mutable std::mutex mutex_;
// The motion worker captures values only; it never takes the task mutex.
std::future<device::Result> approach_motion_;
std::shared_ptr<std::atomic<bool>> approach_cancel_;
// The display worker never takes mutex_ or uses the PBVS perception state.
std::mutex coordinate_overlay_mutex_;
std::condition_variable coordinate_overlay_cv_;
std::thread coordinate_overlay_thread_;
bool coordinate_overlay_stop_{false};
bool coordinate_overlay_enabled_{true};
std::string id_;
std::shared_ptr<device::RobotArm> arm_{nullptr};
std::shared_ptr<device::AbstractTouch> touch_{nullptr};

View File

@ -7,7 +7,6 @@
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <opencv2/imgcodecs.hpp>
@ -45,6 +44,12 @@ bool computeLinearMoveDeltaTool(const Eigen::Matrix<double, 6, 1>& twist_base,
using TouchScreenTaskConfig = cmvr::config::TouchScreenTaskConfig;
void configureTagSizes(perception::AprilTagPerception& detector,
const cmvr::config::TouchScreenTaskTagsConfig& tags) {
detector.setTagSize(tags.screen().size_m());
detector.setTagSizeForId(tags.hand().id(), tags.hand().size_m());
}
std::array<double, 6> toArray6(const Eigen::Matrix<double, 6, 1>& value) {
return {{value[0], value[1], value[2], value[3], value[4], value[5]}};
}
@ -193,14 +198,12 @@ TouchScreenTask::TouchScreenTask(const cmvr::config::TouchScreenTaskConfig& cfg)
TouchScreenTask::~TouchScreenTask() {
cancelApproach();
stopCoordinateOverlayWorker();
}
bool TouchScreenTask::init() {
{
std::lock_guard<std::mutex> lock(mutex_);
stopUnlocked();
stopCoordinateOverlayWorker();
initialized_ = false;
last_status_ = config_valid_ ? Status::NOT_INITIALIZED : Status::INVALID_CONFIG;
if (!config_valid_) return false;
@ -256,7 +259,6 @@ bool TouchScreenTask::init(const std::shared_ptr<device::RobotArm>& arm,
std::lock_guard<std::mutex> lock(mutex_);
stopUnlocked();
initialized_ = false;
stopCoordinateOverlayWorker();
arm_ = arm;
touch_ = touch_sensor;
camera_ = camera;
@ -295,9 +297,6 @@ bool TouchScreenTask::init(const std::shared_ptr<device::RobotArm>& arm,
phase_ = Phase::IDLE;
resetRunState();
last_status_ = Status::IDLE;
// Make presentation settings available before the first task tick.
publishCoordinateOverlay();
startCoordinateOverlayWorker();
return initialized_;
}
@ -331,7 +330,6 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) {
CMVR_LOG(ERROR) << "[TouchScreenTask][START_REJECTED] " << message;
if (phase_ != Phase::FAILED) last_status_ = Status::ROBOT_COMMAND_FAILED;
phase_ = Phase::FAILED;
setCoordinateOverlayEnabled(true);
return false;
};
cancelApproach();
@ -363,8 +361,6 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) {
target_u_ = u;
target_v_ = v;
phase_ = config_.approach().enable() ? Phase::PREPARING : Phase::ALIGNING;
setCoordinateOverlayEnabled(false);
startCoordinateOverlayWorker();
phase_start_time_ = Clock::now();
last_status_ = config_.approach().enable() ? Status::PREPARING : Status::ALIGN_WAITING_TRACK;
return true;
@ -438,153 +434,9 @@ bool TouchScreenTask::step(const double dt) {
return false;
}
device::CameraStreamOverlay TouchScreenTask::buildCoordinateOverlay(
const perception::AprilTagPerception* overlay_perception) const
{
device::CameraStreamOverlay overlay;
overlay.draw_coordinate_frames =
!config_.has_debug_draw_coordinate_frames() ||
config_.debug_draw_coordinate_frames();
overlay.coordinate_axis_length_m = 0.02;
if (config_.has_debug_coordinate_axis_length_m() &&
std::isfinite(config_.debug_coordinate_axis_length_m()) &&
config_.debug_coordinate_axis_length_m() > 0.0) {
overlay.coordinate_axis_length_m = config_.debug_coordinate_axis_length_m();
}
if (overlay.draw_coordinate_frames && overlay_perception) {
const auto& tags = config_.perception().tags();
const int screen_tag_id = tags.screen().id();
const int hand_tag_id = tags.hand().id();
const auto* screen_tag = overlay_perception->findTag(screen_tag_id);
if (screen_tag) {
device::CoordinateFrameOverlay frame;
frame.T_C_Frame = screen_tag->T_C_Tag();
frame.label = "G";
frame.tag_id = screen_tag->id;
frame.valid = true;
overlay.coordinate_frames.push_back(std::move(frame));
}
if (const auto* hand_tag = overlay_perception->findTag(hand_tag_id)) {
device::CoordinateFrameOverlay frame;
frame.T_C_Frame = hand_tag->T_C_Tag();
frame.label = "H";
frame.tag_id = hand_tag->id;
frame.valid = true;
overlay.coordinate_frames.push_back(std::move(frame));
}
}
return overlay;
}
void TouchScreenTask::publishCoordinateOverlay()
{
if (external_camera_) {
external_camera_->setStreamOverlay(buildCoordinateOverlay(external_perception_.get()));
}
}
void TouchScreenTask::startCoordinateOverlayWorker()
{
if (coordinate_overlay_thread_.joinable() || !external_camera_ ||
(config_.has_debug_draw_coordinate_frames() &&
!config_.debug_draw_coordinate_frames())) {
return;
}
try {
// AprilTagPerception owns mutable frame/detector state. Never share
// the PBVS instance with the display worker.
auto overlay_perception =
std::make_shared<perception::AprilTagPerception>(external_camera_);
overlay_perception->setTagSize(config_.perception().tags().screen().size_m());
{
std::lock_guard<std::mutex> lock(coordinate_overlay_mutex_);
coordinate_overlay_stop_ = false;
coordinate_overlay_enabled_ = phase_ != Phase::ALIGNING;
}
coordinate_overlay_thread_ = std::thread(
&TouchScreenTask::coordinateOverlayLoop, this, std::move(overlay_perception));
} catch (const std::exception& e) {
CMVR_LOG(WARNING) << "[TouchScreenTask] Failed to start coordinate overlay worker: "
<< e.what();
}
}
void TouchScreenTask::stopCoordinateOverlayWorker()
{
{
std::lock_guard<std::mutex> lock(coordinate_overlay_mutex_);
coordinate_overlay_stop_ = true;
}
coordinate_overlay_cv_.notify_all();
if (coordinate_overlay_thread_.joinable()) {
coordinate_overlay_thread_.join();
}
}
void TouchScreenTask::setCoordinateOverlayEnabled(const bool enabled)
{
{
std::lock_guard<std::mutex> lock(coordinate_overlay_mutex_);
coordinate_overlay_enabled_ = enabled;
}
coordinate_overlay_cv_.notify_all();
}
void TouchScreenTask::coordinateOverlayLoop(
std::shared_ptr<perception::AprilTagPerception> overlay_perception)
{
perception::AprilTagPerception::Options options;
options.depth_policy = perception::AprilTagPerception::DepthPolicy::NONE;
options.detect_tags = true;
options.fetch_encoded = false;
const auto refresh_period =
std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(1.0 / 30.0));
std::unique_lock<std::mutex> lock(coordinate_overlay_mutex_);
while (true) {
coordinate_overlay_cv_.wait(lock, [this] {
return coordinate_overlay_stop_ || coordinate_overlay_enabled_;
});
if (coordinate_overlay_stop_) {
break;
}
const auto next_refresh = Clock::now() + refresh_period;
lock.unlock();
// No task/worker lock is held during camera acquisition or tag detection.
try {
overlay_perception->update(options);
const auto overlay = buildCoordinateOverlay(overlay_perception.get());
std::lock_guard<std::mutex> publish_lock(coordinate_overlay_mutex_);
// ALIGNING publishes its own perception snapshot. Discard an
// in-flight display frame if alignment or shutdown has started.
if (!coordinate_overlay_stop_ && coordinate_overlay_enabled_) {
external_camera_->setStreamOverlay(overlay);
}
} catch (const std::exception& e) {
CMVR_LOG_EVERY_N(WARNING, 30)
<< "[TouchScreenTask] Coordinate overlay refresh failed: " << e.what();
} catch (...) {
CMVR_LOG_EVERY_N(WARNING, 30)
<< "[TouchScreenTask] Coordinate overlay refresh failed: unknown exception";
}
lock.lock();
coordinate_overlay_cv_.wait_until(lock, next_refresh, [this] {
return coordinate_overlay_stop_ || !coordinate_overlay_enabled_;
});
}
}
void TouchScreenTask::stop() {
std::lock_guard<std::mutex> lock(mutex_);
stopUnlocked();
stopCoordinateOverlayWorker();
}
void TouchScreenTask::stopUnlocked() {
@ -599,7 +451,6 @@ void TouchScreenTask::stopUnlocked() {
pbvs_.resetTwistCommandState();
phase_ = Phase::IDLE;
setCoordinateOverlayEnabled(true);
resetRunState();
last_status_ = Status::STOPPED;
}
@ -904,7 +755,6 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig&
screen_tag.id() == hand_tag.id() ||
!std::isfinite(screen_tag.size_m()) || screen_tag.size_m() <= 0.0 ||
!std::isfinite(hand_tag.size_m()) || hand_tag.size_m() <= 0.0 ||
std::abs(screen_tag.size_m() - hand_tag.size_m()) > 1e-12 ||
config.devices().camera_id().empty() ||
config.devices().external_camera_id().empty() ||
!isHomogeneousTransform(T_H_P) ||
@ -1048,8 +898,8 @@ bool TouchScreenTask::applyConfig() {
const auto& hand_camera_config = perception.hand_camera();
const auto& calibration = config_.alignment().calibration();
const auto& pbvs = config_.alignment().pbvs();
perception_->setTagSize(tags.screen().size_m());
external_perception_->setTagSize(tags.screen().size_m());
configureTagSizes(*perception_, tags);
configureTagSizes(*external_perception_, tags);
tracker_.setTargetPointMethod(toTargetPointMethod(hand_camera_config.target_point_method()));
tcp_pose_tracker_.setPerception(external_perception_);
tcp_pose_tracker_.setScreenTagId(tags.screen().id());
@ -1337,7 +1187,6 @@ bool TouchScreenTask::updateAlignmentTcpPose() {
external_options.detect_tags = true;
external_options.fetch_encoded = false;
const bool perception_ok = external_perception_->update(external_options);
publishCoordinateOverlay();
if (!perception_ok) {
stopPbvsMotion();
align_stable_count_ = 0;
@ -1586,7 +1435,6 @@ bool TouchScreenTask::applyAlignmentCommand(const PbvsController::Output& output
<< output.rotation_error_G.z() << "]";
stopPbvsMotion();
phase_ = Phase::ALIGN_REACHED;
setCoordinateOverlayEnabled(true);
phase_start_time_ = Clock::now();
touch_command_started_ = false;
last_status_ = Status::ALIGN_REACHED;
@ -1935,10 +1783,30 @@ bool TouchScreenTask::initializeHead(const std::shared_ptr<device::RobotArm>& he
command.position.push_back(it->second);
targets.erase(it);
}
if (!head->isConnected() || head->isEmergencyStopped() ||
head->isProtectiveStopped() || head->isFault() || head->busy()) {
const auto read_ready_state = [&](device::ArmState& state) {
if (!head->isConnected() || head->isEmergencyStopped() ||
head->isProtectiveStopped() || head->isFault() || head->busy()) {
return false;
}
state = head->getRobotState();
return state.connected && !state.emergency_stopped && !state.protective_stopped &&
!state.fault && !state.moving;
};
device::ArmState state;
if (!read_ready_state(state)) {
return fail(Status::ROBOT_COMMAND_FAILED, "head is disconnected, stopped, faulted or busy");
}
if (!state.powered_on) {
CMVR_LOG(INFO) << "[TouchScreenTask][HEAD_INIT] torqueOn start, head="
<< config_.devices().head_id();
const auto enabled = head->torqueOn();
if (!enabled.ok()) {
return fail(Status::ROBOT_COMMAND_FAILED, "torqueOn failed: " + enabled.message);
}
if (!read_ready_state(state) || !state.powered_on) {
return fail(Status::ROBOT_COMMAND_FAILED, "head did not report ready and enabled after torqueOn");
}
}
device::MotionOptions options;
options.velocity = head_init.velocity();
@ -1953,7 +1821,7 @@ bool TouchScreenTask::initializeHead(const std::shared_ptr<device::RobotArm>& he
} catch (const std::exception& error) {
return fail(Status::ROBOT_COMMAND_FAILED, error.what());
} catch (...) {
return fail(Status::ROBOT_COMMAND_FAILED, "unknown moveJ initialization error");
return fail(Status::ROBOT_COMMAND_FAILED, "unknown head initialization error");
}
}
@ -2183,7 +2051,6 @@ void TouchScreenTask::enterFailed(const Status status) {
<< ", max_forward_after_retract_mm=" << max_forward_after_retract_m_ * 1000.0;
}
phase_ = Phase::FAILED;
setCoordinateOverlayEnabled(true);
touch_command_started_ = false;
retract_command_started_ = false;
last_status_ = status;

View File

@ -37,6 +37,8 @@
#include "devices/camera/mujoco_camera/include/mujoco_camera.h"
#include "devices/motor/manager/include/motor_manager.h"
#include "manager/device_manager/include/device_manager.h"
#include "manager/media_source_hub/include/camera_coordinate_overlay.h"
#include "manager/media_source_hub/include/device_media_source_adapter.h"
#include "manager/task_manager/include/task_manager.h"
#include "service/grpc/include/grpc_dexhand_service.h"
#include "service/grpc/include/grpc_system_service.h"
@ -161,6 +163,19 @@ cmvr::config::TouchScreenTaskConfig loadMujocoTouchConfig(const std::filesystem:
return root_config.touch_screen_task();
}
cv::Mat makeAlignmentTagFrame()
{
cv::Mat frame(480, 640, CV_8UC3, cv::Scalar::all(255));
const auto tag_directory = findProjectRoot() / "model/april_tag";
for (const auto& [file, x] : {std::pair{"tag36_11_00001.png", 100}, {"tag36_11.png", 380}}) {
const cv::Mat tag = cv::imread((tag_directory / file).string());
if (tag.empty()) return {};
const cv::Rect roi(x, 160, 160, 160);
cv::resize(tag, frame(roi), roi.size(), 0, 0, cv::INTER_NEAREST);
}
return frame;
}
class FailureReturnCamera final : public cmvr::device::AbstractCamera {
public:
std::string typeName() const override { return "FailureReturnCamera"; }
@ -172,6 +187,60 @@ public:
cv::Mat frame;
};
class OverlayCamera final : public cmvr::device::AbstractCamera {
public:
explicit OverlayCamera(cv::Mat frame)
: frame_(std::move(frame)), blank_frame_(frame_.size(), frame_.type(), cv::Scalar::all(255)) {
id_ = "overlay_camera";
}
std::string typeName() const override { return "OverlayCamera"; }
bool startStreaming() override {
++stream_starts;
return true;
}
void stopStreaming() override { ++stream_stops; }
void getState(cmvr::device::CameraState& state) override {
state = {};
state.is_initialized = true;
state.is_opened = true;
}
void getRGBImage(cv::Mat& color, cmvr::device::Rs2Intrinsics& intrinsics) override {
color = frame_;
intrinsics = {320, 240, 600, 600};
++rgb_reads;
}
bool waitEncodedFrame(cmvr::device::StreamFrameData& frame, size_t& cursor,
std::chrono::milliseconds timeout) override {
std::this_thread::sleep_for(std::min(timeout, std::chrono::milliseconds(10)));
const auto epoch = stream_starts.load();
if (epoch == stream_stops.load()) return false;
frame = {};
frame.rgbImage = show_tags.load() ? frame_ : blank_frame_;
frame.rgbFrame = {0x00, 0x00, 0x00, 0x01, 0x65, 0x88};
frame.intrinsics = {320, 240, 600, 600};
frame.width = frame_.cols;
frame.height = frame_.rows;
frame.fps = 30;
frame.bKey = true;
frame.stream_epoch = epoch;
frame.sequence = cursor++;
frame.time_base_den = frame.fps;
frame.capture_monotonic_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
return true;
}
std::atomic<bool> show_tags{true};
std::atomic<std::uint64_t> stream_starts{0};
std::atomic<std::uint64_t> stream_stops{0};
std::atomic<int> rgb_reads{0};
private:
const cv::Mat frame_;
const cv::Mat blank_frame_;
};
class ScriptedTouch final : public cmvr::device::AbstractTouch {
public:
std::string typeName() const override { return "ScriptedTouch"; }
@ -206,7 +275,17 @@ public:
std::string typeName() const override { return "FailureReturnArm"; }
cmvr::RobotModel getRobotModel() const override { return model; }
std::size_t getDof() const override { return model.dof; }
cmvr::device::ArmState getRobotState() const override { return {}; }
cmvr::device::ArmState getRobotState() const override {
cmvr::device::ArmState snapshot;
snapshot.connected = connected;
snapshot.powered_on = powered_on;
snapshot.moving = motion_busy;
snapshot.fault = planning_fault;
snapshot.emergency_stopped = emergency;
snapshot.protective_stopped = protective;
snapshot.safety_mode = getSafetyMode();
return snapshot;
}
cmvr::device::JointGroupState getJointState() const override { return state; }
cmvr::device::CartesianPose getTcpPose(cmvr::device::FrameType) const override { return {}; }
cmvr::device::RobotMode getRobotMode() const override { return cmvr::device::RobotMode::Idle; }
@ -252,7 +331,13 @@ public:
return move_result;
}
Result torqueOn() override { return unsupported(); }
Result torqueOn() override {
if (!torque_on_result) return unsupported();
calls.push_back("torqueOn");
if (torque_on_throws) throw std::runtime_error("injected torqueOn exception");
if (torque_on_result->ok() && confirm_torque_on) powered_on = true;
return *torque_on_result;
}
Result moveP(const cmvr::device::CartesianPose&, const cmvr::device::MotionOptions&,
cmvr::device::FrameType) override { return unsupported(); }
Result torqueOff() override { return unsupported(); }
@ -301,12 +386,16 @@ public:
Result stop_result{Result::success()};
Result move_result{Result::success()};
Result recovery_result{Result::success()};
std::optional<Result> torque_on_result;
bool planning_fault{false};
bool connected{true};
bool powered_on{false};
bool confirm_torque_on{true};
bool emergency{false};
bool protective{false};
bool motion_busy{false};
bool move_j_throws{false};
bool torque_on_throws{false};
int stop_l_calls{0};
std::vector<std::string> calls;
std::vector<double> return_target;
@ -351,6 +440,27 @@ protected:
EXPECT_EQ(arm->calls, calls) << "failure return must run only once";
}
bool configureSuccessfulTouch() {
auto* alignment = config.mutable_alignment();
alignment->set_stable_frames(1);
alignment->set_timeout_s(10);
alignment->set_pause_when_reached(false);
alignment->mutable_target()->set_mode(cmvr::config::TOUCH_SCREEN_ALIGN_MODE_POSITION_ONLY);
auto* threshold = alignment->mutable_error_threshold();
threshold->set_x(1.0);
threshold->set_y(1.0);
threshold->set_z(1.0);
auto* touch_move = config.mutable_touch()->mutable_move_l();
if (!google::protobuf::TextFormat::ParseFromString(R"(
direction_tool { x: 1 y: 0 z: 0 rx: 0 ry: 0 rz: 0 }
distance_m: 0.01 velocity: 0.1 acceleration: 0.1 jerk: 1
)", touch_move)) {
return false;
}
for (std::size_t i = 0; i < arm->getDof(); ++i) touch_move->add_joint_velocity_limits(1.0);
return true;
}
cmvr::config::TouchScreenTaskConfig config;
std::shared_ptr<FailureReturnArm> arm;
};
@ -380,6 +490,7 @@ protected:
arm = std::make_shared<FailureReturnArm>(config);
head = std::make_shared<FailureReturnArm>(config);
head->torque_on_result = cmvr::device::Result::success();
head->model.joint_names = {"neck-joint1", "neck-joint2"};
head->model.dof = 2;
head->state.position = {0.0, 0.0};
@ -641,29 +752,10 @@ TEST_F(TouchScreenFailureReturnTest, SelectedMethodAppliesBeforeStartAndAfterFai
TEST_F(TouchScreenFailureReturnTest, SelectedMethodAppliesAfterFinishWhenEnabled) {
using Init = cmvr::config::TouchScreenTaskInitializationConfig;
const auto camera = std::make_shared<FailureReturnCamera>();
camera->frame = cv::Mat(480, 640, CV_8UC3, cv::Scalar::all(255));
const auto tag_directory = findProjectRoot() / "model/april_tag";
for (const auto& [file, x] : {std::pair{"tag36_11_00001.png", 100}, {"tag36_11.png", 380}}) {
const cv::Mat tag = cv::imread((tag_directory / file).string());
ASSERT_FALSE(tag.empty()) << file;
const cv::Rect roi(x, 160, 160, 160);
cv::resize(tag, camera->frame(roi), roi.size(), 0, 0, cv::INTER_NEAREST);
}
camera->frame = makeAlignmentTagFrame();
ASSERT_FALSE(camera->frame.empty());
config.set_debug_draw_coordinate_frames(false);
auto* alignment = config.mutable_alignment();
alignment->set_stable_frames(1);
alignment->set_timeout_s(10);
alignment->mutable_target()->set_mode(cmvr::config::TOUCH_SCREEN_ALIGN_MODE_POSITION_ONLY);
auto* threshold = alignment->mutable_error_threshold();
threshold->set_x(1.0);
threshold->set_y(1.0);
threshold->set_z(1.0);
auto* touch_move = config.mutable_touch()->mutable_move_l();
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
direction_tool { x: 1 y: 0 z: 0 rx: 0 ry: 0 rz: 0 }
distance_m: 0.01 velocity: 0.1 acceleration: 0.1 jerk: 1
)", touch_move));
for (std::size_t i = 0; i < arm->getDof(); ++i) touch_move->add_joint_velocity_limits(1.0);
ASSERT_TRUE(configureSuccessfulTouch());
// Click the screen tag. Relaxed alignment tolerances let the two fixed
// tag images drive a successful touch without simulating arm motion.
@ -885,12 +977,13 @@ TEST_F(TouchScreenHeadInitializationTest, AbsentOrDisabledConfigurationDoesNotCo
}
}
TEST_F(TouchScreenHeadInitializationTest, MovesOnlyHeadOnceInModelJointOrderWithConfiguredLimits) {
TEST_F(TouchScreenHeadInitializationTest, EnablesAndMovesOnlyHeadOnceInModelJointOrderWithConfiguredLimits) {
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::IDLE);
EXPECT_EQ(task.phase(), cmvr::task::TouchScreenTask::Phase::IDLE);
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_EQ(head->calls, (std::vector<std::string>{"torqueOn", "moveJ"}));
EXPECT_TRUE(head->powered_on);
EXPECT_EQ(head->startup_target, (std::vector<double>{-0.2, 0.15}));
EXPECT_DOUBLE_EQ(head->startup_options.velocity, 0.25);
EXPECT_DOUBLE_EQ(head->startup_options.acceleration, 0.5);
@ -899,13 +992,21 @@ TEST_F(TouchScreenHeadInitializationTest, MovesOnlyHeadOnceInModelJointOrderWith
EXPECT_EQ(arm->stop_l_calls, 0);
}
TEST_F(TouchScreenHeadInitializationTest, AlreadyEnabledHeadMovesWithoutRepeatEnable) {
head->powered_on = true;
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_TRUE(arm->calls.empty());
}
TEST_F(TouchScreenHeadInitializationTest, RepeatedTouchRequestsDoNotRepeatHeadInitialization) {
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera, head));
ASSERT_TRUE(task.touch(320, 240));
task.stop();
ASSERT_TRUE(task.touch(350, 260));
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_EQ(head->calls, (std::vector<std::string>{"torqueOn", "moveJ"}));
EXPECT_EQ(head->stop_l_calls, 0);
EXPECT_EQ(arm->calls, (std::vector<std::string>{
"stopMotion", "recoverSpeedLPlanningFault",
@ -1021,10 +1122,40 @@ TEST_F(TouchScreenHeadInitializationTest, UnavailableHeadFailsWithoutRecoveryOrM
}
}
TEST_F(TouchScreenHeadInitializationTest, FailedOrThrowingHeadEnablePreventsMotionAndTaskInitialization) {
for (const bool throws : {false, true}) {
SCOPED_TRACE(throws);
head->calls.clear();
head->torque_on_throws = throws;
head->torque_on_result = cmvr::device::Result::failure(
cmvr::device::ArmErrorCode::CommandFailed, "injected head enable failure");
cmvr::task::TouchScreenTask task(config);
EXPECT_FALSE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ROBOT_COMMAND_FAILED);
EXPECT_EQ(task.phase(), cmvr::task::TouchScreenTask::Phase::FAILED);
EXPECT_EQ(head->calls, std::vector<std::string>{"torqueOn"});
EXPECT_TRUE(arm->calls.empty());
EXPECT_FALSE(task.touch(320, 240));
EXPECT_EQ(head->calls, std::vector<std::string>{"torqueOn"});
EXPECT_TRUE(arm->calls.empty());
}
}
TEST_F(TouchScreenHeadInitializationTest, UnconfirmedHeadEnablePreventsMotionAndTaskInitialization) {
head->confirm_torque_on = false;
cmvr::task::TouchScreenTask task(config);
EXPECT_FALSE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ROBOT_COMMAND_FAILED);
EXPECT_EQ(task.phase(), cmvr::task::TouchScreenTask::Phase::FAILED);
EXPECT_EQ(head->calls, std::vector<std::string>{"torqueOn"});
EXPECT_TRUE(arm->calls.empty());
}
TEST_F(TouchScreenHeadInitializationTest, FailedOrThrowingHeadMovePreventsTaskInitialization) {
for (const bool throws : {false, true}) {
SCOPED_TRACE(throws);
head->calls.clear();
head->powered_on = false;
head->move_j_throws = throws;
head->move_result = cmvr::device::Result::failure(
cmvr::device::ArmErrorCode::CommandFailed, "injected head move failure");
@ -1032,12 +1163,12 @@ TEST_F(TouchScreenHeadInitializationTest, FailedOrThrowingHeadMovePreventsTaskIn
EXPECT_FALSE(task.init(arm, nullptr, camera, camera, head));
EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ROBOT_COMMAND_FAILED);
EXPECT_EQ(task.phase(), cmvr::task::TouchScreenTask::Phase::FAILED);
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_EQ(head->calls, (std::vector<std::string>{"torqueOn", "moveJ"}));
EXPECT_EQ(head->stop_l_calls, 0);
EXPECT_TRUE(arm->calls.empty());
EXPECT_EQ(arm->stop_l_calls, 0);
EXPECT_FALSE(task.touch(320, 240));
EXPECT_EQ(head->calls, std::vector<std::string>{"moveJ"});
EXPECT_EQ(head->calls, (std::vector<std::string>{"torqueOn", "moveJ"}));
EXPECT_TRUE(arm->calls.empty());
}
}
@ -1132,6 +1263,114 @@ TEST(TouchScreenTaskTest, ConfigFilesUseStructuredSchema) {
}
}
TEST(TouchScreenTaskTest, EstimatesPoseForDifferentTagSizes) {
const auto project_root = findProjectRoot();
auto config = loadMujocoTouchConfig(project_root);
config.set_debug_draw_coordinate_frames(false);
auto* tags = config.mutable_perception()->mutable_tags();
tags->mutable_screen()->set_id(1);
tags->mutable_screen()->set_size_m(0.030);
tags->mutable_hand()->set_id(2);
tags->mutable_hand()->set_size_m(0.025);
const auto tag_dir = project_root / "model/april_tag";
const auto screen = cv::imread((tag_dir / "tag36_11_00001.png").string(), cv::IMREAD_GRAYSCALE);
const auto hand = cv::imread((tag_dir / "tag36_11_00002_1000.png").string(), cv::IMREAD_GRAYSCALE);
ASSERT_FALSE(screen.empty());
ASSERT_FALSE(hand.empty());
const auto camera = std::make_shared<FailureReturnCamera>();
camera->frame = cv::Mat(480, 640, CV_8UC1, cv::Scalar(255));
// The black borders span 80% of the images. At 96 px and 80 px,
// both tags should be 187.5 mm from the camera with a 600 px focal length.
cv::resize(screen, camera->frame(cv::Rect(140, 180, 120, 120)),
cv::Size(120, 120), 0, 0, cv::INTER_NEAREST);
cv::resize(hand, camera->frame(cv::Rect(380, 190, 100, 100)),
cv::Size(100, 100), 0, 0, cv::INTER_NEAREST);
cmvr::task::TouchScreenTask task(config);
const auto arm = std::make_shared<FailureReturnArm>(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera));
for (const auto& perception : {task.perception(), task.externalPerception()}) {
ASSERT_TRUE(perception->update({}));
const auto* screen_tag = perception->findTag(tags->screen().id());
const auto* hand_tag = perception->findTag(tags->hand().id());
ASSERT_NE(screen_tag, nullptr);
ASSERT_NE(hand_tag, nullptr);
EXPECT_NEAR(screen_tag->T_c_t(2, 3), 0.1875, 0.003);
EXPECT_NEAR(hand_tag->T_c_t(2, 3), 0.1875, 0.003);
}
}
TEST_F(TouchScreenFailureReturnTest, CoordinateOverlayFollowsVideoSubscriptions) {
const auto frame = makeAlignmentTagFrame();
ASSERT_FALSE(frame.empty());
const auto camera = std::make_shared<OverlayCamera>(frame);
cmvr::task::TouchScreenTask task(config);
ASSERT_TRUE(task.init(arm, nullptr, camera, camera));
cmvr::media::MediaSourceHub hub;
cmvr::media::CameraCoordinateOverlayConfig overlay_config;
const auto& tags = config.perception().tags();
overlay_config.screen_tag_id = tags.screen().id();
overlay_config.screen_tag_size_m = tags.screen().size_m();
overlay_config.hand_tag_id = tags.hand().id();
overlay_config.hand_tag_size_m = tags.hand().size_m();
overlay_config.axis_length_m = 0.03;
ASSERT_TRUE(cmvr::media::ensureCameraMediaSource(hub, camera, 64, &overlay_config));
const auto track = cmvr::media::cameraColorTrackId(camera->id());
const auto wait_for = [](const auto& ready) {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
while (!ready() && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
return ready();
};
const auto has_both_tags = [&] {
const auto overlay = camera->streamOverlay();
return overlay.draw_coordinate_frames && overlay.coordinate_frames.size() == 2;
};
EXPECT_EQ(camera->stream_starts.load(), 0);
EXPECT_TRUE(camera->streamOverlay().coordinate_frames.empty());
auto first = hub.subscribe(track);
ASSERT_TRUE(first);
ASSERT_TRUE(first.waitRead(std::chrono::seconds(2)).has_value());
ASSERT_TRUE(wait_for(has_both_tags));
const auto overlay = camera->streamOverlay();
EXPECT_DOUBLE_EQ(overlay.coordinate_axis_length_m, 0.03);
EXPECT_EQ(overlay.coordinate_frames.front().tag_id, tags.screen().id());
EXPECT_EQ(overlay.coordinate_frames.front().label, "G");
EXPECT_EQ(overlay.coordinate_frames.back().tag_id, tags.hand().id());
EXPECT_EQ(overlay.coordinate_frames.back().label, "H");
task.stop();
EXPECT_TRUE(has_both_tags());
auto second = hub.subscribe(track);
ASSERT_TRUE(second);
EXPECT_EQ(camera->stream_starts.load(), 1);
first.reset();
EXPECT_EQ(camera->stream_stops.load(), 0);
ASSERT_TRUE(second.waitRead(std::chrono::seconds(2)).has_value());
camera->show_tags.store(false);
ASSERT_TRUE(wait_for([&] { return camera->streamOverlay().coordinate_frames.empty(); }));
camera->show_tags.store(true);
ASSERT_TRUE(wait_for(has_both_tags));
second.reset();
EXPECT_EQ(camera->stream_stops.load(), 1);
EXPECT_TRUE(camera->streamOverlay().coordinate_frames.empty());
auto after_reconnect = hub.subscribe(track);
ASSERT_TRUE(after_reconnect);
ASSERT_TRUE(wait_for(has_both_tags));
after_reconnect.reset();
EXPECT_EQ(camera->stream_starts.load(), 2);
EXPECT_EQ(camera->stream_stops.load(), 2);
EXPECT_TRUE(camera->streamOverlay().coordinate_frames.empty());
EXPECT_EQ(camera->rgb_reads.load(), 0);
}
TEST(TouchScreenTaskTest, MotorArmConfigurationsSupportMoveP) {
const auto project_root = findProjectRoot();
ASSERT_FALSE(project_root.empty());