/*
 * Multi axis random shift script
 *
 * Description of the script: 
 *  This script does shifts on random offset from a specified range of distances
 *  with a random speed from a chosen range of speeds.
 *
 * 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++)
    {
        go_to_random_shift(axes[i]);
    }
}

function go_to_random_shift(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 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)
    axis.command_wait_for_stop(100); // wait until controller stops moving
}

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);
}
