APIs, concepts, guides, and more
_helpers.cs
Note
See ⚙️ Helpers 📜 for a detailed explanation of this sample code.
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.
using RSI.RapidCode; // RSI.RapidCode.dotNET;
public static class Helpers
{
public static void CheckErrors(RapidCodeObject rsiObject)
{
var hasErrors = false;
var errorStrBuilder = new System.Text.StringBuilder();
while (rsiObject.ErrorLogCountGet() > 0)
{
// get error
RsiError rsiError = rsiObject.ErrorLogGet();
// get message
var errorMsg = rsiError.isWarning ? $"WARNING: {rsiError.Message}" : $"ERROR: {rsiError.Message}";
errorStrBuilder.AppendLine(errorMsg);
// set flag
hasErrors = !rsiError.isWarning;
}
if (hasErrors)
throw new Exception(errorStrBuilder.ToString());
}
public static void NetworkStart(MotionController controller)
{
// check if network is started already
if (controller.NetworkStateGet() != RSINetworkState.RSINetworkStateOPERATIONAL)
{
Console.WriteLine("Starting Network..");
// if not started, initialize the network
controller.NetworkStart();
}
// check if network is started again
if (controller.NetworkStateGet() != RSINetworkState.RSINetworkStateOPERATIONAL)
{
// read network log messages
int messagesToRead = controller.NetworkLogMessageCountGet();
// print all the messages to help figure out the problem
for (int i = 0; i < messagesToRead; i++)
Console.WriteLine(controller.NetworkLogMessageGet(i));
throw new SystemException("Expected OPERATIONAL state but the network did not get there.");
}
else
{
Console.WriteLine("Network Started");
}
}
public static void NetworkShutdown(MotionController controller)
{
// check if the network is already shutdown
if (controller.NetworkStateGet() == RSINetworkState.RSINetworkStateUNINITIALIZED ||
controller.NetworkStateGet() == RSINetworkState.RSINetworkStateSHUTDOWN)
return;
// shutdown the network
Console.WriteLine("Shutting down the network..");
controller.NetworkShutdown();
// check if the network is shutdown
var networkState = controller.NetworkStateGet();
if (networkState != RSINetworkState.RSINetworkStateUNINITIALIZED &&
networkState != RSINetworkState.RSINetworkStateSHUTDOWN)
{
// some kind of error shutting down the network, read the network log messages
int messagesToRead = controller.NetworkLogMessageCountGet();
// print all the messages to help figure out the problem
for (int i = 0; i < messagesToRead; i++)
Console.WriteLine(controller.NetworkLogMessageGet(i));
throw new SystemException("Expected SHUTDOWN state but the network did not get there.");
}
else
{
Console.WriteLine("Network Shutdown");
}
}
public static void ControllerSetup(MotionController controller)
{
NetworkShutdown(controller);
// reset the controller to ensure it is in a known state
controller.Reset();
NetworkStart(controller);
}
public static void PhantomAxisReset(Axis phantomAxis)
{
if (phantomAxis.MotorTypeGet() != RSIMotorType.RSIMotorTypePHANTOM)
{
throw new Exception(@$"Axis {phantomAxis.NumberGet()} is not configured as a phantom axis.
Please ensure the axis is set to phantom before calling PhantomAxisConfigure.");
}
// abort any motion
AbortMotionObject(phantomAxis);
// disable all limits (not used for phantom axes)
phantomAxis.ErrorLimitActionSet(RSIAction.RSIActionNONE);
phantomAxis.HardwareNegLimitActionSet(RSIAction.RSIActionNONE);
phantomAxis.HardwarePosLimitActionSet(RSIAction.RSIActionNONE);
phantomAxis.HomeActionSet(RSIAction.RSIActionNONE);
phantomAxis.SoftwareNegLimitActionSet(RSIAction.RSIActionNONE);
phantomAxis.SoftwarePosLimitActionSet(RSIAction.RSIActionNONE);
// set position tolerances to max value for immediate MotionDone
double POSITION_TOLERANCE_MAX = Double.MaxValue / 10.0;
phantomAxis.PositionToleranceCoarseSet(POSITION_TOLERANCE_MAX);
phantomAxis.PositionToleranceFineSet(POSITION_TOLERANCE_MAX);
// set sample apps default motion parameters
phantomAxis.UserUnitsSet(1);
phantomAxis.DefaultVelocitySet(100);
phantomAxis.DefaultAccelerationSet(1000);
phantomAxis.DefaultDecelerationSet(1000);
phantomAxis.DefaultJerkPercentSet(0);
phantomAxis.PositionSet(0);
}
public static void AbortMotionObject(RapidCodeMotion motionObject)
{
motionObject.EStopAbort();
motionObject.MotionDoneWait();
motionObject.ClearFaults();
// check for idle state
if (motionObject.StateGet() != RSIState.RSIStateIDLE)
{
RSISource source = motionObject.SourceGet(); // get state source enum
string errorMsg = @$"Axis or MultiAxis {motionObject.NumberGet()} failed to enter IDLE state after aborting.
The source of the axis error is: {motionObject.SourceNameGet(source)}";
throw new Exception(errorMsg);
}
}
/*
@brief Ensures relationship between USE_HARDWARE constant and network status and throws if mismatch found.
@param controller Pointer to the MotionController to check.
@exception Exception Thrown if mismatch found between USE_HARDWARE constant and network status, or user cancels on warning.
@par Code Snippet
@snippet _helpers.cs VerifyHardwareUsage
*/
public static void VerifyHardwareUsage(MotionController controller)
{
const bool USE_HARDWARE = Constants.USE_HARDWARE; // User must set this in _constants.cs
bool networkIsOperational = controller.NetworkStateGet() == RSINetworkState.RSINetworkStateOPERATIONAL;
if (USE_HARDWARE && !networkIsOperational)
{
throw new Exception("USE_HARDWARE is set to true, but the network is not operational. " +
"Please properly configure your hardware or run _setup.cs.");
}
else if (!USE_HARDWARE && networkIsOperational)
{
throw new Exception("USE_HARDWARE is set to false, but the network is operational. " +
"Please ensure you are not connected to real hardware, or set USE_HARDWARE in _constants.cs to true.");
}
else if (!USE_HARDWARE && !networkIsOperational)
{
Console.WriteLine("Running with phantom axes as expected.");
}
else
{
// State running with hardware and require 'y' input from user to continue or any other key to abort
Console.WriteLine("Caution: You are currently running with hardware. " +
"Do not continue unless you have configured your axes through _setup.cs or another tool!");
Console.Write("Press 'y' to continue: ");
var input = Console.ReadKey();
Console.WriteLine(); // Move to next line after key press
if (input.KeyChar != 'y' && input.KeyChar != 'Y')
{
throw new Exception("User chose not to continue with hardware operation.");
}
}
}
/*
@brief Verifies that the AXIS_COUNT constant matches the controller's axis count, then validates minimum axis and MultiAxis requirements. Outputs comparison information to console.
@param controller The MotionController object to verify.
@param minRequiredSampleAxisCount Minimum number of axes required by the sample application (default: 1).
@param minRequiredSampleMultiAxisCount Minimum number of MultiAxis objects required by the sample application (default: 0).
@exception Exception Thrown if AXIS_COUNT doesn't match controller axis count, if minimum axis count is not met, or if minimum MultiAxis count (calculated as MotionCount minus AxisCount) is not met.
@par Code Snippet
@snippet _helpers.cs VerifyAxisCount
*/
public static void VerifyAxisCount(MotionController controller, int minRequiredSampleAxisCount = 1, int minRequiredSampleMultiAxisCount = 0)
{
int controllerAxisCount = controller.AxisCountGet();
int AXIS_COUNT = Constants.AXIS_COUNT;
// Verify AXIS_COUNT matches controller AxisCountGet()
if (controllerAxisCount != AXIS_COUNT)
{
// Axis count mismatch. Throw exception to stop execution
throw new Exception($"Controller axis count ({controllerAxisCount}) does not match intended AXIS_COUNT ({AXIS_COUNT}). " +
"Please ensure AXIS_COUNT in _constants.cs matches your number of hardware axes, then run _setup.cs or another tool " +
"to configure your hardware.");
}
// Verify minimum axis count
// Check against AXIS_COUNT here because if we get here we know controllerAxisCount == AXIS_COUNT
if (AXIS_COUNT < minRequiredSampleAxisCount)
{
throw new Exception($"This sample requires at least {minRequiredSampleAxisCount} " +
$"{(minRequiredSampleAxisCount == 1 ? "axis" : "axes")}, but AXIS_COUNT is only {AXIS_COUNT}. " +
$"Update your AXIS_COUNT in _constants.cs to meet the minimum requirement.");
}
// Verify minimum MultiAxis count
if (controller.MotionCountGet() - controllerAxisCount < minRequiredSampleMultiAxisCount)
{
throw new Exception($"This sample requires at least {minRequiredSampleMultiAxisCount} " +
$"MultiAxis object{(minRequiredSampleMultiAxisCount == 1 ? "" : "s")}. " +
"Please add more motion supervisors.");
}
}
}
Constants used in the C# sample apps.
Definition _constants.cs:3
const bool USE_HARDWARE
Default: false.
Definition _constants.cs:10
const int AXIS_COUNT
Default: 6.
Definition _constants.cs:14
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.
RSIMotorType MotorTypeGet()
Get the motor type.
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 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 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:5921
void DefaultVelocitySet(double velocity)
Set the default velocity in UserUnits.
void DefaultAccelerationSet(double acceleration)
Set the default acceleration in UserUnits.
void DefaultDecelerationSet(double deceleration)
Set the default deceleration in UserUnits.
void DefaultJerkPercentSet(double jerkPercent)
Set the default jerk percent.
Represents the RMP soft motion controller. This class provides an interface to general controller con...
Definition rsi.h:800
void ClearFaults()
Clear all faults for an Axis or MultiAxis.
int32_t MotionDoneWait(int32_t waitTimeoutMilliseconds=WaitForever)
Waits for a move to complete.
RSIState StateGet()
Get the Axis or MultiAxis state.
RSISource SourceGet()
Get the source of an error state for an Axis or MultiAxis.
void EStopAbort()
E-Stop, then abort an axis.
The RapidCodeMotion interface is implemented by Axis and MultiAxis .
Definition rsi.h:4389
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:184
Represents the error details thrown as an exception by all RapidCode classes. This class contains an ...
Definition rsi.h:111
bool isWarning
Whether the error is or is not a warning.
Definition rsi.h:120
RSINetworkState
State of network.
Definition rsienums.h:573
RSIAction
Action to perform on an Axis.
Definition rsienums.h:1122
RSIMotorType
Motor Type.
Definition rsienums.h:1318
RSISource
Possible sources that have caused an Error state.
Definition rsienums.h:1021
void CheckErrors(RapidCodeObject *rsiObject, const std::source_location &location=std::source_location::current())
Checks for errors in the given RapidCodeObject and throws an exception if any non-warning errors are ...
Definition helpers.h:32
void NetworkStart(MotionController *controller)
[CheckErrors]
Definition helpers.h:73
void NetworkShutdown(MotionController *controller)
[NetworkStart]
Definition helpers.h:108
Helpers namespace provides utility functions for common tasks in RMP applications.
Definition helpers.h:21