APIs, concepts, guides, and more
SampleAppsHelper.h
Attention
See the following Concept pages for a detailed explanation of this sample: Helper Functions.
Warning
This is a sample program to assist in the integration of the RMP motion controller with your application. It may not contain all of the logic and safety features that your application requires. We recommend that you wire an external hardware emergency stop (e-stop) button for safety when using our code sample apps. Doing so will help ensure the safety of you and those around you and will prevent potential injury or damage.

The sample apps assume that the system (network, axes, I/O) are configured prior to running the code featured in the sample app. See the Configuration page for more information.
#ifndef SAMPLE_APPS_HELPER
#define SAMPLE_APPS_HELPER
#include "rsi.h" // Import our RapidCode Library.
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace RSI::RapidCode; // Import the RapidCode namespace
{
// If you want to use hardware, then follow the instructions in the README before setting this to true.
static constexpr bool USE_HARDWARE = false;
// Motion Controller Creation Parameters
static constexpr char RMP_PATH[] = "";
static constexpr char NIC_PRIMARY[] = "";
static constexpr char NODE_NAME[] = "";
static constexpr int CPU_AFFINITY = 0;
// Controller Initial Object Counts (Sample Apps may change these counts as needed)
static constexpr int AXIS_COUNT = 2;
static constexpr int MOTION_COUNT = AXIS_COUNT;
static constexpr int USER_LIMIT_COUNT = 0;
static constexpr int MATH_BLOCK_COUNT = 0;
static constexpr int RECORDER_COUNT = 0;
// Axis Configuration Constants
// First (x) Axis configuration parameters
static constexpr int AXIS_X_USER_UNITS = 1;
static constexpr int AXIS_X_INDEX = 0;
// Second (y) Axis configuration parameters
static constexpr int AXIS_Y_USER_UNITS = 1;
static constexpr int AXIS_Y_INDEX = 1;
static void ConfigureHardwareAxes(MotionController *controller, std::vector<Axis *> axes)
{
// If you have configured your axes using rsiconfig, RapidSetup, or RapidSetupX then you can comment out this error and return.
// IMPLEMENTATION REQUIRED: Configure the axes for hardware
throw std::runtime_error("You must implement the ConfigureHardwareAxes function (found in /include/SampleAppsHelper.h) to use hardware.");
// Simple Axis Configuration Example:
// (Look at the Axis: Configuration section in the RapidCode API Reference for more advanced configurations)
/*
axes[0]->UserUnitsSet(USER_UNITS);
axes[0]->PositionSet(0);
axes[0]->ErrorLimitTriggerValueSet(0.1 * USER_UNITS);
axes[0]->ErrorLimitActionSet(RSIAction::RSIActionABORT);
axes[0]->Abort();
axes[0]->ClearFaults();
*/
}
};
{
#if _WIN32
{
// Create a controller with using defined parameters
return params;
}
#elif __linux__
{
return params;
}
#endif
static void CheckErrors(RapidCodeObject *rsiObject)
{
bool hasErrors = false;
std::string errorStrings("");
while (rsiObject->ErrorLogCountGet() > 0)
{
const RsiError *err = rsiObject->ErrorLogGet();
errorStrings += err->what();
errorStrings += "\n";
if (!err->isWarning)
{
hasErrors = true;
}
}
if (hasErrors)
{
throw std::runtime_error(errorStrings.c_str());
}
}
static void StartTheNetwork(MotionController *controller)
{
// Initialize the Network
if (controller->NetworkStateGet() != RSINetworkState::RSINetworkStateOPERATIONAL) // Check if network is started already.
{
std::cout << "Starting Network.." << std::endl;
controller->NetworkStart(); // If not. Initialize The Network. (This can also be done from RapidSetup Tool)
}
if (controller->NetworkStateGet() != RSINetworkState::RSINetworkStateOPERATIONAL) // Check if network is started again.
{
int messagesToRead = controller->NetworkLogMessageCountGet(); // Some kind of error starting the network, read the network log messages
for (int i = 0; i < messagesToRead; i++)
{
std::cout << controller->NetworkLogMessageGet(i) << std::endl; // Print all the messages to help figure out the problem
}
throw std::runtime_error("Expected OPERATIONAL state but the network did not get there.");
}
else // Else, of network is operational.
{
std::cout << "Network Started" << std::endl << std::endl;
}
}
static void ShutdownTheNetwork(MotionController *controller)
{
// Check if the network is already shutdown
if (controller->NetworkStateGet() == RSINetworkState::RSINetworkStateUNINITIALIZED ||
controller->NetworkStateGet() == RSINetworkState::RSINetworkStateSHUTDOWN)
{
return;
}
// Shutdown the network
std::cout << "Shutting down the network.." << std::endl;
controller->NetworkShutdown();
if (controller->NetworkStateGet() != RSINetworkState::RSINetworkStateUNINITIALIZED &&
controller->NetworkStateGet() != RSINetworkState::RSINetworkStateSHUTDOWN) // Check if the network is shutdown.
{
int messagesToRead = controller->NetworkLogMessageCountGet(); // Some kind of error shutting down the network, read the network log messages
for (int i = 0; i < messagesToRead; i++)
{
std::cout << controller->NetworkLogMessageGet(i) << std::endl; // Print all the messages to help figure out the problem
}
throw std::runtime_error("Expected SHUTDOWN state but the network did not get there.");
}
else // Else, of network is shutdown.
{
std::cout << "Network Shutdown" << std::endl << std::endl;
}
}
static void ConfigurePhantomAxis(MotionController *controller, int axisNumber)
{
// Configure the specified axis as a phantom axis
Axis *axis = controller->AxisGet(axisNumber); // Initialize Axis class
CheckErrors(axis); // [Helper Function] Check that the axis has been initialized correctly
// These limits are not meaningful for a Phantom Axis (e.g., a phantom axis has no actual position so a position error trigger is not necessary)
// Therefore, you must set all of their actions to "NONE".
axis->PositionSet(0); // Set the position to 0
axis->ErrorLimitActionSet(RSIAction::RSIActionNONE); // Set Error Limit Action.
axis->AmpFaultActionSet(RSIAction::RSIActionNONE); // Set Amp Fault Action.
axis->AmpFaultTriggerStateSet(1); // Set Amp Fault Trigger State.
axis->HardwareNegLimitActionSet(RSIAction::RSIActionNONE); // Set Hardware Negative Limit Action.
axis->HardwarePosLimitActionSet(RSIAction::RSIActionNONE); // Set Hardware Positive Limit Action.
axis->SoftwareNegLimitActionSet(RSIAction::RSIActionNONE); // Set Software Negative Limit Action.
axis->SoftwarePosLimitActionSet(RSIAction::RSIActionNONE); // Set Software Positive Limit Action.
axis->HomeActionSet(RSIAction::RSIActionNONE); // Set Home Action.
const double positionToleranceMax =
std::numeric_limits<double>::max() /
10.0; // Reduce from max slightly, so XML to string serialization and deserialization works without throwing System.OverflowException
axis->PositionToleranceCoarseSet(positionToleranceMax); // Set Settling Coarse Position Tolerance to max value
axis->PositionToleranceFineSet(positionToleranceMax
); // Set Settling Fine Position Tolerance to max value (so Phantom axis will get immediate MotionDone when target is reached)
axis->MotorTypeSet(RSIMotorType::RSIMotorTypePHANTOM); // Set the MotorType to phantom
}
static void SetupController(MotionController *controller)
{
// Set the axis and motion counts
// Get the axis objects and check them for errors
CheckErrors(axisX);
CheckErrors(axisY);
// Check if we are using hardware or phantom axes
{
SampleAppsConfig::ConfigureHardwareAxes(controller, {axisX, axisY});
}
else
{
// Set the user units
// Configure them as phantoms
}
// Clear Faults
axisX->ClearFaults();
axisY->ClearFaults();
// Start or shutdown the network depending on the configuration
{
StartTheNetwork(controller);
}
else
{
if (controller->NetworkStateGet() != RSINetworkState::RSINetworkStateUNINITIALIZED &&
controller->NetworkStateGet() != RSINetworkState::RSINetworkStateSHUTDOWN)
{
std::cout << "The Sample Apps are configured to use Phantom Axes, but the network is not in the UNINITIALIZED or SHUTDOWN state.\n";
std::cout << "If you intended to run with hardware, then follow the steps in README.md and /include/SampleAppsHelper.h\n";
}
ShutdownTheNetwork(controller);
}
}
{
ShutdownTheNetwork(controller);
controller->Reset(); // Reset the controller to ensure it is in a known state.
StartTheNetwork(controller);
}
static void ClearControllerCounts(MotionController *controller)
{
// Clear the counts
controller->AxisCountSet(0);
controller->MotionCountSet(0);
controller->UserLimitCountSet(0);
}
static void SetupControllerForPhantoms(MotionController *controller, int axisCount, std::vector<int> axisNums)
{
ShutdownTheNetwork(controller);
ClearControllerCounts(controller);
controller->AxisCountSet(axisCount);
for (auto axisNum : axisNums)
{
ConfigurePhantomAxis(controller, axisNum);
}
}
static void PrintHeader(std::string sampleAppName)
{
std::cout << "----------------------------------------------------------------------------------------------------\n";
std::cout << "Running " << sampleAppName << " Sample App\n";
std::cout << "----------------------------------------------------------------------------------------------------\n" << std::endl;
}
static void PrintFooter(std::string sampleAppName, int exitCode)
{
std::cout << "\n----------------------------------------------------------------------------------------------------\n";
if (exitCode == 0)
{
std::cout << sampleAppName << " Sample App Completed Successfully\n";
}
else
{
std::cout << sampleAppName << " Sample App Failed with Exit Code: " << exitCode << "\n";
}
std::cout << "----------------------------------------------------------------------------------------------------\n" << std::endl;
}
} // namespace SampleAppsHelper
#endif // SAMPLE_APPS_HELPER
void HardwareNegLimitActionSet(RSIAction action)
Set the action that will occur when the Hardware Negative Limit Event triggers.
void HardwarePosLimitActionSet(RSIAction action)
Set the action that will occur when the Hardware Positive Limit Event triggers.
void PositionToleranceCoarseSet(double tolerance)
Set the Coarse Position Tolerance for Axis settling.
void SoftwareNegLimitActionSet(RSIAction action)
Set the action that will occur when the Software Negative Limit Event triggers.
void UserUnitsSet(double countsPerUserUnit)
Sets the number of counts per User Unit.
void AmpFaultActionSet(RSIAction action)
Set the Amp Fault action.
void AmpFaultTriggerStateSet(bool state)
Set the trigger state of the Amp Fault input.
void HomeActionSet(RSIAction action)
Set the action that will occur when the Home Event triggers.
void PositionToleranceFineSet(double tolerance)
Set the Fine Position Tolerance for Axis settling.
void ErrorLimitActionSet(RSIAction action)
Set the action that will occur when the Error Limit Event triggers.
void MotorTypeSet(RSIMotorType type)
Set the motor type.
void PositionSet(double position)
Set the Command and Actual positions.
void SoftwarePosLimitActionSet(RSIAction action)
Set the action that will occur when the Software Positive Limit Event triggers.
Represents a single axis of motion control. This class provides an interface for commanding motion,...
Definition rsi.h:5513
Axis * AxisGet(int32_t axisNumber)
AxisGet returns a pointer to an Axis object and initializes its internals.
RSINetworkState NetworkStateGet()
void MathBlockCountSet(int32_t mathBlockCount)
Set the number of processed MathBlocks in the MotionController.
void Reset()
Reset the controller which stops and restarts the RMP firmware.
void MotionCountSet(int32_t motionCount)
Set the number of processed Motion Supervisors in the controller.
const char *const NetworkLogMessageGet(int32_t messageIndex)
void RecorderCountSet(int32_t recorderCount)
Set the number of processed Recorders in the controller.
void UserLimitCountSet(int32_t userLimitCount)
Set the number of processed UserLimits in the MotionController.
void AxisCountSet(int32_t axisCount)
Set the number of allocated and processed axes in the controller.
Represents the RMP soft motion controller. This class provides an interface to general controller con...
Definition rsi.h:794
void NetworkShutdown()
Shutdown the network. For EtherCAT, this will kill the RMPNetwork process.
void NetworkStart()
Start the network with RSINetworkStartupMethodNORMAL.
void ClearFaults()
Clear all faults for an Axis or MultiAxis.
const RsiError *const ErrorLogGet()
Get the next RsiError in the log.
int32_t ErrorLogCountGet()
Get the number of software errors in the error log.
The RapidCode base class. All non-error objects are derived from this class.
Definition rsi.h:178
Represents the error details thrown as an exception by all RapidCode classes. This class contains an ...
Definition rsi.h:105
bool isWarning
Whether the error is or is not a warning.
Definition rsi.h:114
const char * what() const noexcept
Returns a null terminated character sequence that may be used to identify the exception.
Definition rsi.h:167
static void SetupControllerForHardware(MotionController *controller)
Sets up the controller for hardware use by resetting it and starting the network.
static void PrintFooter(std::string sampleAppName, int exitCode)
Print a message to indicate the sample app has finished and if it was successful or not.
static void ConfigurePhantomAxis(MotionController *controller, int axisNumber)
Configures a specified axis as a phantom axis with custom settings.
static void CheckErrors(RapidCodeObject *rsiObject)
Checks for errors in the given RapidCodeObject and throws an exception if any non-warning errors are ...
static void PrintHeader(std::string sampleAppName)
Print a start message to indicate that the sample app has started.
static void ShutdownTheNetwork(MotionController *controller)
Shuts down the network communication for the given MotionController.
static void SetupControllerForPhantoms(MotionController *controller, int axisCount, std::vector< int > axisNums)
Sets up the controller for phantom axes, including configuring specified axes as phantom.
static void ClearControllerCounts(MotionController *controller)
Clears count settings for axes, motion, and user limits on the controller.
static void StartTheNetwork(MotionController *controller)
Starts the network communication for the given MotionController.
static void SetupController(MotionController *controller)
Setup the controller with user defined axis counts and configuration.
static MotionController::CreationParameters GetCreationParameters()
Returns a MotionController::CreationParameters object with user-defined parameters.
SampleAppsHelper namespace provides static methods for common tasks in RMP applications.
char NodeName[PathLengthMaximum]
[Windows/INtime] Indicate the INtime node on which the RMP and RMPNetwork processes run.
Definition rsi.h:970
char RmpPath[PathLengthMaximum]
Location of the RMP firmware executable, license, and associated binaries and resources.
Definition rsi.h:938
int32_t CpuAffinity
[Linux] Indicate the CPU core on which the RMP and RMPNetwork processes run.
Definition rsi.h:990
char NicPrimary[PathLengthMaximum]
Primary EtherCAT Network Interface (NIC) name.
Definition rsi.h:944
static constexpr uint32_t PathLengthMaximum
MotionController::CreationParameters Maximum string buffer length.
Definition rsi.h:865
CreationParameters for MotionController::Create.
Definition rsi.h:855
static void ConfigureHardwareAxes(MotionController *controller, std::vector< Axis * > axes)
Configures the hardware axes according to user specified implementation.
This struct provides static methods and constants for user configuration in RMP applications....
static constexpr int CPU_AFFINITY
(Linux only) CPU core to use. This should be an isolated core.
static constexpr int AXIS_Y_USER_UNITS
User units for the second axis.
static constexpr int AXIS_COUNT
Number of axes to configure on the controller.
static constexpr int USER_LIMIT_COUNT
Number of user limits to configure on the controller.
static constexpr int MOTION_COUNT
Number of motion objects to configure on the controller.
static constexpr char NIC_PRIMARY[]
Name of the NIC to use for the EtherCAT network (not needed for running on phantom axes)
static constexpr int AXIS_X_INDEX
Index of the first axis to use in the sample apps.
static constexpr int MATH_BLOCK_COUNT
Number of math block objects to configure on the controller.
static constexpr bool USE_HARDWARE
Flag for whether to use hardware or phantom axes.
static constexpr char RMP_PATH[]
Path to the RMP.rta file (usually the RapidSetup folder).
static constexpr int AXIS_X_USER_UNITS
User units for the first axis.
static constexpr int RECORDER_COUNT
Number of recorder objects to configure on the controller.
static constexpr char NODE_NAME[]
(Windows only) INtime node name. Use "" for default node.
static constexpr int AXIS_Y_INDEX
Index of the second axis to use in the sample apps.