Flexiv RDK APIs  1.6.0
intermediate2_realtime_joint_impedance_control.cpp
1 
8 #include <flexiv/rdk/robot.hpp>
10 #include <flexiv/rdk/utility.hpp>
11 #include <spdlog/spdlog.h>
12 
13 #include <iostream>
14 #include <string>
15 #include <cmath>
16 #include <thread>
17 #include <atomic>
18 
19 using namespace flexiv;
20 
21 namespace {
23 constexpr double kLoopPeriod = 0.001;
24 
26 constexpr double kSineAmp = 0.035;
27 constexpr double kSineFreq = 0.3;
28 
30 std::atomic<bool> g_stop_sched = {false};
31 }
32 
34 void PrintHelp()
35 {
36  // clang-format off
37  std::cout << "Required arguments: [robot_sn]" << std::endl;
38  std::cout << " robot_sn: Serial number of the robot to connect. Remove any space, e.g. Rizon4s-123456" << std::endl;
39  std::cout << "Optional arguments: [--hold]" << std::endl;
40  std::cout << " --hold: robot holds current joint positions, otherwise do a sine-sweep" << std::endl;
41  std::cout << std::endl;
42  // clang-format on
43 }
44 
46 void PeriodicTask(
47  rdk::Robot& robot, const std::string& motion_type, const std::vector<double>& init_pos)
48 {
49  // Local periodic loop counter
50  static unsigned int loop_counter = 0;
51 
52  try {
53  // Monitor fault on the connected robot
54  if (robot.fault()) {
55  throw std::runtime_error(
56  "PeriodicTask: Fault occurred on the connected robot, exiting ...");
57  }
58 
59  // Initialize target vectors to hold position
60  std::vector<double> target_pos(robot.info().DoF);
61  std::vector<double> target_vel(robot.info().DoF);
62  std::vector<double> target_acc(robot.info().DoF);
63 
64  // Set target vectors based on motion type
65  if (motion_type == "hold") {
66  target_pos = init_pos;
67  } else if (motion_type == "sine-sweep") {
68  for (size_t i = 0; i < target_pos.size(); ++i) {
69  target_pos[i] = init_pos[i]
70  + kSineAmp * sin(2 * M_PI * kSineFreq * loop_counter * kLoopPeriod);
71  }
72  } else {
73  throw std::invalid_argument(
74  "PeriodicTask: Unknown motion type. Accepted motion types: hold, sine-sweep");
75  }
76 
77  // Reduce stiffness to half of nominal values after 5 seconds
78  if (loop_counter == 5000) {
79  auto new_Kq = robot.info().K_q_nom;
80  for (auto& v : new_Kq) {
81  v *= 0.5;
82  }
83  robot.SetJointImpedance(new_Kq);
84  spdlog::info("Joint stiffness set to [{}]", rdk::utility::Vec2Str(new_Kq));
85  }
86 
87  // Reset impedance properties to nominal values after another 5 seconds
88  if (loop_counter == 10000) {
89  robot.SetJointImpedance(robot.info().K_q_nom);
90  spdlog::info("Joint impedance properties are reset");
91  }
92 
93  // Send commands
94  robot.StreamJointPosition(target_pos, target_vel, target_acc);
95 
96  // Increment loop counter
97  loop_counter++;
98 
99  } catch (const std::exception& e) {
100  spdlog::error(e.what());
101  g_stop_sched = true;
102  }
103 }
104 
105 int main(int argc, char* argv[])
106 {
107  // Program Setup
108  // =============================================================================================
109  // Parse parameters
110  if (argc < 2 || rdk::utility::ProgramArgsExistAny(argc, argv, {"-h", "--help"})) {
111  PrintHelp();
112  return 1;
113  }
114  // Serial number of the robot to connect to. Remove any space, for example: Rizon4s-123456
115  std::string robot_sn = argv[1];
116 
117  // Print description
118  spdlog::info(
119  ">>> Tutorial description <<<\nThis tutorial runs real-time joint impedance control to "
120  "hold or sine-sweep all robot joints.\n");
121 
122  // Type of motion specified by user
123  std::string motion_type = "";
124  if (rdk::utility::ProgramArgsExist(argc, argv, "--hold")) {
125  spdlog::info("Robot holding current pose");
126  motion_type = "hold";
127  } else {
128  spdlog::info("Robot running joint sine-sweep");
129  motion_type = "sine-sweep";
130  }
131 
132  try {
133  // RDK Initialization
134  // =========================================================================================
135  // Instantiate robot interface
136  rdk::Robot robot(robot_sn);
137 
138  // Clear fault on the connected robot if any
139  if (robot.fault()) {
140  spdlog::warn("Fault occurred on the connected robot, trying to clear ...");
141  // Try to clear the fault
142  if (!robot.ClearFault()) {
143  spdlog::error("Fault cannot be cleared, exiting ...");
144  return 1;
145  }
146  spdlog::info("Fault on the connected robot is cleared");
147  }
148 
149  // Enable the robot, make sure the E-stop is released before enabling
150  spdlog::info("Enabling robot ...");
151  robot.Enable();
152 
153  // Wait for the robot to become operational
154  while (!robot.operational()) {
155  std::this_thread::sleep_for(std::chrono::seconds(1));
156  }
157  spdlog::info("Robot is now operational");
158 
159  // Move robot to home pose
160  spdlog::info("Moving to home pose");
161  robot.SwitchMode(rdk::Mode::NRT_PLAN_EXECUTION);
162  robot.ExecutePlan("PLAN-Home");
163  // Wait for the plan to finish
164  while (robot.busy()) {
165  std::this_thread::sleep_for(std::chrono::seconds(1));
166  }
167 
168  // Real-time Joint Impedance Control
169  // =========================================================================================
170  // Switch to real-time joint impedance control mode
171  robot.SwitchMode(rdk::Mode::RT_JOINT_IMPEDANCE);
172 
173  // Set initial joint positions
174  auto init_pos = robot.states().q;
175  spdlog::info("Initial joint positions set to: {}", rdk::utility::Vec2Str(init_pos));
176 
177  // Create real-time scheduler to run periodic tasks
178  rdk::Scheduler scheduler;
179  // Add periodic task with 1ms interval and highest applicable priority
180  scheduler.AddTask(
181  std::bind(PeriodicTask, std::ref(robot), std::ref(motion_type), std::ref(init_pos)),
182  "HP periodic", 1, scheduler.max_priority());
183  // Start all added tasks
184  scheduler.Start();
185 
186  // Block and wait for signal to stop scheduler tasks
187  while (!g_stop_sched) {
188  std::this_thread::sleep_for(std::chrono::milliseconds(1));
189  }
190  // Received signal to stop scheduler tasks
191  scheduler.Stop();
192 
193  } catch (const std::exception& e) {
194  spdlog::error(e.what());
195  return 1;
196  }
197 
198  return 0;
199 }
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.
const RobotStates states() const
[Non-blocking] Current states data of the robot.
void SetJointImpedance(const std::vector< double > &K_q, const std::vector< double > &Z_q={0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7})
[Blocking] Set impedance properties of the robot's joint motion controller used in the joint impedanc...
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 SwitchMode(Mode mode)
[Blocking] Switch to a new control mode and wait until mode transition is finished.
void StreamJointPosition(const std::vector< double > &positions, const std::vector< double > &velocities, const std::vector< double > &accelerations)
[Non-blocking] Continuously stream joint position, velocity, and acceleration command to the robot....
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...
std::vector< double > K_q_nom
Definition: data.hpp:97
std::vector< double > q
Definition: data.hpp:136