﻿// MACRO ATC V 1.1 15-03-2019 GAMMADORO

InitializeGUI ();
dr = new DialogResult ();

exec.Stopspin();

//Tool positions definition
int Chuckopenport = Convert.ToInt32(exec.Readkey ("GP Proto CNC", "chuckPort", "0"));
int Chuckopenpin = Convert.ToInt32(exec.Readkey ("GP Proto CNC", "chuckPin", "0"));
//int Chuckopenport = 1;
//int Chuckopenpin = 17;
int Cleaningopenport = 2;
int Cleaningopenpin = 16;

int maxToolNumber = Convert.ToInt32(exec.Readkey ("GP Proto CNC", "maxToolNumber", "0"));
double offsetToolPosition = Convert.ToDouble(exec.Readkey ("GP Proto CNC", "offsetToolPosition", "0"));
double[] ToolX = new double[maxToolNumber + 1];
double[] ToolY = new double[maxToolNumber + 1];
double ToolDown = Convert.ToDouble (AS3.Getfield (3005)); // Quota di cambio utensile
double ToolUp; // Quota di movimento su cambio utensile per uscire dalla rastrelliera
double ToolYFuori;

ToolDown = Convert.ToDouble (AS3.Getfield (3005)); // Quota Cambio utensile
ToolX[0] = Convert.ToDouble (AS3.Getfield (3003)); // Tool0 X position
ToolY[0] = Convert.ToDouble (AS3.Getfield (3004)); // Tool0 Y position


double zpos = Convert.ToDouble (AS3.Getfield (228));

ToolX[1] = ToolX[0]; // Tool1 X position
ToolY[1] = ToolY[0]; // Tool1 Y position


for (int i = 2; i<=(maxToolNumber); i++)
{
	ToolX [i] = ToolX [0] + (offsetToolPosition*(i-1));
	ToolY [i] = ToolY [0];
}

ToolUp = ToolDown + 45; // sale di 80 mm rispetto alla quota di cambio
ToolYFuori = ToolY[0] - 50; // Quota Y fuori rastrelliera

double SafeZ = -10;
double SafeZup = 0;
double Ztoolrelease = ToolDown;
double Ztoolpickup = ToolDown;
double ZtoolpickupUP = 0;

int Newtool = exec.Getnewtool();
int Currenttool = exec.Getcurrenttool();

if(Newtool == -1) // If new tool number is -1 means a missing T code, so we need to stop here...
{
	textBoxDro.Visible = false;
	btnYES.Visible = false;
	btnNO.Visible = false;
	btnOK.Visible = true;
	textBoxStatus.Clear ();
	textBoxStatus.AppendText (" \n");
	textBoxStatus.AppendText ("Procedura terminata.");
	System.Media.SystemSounds.Exclamation.Play();
	dr = myForm.ShowDialog ();
	if (dr == DialogResult.OK)
	{
		myForm.Close();
	}
	
	return; 
}
if(Newtool <1 || Newtool > maxToolNumber) // Tool number is out of range, so we need to stop here...
{
	textBoxDro.Visible = false;
	btnYES.Visible = false;
	btnNO.Visible = false;
	btnOK.Visible = true;
	textBoxStatus.Clear ();
	textBoxStatus.AppendText (" \n");
	textBoxStatus.AppendText ("Utensile diverso dai valori consentiti!");
	System.Media.SystemSounds.Exclamation.Play();
	dr = myForm.ShowDialog ();
	if (dr == DialogResult.OK)
	{
		myForm.Close();
	}

	return;
}
if(Newtool == Currenttool) // Same tool was selected, so do nothing, stop here...
{ 
	textBoxDro.Visible = false;
	btnYES.Visible = false;
	btnNO.Visible = false;
	btnOK.Visible = true;
	textBoxStatus.Clear ();
	textBoxStatus.AppendText ("Utensile in mandrino e No." + Newtool + " uguale all'utensile richiamato.");
	System.Media.SystemSounds.Exclamation.Play();
	dr = myForm.ShowDialog ();
	if (dr == DialogResult.OK)
	{
		myForm.Close();
	}
	
	return; 
}
 
if(!exec.GetLED(56)||!exec.GetLED(57)||!exec.GetLED(58)) // If machine was not homed then it is unsafe to move in machine coordinates, stop here...
{
	textBoxDro.Visible = false;
	btnYES.Visible = false;
	btnNO.Visible = false;
	btnOK.Visible = true;
	textBoxStatus.Clear ();
	textBoxStatus.AppendText ("Errore! Cambio utensile non effettuabile se non è stata effettuata l'origine macchina!");
	System.Media.SystemSounds.Exclamation.Play();
	dr = myForm.ShowDialog ();
	if (dr == DialogResult.OK)
	{
		myForm.Close();
	}
  
	exec.Stop();
	return;
}

while(exec.IsMoving()){}

// Get current XY machine coordinates to return to this position at the end of the macro
// Legge la posizione corrente di XY delle ccordinate macchina per ritornare in posizione a termina macro

double Xoriginalpos = exec.GetXmachpos();
double Yoriginalpos = exec.GetYmachpos();
double Zoriginalpos = exec.GetZmachpos();

// Stop spindle if running and Move Z up
// Ferma il mandrino e muove la zeta nella posizione di sicurezza

exec.Stopspin(); 
exec.Code("G00 G53 Z"+ SafeZ); // Move Z up
while(exec.IsMoving()){}
if (Currenttool==0) 
{	
	InitializeGUI ();
	textBoxDro.Visible = false;
	btnYES.Visible = true;
	btnNO.Visible = true;
	btnOK.Visible = false;
	textBoxStatus.Clear ();
	textBoxStatus.AppendText ("Attenzione utensile No.0. Vuoi forzare il valore?");
	System.Media.SystemSounds.Exclamation.Play();
	dr = myForm.ShowDialog ();
	if (dr == DialogResult.Yes)
	{
		myForm.Close();
		InitializeGUI ();
		pictureBoxUI.Image = System.Drawing.Image.FromFile (Application.StartupPath + @"\Flashscreen\BMP\Bluescreenset\MessageBox1.png");
		textBoxDro.Visible = true;
		btnYES.Visible = false;
		btnNO.Visible = false;
		btnOK.Visible = true;
		textBoxStatus.Clear ();
		textBoxStatus.AppendText ("Inserisci il numero utensile in mandrino nel DRO.");
		System.Media.SystemSounds.Exclamation.Play();
		dr = myForm.ShowDialog ();
		if (dr == DialogResult.OK)
		{
			int tool_set = Convert.ToInt32(textBoxDro.Text);
			myForm.Close();
			exec.Setcurrenttool(tool_set);
		}
		
	}
	else if (dr == DialogResult.No)
	{
		myForm.Close ();
		InitializeGUI ();
		textBoxDro.Visible = false;
		btnYES.Visible = false;
		btnNO.Visible = false;
		btnOK.Visible = true;
		textBoxStatus.Clear ();
		textBoxStatus.AppendText ("Procedura terminata.");
		System.Media.SystemSounds.Exclamation.Play();
		dr = myForm.ShowDialog ();
		if (dr == DialogResult.OK)
		{
			myForm.Close();
		}
		
		return;
	}
						
}
if(Currenttool!=0) // No need to drop down tool if current tool number is zero
{
  // Muovo verso la posizione dell'utensile in mandrino 

  exec.Code("G00 G53 X" + ToolX[Currenttool]);
  while(exec.IsMoving()){}
  //mi posiziono davanti ala rastrelliera - mi porto a zeta sopra avanzo nella rastrelliera e scendo alla quota di cambio
  exec.Code("G00 G53 Y" + ToolYFuori);
while(exec.IsMoving()){}
	exec.Code("G00 G53 Z"+ ToolUp); 
	while(exec.IsMoving()){}  
    exec.Code("G00 G53 Y" + ToolY[Currenttool]);
  while(exec.IsMoving()){}

  while(exec.IsMoving()){}
	if(!exec.Ismacrostopped()) // If tool change was not interrupted with a stop only then validate new tool number
	{
		// Drop current tool
		// rilascio utensile in mandrino
		// Move Z axis down to tool holder position
		// Muove alla quota di cambio utensile su rastrelliera
  
	exec.Code("G00 G53 Z"+ Ztoolrelease); 
	while(exec.IsMoving()){}
  
		// Open the chuck with pneumatic valve
		// Apre la pinza , attiva valvola pneumatica
  
	exec.Setoutpin(Chuckopenport, Chuckopenpin); 
	exec.Wait(2000); // Wait one 1000msec
	exec.Code("G00 G53 Z"+ ToolUp); // Muove la zeta sopra cono
	while(exec.IsMoving()){}
	}

}


// Move to new tool position on XY plane
// Muove verso la posizione nuovo utensile spostandosi prima fuori dalla rastrelliera

exec.Code("G00 G53 Y" + ToolYFuori);
while(exec.IsMoving()){}

exec.Code("G00 G53 X" + ToolX[Newtool]);
while(exec.IsMoving()){}

//////////////////////////////////////////////////////////////////////////////////////////
	exec.Code("G00 G53 Z"+ ToolUp); 
	while(exec.IsMoving()){}  


exec.Code("G00 G53 Y" + ToolY[Newtool]);
while(exec.IsMoving()){}

// Prende nuovo utensile
// Apre elettrovalvola pulizia cono
exec.Setoutpin(Cleaningopenport, Cleaningopenpin); //COMMENTATO PER NO PULIZIA
// scendo con la Z alla quota di cambio
ZtoolpickupUP = Ztoolpickup + 10;
exec.Code("G00 G53 Z"+ ZtoolpickupUP); 
while(exec.IsMoving()){}

exec.Wait(1000); // Wait one 1000msec
// Chiudo elettrovalvola pulizia cono 
exec.Clroutpin(Cleaningopenport, Cleaningopenpin); //COMMENTATO PER NO PULIZIA
exec.Wait(1000); // Wait one 1000msec
// Chiudo la pinza cono utensile
exec.Code("G00 G53 Z"+ Ztoolpickup); 
while(exec.IsMoving()){}


if(!exec.Ismacrostopped()) // If tool change was not interrupted with a stop only then validate new tool number
{
exec.Clroutpin(Chuckopenport, Chuckopenpin); 
exec.Wait(1000); // Wait one 1000msec
exec.Setcurrenttool(Newtool); 
// Muovo la Z su altezza di sicurezza

	exec.Code("G00 G53 Z"+ ToolUp); 
	while(exec.IsMoving()){} 
	

}
exec.Code("G00 G53 Y" + ToolYFuori);
while(exec.IsMoving()){}
exec.Code("G00 G53 Z"+ SafeZ); 
while(exec.IsMoving()){}
// Muove verso posizione di partenza 

//exec.Code("G00 G53 X" + Xoriginalpos + " Y" + Yoriginalpos);
//while(exec.IsMoving()){}

// Measure new tool will go here....
exec.Code("G43 H"+Newtool); // Load new tool offset
//SafeZup=Zoriginalpos + 20;
//exec.Code("G00 G53 Z" + SafeZup);
//while(exec.IsMoving()){}
//exec.Code("G01 G53 Z" + Zoriginalpos + "F80");
//while(exec.IsMoving()){}

exec.Wait(200);
while(exec.IsMoving()){}
if(!exec.Ismacrostopped()) // If tool change was not interrupted with a stop only then validate new tool number
{
	exec.Setcurrenttool(Newtool); //Set the current tool -> the new tool
    
}
else
{
	exec.StopWithDeccel();
  
	InitializeGUI ();
	textBoxDro.Visible = false;
	btnYES.Visible = false;
	btnNO.Visible = false;
	btnOK.Visible = true;
	textBoxStatus.Clear ();
	textBoxStatus.AppendText ("Operazio interrotta. Verificare corrispondenza utensile in mandrino!");
	System.Media.SystemSounds.Exclamation.Play();
	dr = myForm.ShowDialog ();
	if (dr == DialogResult.OK)
	{
		myForm.Close();
	}
 
}


#Events

Form myForm;
Button btnYES;
Button btnNO;
Button btnOK;
TextBox textBoxStatus;
PictureBox pictureBoxUI;
TextBox textBoxDro;
DialogResult dr;

public Point mouseLocation;

private void pictureBoxUI_MouseDown(object sender, MouseEventArgs e)
{
	mouseLocation = new Point(-e.X, -e.Y);
}

private void pictureBoxUI_MouseMove(object sender, MouseEventArgs e)
{
	if (e.Button == MouseButtons.Left)
	{
		Point mousePos = Control.MousePosition;
		mousePos.Offset(mouseLocation.X, mouseLocation.Y);
		myForm.Location = mousePos;
	}
}

private void InitializeGUI ()
{
btnYES = new Button ();
btnYES.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(164)))), ((int)(((byte)(211)))), ((int)(((byte)(118)))));
btnYES.DialogResult = System.Windows.Forms.DialogResult.Yes;
btnYES.FlatAppearance.BorderSize = 0;
btnYES.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnYES.Font = new System.Drawing.Font("Aero Matics", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
btnYES.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
btnYES.Location = new System.Drawing.Point(236, 112);
btnYES.Size = new System.Drawing.Size(70, 22);
btnYES.TabIndex = 1;
btnYES.Text = "YES";
btnYES.UseVisualStyleBackColor = false;

btnNO = new Button ();
btnNO.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(164)))), ((int)(((byte)(211)))), ((int)(((byte)(118)))));
btnNO.DialogResult = System.Windows.Forms.DialogResult.No;
btnNO.FlatAppearance.BorderSize = 0;
btnNO.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnNO.Font = new System.Drawing.Font("Aero Matics", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
btnNO.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
btnNO.Location = new System.Drawing.Point(315, 112);
btnNO.Size = new System.Drawing.Size(70, 22);
btnNO.TabIndex = 2;
btnNO.Text = "NO";
btnNO.UseVisualStyleBackColor = false;

btnOK = new Button ();
btnOK.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(164)))), ((int)(((byte)(211)))), ((int)(((byte)(118)))));
btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
btnOK.FlatAppearance.BorderSize = 0;
btnOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnOK.Font = new System.Drawing.Font("Aero Matics", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
btnOK.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
btnOK.Location = new System.Drawing.Point(315, 112);
btnOK.Size = new System.Drawing.Size(70, 22);
btnOK.TabIndex = 3;
btnOK.Text = "OK";
btnOK.UseVisualStyleBackColor = false;

textBoxStatus = new TextBox (); 
textBoxStatus.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
textBoxStatus.BorderStyle = System.Windows.Forms.BorderStyle.None;
textBoxStatus.Font = new System.Drawing.Font("Aero Matics", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
textBoxStatus.ForeColor = System.Drawing.Color.LightGray;
textBoxStatus.Location = new System.Drawing.Point(83, 39);
textBoxStatus.Multiline = true;
textBoxStatus.ReadOnly = true;
textBoxStatus.Size = new System.Drawing.Size(302, 54);
textBoxStatus.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
textBoxStatus.TabIndex = 4;
textBoxStatus.TabStop = false;

textBoxDro = new TextBox ();
textBoxDro.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(164)))), ((int)(((byte)(211)))), ((int)(((byte)(118)))));
textBoxDro.BorderStyle = System.Windows.Forms.BorderStyle.None;
textBoxDro.Font = new System.Drawing.Font("Aero Matics", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
textBoxDro.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
textBoxDro.Location = new System.Drawing.Point(19, 114);
textBoxDro.MaxLength = 2;
textBoxDro.Size = new System.Drawing.Size(54, 18);
textBoxDro.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
textBoxDro.TabIndex = 5;
textBoxDro.TabStop = false;

pictureBoxUI = new PictureBox ();
pictureBoxUI.BackColor = System.Drawing.Color.Transparent;
pictureBoxUI.Image = System.Drawing.Image.FromFile (Application.StartupPath + @"\Flashscreen\BMP\Bluescreenset\MessageBox.png");
pictureBoxUI.Location = new System.Drawing.Point(0, 0);
pictureBoxUI.Size = new System.Drawing.Size(400, 150);
pictureBoxUI.Controls.Add(btnYES);
pictureBoxUI.Controls.Add(btnNO);
pictureBoxUI.Controls.Add(btnOK);
pictureBoxUI.Controls.Add(textBoxDro);
pictureBoxUI.Controls.Add(textBoxStatus);
pictureBoxUI.TabIndex = 0;
pictureBoxUI.MouseDown += new System.Windows.Forms.MouseEventHandler(pictureBoxUI_MouseDown);
pictureBoxUI.MouseMove += new System.Windows.Forms.MouseEventHandler(pictureBoxUI_MouseMove);

myForm = new Form ();
myForm.BackColor = System.Drawing.Color.DarkRed;
myForm.ClientSize = new System.Drawing.Size(400, 150);
myForm.Controls.Add(pictureBoxUI);
myForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
myForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
myForm.TransparencyKey = System.Drawing.Color.DarkRed;
myForm.TopMost = true;
}


