-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathArduPilotPlugin.cc
executable file
·2000 lines (1715 loc) · 64 KB
/
ArduPilotPlugin.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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 "ArduPilotPlugin.hh"
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <gz/msgs/imu.pb.h>
#include <gz/msgs/laserscan.pb.h>
#include <algorithm>
#include <chrono>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <sstream>
#include <vector>
#include <gz/common/SignalHandler.hh>
#include <gz/msgs/Utility.hh>
#include <gz/sim/components/CustomSensor.hh>
#include <gz/sim/components/Imu.hh>
#include <gz/sim/components/Joint.hh>
#include <gz/sim/components/JointForceCmd.hh>
#include <gz/sim/components/JointPosition.hh>
#include <gz/sim/components/JointVelocity.hh>
#include <gz/sim/components/JointVelocityCmd.hh>
#include <gz/sim/components/LinearVelocity.hh>
#include <gz/sim/components/Link.hh>
#include <gz/sim/components/Name.hh>
#include <gz/sim/components/Pose.hh>
#include <gz/sim/components/Sensor.hh>
#include <gz/sim/components/World.hh>
#include <gz/sim/Model.hh>
#include <gz/sim/World.hh>
#include <gz/sim/Util.hh>
#include <gz/math/Filter.hh>
#include <gz/math/Helpers.hh>
#include <gz/math/Pose3.hh>
#include <gz/math/PID.hh>
#include <gz/math/Vector3.hh>
#include <gz/plugin/Register.hh>
#include <gz/transport/Node.hh>
#include <sdf/sdf.hh>
#include "SocketUDP.hh"
#include "Util.hh"
#define DEBUG_JSON_IO 0
// MAX_MOTORS limits the maximum number of <control> elements that
// can be defined in the <plugin>.
#define MAX_MOTORS 255
// Register plugin
GZ_ADD_PLUGIN(gz::sim::systems::ArduPilotPlugin,
gz::sim::System,
gz::sim::systems::ArduPilotPlugin::ISystemConfigure,
gz::sim::systems::ArduPilotPlugin::ISystemPostUpdate,
gz::sim::systems::ArduPilotPlugin::ISystemReset,
gz::sim::systems::ArduPilotPlugin::ISystemPreUpdate)
// Add plugin alias so that we can refer to the plugin without the version
// namespace
GZ_ADD_PLUGIN_ALIAS(gz::sim::systems::ArduPilotPlugin, "ArduPilotPlugin")
/// \brief class Control is responsible for controlling a joint
class Control
{
/// \brief Constructor
public: Control()
{
// most of these coefficients are not used yet.
this->rotorVelocitySlowdownSim = this->kDefaultRotorVelocitySlowdownSim;
this->frequencyCutoff = this->kDefaultFrequencyCutoff;
this->samplingRate = this->kDefaultSamplingRate;
this->pid.Init(0.1, 0, 0, 0, 0, 1.0, -1.0);
}
public: ~Control() {}
/// \brief The PWM channel used to command this control
public: int channel = 0;
/// \brief Next command to be applied to the joint
public: double cmd = 0;
/// \brief Velocity PID for motor control
public: gz::math::PID pid;
/// \brief The controller type
///
/// Valid controller types are:
/// VELOCITY control velocity of joint
/// POSITION control position of joint
/// EFFORT control effort of joint
/// COMMAND control sends command to topic
public: std::string type;
/// \brief Use force controller
public: bool useForce = true;
/// \brief The name of the joint being controlled
public: std::string jointName;
/// \brief The name of the topic to forward this command
public: std::string cmdTopic;
/// \brief The joint being controlled
public: gz::sim::Entity joint;
/// \brief A multiplier to scale the raw input command
public: double multiplier = 1.0;
/// \brief An offset to shift the zero-point of the raw input command
public: double offset = 0.0;
/// \brief Lower bound of PWM input, has default (1000).
///
/// The lower bound of PWM input should match SERVOX_MIN for this channel.
public: double servo_min = 1000.0;
/// \brief Upper limit of PWM input, has default (2000).
///
/// The upper limit of PWM input should match SERVOX_MAX for this channel.
public: double servo_max = 2000.0;
/// \brief Publisher for sending commands
public: gz::transport::Node::Publisher pub;
/// \brief unused coefficients
public: double rotorVelocitySlowdownSim;
public: double frequencyCutoff;
public: double samplingRate;
public: gz::math::OnePole<double> filter;
public: static double kDefaultRotorVelocitySlowdownSim;
public: static double kDefaultFrequencyCutoff;
public: static double kDefaultSamplingRate;
};
double Control::kDefaultRotorVelocitySlowdownSim = 10.0;
double Control::kDefaultFrequencyCutoff = 5.0;
double Control::kDefaultSamplingRate = 0.2;
/////////////////////////////////////////////////
// Wrapper class to store callback functions
template <typename M>
class OnMessageWrapper
{
/// \brief Callback function type definition
public: typedef std::function<void(const M &)> callback_t;
/// \brief Callback function
public: callback_t callback;
/// \brief Constructor
public: OnMessageWrapper(const callback_t &_callback)
: callback(_callback)
{
}
/// \brief Callback function
public: void OnMessage(const M &_msg)
{
if (callback)
{
callback(_msg);
}
}
};
typedef std::shared_ptr<OnMessageWrapper<
gz::msgs::LaserScan>> RangeOnMessageWrapperPtr;
/////////////////////////////////////////////////
// Private data class
class gz::sim::systems::ArduPilotPluginPrivate
{
/// \brief The model
public: gz::sim::Model model{gz::sim::kNullEntity};
/// \brief The entity representing the link containing the imu sensor.
public: gz::sim::Entity imuLink{gz::sim::kNullEntity};
/// \brief The model name;
public: std::string modelName;
/// \brief The world
public: gz::sim::World world{gz::sim::kNullEntity};
/// \brief The world name;
public: std::string worldName;
/// \brief Array of controllers
public: std::vector<Control> controls;
/// \brief keep track of controller update sim-time.
public: std::chrono::steady_clock::duration lastControllerUpdateTime{0};
/// \brief Keep track of the time the last servo packet was received.
public: std::chrono::steady_clock::duration lastServoPacketRecvTime{0};
/// \brief Controller update mutex.
public: std::mutex mutex;
/// \brief Socket manager
public: SocketUDP sock = SocketUDP(true, true);
/// \brief The address for the flight dynamics model (i.e. this plugin)
public: std::string fdm_address{"127.0.0.1"};
/// \brief The address for the SITL flight controller - auto detected
public: const char* fcu_address{nullptr};
/// \brief The port for the flight dynamics model
public: uint16_t fdm_port_in{9002};
/// \brief The port for the SITL flight controller - auto detected
public: uint16_t fcu_port_out;
/// \brief The name of the IMU sensor
public: std::string imuName;
/// \brief Set true to enforce lock-step simulation
public: bool isLockStep{false};
/// \brief Set true if have 32 servo channels
public: bool have32Channels{false};
/// \brief Have we initialized subscription to the IMU data yet?
public: bool imuInitialized{false};
/// \brief We need an gz-transport Node to subscribe to IMU data
public: gz::transport::Node node;
/// \brief A copy of the most recently received IMU data message
public: gz::msgs::IMU imuMsg;
/// \brief Have we received at least one IMU data message?
public: bool imuMsgValid{false};
/// \brief This mutex should be used when accessing imuMsg or imuMsgValid
public: std::mutex imuMsgMutex;
/// \brief This subscriber callback latches the most recently received
/// IMU data message for later use.
public: void ImuCb(const gz::msgs::IMU &_msg)
{
std::lock_guard<std::mutex> lock(this->imuMsgMutex);
imuMsg = _msg;
imuMsgValid = true;
}
// Range sensors
/// \brief This mutex must be used when accessing ranges
public: std::mutex rangeMsgMutex;
/// \brief A copy of the most recently received range data
public: std::vector<double> ranges;
/// \brief Callbacks for each range sensor
public: std::vector<RangeOnMessageWrapperPtr> rangeCbs;
/// \brief This subscriber callback latches the most recently received
/// data message for later use.
///
/// \todo(anyone) using msgs::LaserScan as a proxy for msgs::SonarStamped
public: void RangeCb(const gz::msgs::LaserScan &_msg, int _sensorIndex)
{
// Extract data
double range_max = _msg.range_max();
auto&& ranges = _msg.ranges();
auto&& intensities = _msg.intensities();
// If there is no return, the range should be greater than range_max
double sample_min = 2.0 * range_max;
for (auto&& range : ranges)
{
sample_min = std::min(
sample_min, std::isinf(range) ? 2.0 * range_max : range);
}
// Aquire lock and update the range data
std::lock_guard<std::mutex> lock(this->rangeMsgMutex);
this->ranges[_sensorIndex] = sample_min;
}
// Anemometer
/// \brief The entity representing the anemometer.
public: gz::sim::Entity anemometerEntity{gz::sim::kNullEntity};
/// \brief The name of the anemometer.
public: std::string anemometerName;
/// \brief This mutex must be used when accessing the anemometer.
public: std::mutex anemometerMsgMutex;
/// \brief Have we initialized subscription to the anemometer data yet?
public: bool anemometerInitialized{false};
/// \brief A copy of the most recently received apparent wind message.
public: gz::msgs::Vector3d anemometerMsg;
/// \brief Callback for the anemometer.
public: void AnemometerCb(const gz::msgs::Vector3d &_msg)
{
std::lock_guard<std::mutex> lock(this->anemometerMsgMutex);
anemometerMsg = _msg;
}
/// \brief Pointer to an GPS sensor [optional]
// public: sensors::GpsSensorPtr gpsSensor;
/// \brief Pointer to an Rangefinder sensor [optional]
// public: sensors::RaySensorPtr rangefinderSensor;
/// \brief Set to true when the ArduPilot flight controller is online
///
/// Set to false when Gazebo starts to prevent blocking, true when
/// the ArduPilot controller is detected and online, and false if the
/// connection to the ArduPilot controller times out.
public: bool arduPilotOnline{false};
/// \brief Number of consecutive missed ArduPilot controller messages
public: int connectionTimeoutCount{0};
/// \brief Max number of consecutive missed ArduPilot controller
/// messages before timeout
public: int connectionTimeoutMaxCount;
/// \brief Transform from model orientation to x-forward and z-up
public: gz::math::Pose3d modelXYZToAirplaneXForwardZDown;
/// \brief Transform from world frame to NED frame
public: gz::math::Pose3d gazeboXYZToNED;
/// \brief Last received frame rate from the ArduPilot controller
public: uint16_t fcu_frame_rate;
/// \brief Last received frame count from the ArduPilot controller
public: uint32_t fcu_frame_count = -1;
/// \brief Last sent JSON string, so we can resend if needed.
public: std::string json_str;
/// \brief A copy of the most recently received signal.
public: int signal{0};
/// \brief Signal handler.
public: gz::common::SignalHandler sigHandler;
/// \brief Signal handler callback.
public: void OnSignal(int _sig)
{
gzdbg << "Plugin received signal[" << _sig << "]\n";
this->signal = _sig;
}
};
/////////////////////////////////////////////////
gz::sim::systems::ArduPilotPlugin::ArduPilotPlugin()
: dataPtr(new ArduPilotPluginPrivate())
{
}
/////////////////////////////////////////////////
gz::sim::systems::ArduPilotPlugin::~ArduPilotPlugin()
{
}
/////////////////////////////////////////////////
void gz::sim::systems::ArduPilotPlugin::Reset(const UpdateInfo &_info,
EntityComponentManager &_ecm)
{
if (!_ecm.EntityHasComponentType(this->dataPtr->imuLink,
components::WorldPose::typeId))
{
_ecm.CreateComponent(this->dataPtr->imuLink,
gz::sim::components::WorldPose());
}
if (!_ecm.EntityHasComponentType(this->dataPtr->imuLink,
components::WorldLinearVelocity::typeId))
{
_ecm.CreateComponent(this->dataPtr->imuLink,
gz::sim::components::WorldLinearVelocity());
}
// update velocity PID for controls and apply force to joint
for (size_t i = 0; i < this->dataPtr->controls.size(); ++i)
{
gz::sim::components::JointForceCmd* jfcComp = nullptr;
gz::sim::components::JointVelocityCmd* jvcComp = nullptr;
if (this->dataPtr->controls[i].useForce ||
this->dataPtr->controls[i].type == "EFFORT")
{
jfcComp = _ecm.Component<gz::sim::components::JointForceCmd>(
this->dataPtr->controls[i].joint);
if (jfcComp == nullptr)
{
jfcComp = _ecm.CreateComponent(this->dataPtr->controls[i].joint,
gz::sim::components::JointForceCmd({0}));
}
}
else if (this->dataPtr->controls[i].type == "VELOCITY")
{
jvcComp = _ecm.Component<gz::sim::components::JointVelocityCmd>(
this->dataPtr->controls[i].joint);
if (jvcComp == nullptr)
{
jvcComp = _ecm.CreateComponent(this->dataPtr->controls[i].joint,
gz::sim::components::JointVelocityCmd({0}));
}
}
}
}
/////////////////////////////////////////////////
void gz::sim::systems::ArduPilotPlugin::Configure(
const gz::sim::Entity &_entity,
const std::shared_ptr<const sdf::Element> &_sdf,
gz::sim::EntityComponentManager &_ecm,
gz::sim::EventManager &/*&_eventMgr*/)
{
// Make a clone so that we can call non-const methods
sdf::ElementPtr sdfClone = _sdf->Clone();
this->dataPtr->model = gz::sim::Model(_entity);
if (!this->dataPtr->model.Valid(_ecm))
{
gzerr << "ArduPilotPlugin should be attached to a model "
<< "entity. Failed to initialize." << "\n";
return;
}
this->dataPtr->modelName = this->dataPtr->model.Name(_ecm);
this->dataPtr->world = gz::sim::World(
_ecm.EntityByComponents(components::World()));
if (!this->dataPtr->world.Valid(_ecm))
{
gzerr << "World entity not found" <<std::endl;
return;
}
if (this->dataPtr->world.Name(_ecm).has_value())
{
this->dataPtr->worldName = this->dataPtr->world.Name(_ecm).value();
}
// modelXYZToAirplaneXForwardZDown brings us from gazebo model frame:
// x-forward, y-right, z-down
// to the aerospace convention: x-forward, y-left, z-up
this->dataPtr->modelXYZToAirplaneXForwardZDown =
gz::math::Pose3d(0, 0, 0, GZ_PI, 0, 0);
if (sdfClone->HasElement("modelXYZToAirplaneXForwardZDown"))
{
this->dataPtr->modelXYZToAirplaneXForwardZDown =
sdfClone->Get<gz::math::Pose3d>("modelXYZToAirplaneXForwardZDown");
}
// gazeboXYZToNED: from gazebo model frame: x-forward, y-right, z-down
// to the aerospace convention: x-forward, y-left, z-up
this->dataPtr->gazeboXYZToNED = gz::math::Pose3d(0, 0, 0, GZ_PI, 0, 0);
if (sdfClone->HasElement("gazeboXYZToNED"))
{
this->dataPtr->gazeboXYZToNED =
sdfClone->Get<gz::math::Pose3d>("gazeboXYZToNED");
}
// Load control channel params
this->LoadControlChannels(sdfClone, _ecm);
// Load sensor params
this->LoadImuSensors(sdfClone, _ecm);
this->LoadGpsSensors(sdfClone, _ecm);
this->LoadRangeSensors(sdfClone, _ecm);
this->LoadWindSensors(sdfClone, _ecm);
// Initialise sockets
if (!InitSockets(sdfClone))
{
return;
}
// Missed update count before we declare arduPilotOnline status false
this->dataPtr->connectionTimeoutMaxCount =
sdfClone->Get("connectionTimeoutMaxCount", 10).first;
// Enforce lock-step simulation (has default: false)
this->dataPtr->isLockStep =
sdfClone->Get("lock_step", this->dataPtr->isLockStep).first;
this->dataPtr->have32Channels =
sdfClone->Get("have_32_channels", false).first;
// Add the signal handler
this->dataPtr->sigHandler.AddCallback(
std::bind(
&gz::sim::systems::ArduPilotPluginPrivate::OnSignal,
this->dataPtr.get(),
std::placeholders::_1));
gzlog << "[" << this->dataPtr->modelName << "] "
<< "ArduPilot ready to fly. The force will be with you" << "\n";
}
/////////////////////////////////////////////////
void gz::sim::systems::ArduPilotPlugin::LoadControlChannels(
sdf::ElementPtr _sdf,
gz::sim::EntityComponentManager &_ecm)
{
// per control channel
sdf::ElementPtr controlSDF;
if (_sdf->HasElement("control"))
{
controlSDF = _sdf->GetElement("control");
}
else if (_sdf->HasElement("rotor"))
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "please deprecate <rotor> block, use <control> block instead.\n";
controlSDF = _sdf->GetElement("rotor");
}
while (controlSDF)
{
Control control;
if (controlSDF->HasAttribute("channel"))
{
control.channel =
atoi(controlSDF->GetAttribute("channel")->GetAsString().c_str());
}
else if (controlSDF->HasAttribute("id"))
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "please deprecate attribute id, use channel instead.\n";
control.channel =
atoi(controlSDF->GetAttribute("id")->GetAsString().c_str());
}
else
{
control.channel = this->dataPtr->controls.size();
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "id/channel attribute not specified, use order parsed ["
<< control.channel << "].\n";
}
if (controlSDF->HasElement("type"))
{
control.type = controlSDF->Get<std::string>("type");
}
else
{
gzerr << "[" << this->dataPtr->modelName << "] "
<< "Control type not specified,"
<< " using velocity control by default.\n";
control.type = "VELOCITY";
}
if (control.type != "VELOCITY" &&
control.type != "POSITION" &&
control.type != "EFFORT" &&
control.type != "COMMAND")
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "Control type [" << control.type
<< "] not recognized, must be one of"
<< "VELOCITY, POSITION, EFFORT, COMMAND."
<< " default to VELOCITY.\n";
control.type = "VELOCITY";
}
if (controlSDF->HasElement("useForce"))
{
control.useForce = controlSDF->Get<bool>("useForce");
}
if (controlSDF->HasElement("jointName"))
{
control.jointName = controlSDF->Get<std::string>("jointName");
}
else
{
gzerr << "[" << this->dataPtr->modelName << "] "
<< "Please specify a jointName,"
<< " where the control channel is attached.\n";
}
// Get the pointer to the joint.
control.joint = JointByName(_ecm,
this->dataPtr->model.Entity(), control.jointName);
if (control.joint == gz::sim::kNullEntity)
{
gzerr << "[" << this->dataPtr->modelName << "] "
<< "Couldn't find specified joint ["
<< control.jointName << "]. This plugin will not run.\n";
return;
}
// set up publisher if relaying the command
if (control.type == "COMMAND")
{
if (controlSDF->HasElement("cmd_topic"))
{
control.cmdTopic = controlSDF->Get<std::string>("cmd_topic");
}
else
{
control.cmdTopic =
"/world/" + this->dataPtr->worldName
+ "/model/" + this->dataPtr->modelName
+ "/joint/" + control.jointName + "/cmd";
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "Control type [" << control.type
<< "] requires a valid <cmd_topic>. Using default\n";
}
gzmsg << "[" << this->dataPtr->modelName << "] "
<< "Advertising on " << control.cmdTopic << ".\n";
control.pub = this->dataPtr->
node.Advertise<msgs::Double>(control.cmdTopic);
}
if (controlSDF->HasElement("multiplier"))
{
// overwrite turningDirection, deprecated.
control.multiplier = controlSDF->Get<double>("multiplier");
}
else if (controlSDF->HasElement("turningDirection"))
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "<turningDirection> is deprecated. Please use"
<< " <multiplier>. Map 'cw' to '-1' and 'ccw' to '1'.\n";
std::string turningDirection = controlSDF->Get<std::string>(
"turningDirection");
// special cases mimic from controls_gazebo_plugins
if (turningDirection == "cw")
{
control.multiplier = -1;
}
else if (turningDirection == "ccw")
{
control.multiplier = 1;
}
else
{
gzdbg << "[" << this->dataPtr->modelName << "] "
<< "not string, check turningDirection as float\n";
control.multiplier = controlSDF->Get<double>("turningDirection");
}
}
else
{
gzdbg << "[" << this->dataPtr->modelName << "] "
<< "channel[" << control.channel
<< "]: <multiplier> (or deprecated <turningDirection>)"
<< " not specified, "
<< " default to " << control.multiplier
<< " (or deprecated <turningDirection> 'ccw').\n";
}
if (controlSDF->HasElement("offset"))
{
control.offset = controlSDF->Get<double>("offset");
}
else
{
gzdbg << "[" << this->dataPtr->modelName << "] "
<< "channel[" << control.channel
<< "]: <offset> not specified, default to "
<< control.offset << "\n";
}
if (controlSDF->HasElement("servo_min"))
{
control.servo_min = controlSDF->Get<double>("servo_min");
}
else
{
gzdbg << "[" << this->dataPtr->modelName << "] "
<< "channel[" << control.channel
<< "]: <servo_min> not specified, default to "
<< control.servo_min << "\n";
}
if (controlSDF->HasElement("servo_max"))
{
control.servo_max = controlSDF->Get<double>("servo_max");
}
else
{
gzdbg << "[" << this->dataPtr->modelName << "] "
<< "channel[" << control.channel
<< "]: <servo_max> not specified, default to "
<< control.servo_max << "\n";
}
control.rotorVelocitySlowdownSim =
controlSDF->Get("rotorVelocitySlowdownSim", 1).first;
if (gz::math::equal(control.rotorVelocitySlowdownSim, 0.0))
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "control for joint [" << control.jointName
<< "] rotorVelocitySlowdownSim is zero,"
<< " assume no slowdown.\n";
control.rotorVelocitySlowdownSim = 1.0;
}
control.frequencyCutoff =
controlSDF->Get("frequencyCutoff", control.frequencyCutoff).first;
control.samplingRate =
controlSDF->Get("samplingRate", control.samplingRate).first;
// use gazebo::math::Filter
control.filter.Fc(control.frequencyCutoff, control.samplingRate);
// initialize filter to zero value
control.filter.Set(0.0);
// note to use this filter, do
// stateFiltered = filter.Process(stateRaw);
// Overload the PID parameters if they are available.
double param;
// carry over from ArduCopter plugin
param = controlSDF->Get("vel_p_gain", control.pid.PGain()).first;
control.pid.SetPGain(param);
param = controlSDF->Get("vel_i_gain", control.pid.IGain()).first;
control.pid.SetIGain(param);
param = controlSDF->Get("vel_d_gain", control.pid.DGain()).first;
control.pid.SetDGain(param);
param = controlSDF->Get("vel_i_max", control.pid.IMax()).first;
control.pid.SetIMax(param);
param = controlSDF->Get("vel_i_min", control.pid.IMin()).first;
control.pid.SetIMin(param);
param = controlSDF->Get("vel_cmd_max", control.pid.CmdMax()).first;
control.pid.SetCmdMax(param);
param = controlSDF->Get("vel_cmd_min", control.pid.CmdMin()).first;
control.pid.SetCmdMin(param);
// new params, overwrite old params if exist
param = controlSDF->Get("p_gain", control.pid.PGain()).first;
control.pid.SetPGain(param);
param = controlSDF->Get("i_gain", control.pid.IGain()).first;
control.pid.SetIGain(param);
param = controlSDF->Get("d_gain", control.pid.DGain()).first;
control.pid.SetDGain(param);
param = controlSDF->Get("i_max", control.pid.IMax()).first;
control.pid.SetIMax(param);
param = controlSDF->Get("i_min", control.pid.IMin()).first;
control.pid.SetIMin(param);
param = controlSDF->Get("cmd_max", control.pid.CmdMax()).first;
control.pid.SetCmdMax(param);
param = controlSDF->Get("cmd_min", control.pid.CmdMin()).first;
control.pid.SetCmdMin(param);
// set pid initial command
control.pid.SetCmd(0.0);
this->dataPtr->controls.push_back(control);
controlSDF = controlSDF->GetNextElement("control");
}
}
/////////////////////////////////////////////////
void gz::sim::systems::ArduPilotPlugin::LoadImuSensors(
sdf::ElementPtr _sdf,
gz::sim::EntityComponentManager &/*_ecm*/)
{
this->dataPtr->imuName =
_sdf->Get("imuName", static_cast<std::string>("imu_sensor")).first;
}
/////////////////////////////////////////////////
void gz::sim::systems::ArduPilotPlugin::LoadGpsSensors(
sdf::ElementPtr /*_sdf*/,
gz::sim::EntityComponentManager &/*_ecm*/)
{
/*
NOT MERGED IN MASTER YET
// Get GPS
std::string gpsName = _sdf->Get("imuName",
static_cast<std::string>("gps_sensor")).first;
std::vector<std::string> gpsScopedName =
SensorScopedName(this->dataPtr->model, gpsName);
if (gpsScopedName.size() > 1)
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "multiple names match [" << gpsName << "] using first found"
<< " name.\n";
for (unsigned k = 0; k < gpsScopedName.size(); ++k)
{
gzwarn << " sensor " << k << " [" << gpsScopedName[k] << "].\n";
}
}
if (gpsScopedName.size() > 0)
{
this->dataPtr->gpsSensor = std::dynamic_pointer_cast<sensors::GpsSensor>
(sensors::SensorManager::Instance()->GetSensor(gpsScopedName[0]));
}
if (!this->dataPtr->gpsSensor)
{
if (gpsScopedName.size() > 1)
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "first gps_sensor scoped name [" << gpsScopedName[0]
<< "] not found, trying the rest of the sensor names.\n";
for (unsigned k = 1; k < gpsScopedName.size(); ++k)
{
this->dataPtr->gpsSensor =
std::dynamic_pointer_cast<sensors::GpsSensor>
(sensors::SensorManager::Instance()->GetSensor(gpsScopedName[k]));
if (this->dataPtr->gpsSensor)
{
gzwarn << "found [" << gpsScopedName[k] << "]\n";
break;
}
}
}
if (!this->dataPtr->gpsSensor)
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "gps_sensor scoped name [" << gpsName
<< "] not found, trying unscoped name.\n" << "\n";
this->dataPtr->gpsSensor = std::dynamic_pointer_cast<sensors::GpsSensor>
(sensors::SensorManager::Instance()->GetSensor(gpsName));
}
if (!this->dataPtr->gpsSensor)
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "gps [" << gpsName
<< "] not found, skipping gps support.\n" << "\n";
}
else
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< " found " << " [" << gpsName << "].\n";
}
}
*/
}
/////////////////////////////////////////////////
void gz::sim::systems::ArduPilotPlugin::LoadRangeSensors(
sdf::ElementPtr _sdf,
gz::sim::EntityComponentManager &/*_ecm*/)
{
struct SensorIdentifier
{
std::string type;
int index;
std::string topic;
};
std::vector<SensorIdentifier> sensorIds;
// read sensor elements
sdf::ElementPtr sensorSdf;
if (_sdf->HasElement("sensor"))
{
sensorSdf = _sdf->GetElement("sensor");
}
while (sensorSdf)
{
SensorIdentifier sensorId;
// <type> is required
if (sensorSdf->HasElement("type"))
{
sensorId.type = sensorSdf->Get<std::string>("type");
}
else
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "sensor element 'type' not specified, skipping.\n";
}
// <index> is required
if (sensorSdf->HasElement("index"))
{
sensorId.index = sensorSdf->Get<int>("index");
}
else
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "sensor element 'index' not specified, skipping.\n";
}
// <topic> is required
if (sensorSdf->HasElement("topic"))
{
sensorId.topic = sensorSdf->Get<std::string>("topic");
}
else
{
gzwarn << "[" << this->dataPtr->modelName << "] "
<< "sensor element 'topic' not specified, skipping.\n";
}
sensorIds.push_back(sensorId);
sensorSdf = sensorSdf->GetNextElement("sensor");
gzmsg << "[" << this->dataPtr->modelName << "] range "
<< "type: " << sensorId.type
<< ", index: " << sensorId.index
<< ", topic: " << sensorId.topic
<< "\n";
}
/// \todo(anyone) gazebo classic has different rules for generating
/// topic names, gazebo sim would benefit from similar rules when providing
/// topics names in sdf sensors elements.
// get the topic prefix
// std::string topicPrefix = "~/";
// topicPrefix += this->dataPtr->modelName;
// boost::replace_all(topicPrefix, "::", "/");
// subscriptions
for (auto &&sensorId : sensorIds)
{
/// \todo(anyone) see comment above re. topics
/// fully qualified topic name
/// std::string topicName = topicPrefix;
/// topicName.append("/").append(sensorId.topic);
std::string topicName = sensorId.topic;
// Bind the sensor index to the callback function
// (adjust from unit to zero offset)
OnMessageWrapper<gz::msgs::LaserScan>::callback_t fn =
std::bind(
&gz::sim::systems::ArduPilotPluginPrivate::RangeCb,
this->dataPtr.get(),
std::placeholders::_1,
sensorId.index - 1);
// Wrap the std::function so we can register the callback
auto callbackWrapper = RangeOnMessageWrapperPtr(
new OnMessageWrapper<gz::msgs::LaserScan>(fn));
auto callback = &OnMessageWrapper<gz::msgs::LaserScan>::OnMessage;
// Subscribe to range sensor topic
this->dataPtr->node.Subscribe(
topicName, callback, callbackWrapper.get());
this->dataPtr->rangeCbs.push_back(callbackWrapper);
/// \todo(anyone) initalise ranges properly
/// (AP convention for ignored value?)
this->dataPtr->ranges.push_back(-1.0);
gzmsg << "[" << this->dataPtr->modelName << "] subscribing to "
<< topicName << "\n";
}
}
/////////////////////////////////////////////////
void gz::sim::systems::ArduPilotPlugin::LoadWindSensors(
sdf::ElementPtr _sdf,
gz::sim::EntityComponentManager &/*_ecm*/)
{
this->dataPtr->anemometerName =
_sdf->Get("anemometer", static_cast<std::string>("")).first;