/*
 * Multi axis homing test with extio
 *
 * Description of the script: 
 *  The script starts calibration when a signal is received from a general purpose digital input/output (extio)
 * 
 * How to connect wires?
 *  You must connect to the HDB-26 connector (pin 25 on the controller).
 *
 * 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 XILab 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(2500);
}

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

while (1)
{
  axis.command_home(); // send HOME command (find home position)
  msleep(1500);

  BorderCycle();
  BorderCycle();

  command_wait_for_stop(100); // wait until controller stops moving

  s = axis.get_status();

  if (s.MvCmdSts & MVCMD_ERROR) // Checking the completion of the movement with an error
  {
    count_error++;

    log(">>> Alarm! Homing broken", 1);
  }
  else
  {
    count_good++;

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