Flexiv RDK APIs  1.6.0
intermediate6_realtime_cartesian_motion_force_control.cpp
1 
10 #include <flexiv/rdk/robot.hpp>
11 #include <flexiv/rdk/scheduler.hpp>
12 #include <flexiv/rdk/utility.hpp>
13 #include <spdlog/spdlog.h>
14 
15 #include <iostream>
16 #include <cmath>
17 #include <thread>
18 #include <atomic>
19 
20 using namespace flexiv;
21 
22 namespace {
24 constexpr double kLoopPeriod = 0.001;
25 
27 constexpr double kSwingAmp = 0.1;
28 
30 constexpr double kSwingFreq = 0.3;
31 
33 constexpr double kPressingForce = 5.0;
34 
36 constexpr double kSearchVelocity = 0.02;
37 
39 constexpr double kSearchDistance = 1.0;
40 
42 const std::array<double, rdk::kCartDoF> kMaxWrenchForContactSearch
43  = {10.0, 10.0, 10.0, 3.0, 3.0, 3.0};
44 
46 std::atomic<bool> g_stop_sched = {false};
47 }
48 
50 void PrintHelp()
51 {
52  // clang-format off
53  std::cout << "Required arguments: [robot_sn]" << std::endl;
54  std::cout << " robot_sn: Serial number of the robot to connect. Remove any space, e.g. Rizon4s-123456" << std::endl;
55  std::cout << "Optional arguments: [--TCP] [--polish]" << std::endl;
56  std::cout << " --TCP: use TCP frame as reference frame for force control, otherwise use world frame" << std::endl;
57  std::cout << " --polish: run a simple polish motion along XY plane in world frame, otherwise hold robot motion in non-force-control axes"
58  << std::endl
59  << std::endl;
60  // clang-format on
61 }
62 
64 void PeriodicTask(rdk::Robot& robot, const std::array<double, rdk::kPoseSize>& init_pose,
65  rdk::CoordType force_ctrl_frame, bool enable_polish)
66 {
67  // Local periodic loop counter
68  static uint64_t loop_counter = 0;
69 
70  try {
71  // Monitor fault on the connected robot
72  if (robot.fault()) {
73  throw std::runtime_error(
74  "PeriodicTask: Fault occurred on the connected robot, exiting ...");
75  }
76 
77  // Initialize target pose to initial pose
78  auto target_pose = init_pose;
79 
80  // Set Fz according to reference frame to achieve a "pressing down" behavior
81  double Fz = 0.0;
82  if (force_ctrl_frame == rdk::CoordType::WORLD) {
83  Fz = kPressingForce;
84  } else if (force_ctrl_frame == rdk::CoordType::TCP) {
85  Fz = -kPressingForce;
86  }
87  std::array<double, rdk::kCartDoF> target_wrench = {0.0, 0.0, Fz, 0.0, 0.0, 0.0};
88 
89  // Apply constant force along Z axis of chosen reference frame, and do a simple polish
90  // motion along XY plane in robot world frame
91  if (enable_polish) {
92  // Create motion command to sine-sweep along Y direction
93  target_pose[1] = init_pose[1]
94  + kSwingAmp * sin(2 * M_PI * kSwingFreq * loop_counter * kLoopPeriod);
95  // Command target pose and target wrench
96  robot.StreamCartesianMotionForce(target_pose, target_wrench);
97  }
98  // Apply constant force along Z axis of chosen reference frame, and hold motions in all
99  // other axes
100  else {
101  // Command initial pose and target wrench
102  robot.StreamCartesianMotionForce(init_pose, target_wrench);
103  }
104 
105  // Increment loop counter
106  loop_counter++;
107 
108  } catch (const std::exception& e) {
109  spdlog::error(e.what());
110  g_stop_sched = true;
111  }
112 }
113 
114 int main(int argc, char* argv[])
115 {
116  // Program Setup
117  // =============================================================================================
118  // Parse parameters
119  if (argc < 2 || rdk::utility::ProgramArgsExistAny(argc, argv, {"-h", "--help"})) {
120  PrintHelp();
121  return 1;
122  }
123  // Serial number of the robot to connect to. Remove any space, for example: Rizon4s-123456
124  std::string robot_sn = argv[1];
125 
126  // Print description
127  spdlog::info(
128  ">>> Tutorial description <<<\nThis tutorial runs real-time Cartesian-space unified "
129  "motion-force control. The Z axis of the chosen reference frame will be activated for "
130  "explicit force control, while the rest axes in the same reference frame will stay motion "
131  "controlled.\n");
132 
133  // The reference frame used for force control, see Robot::SetForceControlFrame()
134  auto force_ctrl_frame = rdk::CoordType::WORLD;
135  if (rdk::utility::ProgramArgsExist(argc, argv, "--TCP")) {
136  spdlog::info("Reference frame used for force control: robot TCP frame");
137  force_ctrl_frame = rdk::CoordType::TCP;
138  } else {
139  spdlog::info("Reference frame used for force control: robot world frame");
140  }
141 
142  // Whether to enable polish motion
143  bool enable_polish = false;
144  if (rdk::utility::ProgramArgsExist(argc, argv, "--polish")) {
145  spdlog::info("Robot will run a polish motion along XY plane in robot world frame");
146  enable_polish = true;
147  } else {
148  spdlog::info("Robot will hold its motion in all non-force-controlled axes");
149  }
150 
151  try {
152  // RDK Initialization
153  // =========================================================================================
154  // Instantiate robot interface
155  rdk::Robot robot(robot_sn);
156 
157  // Clear fault on the connected robot if any
158  if (robot.fault()) {
159  spdlog::warn("Fault occurred on the connected robot, trying to clear ...");
160  // Try to clear the fault
161  if (!robot.ClearFault()) {
162  spdlog::error("Fault cannot be cleared, exiting ...");
163  return 1;
164  }
165  spdlog::info("Fault on the connected robot is cleared");
166  }
167 
168  // Enable the robot, make sure the E-stop is released before enabling
169  spdlog::info("Enabling robot ...");
170  robot.Enable();
171 
172  // Wait for the robot to become operational
173  while (!robot.operational()) {
174  std::this_thread::sleep_for(std::chrono::seconds(1));
175  }
176  spdlog::info("Robot is now operational");
177 
178  // Move robot to home pose
179  spdlog::info("Moving to home pose");
180  robot.SwitchMode(rdk::Mode::NRT_PLAN_EXECUTION);
181  robot.ExecutePlan("PLAN-Home");
182  // Wait for the plan to finish
183  while (robot.busy()) {
184  std::this_thread::sleep_for(std::chrono::seconds(1));
185  }
186 
187  // Zero Force-torque Sensor
188  // =========================================================================================
189  robot.SwitchMode(rdk::Mode::NRT_PRIMITIVE_EXECUTION);
190  // IMPORTANT: must zero force/torque sensor offset for accurate force/torque measurement
191  robot.ExecutePrimitive("ZeroFTSensor", std::map<std::string, rdk::FlexivDataTypes> {});
192 
193  // WARNING: during the process, the robot must not contact anything, otherwise the result
194  // will be inaccurate and affect following operations
195  spdlog::warn(
196  "Zeroing force/torque sensors, make sure nothing is in contact with the robot");
197 
198  // Wait for primitive completion
199  while (robot.busy()) {
200  std::this_thread::sleep_for(std::chrono::seconds(1));
201  }
202  spdlog::info("Sensor zeroing complete");
203 
204  // Search for Contact
205  // =========================================================================================
206  // NOTE: there are several ways to do contact search, such as using primitives, or real-time
207  // and non-real-time direct motion controls, etc. Here we use non-real-time direct Cartesian
208  // control for example.
209  spdlog::info("Searching for contact ...");
210 
211  // Set initial pose to current TCP pose
212  auto init_pose = robot.states().tcp_pose;
213  spdlog::info("Initial TCP pose set to [position 3x1, rotation (quaternion) 4x1]: "
214  + rdk::utility::Arr2Str(init_pose));
215 
216  // Use non-real-time mode to make the robot go to a set point with its own motion generator
217  robot.SwitchMode(rdk::Mode::NRT_CARTESIAN_MOTION_FORCE);
218 
219  // Search for contact with max contact wrench set to a small value for making soft contact
220  robot.SetMaxContactWrench(kMaxWrenchForContactSearch);
221 
222  // Set target point along -Z direction and expect contact to happen during the travel
223  auto target_pose = init_pose;
224  target_pose[2] -= kSearchDistance;
225 
226  // Send target point to robot to start searching for contact and limit the velocity. Keep
227  // target wrench 0 at this stage since we are not doing force control yet
228  robot.SendCartesianMotionForce(target_pose, {}, kSearchVelocity);
229 
230  // Use a while loop to poll robot states and check if a contact is made
231  bool is_contacted = false;
232  while (!is_contacted) {
233  // Compute norm of sensed external force applied on robot TCP
234  Eigen::Vector3d ext_force = {robot.states().ext_wrench_in_world[0],
235  robot.states().ext_wrench_in_world[1], robot.states().ext_wrench_in_world[2]};
236 
237  // Contact is considered to be made if sensed TCP force exceeds the threshold
238  if (ext_force.norm() > kPressingForce) {
239  is_contacted = true;
240  spdlog::info("Contact detected at robot TCP");
241  }
242  // Check at 1ms interval
243  std::this_thread::sleep_for(std::chrono::milliseconds(1));
244  }
245 
246  // Configure Force Control
247  // =========================================================================================
248  // Switch to real-time mode for continuous motion force control
249  robot.SwitchMode(rdk::Mode::RT_CARTESIAN_MOTION_FORCE);
250 
251  // Set force control reference frame based on program argument. See function doc for more
252  // details
253  robot.SetForceControlFrame(force_ctrl_frame);
254 
255  // Set which Cartesian axis(s) to activate for force control. See function doc for more
256  // details. Here we only active Z axis
257  robot.SetForceControlAxis(
258  std::array<bool, rdk::kCartDoF> {false, false, true, false, false, false});
259 
260  // Uncomment the following line to enable passive force control, otherwise active force
261  // control is used by default. See function doc for more details
262  /* robot.setPassiveForceControl(true); */
263 
264  // NOTE: motion control always uses robot world frame, while force control can use
265  // either world or TCP frame as reference frame
266 
267  // Start Unified Motion Force Control
268  // =========================================================================================
269  // Disable max contact wrench regulation. Need to do this AFTER the force control in Z axis
270  // is activated (i.e. motion control disabled in Z axis) and the motion force control mode
271  // is entered, this way the contact force along Z axis is explicitly regulated and will not
272  // spike after the max contact wrench regulation for motion control is disabled
273  std::array<double, rdk::kCartDoF> inf;
274  inf.fill(std::numeric_limits<double>::infinity());
275  robot.SetMaxContactWrench(inf);
276 
277  // Update initial pose to current TCP pose
278  init_pose = robot.states().tcp_pose;
279 
280  // Create real-time scheduler to run periodic tasks
281  rdk::Scheduler scheduler;
282  // Add periodic task with 1ms interval and highest applicable priority
283  scheduler.AddTask(std::bind(PeriodicTask, std::ref(robot), std::ref(init_pose),
284  std::ref(force_ctrl_frame), enable_polish),
285  "HP periodic", 1, scheduler.max_priority());
286  // Start all added tasks
287  scheduler.Start();
288 
289  // Block and wait for signal to stop scheduler tasks
290  while (!g_stop_sched) {
291  std::this_thread::sleep_for(std::chrono::milliseconds(1));
292  }
293  // Received signal to stop scheduler tasks
294  scheduler.Stop();
295 
296  } catch (const std::exception& e) {
297  spdlog::error(e.what());
298  return 1;
299  }
300 
301  return 0;
302 }
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...
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 SetForceControlFrame(CoordType root_coord, const std::array< double, kPoseSize > &T_in_root={0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0})
[Blocking] Set reference frame for force control while in the Cartesian motion-force control modes....
void SwitchMode(Mode mode)
[Blocking] Switch to a new control mode and wait until mode transition is finished.
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 SendCartesianMotionForce(const std::array< double, kPoseSize > &pose, const std::array< double, kCartDoF > &wrench={}, double max_linear_vel=0.5, double max_angular_vel=1.0, double max_linear_acc=2.0, double max_angular_acc=5.0)
[Non-blocking] Discretely send Cartesian motion and/or force command for the robot to track using its...
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...
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...
CoordType
Type of commonly-used reference coordinates.
Definition: data.hpp:58
std::array< double, kCartDoF > ext_wrench_in_world
Definition: data.hpp:247
std::array< double, kPoseSize > tcp_pose
Definition: data.hpp:208