-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathJointPositionController.cc
369 lines (318 loc) · 10.7 KB
/
JointPositionController.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
/*
* Copyright (C) 2020 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 "JointPositionController.hh"
#include <gz/msgs/double.pb.h>
#include <string>
#include <unordered_set>
#include <gz/common/Profiler.hh>
#include <gz/math/PID.hh>
#include <gz/plugin/Register.hh>
#include <gz/transport/Node.hh>
#include "gz/sim/components/JointForceCmd.hh"
#include "gz/sim/components/JointVelocityCmd.hh"
#include "gz/sim/components/JointPosition.hh"
#include "gz/sim/Model.hh"
using namespace gz;
using namespace sim;
using namespace systems;
class gz::sim::systems::JointPositionControllerPrivate
{
/// \brief Callback for position subscription
/// \param[in] _msg Position message
public: void OnCmdPos(const msgs::Double &_msg);
/// \brief Gazebo communication node.
public: transport::Node node;
/// \brief Joint Entity
public: Entity jointEntity{kNullEntity};
/// \brief Joint name
public: std::string jointName;
/// \brief Commanded joint position
public: double jointPosCmd{0.0};
/// \brief mutex to protect joint commands
public: std::mutex jointCmdMutex;
/// \brief Model interface
public: Model model{kNullEntity};
/// \brief Position PID controller.
public: math::PID posPid;
/// \brief Joint index to be used.
public: unsigned int jointIndex = 0u;
/// \brief Operation modes
enum OperationMode
{
/// \brief Use PID to achieve positional control
PID,
/// \brief Bypass PID completely. This means the joint will move to that
/// position bypassing the physics engine.
ABS
};
/// \brief Joint position mode
public: OperationMode mode = OperationMode::PID;
};
//////////////////////////////////////////////////
JointPositionController::JointPositionController()
: dataPtr(std::make_unique<JointPositionControllerPrivate>())
{
}
//////////////////////////////////////////////////
void JointPositionController::Configure(const Entity &_entity,
const std::shared_ptr<const sdf::Element> &_sdf,
EntityComponentManager &_ecm,
EventManager &/*_eventMgr*/)
{
this->dataPtr->model = Model(_entity);
if (!this->dataPtr->model.Valid(_ecm))
{
gzerr << "JointPositionController plugin should be attached to a model "
<< "entity. Failed to initialize." << std::endl;
return;
}
// Get params from SDF
this->dataPtr->jointName = _sdf->Get<std::string>("joint_name");
if (this->dataPtr->jointName == "")
{
gzerr << "JointPositionController found an empty jointName parameter. "
<< "Failed to initialize.";
return;
}
if (_sdf->HasElement("joint_index"))
{
this->dataPtr->jointIndex = _sdf->Get<unsigned int>("joint_index");
}
// PID parameters
double p = 1;
double i = 0.1;
double d = 0.01;
double iMax = 1;
double iMin = -1;
double cmdMax = 1000;
double cmdMin = -1000;
double cmdOffset = 0;
if (_sdf->HasElement("p_gain"))
{
p = _sdf->Get<double>("p_gain");
}
if (_sdf->HasElement("i_gain"))
{
i = _sdf->Get<double>("i_gain");
}
if (_sdf->HasElement("d_gain"))
{
d = _sdf->Get<double>("d_gain");
}
if (_sdf->HasElement("i_max"))
{
iMax = _sdf->Get<double>("i_max");
}
if (_sdf->HasElement("i_min"))
{
iMin = _sdf->Get<double>("i_min");
}
if (_sdf->HasElement("cmd_max"))
{
cmdMax = _sdf->Get<double>("cmd_max");
}
if (_sdf->HasElement("cmd_min"))
{
cmdMin = _sdf->Get<double>("cmd_min");
}
if (_sdf->HasElement("cmd_offset"))
{
cmdOffset = _sdf->Get<double>("cmd_offset");
}
if (_sdf->HasElement("use_velocity_commands"))
{
auto useVelocityCommands = _sdf->Get<bool>("use_velocity_commands");
if (useVelocityCommands)
{
this->dataPtr->mode =
JointPositionControllerPrivate::OperationMode::ABS;
}
}
this->dataPtr->posPid.Init(p, i, d, iMax, iMin, cmdMax, cmdMin, cmdOffset);
if (_sdf->HasElement("initial_position"))
{
this->dataPtr->jointPosCmd = _sdf->Get<double>("initial_position");
}
// Subscribe to commands
std::string topic = transport::TopicUtils::AsValidTopic("/model/" +
this->dataPtr->model.Name(_ecm) + "/joint/" + this->dataPtr->jointName +
"/" + std::to_string(this->dataPtr->jointIndex) + "/cmd_pos");
if (topic.empty())
{
gzerr << "Failed to create topic for joint [" << this->dataPtr->jointName
<< "]" << std::endl;
return;
}
if (_sdf->HasElement("topic"))
{
topic = transport::TopicUtils::AsValidTopic(
_sdf->Get<std::string>("topic"));
if (topic.empty())
{
gzerr << "Failed to create topic [" << _sdf->Get<std::string>("topic")
<< "]" << " for joint [" << this->dataPtr->jointName
<< "]" << std::endl;
return;
}
}
this->dataPtr->node.Subscribe(
topic, &JointPositionControllerPrivate::OnCmdPos, this->dataPtr.get());
gzdbg << "[JointPositionController] system parameters:" << std::endl;
gzdbg << "p_gain: [" << p << "]" << std::endl;
gzdbg << "i_gain: [" << i << "]" << std::endl;
gzdbg << "d_gain: [" << d << "]" << std::endl;
gzdbg << "i_max: [" << iMax << "]" << std::endl;
gzdbg << "i_min: [" << iMin << "]" << std::endl;
gzdbg << "cmd_max: [" << cmdMax << "]" << std::endl;
gzdbg << "cmd_min: [" << cmdMin << "]" << std::endl;
gzdbg << "cmd_offset: [" << cmdOffset << "]" << std::endl;
gzdbg << "Topic: [" << topic << "]" << std::endl;
gzdbg << "initial_position: [" << this->dataPtr->jointPosCmd << "]"
<< std::endl;
}
//////////////////////////////////////////////////
void JointPositionController::PreUpdate(
const UpdateInfo &_info,
EntityComponentManager &_ecm)
{
GZ_PROFILE("JointPositionController::PreUpdate");
// \TODO(anyone) Support rewind
if (_info.dt < std::chrono::steady_clock::duration::zero())
{
gzwarn << "Detected jump back in time ["
<< std::chrono::duration_cast<std::chrono::seconds>(_info.dt).count()
<< "s]. System may not work properly." << std::endl;
}
// If the joint hasn't been identified yet, look for it
if (this->dataPtr->jointEntity == kNullEntity)
{
this->dataPtr->jointEntity =
this->dataPtr->model.JointByName(_ecm, this->dataPtr->jointName);
}
// If the joint is still not found then warn the user, they may have entered
// the wrong joint name.
if (this->dataPtr->jointEntity == kNullEntity)
{
static bool warned = false;
if(!warned)
gzerr << "Could not find joint with name ["
<< this->dataPtr->jointName <<"]\n";
warned = true;
return;
}
// Nothing left to do if paused.
if (_info.paused)
return;
// Create joint position component if one doesn't exist
auto jointPosComp =
_ecm.Component<components::JointPosition>(this->dataPtr->jointEntity);
if (jointPosComp == nullptr)
{
_ecm.CreateComponent(
this->dataPtr->jointEntity, components::JointPosition());
}
// We just created the joint position component, give one iteration for the
// physics system to update its size
if (jointPosComp == nullptr || jointPosComp->Data().empty())
return;
// Sanity check: Make sure that the joint index is valid.
if (this->dataPtr->jointIndex >= jointPosComp->Data().size())
{
static std::unordered_set<Entity> reported;
if (reported.find(this->dataPtr->jointEntity) == reported.end())
{
gzerr << "[JointPositionController]: Detected an invalid <joint_index> "
<< "parameter. The index specified is ["
<< this->dataPtr->jointIndex << "] but joint ["
<< this->dataPtr->jointName << "] only has ["
<< jointPosComp->Data().size() << "] index[es]. "
<< "This controller will be ignored" << std::endl;
reported.insert(this->dataPtr->jointEntity);
}
return;
}
// Get error in position
double error;
{
std::lock_guard<std::mutex> lock(this->dataPtr->jointCmdMutex);
error = jointPosComp->Data().at(this->dataPtr->jointIndex) -
this->dataPtr->jointPosCmd;
}
// Check if the mode is ABS
if (this->dataPtr->mode ==
JointPositionControllerPrivate::OperationMode::ABS)
{
// Calculate target velcity
double targetVel = 0;
// Get time in seconds
auto dt = std::chrono::duration<double>(_info.dt).count();
// Get the maximum amount in m that this joint may move
auto maxMovement = this->dataPtr->posPid.CmdMax() * dt;
// Limit the maximum change to maxMovement
if (abs(error) > maxMovement)
{
targetVel = (error < 0) ? this->dataPtr->posPid.CmdMax() :
-this->dataPtr->posPid.CmdMax();
}
else
{
targetVel = -error;
}
// Set velocity and return
auto vel =
_ecm.Component<components::JointVelocityCmd>(this->dataPtr->jointEntity);
if (vel == nullptr)
{
_ecm.CreateComponent(
this->dataPtr->jointEntity,
components::JointVelocityCmd({targetVel}));
}
else if (!vel->Data().empty())
{
vel->Data()[0] = targetVel;
}
return;
}
// Update force command.
double force = this->dataPtr->posPid.Update(error, _info.dt);
auto forceComp =
_ecm.Component<components::JointForceCmd>(this->dataPtr->jointEntity);
if (forceComp == nullptr)
{
_ecm.CreateComponent(this->dataPtr->jointEntity,
components::JointForceCmd({force}));
}
else
{
forceComp->Data()[this->dataPtr->jointIndex] = force;
}
}
//////////////////////////////////////////////////
void JointPositionControllerPrivate::OnCmdPos(const msgs::Double &_msg)
{
std::lock_guard<std::mutex> lock(this->jointCmdMutex);
this->jointPosCmd = _msg.data();
}
GZ_ADD_PLUGIN(JointPositionController,
System,
JointPositionController::ISystemConfigure,
JointPositionController::ISystemPreUpdate)
GZ_ADD_PLUGIN_ALIAS(JointPositionController,
"gz::sim::systems::JointPositionController")
// TODO(CH3): Deprecated, remove on version 8
GZ_ADD_PLUGIN_ALIAS(JointPositionController,
"ignition::gazebo::systems::JointPositionController")