-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathxs_driver.cpp
More file actions
1492 lines (1387 loc) · 51.2 KB
/
xs_driver.cpp
File metadata and controls
1492 lines (1387 loc) · 51.2 KB
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 2022 Trossen Robotics
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "interbotix_xs_driver/xs_driver.hpp"
#include <string>
#include <vector>
#include <memory>
#include <mutex>
#include <thread>
#include <unordered_map>
namespace interbotix_xs
{
InterbotixDriverXS::InterbotixDriverXS(
std::string filepath_motor_configs,
std::string filepath_mode_configs,
bool write_eeprom_on_startup,
std::string logging_level)
{
XSLOG_INFO(
"Using Interbotix X-Series Driver Version: 'v%d.%d.%d'.",
VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
logging::set_level(logging_level);
XSLOG_INFO("Using logging level '%s'.", logging_level.c_str());
if (!retrieve_motor_configs(filepath_motor_configs, filepath_mode_configs)) {
throw std::runtime_error("Failed due to bad config.");
}
if (!init_port()) {
throw std::runtime_error("Failed to open port.");
}
if (!ping_motors()) {
XSLOG_FATAL("Failed to find all motors. Shutting down...");
throw std::runtime_error("Failed to find all motors.");
}
if (write_eeprom_on_startup) {
if (!load_motor_configs()) {
XSLOG_FATAL("Failed to write configurations to all motors. Shutting down...");
throw std::runtime_error("Failed to write configurations to all motors.");
}
XSLOG_WARN(
"Writing startup register values to EEPROM. This only needs to be done once on a robot if "
"using a default motor config file, or after a motor config file has been modified. "
"Can set `write_eeprom_on_startup` to false from now on.");
} else {
XSLOG_INFO("Skipping Load Configs.");
}
init_controlItems();
init_workbench_handlers();
init_operating_modes();
init_controlItems();
XSLOG_INFO("Interbotix X-Series Driver is up!");
}
bool InterbotixDriverXS::set_operating_modes(
const std::string & cmd_type,
const std::string & name,
const std::string & mode,
const std::string profile_type,
const int32_t profile_velocity,
const int32_t profile_acceleration)
{
if (cmd_type == cmd_type::GROUP && group_map.count(name) > 0) {
// group case
for (auto const & joint_name : get_group_info(name)->joint_names) {
set_joint_operating_mode(
joint_name,
mode,
profile_type,
profile_velocity,
profile_acceleration);
}
get_group_info(name)->mode = mode;
get_group_info(name)->profile_type = profile_type;
get_group_info(name)->profile_velocity = profile_velocity;
get_group_info(name)->profile_acceleration = profile_acceleration;
XSLOG_INFO(
"The operating mode for the '%s' group was changed to '%s' with profile type '%s'.",
name.c_str(), mode.c_str(), profile_type.c_str());
} else if (cmd_type == cmd_type::SINGLE && motor_map.count(name) > 0) {
// single case
set_joint_operating_mode(
name,
mode,
profile_type,
profile_velocity,
profile_acceleration);
XSLOG_INFO(
"The operating mode for the '%s' joint was changed to '%s' with profile type '%s'.",
name.c_str(), mode.c_str(), profile_type.c_str());
} else if ( // NOLINT https://github.com/ament/ament_lint/issues/158
(cmd_type == cmd_type::GROUP && group_map.count(name) == 0) ||
(cmd_type == cmd_type::SINGLE && motor_map.count(name) == 0))
{
// case where specified joint or group does not exist depending on cmd_type
XSLOG_ERROR(
"The '%s' joint/group does not exist. Was it added to the motor config file?",
name.c_str());
return false;
} else {
// case where cmd_type is invalid (i.e. not 'group' or 'single')
XSLOG_ERROR("Invalid command for argument 'cmd_type' while setting operating mode.");
return false;
}
return true;
}
bool InterbotixDriverXS::set_joint_operating_mode(
const std::string & name,
const std::string & mode,
const std::string profile_type,
const int32_t profile_velocity,
const int32_t profile_acceleration)
{
// torque off sister servos
for (auto const & joint_name : sister_map[name]) {
dxl_wb.torque(motor_map[joint_name].motor_id, false);
XSLOG_DEBUG("ID: %d, torqued off.", motor_map[joint_name].motor_id);
}
for (auto const & motor_name : shadow_map[name]) {
int32_t drive_mode;
// read drive mode for each shadow
dxl_wb.itemRead(motor_map[motor_name].motor_id, "Drive_Mode", &drive_mode);
std::bitset<8> drive_mode_bitset_read = drive_mode, drive_mode_bitset_write = drive_mode;
XSLOG_DEBUG(
"ID: %d, read Drive_Mode [%s].",
motor_map[motor_name].motor_id, drive_mode_bitset_read.to_string().c_str());
// The 2nd (0x04) bit of the Drive_Mode register sets Profile Configuration
// [0/false]: Velocity-based Profile: Create a Profile based on Velocity
// [1/true]: Time-based Profile: Create Profile based on Time
if (profile_type == profile::TIME) {
drive_mode_bitset_write.set(2); // turn ON for time profile
} else if (profile_type == profile::VELOCITY) {
drive_mode_bitset_write.reset(2); // turn OFF for velocity profile
}
// if not correct, write the correct drive mode based on the profile type
// see https://emanual.robotis.com/docs/en/dxl/x/xm430-w350/#drive-mode for details
if (!drive_mode_bitset_read.test(2) && profile_type == profile::TIME) {
// if the 2nd read bit was OFF and profile_type is time, write new Drive_Mode
dxl_wb.itemWrite(
motor_map[motor_name].motor_id, "Drive_Mode", drive_mode_bitset_write.to_ulong());
XSLOG_DEBUG(
"ID: %d, write Drive_Mode [%s].",
motor_map[motor_name].motor_id, drive_mode_bitset_write.to_string().c_str());
} else if (drive_mode_bitset_read.test(2) && profile_type == profile::VELOCITY) {
// if the 2nd read bit was ON and profile_type is velocity, write new Drive_Mode
dxl_wb.itemWrite(
motor_map[motor_name].motor_id, "Drive_Mode", drive_mode_bitset_write.to_ulong());
XSLOG_DEBUG(
"ID: %d, write Drive_Mode [%s].",
motor_map[motor_name].motor_id, drive_mode_bitset_write.to_string().c_str());
}
if (mode == mode::POSITION || mode == mode::LINEAR_POSITION) {
// set position control mode if the mode is position or linear_position
// also set prof_acc and prof_vel
dxl_wb.setPositionControlMode(motor_map[motor_name].motor_id);
dxl_wb.itemWrite(
motor_map[motor_name].motor_id,
"Profile_Velocity",
profile_velocity);
dxl_wb.itemWrite(
motor_map[motor_name].motor_id,
"Profile_Acceleration",
profile_acceleration);
XSLOG_DEBUG(
"ID: %d, set mode position, prof_vel=%i, prof_acc=%i.",
motor_map[motor_name].motor_id, profile_velocity, profile_acceleration);
} else if (mode == mode::EXT_POSITION) {
// set ext_position control mode if the mode is ext_position
// also set prof_acc and prof_vel
dxl_wb.setExtendedPositionControlMode(
motor_map[motor_name].motor_id);
dxl_wb.itemWrite(
motor_map[motor_name].motor_id,
"Profile_Velocity",
profile_velocity);
dxl_wb.itemWrite(
motor_map[motor_name].motor_id,
"Profile_Acceleration",
profile_acceleration);
XSLOG_DEBUG(
"ID: %d, set mode ext_postition, pv=%i, pa=%i.",
motor_map[motor_name].motor_id, profile_velocity, profile_acceleration);
} else if (mode == mode::VELOCITY) {
// set velocity control mode if the mode is velocity
// also set prof_acc
dxl_wb.setVelocityControlMode(
motor_map[motor_name].motor_id);
dxl_wb.itemWrite(
motor_map[motor_name].motor_id,
"Profile_Acceleration",
profile_acceleration);
XSLOG_DEBUG(
"ID: %d, set mode velocity, prof_acc=%i.",
motor_map[motor_name].motor_id, profile_acceleration);
} else if (mode == mode::PWM) {
// set pwm control mode if the mode is pwm
dxl_wb.setPWMControlMode(
motor_map[motor_name].motor_id);
XSLOG_DEBUG(
"ID: %d, set mode pwm.",
motor_map[motor_name].motor_id);
} else if (mode == mode::CURRENT) {
// set current control mode if the mode is current
dxl_wb.setCurrentControlMode(
motor_map[motor_name].motor_id);
XSLOG_DEBUG(
"ID: %d, set mode current.",
motor_map[motor_name].motor_id);
} else if (mode == mode::CURRENT_BASED_POSITION) {
// set current_based_position control mode if the mode is current_based_position
dxl_wb.setCurrentBasedPositionControlMode(
motor_map[motor_name].motor_id);
XSLOG_DEBUG(
"ID: %d, set mode current_based_position.",
motor_map[motor_name].motor_id);
} else {
// mode was invalid
XSLOG_ERROR(
"Invalid command for argument 'mode' while setting the operating mode for the %s motor.",
motor_name.c_str());
continue;
}
// set the mode and profile_type of each servo in the motor map
motor_map[motor_name].mode = mode;
motor_map[motor_name].profile_type = profile_type;
motor_map[motor_name].profile_velocity = profile_velocity;
motor_map[motor_name].profile_acceleration = profile_acceleration;
}
// torque on all sister servos
for (auto const & joint_name : sister_map[name]) {
dxl_wb.torque(motor_map[joint_name].motor_id, true);
XSLOG_DEBUG(
"ID: %d, torqued on.",
motor_map[joint_name].motor_id);
}
return true;
}
bool InterbotixDriverXS::torque_enable(
const std::string cmd_type,
const std::string & name,
const bool & enable)
{
if (cmd_type == cmd_type::GROUP && group_map.count(name) > 0) {
// group case
for (auto const & joint_name : get_group_info(name)->joint_names) {
// torque each servo in group
dxl_wb.torque(motor_map[joint_name].motor_id, enable);
}
// log torque action
if (enable) {
XSLOG_INFO("The '%s' group was torqued on.", name.c_str());
} else {
XSLOG_INFO("The '%s' group was torqued off.", name.c_str());
}
} else if (cmd_type == cmd_type::SINGLE && motor_map.count(name) > 0) {
// single case
// torque the single servo
dxl_wb.torque(motor_map[name].motor_id, enable);
// log torque action
if (enable) {
XSLOG_INFO("The '%s' joint was torqued on.", name.c_str());
} else {
XSLOG_INFO("The '%s' joint was torqued off.", name.c_str());
}
} else if ( // NOLINT https://github.com/ament/ament_lint/issues/158
(cmd_type == cmd_type::GROUP && group_map.count(name) == 0) ||
(cmd_type == cmd_type::SINGLE && motor_map.count(name) == 0))
{
// invalid name
XSLOG_ERROR(
"The '%s' joint/group does not exist. Was it added to the motor config file?",
name.c_str());
return false;
} else {
// inavlid cmd_type
XSLOG_ERROR(
"Invalid command for argument 'cmd_type' while torquing joints.");
return false;
}
return true;
}
bool InterbotixDriverXS::reboot_motors(
const std::string cmd_type,
const std::string & name,
const bool & enable,
const bool & smart_reboot)
{
std::vector<std::string> joints_to_torque;
if (cmd_type == cmd_type::GROUP && group_map.count(name) > 0) {
// group case
for (auto const & joint_name : get_group_info(name)->joint_names) {
// iterate through each joint in group
if (smart_reboot) {
// if smart_reboot, find the servos that are in an error status
int32_t value = 0;
const char * log;
bool success = dxl_wb.itemRead(
motor_map[joint_name].motor_id,
"Hardware_Error_Status",
&value, &log);
if (success && value == 0) {
continue;
}
}
// reboot the servo
dxl_wb.reboot(motor_map[joint_name].motor_id);
XSLOG_INFO("The '%s' joint was rebooted.", joint_name.c_str());
if (enable) {
// add servo to joints_to_torque if enabled
joints_to_torque.push_back(joint_name);
}
}
if (!smart_reboot) {
XSLOG_INFO("The '%s' group was rebooted.", name.c_str());
}
} else if (cmd_type == cmd_type::SINGLE && motor_map.count(name) > 0) {
// single case
// reboot the single servo
dxl_wb.reboot(motor_map[name].motor_id);
XSLOG_INFO("The '%s' joint was rebooted.", name.c_str());
if (enable) {
// add servo to joints_to_torque if enabled
joints_to_torque.push_back(name);
}
} else if ( // NOLINT https://github.com/ament/ament_lint/issues/158
(cmd_type == cmd_type::GROUP && group_map.count(name) == 0) ||
(cmd_type == cmd_type::SINGLE && motor_map.count(name) == 0))
{
// invalid name
XSLOG_ERROR(
"The '%s' joint/group does not exist. Was it added to the motor config file?",
name.c_str());
return false;
} else {
// invalid cmd_type
XSLOG_ERROR(
"Invalid command for argument 'cmd_type' while rebooting motors.");
return false;
}
// torque servos in joints_to_torque and their sisters
for (const auto & joint_name : joints_to_torque) {
for (const auto & name : sister_map[joint_name]) {
torque_enable(cmd_type::SINGLE, name, true);
}
}
return true;
}
template<typename T>
bool InterbotixDriverXS::write_commands(
const std::string & name,
std::vector<T> commands_in)
{
std::vector<float> commands(commands_in.begin(), commands_in.end());
if (commands.size() != get_group_info(name)->joint_num) {
XSLOG_ERROR(
"Number of commands (%ld) does not match the number of joints in group '%s' (%d). "
"Will not execute.",
commands.size(), name.c_str(), get_group_info(name)->joint_num);
return false;
}
const std::string mode = get_group_info(name)->mode;
std::vector<int32_t> dynamixel_commands(commands.size());
if (
(mode == mode::POSITION) ||
(mode == mode::EXT_POSITION) ||
(mode == mode::CURRENT_BASED_POSITION) ||
(mode == mode::LINEAR_POSITION))
{
// position commands case
for (size_t i{0}; i < commands.size(); i++) {
if (mode == mode::LINEAR_POSITION) {
// convert from linear position if necessary
commands.at(i) = convert_linear_position_to_radian(
get_group_info(name)->joint_names.at(i),
commands.at(i));
}
// Apply mechanical reduction to the angular values
float j_reduction = js_mech_reduction_map[get_group_info(name)->joint_ids.at(i)];
for (size_t i{0}; i < commands.size(); i++) {
commands.at(i) = commands.at(i) / j_reduction;
}
// translate from position to command value
dynamixel_commands[i] = dxl_wb.convertRadian2Value(
get_group_info(name)->joint_ids.at(i),
commands.at(i));
XSLOG_DEBUG(
"ID: %d, writing %s command %d.",
get_group_info(name)->joint_ids.at(i),
mode.c_str(),
dynamixel_commands[i]);
}
// write position commands
dxl_wb.syncWrite(
SYNC_WRITE_HANDLER_FOR_GOAL_POSITION,
get_group_info(name)->joint_ids.data(),
get_group_info(name)->joint_num,
&dynamixel_commands[0],
1);
} else if (mode == mode::VELOCITY) {
// velocity commands case
for (size_t i{0}; i < commands.size(); i++) {
// translate from velocity to command value
dynamixel_commands[i] = dxl_wb.convertVelocity2Value(
get_group_info(name)->joint_ids.at(i),
commands.at(i));
XSLOG_DEBUG(
"ID: %d, writing %s command %d.",
get_group_info(name)->joint_ids.at(i),
mode.c_str(),
dynamixel_commands[i]);
}
// write velocity commands
dxl_wb.syncWrite(
SYNC_WRITE_HANDLER_FOR_GOAL_VELOCITY,
get_group_info(name)->joint_ids.data(),
get_group_info(name)->joint_num,
&dynamixel_commands[0],
1);
} else if (mode == mode::CURRENT) {
// velocity commands case
for (size_t i{0}; i < commands.size(); i++) {
// translate from current to command value
dynamixel_commands[i] = dxl_wb.convertCurrent2Value(commands.at(i));
XSLOG_DEBUG(
"ID: %d, writing %s command %d.",
get_group_info(name)->joint_ids.at(i),
mode.c_str(),
dynamixel_commands[i]);
}
// write velocity commands
dxl_wb.syncWrite(
SYNC_WRITE_HANDLER_FOR_GOAL_CURRENT,
get_group_info(name)->joint_ids.data(),
get_group_info(name)->joint_num,
&dynamixel_commands[0],
1);
} else if (mode == mode::PWM) {
// pwm commands case, don't need to translate from pwm to value
for (size_t i{0}; i < commands.size(); i++) {
dynamixel_commands[i] = int32_t(commands.at(i));
XSLOG_DEBUG(
"ID: %d, writing %s command %d.",
get_group_info(name)->joint_ids.at(i),
mode.c_str(),
dynamixel_commands[i]);
}
// write pwm commands
dxl_wb.syncWrite(
SYNC_WRITE_HANDLER_FOR_GOAL_PWM,
get_group_info(name)->joint_ids.data(),
get_group_info(name)->joint_num,
&dynamixel_commands[0],
1);
} else {
// invalid mode
XSLOG_ERROR(
"Invalid command for argument 'mode' while commanding joint group.");
return false;
}
return true;
}
bool InterbotixDriverXS::write_position_commands(
const std::string & name,
std::vector<float> commands,
bool blocking)
{
std::string mode = group_map.at(name).mode;
if (mode != mode::POSITION) {
XSLOG_ERROR(
"Group '%s' is in %s mode not in position mode. Will not execute commands.",
name.c_str(), mode.c_str());
return false;
}
bool res = write_commands(name, commands);
if (blocking) {
std::this_thread::sleep_for(std::chrono::milliseconds(group_map.at(name).profile_velocity));
}
return res;
}
bool InterbotixDriverXS::write_joint_command(
const std::string & name,
float command)
{
const std::string mode = motor_map[name].mode;
if (
(mode == mode::POSITION) ||
(mode == mode::EXT_POSITION) ||
(mode == mode::CURRENT_BASED_POSITION) ||
(mode == mode::LINEAR_POSITION))
{
// position command case
if (mode == mode::LINEAR_POSITION) {
// convert from linear position if necessary
command = convert_linear_position_to_radian(name, command);
}
// Apply mechanical reduction to the angular values
float j_reduction = js_mech_reduction_map[motor_map[name].motor_id];
command = command / j_reduction;
XSLOG_DEBUG(
"ID: %d, writing %s command %f.",
motor_map[name].motor_id, mode.c_str(), command);
// write position command
dxl_wb.goalPosition(motor_map[name].motor_id, command);
} else if (mode == mode::VELOCITY) {
// position velocity case
XSLOG_DEBUG(
"ID: %d, writing %s command %f.",
motor_map[name].motor_id, mode.c_str(), command);
// write velocity command
dxl_wb.goalVelocity(motor_map[name].motor_id, command);
} else if (mode == mode::CURRENT) {
// position current case
XSLOG_DEBUG(
"ID: %d, writing %s command %f.",
motor_map[name].motor_id, mode.c_str(), command);
// write current command
dxl_wb.itemWrite(
motor_map[name].motor_id, "Goal_Current", dxl_wb.convertCurrent2Value(command));
} else if (mode == mode::PWM) {
// pwm current case
XSLOG_DEBUG(
"ID: %d, writing %s command %f.",
motor_map[name].motor_id, mode.c_str(), command);
// write pwm command
dxl_wb.itemWrite(motor_map[name].motor_id, "Goal_PWM", int32_t(command));
} else {
// invalid mode
XSLOG_ERROR(
"Invalid command for argument 'mode' while commanding joint '%s'.", name.c_str());
return false;
}
return true;
}
bool InterbotixDriverXS::set_motor_pid_gains(
const std::string cmd_type,
const std::string & name,
const std::vector<int32_t> & gains)
{
std::vector<std::string> names;
if (cmd_type == cmd_type::GROUP) {
// group case, get names from group map
names = get_group_info(name)->joint_names;
} else if (cmd_type == cmd_type::SINGLE) {
// single case, just use given name
names.push_back(name);
}
for (auto const & name : names) {
// write gains for each servo
uint8_t id = motor_map[name].motor_id;
XSLOG_DEBUG("ID: %d, writing gains:", motor_map[name].motor_id);
XSLOG_DEBUG(" Pos_P: %i", gains.at(0));
XSLOG_DEBUG(" Pos_I: %i", gains.at(1));
XSLOG_DEBUG(" Pos_D: %i", gains.at(2));
XSLOG_DEBUG(" FF_1: %i", gains.at(3));
XSLOG_DEBUG(" FF_2: %i", gains.at(4));
XSLOG_DEBUG(" Vel_P: %i", gains.at(5));
XSLOG_DEBUG(" Vel_I: %i", gains.at(6));
dxl_wb.itemWrite(id, "Position_P_Gain", gains.at(0));
dxl_wb.itemWrite(id, "Position_I_Gain", gains.at(1));
dxl_wb.itemWrite(id, "Position_D_Gain", gains.at(2));
dxl_wb.itemWrite(id, "Feedforward_1st_Gain", gains.at(3));
dxl_wb.itemWrite(id, "Feedforward_2nd_Gain", gains.at(4));
dxl_wb.itemWrite(id, "Velocity_P_Gain", gains.at(5));
dxl_wb.itemWrite(id, "Velocity_I_Gain", gains.at(6));
}
return true;
}
bool InterbotixDriverXS::set_motor_registers(
const std::string cmd_type,
const std::string & name,
const std::string & reg,
const int32_t & value)
{
std::vector<std::string> names;
if (cmd_type == cmd_type::GROUP) {
// group case, get names from group map
names = get_group_info(name)->joint_names;
} else if (cmd_type == cmd_type::SINGLE) {
// single case, just use given name
names.push_back(name);
}
for (auto const & name : names) {
// write register for each servo
XSLOG_DEBUG(
"ID: %d, writing reg: %s, value: %d.",
motor_map[name].motor_id, reg.c_str(), value);
dxl_wb.itemWrite(motor_map[name].motor_id, reg.c_str(), value);
}
return true;
}
bool InterbotixDriverXS::get_motor_registers(
const std::string cmd_type,
const std::string & name,
const std::string & reg,
std::vector<int32_t> & values)
{
std::vector<std::string> names;
if (cmd_type == cmd_type::GROUP) {
// group case, get names from group map
names = get_group_info(name)->joint_names;
} else if (cmd_type == cmd_type::SINGLE) {
// single case, just use given name
names.push_back(name);
}
// get info on the register that is going to be read from
const ControlItem * goal_reg = dxl_wb.getItemInfo(
motor_map.at(names.front()).motor_id, reg.c_str());
if (goal_reg == NULL) {
XSLOG_ERROR(
"Could not get '%s' Item Info. Did you spell the register name correctly?",
reg.c_str());
return false;
}
for (auto const & name : names) {
int32_t value = 0;
const char * log;
// read register for each servo and check result for success
if (!dxl_wb.itemRead(motor_map[name].motor_id, reg.c_str(), &value, &log)) {
XSLOG_ERROR("%s", log);
return false;
} else {
XSLOG_DEBUG(
"ID: %d, reading reg: '%s', value: %d.", motor_map[name].motor_id, reg.c_str(), value);
}
// add register to values vector with type depending on data_length
if (goal_reg->data_length == 1) {
values.push_back((uint8_t)value);
} else if (goal_reg->data_length == 2) {
values.push_back((int16_t)value);
} else {
values.push_back(value);
}
}
return true;
}
bool InterbotixDriverXS::get_joint_states(
const std::string & name,
std::vector<float> * positions,
std::vector<float> * velocities,
std::vector<float> * effort)
{
read_joint_states();
std::lock_guard<std::mutex> guard(_mutex_js);
for (const auto & joint_name : get_group_info(name)->joint_names) {
// iterate through each joint in group, reading pos, vel, and eff
if (positions) {
positions->push_back(robot_positions.at(get_js_index(joint_name)));
}
if (velocities) {
velocities->push_back(robot_velocities.at(get_js_index(joint_name)));
}
if (effort) {
effort->push_back(robot_efforts.at(get_js_index(joint_name)));
}
}
return true;
}
bool InterbotixDriverXS::get_joint_states(
const std::string & name,
std::vector<double> * positions,
std::vector<double> * velocities,
std::vector<double> * effort)
{
read_joint_states();
std::lock_guard<std::mutex> guard(_mutex_js);
for (const auto & joint_name : get_group_info(name)->joint_names) {
// iterate through each joint in group, reading pos, vel, and eff
if (positions) {
positions->push_back(robot_positions.at(get_js_index(joint_name)));
}
if (velocities) {
velocities->push_back(robot_velocities.at(get_js_index(joint_name)));
}
if (effort) {
effort->push_back(robot_efforts.at(get_js_index(joint_name)));
}
}
return true;
}
bool InterbotixDriverXS::get_joint_state(
const std::string & name,
float * position,
float * velocity,
float * effort)
{
read_joint_states();
std::lock_guard<std::mutex> guard(_mutex_js);
// read pos, vel, and eff for specified joint
if (position) {
*position = robot_positions.at(get_js_index(name));
}
if (velocity) {
*velocity = robot_velocities.at(get_js_index(name));
}
if (effort) {
*effort = robot_efforts.at(get_js_index(name));
}
return true;
}
float InterbotixDriverXS::convert_linear_position_to_radian(
const std::string & name,
const float & linear_position)
{
float half_dist = linear_position / 2.0;
float arm_length = gripper_map[name].arm_length;
float horn_radius = gripper_map[name].horn_radius;
// (pi / 2) - acos(horn_rad^2 + (pos / 2)^2 - arm_length^2) / (2 * horn_rad * (pos / 2))
return 3.14159 / 2.0 - \
acos(
(pow(horn_radius, 2) + \
pow(half_dist, 2) - \
pow(arm_length, 2)) / (2 * horn_radius * half_dist));
}
float InterbotixDriverXS::convert_angular_position_to_linear(
const std::string & name,
const float & angular_position)
{
float arm_length = gripper_map[name].arm_length;
float horn_radius = gripper_map[name].horn_radius;
float a1 = horn_radius * sin(angular_position);
float c = sqrt(pow(horn_radius, 2) - pow(a1, 2));
float a2 = sqrt(pow(arm_length, 2) - pow(c, 2));
return a1 + a2;
}
bool InterbotixDriverXS::retrieve_motor_configs(
std::string filepath_motor_configs,
std::string filepath_mode_configs)
{
// read motor_configs param
try {
// try to load motor_configs yaml file
motor_configs = YAML::LoadFile(filepath_motor_configs.c_str());
} catch (YAML::BadFile & error) {
// if file is not found or a bad format, shut down
XSLOG_FATAL("Motor Config file was not found or has a bad format. Shutting down...");
XSLOG_FATAL("YAML Error: '%s'", error.what());
return false;
}
if (motor_configs.IsNull()) {
// if motor_configs is not found or empty, shut down
XSLOG_FATAL("Motor Config file was not found. Shutting down...");
return false;
}
// read mode_configs param
try {
// try to load mode_configs yaml file
mode_configs = YAML::LoadFile(filepath_mode_configs.c_str());
XSLOG_INFO(
"Loaded mode configs from '%s'.",
filepath_mode_configs.c_str());
} catch (YAML::BadFile & error) {
// if file is not found or a bad format, shut down
XSLOG_FATAL(
"Mode Config file was not found or has a bad format. Shutting down...");
XSLOG_FATAL(
"YAML Error: '%s'",
error.what());
return false;
}
if (mode_configs.IsNull()) {
// if mode_configs is not found or empty, use defaults
XSLOG_WARN("Mode Config file is empty. Will use defaults.");
}
// use specified or default port
port = motor_configs["port"].as<std::string>(DEFAULT_PORT);
if (mode_configs["port"]) {
port = mode_configs["port"].as<std::string>(DEFAULT_PORT);
}
// create all_motors node from 'motors'
YAML::Node all_motors = motor_configs["motors"];
for (
YAML::const_iterator motor_itr = all_motors.begin();
motor_itr != all_motors.end();
motor_itr++)
{
// iterate through each motor in all_motors node
// get motor name
std::string motor_name = motor_itr->first.as<std::string>();
// create single_motor node from the motor_name
YAML::Node single_motor = all_motors[motor_name];
// extract ID from node
uint8_t id = (uint8_t)single_motor["ID"].as<int32_t>();
// extract mech reduction from node
try {
float mech_red = (float)single_motor["Mech_Reduction"].as<float>();
js_mech_reduction_map[id] = mech_red;
XSLOG_DEBUG("Reading mech reduction, motor id: %i, red: %i", id, mech_red);
}
catch (const std::exception& e) {
XSLOG_ERROR("Could not read the Mech_Reduction field in the motor configs. Motor ID: %i.", id);
XSLOG_FATAL("YAML Error: '%s'", e.what());
return false;
}
// add the motor to the motor_map with it's ID, pos as the default opmode, vel as default
// profile
motor_map.insert({motor_name, {id, mode::POSITION, profile::VELOCITY}});
for (
YAML::const_iterator info_itr = single_motor.begin();
info_itr != single_motor.end();
info_itr++)
{
// iterate through the single_motor node
// save all registers that are not ID or Baud_Rate
std::string reg = info_itr->first.as<std::string>();
if (reg != "ID" && reg != "Baud_Rate" && reg != "Mech_Reduction") {
int32_t value = info_itr->second.as<int32_t>();
MotorRegVal motor_info = {id, reg, value};
motor_info_vec.push_back(motor_info);
}
}
}
// create all_grippers node from 'grippers'
YAML::Node all_grippers = motor_configs["grippers"];
for (
YAML::const_iterator gripper_itr = all_grippers.begin();
gripper_itr != all_grippers.end();
gripper_itr++)
{
// iterate through each gripper in all_grippers node
// get gripper name
std::string gripper_name = gripper_itr->first.as<std::string>();
// create single_gripper node from the gripper_name
YAML::Node single_gripper = all_grippers[gripper_name];
// initialize a Gripper struct to save the info about this gripper
Gripper gripper;
// load all info from the single_gripper node into the Griper struct, substituting the default
// values if not given the value
gripper.horn_radius = single_gripper["horn_radius"].as<float>(0.014);
gripper.arm_length = single_gripper["arm_length"].as<float>(0.024);
gripper.left_finger = single_gripper["left_finger"].as<std::string>("left_finger");
gripper.right_finger = single_gripper["right_finger"].as<std::string>("right_finger");
gripper_map.insert({gripper_name, gripper});
}
// create joint_order node from 'joint_order'
YAML::Node joint_order = motor_configs["joint_order"];
// create sleep_positions node from 'sleep_positions'
YAML::Node sleep_positions = motor_configs["sleep_positions"];
// create JointGroup struct for all_joints - contains all joints in robot
JointGroup all_joints;
all_joints.joint_num = (uint8_t) joint_order.size();
all_joints.mode = mode::POSITION;
all_joints.profile_type = profile::VELOCITY;
all_joints.profile_velocity = DEFAULT_PROF_VEL;
all_joints.profile_acceleration = DEFAULT_PROF_ACC;
for (size_t i{0}; i < joint_order.size(); i++) {
// iterate through each joint in joint_order list
// save each joint ID and name
std::string joint_name = joint_order[i].as<std::string>();
all_joints.joint_names.push_back(joint_name);
all_joints.joint_ids.push_back(motor_map[joint_name].motor_id);
// add this joint's index to the js_index_map
js_index_map.insert({joint_name, i});
// add any shadows
shadow_map.insert({joint_name, {joint_name}});
// add any sisters
sister_map.insert({joint_name, {joint_name}});
// add the sleep position of this joint, defaults to 0 if not specified
sleep_map.insert({joint_name, sleep_positions[i].as<float>(0)});
// if this joint is a gripper, add it to the gripper_name
if (gripper_map.count(joint_name) > 0) {
gripper_map[joint_name].js_index = i;
gripper_order.push_back(joint_name);
}
}
// append the left and right finger to the gripper_map
for (auto const & name : gripper_order) {
js_index_map.insert({gripper_map[name].left_finger, js_index_map.size()});
js_index_map.insert({gripper_map[name].right_finger, js_index_map.size()});
}
// all the all_joints JointGroup to the group_map
group_map.insert({"all", all_joints});
// create a pointer from the group_map's all group reference
all_ptr = &group_map.at("all");
// create all_shadows node from 'shadows'
YAML::Node all_shadows = motor_configs["shadows"];
for (
YAML::const_iterator master_itr = all_shadows.begin();
master_itr != all_shadows.end();
master_itr++)
{
// iterate through each shadow servo's master in all_shadows node
std::string master_name = master_itr->first.as<std::string>();
YAML::Node master = all_shadows[master_name];
YAML::Node shadow_list = master["shadow_list"];
for (size_t i{0}; i < shadow_list.size(); i++) {
shadow_map[master_name].push_back(shadow_list[i].as<std::string>());
}
}
// create all_sisters node from 'sisters'
YAML::Node all_sisters = motor_configs["sisters"];
for (
YAML::const_iterator sister_itr = all_sisters.begin();
sister_itr != all_sisters.end();
sister_itr++)
{
// iterate through each sister servo in all_sisters node
// save each 2-in-1 servo to the sister_map
std::string sister_one = sister_itr->first.as<std::string>();
std::string sister_two = sister_itr->second.as<std::string>();
sister_map[sister_one].push_back(sister_two);
sister_map[sister_two].push_back(sister_one);
}
// create all_groups node from 'groups'
YAML::Node all_groups = motor_configs["groups"];
for (
YAML::const_iterator group_itr = all_groups.begin();
group_itr != all_groups.end();
group_itr++)
{
// iterate through each sister servo in all_sisters node
// get the name of the group
std::string name = group_itr->first.as<std::string>();
// get the list of joints in the group from the all_group map
YAML::Node joint_list = all_groups[name];
// create a JointGroup for this group
JointGroup group;
// the number of joints in this group is the size of the list of joints
group.joint_num = (uint8_t) joint_list.size();
for (size_t i{0}; i < joint_list.size(); i++) {
// add each joint's name and id to the JointGroup
std::string joint_name = joint_list[i].as<std::string>();
group.joint_names.push_back(joint_name);
group.joint_ids.push_back(motor_map[joint_name].motor_id);
}