/*
 * Border crossing test
 *
 * Description of the script: 
 *  The script checks the correct operation of the connected external limit switch
 * 
 * How to connect wires?
 *  You must connect the limit switch to the DVI-I connector (pins 2 and 3 on the controller connector).
 *
 * Note:
 *  This is a rather difficult script to learn, since it uses a large number of commands and structures.
 *
 * Important: 
 *  To run the script, upload it to the mDrive Direct Control software
 */

const MVCMD_ERROR = 0x40;
const MVCMD_RUNNING = 0x80;

var axis = new_axis(get_next_serial(0));
var m = axis.get_extio_settings();
var s = axis.get_status();

var count_error = 0;
var count_good = 0;

function BorderOff()
{
  m.EXTIOSetupFlags = 0x01; // Setting the foot to output mode
  m.EXTIOModeFlags = 0x10; // The output is always in the active state.

  axis.set_extio_settings(m); // The command to record the settings of the external input/output modes.
}

function BorderOn()
{
  m.EXTIOSetupFlags = 0x01; // Setting the foot to output mode
  m.EXTIOModeFlags = 0x00; // Do nothing

  axis.set_extio_settings(m); // The command to record the settings of the external input/output modes.
}

function BorderCycle()
{
  BorderOn();
  msleep(50);

  BorderOff();
  msleep(100);
}

log("You have to connect the common",2);
log("input/output pin on the backplane connector to",2);
log("the 2nd limit switch pin on the positioner connector", 2);
log("Also its recommended to load the profile for your stage", 2);

log(">>> Start testing", 3);

while (1)
{
  axis.command_left(); // Moving to the left
  msleep(200);
  BorderOn();
  msleep(200);
  s = axis.get_status(); // 

  if (s.MvCmdSts & MVCMD_RUNNING) // Checking the execution of the motion command
  {
    count_error++;

    log(">>> ALARM ! Crossing through the limit switch !" ,1);
  }
  else
  {
    count_good++;

    if (!(count_good % 50))
      log(">>> " + count_good + " cycles were done correct, " + count_error + " cycles were done incorrect", 3);
  }

  BorderOff();
}
