-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathRobotInterface.cpp
439 lines (371 loc) · 13.9 KB
/
RobotInterface.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*
* Copyright (C) 2018 Istituto Italiano di Tecnologia (IIT)
* All rights reserved.
*
* This software may be modified and distributed under the terms of the
* GNU Lesser General Public License v2.1 or any later version.
*/
#include "WBToolbox/Base/RobotInterface.h"
#include "WBToolbox/Base/Configuration.h"
#include <BlockFactory/Core/Log.h>
#include <iDynTree/KinDynComputations.h>
#include <iDynTree/Model/FreeFloatingMatrices.h>
#include <iDynTree/Model/Indices.h>
#include <iDynTree/Model/Model.h>
#include <iDynTree/ModelIO/ModelLoader.h>
#include <yarp/dev/ControlBoardInterfaces.h>
#include <yarp/dev/PolyDriver.h>
#include <yarp/os/Bottle.h>
#include <yarp/os/Network.h>
#include <yarp/os/Property.h>
#include <yarp/os/ResourceFinder.h>
#include <cassert>
#include <chrono>
#include <functional>
#include <sstream>
#include <thread>
#include <utility>
#include <vector>
using namespace wbt::base;
// ====================
// ROBOTINTERFACE PIMPL
// ====================
struct YarpInterfaces
{
yarp::dev::IControlMode* iControlMode = nullptr;
yarp::dev::IPositionControl* iPositionControl = nullptr;
yarp::dev::IPositionDirect* iPositionDirect = nullptr;
yarp::dev::IVelocityControl* iVelocityControl = nullptr;
yarp::dev::ITorqueControl* iTorqueControl = nullptr;
yarp::dev::IPWMControl* iPWMControl = nullptr;
yarp::dev::ICurrentControl* iCurrentControl = nullptr;
yarp::dev::IEncoders* iEncoders = nullptr;
yarp::dev::IMotorEncoders* iMotorEncoders = nullptr;
yarp::dev::IControlLimits* iControlLimits = nullptr;
yarp::dev::IPidControl* iPidControl = nullptr;
};
class RobotInterface::impl
{
public:
std::unique_ptr<yarp::os::Network> network = nullptr;
std::unique_ptr<yarp::dev::PolyDriver> robotDevice;
std::shared_ptr<iDynTree::KinDynComputations> kinDynComp;
YarpInterfaces yarpInterfaces;
const Configuration config; // Configuration from Simulink Block's parameters
impl() = delete;
explicit impl(const Configuration& configuration)
: config(configuration)
{}
template <typename T>
T* getInterfaceLazyEval(T*& interface,
const std::unique_ptr<yarp::dev::PolyDriver>& cbRemapper);
bool checkInterface(std::function<bool(double*)>& getMeasurement)
{
// This method is used only on interfaces which get measurements. There is an interval right
// after the allocation of the RemoteControlBoardRemapper when a get*() calls from a viewed
// interface will return false. This failure is not due to a wrong usage of the interface,
// but rather to a call before the interface actually receives data.
unsigned counter = 0;
constexpr unsigned maxIter = 100;
std::vector<double> buffer(config.getNumberOfDoFs(), 0);
while (!getMeasurement(buffer.data())) {
if (++counter == maxIter) {
bfError << "Failed to get a measurement during the interface initialization.";
return false;
}
// Sleep for some while
std::this_thread::sleep_for(std::chrono::microseconds(500));
}
return true;
}
bool initializeModel()
{
assert(!kinDynComp);
// Allocate the object
kinDynComp = std::make_shared<iDynTree::KinDynComputations>();
if (!kinDynComp)
return false;
// Explicitly set the velocity representation
kinDynComp->setFrameVelocityRepresentation(iDynTree::MIXED_REPRESENTATION);
// Use RF to load the urdf file
// ----------------------------
// Initialize RF
// Workaround for the fact that ResourceFinder initializes the network by itself. See
// YARP#1014
using namespace yarp::os;
Network network;
ResourceFinder& rf = ResourceFinder::getResourceFinderSingleton();
rf.configure(0, nullptr);
// Get the absolute path of the urdf file
std::string urdf_file = config.getUrdfFile();
std::string urdf_file_path = rf.findFile(urdf_file.c_str());
// Fail if the file is not found
if (urdf_file_path.empty()) {
bfError << "ResourceFinder couldn't find urdf file " + urdf_file + ".";
return false;
}
// Load the reduced model into KinDynComputations
// ----------------------------------------------
// Load the joint list
std::vector<std::string> controlledJoints = config.getControlledJoints();
// Use ModelLoader to load the reduced model
iDynTree::ModelLoader mdlLoader;
if (!mdlLoader.loadReducedModelFromFile(urdf_file_path, controlledJoints)) {
bfError << "Impossible to load " + urdf_file + "." << std::endl
<< "Possible causes: file not found, or the joint "
<< "list contains an entry not present in the urdf model.";
return false;
}
// Add the loaded model to the KinDynComputations object
return kinDynComp->loadRobotModel(mdlLoader.model());
}
bool initializeRemoteControlBoardRemapper()
{
if (!network) {
network = std::make_unique<yarp::os::Network>();
}
// Initialize the network
if (!yarp::os::Network::initialized() || !yarp::os::Network::checkNetwork(5.0)) {
bfError << "YARP server wasn't found active.";
return false;
}
// Object where the RemoteControlBoardRemapper options will be stored
yarp::os::Property options;
// Name of the device
options.put("device", "remotecontrolboardremapper");
// Controlled joints (axes)
yarp::os::Bottle axesNames;
yarp::os::Bottle& axesList = axesNames.addList();
for (auto axis : config.getControlledJoints()) {
axesList.addString(axis);
}
options.put("axesNames", axesNames.get(0));
// ControlBoard names
yarp::os::Bottle remoteControlBoards;
yarp::os::Bottle& remoteControlBoardsList = remoteControlBoards.addList();
for (auto cb : config.getControlBoardsNames()) {
remoteControlBoardsList.addString("/" + config.getRobotName() + "/" + cb);
}
options.put("remoteControlBoards", remoteControlBoards.get(0));
// Prefix of the openened ports
// In this case appending the unique id is necessary, since multiple configuration can
// share some ControlBoard in their RemoteControlBoardRemappers. In this case, it is not
// possible using the same prefix for all the RemoteControlBoardRemapper devices.
options.put("localPortPrefix", config.getLocalName() + "/" + config.getUniqueId());
// Misc options
yarp::os::Property& remoteCBOpts = options.addGroup("REMOTE_CONTROLBOARD_OPTIONS");
remoteCBOpts.put("writeStrict", "on");
// Allocate the interface driver
robotDevice = std::unique_ptr<yarp::dev::PolyDriver>(new yarp::dev::PolyDriver());
if (!robotDevice) {
bfError << "Failed to instantiante an empty PolyDriver class.";
return false;
}
// Open the interface driver
if (!robotDevice->open(options) && !robotDevice->isValid()) {
// Remove garbage if the opening fails
robotDevice.reset();
bfError << "Failed to open the RemoteControlBoardRemapper with the options passed.";
return false;
}
return true;
}
};
// ==============
// ROBOTINTERFACE
// ==============
// CONSTRUCTOR / DESTRUCTOR
// ========================
RobotInterface::RobotInterface(const Configuration& config)
: pImpl{new impl(config)}
{}
RobotInterface::~RobotInterface()
{
// Close the RemoteControlBoardRemapper
if (pImpl->robotDevice) {
pImpl->robotDevice->close();
}
}
// GET METHODS
// ===========
const Configuration& RobotInterface::getConfiguration() const
{
return pImpl->config;
}
const std::shared_ptr<iDynTree::KinDynComputations> RobotInterface::getKinDynComputations()
{
if (pImpl->kinDynComp) {
return pImpl->kinDynComp;
}
// Otherwise, initialize a new object
if (!pImpl->initializeModel()) {
bfError << "Failed to initialize the KinDynComputations object.";
// Return an empty shared_ptr (implicitly initialized)
return nullptr;
}
return pImpl->kinDynComp;
}
// TEMPLATED METHODS
// =================
template <typename T>
T* RobotInterface::impl::getInterfaceLazyEval(
T*& interface,
const std::unique_ptr<yarp::dev::PolyDriver>& cbRemapper)
{
if (!interface) {
// Lazy-initialize the RemoteControlBoardRemapper device
if (!cbRemapper) {
if (!initializeRemoteControlBoardRemapper()) {
bfError << "Failed to initialize the RemoteControlBoardRemapper.";
return nullptr;
}
}
// Ask the interface from the device
if (!robotDevice->view(interface)) {
bfError << "Failed to view the interface.";
return nullptr;
}
}
// Return the raw pointer
return interface;
}
template <>
bool RobotInterface::getInterface(yarp::dev::IControlMode*& interface)
{
interface = pImpl->getInterfaceLazyEval(pImpl->yarpInterfaces.iControlMode, pImpl->robotDevice);
return static_cast<bool>(interface);
}
template <>
bool RobotInterface::getInterface(yarp::dev::IPositionControl*& interface)
{
interface =
pImpl->getInterfaceLazyEval(pImpl->yarpInterfaces.iPositionControl, pImpl->robotDevice);
return interface;
}
template <>
bool RobotInterface::getInterface(yarp::dev::IPositionDirect*& interface)
{
interface =
pImpl->getInterfaceLazyEval(pImpl->yarpInterfaces.iPositionDirect, pImpl->robotDevice);
return interface;
}
template <>
bool RobotInterface::getInterface(yarp::dev::IVelocityControl*& interface)
{
interface =
pImpl->getInterfaceLazyEval(pImpl->yarpInterfaces.iVelocityControl, pImpl->robotDevice);
return interface;
}
template <>
bool RobotInterface::getInterface(yarp::dev::ITorqueControl*& interface)
{
auto& storedInterface = pImpl->yarpInterfaces.iTorqueControl;
if (!storedInterface) {
// Get the interface
if (!pImpl->getInterfaceLazyEval(storedInterface, pImpl->robotDevice)) {
return false;
}
// Check if it works fine
std::function<bool(double*)> getMeas = std::bind(
&yarp::dev::ITorqueControl::getTorques, storedInterface, std::placeholders::_1);
if (!pImpl->checkInterface(getMeas)) {
return false;
}
}
// Return a pointer to the interface to the caller
interface = storedInterface;
return static_cast<bool>(interface);
}
template <>
bool RobotInterface::getInterface(yarp::dev::IPWMControl*& interface)
{
auto& storedInterface = pImpl->yarpInterfaces.iPWMControl;
if (!storedInterface) {
// Get the interface
if (!pImpl->getInterfaceLazyEval(storedInterface, pImpl->robotDevice)) {
return false;
}
// Check if it works fine
std::function<bool(double*)> getMeas = std::bind(
&yarp::dev::IPWMControl::getDutyCycles, storedInterface, std::placeholders::_1);
if (!pImpl->checkInterface(getMeas)) {
return false;
}
}
// Return a pointer to the interface to the caller
interface = storedInterface;
return static_cast<bool>(interface);
}
template <>
bool RobotInterface::getInterface(yarp::dev::ICurrentControl*& interface)
{
auto& storedInterface = pImpl->yarpInterfaces.iCurrentControl;
if (!storedInterface) {
// Get the interface
if (!pImpl->getInterfaceLazyEval(storedInterface, pImpl->robotDevice)) {
return false;
}
// Check if it works fine
std::function<bool(double*)> getMeas = std::bind(
&yarp::dev::ICurrentControl::getCurrents, storedInterface, std::placeholders::_1);
if (!pImpl->checkInterface(getMeas)) {
return false;
}
}
// Return a pointer to the interface to the caller
interface = storedInterface;
return static_cast<bool>(interface);
}
template <>
bool RobotInterface::getInterface(yarp::dev::IEncoders*& interface)
{
auto& storedInterface = pImpl->yarpInterfaces.iEncoders;
if (!storedInterface) {
// Get the interface
if (!pImpl->getInterfaceLazyEval(storedInterface, pImpl->robotDevice)) {
return false;
}
// Check if it works fine
std::function<bool(double*)> getMeas =
std::bind(&yarp::dev::IEncoders::getEncoders, storedInterface, std::placeholders::_1);
if (!pImpl->checkInterface(getMeas)) {
return false;
}
}
// Return a pointer to the interface to the caller
interface = storedInterface;
return static_cast<bool>(interface);
}
template <>
bool RobotInterface::getInterface(yarp::dev::IMotorEncoders*& interface)
{
auto& storedInterface = pImpl->yarpInterfaces.iMotorEncoders;
if (!storedInterface) {
// Get the interface
if (!pImpl->getInterfaceLazyEval(storedInterface, pImpl->robotDevice)) {
return false;
}
// Check if it works fine
std::function<bool(double*)> getMeas = std::bind(
&yarp::dev::IMotorEncoders::getMotorEncoders, storedInterface, std::placeholders::_1);
if (!pImpl->checkInterface(getMeas)) {
return false;
}
}
// Return a pointer to the interface to the caller
interface = storedInterface;
return static_cast<bool>(interface);
}
template <>
bool RobotInterface::getInterface(yarp::dev::IControlLimits*& interface)
{
interface =
pImpl->getInterfaceLazyEval(pImpl->yarpInterfaces.iControlLimits, pImpl->robotDevice);
return interface;
}
template <>
bool RobotInterface::getInterface(yarp::dev::IPidControl*& interface)
{
interface = pImpl->getInterfaceLazyEval(pImpl->yarpInterfaces.iPidControl, pImpl->robotDevice);
return interface;
}