Flexiv RDK APIs  1.6.0
intermediate5_realtime_cartesian_pure_motion_control.cpp
1 
9 #include <flexiv/rdk/robot.hpp>
10 #include <flexiv/rdk/scheduler.hpp>
11 #include <flexiv/rdk/utility.hpp>
12 #include <spdlog/spdlog.h>
13 
14 #include <iostream>
15 #include <cmath>
16 #include <thread>
17 #include <atomic>
18 
19 using namespace flexiv;
20 
21 namespace {
23 constexpr size_t kLoopFreq = 1000;
24 
26 constexpr double kLoopPeriod = 0.001;
27 
29 constexpr double kSwingAmp = 0.1;
30 
32 constexpr double kSwingFreq = 0.3;
33 
35 constexpr double kExtForceThreshold = 10.0;
36 
38 constexpr double kExtTorqueThreshold = 5.0;
39 
41 std::atomic<bool> g_stop_sched = {false};
42 }
43 
45 void PrintHelp()
46 {
47  // clang-format off
48  std::cout << "Required arguments: [robot_sn]" << std::endl;
49  std::cout << " robot_sn: Serial number of the robot to connect. Remove any space, e.g. Rizon4s-123456" << std::endl;
50  std::cout << "Optional arguments: [--hold] [--collision]" << std::endl;
51  std::cout << " --hold: robot holds current TCP pose, otherwise do a sine-sweep" << std::endl;
52  std::cout << " --collision: enable collision detection, robot will stop upon collision" << std::endl;
53  std::cout << std::endl;
54  // clang-format on
55 }
56 
58 void PeriodicTask(rdk::Robot& robot, const std::array<double, rdk::kPoseSize>& init_pose,
59  const std::vector<double>& init_q, bool enable_hold, bool enable_collision)
60 {
61  // Local periodic loop counter
62  static uint64_t loop_counter = 0;
63 
64  try {
65  // Monitor fault on the connected robot
66  if (robot.fault()) {
67  throw std::runtime_error(
68  "PeriodicTask: Fault occurred on the connected robot, exiting ...");
69  }
70 
71  // Initialize target pose to initial pose
72  auto target_pose = init_pose;
73 
74  // Sine-sweep TCP along Y axis
75  if (!enable_hold) {
76  target_pose[1] = init_pose[1]
77  + kSwingAmp * sin(2 * M_PI * kSwingFreq * loop_counter * kLoopPeriod);
78  }
79  // Otherwise robot TCP will hold at initial pose
80 
81  // Send command. Calling this method with only target pose input results in pure motion
82  // control
83  robot.StreamCartesianMotionForce(target_pose);
84 
85  // Do the following operations in sequence for every 20 seconds
86  switch (loop_counter % (20 * kLoopFreq)) {
87  // Online change reference joint positions at 3 seconds
88  case (3 * kLoopFreq): {
89  std::vector<double> preferred_jnt_pos
90  = {0.938, -1.108, -1.254, 1.464, 1.073, 0.278, -0.658};
91  robot.SetNullSpacePosture(preferred_jnt_pos);
92  spdlog::info("Reference joint positions set to: "
93  + rdk::utility::Vec2Str(preferred_jnt_pos));
94  } break;
95  // Online change stiffness to half of nominal at 6 seconds
96  case (6 * kLoopFreq): {
97  auto new_K = robot.info().K_x_nom;
98  for (auto& v : new_K) {
99  v *= 0.5;
100  }
101  robot.SetCartesianImpedance(new_K);
102  spdlog::info("Cartesian stiffness set to: {}", rdk::utility::Arr2Str(new_K));
103  } break;
104  // Online change to another reference joint positions at 9 seconds
105  case (9 * kLoopFreq): {
106  std::vector<double> preferred_jnt_pos
107  = {-0.938, -1.108, 1.254, 1.464, -1.073, 0.278, 0.658};
108  robot.SetNullSpacePosture(preferred_jnt_pos);
109  spdlog::info("Reference joint positions set to: "
110  + rdk::utility::Vec2Str(preferred_jnt_pos));
111  } break;
112  // Online reset impedance properties to nominal at 12 seconds
113  case (12 * kLoopFreq): {
114  robot.SetCartesianImpedance(robot.info().K_x_nom);
115  spdlog::info("Cartesian impedance properties are reset");
116  } break;
117  // Online reset reference joint positions to nominal at 14 seconds
118  case (14 * kLoopFreq): {
119  robot.SetNullSpacePosture(init_q);
120  spdlog::info("Reference joint positions are reset");
121  } break;
122  // Online enable max contact wrench regulation at 16 seconds
123  case (16 * kLoopFreq): {
124  std::array<double, rdk::kCartDoF> max_wrench = {10.0, 10.0, 10.0, 2.0, 2.0, 2.0};
125  robot.SetMaxContactWrench(max_wrench);
126  spdlog::info("Max contact wrench set to: {}", rdk::utility::Arr2Str(max_wrench));
127  } break;
128  // Disable max contact wrench regulation at 19 seconds
129  case (19 * kLoopFreq): {
130  std::array<double, rdk::kCartDoF> inf;
131  inf.fill(std::numeric_limits<double>::infinity());
132  robot.SetMaxContactWrench(inf);
133  spdlog::info("Max contact wrench regulation is disabled");
134  } break;
135  default:
136  break;
137  }
138 
139  // Simple collision detection: stop robot if collision is detected from either end-effector
140  // or robot body
141  if (enable_collision) {
142  bool collision_detected = false;
143  Eigen::Vector3d ext_force = {robot.states().ext_wrench_in_world[0],
144  robot.states().ext_wrench_in_world[1], robot.states().ext_wrench_in_world[2]};
145  if (ext_force.norm() > kExtForceThreshold) {
146  collision_detected = true;
147  }
148  for (const auto& v : robot.states().tau_ext) {
149  if (fabs(v) > kExtTorqueThreshold) {
150  collision_detected = true;
151  }
152  }
153  if (collision_detected) {
154  robot.Stop();
155  spdlog::warn("Collision detected, stopping robot and exit program ...");
156  g_stop_sched = true;
157  }
158  }
159 
160  // Increment loop counter
161  loop_counter++;
162 
163  } catch (const std::exception& e) {
164  spdlog::error(e.what());
165  g_stop_sched = true;
166  }
167 }
168 
169 int main(int argc, char* argv[])
170 {
171  // Program Setup
172  // =============================================================================================
173  // Parse parameters
174  if (argc < 2 || rdk::utility::ProgramArgsExistAny(argc, argv, {"-h", "--help"})) {
175  PrintHelp();
176  return 1;
177  }
178  // Serial number of the robot to connect to. Remove any space, for example: Rizon4s-123456
179  std::string robot_sn = argv[1];
180 
181  // Print description
182  spdlog::info(
183  ">>> Tutorial description <<<\nThis tutorial runs real-time Cartesian-space pure motion "
184  "control to hold or sine-sweep the robot TCP. A simple collision detection is also "
185  "included.\n");
186 
187  // Type of motion specified by user
188  bool enable_hold = false;
189  if (rdk::utility::ProgramArgsExist(argc, argv, "--hold")) {
190  spdlog::info("Robot holding current TCP pose");
191  enable_hold = true;
192  } else {
193  spdlog::info("Robot running TCP sine-sweep");
194  }
195 
196  // Whether to enable collision detection
197  bool enable_collision = false;
198  if (rdk::utility::ProgramArgsExist(argc, argv, "--collision")) {
199  spdlog::info("Collision detection enabled");
200  enable_collision = true;
201  } else {
202  spdlog::info("Collision detection disabled");
203  }
204 
205  try {
206  // RDK Initialization
207  // =========================================================================================
208  // Instantiate robot interface
209  rdk::Robot robot(robot_sn);
210 
211  // Clear fault on the connected robot if any
212  if (robot.fault()) {
213  spdlog::warn("Fault occurred on the connected robot, trying to clear ...");
214  // Try to clear the fault
215  if (!robot.ClearFault()) {
216  spdlog::error("Fault cannot be cleared, exiting ...");
217  return 1;
218  }
219  spdlog::info("Fault on the connected robot is cleared");
220  }
221 
222  // Enable the robot, make sure the E-stop is released before enabling
223  spdlog::info("Enabling robot ...");
224  robot.Enable();
225 
226  // Wait for the robot to become operational
227  while (!robot.operational()) {
228  std::this_thread::sleep_for(std::chrono::seconds(1));
229  }
230  spdlog::info("Robot is now operational");
231 
232  // Move robot to home pose
233  spdlog::info("Moving to home pose");
234  robot.SwitchMode(rdk::Mode::NRT_PLAN_EXECUTION);
235  robot.ExecutePlan("PLAN-Home");
236  // Wait for the plan to finish
237  while (robot.busy()) {
238  std::this_thread::sleep_for(std::chrono::seconds(1));
239  }
240 
241  // Zero Force-torque Sensor
242  // =========================================================================================
243  robot.SwitchMode(rdk::Mode::NRT_PRIMITIVE_EXECUTION);
244  // IMPORTANT: must zero force/torque sensor offset for accurate force/torque measurement
245  robot.ExecutePrimitive("ZeroFTSensor", std::map<std::string, rdk::FlexivDataTypes> {});
246 
247  // WARNING: during the process, the robot must not contact anything, otherwise the result
248  // will be inaccurate and affect following operations
249  spdlog::warn(
250  "Zeroing force/torque sensors, make sure nothing is in contact with the robot");
251 
252  // Wait for primitive completion
253  while (robot.busy()) {
254  std::this_thread::sleep_for(std::chrono::seconds(1));
255  }
256  spdlog::info("Sensor zeroing complete");
257 
258  // Configure Motion Control
259  // =========================================================================================
260  // The Cartesian motion force modes do pure motion control out of the box, thus nothing
261  // needs to be explicitly configured
262 
263  // NOTE: motion control always uses robot world frame, while force control can use
264  // either world or TCP frame as reference frame
265 
266  // Start Pure Motion Control
267  // =========================================================================================
268  // Switch to real-time mode for continuous motion control
269  robot.SwitchMode(rdk::Mode::RT_CARTESIAN_MOTION_FORCE);
270 
271  // Set all Cartesian axis(s) to motion control
272  robot.SetForceControlAxis(
273  std::array<bool, rdk::kCartDoF> {false, false, false, false, false, false});
274 
275  // Save initial pose
276  auto init_pose = robot.states().tcp_pose;
277 
278  // Save initial joint positions
279  auto init_q = robot.states().q;
280 
281  // Create real-time scheduler to run periodic tasks
282  rdk::Scheduler scheduler;
283  // Add periodic task with 1ms interval and highest applicable priority
284  scheduler.AddTask(std::bind(PeriodicTask, std::ref(robot), std::ref(init_pose),
285  std::ref(init_q), enable_hold, enable_collision),
286  "HP periodic", 1, scheduler.max_priority());
287  // Start all added tasks
288  scheduler.Start();
289 
290  // Block and wait for signal to stop scheduler tasks
291  while (!g_stop_sched) {
292  std::this_thread::sleep_for(std::chrono::milliseconds(1));
293  }
294  // Received signal to stop scheduler tasks
295  scheduler.Stop();
296 
297  } catch (const std::exception& e) {
298  spdlog::error(e.what());
299  return 1;
300  }
301 
302  return 0;
303 }
Main interface with the robot, containing several function categories and background services.
Definition: robot.hpp:25
void ExecutePlan(unsigned int index, bool continue_exec=false, bool block_until_started=true)
[Blocking] Execute a plan by specifying its index.
void SetMaxContactWrench(const std::array< double, kCartDoF > &max_wrench)
[Blocking] Set maximum contact wrench for the motion control part of the Cartesian motion-force contr...
const RobotStates states() const
[Non-blocking] Current states data of the robot.
void ExecutePrimitive(const std::string &primitive_name, const std::map< std::string, FlexivDataTypes > &input_params, const std::map< std::string, FlexivDataTypes > &properties={}, bool block_until_started=true)
[Blocking] Execute a primitive by specifying its name and parameters, which can be found in the Flexi...
const RobotInfo info() const
[Non-blocking] General information about the connected robot.
bool operational(bool verbose=true) const
[Non-blocking] Whether the robot is ready to be operated, which requires the following conditions to ...
void StreamCartesianMotionForce(const std::array< double, kPoseSize > &pose, const std::array< double, kCartDoF > &wrench={}, const std::array< double, kCartDoF > &velocity={}, const std::array< double, kCartDoF > &acceleration={})
[Non-blocking] Continuously stream Cartesian motion and/or force command for the robot to track using...
void Stop()
[Blocking] Stop the robot and transit robot mode to IDLE.
void SwitchMode(Mode mode)
[Blocking] Switch to a new control mode and wait until mode transition is finished.
void SetCartesianImpedance(const std::array< double, kCartDoF > &K_x, const std::array< double, kCartDoF > &Z_x={0.7, 0.7, 0.7, 0.7, 0.7, 0.7})
[Blocking] Set impedance properties of the robot's Cartesian motion controller used in the Cartesian ...
void SetForceControlAxis(const std::array< bool, kCartDoF > &enabled_axes, const std::array< double, kCartDoF/2 > &max_linear_vel={1.0, 1.0, 1.0})
[Blocking] Set Cartesian axes to enable force control while in the Cartesian motion-force control mod...
void Enable()
[Blocking] Enable the robot, if E-stop is released and there's no fault, the robot will release brake...
bool fault() const
[Non-blocking] Whether the robot is in fault state.
bool ClearFault(unsigned int timeout_sec=30)
[Blocking] Try to clear minor or critical fault of the robot without a power cycle.
bool busy() const
[Non-blocking] Whether the robot is currently executing a task. This includes any user commanded oper...
void SetNullSpacePosture(const std::vector< double > &ref_positions)
[Blocking] Set reference joint positions for the null-space posture control module used in the Cartes...
Real-time scheduler that can simultaneously run multiple periodic tasks. Parameters for each task are...
Definition: scheduler.hpp:22
int max_priority() const
[Non-blocking] Get maximum available priority for user tasks.
void AddTask(std::function< void(void)> &&callback, const std::string &task_name, int interval, int priority, int cpu_affinity=-1)
[Non-blocking] Add a new periodic task to the scheduler's task pool. Each task in the pool is assigne...
void Stop()
[Blocking] Stop all added tasks. The periodic execution will stop and all task threads will be closed...
void Start()
[Blocking] Start all added tasks. A dedicated thread will be created for each added task and the peri...
std::array< double, kCartDoF > K_x_nom
Definition: data.hpp:91
std::array< double, kCartDoF > ext_wrench_in_world
Definition: data.hpp:247
std::vector< double > q
Definition: data.hpp:136
std::vector< double > tau_ext
Definition: data.hpp:183
std::array< double, kPoseSize > tcp_pose
Definition: data.hpp:208