forked from gazebosim/gazebo-classic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgz.cc
1340 lines (1137 loc) · 36.2 KB
/
gz.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) 2014 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 <stdio.h>
#include <signal.h>
#include <tinyxml.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <streambuf>
#include <gazebo/common/common.hh>
#include <gazebo/transport/transport.hh>
#include <sdf/sdf.hh>
#include "gz_log.hh"
#include "gz_marker.hh"
#include "gz_topic.hh"
#include "gz.hh"
using namespace gazebo;
boost::mutex Command::sigMutex;
boost::condition_variable Command::sigCondition;
std::map<std::string, Command *> g_commandMap;
/////////////////////////////////////////////////
Command::Command(const std::string &_name, const std::string &_brief)
: name(_name), brief(_brief), visibleOptions("Options"), argc(0), argv(NULL)
{
this->visibleOptions.add_options()
("verbose", "Print extra information")
("help,h", "Print this help message");
}
/////////////////////////////////////////////////
Command::~Command()
{
delete [] this->argv;
this->argv = NULL;
}
/////////////////////////////////////////////////
void Command::Signal()
{
boost::mutex::scoped_lock lock(sigMutex);
sigCondition.notify_all();
}
/////////////////////////////////////////////////
void Command::ListOptions()
{
std::vector<std::string> pieces;
std::vector<boost::shared_ptr<po::option_description> >::const_iterator iter;
for (iter = this->visibleOptions.options().begin();
iter != this->visibleOptions.options().end(); ++iter)
{
pieces.clear();
std::string formatName = (*iter)->format_name();
pieces = common::split(formatName, " ");
if (pieces.empty())
{
std::cerr << "Unable to process list options.\n";
return;
}
// Output the short name option, or long name if there is no shortname
std::cout << pieces[0] << std::endl;
// Output the long name option if it exists.
if (pieces.size() > 3)
std::cout << pieces[2] << std::endl;
}
}
/////////////////////////////////////////////////
void Command::Help()
{
std::cerr << " gz " << this->name << " [options]\n\n";
this->HelpDetailed();
std::cerr << this->visibleOptions << "\n";
}
/////////////////////////////////////////////////
std::string Command::GetBrief() const
{
return this->brief;
}
/////////////////////////////////////////////////
bool Command::TransportInit()
{
// Some command require transport, and some do not. Only initialize
// transport if required.
if (!this->TransportRequired())
return true;
// Setup transport (communication)
if (!transport::init("", 0, 1))
return false;
// Run transport (communication)
transport::run();
return true;
}
/////////////////////////////////////////////////
bool Command::TransportRequired()
{
return true;
}
/////////////////////////////////////////////////
bool Command::TransportFini()
{
transport::fini();
return true;
}
/////////////////////////////////////////////////
bool Command::Run(int _argc, char **_argv)
{
// save a copy of argc and argv for consumption by child commands
this->argc = _argc;
this->argv = new char*[_argc];
for (int i = 0; i < _argc; ++i)
{
int argvLen = strlen(_argv[i]) + 1;
this->argv[i] = new char[argvLen];
#ifndef _WIN32
snprintf(this->argv[i], argvLen, "%s", _argv[i]);
#else
sprintf_s(this->argv[i], argvLen, "%s", _argv[i]);
#endif
}
// The SDF find file callback.
using namespace boost::placeholders;
sdf::setFindCallback(boost::bind(&gazebo::common::find_file, _1));
// Hidden options
po::options_description hiddenOptions("hidden options");
hiddenOptions.add_options()
("command", po::value<std::string>(), "Command")
("pass", po::value<std::vector<std::string> >(), "pass through");
po::options_description allOptions("all options");
allOptions.add(hiddenOptions).add(this->visibleOptions);
// The command and file options are positional
po::positional_options_description positional;
positional.add("command", 1).add("pass", -1);
try
{
po::store(
po::command_line_parser(_argc, _argv).options(allOptions).positional(
positional).run(), this->vm);
po::notify(this->vm);
}
catch(boost::exception &_e)
{
std::cerr << "Invalid arguments\n";
return false;
}
if (this->vm.count("help"))
{
this->Help();
return true;
}
if (this->vm.count("verbose"))
{
gazebo::common::Console::SetQuiet(false);
}
if (!this->TransportInit())
{
std::cerr << "An instance of Gazebo is not running.\n";
return false;
}
bool result = this->RunImpl();
this->TransportFini();
return result;
}
/////////////////////////////////////////////////
WorldCommand::WorldCommand()
: Command("world", "Modify world properties")
{
// Options that are visible to the user through help.
this->visibleOptions.add_options()
("world-name,w", po::value<std::string>(), "World name.")
("pause,p", po::value<bool>(), "Pause/unpause simulation. "
"0=unpause, 1=pause.")
("step,s", "Step simulation one iteration.")
("multi-step,m", po::value<uint32_t>(),
"Step simulation mulitple iteration.")
("reset-all,r", "Reset time and model poses")
("reset-time,t", "Reset time")
("reset-models,o", "Reset models");
}
/////////////////////////////////////////////////
void WorldCommand::HelpDetailed()
{
std::cerr <<
"\tChange properties of a Gazebo world on a running\n "
"\tserver. If a name for the world, option -w, is not specified\n"
"\tthe first world found on the Gazebo master will be used.\n"
<< std::endl;
}
/////////////////////////////////////////////////
bool WorldCommand::RunImpl()
{
std::string worldName;
if (this->vm.count("world-name"))
worldName = this->vm["world-name"].as<std::string>();
transport::NodePtr node(new transport::Node());
node->Init(worldName);
transport::PublisherPtr pub =
node->Advertise<msgs::WorldControl>("~/world_control");
pub->WaitForConnection();
msgs::WorldControl msg;
bool good = false;
if (this->vm.count("pause"))
{
msg.set_pause(this->vm["pause"].as<bool>());
good = true;
}
if (this->vm.count("step"))
{
msg.set_step(true);
good = true;
}
if (this->vm.count("multi-step"))
{
msg.set_multi_step(this->vm["multi-step"].as<uint32_t>());
good = true;
}
if (this->vm.count("reset-all"))
{
msg.mutable_reset()->set_all(true);
good = true;
}
if (this->vm.count("reset-time"))
{
msg.mutable_reset()->set_time_only(true);
good = true;
}
if (this->vm.count("reset-models"))
{
msg.mutable_reset()->set_model_only(true);
good = true;
}
if (good)
pub->Publish(msg, true);
else
this->Help();
return true;
}
/////////////////////////////////////////////////
PhysicsCommand::PhysicsCommand()
: Command("physics", "Modify properties of the physics engine")
{
// Options that are visible to the user through help.
this->visibleOptions.add_options()
("world-name,w", po::value<std::string>(), "World name.")
("gravity,g", po::value<std::string>(),
"Gravity vector. Comma separated 3-tuple without whitespace, "
"eg: -g 0,0,-9.8")
("step-size,s", po::value<double>(), "Maximum step size (seconds).")
("iters,i", po::value<double>(), "Number of iterations.")
("update-rate,u", po::value<double>(), "Target real-time update rate.")
("profile,o", po::value<std::string>(), "Preset physics profile.");
}
/////////////////////////////////////////////////
void PhysicsCommand::HelpDetailed()
{
std::cerr <<
"\tChange properties of the physics engine on a specific\n"
"\tworld. If a name for the world, option -w, is not specified,\n"
"\tthe first world found on the Gazebo master will be used.\n"
<< std::endl;
}
/////////////////////////////////////////////////
bool PhysicsCommand::RunImpl()
{
std::string worldName;
if (this->vm.count("world-name"))
worldName = this->vm["world-name"].as<std::string>();
transport::NodePtr node(new transport::Node());
node->Init(worldName);
transport::PublisherPtr pub =
node->Advertise<msgs::Physics>("~/physics");
pub->WaitForConnection();
msgs::Physics msg;
bool good = false;
if (this->vm.count("step-size"))
{
msg.set_max_step_size(this->vm["step-size"].as<double>());
good = true;
}
if (this->vm.count("iters"))
{
msg.set_iters(this->vm["iters"].as<double>());
good = true;
}
if (this->vm.count("update-rate"))
{
msg.set_real_time_update_rate(this->vm["update-rate"].as<double>());
good = true;
}
if (this->vm.count("gravity"))
{
auto values = common::split(this->vm["gravity"].as<std::string>(), ",");
msg.mutable_gravity()->set_x(boost::lexical_cast<double>(values[0]));
msg.mutable_gravity()->set_y(boost::lexical_cast<double>(values[1]));
msg.mutable_gravity()->set_z(boost::lexical_cast<double>(values[2]));
good = true;
}
if (this->vm.count("profile") &&
this->vm["profile"].as<std::string>().size() > 0)
{
msg.set_profile_name(this->vm["profile"].as<std::string>());
good = true;
}
if (good)
pub->Publish(msg, true);
else
this->Help();
return true;
}
/////////////////////////////////////////////////
ModelCommand::ModelCommand()
: Command("model", "Modify properties of a model")
{
// Options that are visible to the user through help.
this->visibleOptions.add_options()
("model-name,m", po::value<std::string>(), "Model name.")
("world-name,w", po::value<std::string>(), "World name.")
("delete,d", "Delete a model.")
("spawn-file,f", po::value<std::string>(), "Spawn model from SDF file.")
("spawn-string,s", "Spawn model from SDF string, pass by a pipe.")
("info,i", "Output model state information to the terminal.")
("pose,p",
"Output model pose as a space separated 6-tuple: x y z roll pitch yaw.")
("pose-x,x", po::value<double>(), "x value")
("pose-y,y", po::value<double>(), "y value")
("pose-z,z", po::value<double>(), "z value")
("pose-R,R", po::value<double>(), "roll in radians.")
("pose-P,P", po::value<double>(), "pitch in radians.")
("pose-Y,Y", po::value<double>(), "yaw in radians.");
}
/////////////////////////////////////////////////
void ModelCommand::HelpDetailed()
{
std::cerr <<
"\tChange properties of a model, delete a model, or\n"
"\tspawn a new model. If a name for the world, option -w, is\n"
"\tnot pecified, the first world found on the Gazebo master\n"
"\twill be used.\n"
<< std::endl;
}
/////////////////////////////////////////////////
bool ModelCommand::RunImpl()
{
std::string modelName, worldName;
if (this->vm.count("world-name"))
worldName = this->vm["world-name"].as<std::string>();
if (this->vm.count("model-name"))
modelName = this->vm["model-name"].as<std::string>();
else
{
std::cerr << "A model name is required using the "
<< "(-m <model_name> command line argument)\n";
std::cerr << "For more information: gz help model.\n";
return false;
}
ignition::math::Pose3d pose;
ignition::math::Vector3d rpy;
if (this->vm.count("pose-x"))
pose.Pos().X(this->vm["pose-x"].as<double>());
if (this->vm.count("pose-y"))
pose.Pos().Y(this->vm["pose-y"].as<double>());
if (this->vm.count("pose-z"))
pose.Pos().Z(this->vm["pose-z"].as<double>());
if (this->vm.count("pose-R"))
rpy.X(this->vm["pose-R"].as<double>());
if (this->vm.count("pose-P"))
rpy.Y(this->vm["pose-P"].as<double>());
if (this->vm.count("pose-Y"))
rpy.Z(this->vm["pose-Y"].as<double>());
pose.Rot().Euler(rpy);
transport::NodePtr node(new transport::Node());
node->Init(worldName);
if (this->vm.count("delete"))
{
msgs::Request *msg = msgs::CreateRequest("entity_delete", modelName);
transport::PublisherPtr pub = node->Advertise<msgs::Request>("~/request");
pub->WaitForConnection();
pub->Publish(*msg, true);
delete msg;
}
else if (this->vm.count("spawn-file"))
{
std::string filename = this->vm["spawn-file"].as<std::string>();
std::ifstream ifs(filename.c_str());
if (!ifs)
{
std::cerr << "Error: Unable to open file[" << filename << "]\n";
return false;
}
sdf::SDFPtr sdf(new sdf::SDF());
if (!sdf::init(sdf))
{
std::cerr << "Error: SDF parsing the xml failed" << std::endl;
return false;
}
sdf::Errors errors;
if (!sdf::readFileWithoutConversion(filename, sdf, errors))
{
std::cerr << "Error: SDF parsing the xml failed\n";
return false;
}
std::string resolvedFileName = filename;
if (common::isDirectory(filename))
{
// Use sdf::getModelFilePath() instead of filename because filename
// might be a model rectory
resolvedFileName = sdf::getModelFilePath(filename);
if (resolvedFileName.empty())
{
std::cerr << "The provided file is a directory, but a model could not "
<< "be found" << std::endl;
}
}
std::ifstream sdfFile(resolvedFileName);
// Using const std::string sdfString(arg, arg) confuses the compiler, so use
// move assignment
const auto sdfString = std::string(std::istreambuf_iterator<char>(sdfFile),
std::istreambuf_iterator<char>());
return this->ProcessSpawn(sdfString, modelName, pose, node);
}
else if (this->vm.count("spawn-string"))
{
std::string input;
std::string sdfString;
// Read input from the command line.
while (std::getline(std::cin, input))
{
sdfString += input;
}
sdf::SDFPtr sdf(new sdf::SDF());
if (!sdf::init(sdf))
{
std::cerr << "Error: SDF parsing the xml failed" << std::endl;
return false;
}
sdf::Errors errors;
if (!sdf::readStringWithoutConversion(sdfString, sdf, errors))
{
std::cerr << "Error: SDF parsing the xml failed\n";
return false;
}
return this->ProcessSpawn(sdfString, modelName, pose, node);
}
else if (this->vm.count("info") || this->vm.count("pose"))
{
boost::shared_ptr<msgs::Response> response = gazebo::transport::request(
worldName, "entity_info", modelName);
gazebo::msgs::Model modelMsg;
if (response->has_serialized_data() &&
!response->serialized_data().empty() &&
modelMsg.ParseFromString(response->serialized_data()))
{
if (this->vm.count("info"))
std::cout << modelMsg.DebugString() << std::endl;
else if (this->vm.count("pose"))
std::cout << gazebo::msgs::ConvertIgn(modelMsg.pose()) << std::endl;
}
else
{
std::string tmpWorldName = worldName.empty() ? "default" : worldName;
std::cout << "Unable to get info on model[" << modelName << "] in "
<< "the world[" << tmpWorldName << "]\n";
}
}
else
{
transport::PublisherPtr pub =
node->Advertise<msgs::Model>("~/model/modify");
pub->WaitForConnection();
msgs::Model msg;
msg.set_name(modelName);
msgs::Set(msg.mutable_pose(), pose);
pub->Publish(msg, true);
}
return true;
}
/////////////////////////////////////////////////
bool ModelCommand::ProcessSpawn(const std::string &_sdfString,
const std::string &_name, const ignition::math::Pose3d &_pose,
transport::NodePtr _node)
{
transport::PublisherPtr pub = _node->Advertise<msgs::Factory>("~/factory");
pub->WaitForConnection();
// To set the name of the model, we have to parse the file, set the name and
// reserialize to SDFormat. However, loading it using libsdformat will result
// in upconversion, which we would like to avoid because the resulting
// document will lose its OriginalVersion attribute. So, instead, we parse and
// edit the model name with TinyXML.
TiXmlDocument doc;
doc.Parse(_sdfString.c_str());
auto *root = doc.RootElement();
if (nullptr == root)
{
std::cerr << "Invalid XML file" << std::endl;
std::cout << _sdfString << std::endl;
return false;
}
// Handle SDFormat and URDF separately
if (root->ValueStr() == "sdf")
{
auto *model = root->FirstChildElement("model");
if (nullptr != model)
{
model->SetAttribute("name", _name);
}
else
{
std::cerr << "Could not find <model> tag in SDFormat file" << std::endl;
}
}
else if (root->ValueStr() == "robot")
{
root->SetAttribute("name", _name);
}
else
{
std::cerr << "Unknown file format" << std::endl;
}
TiXmlPrinter printer;
doc.Accept(&printer);
msgs::Factory msg;
msg.set_sdf(printer.Str());
msgs::Set(msg.mutable_pose(), _pose);
pub->Publish(msg, true);
return true;
}
/////////////////////////////////////////////////
JointCommand::JointCommand()
: Command("joint", "Modify properties of a joint")
{
// Options that are visible to the user through help.
this->visibleOptions.add_options()
("world-name,w", po::value<std::string>(), "World name.")
("model-name,m", po::value<std::string>(), "Model name.")
("joint-name,j", po::value<std::string>(), "Joint name.")
("force,f", po::value<double>(), "Force to apply to a joint (N).")
("pos-t", po::value<double>(),
"Target angle(rad) for rotation joints or position (m) for linear joints.")
("pos-p", po::value<double>(), "Position proportional gain.")
("pos-i", po::value<double>(), "Position integral gain.")
("pos-d", po::value<double>(), "Position differential gain.")
("vel-t", po::value<double>(),
"Target speed (rad/s for rotational joints or m/s for linear joints).")
("vel-p", po::value<double>(), "Velocity proportional gain.")
("vel-i", po::value<double>(), "Velocity integral gain.")
("vel-d", po::value<double>(), "Velocity differential gain.");
}
/////////////////////////////////////////////////
void JointCommand::HelpDetailed()
{
std::cerr <<
"\tChange properties of a joint. If a name for the world, \n"
"\toption -w, is not specified, the first world found on \n"
"\tthe Gazebo master will be used.\n"
"\tA model name and joint name are required.\n"
"\n"
"\tIt is recommended to use only one type of command:\n"
"\tforce, position PID, or velocity PID.\n"
"\n"
"\tForce: Use --force to apply a force.\n"
"\n"
"\tPosition PID: Use --pos-t to specify a target position\n"
"\twith --pos-p, --pos-i, --pos-d to specify the PID parameters.\n"
"\n"
"\tVelocity PID: Use --vel-t to specify a target velocity\n"
"\twith --vel-p, --vel-i, --vel-d to specify the PID parameters.\n"
<< std::endl;
}
/////////////////////////////////////////////////
bool JointCommand::RunImpl()
{
std::string modelName, jointName;
if (this->vm.count("model-name"))
modelName = this->vm["model-name"].as<std::string>();
else
{
std::cerr << "A model name is required using the "
<< "(-m <model_name> command line argument)\n";
std::cerr << "For more information: gz help joint.\n";
return false;
}
if (this->vm.count("joint-name"))
jointName = this->vm["joint-name"].as<std::string>();
else
{
std::cerr << "A joint name is required using the "
<< "(-j <joint_name> command line argument)\n";
std::cerr << "For more information: gz help joint.\n";
return false;
}
ignition::msgs::JointCmd msg;
msg.set_name(modelName + "::" + jointName);
if (this->vm.count("force"))
msg.mutable_force_optional()->set_data(this->vm["force"].as<double>());
if (this->vm.count("pos-t"))
{
msg.mutable_position()->mutable_target_optional()->set_data(
this->vm["pos-t"].as<double>());
if (this->vm.count("pos-p"))
{
msg.mutable_position()->mutable_p_gain_optional()->set_data(
this->vm["pos-p"].as<double>());
}
if (this->vm.count("pos-i"))
{
msg.mutable_position()->mutable_i_gain_optional()->set_data(
this->vm["pos-i"].as<double>());
}
if (this->vm.count("pos-d"))
{
msg.mutable_position()->mutable_d_gain_optional()->set_data(
this->vm["pos-d"].as<double>());
}
}
if (this->vm.count("vel-t"))
{
msg.mutable_velocity()->mutable_target_optional()->set_data(
this->vm["vel-t"].as<double>());
if (this->vm.count("vel-p"))
{
msg.mutable_velocity()->mutable_p_gain_optional()->set_data(
this->vm["vel-p"].as<double>());
}
if (this->vm.count("vel-i"))
{
msg.mutable_velocity()->mutable_i_gain_optional()->set_data(
this->vm["vel-i"].as<double>());
}
if (this->vm.count("vel-d"))
{
msg.mutable_velocity()->mutable_d_gain_optional()->set_data(
this->vm["vel-d"].as<double>());
}
}
std::string topic = std::string("/") + modelName + "/joint_cmd";
ignition::transport::Node ignNode;
auto pub = ignNode.Advertise<ignition::msgs::JointCmd>(topic);
unsigned int maxSleep = 30;
unsigned int sleep = 0;
unsigned int mSleep = 100;
for (; sleep < maxSleep && !pub.HasConnections(); ++sleep)
{
common::Time::MSleep(mSleep);
}
if (sleep == maxSleep)
{
gzerr << "No subscribers to topic [" << topic <<"], timed out after " <<
maxSleep * mSleep << "ms." << std::endl;
return false;
}
pub.Publish(msg);
return true;
}
/////////////////////////////////////////////////
CameraCommand::CameraCommand()
: Command("camera", "Control a camera")
{
// Options that are visible to the user through help.
this->visibleOptions.add_options()
("world-name,w", po::value<std::string>(), "World name.")
("camera-name,c", po::value<std::string>(),
"Camera name. Use gz camera -l to get a list of camera names.")
("list,l", "List all cameras")
("follow,f", po::value<std::string>(), "Model to follow.");
}
/////////////////////////////////////////////////
void CameraCommand::HelpDetailed()
{
std::cerr <<
"\tChange properties of a camera. If a name for the world, \n"
"\toption -w, is not specified, the first world found on \n"
"\tthe Gazebo master will be used.\n"
"\tA camera name is required.\n"
<< std::endl;
}
/////////////////////////////////////////////////
bool CameraCommand::RunImpl()
{
std::string cameraName, worldName;
if (this->vm.count("world-name"))
worldName = this->vm["world-name"].as<std::string>();
if (this->vm.count("list"))
{
transport::ConnectionPtr connection = transport::connectToMaster();
if (connection)
{
msgs::Packet packet;
msgs::Request *request;
msgs::GzString_V topics;
std::string data;
request = msgs::CreateRequest("get_topics");
request->set_id(0);
connection->EnqueueMsg(msgs::Package("request", *request), true);
connection->Read(data);
packet.ParseFromString(data);
topics.ParseFromString(packet.serialized_data());
for (int i = 0; i < topics.data_size(); ++i)
{
request = msgs::CreateRequest("topic_info", topics.data(i));
connection->EnqueueMsg(msgs::Package("request", *request), true);
int j = 0;
do
{
connection->Read(data);
packet.ParseFromString(data);
} while (packet.type() != "topic_info_response" && ++j < 10);
msgs::TopicInfo topicInfo;
if (j <10)
topicInfo.ParseFromString(packet.serialized_data());
else
{
std::cerr << "Unable to get info for topic["
<< topics.data(i) << "]\n";
}
if (topicInfo.msg_type() == "gazebo.msgs.CameraCmd")
{
auto parts = common::split(topics.data(i), "/");
std::cout << parts[parts.size()-2] << std::endl;
}
}
}
else
{
std::cerr << "Unable to connect to a running instance of gazebo.\n";
}
return true;
}
if (this->vm.count("camera-name"))
cameraName = this->vm["camera-name"].as<std::string>();
else
{
std::cerr << "A camera name is required using the "
<< "(-c <camera_name> command line argument)\n";
std::cerr << "For more information: gz help camera\n";
return false;
}
msgs::CameraCmd msg;
if (this->vm.count("follow"))
msg.set_follow_model(this->vm["follow"].as<std::string>());
transport::NodePtr node(new transport::Node());
node->Init(worldName);
boost::replace_all(cameraName, "::", "/");
transport::PublisherPtr pub =
node->Advertise<msgs::CameraCmd>(
std::string("~/") + cameraName + "/cmd");
pub->WaitForConnection();
pub->Publish(msg, true);
return true;
}
/////////////////////////////////////////////////
StatsCommand::StatsCommand()
: Command("stats", "Print statistics about a running gzserver instance.")
{
// Options that are visible to the user through help.
this->visibleOptions.add_options()
("world-name,w", po::value<std::string>(), "World name.")
("duration,d", po::value<uint64_t>(), "Duration (seconds) to run.")
("plot,p", "Output comma-separated values, useful for processing and "
"plotting.");
}
/////////////////////////////////////////////////
void StatsCommand::HelpDetailed()
{
std::cerr <<
"\tPrint gzserver statics to standard out. If a name for the world, \n"
"\toption -w, is not specified, the first world found on \n"
"\tthe Gazebo master will be used.\n"
<< std::endl;
}
/////////////////////////////////////////////////
bool StatsCommand::RunImpl()
{
std::string worldName;
if (this->vm.count("world-name"))
worldName = this->vm["world-name"].as<std::string>();
transport::NodePtr node(new transport::Node());
node->Init(worldName);
transport::SubscriberPtr sub =
node->Subscribe("~/world_stats", &StatsCommand::CB, this);
boost::mutex::scoped_lock lock(this->sigMutex);
if (this->vm.count("duration"))
this->sigCondition.timed_wait(lock,
boost::posix_time::seconds(this->vm["duration"].as<uint64_t>()));
else
this->sigCondition.wait(lock);
return true;
}
/////////////////////////////////////////////////
void StatsCommand::CB(ConstWorldStatisticsPtr &_msg)
{
GZ_ASSERT(_msg, "Invalid message received");
double percent = 0;
char paused;
common::Time simTime = msgs::Convert(_msg->sim_time());
common::Time realTime = msgs::Convert(_msg->real_time());
this->simTimes.push_back(msgs::Convert(_msg->sim_time()));
if (this->simTimes.size() > 20)
this->simTimes.pop_front();
this->realTimes.push_back(msgs::Convert(_msg->real_time()));
if (this->realTimes.size() > 20)
this->realTimes.pop_front();
common::Time simAvg, realAvg;
std::list<common::Time>::iterator simIter, realIter;
simIter = ++(this->simTimes.begin());
realIter = ++(this->realTimes.begin());
while (simIter != this->simTimes.end() && realIter != this->realTimes.end())
{
simAvg += ((*simIter) - this->simTimes.front());
realAvg += ((*realIter) - this->realTimes.front());
++simIter;
++realIter;
}
// Prevent divide by zero
if (realAvg <= 0)
return;
simAvg = simAvg / realAvg;
if (simAvg > 0)
percent = simAvg.Double();
else
percent = 0;
if (_msg->paused())
paused = 'T';
else
paused = 'F';
if (this->vm.count("plot"))
{
static bool first = true;
if (first)
{
std::cout << "# real-time factor (percent), simtime (sec), "
<< "realtime (sec), paused (T or F)\n";
first = false;
}
printf("%4.2f, %16.6f, %16.6f, %c\n",
percent, simTime.Double(), realTime.Double(), paused);
fflush(stdout);
}