/*
 * Move EXTIO calb script
 *
 * The script moves to one of the 2 specified points,
 * depending on the state of the EXTIO input.
 * The movement is carried out in calibrated units.
 */

// Main characteristics
var time_discre = 10; // Discreteness of movement control(ms)
var nomspeed = 5;
var end_err = 0.015;

var low_position = 0; // Move to position for low EXTIO
var high_position = 180; // Move to position for high EXTIO

// Advanced setting.
var gr_per_step = 0.015; // Distance in gr for 1 completed step.
var calb = new_calibration(gr_per_step, get_engine_settings().MicrostepMode); // create calibration structure

// Setting the starting position.
command_stop(); // send STOP command (does immediate stop)
command_wait_for_stop(10); // wait until controller stops moving
command_home();
command_zero(); // send ZERO command (sets current position and encoder value to zero)


log("Start:");
// Setting 0 speeds and accelerations.
movesettings();

extiosettings();
// 
go_position(time_discre)

function extiosettings()
{
  var extsettings = get_extio_settings();
  extsettings.EXTIOSetupFlags = 0x00;
  extsettings.EXTIOModeFlags = 0x00;
  set_extio_settings(extsettings);
}

// Set the initial parameters of motion
function movesettings()
{
  var m = get_move_settings_calb(calb); // read movement settings from the controller
  m.Speed = nomspeed; // set movement speed
  
  set_move_settings_calb(m, calb); // write movement settings into the controller
}


// The main moving
function go_position(time_discre)
{
  var oldstate = 0;
  var maskstate = 32;
  
  // Setting the movement to the desired coordinate.
  command_move_calb(low_position, calb);
  
  // Pause before starting to move, to turn on the power button.
  msleep(300);

  while(1) {
	
	//
	var status = get_status_calb(calb);
	if ((status.GPIOFlags & maskstate) != oldstate)
	{
	  log(status.GPIOFlags);
	  if (oldstate)
	    command_move_calb(high_position, calb);
	  else
	    command_move_calb(low_position, calb);
	  
	  oldstate = status.GPIOFlags & maskstate;
	}
	// Waiting for the end of a discrete time interval
	msleep(time_discre);
  }
}