File size: 42,147 Bytes
bd5cb32 | 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 | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */
/*
Author(s): Zihan Chen, Anton Deguet
Created on: 2013-02-22
(C) Copyright 2013-2026 Johns Hopkins University (JHU), All Rights Reserved.
--- begin cisst license - do not edit ---
This software is provided "as is" under an open source license, with
no warranty. The complete license can be found in license.txt and
http://www.cisst.org/cisst/license.txt.
--- end cisst license ---
*/
#include <sawControllers/mtsPID.h>
#include <algorithm>
#include <cisstOSAbstraction/osaSleep.h>
#include <cisstMultiTask/mtsInterfaceRequired.h>
#include <cisstMultiTask/mtsInterfaceProvided.h>
#include <cisstParameterTypes/prmPositionJointSet.h>
CMN_IMPLEMENT_SERVICES_DERIVED_ONEARG(mtsPID, mtsTaskPeriodic, mtsTaskPeriodicConstructorArg);
mtsPID::mtsPID(const std::string & componentName, const double periodInSeconds):
mtsTaskPeriodic(componentName, periodInSeconds),
mConfigurationStateTable(100, "Configuration")
{
Init();
}
mtsPID::mtsPID(const mtsTaskPeriodicConstructorArg & arg):
mtsTaskPeriodic(arg),
mConfigurationStateTable(100, "Configuration")
{
Init();
}
void mtsPID::Init(void)
{
AddStateTable(&mConfigurationStateTable);
mConfigurationStateTable.SetAutomaticAdvance(false);
}
void mtsPID::SetupInterfaces(void)
{
// require RobotJointTorque interface
mtsInterfaceRequired * requiredInterface = AddInterfaceRequired("RobotJointTorqueInterface");
if (requiredInterface) {
requiredInterface->AddFunction("configuration_js", IO.configuration_js);
requiredInterface->AddFunction("configure_js", IO.configure_js);
requiredInterface->AddFunction("measured_js", IO.measured_js);
requiredInterface->AddFunction("servo_jf", IO.servo_jf);
// event handlers
requiredInterface->AddEventHandlerWrite(&mtsPID::ErrorEventHandler, this, "error");
}
// this should go in "write" state table
StateTable.AddData(m_requested_jf, "requested_jf");
// this should go in a "read" state table
StateTable.AddData(m_enabled, "enabled");
StateTable.AddData(m_joints_enabled, "joints_enabled");
StateTable.AddData(m_setpoint_v_used, "setpoint_v_used");
// measures are timestamped by the IO level
StateTable.AddData(m_enforce_position_limits, "enforce_position_limits");
m_measured_js.SetAutomaticTimestamp(false);
StateTable.AddData(m_measured_js, "measured_js");
StateTable.AddData(m_setpoint_js, "setpoint_js");
StateTable.AddData(m_error_state, "error_state");
// configuration state table with occasional start/advance
mConfigurationStateTable.AddData(m_configuration, "configuration");
mConfigurationStateTable.AddData(m_configuration_js, "configuration_js");
StateTable.AddData(m_measured_setpoint_check, "enable_measured_setpoint_check"); // that table advances automatically
mInterface = AddInterfaceProvided("Controller");
mInterface->AddMessageEvents();
if (mInterface) {
mInterface->AddCommandVoid(&mtsPID::reset_controller, this, "reset_controller");
mInterface->AddCommandWrite(&mtsPID::enable, this, "enable", m_enabled);
mInterface->AddCommandWrite(&mtsPID::enable_joints, this, "enable_joints", m_joints_enabled);
mInterface->AddCommandWrite(&mtsPID::use_setpoint_v, this, "use_setpoint_v", m_setpoint_v_used);
mInterface->AddCommandWrite(&mtsPID::EnableEffortMode, this, "EnableTorqueMode", m_effort_mode);
mInterface->AddCommandReadState(StateTable, m_enabled, "enabled");
mInterface->AddCommandReadState(StateTable, m_joints_enabled, "joints_enabled");
mInterface->AddCommandReadState(StateTable, m_setpoint_v_used, "setpoint_v_used");
// set goals
mInterface->AddCommandWrite(&mtsPID::servo_jp, this, "servo_jp", prmPositionJointSet());
mInterface->AddCommandWrite(&mtsPID::feed_forward_servo_jf, this, "feed_forward/servo_jf", prmForceTorqueJointSet());
mInterface->AddCommandWrite(&mtsPID::servo_jf, this, "servo_jf", prmForceTorqueJointSet());
// ROS compatible joint state
mInterface->AddCommandReadState(StateTable, m_measured_js, "measured_js");
mInterface->AddCommandReadState(StateTable, m_setpoint_js, "setpoint_js");
// disturbance
mInterface->AddCommandReadState(StateTable, m_error_state, "error_state/measured_js");
// Get joint configuration
mInterface->AddCommandReadState(mConfigurationStateTable, m_configuration, "configuration");
mInterface->AddCommandReadState(mConfigurationStateTable, m_configuration_js, "configuration_js");
// Set enforce position limits
mInterface->AddCommandWrite(&mtsPID::enforce_position_limits, this, "enforce_position_limits", m_enforce_position_limits);
mInterface->AddCommandReadState(StateTable, m_enforce_position_limits, "position_limits_enforced");
// measured vs setpoint check
mInterface->AddCommandWriteState(StateTable, m_measured_setpoint_check, "enable_measured_setpoint_check");
mInterface->AddCommandReadState(StateTable, m_measured_setpoint_check, "measured_setpoint_check_enabled");
mInterface->AddCommandWrite(&mtsPID::set_measured_setpoint_tolerance, this, "set_measured_setpoint_tolerance");
// Set joint configuration
mInterface->AddCommandWrite(&mtsPID::configure, this, "configure", m_configuration);
// Events
mInterface->AddEventWrite(Events.enabled, "enabled", m_enabled);
mInterface->AddEventWrite(Events.enabled_joints, "enabled_joints", vctBoolVec());
mInterface->AddEventWrite(Events.setpoint_v_used, "setpoint_v_used", m_setpoint_v_used);
mInterface->AddEventWrite(Events.position_limit, "position_limit", vctBoolVec());
}
}
void mtsPID::enforce_position_limits(const bool & enforce)
{
// make sure we have proper joint limits
if (enforce) {
// if any value is different from 0, we assume we have proper limits
if (m_configuration_js.PositionMin().Any() || m_configuration_js.PositionMax().Any()) {
m_enforce_position_limits = enforce;
return;
} else {
if (m_simulation_mode != prmSimulationType::KINEMATIC) {
mInterface->SendWarning(this->GetName() + ": unable to enforce position limits since the limits are not set properly");
}
CMN_LOG_CLASS_INIT_VERBOSE << this->GetName() << " enforce_position_limits: using configuration " << m_configuration_js << std::endl;
}
}
m_enforce_position_limits = false;
}
void mtsPID::Configure(const std::string & filename)
{
mConfigurationStateTable.Start();
CMN_LOG_CLASS_INIT_VERBOSE << this->GetName() << " Configure: using " << filename << std::endl;
try {
std::ifstream json_stream;
Json::Value json_config;
Json::Reader json_reader;
json_stream.open(filename.c_str());
if (!json_reader.parse(json_stream, json_config)) {
CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
<< ": failed to parse configuration file \""
<< filename << "\"\n"
<< json_reader.getFormattedErrorMessages();
exit(EXIT_FAILURE);
}
// id & version check
const std::string id = json_config["$id"].asString();
const std::string id_expected = "saw-controllers-pid.schema.json";
if (id != id_expected) {
CMN_LOG_CLASS_INIT_ERROR << "Configure: file " << filename
<< " has incorrect or missing $id, found \"" << id
<< "\", expected \"" << id_expected << "\"" << std::endl;
exit(EXIT_FAILURE);
}
const std::string version = json_config["$version"].asString();
if (version != "1") {
CMN_LOG_CLASS_INIT_ERROR << "Configure: file " << filename
<< " has incorrect or missing $version, found \"" << version
<< "\", expected \"6\"" << std::endl;
exit(EXIT_FAILURE);
}
CMN_LOG_CLASS_INIT_VERBOSE << "Configure: " << this->GetName()
<< " using file \"" << filename << "\"" << std::endl
<< "----> content of configuration file: " << std::endl
<< json_config << std::endl
<< "<----" << std::endl;
const auto jsonPID = json_config["pid"];
if (jsonPID.isNull()) {
CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
<< ": failed to find \"pid\" in configuration file \""
<< filename << "\"\n" << std::endl;
exit(EXIT_FAILURE);
}
cmnDataJSON<mtsPIDConfiguration>::DeSerializeText(m_configuration, jsonPID);
// post parsing checks
size_t index = 0;
for (const auto & c : m_configuration) {
if (c.index != index) {
CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
<< ": index " << c.index << " doesn't match the position "
<< index << " in configuration file \""
<< filename << "\"\n" << std::endl;
exit(EXIT_FAILURE);
}
++index;
if ((c.v_low_pass_cutoff <= 0.0) || (c.v_low_pass_cutoff > 1.0)) {
CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
<< ": velocity low pass filter cut off value for " << c.index
<< " must be in ]0, 1] range, found "
<< c.v_low_pass_cutoff << " in configuration file \""
<< filename << "\"\n" << std::endl;
exit(EXIT_FAILURE);
}
}
} catch (std::exception & e) {
CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName() << ": parsing file \""
<< filename << "\", got error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (...) {
CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName() << ": make sure the file \""
<< filename << "\" is in JSON format" << std::endl;
exit(EXIT_FAILURE);
}
m_number_of_joints = m_configuration.size();
if (m_number_of_joints < 1) {
CMN_LOG_CLASS_INIT_ERROR << this->GetName()
<< " Configure: invalid number of joints: "
<< m_number_of_joints << std::endl;
exit(EXIT_FAILURE);
}
// feedback
m_pid_setpoint_jf.ForceTorque().SetSize(m_number_of_joints, 0.0);
m_feed_forward_jf.ForceTorque().SetSize(m_number_of_joints, 0.0);
m_requested_jf.ForceTorque().SetSize(m_number_of_joints, 0.0);
// size all vectors
m_configuration_js.Name().resize(m_number_of_joints);
m_configuration_js.Type().SetSize(m_number_of_joints);
m_configuration_js.PositionMin().SetSize(m_number_of_joints, 0.0);
m_configuration_js.PositionMax().SetSize(m_number_of_joints, 0.0);
m_configuration_js.EffortMin().SetSize(m_number_of_joints, 0.0);
m_configuration_js.EffortMax().SetSize(m_number_of_joints, 0.0);
m_measured_js.Name().resize(m_number_of_joints);
m_measured_js.Position().SetSize(m_number_of_joints, 0.0);
m_measured_js.Velocity().SetSize(m_number_of_joints, 0.0);
m_measured_js.Effort().SetSize(m_number_of_joints, 0.0);
m_setpoint_js.Name().resize(m_number_of_joints);
m_setpoint_js.Position().SetSize(m_number_of_joints, 0.0);
m_setpoint_js.Velocity().SetSize(m_number_of_joints, 0.0);
m_setpoint_js.Effort().SetSize(m_number_of_joints, 0.0);
m_measured_js_previous.Position().SetSize(m_number_of_joints, 0.0);
m_measured_js_previous.Velocity().SetSize(m_number_of_joints, 0.0);
m_measured_js_previous.Effort().SetSize(m_number_of_joints, 0.0);
mPositionLimitFlag.SetSize(m_number_of_joints);
mPositionLimitFlag.SetAll(false);
mPositionLimitFlagPrevious.ForceAssign(mPositionLimitFlag);
m_joints_enabled.SetSize(m_number_of_joints);
m_joints_enabled.SetAll(true);
// errors
m_error_state.Name().resize(m_number_of_joints);
m_error_state.Position().SetSize(m_number_of_joints);
m_error_state.Velocity().SetSize(m_number_of_joints);
m_error_state.Effort().SetSize(m_number_of_joints); // disturbance
m_i_error.SetSize(m_number_of_joints);
// disturbance observer
m_disturbance_state.SetSize(m_number_of_joints);
m_disturbance_state.SetAll(0.0);
m_disturbance_input.SetSize(m_number_of_joints);
m_disturbance_input.SetAll(0.0);
reset_controller();
// default: 1 so there's no filtering
m_setpoint_filtered_v.SetSize(m_number_of_joints, 0.0);
m_setpoint_filtered_v_previous.SetSize(m_number_of_joints, 0.0);
// effort mode
m_effort_mode.SetSize(m_number_of_joints);
m_effort_mode.SetAll(false);
// tracking error
m_measured_setpoint_check = false;
m_measured_setpoint_error.SetSize(m_number_of_joints, false);
m_previous_measured_setpoint_error.ForceAssign(m_measured_setpoint_error);
// copy data from configuration, name and type
size_t index = 0;
for (const auto & c : m_configuration) {
m_configuration_js.Name().at(index) = c.name;
m_configuration_js.Type().at(index) = c.type;
m_measured_js.Name().at(index) = c.name;
m_setpoint_js.Name().at(index) = c.name;
m_error_state.Name().at(index) = c.name;
++index;
}
mConfigurationStateTable.Advance();
// now that we know the sizes of vectors, create interfaces
this->SetupInterfaces();
}
void mtsPID::Startup(void)
{
// get joint type from IO and check against values from PID config file
if (m_simulation_mode != prmSimulationType::KINEMATIC) {
mtsExecutionResult result;
prmConfigurationJoint io_configuration_js;
result = IO.configuration_js(io_configuration_js);
if (!result) {
CMN_LOG_CLASS_INIT_ERROR << this->GetName() << " Startup: Robot interface isn't connected properly, unable to get joint configuration. Function call returned: "
<< result << std::endl;
} else {
// check the types
for (size_t index = 0;
index < m_number_of_joints;
++index) {
if (io_configuration_js.Type().at(index) != m_configuration_js.Type().at(index)) {
std::string message = this->GetName() + " Startup: joint types from IO don't match types from configuration files for " + this->GetName();
CMN_LOG_CLASS_INIT_ERROR << message << std::endl
<< "From IO: " << io_configuration_js.Type() << std::endl
<< "From config: " << m_configuration_js.Type() << std::endl;
cmnThrow("PID::" + message);
}
}
// get the position min/max based on IO level. Provided
// from IO level based on max current and position to
// current scale
if ((io_configuration_js.PositionMin().size() != m_configuration_js.Name().size())
|| (io_configuration_js.PositionMax().size() != m_configuration_js.Name().size())) {
std::string message = this->GetName() + " Startup: min and max position vectors from IO don't have the correct size for " + this->GetName();
CMN_LOG_CLASS_INIT_ERROR << message << std::endl
<< "IO configuration position min: " << io_configuration_js.PositionMin() << std::endl
<< "IO configuration position max: " << io_configuration_js.PositionMax() << std::endl;
cmnThrow("PID::" + message);
} else {
m_configuration_js.PositionMin().ForceAssign(io_configuration_js.PositionMin());
m_configuration_js.PositionMax().ForceAssign(io_configuration_js.PositionMax());
CheckLowerUpper(m_configuration_js.PositionMin(), m_configuration_js.PositionMax(), "Startup, position");
}
// get the effort min/max based on IO level. Provided
// from IO level based on max current and effort to
// current scale
if ((io_configuration_js.EffortMin().size() != m_configuration_js.Name().size())
|| (io_configuration_js.EffortMax().size() != m_configuration_js.Name().size())) {
std::string message = this->GetName() + " Startup: min and max effort vectors from IO don't have the correct size for " + this->GetName();
CMN_LOG_CLASS_INIT_ERROR << message << std::endl
<< "IO configuration effort min: " << io_configuration_js.EffortMin() << std::endl
<< "IO configuration effort max: " << io_configuration_js.EffortMax() << std::endl;
cmnThrow("PID::" + message);
} else {
m_configuration_js.EffortMin().ForceAssign(io_configuration_js.EffortMin());
m_configuration_js.EffortMax().ForceAssign(io_configuration_js.EffortMax());
CheckLowerUpper(m_configuration_js.EffortMin(), m_configuration_js.EffortMax(), "Startup, effort");
}
// check that names are also set properly
if (io_configuration_js.Name().size() == m_configuration_js.Name().size()) {
if (io_configuration_js.Name() != m_configuration_js.Name()) {
std::string message = this->GetName() + " Startup: joint names from IO don't match names from configuration files for " + this->GetName();
CMN_LOG_CLASS_INIT_ERROR << message << std::endl
<< "From IO: " << cmnDataHumanReadable(io_configuration_js.Name())
<< std::endl
<< "From config: " << cmnDataHumanReadable(m_configuration_js.Name())
<< std::endl;
cmnThrow("PID::" + message);
}
} else if (io_configuration_js.Name().size() == 0) {
// IO doesn't have proper names, let's configure them
IO.configure_js(m_configuration_js);
}
CMN_LOG_CLASS_INIT_VERBOSE << "Startup: configuration_js:" << std::endl
<< m_configuration_js << std::endl;
}
}
}
void mtsPID::Run(void)
{
// first process events from IO (likely errors)
ProcessQueuedEvents();
// get data from IO if not in simulated mode
get_IO_data();
// now that we have recent data, deal with user commands
ProcessQueuedCommands();
// initialize variables
bool anyTrackingError = false;
bool newTrackingError = false;
// loop on all joints
vctBoolVec::const_iterator enabled = m_joints_enabled.begin();
vctDoubleVec::const_iterator measured_p = m_measured_js.Position().begin();
vctDoubleVec::const_iterator measured_v = m_measured_js.Velocity().begin();
vctDoubleVec::iterator setpoint_p = m_setpoint_js.Position().begin();
vctDoubleVec::iterator setpoint_f = m_setpoint_js.Effort().begin();
vctBoolVec::const_iterator effortMode = m_effort_mode.begin();
vctDoubleVec::const_iterator effortUserCommand = m_requested_jf.ForceTorque().begin();
vctDoubleVec::iterator p_error = m_error_state.Position().begin();
vctDoubleVec::iterator v_error = m_error_state.Velocity().begin();
vctBoolVec::iterator limitFlag = mPositionLimitFlag.begin();
vctBoolVec::iterator trackingErrorFlag = m_measured_setpoint_error.begin();
vctBoolVec::iterator previousTrackingErrorFlag = m_previous_measured_setpoint_error.begin();
vctDoubleVec::iterator i_error = m_i_error.begin();
vctDoubleVec::iterator disturbance = m_error_state.Effort().begin();
vctDoubleVec::iterator disturbance_state = m_disturbance_state.begin();
vctDoubleVec::iterator disturbance_input = m_disturbance_input.begin();
auto c = m_configuration.cbegin();
vctDoubleVec::const_iterator feed_forward = m_feed_forward_jf.ForceTorque().begin();
vctDoubleVec::iterator filtered_setpoint_v = m_setpoint_filtered_v.begin();
vctDoubleVec::iterator filtered_setpoint_v_previous = m_setpoint_filtered_v_previous.begin();
vctDoubleVec::const_iterator effortLowerLimit = m_configuration_js.EffortMin().begin();
vctDoubleVec::const_iterator effortUpperLimit = m_configuration_js.EffortMax().begin();
// check if the setpoint has velocities
vctDoubleVec::iterator setpoint_v;
if (m_has_setpoint_v) {
setpoint_v = m_setpoint_js.Velocity().begin();
}
CMN_ASSERT(m_joints_enabled.size() == m_number_of_joints);
CMN_ASSERT(m_measured_js.Position().size() == m_number_of_joints);
CMN_ASSERT(m_measured_js.Velocity().size() == m_number_of_joints);
CMN_ASSERT(m_setpoint_js.Position().size() == m_number_of_joints);
CMN_ASSERT(m_setpoint_js.Effort().size() == m_number_of_joints);
CMN_ASSERT(m_setpoint_filtered_v.size() == m_number_of_joints);
CMN_ASSERT(m_setpoint_filtered_v_previous.size() == m_number_of_joints);
CMN_ASSERT(m_effort_mode.size() == m_number_of_joints);
CMN_ASSERT(m_requested_jf.ForceTorque().size() == m_number_of_joints);
CMN_ASSERT(m_configuration.size() == m_number_of_joints);
CMN_ASSERT(mPositionLimitFlag.size() == m_number_of_joints);
CMN_ASSERT(m_measured_setpoint_error.size() == m_number_of_joints);
CMN_ASSERT(m_previous_measured_setpoint_error.size() == m_number_of_joints);
CMN_ASSERT(m_i_error.size() == m_number_of_joints);
CMN_ASSERT(m_error_state.Effort().size() == m_number_of_joints);
CMN_ASSERT(m_disturbance_state.size() == m_number_of_joints);
CMN_ASSERT(m_configuration.size() == m_number_of_joints);
CMN_ASSERT(m_configuration_js.EffortMin().size() == m_number_of_joints);
CMN_ASSERT(m_configuration_js.EffortMax().size() == m_number_of_joints);
// loop on all joints using iterators
for (size_t i = 0;
i < m_number_of_joints;
++i,
// make sure you increment all iterators declared above!
++enabled,
++measured_p,
++measured_v,
++setpoint_p,
++setpoint_f,
++effortMode,
++effortUserCommand,
++p_error,
++v_error,
++limitFlag,
++trackingErrorFlag,
++previousTrackingErrorFlag,
++i_error,
++disturbance,
++disturbance_state,
++disturbance_input,
++c,
++feed_forward,
++filtered_setpoint_v,
++filtered_setpoint_v_previous,
++effortLowerLimit,
++effortUpperLimit
) {
// first check if the controller and this joint is enabled
if (!m_enabled || !(*enabled)) {
*setpoint_f = 0.0;
*disturbance_input = 0.0;
*setpoint_p = *measured_p;
} else {
// the PID controller is enabled and this joint is actively controlled
// check the mode, i.e. position or effort pass-through
if (*effortMode) {
*setpoint_f = *effortUserCommand + *feed_forward;
*setpoint_p = *measured_p;
} else {
// PID mode
*p_error = *setpoint_p - *measured_p;
// deadband. With p_deadband_outer enabled, smoothly ramp the
// effective error from zero at the inner edge to the regular
// deadband response at the outer edge. This avoids an abrupt
// change in closed-loop stiffness around quantized encoder values.
const double error_sign = (*p_error >= 0.0) ? 1.0 : -1.0;
const double error_magnitude = fabs(*p_error);
const double outer_deadband = std::max(c->p_deadband_outer,
c->p_deadband);
bool in_deadband = (error_magnitude < c->p_deadband);
if (in_deadband) {
*p_error = 0.0;
} else if (outer_deadband > c->p_deadband
&& error_magnitude < outer_deadband) {
const double x = (error_magnitude - c->p_deadband)
/ (outer_deadband - c->p_deadband);
const double smoothstep = x * x * (3.0 - 2.0 * x);
*p_error = error_sign
* (error_magnitude - c->p_deadband) * smoothstep;
} else {
*p_error = error_sign
* (error_magnitude - c->p_deadband);
}
// check for tracking errors
if (m_measured_setpoint_check) {
double errorAbsolute = fabs(*p_error);
// trigger error if the error is too high
// AND the last request was not outside joint limit
if ((errorAbsolute > c->p_measured_setpoint_tolerance) && !(*limitFlag)) {
anyTrackingError = true;
*trackingErrorFlag = true;
if (*trackingErrorFlag != *previousTrackingErrorFlag) {
newTrackingError = true;
}
} else {
*trackingErrorFlag = false;
}
*previousTrackingErrorFlag = *trackingErrorFlag;
} // end of tracking error
// compute error derivative
*v_error = 0.0;
if (!in_deadband) {
double _setpoint_v = 0.0;
if (m_has_setpoint_v && m_setpoint_v_used) {
// apply filter on setpoint_v only
*filtered_setpoint_v = (1.0 - c->v_low_pass_cutoff) * *filtered_setpoint_v_previous + c->v_low_pass_cutoff * *setpoint_v;
_setpoint_v = *filtered_setpoint_v;
*filtered_setpoint_v_previous = *filtered_setpoint_v;
}
*v_error = _setpoint_v - (*measured_v);
}
// compute error integral
*i_error *= c->i_forget_rate;
*i_error += *p_error;
if (*i_error > c->i_limit) {
*i_error = c->i_limit;
} else if (*i_error < -c->i_limit) {
*i_error = -c->i_limit;
}
// compute disturbance observer before setpoint_f is changed
if (c->use_disturbance_observer) {
const double d_t = this->GetPeriodicity();
const double dis_tmp = *disturbance_input
+ c->nominal_mass * c->disturbance_cutoff * *measured_v;
*disturbance_state += (dis_tmp - *disturbance_state)
* c->disturbance_cutoff * d_t;
*disturbance = *disturbance_state
- c->nominal_mass * c->disturbance_cutoff * *measured_v;
*setpoint_f = *disturbance;
} else {
*disturbance = 0.0;
*setpoint_f = 0.0;
}
// compute PID effort
*setpoint_f +=
c->p_gain * (*p_error) + c->d_gain * (*v_error) + c->i_gain * (*i_error);
// cap with max PID effort, not applying to effort specified by users
if (c->pid_max_output >= 0.0) {
*setpoint_f = std::clamp(*setpoint_f, -c->pid_max_output, c->pid_max_output);
}
*disturbance_input = *setpoint_f;
// add constant offsets in PID mode only and after non-linear scaling
*setpoint_f += c->offset;
// add feedForward
*setpoint_f += *feed_forward;
} // end of PID mode
// apply effort limits if needed
if (*effortLowerLimit != *effortUpperLimit) {
*setpoint_f = std::clamp(*setpoint_f, *effortLowerLimit, *effortUpperLimit);
*disturbance_input = std::clamp(*disturbance_input, *effortLowerLimit, *effortUpperLimit);
}
} // end of enabled
// increment setpoint_v if it's used
if (m_has_setpoint_v) {
++setpoint_v;
}
}
// report errors (tracking)
if (m_measured_setpoint_check && anyTrackingError) {
this->enable(false);
if (newTrackingError) {
std::string message = this->GetName() + ": tracking error, mask (1 for error): ";
message.append(m_measured_setpoint_error.ToString());
mInterface->SendError(message);
vctDoubleVec temp(m_number_of_joints);
for (size_t index = 0; index < m_number_of_joints; ++index) {
temp.at(index) = m_configuration.at(index).p_measured_setpoint_tolerance;
}
CMN_LOG_CLASS_RUN_ERROR << message << std::endl
<< "errors: " << m_error_state.Position() << std::endl
<< "tolerances: " << temp << std::endl
<< "measured: " << m_measured_js.Position() << std::endl
<< "setpoint: " << m_setpoint_js.Position() << std::endl;
}
}
// make sure we apply efforts only if enabled
if (m_enabled) {
servo_jf_local(m_setpoint_js.Effort());
}
// for simulated mode
if (m_simulation_mode == prmSimulationType::KINEMATIC) {
m_measured_js.SetValid(true);
m_measured_js.Position().Assign(m_setpoint_js.Position());
m_measured_js.SetTimestamp(StateTable.GetTic());
}
}
void mtsPID::Cleanup(void)
{
// cleanup
m_setpoint_js.Effort().Zeros();
servo_jf_local(m_setpoint_js.Effort());
}
void mtsPID::set_simulation_mode(const prmSimulationType & mode)
{
m_simulation_mode = mode;
switch (mode) {
case prmSimulationType::NONE:
break;
case prmSimulationType::KINEMATIC:
case prmSimulationType::IO:
// in simulation mode, we don't need IO
RemoveInterfaceRequired("RobotJointTorqueInterface");
break;
default:
cmnThrow("mtsPID::set_simulation_mode received unsupported mode");
}
}
void mtsPID::configure(const mtsPIDConfiguration & configuration)
{
if (SizeMismatch(configuration.size(), "configure")) {
return;
}
mConfigurationStateTable.Start();
m_configuration = configuration;
mConfigurationStateTable.Advance();
}
void mtsPID::reset_controller(void)
{
CMN_LOG_CLASS_RUN_VERBOSE << this->GetName() << " reset_controller" << std::endl;
m_error_state.Position().SetAll(0.0);
m_error_state.Velocity().SetAll(0.0);
m_error_state.Effort().SetAll(0.0); // disturbance
m_i_error.SetAll(0.0);
this->enable(false);
}
void mtsPID::servo_jp(const prmPositionJointSet & command)
{
// set position within limits
if (SizeMismatch(command.Goal().size(), "servo_jp")) {
return;
}
m_setpoint_js.Position().Assign(command.Goal());
m_command_time = command.Timestamp(); // m_setpoint_js timestamp is set by this class so can't use it later
if (m_enforce_position_limits) {
bool limitReached = false;
vctDoubleVec::const_iterator upper = m_configuration_js.PositionMax().begin();
vctDoubleVec::const_iterator lower = m_configuration_js.PositionMin().begin();
vctBoolVec::iterator flags = mPositionLimitFlag.begin();
vctDoubleVec::iterator desired = m_setpoint_js.Position().begin();
const vctDoubleVec::iterator end = m_setpoint_js.Position().end();
for (; desired != end; ++desired, ++upper, ++lower, ++flags) {
if (*desired > *upper) {
limitReached = true;
*desired = *upper;
*flags = true;
} else if (*desired < *lower) {
limitReached = true;
*desired = *lower;
*flags = true;
} else {
*flags = false;
}
}
if (limitReached) {
if (mPositionLimitFlagPrevious.NotEqual(mPositionLimitFlag)) {
mPositionLimitFlagPrevious.Assign(mPositionLimitFlag);
Events.position_limit(mPositionLimitFlag);
std::string message = this->GetName() + ": position limit, mask (1 for limit): ";
message.append(mPositionLimitFlag.ToString());
mInterface->SendWarning(message);
CMN_LOG_CLASS_RUN_WARNING << message
<< ", \n requested: " << m_setpoint_js.Position()
<< ", \n lower limits: " << m_configuration_js.PositionMin()
<< ", \n upper limits: " << m_configuration_js.PositionMax()
<< std::endl;
}
}
}
// set and resize setpoint_v as needed
m_has_setpoint_v = false;
if (command.Velocity().size() > 0) {
if (SizeMismatch(command.Velocity().size(), "servo_jp")) {
m_setpoint_js.Velocity().Zeros();
return;
}
m_has_setpoint_v = true;
m_setpoint_js.Velocity().Assign(command.Velocity());
} else {
m_setpoint_js.Velocity().Zeros();
}
}
void mtsPID::feed_forward_servo_jf(const prmForceTorqueJointSet & feedForward)
{
if (SizeMismatch(feedForward.ForceTorque().size(), "feed_forward/servo_jf")) {
return;
}
m_feed_forward_jf.ForceTorque().Assign(feedForward.ForceTorque());
}
void mtsPID::servo_jf(const prmForceTorqueJointSet & command)
{
if (SizeMismatch(command.ForceTorque().size(), "servo_jf")) {
return;
}
m_requested_jf.ForceTorque().Assign(command.ForceTorque());
}
void mtsPID::enable(const bool & enable)
{
if (enable == m_enabled) {
// trigger enabled
Events.enabled(m_enabled);
return;
}
m_enabled = enable;
// set effort to 0
m_setpoint_js.Effort().Zeros();
servo_jf_local(m_setpoint_js.Effort());
// reset error flags
if (enable) {
m_previous_measured_setpoint_error.SetAll(false);
m_measured_setpoint_error.SetAll(false);
mPositionLimitFlagPrevious.SetAll(false);
mPositionLimitFlag.SetAll(false);
m_previous_command_time = 0.0;
m_feed_forward_jf.ForceTorque().Zeros();
m_has_setpoint_v = false;
m_setpoint_filtered_v_previous.Zeros();
// set valid flags
m_error_state.SetValid(true);
} else {
m_error_state.SetValid(false);
}
// trigger Enabled
Events.enabled(m_enabled);
}
void mtsPID::enable_joints(const vctBoolVec & enable)
{
if (SizeMismatch(enable.size(), "enable_joints")) {
return;
}
m_joints_enabled.Assign(enable);
Events.enabled_joints(enable);
}
void mtsPID::use_setpoint_v(const bool & use)
{
m_setpoint_v_used = use;
std::cerr << "used: " << use << std::endl;
Events.setpoint_v_used(m_setpoint_v_used);
if (m_setpoint_v_used) {
m_setpoint_filtered_v_previous.Zeros();
}
}
void mtsPID::EnableEffortMode(const vctBoolVec & enable)
{
if (SizeMismatch(enable.size(), "EnableEffortMode")) {
return;
}
// save preference
m_effort_mode.Assign(enable);
// reset effort to 0
m_setpoint_js.Effort().Zeros();
m_feed_forward_jf.ForceTorque().Zeros();
}
void mtsPID::get_IO_data(void)
{
// get data from IO if not in simulated mode. When is simulation
// mode, position come from the user/client and is found in
// m_setpoint_js
if (m_simulation_mode == prmSimulationType::KINEMATIC) {
// check that position is not too old
if ((StateTable.GetTic() - m_command_time) > 20.0 * cmn_ms) {
m_measured_js.Velocity().Zeros();
} else {
// evaluate velocity based on positions sent by arm/client
const double dt = m_command_time - m_previous_command_time;
if (dt > 0) {
vctDoubleVec::const_iterator currentPosition = m_setpoint_js.Position().begin();
vctDoubleVec::const_iterator previousPosition = m_measured_js_previous.Position().begin();
vctBoolVec::const_iterator effortMode = m_effort_mode.begin();
vctDoubleVec::iterator velocity;
const vctDoubleVec::iterator end = m_measured_js.Velocity().end();
for (velocity = m_measured_js.Velocity().begin();
velocity != end;
++currentPosition,
++previousPosition,
++effortMode,
++velocity) {
if (*effortMode) {
*velocity = 0.0;
} else {
*velocity = (*currentPosition - *previousPosition) / dt;
}
}
}
}
// timestamp using last know position
m_measured_js_previous = m_setpoint_js;
m_previous_command_time = m_command_time;
}
// talking to actual robot
else {
IO.measured_js(m_measured_js);
// velocities are not provided by the robot
if (m_measured_js.Velocity().size() == 0) {
// IO level doesn't provide velocities
// so estimate it from measured positions. this
// estimation is very simple and likely noisy so try to
// avoid this case as much as possible
const double dt = m_measured_js.Timestamp() - m_measured_js_previous.Timestamp();
if (dt > 0) {
vctDoubleVec::const_iterator currentPosition = m_measured_js.Position().begin();
vctDoubleVec::const_iterator previousPosition = m_measured_js_previous.Position().begin();
vctDoubleVec::iterator velocity;
const vctDoubleVec::iterator end = m_measured_js.Velocity().end();
for (velocity = m_measured_js.Velocity().begin();
velocity != end;
++currentPosition,
++previousPosition,
++velocity) {
*velocity = (*currentPosition - *previousPosition) / dt;
}
}
} // end of software base velocity estimation based on
// measured positions
// save previous position with timestamp
m_measured_js_previous = m_measured_js;
}
}
void mtsPID::servo_jf_local(const vctDoubleVec & effort)
{
if (m_simulation_mode != prmSimulationType::KINEMATIC) {
m_pid_setpoint_jf.ForceTorque().Assign(effort);
IO.servo_jf(m_pid_setpoint_jf);
}
}
void mtsPID::set_measured_setpoint_tolerance(const vctDoubleVec & tolerances)
{
if (tolerances.size() == m_number_of_joints) {
for (size_t index = 0; index < m_number_of_joints; ++index) {
m_configuration.at(index).p_measured_setpoint_tolerance = tolerances.at(index);
}
} else {
std::string message = this->GetName() + ": incorrect vector size for set_measured_setpoint_tolerance";
cmnThrow(message);
}
}
void mtsPID::ErrorEventHandler(const mtsMessage & message)
{
if (this->m_enabled) {
this->enable(false);
mInterface->SendError(this->GetName() + ": received [" + message.Message + "]");
} else {
mInterface->SendStatus(this->GetName() + ": received [" + message.Message + "]");
}
}
bool mtsPID::SizeMismatch(const size_t size, const std::string & methodName)
{
if (size != m_number_of_joints) {
CMN_LOG_CLASS_INIT_ERROR << this->GetName() << " " << methodName << ": size mismatch, expected "
<< m_number_of_joints << ", received "
<< size << std::endl;
this->enable(false);
mInterface->SendError(this->GetName() + "::" + methodName + ": size mismatch (check cisstLog)");
return true;
}
return false;
}
void mtsPID::CheckLowerUpper(const vctDoubleVec & lower, const vctDoubleVec & upper,
const std::string & methodName)
{
// it only makes sense to check if there's at least one limit set
if (lower.Any() || upper.Any()) {
if (lower.ElementwiseGreaterOrEqual(upper).Any()) {
CMN_LOG_CLASS_INIT_ERROR << this->GetName() << " " << methodName
<< ": lower limit greater or equal to upper limit " << std::endl
<< " - lower: " << lower << std::endl
<< " - upper: " << upper << std::endl;
mInterface->SendWarning(this->GetName() + "::" + methodName + ": lower limit greater or equal to upper limit");
}
}
}
|