-
Notifications
You must be signed in to change notification settings - Fork 251
/
MulticopterVelocityControl.cc
458 lines (389 loc) · 13.8 KB
/
MulticopterVelocityControl.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
/*
* Copyright (C) 2019 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 <ignition/msgs/actuators.pb.h>
#include <ignition/msgs/twist.pb.h>
#include <limits>
#include <ignition/common/Profiler.hh>
#include <ignition/plugin/Register.hh>
#include <ignition/transport/Node.hh>
#include <ignition/math/Inertial.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/math/eigen3/Conversions.hh>
#include <sdf/sdf.hh>
#include "ignition/gazebo/components/Actuators.hh"
#include "ignition/gazebo/components/Gravity.hh"
#include "ignition/gazebo/components/Inertial.hh"
#include "ignition/gazebo/components/Link.hh"
#include "ignition/gazebo/components/ParentEntity.hh"
#include "ignition/gazebo/components/World.hh"
#include "ignition/gazebo/Link.hh"
#include "ignition/gazebo/Model.hh"
#include "MulticopterVelocityControl.hh"
using namespace ignition;
using namespace gazebo;
using namespace systems;
using namespace multicopter_control;
//////////////////////////////////////////////////
void MulticopterVelocityControl::Configure(const Entity &_entity,
const std::shared_ptr<const sdf::Element> &_sdf,
EntityComponentManager &_ecm,
EventManager &/*_eventMgr*/)
{
this->model = Model(_entity);
if (!this->model.Valid(_ecm))
{
ignerr << "MulticopterVelocityControl plugin should be attached to a model "
<< "entity. Failed to initialize." << std::endl;
return;
}
auto sdfClone = _sdf->Clone();
if (sdfClone->HasElement("comLinkName"))
{
this->comLinkName = sdfClone->Get<std::string>("comLinkName");
}
if (this->comLinkName.empty())
{
ignerr << "found an empty comLinkName parameter. Failed to initialize.\n";
return;
}
// Get the link entity
this->comLinkEntity = this->model.LinkByName(_ecm, this->comLinkName);
if (this->comLinkEntity == kNullEntity)
{
ignerr << "Link " << this->comLinkName
<< " could not be found. Failed to initialize.\n";
return;
}
createFrameDataComponents(_ecm, this->comLinkEntity);
VehicleParameters vehicleParams;
math::Inertiald vehicleInertial;
// Compute the vehicle's moment of inertia and mass assuming that all the
// links in the model belong to the vehicle.
for (const Entity &link :
_ecm.ChildrenByComponents(this->model.Entity(), components::Link()))
{
auto inertial = _ecm.Component<components::Inertial>(link);
if (nullptr == inertial)
{
ignerr << "Could not find inertial component on on link "
<< this->comLinkName << std::endl;
return;
}
vehicleInertial += inertial->Data();
}
vehicleParams.mass = vehicleInertial.MassMatrix().Mass();
vehicleParams.inertia = math::eigen3::convert(vehicleInertial.Moi());
if (sdfClone->HasElement("rotorConfiguration"))
{
vehicleParams.rotorConfiguration =
loadRotorConfiguration(_ecm, sdfClone->GetElement("rotorConfiguration"),
this->model, this->comLinkEntity);
// DEBUG
// std::cout << "Found "
// << vehicleParams.rotorConfiguration.size()
// << " rotors" << std::endl;
// for (const auto &rotor : vehicleParams.rotorConfiguration)
// {
// std::cout << rotor.angle << " "
// << rotor.armLength << " " << rotor.forceConstant << " "
// << rotor.momentConstant << " " << rotor.direction << "\n\n";
// }
}
else
{
ignerr << "Please specify rotorConfiguration.\n";
}
this->rotorVelocities.resize(vehicleParams.rotorConfiguration.size());
auto worldEntity = _ecm.EntityByComponents(components::World());
if (kNullEntity == worldEntity)
{
ignerr << "World entity missing." << std::endl;
return;
}
// Get the world acceleration (defined in world frame)
auto gravityComp = _ecm.Component<components::Gravity>(worldEntity);
if (nullptr == gravityComp)
{
ignerr << "World missing gravity." << std::endl;
return;
}
vehicleParams.gravity = math::eigen3::convert(gravityComp->Data());
LeeVelocityControllerParameters controllerParameters;
if (sdfClone->HasElement("velocityGain"))
{
controllerParameters.velocityGain =
math::eigen3::convert(sdfClone->Get<math::Vector3d>("velocityGain"));
}
else
{
ignerr << "Please specify velocityGain for MulticopterVelocityControl.\n";
return;
}
if (sdfClone->HasElement("attitudeGain"))
{
controllerParameters.attitudeGain =
math::eigen3::convert(sdfClone->Get<math::Vector3d>("attitudeGain"));
}
else
{
ignerr << "Please specify attitudeGain for MulticopterVelocityControl.\n";
return;
}
if (sdfClone->HasElement("angularRateGain"))
{
controllerParameters.angularRateGain =
math::eigen3::convert(sdfClone->Get<math::Vector3d>("angularRateGain"));
}
else
{
ignerr << "Please specify angularRateGain MulticopterVelocityControl.\n";
return;
}
if (sdfClone->HasElement("maximumLinearAcceleration"))
{
controllerParameters.maxLinearAcceleration = math::eigen3::convert(
sdfClone->Get<math::Vector3d>("maximumLinearAcceleration"));
}
else
{
controllerParameters.maxLinearAcceleration.setConstant(
std::numeric_limits<double>::max());
}
if (sdfClone->HasElement("maximumLinearVelocity"))
{
this->maximumLinearVelocity =
sdfClone->Get<math::Vector3d>("maximumLinearVelocity").Abs();
}
else
{
this->maximumLinearVelocity.Set(
std::numeric_limits<double>::max(),
std::numeric_limits<double>::max(),
std::numeric_limits<double>::max());
}
if (sdfClone->HasElement("maximumAngularVelocity"))
{
this->maximumAngularVelocity =
sdfClone->Get<math::Vector3d>("maximumAngularVelocity").Abs();
}
else
{
this->maximumAngularVelocity.Set(
std::numeric_limits<double>::max(),
std::numeric_limits<double>::max(),
std::numeric_limits<double>::max());
}
this->velocityController = LeeVelocityController::MakeController(
controllerParameters, vehicleParams);
if (nullptr == this->velocityController)
{
ignerr << "Error while creating the LeeVelocityController\n";
return;
}
math::Vector3d linearVelocityMean{0, 0, 0};
sdfClone->Get<math::Vector3d>("linearVelocityNoiseMean",
linearVelocityMean, linearVelocityMean);
math::Vector3d linearVelocityStdDev{0, 0, 0};
sdfClone->Get<math::Vector3d>("linearVelocityNoiseStdDev",
linearVelocityStdDev, linearVelocityStdDev);
math::Vector3d angularVelocityMean{0, 0, 0};
sdfClone->Get<math::Vector3d>("angularVelocityNoiseMean",
angularVelocityMean, angularVelocityMean);
math::Vector3d angularVelocityStdDev{0, 0, 0};
sdfClone->Get<math::Vector3d>("angularVelocityNoiseStdDev",
angularVelocityStdDev, angularVelocityStdDev);
this->noiseParameters.linearVelocityMean =
math::eigen3::convert(linearVelocityMean);
this->noiseParameters.linearVelocityStdDev =
math::eigen3::convert(linearVelocityStdDev);
this->noiseParameters.angularVelocityMean =
math::eigen3::convert(angularVelocityMean);
this->noiseParameters.angularVelocityStdDev =
math::eigen3::convert(angularVelocityStdDev);
if (sdfClone->HasElement("robotNamespace"))
{
this->robotNamespace = transport::TopicUtils::AsValidTopic(
sdfClone->Get<std::string>("robotNamespace"));
if (this->robotNamespace.empty())
{
ignerr << "Robot namespace ["
<< sdfClone->Get<std::string>("robotNamespace") <<"] is invalid."
<< std::endl;
return;
}
}
else
{
ignerr << "Please specify a robotNamespace.\n";
return;
}
sdfClone->Get<std::string>("commandSubTopic",
this->commandSubTopic, this->commandSubTopic);
this->commandSubTopic = transport::TopicUtils::AsValidTopic(
this->commandSubTopic);
if (this->commandSubTopic.empty())
{
ignerr << "Invalid command sub-topic." << std::endl;
return;
}
sdfClone->Get<std::string>("enableSubTopic",
this->enableSubTopic, this->enableSubTopic);
this->enableSubTopic = transport::TopicUtils::AsValidTopic(
this->enableSubTopic);
if (this->enableSubTopic.empty())
{
ignerr << "Invalid enable sub-topic." << std::endl;
return;
}
// Subscribe to actuator command messages
std::string topic{this->robotNamespace + "/" + this->commandSubTopic};
this->node.Subscribe(topic, &MulticopterVelocityControl::OnTwist, this);
ignmsg << "MulticopterVelocityControl subscribing to Twist messages on ["
<< topic << "]" << std::endl;
std::string enableTopic{this->robotNamespace + "/" + this->enableSubTopic};
this->node.Subscribe(enableTopic, &MulticopterVelocityControl::OnEnable,
this);
ignmsg << "MulticopterVelocityControl subscribing to Boolean messages on ["
<< enableTopic << "]" << std::endl;
// Create the Actuators component to take control of rotor speeds
this->rotorVelocitiesMsg.mutable_velocity()->Resize(
this->rotorVelocities.size(), 0);
_ecm.CreateComponent(this->model.Entity(),
components::Actuators(this->rotorVelocitiesMsg));
this->initialized = true;
}
//////////////////////////////////////////////////
void MulticopterVelocityControl::PreUpdate(
const ignition::gazebo::UpdateInfo &_info,
ignition::gazebo::EntityComponentManager &_ecm)
{
IGN_PROFILE("MulticopterVelocityControl::PreUpdate");
if (!this->initialized)
{
return;
}
// \TODO(anyone) Support rewind
if (_info.dt < std::chrono::steady_clock::duration::zero())
{
ignwarn << "Detected jump back in time ["
<< std::chrono::duration_cast<std::chrono::seconds>(_info.dt).count()
<< "s]. System may not work properly." << std::endl;
}
// Nothing left to do if paused.
if (_info.paused)
{
return;
}
if (!this->controllerActive)
{
// If the last published rotor velocities were not 0, publish zero
// velocities
if (this->rotorVelocities.squaredNorm() > 0)
{
this->rotorVelocities.setZero();
this->PublishRotorVelocities(_ecm, this->rotorVelocities);
// Clear the cmdVelMsg so that the system waits for a new command after
// being renabled.
std::lock_guard<std::mutex> lock(this->cmdVelMsgMutex);
this->cmdVelMsg.reset();
}
return;
}
EigenTwist cmdVel;
{
std::lock_guard<std::mutex> lock(this->cmdVelMsgMutex);
if (!this->cmdVelMsg.has_value())
{
return;
}
// Clip with max linear velocity
math::Vector3d linear = msgs::Convert(this->cmdVelMsg->linear());
linear.Min(this->maximumLinearVelocity);
linear.Max(-this->maximumLinearVelocity);
math::Vector3d angular = msgs::Convert(this->cmdVelMsg->angular());
angular.Min(this->maximumAngularVelocity);
angular.Max(-this->maximumAngularVelocity);
cmdVel.linear = math::eigen3::convert(linear);
cmdVel.angular = math::eigen3::convert(angular);
}
std::optional<FrameData> frameData =
getFrameData(_ecm, this->comLinkEntity, this->noiseParameters);
if (!frameData.has_value())
{
// Errors would have already been printed
return;
}
this->velocityController->CalculateRotorVelocities(*frameData, cmdVel,
this->rotorVelocities);
this->PublishRotorVelocities(_ecm, this->rotorVelocities);
}
//////////////////////////////////////////////////
void MulticopterVelocityControl::OnTwist(
const msgs::Twist &_msg)
{
std::lock_guard<std::mutex> lock(this->cmdVelMsgMutex);
this->cmdVelMsg = _msg;
}
//////////////////////////////////////////////////
void MulticopterVelocityControl::OnEnable(
const msgs::Boolean &_msg)
{
this->controllerActive = _msg.data();
}
//////////////////////////////////////////////////
void MulticopterVelocityControl::PublishRotorVelocities(
ignition::gazebo::EntityComponentManager &_ecm,
const Eigen::VectorXd &_vels)
{
if (_vels.size() != this->rotorVelocitiesMsg.velocity_size())
{
this->rotorVelocitiesMsg.mutable_velocity()->Resize(_vels.size(), 0);
}
for (int i = 0; i < this->rotorVelocities.size(); ++i)
{
this->rotorVelocitiesMsg.set_velocity(i, _vels(i));
}
// Publish the message by setting the Actuators component on the model entity.
// This assumes that the MulticopterMotorModel system is attached to this
// model
auto actuatorMsgComp =
_ecm.Component<components::Actuators>(this->model.Entity());
if (actuatorMsgComp)
{
auto compFunc = [](const msgs::Actuators &_a, const msgs::Actuators &_b)
{
return std::equal(_a.velocity().begin(), _a.velocity().end(),
_b.velocity().begin());
};
auto state = actuatorMsgComp->SetData(this->rotorVelocitiesMsg, compFunc)
? ComponentState::PeriodicChange
: ComponentState::NoChange;
_ecm.SetChanged(this->model.Entity(), components::Actuators::typeId, state);
}
else
{
_ecm.CreateComponent(this->model.Entity(),
components::Actuators(this->rotorVelocitiesMsg));
}
}
IGNITION_ADD_PLUGIN(MulticopterVelocityControl,
ignition::gazebo::System,
MulticopterVelocityControl::ISystemConfigure,
MulticopterVelocityControl::ISystemPreUpdate)
IGNITION_ADD_PLUGIN_ALIAS(
MulticopterVelocityControl,
"ignition::gazebo::systems::MulticopterVelocityControl")