diff --git a/docs/extensions/index.md b/docs/extensions/index.md index 74935733..4765048b 100644 --- a/docs/extensions/index.md +++ b/docs/extensions/index.md @@ -17,4 +17,5 @@ rcs_usb_cam rcs_tacto rcs_robotiq2f85 rcs_zed +rcs_webui ``` diff --git a/docs/extensions/rcs_webui.md b/docs/extensions/rcs_webui.md new file mode 100644 index 00000000..db96809e --- /dev/null +++ b/docs/extensions/rcs_webui.md @@ -0,0 +1,5 @@ +# RCS Web Interface + +```{include} ../../extensions/rcs_webui/README.md +:start-line: 1 +``` diff --git a/extensions/rcs_fr3/src/hw/ControlStateBuffer.h b/extensions/rcs_fr3/src/hw/ControlStateBuffer.h new file mode 100644 index 00000000..6bc5f69a --- /dev/null +++ b/extensions/rcs_fr3/src/hw/ControlStateBuffer.h @@ -0,0 +1,207 @@ +#ifndef RCS_FRANKA_CONTROL_STATE_BUFFER_H +#define RCS_FRANKA_CONTROL_STATE_BUFFER_H + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rcs { +namespace hw { + +/** + * @brief One sample of the robot state as seen by the 1 kHz control loop. + * + * Plain old data so that it can be copied into a preallocated ring buffer + * without any allocation inside the real-time loop. + */ +struct ControlStateSample { + // host wall clock in seconds since epoch (same clock as Python's + // time.time()), taken when the sample was recorded + double timestamp = 0.0; + // robot clock in seconds (franka::RobotState::time) + double robot_time = 0.0; + std::array q{}; + std::array dq{}; + std::array tau_J{}; + std::array tau_J_d{}; + std::array dtau_J{}; + std::array tau_ext_hat_filtered{}; + std::array O_F_ext_hat_K{}; + std::array K_F_ext_hat_K{}; + // column major 4x4 end effector pose in base frame + std::array O_T_EE{}; + double control_command_success_rate = 0.0; + // franka::RobotMode as integer + int32_t robot_mode = 0; + // bit i is set if error i of franka::Errors is active + uint64_t current_errors = 0; + uint64_t last_motion_errors = 0; +}; + +// number of error flags in franka::Errors +constexpr size_t kNumFrankaErrors = 41; +static_assert(kNumFrankaErrors <= 64, "errors must fit into a uint64 mask"); + +/** + * @brief Packs the error flags of franka::Errors into a bit mask. + * + * franka::Errors only exposes its flags as references into a private + * std::array, bound in declaration order. The first reference + * therefore points to the start of that array. + */ +inline uint64_t ErrorsToMask(const franka::Errors& errors) noexcept { + const bool* flags = &errors.joint_position_limits_violation; + uint64_t mask = 0; + for (size_t i = 0; i < kNumFrankaErrors; ++i) { + if (flags[i]) { + mask |= (uint64_t{1} << i); + } + } + return mask; +} + +/** + * @brief Names of the error flags, index i corresponds to bit i of the masks. + */ +inline std::vector ErrorNames() { + std::vector names; + names.reserve(kNumFrankaErrors); + for (size_t i = 0; i < kNumFrankaErrors; ++i) { + std::array flags{}; + flags[i] = true; + // format is ["name"] + std::string name; + for (char c : static_cast(franka::Errors(flags))) { + if (c != '[' && c != ']' && c != '"') { + name.push_back(c); + } + } + names.push_back(name); + } + return names; +} + +inline void FillSample(const franka::RobotState& state, + ControlStateSample& sample) noexcept { + sample.timestamp = std::chrono::duration( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + sample.robot_time = state.time.toSec(); + sample.q = state.q; + sample.dq = state.dq; + sample.tau_J = state.tau_J; + sample.tau_J_d = state.tau_J_d; + sample.dtau_J = state.dtau_J; + sample.tau_ext_hat_filtered = state.tau_ext_hat_filtered; + sample.O_F_ext_hat_K = state.O_F_ext_hat_K; + sample.K_F_ext_hat_K = state.K_F_ext_hat_K; + sample.O_T_EE = state.O_T_EE; + sample.control_command_success_rate = state.control_command_success_rate; + sample.robot_mode = static_cast(state.robot_mode); + sample.current_errors = ErrorsToMask(state.current_errors); + sample.last_motion_errors = ErrorsToMask(state.last_motion_errors); +} + +/** + * @brief Single producer single consumer lock-free ring buffer of + * ControlStateSample. + * + * The producer is the 1 kHz control thread (push), the consumer is the + * Python env step (drain). All memory is allocated in the constructor, push + * neither allocates nor locks. If the consumer does not drain in time the + * newest samples are dropped and counted. + */ +class ControlStateBuffer { + public: + // 8192 samples are > 8 s at 1 kHz, much longer than one env step + static constexpr size_t kDefaultCapacity = 8192; + + explicit ControlStateBuffer(size_t capacity = kDefaultCapacity) + : m_capacity(RoundUpPow2(capacity)), + m_mask(m_capacity - 1), + m_samples(std::make_unique(m_capacity)) {} + + ControlStateBuffer(const ControlStateBuffer&) = delete; + ControlStateBuffer& operator=(const ControlStateBuffer&) = delete; + + size_t capacity() const noexcept { return m_capacity; } + + /// producer side, real-time safe + bool push(const franka::RobotState& state) noexcept { + const size_t head = m_head.load(std::memory_order_relaxed); + const size_t tail = m_tail.load(std::memory_order_acquire); + if (head - tail >= m_capacity) { + m_dropped.fetch_add(1, std::memory_order_relaxed); + return false; + } + FillSample(state, m_samples[head & m_mask]); + m_head.store(head + 1, std::memory_order_release); + return true; + } + + /// consumer side: number of samples ready to be drained + size_t size() const noexcept { + return m_head.load(std::memory_order_acquire) - + m_tail.load(std::memory_order_relaxed); + } + + /** + * @brief consumer side: calls fn(index, sample) for every available sample + * in order and frees them. Returns the number of drained samples. + */ + template + size_t drain(Fn&& fn, size_t max_samples) { + const size_t tail = m_tail.load(std::memory_order_relaxed); + const size_t head = m_head.load(std::memory_order_acquire); + size_t n = head - tail; + if (n > max_samples) { + n = max_samples; + } + for (size_t i = 0; i < n; ++i) { + fn(i, m_samples[(tail + i) & m_mask]); + } + m_tail.store(tail + n, std::memory_order_release); + return n; + } + + /// consumer side: discard all available samples + void clear() noexcept { + m_tail.store(m_head.load(std::memory_order_acquire), + std::memory_order_release); + } + + /// number of samples dropped since the last call, resets the counter + uint64_t take_dropped() noexcept { + return m_dropped.exchange(0, std::memory_order_relaxed); + } + + private: + static size_t RoundUpPow2(size_t v) { + size_t p = 1; + while (p < v) { + p <<= 1; + } + return p; + } + + const size_t m_capacity; + const size_t m_mask; + std::unique_ptr m_samples; + // separate cache lines for producer and consumer indices + alignas(64) std::atomic m_head{0}; + alignas(64) std::atomic m_tail{0}; + alignas(64) std::atomic m_dropped{0}; +}; + +} // namespace hw +} // namespace rcs + +#endif // RCS_FRANKA_CONTROL_STATE_BUFFER_H diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index ca34468d..9839491f 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -35,6 +35,7 @@ Franka::Franka(const FrankaConfig& cfg, m_ik(ik), robot(cfg.ip, cfg.ignore_realtime ? franka::RealtimeConfig::kIgnore : franka::RealtimeConfig::kEnforce) { + this->m_record_control_states.store(cfg.record_control_states); // set collision behavior and impedance this->set_default_robot_behavior(); this->set_guiding_mode(true, true, true, true, true, true, true); @@ -56,6 +57,7 @@ Franka::~Franka() { bool Franka::set_config(const FrankaConfig& cfg) { this->m_cfg = cfg; this->m_cfg.speed_factor = std::min(std::max(cfg.speed_factor, 0.0), 1.0); + this->m_record_control_states.store(cfg.record_control_states); if (this->m_cfg.load_parameters.has_value()) { auto load_value = &(this->m_cfg.load_parameters.value()); @@ -177,6 +179,34 @@ void PInverse(const Eigen::MatrixXd& M, Eigen::MatrixXd& M_inv, M_inv = Eigen::MatrixXd(svd.matrixV() * S_inv * svd.matrixU().transpose()); } +// Joint-limit guard shared by the torque controllers, see +// FrankaConfig::joint_limit_*: velocity braking towards a limit within the +// avoidance band, no torque towards a limit within the stop margin. +void JointLimitGuardFn(Eigen::Matrix& tau, + const Eigen::Matrix& q, + const Eigen::Matrix& dq, + const Eigen::Array& q_min, + const Eigen::Array& q_max, + const common::Vector7d& stop_margin, + const common::Vector7d& avoid_margin, + const common::Vector7d& damping) { + for (int i = 0; i < 7; i++) { + const double d_max = q_max[i] - q[i]; + const double d_min = q[i] - q_min[i]; + const double band = std::max(avoid_margin[i] - stop_margin[i], 1e-6); + if (d_max < avoid_margin[i] && dq[i] > 0.) { + tau[i] -= damping[i] * + std::clamp((avoid_margin[i] - d_max) / band, 0., 1.) * dq[i]; + } + if (d_min < avoid_margin[i] && dq[i] < 0.) { + tau[i] -= damping[i] * + std::clamp((avoid_margin[i] - d_min) / band, 0., 1.) * dq[i]; + } + if (d_max < stop_margin[i] && tau[i] > 0.) tau[i] = 0.; + if (d_min < stop_margin[i] && tau[i] < 0.) tau[i] = 0.; + } +} + void TorqueSafetyGuardFn(std::array& tau_d_array, const common::Vector7d& torque_limit) { for (size_t i = 0; i < tau_d_array.size(); i++) { @@ -269,6 +299,13 @@ void Franka::controller_set_joint_position(const common::Vector7d& desired_q) { } } +void Franka::record_control_state( + const franka::RobotState& robot_state) noexcept { + if (this->m_record_control_states.load(std::memory_order_relaxed)) { + this->m_control_states.push(robot_state); + } +} + void Franka::check_for_background_errors() { std::exception_ptr ex = this->background_exception.load_and_clear(); if (ex) { @@ -399,6 +436,9 @@ void Franka::osc() { const Eigen::Vector3d kp_p_cfg = this->m_cfg.kp_p; const double kp_r_cfg = this->m_cfg.kp_r; const common::Vector7d torque_limit = this->m_cfg.torque_limit; + const common::Vector7d stop_margin = this->m_cfg.joint_limit_stop_margin; + const common::Vector7d avoid_margin = this->m_cfg.joint_limit_avoid_margin; + const common::Vector7d limit_damping = this->m_cfg.joint_limit_damping; const bool allow_high_collision = this->m_cfg.allow_high_collision; this->controller_time = 0.0; @@ -447,8 +487,9 @@ void Franka::osc() { // The manual residual mass matrix to add on the internal mass matrix residual_mass_vec_ << 0.0, 0.0, 0.0, 0.0, 0.1, 0.5, 0.5; - joint_max_ << 2.8978, 1.7628, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973; - joint_min_ << -2.8973, -1.7628, -2.8973, -3.0718, -2.8973, -0.0175, -2.8973; + // joint limits of the configured robot (were hard coded Panda limits) + joint_min_ = this->m_cfg.joint_limits.row(0).head<7>().transpose().array(); + joint_max_ = this->m_cfg.joint_limits.row(1).head<7>().transpose().array(); avoidance_weights_ << 1., 1., 1., 1., 1., 10., 10.; try { @@ -474,6 +515,7 @@ void Franka::osc() { int traj_rate = 500; this->curr_state.store(robot_state); + this->record_control_state(robot_state); this->interpolator_mutex.lock(); this->controller_time += period.toSec(); @@ -590,16 +632,21 @@ void Franka::osc() { dist2joint_min = q - joint_min_.matrix(); for (int i = 0; i < 7; i++) { - if (dist2joint_max[i] < 0.25 && dist2joint_max[i] > 0.1) + if (dist2joint_max[i] < avoid_margin[i] && + dist2joint_max[i] > stop_margin[i]) avoidance_force[i] += -avoidance_weights_[i] * dist2joint_max[i]; - if (dist2joint_min[i] < 0.25 && dist2joint_min[i] > 0.1) + if (dist2joint_min[i] < avoid_margin[i] && + dist2joint_min[i] > stop_margin[i]) avoidance_force[i] += avoidance_weights_[i] * dist2joint_min[i]; } tau_d << tau_d + Nullspace * avoidance_force; - for (int i = 0; i < 7; i++) { - if (dist2joint_max[i] < 0.1 && tau_d[i] > 0.) tau_d[i] = 0.; - if (dist2joint_min[i] < 0.1 && tau_d[i] < 0.) tau_d[i] = 0.; - } + + // Coriolis feed-forward: libfranka compensates gravity, not Coriolis / + // centrifugal torques (see the impedance examples of libfranka) + tau_d << tau_d + coriolis; + + JointLimitGuardFn(tau_d, q, dq, joint_min_, joint_max_, stop_margin, + avoid_margin, limit_damping); std::array tau_d_array{}; Eigen::VectorXd::Map(&tau_d_array[0], 7) = tau_d; @@ -630,6 +677,9 @@ void Franka::joint_controller() { const common::Vector7d Kp = this->m_cfg.kp; const common::Vector7d Kd = this->m_cfg.kd; const common::Vector7d torque_limit = this->m_cfg.torque_limit; + const common::Vector7d stop_margin = this->m_cfg.joint_limit_stop_margin; + const common::Vector7d avoid_margin = this->m_cfg.joint_limit_avoid_margin; + const common::Vector7d limit_damping = this->m_cfg.joint_limit_damping; const bool allow_high_collision = this->m_cfg.allow_high_collision; this->controller_time = 0.0; @@ -648,8 +698,9 @@ void Franka::joint_controller() { Eigen::Array joint_max_; Eigen::Array joint_min_; - joint_max_ << 2.8978, 1.7628, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973; - joint_min_ << -2.8973, -1.7628, -2.8973, -3.0718, -2.8973, -0.0175, -2.8973; + // joint limits of the configured robot (were hard coded Panda limits) + joint_min_ = this->m_cfg.joint_limits.row(0).head<7>().transpose().array(); + joint_max_ = this->m_cfg.joint_limits.row(1).head<7>().transpose().array(); try { this->robot.control([&](const franka::RobotState& robot_state, @@ -665,6 +716,7 @@ void Franka::joint_controller() { common::Vector7d desired_q; this->curr_state.store(robot_state); + this->record_control_state(robot_state); this->interpolator_mutex.lock(); this->controller_time += period.toSec(); @@ -686,16 +738,21 @@ void Franka::joint_controller() { tau_d << Kp.cwiseProduct(joint_pos_error) - Kd.cwiseProduct(dq); + // Coriolis feed-forward: libfranka compensates gravity, not Coriolis / + // centrifugal torques (see the impedance examples of libfranka) + std::array coriolis_array = model.coriolis(robot_state); + Eigen::Map> coriolis( + coriolis_array.data()); + tau_d << tau_d + coriolis; + Eigen::Matrix dist2joint_max; Eigen::Matrix dist2joint_min; dist2joint_max = joint_max_.matrix() - q; dist2joint_min = q - joint_min_.matrix(); - for (int i = 0; i < 7; i++) { - if (dist2joint_max[i] < 0.1 && tau_d[i] > 0.) tau_d[i] = 0.; - if (dist2joint_min[i] < 0.1 && tau_d[i] < 0.) tau_d[i] = 0.; - } + JointLimitGuardFn(tau_d, q, dq, joint_min_, joint_max_, stop_margin, + avoid_margin, limit_damping); std::array tau_d_array{}; Eigen::VectorXd::Map(&tau_d_array[0], 7) = tau_d; @@ -747,6 +804,7 @@ void Franka::zero_torque_controller() { this->robot.control([&](const franka::RobotState& robot_state, franka::Duration period) -> franka::Torques { this->curr_state.store(robot_state); + this->record_control_state(robot_state); this->interpolator_mutex.lock(); this->controller_time += period.toSec(); diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index 7d875f9a..cdea88c5 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -12,6 +12,7 @@ #include #include +#include "ControlStateBuffer.h" #include "rcs/Kinematics.h" #include "rcs/LinearPoseTrajInterpolator.h" #include "rcs/Pose.h" @@ -47,6 +48,15 @@ struct FrankaConfig : common::RobotConfig { common::Vector7d kd = (common::Vector7d() << 20., 20., 20., 20., 7.5, 15.0, 5.0).finished(); common::Vector7d torque_limit = common::Vector7d::Constant(5.0); + // Joint-limit guard of the torque controllers, per joint, distances to the + // nearest limit in rad: within joint_limit_avoid_margin the OSC adds a + // nullspace avoidance potential and both controllers brake the velocity + // towards the limit (joint_limit_damping in Nm s/rad, reached at the stop + // margin, growing linearly over the band; 0 disables braking); within + // joint_limit_stop_margin no torque towards the limit is applied at all. + common::Vector7d joint_limit_stop_margin = common::Vector7d::Constant(0.1); + common::Vector7d joint_limit_avoid_margin = common::Vector7d::Constant(0.25); + common::Vector7d joint_limit_damping = common::Vector7d::Zero(); bool allow_high_collision = false; // values from deoxys/config/osc-position-controller.yml Eigen::Vector3d kp_p = (Eigen::Vector3d() << 150., 150., 150.).finished(); @@ -76,6 +86,11 @@ struct FrankaConfig : common::RobotConfig { double approach_cartesian_speed = 0.1; double approach_rotation_speed = 0.5; bool ignore_realtime = false; + // When true, every state seen by the 1 kHz control loop is copied into a + // preallocated lock-free ring buffer that can be drained once per env step + // with Franka::drain_control_states. Only active while a controller thread + // runs (async_control). + bool record_control_states = false; size_t dof = 7; Eigen::Matrix joint_limits = (Eigen::Matrix(2, 7) << @@ -123,6 +138,10 @@ class Franka : public common::Robot { std::mutex interpolator_mutex; std::atomic running_controller{Controller::none}; common::ThreadSafeValue background_exception; + // filled by the control thread, drained by the env step + ControlStateBuffer m_control_states; + std::atomic m_record_control_states{false}; + void record_control_state(const franka::RobotState& robot_state) noexcept; void osc(); void joint_controller(); void zero_torque_controller(); @@ -183,6 +202,13 @@ class Franka : public common::Robot { void reset() override; void close() override {}; + + /** + * @brief Buffer of the states seen by the control loop, see + * FrankaConfig::record_control_states. Must only be drained from one + * thread. + */ + ControlStateBuffer& control_state_buffer() { return m_control_states; } }; } // namespace hw } // namespace rcs diff --git a/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index fc3ddc18..92d4f039 100644 --- a/extensions/rcs_fr3/src/pybind/rcs.cpp +++ b/extensions/rcs_fr3/src/pybind/rcs.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -22,6 +23,96 @@ namespace py = pybind11; +namespace { +template +void CopyRow(const std::array& src, double* dst, size_t row) { + std::copy(src.begin(), src.end(), dst + row * D); +} + +/** + * Drains all samples of the buffer into one contiguous numpy array per signal + * (shape N or N x D) plus the sample count and number of dropped samples. + */ +py::dict DrainControlStates(rcs::hw::ControlStateBuffer& buffer) { + const auto n = static_cast(buffer.size()); + auto vec = [n]() { return py::array_t(n); }; + auto mat = [n](py::ssize_t d) { + return py::array_t(std::vector{n, d}); + }; + auto timestamp = vec(); + auto robot_time = vec(); + auto q = mat(7); + auto dq = mat(7); + auto tau_J = mat(7); + auto tau_J_d = mat(7); + auto dtau_J = mat(7); + auto tau_ext = mat(7); + auto O_F_ext = mat(6); + auto K_F_ext = mat(6); + auto O_T_EE = mat(16); + auto success_rate = vec(); + auto robot_mode = py::array_t(n); + auto current_errors = py::array_t(n); + auto last_motion_errors = py::array_t(n); + + double* p_timestamp = timestamp.mutable_data(); + double* p_robot_time = robot_time.mutable_data(); + double* p_q = q.mutable_data(); + double* p_dq = dq.mutable_data(); + double* p_tau_J = tau_J.mutable_data(); + double* p_tau_J_d = tau_J_d.mutable_data(); + double* p_dtau_J = dtau_J.mutable_data(); + double* p_tau_ext = tau_ext.mutable_data(); + double* p_O_F_ext = O_F_ext.mutable_data(); + double* p_K_F_ext = K_F_ext.mutable_data(); + double* p_O_T_EE = O_T_EE.mutable_data(); + double* p_success_rate = success_rate.mutable_data(); + int32_t* p_robot_mode = robot_mode.mutable_data(); + uint64_t* p_current_errors = current_errors.mutable_data(); + uint64_t* p_last_motion_errors = last_motion_errors.mutable_data(); + + const size_t drained = buffer.drain( + [&](size_t i, const rcs::hw::ControlStateSample& s) { + p_timestamp[i] = s.timestamp; + p_robot_time[i] = s.robot_time; + CopyRow(s.q, p_q, i); + CopyRow(s.dq, p_dq, i); + CopyRow(s.tau_J, p_tau_J, i); + CopyRow(s.tau_J_d, p_tau_J_d, i); + CopyRow(s.dtau_J, p_dtau_J, i); + CopyRow(s.tau_ext_hat_filtered, p_tau_ext, i); + CopyRow(s.O_F_ext_hat_K, p_O_F_ext, i); + CopyRow(s.K_F_ext_hat_K, p_K_F_ext, i); + CopyRow(s.O_T_EE, p_O_T_EE, i); + p_success_rate[i] = s.control_command_success_rate; + p_robot_mode[i] = s.robot_mode; + p_current_errors[i] = s.current_errors; + p_last_motion_errors[i] = s.last_motion_errors; + }, + static_cast(n)); + + py::dict out; + out["num_samples"] = drained; + out["dropped"] = buffer.take_dropped(); + out["timestamp"] = timestamp; + out["robot_time"] = robot_time; + out["q"] = q; + out["dq"] = dq; + out["tau_J"] = tau_J; + out["tau_J_d"] = tau_J_d; + out["dtau_J"] = dtau_J; + out["tau_ext_hat_filtered"] = tau_ext; + out["O_F_ext_hat_K"] = O_F_ext; + out["K_F_ext_hat_K"] = K_F_ext; + out["O_T_EE"] = O_T_EE; + out["control_command_success_rate"] = success_rate; + out["robot_mode"] = robot_mode; + out["current_errors"] = current_errors; + out["last_motion_errors"] = last_motion_errors; + return out; +} +} // namespace + PYBIND11_MODULE(_core, m) { m.doc() = R"pbdoc( Franka Python Bindings @@ -107,6 +198,21 @@ PYBIND11_MODULE(_core, m) { // .def_readonly("time", &franka::RobotState::time) .def_readonly("robot_mode", &franka::RobotState::robot_mode); + py::class_( + hw, "ControlStateBuffer", + "Lock-free ring buffer of the states seen by the 1 kHz control loop.") + .def(py::init(), + py::arg("capacity") = rcs::hw::ControlStateBuffer::kDefaultCapacity) + .def("capacity", &rcs::hw::ControlStateBuffer::capacity) + .def("size", &rcs::hw::ControlStateBuffer::size) + .def("push", &rcs::hw::ControlStateBuffer::push, py::arg("state"), + "Adds a state as the control loop would do (for tests and mocks).") + .def("drain", &DrainControlStates) + .def("clear", &rcs::hw::ControlStateBuffer::clear); + hw.def("control_state_error_names", &rcs::hw::ErrorNames, + "Names of the franka error flags, index i is bit i of the " + "current_errors and last_motion_errors masks."); + py::object robot_state = (py::object)py::module_::import("rcs").attr("common").attr("RobotState"); py::class_(hw, "FrankaState", robot_state) @@ -132,6 +238,12 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("kp", &rcs::hw::FrankaConfig::kp) .def_readwrite("kd", &rcs::hw::FrankaConfig::kd) .def_readwrite("torque_limit", &rcs::hw::FrankaConfig::torque_limit) + .def_readwrite("joint_limit_stop_margin", + &rcs::hw::FrankaConfig::joint_limit_stop_margin) + .def_readwrite("joint_limit_avoid_margin", + &rcs::hw::FrankaConfig::joint_limit_avoid_margin) + .def_readwrite("joint_limit_damping", + &rcs::hw::FrankaConfig::joint_limit_damping) .def_readwrite("allow_high_collision", &rcs::hw::FrankaConfig::allow_high_collision) .def_readwrite("kp_p", &rcs::hw::FrankaConfig::kp_p) @@ -158,6 +270,8 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("approach_rotation_speed", &rcs::hw::FrankaConfig::approach_rotation_speed) .def_readwrite("ignore_realtime", &rcs::hw::FrankaConfig::ignore_realtime) + .def_readwrite("record_control_states", + &rcs::hw::FrankaConfig::record_control_states) .def_readwrite("ip", &rcs::hw::FrankaConfig::ip); rcs::hw::FR3Config default_fr3_config; @@ -337,6 +451,15 @@ PYBIND11_MODULE(_core, m) { &rcs::hw::Franka::controller_set_joint_position, py::arg("desired_q")) .def("stop_control_thread", &rcs::hw::Franka::stop_control_thread) + .def( + "drain_control_states", + [](rcs::hw::Franka& self) { + return DrainControlStates(self.control_state_buffer()); + }, + "Returns and removes all states recorded by the control loop since " + "the last call, see FrankaConfig.record_control_states.") + .def("clear_control_states", + [](rcs::hw::Franka& self) { self.control_state_buffer().clear(); }) .def("automatic_error_recovery", &rcs::hw::Franka::automatic_error_recovery) .def("double_tap_robot_to_continue", diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 5b9ab3eb..9cf24495 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -13,6 +13,7 @@ import rcs._core.common from . import exceptions __all__: list[str] = [ + "ControlStateBuffer", "FHConfig", "FHState", "FR3Config", @@ -25,6 +26,7 @@ __all__: list[str] = [ "PandaConfig", "RobotMode", "RobotState", + "control_state_error_names", "exceptions", "franka_ik", "kAutomaticErrorRecovery", @@ -37,6 +39,22 @@ __all__: list[str] = [ "rcs_ik", ] +class ControlStateBuffer: + """ + Lock-free ring buffer of the states seen by the 1 kHz control loop. + """ + + def __init__(self, capacity: int = 8192) -> None: ... + def capacity(self) -> int: ... + def clear(self) -> None: ... + def drain(self) -> dict: ... + def push(self, state: RobotState) -> bool: + """ + Adds a state as the control loop would do (for tests and mocks). + """ + + def size(self) -> int: ... + class FHConfig(rcs._core.common.GripperConfig): async_control: bool epsilon_inner: float @@ -76,10 +94,16 @@ class FHState(rcs._core.common.GripperState): class Franka(rcs._core.common.Robot): def __init__(self, cfg: FrankaConfig, ik: rcs._core.common.Kinematics | None = None) -> None: ... def automatic_error_recovery(self) -> None: ... + def clear_control_states(self) -> None: ... def controller_set_joint_position( self, desired_q: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] ) -> None: ... def double_tap_robot_to_continue(self) -> None: ... + def drain_control_states(self) -> dict: + """ + Returns and removes all states recorded by the control loop since the last call, see FrankaConfig.record_control_states. + """ + def get_cartesian_flange_position(self) -> rcs._core.common.Pose: ... def get_config(self) -> FrankaConfig: ... def get_state(self) -> FrankaState: ... @@ -119,10 +143,14 @@ class FrankaConfig(rcs._core.common.RobotConfig): kp_r: float load_parameters: FrankaLoad | None policy_rate: int + record_control_states: bool speed_factor: float tcp_offset: rcs._core.common.Pose tcp_offset_explicit: bool torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + joint_limit_stop_margin: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + joint_limit_avoid_margin: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + joint_limit_damping: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] world_to_robot: rcs._core.common.Pose | None class FrankaHand(rcs._core.common.Gripper): @@ -351,6 +379,11 @@ class FrankaState(rcs._core.common.RobotState): @property def robot_state(self) -> RobotState: ... +def control_state_error_names() -> list[str]: + """ + Names of the franka error flags, index i is bit i of the current_errors and last_motion_errors masks. + """ + franka_ik: IKSolver # value = kAutomaticErrorRecovery: RobotMode # value = kGuiding: RobotMode # value = diff --git a/extensions/rcs_fr3/src/rcs_fr3/creators.py b/extensions/rcs_fr3/src/rcs_fr3/creators.py index 57a1f7b0..4587aeb9 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/creators.py +++ b/extensions/rcs_fr3/src/rcs_fr3/creators.py @@ -162,6 +162,10 @@ class FR3HardwareEnvCreatorConfig: gripper_cfg: GripperConfig | rcs.hand.tilburg_hand.THConfig | None = None camera_cfgs: dict[str, HardwareCameraCreatorConfig] | None = None max_relative_movement: float | tuple[float, float] | None = None + max_step_movement: float | tuple[float, float] | None = None + """per-step limit of the commanded target relative to the *measured* pose (LimitedAbsoluteAction below the + RelativeActionSpace), e.g. (0.075, 0.15) m / rad like DROID; None disables it. max_relative_movement only bounds the + action relative to the origin / last step.""" relative_to: RelativeTo = RelativeTo.LAST_STEP frequency: float | None = None """Control frequency in Hz, rate limits env.step(). None disables rate limiting.""" @@ -175,6 +179,10 @@ class FR3MultiHardwareEnvCreatorConfig: gripper_cfgs: dict[str, GripperConfig | rcs.hand.tilburg_hand.THConfig | None] | None = None camera_cfgs: dict[str, HardwareCameraCreatorConfig] | None = None max_relative_movement: float | tuple[float, float] | None = None + max_step_movement: float | tuple[float, float] | None = None + """per-step limit of the commanded target relative to the *measured* pose (LimitedAbsoluteAction below the + RelativeActionSpace), e.g. (0.075, 0.15) m / rad like DROID; None disables it. max_relative_movement only bounds the + action relative to the origin / last step.""" relative_to: RelativeTo = RelativeTo.LAST_STEP robot_to_shared_base_frame: dict[str, rcs.common.Pose] | None = None frequency: float | None = None @@ -190,6 +198,8 @@ def create_env(self, cfg: FR3HardwareEnvCreatorConfig) -> gym.Env: urdf=cfg.robot_cfg.kinematic_model_path.endswith(".urdf"), joint_limits=cfg.robot_cfg.joint_limits, ) + if cfg.wrapper_cfg.record_control_states: + cfg.robot_cfg.record_control_states = True robot = hw.Franka(cfg.robot_cfg, ik) env: gym.Env = HardwareEnv(frequency=cfg.frequency) @@ -214,6 +224,9 @@ def create_env(self, cfg: FR3HardwareEnvCreatorConfig) -> gym.Env: env = CameraSetWrapper(env, camera_set, cfg.wrapper_cfg.include_depth) if cfg.relative_to != RelativeTo.NONE: + if cfg.max_step_movement is not None: + # below the relative wrapper: limits its absolute target against the measured pose + env = LimitedAbsoluteAction(env, max_mov=cfg.max_step_movement) env = RelativeActionSpace(env, max_mov=cfg.max_relative_movement, relative_to=cfg.relative_to) else: env = LimitedAbsoluteAction(env, max_mov=cfg.max_relative_movement) @@ -235,6 +248,7 @@ def create_env(self, cfg: FR3MultiHardwareEnvCreatorConfig) -> gym.Env: gripper_cfg=cfg.gripper_cfgs[robot_name] if cfg.gripper_cfgs is not None else None, camera_cfgs=None, max_relative_movement=cfg.max_relative_movement, + max_step_movement=cfg.max_step_movement, relative_to=cfg.relative_to, frequency=cfg.frequency, wrapper_cfg=cfg.wrapper_cfg, diff --git a/extensions/rcs_fr3/src/rcs_fr3/envs.py b/extensions/rcs_fr3/src/rcs_fr3/envs.py index 3bd10c58..6451b6e4 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/envs.py +++ b/extensions/rcs_fr3/src/rcs_fr3/envs.py @@ -9,28 +9,68 @@ class FR3HW(gym.Wrapper): + """Hardware specific additions for the FR3. + + - adds the libfranka robot state to the observation (``obs["robot_state"]``) + - if ``record_control_states`` is enabled in the robot config, all states seen by the 1 kHz + control loop since the last step are added to ``info["control_states"]`` as one array per + signal (shape N or N x D) together with ``num_samples`` and ``dropped`` + - a robot error (e.g. a reflex) ends the episode visibly: the step returns ``truncated=True`` + and the error message in ``info["robot_error"]`` (empty string if there is no error). + The robot is not recovered silently in the step, the recovery happens on the next reset. + """ + + CONTROL_STATES_KEY = "control_states" + ROBOT_ERROR_KEY = "robot_error" + def __init__(self, env): super().__init__(env) assert self.env.get_wrapper_attr("PLATFORM") == RobotPlatform.HARDWARE, "Base environment must be hardware." assert isinstance(self.get_wrapper_attr("robot"), hw.Franka), "Robot must be a hw.Franka instance." self.hw_robot = cast(hw.Franka, self.get_wrapper_attr("robot")) self._robot_state_keys: list[str] | None = None + self._record_control_states = bool(self.hw_robot.get_config().record_control_states) + self._last_obs: dict[str, Any] | None = None + + def _add_control_states(self, info: dict[str, Any]) -> dict[str, Any]: + if self._record_control_states: + info[self.CONTROL_STATES_KEY] = self.hw_robot.drain_control_states() + return info def step(self, action: Any) -> tuple[dict[str, Any], SupportsFloat, bool, bool, dict]: try: obs, reward, terminated, truncated, info = super().step(action) obs = self.get_obs(obs) - return obs, reward, terminated, truncated, info + info[self.ROBOT_ERROR_KEY] = "" + return obs, reward, terminated, truncated, self._add_control_states(info) except hw.exceptions.FrankaControlException as e: - _logger.error("FrankaControlException: %s", e) - self.hw_robot.automatic_error_recovery() - return self.get_obs(), 0, False, True, {} + _logger.error("FrankaControlException, truncating the episode: %s", e) + try: + obs = self.get_obs() + except Exception: + _logger.exception("could not read the robot state after the control exception") + obs = self._last_obs if self._last_obs is not None else {} + info = { + "platform": "hardware", + "robot_type": self.hw_robot.get_config().robot_type.id, + self.ROBOT_ERROR_KEY: str(e), + } + return obs, 0, False, True, self._add_control_states(info) + + def recover(self) -> None: + """Clears a robot error (e.g. a reflex) without resetting the env: the robot stays where it stopped and the + next action starts the controller again from the measured state. Raises if the robot can not recover. + + The stored control-thread exception is already cleared when it was raised in the step + (Franka::check_for_background_errors loads and clears it and stops the control thread).""" + self.hw_robot.automatic_error_recovery() def get_obs(self, obs: dict | None = None) -> dict[str, Any]: if obs is None: obs = dict(self.get_wrapper_attr("get_robot_obs")()) robot_state = cast(hw.FrankaState, self.hw_robot.get_state()) obs["robot_state"] = self._rs2dict(robot_state.robot_state) + self._last_obs = obs return obs def _rs2dict(self, state: hw.RobotState): @@ -45,6 +85,10 @@ def reset( self, *, seed: int | None = None, options: dict[str, Any] | None = None ) -> tuple[dict[str, Any], dict[str, Any]]: obs, info = super().reset(seed=seed, options=options) + # the config might have changed, states recorded before and during the reset do not belong to the next episode + self._record_control_states = bool(self.hw_robot.get_config().record_control_states) + self.hw_robot.clear_control_states() + info[self.ROBOT_ERROR_KEY] = "" return self.get_obs(obs), info def close(self): diff --git a/extensions/rcs_fr3/tests/test_control_state_buffer.py b/extensions/rcs_fr3/tests/test_control_state_buffer.py new file mode 100644 index 00000000..2634a834 --- /dev/null +++ b/extensions/rcs_fr3/tests/test_control_state_buffer.py @@ -0,0 +1,58 @@ +"""Tests of the control state ring buffer, they do not need a robot.""" + +import numpy as np +import pytest + +hw = pytest.importorskip("rcs_fr3._core").hw + + +def test_drain_shapes_and_order(): + buffer = hw.ControlStateBuffer(100) + assert buffer.capacity() == 128 + state = hw.RobotState() + for _ in range(66): + assert buffer.push(state) + assert buffer.size() == 66 + states = buffer.drain() + assert states["num_samples"] == 66 + assert states["dropped"] == 0 + assert states["timestamp"].shape == (66,) + assert states["q"].shape == (66, 7) + assert states["tau_J"].shape == (66, 7) + assert states["dtau_J"].shape == (66, 7) + assert states["tau_ext_hat_filtered"].shape == (66, 7) + assert states["O_F_ext_hat_K"].shape == (66, 6) + assert states["O_T_EE"].shape == (66, 16) + assert states["robot_mode"].dtype == np.int32 + assert states["current_errors"].dtype == np.uint64 + # timestamps are taken at push time and must be monotonic + assert np.all(np.diff(states["timestamp"]) >= 0) + assert buffer.size() == 0 + assert buffer.drain()["num_samples"] == 0 + + +def test_overflow_drops_newest_and_counts(): + buffer = hw.ControlStateBuffer(8) + state = hw.RobotState() + pushed = [buffer.push(state) for _ in range(10)] + assert pushed == [True] * 8 + [False] * 2 + states = buffer.drain() + assert states["num_samples"] == 8 + assert states["dropped"] == 2 + # counter is reset after it was reported + assert buffer.drain()["dropped"] == 0 + + +def test_error_names(): + names = hw.control_state_error_names() + assert len(names) == 41 + assert names[0] == "joint_position_limits_violation" + assert "joint_reflex" in names + assert "cartesian_reflex" in names + + +def test_config_flag_is_opt_in(): + cfg = hw.FR3Config(ip="localhost") + assert cfg.record_control_states is False + cfg.record_control_states = True + assert cfg.record_control_states is True diff --git a/extensions/rcs_fr3/tests/test_fr3hw_mock.py b/extensions/rcs_fr3/tests/test_fr3hw_mock.py new file mode 100644 index 00000000..68d6984b --- /dev/null +++ b/extensions/rcs_fr3/tests/test_fr3hw_mock.py @@ -0,0 +1,121 @@ +"""Tests of the FR3HW wrapper against a mocked robot, no hardware is contacted.""" + +from types import SimpleNamespace +from typing import Any + +import gymnasium as gym +import numpy as np +import pytest +from rcs._core.common import RobotPlatform + +core = pytest.importorskip("rcs_fr3._core") +envs = pytest.importorskip("rcs_fr3.envs") +hw = core.hw + + +class FakeFranka: + """Stands in for hw.Franka: the control loop is simulated by pushing into a real ControlStateBuffer.""" + + def __init__(self, record: bool = True): + self.cfg = SimpleNamespace(record_control_states=record, robot_type=SimpleNamespace(id="FR3")) + self.buffer = hw.ControlStateBuffer() + self.fail_next_step = False + self.recovered = 0 + + def get_config(self): + return self.cfg + + def get_state(self): + return SimpleNamespace(robot_state=hw.RobotState()) + + def drain_control_states(self): + return self.buffer.drain() + + def clear_control_states(self): + self.buffer.clear() + + def automatic_error_recovery(self): + self.recovered += 1 + + def stop_control_thread(self): + pass + + def control_loop(self, n: int): + state = hw.RobotState() + for _ in range(n): + self.buffer.push(state) + + +class FakeHardwareEnv(gym.Env): + PLATFORM = RobotPlatform.HARDWARE + + def __init__(self, robot: FakeFranka): + self.robot = robot + + def get_robot_obs(self) -> dict[str, Any]: + return {"joints": np.zeros(7)} + + def step(self, action): + if self.robot.fail_next_step: + self.robot.fail_next_step = False + msg = "libfranka: Move command aborted: motion aborted by reflex! ['cartesian_reflex']" + raise hw.exceptions.FrankaControlException(msg) + # 15 Hz env step with a 1 kHz control loop + self.robot.control_loop(66) + return self.get_robot_obs(), 0.0, False, False, {"platform": "hardware"} + + def reset(self, *, seed=None, options=None): + # samples during the reset (e.g. homing) must not leak into the next episode + self.robot.control_loop(10) + return self.get_robot_obs(), {} + + +@pytest.fixture() +def _patched_hw(monkeypatch): + fake_hw = SimpleNamespace( + Franka=FakeFranka, FrankaState=SimpleNamespace, RobotState=hw.RobotState, exceptions=hw.exceptions + ) + monkeypatch.setattr(envs, "hw", fake_hw) + + +@pytest.mark.usefixtures("_patched_hw") +def test_control_states_in_info(): + robot = FakeFranka(record=True) + env = envs.FR3HW(FakeHardwareEnv(robot)) + env.reset() + _, _, _, _, info = env.step({}) + states = info["control_states"] + assert states["num_samples"] == 66 + assert states["q"].shape == (66, 7) + assert states["tau_ext_hat_filtered"].shape == (66, 7) + + +@pytest.mark.usefixtures("_patched_hw") +def test_control_states_opt_in(): + robot = FakeFranka(record=False) + env = envs.FR3HW(FakeHardwareEnv(robot)) + env.reset() + _, _, _, _, info = env.step({}) + assert "control_states" not in info + + +@pytest.mark.usefixtures("_patched_hw") +def test_robot_error_truncates_visibly(): + robot = FakeFranka(record=True) + env = envs.FR3HW(FakeHardwareEnv(robot)) + env.reset() + _, _, _, truncated, info = env.step({}) + assert not truncated + assert info["robot_error"] == "" + + robot.fail_next_step = True + robot.control_loop(5) # states recorded until the reflex + obs, _, terminated, truncated, info = env.step({}) + assert truncated + assert not terminated + assert "reflex" in info["robot_error"] + # the states that lead to the reflex are not lost + assert info["control_states"]["num_samples"] == 5 + # no silent recovery inside the step, this happens on reset + assert robot.recovered == 0 + assert "joints" in obs diff --git a/extensions/rcs_fr3/tests/test_recover.py b/extensions/rcs_fr3/tests/test_recover.py new file mode 100644 index 00000000..38b1f280 --- /dev/null +++ b/extensions/rcs_fr3/tests/test_recover.py @@ -0,0 +1,14 @@ +"""FR3HW.recover() without a robot: it may only call what the compiled hw.Franka binding provides.""" + +from unittest import mock + +from rcs_fr3._core import hw +from rcs_fr3.envs import FR3HW + + +def test_recover_uses_only_bound_methods(): + robot = mock.create_autospec(hw.Franka, instance=True) # attribute access not in the binding raises + env = FR3HW.__new__(FR3HW) + env.hw_robot = robot + env.recover() + robot.automatic_error_recovery.assert_called_once_with() diff --git a/extensions/rcs_robotiq2f85/src/rcs_robotiq2f85/hw.py b/extensions/rcs_robotiq2f85/src/rcs_robotiq2f85/hw.py index 8046648b..79ca8161 100644 --- a/extensions/rcs_robotiq2f85/src/rcs_robotiq2f85/hw.py +++ b/extensions/rcs_robotiq2f85/src/rcs_robotiq2f85/hw.py @@ -1,3 +1,6 @@ +import contextlib +import logging +import threading import typing from rcs._core.common import Gripper, GripperConfig, GripperState @@ -6,6 +9,8 @@ import rcs +logger = logging.getLogger(__name__) + class RobotiQ2F85GripperConfig(GripperConfig): @@ -46,6 +51,16 @@ def __init__(self, cfg: RobotiQ2F85GripperConfig): self._cfg: RobotiQ2F85GripperConfig = cfg self.gripper = Robotiq2F85(serial_number=cfg.serial_number, async_control=cfg.async_control) self.gripper.reset() + # async control: robotiq2f only reads the status in a thread, go_to() still writes the Modbus registers in + # the calling thread and waits for the gripper's reply (seen: 80-200 ms stalls of the env step at open / + # close). Commands are therefore sent from a writer thread; only the newest pending command is sent. + self._command = threading.Condition() + self._pending: tuple[float, float, float] | None = None + self._stop_writer = False + self._writer: threading.Thread | None = None + if cfg.async_control: + self._writer = threading.Thread(target=self._write_commands, daemon=True, name="robotiq-commands") + self._writer.start() def get_normalized_width(self) -> float: return self.gripper.opening / self.gripper.MAX_OPENING @@ -72,12 +87,31 @@ def set_normalized_width(self, width: float, force: float = 0) -> None: if not (0 <= width <= 1): msg = f"Width must be between 0 and 1, got {width}." raise ValueError(msg) - abs_width = width * self.gripper.MAX_OPENING - self.gripper.go_to( - opening=float(abs_width), - speed=self._cfg.speed, - force=force if force != 0 else self._cfg.force, + command = ( + float(width * self.gripper.MAX_OPENING), + float(self._cfg.speed), + float(force if force != 0 else self._cfg.force), ) + if self._writer is None: + self.gripper.go_to(opening=command[0], speed=command[1], force=command[2]) + return + with self._command: + self._pending = command + self._command.notify() + + def _write_commands(self) -> None: + while True: + with self._command: + while self._pending is None and not self._stop_writer: + self._command.wait() + if self._stop_writer: + return + opening, speed, force = self._pending # type: ignore[misc] + self._pending = None + try: + self.gripper.go_to(opening=opening, speed=speed, force=force) + except Exception: + logger.exception("sending the Robotiq command failed") def shut(self) -> None: """ @@ -86,7 +120,34 @@ def shut(self) -> None: self.set_normalized_width(0.0) def close(self) -> None: - self.gripper.client.serial.close() + """Stops the command writer and the status thread of async control, then closes the serial port. + + robotiq2f 0.2.0 reads the status in a ``while True`` thread without a stop flag, so closing the port under + it made the thread crash with ``termios.error: Bad file descriptor`` (seen when the RCS web interface + closed the env). The thread looks ``read_status_sync`` up on the instance in every loop: shadowing it with + a function that raises SystemExit ends the thread silently after its current read. Remove this once + robotiq2f can stop the thread itself. + """ + writer = getattr(self, "_writer", None) + if writer is not None: + with self._command: + self._stop_writer = True + self._command.notify() + writer.join(timeout=2.0) + gripper = self.gripper + thread = getattr(gripper, "_async_thread", None) + if thread is not None and thread.is_alive(): + + def _stop_status_thread(): + raise SystemExit + + gripper.read_status_sync = _stop_status_thread # type: ignore[method-assign] + thread.join(timeout=2.0) + if thread.is_alive(): + logger.warning("the Robotiq status thread did not stop, closing the serial port anyway") + lock = getattr(gripper, "_client_mutex", None) + with lock if lock is not None else contextlib.nullcontext(): + gripper.client.serial.close() def get_config(self) -> GripperConfig: return self._cfg diff --git a/extensions/rcs_robotiq2f85/tests/test_close.py b/extensions/rcs_robotiq2f85/tests/test_close.py new file mode 100644 index 00000000..492fbf16 --- /dev/null +++ b/extensions/rcs_robotiq2f85/tests/test_close.py @@ -0,0 +1,98 @@ +"""close() must stop the async status thread of robotiq2f before the serial port is closed (no hardware needed).""" + +import threading +import time + +from rcs_robotiq2f85.hw import RobotiQ2F85Gripper +from robotiq2f import Robotiq2F85 + + +class _Serial: + def __init__(self): + self.closed = False + + def close(self): + self.closed = True + + +class _Client: + def __init__(self): + self.serial = _Serial() + + +def test_close_stops_the_status_thread_before_closing_the_port(): + lib = Robotiq2F85.__new__(Robotiq2F85) + lib.client = _Client() + lib._client_mutex = threading.Lock() + lib.read_frequency = 200 + reads = [] + + def read_status_sync(): # stands in for the register read: fails like termios once the port is closed + with lib._client_mutex: + if lib.client.serial.closed: + msg = "(9, 'Bad file descriptor')" + raise OSError(msg) + reads.append(time.perf_counter()) + + lib.read_status_sync = read_status_sync + lib._async_thread = threading.Thread(target=lib.read_status_thread, daemon=True) # the library's own loop + errors = [] + previous_hook = threading.excepthook + # the default hook ignores SystemExit (how close() ends the thread), everything else is a crash + threading.excepthook = lambda args: None if args.exc_type is SystemExit else errors.append(args.exc_value) + try: + lib._async_thread.start() + while len(reads) < 5: + time.sleep(0.01) + gripper = RobotiQ2F85Gripper.__new__(RobotiQ2F85Gripper) + gripper.gripper = lib + gripper.close() + time.sleep(0.05) + finally: + threading.excepthook = previous_hook + assert lib.client.serial.closed + assert not lib._async_thread.is_alive() + assert errors == [] + + +def _gripper_with_slow_go_to(delay: float): + """A RobotiQ2F85Gripper with async control whose library go_to() blocks like a slow Modbus reply.""" + from rcs_robotiq2f85.hw import RobotiQ2F85GripperConfig + + lib = Robotiq2F85.__new__(Robotiq2F85) + lib.client = _Client() + lib._client_mutex = threading.Lock() + lib.MAX_OPENING = 85.0 + sent = [] + + def go_to(opening, **_kwargs): + time.sleep(delay) + sent.append(opening) + + lib.go_to = go_to + gripper = RobotiQ2F85Gripper.__new__(RobotiQ2F85Gripper) + gripper._cfg = RobotiQ2F85GripperConfig(serial_number="X", async_control=True) + gripper.gripper = lib + gripper._command = threading.Condition() + gripper._pending = None + gripper._stop_writer = False + gripper._writer = threading.Thread(target=gripper._write_commands, daemon=True) + gripper._writer.start() + return gripper, lib, sent + + +def test_async_commands_do_not_block_the_caller(): + gripper, lib, sent = _gripper_with_slow_go_to(0.2) + start = time.perf_counter() + gripper.open() + assert time.perf_counter() - start < 0.02 # the env step does not wait for the gripper's reply + while gripper._pending is not None: # the writer picked up the first command and is sending it + time.sleep(0.001) + # while the first command is being written, newer ones replace each other: only the newest is sent + gripper.grasp() + gripper.set_normalized_width(0.5) + time.sleep(0.6) + assert sent == [85.0, 42.5] + gripper.close() + assert not gripper._writer.is_alive() + assert lib.client.serial.closed diff --git a/extensions/rcs_webui/Makefile b/extensions/rcs_webui/Makefile new file mode 100644 index 00000000..4c746c8c --- /dev/null +++ b/extensions/rcs_webui/Makefile @@ -0,0 +1,18 @@ +PYSRC = src/rcs_webui +TESTSRC = tests + +pycheckformat: + isort --check-only ${PYSRC} ${TESTSRC} + black --check ${PYSRC} ${TESTSRC} + +pyformat: + isort ${PYSRC} ${TESTSRC} + black ${PYSRC} ${TESTSRC} + +ruff: + ruff check ${PYSRC} ${TESTSRC} + +pytest: + python -m pytest ${TESTSRC} + +.PHONY: pycheckformat pyformat ruff pytest diff --git a/extensions/rcs_webui/README.md b/extensions/rcs_webui/README.md new file mode 100644 index 00000000..7c125385 --- /dev/null +++ b/extensions/rcs_webui/README.md @@ -0,0 +1,204 @@ +# RCS Web Interface + +A web interface for data collection and evaluation with RCS. It starts and owns the gym env, reads the +Meta Quest and records every step of every episode into the RCS parquet format with the `StorageWrapper`. + +- **Labelling on the Quest**: `A` starts an episode, `B` ends it as successful, `Y` as unsuccessful. + The same buttons are in the web page. +- **Everything in one place**: observations, camera frames, actions, the info dict and all robot states of + the low level controller since the last step (1 kHz on the FR3, every physics step in sim) are stored in + the same parquet rows. A robot error (e.g. a reflex) ends the episode with `truncated=True` and the error + message in `info..robot_error`. +- **Reproducible**: every env (re)start creates a new data folder with the complete env config, the git + commit and the git diff. A new env can be started from that stored config. + +- **Viewer**: plots of joints, gripper, TCP, actions and the controller rate signals, camera playback, + relabel (successful / unsuccessful) and delete of episodes. + +## Setup from scratch + +Steps marked *untested on hardware* were only checked in simulation or with mocked hardware. + +### 1. Repositories and versions + +| what | where | version | +|------|-------|---------| +| RCS incl. this extension and `rcs_fr3` | `https://github.com/RobotControlStack/robot-control-stack` | branch `feat/webui-extension` (based on v0.7.4) | +| Quest app (IRIS) | `https://github.com/RobotControlStack/IRIS-Meta-Quest3/releases/tag/rcsv0.7.x` | `rcsv0.7.x` APK | +| SimPublisher (Python client of the Quest app) | `https://github.com/RobotControlStack/SimPublisher` | default branch | + +Linux (Debian / Ubuntu LTS), Python 3.11, a real time kernel for the FR3 (see the libfranka docs). + +### 2. Install RCS, the FR3 extension and this extension + +```shell +git clone -b feat/webui-extension https://github.com/RobotControlStack/robot-control-stack.git +cd robot-control-stack +sudo apt install $(cat debian_deps.txt) $(cat extensions/rcs_fr3/debian_deps.txt) +python3.11 -m venv .venv && source .venv/bin/activate +pip install 'pip>=25.1' +pip install --group build_deps +pip install -ve . --no-build-isolation # RCS core (C++ build, a few minutes) +pip install -ve extensions/rcs_fr3 --no-build-isolation # FR3 (fetches and builds libfranka) +pip install -ve extensions/rcs_webui # this extension, provides the rcs-webui command +``` + +Limit the parallel C++ build jobs on machines with little memory with `export CMAKE_BUILD_PARALLEL_LEVEL=8`. + +Optional, depending on the setup: + +```shell +pip install -ve extensions/rcs_robotiq2f85 # Robotiq 2F-85 gripper +pip install -ve extensions/rcs_realsense # RealSense cameras +pip install -ve extensions/rcs_zed # ZED cameras (needs the ZED SDK) +``` + +### 3. Meta Quest (operator) + +Install the Quest app and SimPublisher as described in +[`examples/teleop/README.md`](../../examples/teleop/README.md) ("Teleoperation with Meta Quest 3"): +put PC and Quest into the same network, install the IRIS APK, `pip install` SimPublisher from source, +name the Quest `RCSNode` and align the coordinate frame with `examples/teleop/quest_align_frame.py`. +The IP of the PC in that network is set in the web page (*Settings*, default `10.42.0.1`). + +### 4. Start the interface + +```shell +rcs-webui serve --data-root ~/rcs_data # optional: --port 8080 --host 0.0.0.0 +``` + +Open `http://:8080`. No env runs yet. Everything is configured in the page and kept in +`/.rcs_webui/settings.json`: + +- *Settings*: mode (collect / eval), operator (Meta Quest or web buttons only), Quest network IP, swap left / + right, MuJoCo viewer (sim), the rate of default configs, config directories (their `*.json` files are offered + as configs) and env packages (modules that register more envs, default `duobench.tasks`). Mode, operator, + Quest and viewer settings are used at env start and can only be changed while no env runs. +- *Auto reset* (on by default): when the env ends the episode itself, it is stored and the env is reset: as + successful if the task check reports success (`terminated` with `info["success"]`, e.g. DuoBench tasks), as + unsuccessful for any other termination or truncation. Off: the env's end is only shown in the status and the + episode keeps recording until `B` / `Y`. Robot errors always end the episode and reset the env. +- *On robot error*: `end episode` (default) stores the episode as unsuccessful (`truncated=True` and the message in + `info..robot_error` in the last row) and resets the env. `recover and continue` clears the error + (`FR3HW.recover()`, libfranka automatic error recovery), the robot stays where it stopped and the episode keeps + recording; the row of the error keeps `truncated=True` and the message, so converters can cut there. The Quest + origin is reset: re-press the trigger to continue from where the robot is. If recovery fails, the episode ends. +- *Consolidate files on stop* (default on): when the env is stopped or restarted, the session's batch files are + merged into files of about 512 MB (row groups of about 128 MB) in the background; relabel / delete of that session + wait until it is done. +- *Env config*: pick a config, it is shown complete and editable, then *start env*. The list has the running + env, the config directories, previous recordings and the default configs of the code (hardware: `fr3`, + `fr3_duo`, `fr3_dual`, `droid`; simulation: `rcs/*` and e.g. `duobench/*` when DuoBench is installed). + Changes against the picked config are marked in the gutter like in VS Code (green added, blue changed, red + wedge deleted); click a mark to see the old and new lines and revert that change. Each start stores the + picked config's id and the changed fields (`source.base` / `source.changed` in `session.json`). + +The Quest operator is created with every env start: on hardware the Quest app gets an empty scene, in sim the +MuJoCo scene is streamed to the Quest. A config file holds the env creator and the serialized config +(`{"creator": ..., "config": ...}`, see `rcs-webui dump-config `); a file without creator (e.g. an +`env_config.json`) gets the generic creator of its config type (`rcs_fr3.creators:RCSFR3MultiConfigEnvCreator` +for FR3 hardware, `rcs_webui.envs:ConfigSimEnvCreator` for sim). `robot_platform` of hardware robot configs is +set to `HARDWARE` (the C++ default `SIMULATION` is never read on hardware, the env class decides). + +Try it in simulation first: pick e.g. `rcs/fr3` or `duobench/pick_place_red_on_green` (DuoBench branch +`juelg/single-arm`, a single FR3 with the DROID cameras `front_rgb` and `gripper_rgb`), set the operator to +*none* to use only the web buttons. + +### 5. On the robot PC (*untested on hardware*) + +1. Unlock the FR3 joints and activate FCI in Desk. +2. Put the config of your setup into a config directory, e.g. start from the default + (`rcs-webui dump-config droid > ~/rcs_configs/droid.json`) and set robot IP, gripper and cameras with their + serial numbers, or edit it in the page and start it there. +3. Hold the index trigger of the right controller to move the robot, the hand trigger closes the gripper. + Press `A` to start recording, `B` (successful) or `Y` (unsuccessful) to end the episode, the env is reset + (the robot moves home) after each episode. Ctrl+C stops the interface after flushing the recording, a second + Ctrl+C exits immediately. + +Default configs are adapted for recording: `wrapper_cfg.record_control_states=True`, async control at the +default config rate (15 Hz, also the controller interpolation window `policy_rate`), and in collect mode the +action space of the Quest (`tquat` relative to the configured origin). Config files and previous recordings are +used as stored. + +### 6. Where the data lands + +```text +/ + 2026-11-15_13-42-36_fr3_collect/ one folder per env (re)start: _