/*
 * Multi axis homing test script
 *
 * Description of the script: 
 *  This script tests homing function by repeatedly moving to a random position,
 *  doing quick stop and then homing, for all axes found. The script is similar to the GO
 *  Home button in mDrive Direct Control
 * 
 * Important:
 *  To run the script, upload it to the mDrive Direct Control software. For multi-controller operation, open them in a single multi-axis mDrive Direct Control window
 */

var axes = [];
var number_of_axes = 0;
var last_serial = 0;
while (serial = get_next_serial(last_serial)) // get next serial number and repeat for each axes.
{
    axes[number_of_axes] = new_axis(serial);
    log("Found axis " + number_of_axes + " with serial number " + serial);
    number_of_axes++;
    last_serial = serial;
}

while (1) { // infinite loop
    for (var i = 0; i < number_of_axes; i++)
    {
        homing_test(axes[i]);
    }
}

function homing_test(axis)
{
    var shift_low = 0; // minimum shift distance in steps
    var shift_high = 10000; // maximum shift distance in steps
    var speed_low = 100; // minimum movement speed in steps / second
    var speed_high = 5000; // maximum movement speed in steps / second
    var time_low = 1; // minimum wait time in seconds
    var time_high = 10; // maximum wait time in seconds
    
    axis.command_home(); // send HOME command (find home position)
    axis.command_wait_for_stop(100); // wait until controller stops moving
    var m = axis.get_move_settings(); // read movement settings from the controller
    m.Speed = rnd(speed_low, speed_high); // set random speed from a range of speeds between "speed_low" and "speed_high"
    axis.set_move_settings(m); // write movement settings into the controller
    var shift = rnd(shift_low, shift_high); // pick random shift value from a range of distances between "shift_low" and "shift_high"
    if (Math.random() < 0.5) { // pick random direction
        shift = -shift;
    }
    axis.command_movr(shift); // send MOVR command (does a relative shift)
    msleep( rnd(time_low*1000, time_high*1000) ); // pause for a random time from a range between "time_low" and "time_high"
    axis.command_stop(); // send STOP command (does immediate stop)
}

function rnd(min,max) { // "rnd" is a helper function which uses Math.random() and returns a uniformly distributed integer random value between "min" and "max"
  var r = Math.random()*(max-min)+min;
  return Math.round(r);
}
