-
Notifications
You must be signed in to change notification settings - Fork 474
/
HarnessPlugin.cc
549 lines (478 loc) · 16.6 KB
/
HarnessPlugin.cc
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/*
* Copyright (C) 2016 Open Source Robotics Foundation
*
* 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.
*
*/
#include <mutex>
#include <boost/thread/recursive_mutex.hpp>
#include <sdf/sdf.hh>
#include "gazebo/common/PID.hh"
#include "gazebo/transport/Node.hh"
#include "gazebo/transport/Subscriber.hh"
#include "gazebo/physics/Joint.hh"
#include "gazebo/physics/Link.hh"
#include "gazebo/physics/Model.hh"
#include "gazebo/physics/PhysicsEngine.hh"
#include "gazebo/physics/World.hh"
#include "plugins/HarnessPlugin.hh"
namespace gazebo
{
/// \brief Private data for the HarnessPlugin class
class HarnessPluginPrivate
{
/// \brief sdf pointer to the <plugin> block
public: sdf::ElementPtr sdf;
/// \brief model pointer
public: physics::ModelPtr model;
/// \brief Vector of joints
public: std::vector<physics::JointPtr> joints;
/// \brief Mutex guarding access to joints vector and index variables.
public: std::recursive_mutex jointsMutex;
/// \brief Index into the joints vector that specifies the winch joint.
public: int winchIndex = -1;
/// \brief Index into the joints vector that specifies the joint to detach.
public: int detachIndex = -1;
/// \brief Name of child link of detach joint.
/// This is used when re-attaching.
public: std::string detachLinkName;
/// \brief Position PID controller for the winch
public: common::PID winchPosPID;
/// \brief Velocity PID controller for the winch
public: common::PID winchVelPID;
/// \brief Target winch position
public: float winchTargetPos = 0.0;
/// \brief Target winch velocity
public: float winchTargetVel = 0.0;
/// \brief Previous simulation time
public: common::Time prevSimTime = common::Time::Zero;
/// \brief Communication node
/// \todo: Transition to ignition-transport in gazebo8
public: transport::NodePtr node;
/// \brief Velocity control subscriber
/// \todo: Transition to ignition-transport in gazebo8
public: transport::SubscriberPtr velocitySub;
/// \brief Attach control subscriber
/// \todo: Transition to ignition-transport in gazebo8
public: transport::SubscriberPtr attachSub;
/// \brief Detach control subscriber
/// \todo: Transition to ignition-transport in gazebo8
public: transport::SubscriberPtr detachSub;
/// \brief Connection to World Update events.
public: event::ConnectionPtr updateConnection;
};
}
using namespace gazebo;
// cached value of parsed joint.sdf
sdf::ElementPtr sdfJoint;
GZ_REGISTER_MODEL_PLUGIN(HarnessPlugin)
/////////////////////////////////////////////////
HarnessPlugin::HarnessPlugin()
: dataPtr(new HarnessPluginPrivate)
{
if (!sdfJoint)
{
sdfJoint.reset(new sdf::Element);
sdf::initFile("joint.sdf", sdfJoint);
}
}
/////////////////////////////////////////////////
HarnessPlugin::~HarnessPlugin()
{
// clear subscribers and transport
this->dataPtr->updateConnection.reset();
this->dataPtr->detachSub.reset();
this->dataPtr->attachSub.reset();
this->dataPtr->velocitySub.reset();
if (this->dataPtr->node)
this->dataPtr->node->Fini();
this->dataPtr->node.reset();
}
/////////////////////////////////////////////////
void HarnessPlugin::Load(physics::ModelPtr _model,
sdf::ElementPtr _sdf)
{
// store pointers
this->dataPtr->model = _model;
this->dataPtr->sdf = _sdf;
// Load all the harness joints
this->Attach();
// Get the winch
if (_sdf->HasElement("winch"))
{
sdf::ElementPtr winchElem = _sdf->GetElement("winch");
// Load the Position PID controller
if (winchElem->HasElement("pos_pid"))
{
sdf::ElementPtr pidElem = winchElem->GetElement("pos_pid");
double pValue = pidElem->HasElement("p") ? pidElem->Get<double>("p") : 0;
double iValue = pidElem->HasElement("i") ? pidElem->Get<double>("i") : 0;
double dValue = pidElem->HasElement("d") ? pidElem->Get<double>("d") : 0;
double iMax =
pidElem->HasElement("i_max") ? pidElem->Get<double>("i_max") : 0;
double iMin =
pidElem->HasElement("i_min") ? pidElem->Get<double>("i_min") : 0;
double cmdMax =
pidElem->HasElement("cmd_max") ? pidElem->Get<double>("cmd_max") : 0;
double cmdMin =
pidElem->HasElement("cmd_min") ? pidElem->Get<double>("cmd_min") : 0;
this->dataPtr->winchPosPID.Init(pValue, iValue, dValue,
iMax, iMin, cmdMax, cmdMin);
}
// Load the Velocity PID controller
if (winchElem->HasElement("vel_pid"))
{
sdf::ElementPtr pidElem = winchElem->GetElement("vel_pid");
double pValue = pidElem->HasElement("p") ? pidElem->Get<double>("p") : 0;
double iValue = pidElem->HasElement("i") ? pidElem->Get<double>("i") : 0;
double dValue = pidElem->HasElement("d") ? pidElem->Get<double>("d") : 0;
double iMax =
pidElem->HasElement("i_max") ? pidElem->Get<double>("i_max") : 0;
double iMin =
pidElem->HasElement("i_min") ? pidElem->Get<double>("i_min") : 0;
double cmdMax =
pidElem->HasElement("cmd_max") ? pidElem->Get<double>("cmd_max") : 0;
double cmdMin =
pidElem->HasElement("cmd_min") ? pidElem->Get<double>("cmd_min") : 0;
this->dataPtr->winchVelPID.Init(pValue, iValue, dValue,
iMax, iMin, cmdMax, cmdMin);
}
}
}
/////////////////////////////////////////////////
void HarnessPlugin::Init()
{
// Get a pointer to the world
physics::WorldPtr world = this->dataPtr->model->GetWorld();
this->dataPtr->node = transport::NodePtr(new transport::Node());
this->dataPtr->node->Init(world->Name());
this->dataPtr->velocitySub = this->dataPtr->node->Subscribe(
"~/" + this->dataPtr->model->GetName() + "/harness/velocity",
&HarnessPlugin::OnVelocity, this);
this->dataPtr->attachSub = this->dataPtr->node->Subscribe(
"~/" + this->dataPtr->model->GetName() + "/harness/attach",
&HarnessPlugin::OnAttach, this);
this->dataPtr->detachSub = this->dataPtr->node->Subscribe(
"~/" + this->dataPtr->model->GetName() + "/harness/detach",
&HarnessPlugin::OnDetach, this);
if (!this->dataPtr->joints.empty())
{
this->dataPtr->updateConnection = event::Events::ConnectWorldUpdateBegin(
std::bind(&HarnessPlugin::OnUpdate, this, std::placeholders::_1));
}
}
/////////////////////////////////////////////////
void HarnessPlugin::OnUpdate(const common::UpdateInfo &_info)
{
// Bootstrap the time.
if (this->dataPtr->prevSimTime == common::Time::Zero)
{
this->dataPtr->prevSimTime = _info.simTime;
return;
}
common::Time dt = _info.simTime - this->dataPtr->prevSimTime;
std::lock_guard<std::recursive_mutex> lock(this->dataPtr->jointsMutex);
const int joints_size = static_cast<int>(this->dataPtr->joints.size());
const int winchIndex = this->dataPtr->winchIndex;
if (winchIndex < 0 ||
winchIndex >= joints_size)
{
if (this->dataPtr->detachIndex >= 0 &&
this->dataPtr->detachIndex < joints_size)
{
gzmsg << "Detaching harness joint" << std::endl;
this->Detach();
return;
}
gzerr << "No known winch joint to control" << std::endl;
return;
}
double pError = 0;
if (ignition::math::equal(this->dataPtr->winchTargetVel, 0.0f))
{
// Calculate the position error if vel target is 0
pError = this->dataPtr->joints[winchIndex]->Position(0) -
this->dataPtr->winchTargetPos;
}
// Calculate the velocity error
double vError = this->dataPtr->joints[winchIndex]->GetVelocity(0) -
this->dataPtr->winchTargetVel;
// Use the PID controller to compute the joint force
double winchPosForce = this->dataPtr->winchPosPID.Update(pError, dt);
double winchVelForce = this->dataPtr->winchVelPID.Update(vError, dt);
// Truncate winchForce so it doesn't push the robot downwards
// although this can also be accomplished by cmd_min and cmd_max.
winchVelForce = winchVelForce > 0? winchVelForce : 0.0;
// Apply the joint force
this->dataPtr->joints[winchIndex]->SetForce(0, winchVelForce + winchPosForce);
this->dataPtr->prevSimTime = _info.simTime;
}
/////////////////////////////////////////////////
void HarnessPlugin::Attach()
{
std::lock_guard<std::recursive_mutex> lock(this->dataPtr->jointsMutex);
// Load all the harness joints
sdf::ElementPtr jointElem = this->dataPtr->sdf->GetElement("joint");
while (jointElem)
{
auto jointParsed = sdfJoint->Clone();
if (sdf::readString(
std::string("<sdf version='" SDF_VERSION "'>") +
jointElem->ToString("") +
std::string("</sdf>"),
jointParsed))
{
std::string jointName = jointParsed->Get<std::string>("name");
try
{
auto joint = this->dataPtr->model->CreateJoint(jointParsed);
this->dataPtr->joints.push_back(joint);
}
catch(gazebo::common::Exception &_e)
{
gzerr << "Unable to load joint[" << jointName << "]. "
<< _e.GetErrorStr()
<< std::endl;
}
}
else
{
gzerr << "Error parsing joint xml ["
<< jointElem->ToString("")
<< "]"
<< std::endl;
}
jointElem = jointElem->GetNextElement("joint");
}
// Make sure at least one joint was created.
if (this->dataPtr->joints.empty())
{
gzerr << "No joints specified in the harness plugin."
<< "The harness plugin will not run."
<< std::endl;
return;
}
// Get the detach joint
if (this->dataPtr->sdf->HasElement("detach"))
{
std::string jointName = this->dataPtr->sdf->Get<std::string>("detach");
this->dataPtr->detachIndex = this->JointIndex(jointName);
// Error reporting
if (this->dataPtr->detachIndex < 0)
{
this->dataPtr->detachIndex = 0;
gzwarn << "Invalid <detach> joint name[" << jointName << "] in the "
<< "harness plugin. The first joint will be used as the detach "
<< "joint."
<< std::endl;
}
// Get name of child link of detach joint for when we re-attach.
auto child = this->dataPtr->joints[this->dataPtr->detachIndex]->GetChild();
if (child)
{
this->dataPtr->detachLinkName = child->GetName();
}
}
else
{
// Error reporting
gzwarn << "A <detach> element is missing from the harness plugin. "
<< "The first joint will be used as the detach joint."
<< std::endl;
}
// Get the winch
if (this->dataPtr->sdf->HasElement("winch"))
{
sdf::ElementPtr winchElem = this->dataPtr->sdf->GetElement("winch");
// Find the winch joint
if (winchElem->HasElement("joint"))
{
std::string winchJointName = winchElem->Get<std::string>("joint");
this->dataPtr->winchIndex = this->JointIndex(winchJointName);
// Error reporting
if (this->dataPtr->winchIndex < 0)
{
this->dataPtr->winchIndex = 0;
gzwarn << "Invalid <joint> name[" << winchJointName << "] in the "
<< "<winch> element of the harness plugin.\n"
<< "The first joint will be used as the winch."
<< std::endl;
}
}
else
{
// Error reporting
gzwarn << "A <winch><joint>joint_name</joint></winch> element is "
<< "missing from the harness plugin.\n"
<< "The first joint will be used as the winch."
<< std::endl;
}
}
else
{
// Error reporting
gzwarn << "A <winch> element is missing from the harness plugin. "
<< "The first joint will be used as the winch."
<< std::endl;
}
// Init the joints
for (auto &joint : this->dataPtr->joints)
{
try
{
joint->Init();
}
catch(...)
{
gzerr << "Init joint failed" << std::endl;
return;
}
}
}
/////////////////////////////////////////////////
void HarnessPlugin::Attach(const ignition::math::Pose3d &_pose)
{
std::lock_guard<std::recursive_mutex> lock(this->dataPtr->jointsMutex);
if (this->dataPtr->detachIndex >= 0 || this->dataPtr->winchIndex >= 0)
{
gzerr << "Winch or detach joints already exist, unable to attach new joint"
<< std::endl;
return;
}
ignition::math::Pose3d detachLinkOffset;
auto link = this->dataPtr->model->GetLink(this->dataPtr->detachLinkName);
if (link)
{
detachLinkOffset = link->WorldPose() - this->dataPtr->model->WorldPose();
}
else
{
gzerr << "Unable to determine link to set pose, default to canonical link"
<< std::endl;
}
this->dataPtr->model->SetWorldPose(-detachLinkOffset + _pose);
this->Attach();
this->dataPtr->winchTargetPos = 0;
this->dataPtr->winchTargetVel = 0;
if (!this->dataPtr->joints.empty())
{
this->dataPtr->updateConnection = event::Events::ConnectWorldUpdateBegin(
std::bind(&HarnessPlugin::OnUpdate, this, std::placeholders::_1));
}
}
/////////////////////////////////////////////////
void HarnessPlugin::Detach()
{
std::lock_guard<std::recursive_mutex> lock(this->dataPtr->jointsMutex);
const int joints_size = static_cast<int>(this->dataPtr->joints.size());
if (this->dataPtr->detachIndex < 0 ||
this->dataPtr->detachIndex >= joints_size)
{
gzerr << "No known joint to detach" << std::endl;
return;
}
const auto detachName =
this->dataPtr->joints[this->dataPtr->detachIndex]->GetName();
physics::BasePtr parent =
this->dataPtr->joints[this->dataPtr->detachIndex]->Base::GetParent();
auto model = boost::dynamic_pointer_cast<physics::Model>(parent);
if (!model)
{
gzerr << "Can't get valid model pointer" << std::endl;
return;
}
// We no longer need to update
this->dataPtr->updateConnection.reset();
(this->dataPtr->joints[this->dataPtr->detachIndex]).reset();
model->RemoveJoint(detachName);
this->dataPtr->detachIndex = -1;
this->dataPtr->winchIndex = -1;
this->dataPtr->joints.clear();
this->dataPtr->prevSimTime == common::Time::Zero;
}
/////////////////////////////////////////////////
double HarnessPlugin::WinchVelocity() const
{
std::lock_guard<std::recursive_mutex> lock(this->dataPtr->jointsMutex);
const int winchIndex = this->dataPtr->winchIndex;
if (winchIndex < 0 ||
winchIndex >= static_cast<int>(this->dataPtr->joints.size()))
{
gzerr << "No known winch joint to get velocity" << std::endl;
return 0;
}
return this->dataPtr->joints[winchIndex]->GetVelocity(0);
}
/////////////////////////////////////////////////
void HarnessPlugin::SetWinchVelocity(const float _value)
{
std::lock_guard<std::recursive_mutex> lock(this->dataPtr->jointsMutex);
const int winchIndex = this->dataPtr->winchIndex;
if (winchIndex < 0 ||
winchIndex >= static_cast<int>(this->dataPtr->joints.size()))
{
gzerr << "No known winch joint to set velocity" << std::endl;
return;
}
this->dataPtr->winchTargetVel = _value;
if (ignition::math::equal(_value, 0.0f))
{
// if zero velocity is commanded, hold position
this->dataPtr->winchTargetPos =
this->dataPtr->joints[winchIndex]->Position(0);
this->dataPtr->winchPosPID.Reset();
}
}
/////////////////////////////////////////////////
int HarnessPlugin::JointIndex(const std::string &_name) const
{
std::lock_guard<std::recursive_mutex> lock(this->dataPtr->jointsMutex);
// Find the given joint in our list of joints
for (size_t i = 0; i < this->dataPtr->joints.size(); ++i)
{
if (this->dataPtr->joints[i]->GetName() == _name)
return i;
}
return -1;
}
/////////////////////////////////////////////////
void HarnessPlugin::OnVelocity(ConstGzStringPtr &_msg)
{
try
{
this->SetWinchVelocity(std::stof(_msg->data()));
}
catch(...)
{
gzerr << "Invalid velocity data[" << _msg->data() << "]\n";
}
}
/////////////////////////////////////////////////
void HarnessPlugin::OnAttach(ConstPosePtr &_msg)
{
// Block physics updates during harness attachment
boost::recursive_mutex::scoped_lock lock(
*this->dataPtr->model->GetWorld()->Physics()->GetPhysicsUpdateMutex());
this->Attach(msgs::ConvertIgn(*_msg));
}
/////////////////////////////////////////////////
void HarnessPlugin::OnDetach(ConstGzStringPtr &_msg)
{
if (_msg->data() == "true" ||
_msg->data() == "TRUE" ||
_msg->data() == "True")
{
std::lock_guard<std::recursive_mutex> lock(this->dataPtr->jointsMutex);
this->dataPtr->winchIndex = -1;
}
}