forked from UniversalRobots/Universal_Robots_Client_Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathur_driver.cpp
329 lines (285 loc) · 10.9 KB
/
ur_driver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2019 FZI Forschungszentrum Informatik
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Many parts from this (Most of the URScript program) comes from the ur_modern_driver
// Copyright 2017, 2018 Simon Rasmussen (refactor)
// Copyright 2015, 2016 Thomas Timm Andersen (original version)
//
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Felix Exner [email protected]
* \date 2019-04-11
*
*/
//----------------------------------------------------------------------
#include "ur_client_library/ur/ur_driver.h"
#include "ur_client_library/exceptions.h"
#include "ur_client_library/primary/primary_parser.h"
#include <memory>
#include <sstream>
#include <ur_client_library/ur/calibration_checker.h>
namespace urcl
{
static const int32_t MULT_JOINTSTATE = 1000000;
static const std::string BEGIN_REPLACE("{{BEGIN_REPLACE}}");
static const std::string JOINT_STATE_REPLACE("{{JOINT_STATE_REPLACE}}");
static const std::string SERVO_J_REPLACE("{{SERVO_J_REPLACE}}");
static const std::string SERVER_IP_REPLACE("{{SERVER_IP_REPLACE}}");
static const std::string SERVER_PORT_REPLACE("{{SERVER_PORT_REPLACE}}");
urcl::UrDriver::UrDriver(const std::string& robot_ip, const std::string& script_file,
const std::string& output_recipe_file, const std::string& input_recipe_file,
std::function<void(bool)> handle_program_state, bool headless_mode,
std::unique_ptr<ToolCommSetup> tool_comm_setup, const std::string& calibration_checksum,
const uint32_t reverse_port, const uint32_t script_sender_port, int servoj_gain,
double servoj_lookahead_time, bool non_blocking_read)
: servoj_time_(0.008)
, servoj_gain_(servoj_gain)
, servoj_lookahead_time_(servoj_lookahead_time)
, reverse_interface_active_(false)
, reverse_port_(reverse_port)
, handle_program_state_(handle_program_state)
, robot_ip_(robot_ip)
{
URCL_LOG_DEBUG("Initializing urdriver");
URCL_LOG_DEBUG("Initializing RTDE client");
rtde_client_.reset(new rtde_interface::RTDEClient(robot_ip_, notifier_, output_recipe_file, input_recipe_file));
primary_stream_.reset(
new comm::URStream<primary_interface::PrimaryPackage>(robot_ip_, urcl::primary_interface::UR_PRIMARY_PORT));
secondary_stream_.reset(
new comm::URStream<primary_interface::PrimaryPackage>(robot_ip_, urcl::primary_interface::UR_SECONDARY_PORT));
secondary_stream_->connect();
URCL_LOG_INFO("Checking if calibration data matches connected robot.");
checkCalibration(calibration_checksum);
non_blocking_read_ = non_blocking_read;
get_packet_timeout_ = non_blocking_read_ ? 0 : 100;
if (!rtde_client_->init())
{
throw UrException("Initialization of RTDE client went wrong.");
}
rtde_frequency_ = rtde_client_->getMaxFrequency();
servoj_time_ = 1.0 / rtde_frequency_;
std::string local_ip = rtde_client_->getIP();
std::string prog = readScriptFile(script_file);
while (prog.find(JOINT_STATE_REPLACE) != std::string::npos)
{
prog.replace(prog.find(JOINT_STATE_REPLACE), JOINT_STATE_REPLACE.length(), std::to_string(MULT_JOINTSTATE));
}
std::ostringstream out;
out << "lookahead_time=" << servoj_lookahead_time_ << ", gain=" << servoj_gain_;
while (prog.find(SERVO_J_REPLACE) != std::string::npos)
{
prog.replace(prog.find(SERVO_J_REPLACE), SERVO_J_REPLACE.length(), out.str());
}
while (prog.find(SERVER_IP_REPLACE) != std::string::npos)
{
prog.replace(prog.find(SERVER_IP_REPLACE), SERVER_IP_REPLACE.length(), local_ip);
}
while (prog.find(SERVER_PORT_REPLACE) != std::string::npos)
{
prog.replace(prog.find(SERVER_PORT_REPLACE), SERVER_PORT_REPLACE.length(), std::to_string(reverse_port));
}
robot_version_ = rtde_client_->getVersion();
std::stringstream begin_replace;
if (tool_comm_setup != nullptr)
{
if (robot_version_.major < 5)
{
throw ToolCommNotAvailable("Tool communication setup requested, but this robot version does not support using "
"the tool communication interface. Please check your configuration.",
5, robot_version_.major);
}
begin_replace << "set_tool_voltage("
<< static_cast<std::underlying_type<ToolVoltage>::type>(tool_comm_setup->getToolVoltage()) << ")\n";
begin_replace << "set_tool_communication("
<< "True"
<< ", " << tool_comm_setup->getBaudRate() << ", "
<< static_cast<std::underlying_type<Parity>::type>(tool_comm_setup->getParity()) << ", "
<< tool_comm_setup->getStopBits() << ", " << tool_comm_setup->getRxIdleChars() << ", "
<< tool_comm_setup->getTxIdleChars() << ")";
}
prog.replace(prog.find(BEGIN_REPLACE), BEGIN_REPLACE.length(), begin_replace.str());
in_headless_mode_ = headless_mode;
if (in_headless_mode_)
{
full_robot_program_ = "def externalControl():\n";
std::istringstream prog_stream(prog);
std::string line;
while (std::getline(prog_stream, line))
{
full_robot_program_ += "\t" + line + "\n";
}
full_robot_program_ += "end\n";
sendRobotProgram();
}
else
{
script_sender_.reset(new comm::ScriptSender(script_sender_port, prog));
script_sender_->start();
URCL_LOG_DEBUG("Created script sender");
}
reverse_port_ = reverse_port;
watchdog_thread_ = std::thread(&UrDriver::startWatchdog, this);
URCL_LOG_DEBUG("Initialization done");
}
std::unique_ptr<rtde_interface::DataPackage> urcl::UrDriver::getDataPackage()
{
// This can take one of two values, 0ms or 100ms. The large timeout is for when the robot is commanding the control
// loop's timing (read is blocking). The zero timeout is for when the robot is sharing a control loop with
// something else (combined_robot_hw)
std::chrono::milliseconds timeout(get_packet_timeout_);
return rtde_client_->getDataPackage(timeout);
}
bool UrDriver::writeJointCommand(const vector6d_t& values, const comm::ControlMode control_mode)
{
if (reverse_interface_active_)
{
return reverse_interface_->write(&values, control_mode);
}
return false;
}
bool UrDriver::writeKeepalive()
{
if (reverse_interface_active_)
{
vector6d_t* fake = nullptr;
return reverse_interface_->write(fake, comm::ControlMode::MODE_IDLE);
}
return false;
}
void UrDriver::startRTDECommunication()
{
rtde_client_->start();
}
bool UrDriver::stopControl()
{
if (reverse_interface_active_)
{
vector6d_t* fake = nullptr;
return reverse_interface_->write(fake, comm::ControlMode::MODE_STOPPED);
}
return false;
}
void UrDriver::startWatchdog()
{
handle_program_state_(false);
reverse_interface_.reset(new comm::ReverseInterface(reverse_port_));
reverse_interface_active_ = true;
URCL_LOG_DEBUG("Created reverse interface");
while (true)
{
URCL_LOG_INFO("Robot ready to receive control commands.");
handle_program_state_(true);
while (reverse_interface_active_ == true)
{
std::string keepalive = readKeepalive();
if (keepalive == std::string(""))
{
reverse_interface_active_ = false;
}
}
URCL_LOG_INFO("Connection to robot dropped, waiting for new connection.");
handle_program_state_(false);
// We explicitly call the destructor here, as unique_ptr.reset() creates a new object before
// replacing the pointer and destroying the old object. This will result in a resource conflict
// when trying to bind the socket.
// TODO: It would probably make sense to keep the same instance alive for the complete runtime
// instead of killing it all the time.
reverse_interface_->~ReverseInterface();
reverse_interface_.reset(new comm::ReverseInterface(reverse_port_));
reverse_interface_active_ = true;
}
}
std::string UrDriver::readScriptFile(const std::string& filename)
{
std::ifstream ifs(filename);
std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
return content;
}
std::string UrDriver::readKeepalive()
{
if (reverse_interface_active_)
{
return reverse_interface_->readKeepalive();
}
else
{
return std::string("");
}
}
void UrDriver::checkCalibration(const std::string& checksum)
{
if (primary_stream_ == nullptr)
{
throw std::runtime_error("checkCalibration() called without a primary interface connection being established.");
}
primary_interface::PrimaryParser parser;
comm::URProducer<primary_interface::PrimaryPackage> prod(*primary_stream_, parser);
prod.setupProducer();
CalibrationChecker consumer(checksum);
comm::INotifier notifier;
comm::Pipeline<primary_interface::PrimaryPackage> pipeline(prod, &consumer, "Pipeline", notifier);
pipeline.run();
while (!consumer.isChecked())
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
URCL_LOG_DEBUG("Got calibration information from robot.");
}
rtde_interface::RTDEWriter& UrDriver::getRTDEWriter()
{
return rtde_client_->getWriter();
}
bool UrDriver::sendScript(const std::string& program)
{
if (secondary_stream_ == nullptr)
{
throw std::runtime_error("Sending script to robot requested while there is no primary interface established. This "
"should not happen.");
}
// urscripts (snippets) must end with a newline, or otherwise the controller's runtime will
// not execute them. To avoid problems, we always just append a newline here, even if
// there may already be one.
auto program_with_newline = program + '\n';
size_t len = program_with_newline.size();
const uint8_t* data = reinterpret_cast<const uint8_t*>(program_with_newline.c_str());
size_t written;
if (secondary_stream_->write(data, len, written))
{
URCL_LOG_DEBUG("Sent program to robot:\n%s", program_with_newline.c_str());
return true;
}
URCL_LOG_ERROR("Could not send program to robot");
return false;
}
bool UrDriver::sendRobotProgram()
{
if (in_headless_mode_)
{
return sendScript(full_robot_program_);
}
else
{
URCL_LOG_ERROR("Tried to send robot program directly while not in headless mode");
return false;
}
}
std::vector<std::string> UrDriver::getRTDEOutputRecipe()
{
return rtde_client_->getOutputRecipe();
}
} // namespace urcl