
' *****
Imports EgtUILib
' *****


Namespace Fanuc

	Public Class Fanuc
		Inherits CN_generico


#Region " Structures"
		Public Structure NC_var_Int_str_Type
			Dim index As Short
			Dim offset As Short
			Dim address As String
		End Structure
		Public Structure NC_var_Bit_str_Type
			Dim index As Short
			Dim offset As Short
			Dim bit_no As Short
			Dim address As String
		End Structure
#End Region

		Const A_AXIS As Short = 6

		Const Vmminch As Double = 1000.0
		Const NumCifreDecP4 As Double = 1000.0

		Const MAX_NC_VAR As Short = 100

#Region " Variabili "

		'		Private aTimer As System.Timers.Timer

		Private nCount As Integer = 0
		Private b_busy As Boolean = False
		Private b_OM_pos As Boolean = True

		Private Nc_var_int(MAX_NC_VAR) As NC_var_Int_str_Type
		Private Nc_var_bit(MAX_NC_VAR) As NC_var_Bit_str_Type

		Private n_Nc_var_int_defined As Short
		Private n_Nc_var_bit_defined As Short

		Private m_CnDataVar_Index(NUM_DATA) As Integer
		Private m_nCnDataVarNum As Integer = 0


#End Region

#Region " DLL import"
#End Region

#Region " Constructor"

		Sub New()
			n_state = 0
			sz_NC_error_messages = New List(Of String)
		End Sub
#End Region

#Region " PRIVATE DA FARE !!"

		Function timer_read_var() As Int16

			Dim nret As Int16 = -1
#If False Then
			'
			' alla brutta de dios vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
			'
			Dim buffer(30) As Short
			Dim b_ret As Boolean

			b_ret = F_Read_n_Int_From_PLC(59800, Convert_NC_Area_code("D"), buffer, 9)

			For n As Short = 0 To 9 - 1
				d_Dvariable_values(n) = buffer(n)
			Next

			d_spindle_power = Convert.ToDouble(buffer(0)) / 1000.0
			d_spindle_eff(0) = Convert.ToDouble(buffer(2))
			d_DInterpo_Feed_override = Convert.ToDouble(buffer(4))
			n_spindle_override(0) = buffer(5)

			d_DInterpo_Prog_Feed = Convert.ToDouble(buffer(8))

			d_spindle_prog(0) = Convert.ToDouble(buffer(9))


			b_feed_changed = True
			b_spindle_data_changed = True

			MyBase.OnNewVarChanged()

			' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#End If
			Call Read_Nc_var_structures()

			Return nret

		End Function

		Private Function set_NC_mode(n_mode As Integer) As Int16
		Dim nret As Integer = -1
			' Nicola: 29/03/2023
			'
			' trascodifica !!!!! da mettere anche nella SET MODE !!!!!
			'
			Select Case n_mode

				Case 0  ' Auto
					n_mode = 1      '    NUM dice 2 per Auto

				Case 1 ' EDIT
					n_mode = 3      '    NUM dice .. ?

				Case 2  ' MDI
					n_mode = 0      '    NUM dice 2 per MDI

				Case 7 ' JOG-Manual
					n_mode = 5      '    NUM dice 2 per Manual

				Case Else
					n_mode = -99

			End Select

			Dim bret As Boolean = NC_write_var_short(s_addr_set_nc_mode, CShort(n_mode))

			If Not bret Then
				EgtOutLog("Error in set_NC_mode(" & n_mode.ToString() & ")")
			Else
				nret = 0
			End If

			Return nret

			'nret = WriteObjectVarious2(n_portNC, Mode, n_mode)  '     0 AUTO    1 SEQUENZIALE    2 IMD    7 MANUALE   

			'If nret <> 0 Then
			'   EgtOutLog("Error in set_NC_mode(" & n_mode.ToString() & ") : " & nret.ToString())
			'End If


		End Function

		Private Function set_MDI_command(sz_command As String) As Int16
			Dim b_ret As Boolean
			Dim n_ret As Short

			'  !!!!! SET THE NC TO THE MDI MODE

			b_ret = F_MDI_write_program(sz_command)             ' create the command

			If b_ret Then

				' START CYCLE-2

				n_ret = F_cycle_start()

				If b_ret Then
					Return 0
				Else
					EgtOutLog(" set_MDI_command 3 " & M_Fanuc.sz_Err_Msg)
					Return -3
				End If

			Else
				EgtOutLog(" set_MDI_command 2 " & M_Fanuc.sz_Err_Msg)
				Return -2
			End If

		End Function
#End Region

#Region " Metodi pubblici DA FARE !!!"

		Public Overrides Sub ReadEls_Add_Parameter(sz_var As String, n_par As Short)
			Read_Variable(sz_var, CN_generico.Type.TDouble, 0, 0, d_DReadELS_value, "")
			n_DReadELS_handle = n_par
		End Sub
		'
		' call DVariables_WriteVariables("E80000;E80001" , "1;2" )
		'
		Public Overrides Sub DVariables_WriteVariables(sz_parameters As String, sz_values As String)
			' num vecchio erano vuote
		End Sub

		Public Overrides Sub DVariables_WriteVariables2(sz_parameters As String, sz_values As String)
			DVariables_WriteVariables3(sz_parameters, CN_generico.Type.TDouble, 0, 0, sz_values, "")
			' num vecchio erano vuote
		End Sub
		'
		' Write var
		'
		Public Overrides Function Write_var_1(sz_par As String, lvalue As Long) As Int16

			Dim nret As Int16 = -1


			Return nret

		End Function
		'
		' MDI command
		'
		Public Overrides Function MDI_command() As Short

			Dim nret As Int16 = set_MDI_command(sz_ManualDataInput)

			If nret <> 0 Then
				EgtOutLog("Error Execute MDI Command :" & nret.ToString())
			End If

			Return nret

		End Function
		'
		' Set Feed Hold
		'
		Public Overrides Function DGeneralFunctions_FeedHold() As Int16

			Dim nret As Int16 = -1

			If NC_pulse_bit(s_addr_feedhold) Then
				nret = 0
			End If

			Return nret


		End Function
		'
		' Set NC mode
		'
		Public Overrides Function DGeneralFunctions_WriteCncMode(nmode As Short) As Int16

			' Non controllare global_state, lo fa già la set_NC_mode
			Return set_NC_mode(nmode)

		End Function
		'
		' is G24 active ?
		'
		Public Overrides Function Is_G24_active() As Boolean

			' leggo lo stato di una variabile caricata dall'elenco NcData del file ini macchina
			Return b5AxesActive

		End Function

#End Region

#Region " Metodi pubblici FATTI"
		Public Overrides Function Init() As Boolean

			Dim sz_tokens() As String, sz_temp As String, n_temp As Short

			n_state = 0

			' Stringhe valide : "SIM;IN;HSSB" o "OK;MM;ET;192.168.1.139;8139;false;c:\partprg"

			sz_tokens = m_szCnDataVar(CnData.Comm).Split(";")

			M_Fanuc.bSimulation = False
			sz_temp = Trim(sz_tokens(0)).ToUpper
			If sz_temp.StartsWith("SI") Then bSimulation = True

			M_Fanuc.b_machine_in_inches = False
			sz_temp = Trim(sz_tokens(1)).ToUpper
			If sz_temp.StartsWith("IN") Then M_Fanuc.b_machine_in_inches = True

			M_Fanuc.cnc_info.Node_number = 0
			M_Fanuc.cnc_info.Handle = 0
			M_Fanuc.cnc_info.ConnectionStatus = CNC_Connection_Status_Type.NOT_CONNECTED

			'        cnc_info.ConnectionType = M_fanuc.CNC_Connection_Type.Ethernet
			'        cnc_info.IPAddress = "192.168.1.10"
			'        cnc_info.Port = 8193

			sz_temp = Trim(sz_tokens(2)).ToUpper

			If sz_temp.StartsWith("ET") Then
				M_Fanuc.cnc_info.ConnectionType = CNC_Connection_Type.Ethernet
				M_Fanuc.cnc_info.IPAddress = sz_tokens(3)
				If Short.TryParse(sz_tokens(4), n_temp) Then
					M_Fanuc.cnc_info.Port = n_temp
				End If

			Else
				M_Fanuc.cnc_info.ConnectionType = CNC_Connection_Type.HSSB
			End If


			Dim nret As Integer = M_Fanuc.NC_connect(M_Fanuc.cnc_info)
			If nret <> Focas1.EW_OK Then Return False

			n_state = 2

			' Create a timer and set an half second interval.
			'			aTimer = New System.Timers.Timer()

			Dim nRefresh As Integer = 200
			Dim nTemp As Integer
			If Integer.TryParse(m_szCnDataVar(CnData.Refresh), nTemp) Then
				nRefresh = nTemp
			End If

			'			aTimer.Interval = nRefresh

			' Hook up the Elapsed event for the timer.  
			'			AddHandler aTimer.Elapsed, AddressOf OnTimedEvent

			'			aTimer.AutoReset = True         ' Have the timer fire repeated events (true is the default)

			'			aTimer.Enabled = True          ' Start the timer


			For n As Integer = 0 To 7
				b_axis_valid(n) = True
			Next

			Call Init_NC_var_structures()

			Return n_state >= 2

		End Function

		Public Overrides Function Stop_Connection() As Boolean

			Dim msga As String

			'			aTimer.Stop()

			Dim nRet As Short = M_Fanuc.NC_disconnect()

			If nRet <> 0 Then
				msga = "Error in NC_disconnect : " & nRet.ToString
				'   EgtOutLog(msga)
			End If

			Return True

		End Function
		'
		' Set DPOsition Mode OP/OM
		'
		Public Overrides Sub set_OP_OM(n As Short)

			b_OM_pos = (n = 0)

		End Sub
		'
		' da PC a CN
		'
		Public Overrides Function Download_NC_prog(sz_PC_filename As String, sz_NC_filename As String) As Int16

			Dim b_ret As Boolean, n_ret As Short = -99

			b_ret = M_Fanuc.Send_file_to_nc(sz_PC_filename, "", sz_NC_filename)

			If b_ret Then Return 0

			Return n_ret

		End Function
		'
		' da CN a pc
		'
		Public Overrides Function Upload_NC_prog(sz_PC_filename As String, sz_NC_filename As String) As Int16

			Dim b_ret As Boolean, n_ret As Short = -99

			b_ret = F_Receive_Prg(sz_PC_filename, sz_NC_filename)

			If b_ret Then Return 0

			Return n_ret

		End Function
		'
		' delete NC file
		'
		Public Overrides Function Delete_NC_prog(sz_NC_filename As String) As Int16

			Dim b_ret As Boolean, n_ret As Short = -99

			b_ret = F_Delete_Prg(sz_NC_filename)

			If b_ret Then Return 0

			Return n_ret

		End Function
		'
		' Activate program
		' returns 0 = OK ; > 0 error
		'
		Public Overrides Function ActivateProgram(n_part_program As Integer) As Int16

			Dim nret As Int16 = -1

			If M_Fanuc.F_Select_Prg(n_part_program.ToString) Then Return Focas1.EW_OK

			'If nret <> 0 Then
			'   EgtOutLog("Error in Activate program : " & nret.ToString())
			'End If

			Return nret

		End Function
		'
		' Set Cycle Start
		'
		Public Overrides Function DGeneralFunctions_CycleStart() As Int16

			Dim nret As Int16 = -1

			If M_Fanuc.F_cycle_start() Then Return Focas1.EW_OK

			Return nret

		End Function
		'
		' Set NC Reset
		'
		Public Overrides Function DGeneralFunctions_Reset() As Int16
			Dim nret As Int16 = -1

			If M_Fanuc.F_reset() Then Return Focas1.EW_OK

			Return nret

		End Function
		'
		' Read active mode
		'
		Public Overrides Function read_active_mode() As Int16

			Dim n_status As Short

			If M_Fanuc.F_NC_status(n_status) Then

				'
				' trascodifica !!!!! da mettere anche nella SET MODE !!!!!
				'

				Return Trascodifica_nc_mode(n_status)

			Else
				' !! msg errore
				Return -99
			End If

		End Function

		Private Function Trascodifica_nc_mode(n_status As Short) As Int16

			Select Case n_status

				Case 0  ' MDI
					Return 2      '    NUM dice 2 per MDI

				Case 1  ' Auto
					Return 0      '    NUM dice 2 per Auto

				Case 3 ' EDIT
					Return 1      '    NUM dice 2 per Single

				Case 5 ' JOG-Manual
					Return 7      '    NUM dice 2 per Manual

				Case Else
					Return -99

			End Select

		End Function

		Public Overrides Sub DVariables_WriteVariables3(szVarAddr As String, ParType As Short, nVarValue As Integer, lVarValue As Long, dVarValue As Double, sVarValue As String)

			Dim sz_temp As String, n_addr As Integer, b_ret As Boolean

			Select Case ParType

				Case Type.TDouble

					If szVarAddr.StartsWith("#") Then

						sz_temp = szVarAddr.Replace("#", "")

						If Integer.TryParse(sz_temp, n_addr) Then
							b_ret = F_Write_macro(n_addr, dVarValue)

						End If

					End If


				Case Type.TBoolean
				Case Type.TInteger
				Case Type.TLong
				Case Type.TString

			End Select


		End Sub

		Public Overrides Sub Read_Variable(szVarAddr As String, ParType As Integer, ByRef nVarValue As Integer, ByRef lVarValue As Long, ByRef dVarValue As Double, ByRef sVarValue As String)

			Dim sz_temp As String, n_addr As Integer, b_ret As Boolean

			Select Case ParType

				Case Type.TDouble

					If szVarAddr.StartsWith("#") Then

						sz_temp = szVarAddr.Replace("#", "")

						If Integer.TryParse(sz_temp, n_addr) Then
							b_ret = F_Read_macro(n_addr, dVarValue)

						End If

					End If


				Case Type.TBoolean
				Case Type.TInteger
				Case Type.TLong
				Case Type.TString

			End Select

		End Sub
		'
		' allarmi
		'
		Public Overrides Function get_plc_messages() As Int16

			Return get_errors()

		End Function
#End Region

#Region " private fatti"
		'
		' private functions
		'
		Private Sub Init_NC_var_structures()

			' STAI ATTENTO !!!
			' n_Base_addr_int_vars = 59800
			' n_Base_addr_byte_for_bits_vars = 59820
			' n_num_var_int_to_read = 10
			' n_num_var_byte_for_bits_to_read = 30
			' s_addr_set_nc_mode = "D59825"

			Dim sz_t As String, sz_data_type As String = "", n_address As Integer, n_bit As Integer

			n_Nc_var_int_defined = 0
			n_Nc_var_bit_defined = 0

			' Creo lista nomi variabili PLC da leggere

			For nI As Integer = 0 To NUM_DATA - 1

				'sz_t = m_szCnDataVar(nI) ' indirizzo variabile da configurare
				If Not String.IsNullOrEmpty(m_szCnDataVar(nI)) AndAlso m_szCnDataVar(nI).Contains("PLC,") Then
					m_szCnDataVar(nI) = m_szCnDataVar(nI).Replace("PLC,", "")
				Else
					m_CnDataVar_Index(m_nCnDataVarNum) = nI             ' imposto indice variabile
					m_nCnDataVarNum += 1
					Continue For
				End If

				sz_t = m_szCnDataVar(nI) ' indirizzo variabile da configurare

				If Not String.IsNullOrWhiteSpace(sz_t) Then  ' addres not null ?

					If sz_t.Contains(".") Then ' bit variable?

						If Check_var_bit_address(sz_t, sz_data_type, n_address, n_bit) Then ' valid bit address ?

							Nc_var_bit(n_Nc_var_bit_defined).offset = n_address - n_Base_addr_byte_for_bits_vars
							Nc_var_bit(n_Nc_var_bit_defined).bit_no = n_bit
							Nc_var_bit(n_Nc_var_bit_defined).address = sz_t
							Nc_var_bit(n_Nc_var_bit_defined).index = nI
							n_Nc_var_bit_defined = n_Nc_var_bit_defined + 1           ' incremento numero di variabili da leggere

						End If ' valid bit address 

					Else
						If Check_var_address(sz_t, sz_data_type, n_address) Then ' valid int address ?

							Nc_var_int(n_Nc_var_int_defined).offset = n_address - n_Base_addr_int_vars
							Nc_var_int(n_Nc_var_int_defined).address = sz_t
							Nc_var_int(n_Nc_var_int_defined).index = nI
							n_Nc_var_int_defined = n_Nc_var_int_defined + 1           ' incremento numero di variabili da leggere

						End If ' valid int address

					End If ' bit variable

					m_CnDataVar_Index(m_nCnDataVarNum) = nI             ' imposto indice variabile
					m_nCnDataVarNum += 1                                ' incremento numero di variabili da leggere

				End If ' addres not null

			Next

		End Sub

		Sub Read_Nc_var_structures()

			Dim n As Short, n_temp As Short, n_index As Short, n_num_bit As Short
			Dim b_ret As Boolean
			Dim buffer(300) As Short
			Dim by_buffer(300) As Byte, by_temp As Byte
			Dim b_temp As Boolean

			' read int variables

			b_ret = F_Read_n_Int_From_PLC(n_Base_addr_int_vars, Convert_NC_Area_code("D"), buffer, n_num_var_int_to_read)
			If Not b_ret Then
				Exit Sub
			End If

			' process int variables

			For n = 0 To (n_Nc_var_int_defined - 1)

				n_temp = buffer((Nc_var_int(n).offset) / 2)
				n_index = Nc_var_int(n).index

				Select Case n_index

					Case CnData.Mode       ' (0) modo   0:AUTO;1:SEQ;2:MDI;3:RAPIDO;4:SERCH;5:EDIT;6:TEST;7:MANUALE;
						' nMachineMode = n_temp

						' Applico transcodifica					
						nMachineMode = Trascodifica_nc_mode(n_temp)

					Case CnData.JogIncr    ' (1) Tipo man. 0:0.1 u; 1:1 u; 2:10 u; 3:100 u; 4:1 mm; 5:10 mm; 6:ILL; 8:HANDWEEL; 9:0.01 u; 10:0.001 u;
					  ' ...

					Case CnData.Feed       ' (2)
						d_DInterpo_Prog_Feed = CDbl(n_temp) ' d_DInterpo_Prog_Feed

					Case CnData.FeedOvr    ' (3) Potenziom. Feed  = * 0.47059
						d_DInterpo_Feed_override = CDbl(n_temp)
						b_feed_changed = True

					Case CnData.Speed      ' (4) Speed
						d_spindle_eff(0) = CDbl(n_temp)

					Case CnData.SpeedOvr   ' (5) Potenziom. speed  = ...
						n_spindle_override(0) = n_temp

					Case CnData.Power      ' (6) Ampère = * 0.01
						d_spindle_power = CDbl(n_temp)
						b_spindle_power_changed = True

					Case CnData.PowerOvr    ' (10) valore assorbimento massimo mandrino con l'utensile corrente
						bPowerOvr = CDbl(n_temp)
						b_spindle_power_changed = True

					Case CnData.DoorClosed     ' (20) Stato porte
						nDoorClosedState = n_temp

					Case CnData.EnableZone     ' (53)
						nEnableZone = n_temp

					Case CnData.EnablePC     ' (54)
						nEnablePc = n_temp

				End Select

			Next

			' read bit variables as bytes

			b_ret = F_Read_n_Bytes_From_PLC(n_Base_addr_byte_for_bits_vars, Convert_NC_Area_code("D"), by_buffer, n_num_var_byte_for_bits_to_read)
			If Not b_ret Then
				Exit Sub
			End If

			' process bit variables

			For n = 0 To (n_Nc_var_bit_defined - 1)

				by_temp = by_buffer(Nc_var_bit(n).offset)
				n_index = Nc_var_bit(n).index
				n_num_bit = Nc_var_bit(n).bit_no

				b_temp = Get_bit2(by_temp, n_num_bit)


				Select Case n_index

					Case CnData.Spindle     ' (7) Stato rotazione mandrino
						bSpindleState = b_temp
					Case CnData.Coolant     ' (8) Stato acqua
						bCoolantState = b_temp
					Case CnData.Laser       ' (9) Stato laser punto
						bLaserState = b_temp
					Case CnData.InternalCoolant     ' (13) Stato acqua interna
						bInternalCoolantState = b_temp
					Case CnData.ExternCoolant     ' (14) Stato acqua esterna
						bExternCoolantState = b_temp
					Case CnData.CBAxes     ' (15) Stato ativazione assi c e b
						bCBAxesState = b_temp
					Case CnData.AirBlow     ' (16) Stato soffio utensile
						bAirBlowState = b_temp
					Case CnData.Home     ' (17) Stato home
						bHomeState = b_temp
					Case CnData.TableUp     ' (18) Stato tavolo su
						bTableUpState = b_temp
					Case CnData.TableDown     ' (19) Stato tavolo giu'
						bTableDownState = b_temp

					Case CnData.LimitZ     ' (21) Stato limitazione asse Z
						bLimitZState = b_temp
					Case CnData.VacuumUp     ' (22) Stato ventosa su'
						bVacuumUp = b_temp
					Case CnData.VacuumDown     ' (23) Stato ventosa giu'
						bVacuumDown = b_temp
					Case CnData.Vacuum2Up     ' (24) Stato ventosa2 su'
						bVacuum2Up = b_temp
					Case CnData.Vacuum2Down     ' (25) Stato ventosa2 giu'
						bVacuum2Down = b_temp
					Case CnData.Vacuum1State     ' (26) Stato ventosa 1
						bVacuum1State = b_temp
					Case CnData.Vacuum2State     ' (27) Stato ventosa 2
						bVacuum2State = b_temp
					Case CnData.Vacuum3State     ' (28) Stato ventosa 3
						bVacuum3State = b_temp
					Case CnData.Vacuum4State     ' (29) Stato ventosa 4
						bVacuum4State = b_temp
					Case CnData.Vacuum5State     ' (30) Stato ventosa 5
						bVacuum5State = b_temp
					Case CnData.Vacuum6State     ' (31) Stato ventosa 6
						bVacuum6State = b_temp
					Case CnData.Vacuum135State     ' (32) Stato ventose 135
						bVacuum135State = b_temp
					Case CnData.Vacuum246State     ' (33) Stato ventose 246
						bVacuum246State = b_temp
					Case CnData.OpenAllState     ' (34) Stato apertura ventose
						bOpenAllState = b_temp
					Case CnData.CloseAllState     ' (35) Stato chiusura ventose
						bCloseAllState = b_temp
					Case CnData.Open123State     ' (36) Stato apertura ventose
						bOpen123State = b_temp
					Case CnData.Open456State     ' (37) Stato apertura ventose
						bOpen456State = b_temp
					Case CnData.Close123State     ' (38) Stato chiusura ventose
						bClose123State = b_temp
					Case CnData.Close456State     ' (39) Stato chiusura ventose
						bClose456State = b_temp
					Case CnData.BlowState     ' (40) Stato soffio ventose
						bBlowState = b_temp
					Case CnData.VacuumOn     ' (41) Stato aspirazione ventose acceso
						bVacuumOn = b_temp
					Case CnData.BypassState     ' (42) Stato bypass
						bBypassState = b_temp
					Case CnData.Vacuum0     ' (43) Stato rotazione ventosa 0
						bVacuum0 = b_temp
					Case CnData.Vacuum90     ' (44) Stato rotazione ventosa 0
						bVacuum90 = b_temp
					Case CnData.VacuumOff     ' (45) Stato aspirazione ventose spento
						bVacuumOff = b_temp

					Case CnData.LaserTrac   ' (46) Stato laser tracciatura
						bLaserTracState = b_temp

					Case CnData.XYJog     ' (47) 
						bXYJog = b_temp
					Case CnData.ZCJog     ' (48)
						bZCJog = b_temp
					Case CnData.ZBJog     ' (49)
						bZBCJog = b_temp
					Case CnData.PowerON     ' (50)
						bPowerON = b_temp
					Case CnData.Remote     ' (51)
						bRemote = b_temp

					Case CnData.Parking     ' (52)
						bParkingState = b_temp

					Case CnData.nAxes     ' (55)
						b5AxesActive = b_temp

				End Select

			Next



		End Sub







		'		Private Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs)
		Public Overrides Function Geppo() As Boolean

			If Not b_busy Then
				b_busy = True

				nCount += 1

				Read_machine_pos()     ' leggo posizioni assi

				If nCount = 2 Or nCount = 4 Then
					timer_read_var()       ' leggo un mucchio di variabili in un colpo solo
				End If

				If nCount = 4 Then
					nCount = 0
					get_errors()        ' leggo eventueli errori PLC e CN
				End If

				b_busy = False

			End If

			Return False
		End Function

		Private Function get_errors() As Int16

			Dim n_errors As Short
			Dim szt As String

			sz_NC_error_messages.Clear()
			b_NC_error = False
			'
			'PLC errors .... ???

			' NC alarms

			n_errors = M_Fanuc.F_get_cnc_alarms3()

			If n_errors <> BAD_RETURN_SH Then

				For i As Short = 0 To (M_Fanuc.AlarmMessageCount - 1)

					szt = M_Fanuc.AlarmNumber(i).ToString & " - " & M_Fanuc.AlarmMessage(i)
					sz_NC_error_messages.Add(szt)

				Next i

			Else
				Return BAD_RETURN_SH
			End If

			If n_errors > 0 Then b_NC_error = True



			n_errors = F_get_operator_messages()

			If n_errors <> BAD_RETURN_SH Then

				For i As Short = 0 To (M_Fanuc.OperatorMessageCount - 1)

					szt = M_Fanuc.OperatorMsgNumber(i).ToString & " - " & M_Fanuc.OperatorMessage(i)
					sz_NC_error_messages.Add(szt)

				Next i

			Else
				Return BAD_RETURN_SH
			End If

			If (n_errors > 0) Or (b_NC_error) Then b_NC_error = True


			n_errors = F_get_PLC_messages()

			If n_errors <> BAD_RETURN_SH Then

				For i As Short = 0 To (n_errors - 1)

					szt = lst_plc_messages(i)
					sz_NC_error_messages.Add(szt)

				Next i

			Else
				Return BAD_RETURN_SH
			End If

			If (n_errors > 0) Or (b_NC_error) Then b_NC_error = True


			Return Focas1.EW_OK

		End Function

		Function Read_machine_pos() As Int16

			Dim b_ret As Boolean


			If b_OM_pos Then               ' quote rispetto a 0  Macchina
				b_ret = F_read_position_MACH()
			Else                           ' quote rispetto a 0 Pezzo
				b_ret = F_read_position_ABS()
			End If

			If Not b_ret Then
				Dim sMsg As String = "Error in F_read_position_* : " & M_Fanuc.sz_Err_Msg
				'   EgtOutLog(sMsg)
				Return -1
			End If

			b_ret = F_read_position_DELTA()
			If Not b_ret Then
				Dim sMsg As String = "Error in F_read_position_DELTA* : " & M_Fanuc.sz_Err_Msg
				'   EgtOutLog(sMsg)
				Return -1
			End If


			For i As Short = 0 To (Focas1.MAX_AXIS - 1)      ' si possono leggere come massimo 9 assi 0 -> 8

				If i < A_AXIS Then
					d_axis_position(i) = M_Fanuc.l_pos_values(i) / Vmminch  ' X
					d_axis_delta(i) = M_Fanuc.l_delta_values(i) / Vmminch
				Else
					d_axis_position(i) = M_Fanuc.l_pos_values(i) / NumCifreDecP4 ' A
					d_axis_delta(i) = M_Fanuc.l_delta_values(i) / Vmminch
				End If

			Next

			If b_axis_events_enable Then
				MyBase.OnNewPositionData()
				MyBase.OnNewPosDeltaData()
			End If

			Return 0

		End Function

#End Region

#Region " Nuovi metodi pubblici"

		Private sz_Data_type As String
		Private n_address As Integer
		Private n_end_address As Integer
		Private n_bit As Integer

		Private bit_mask() As Byte = {&H1, &H2, &H4, &H8, &H10, &H20, &H40, &H80}
		Private neg_bit_mask() As Byte = {&HFE, &HFD, &HFB, &HF7, &HEF, &HDF, &HBF, &H7F}

		Public Overrides Function NC_read_var_short(sz_VarAddr As String, ByRef value As Short) As Boolean

			Dim b_ret As Boolean = False
			Dim Buffer As Short()

			ReDim Buffer(2)

			If Check_var_address(sz_VarAddr, sz_Data_type, n_address) Then

				b_ret = F_Read_n_Int_From_PLC(n_address, Convert_NC_Area_code(sz_Data_type), Buffer, 1)

				If b_ret Then
					value = Buffer(0)
					Return True
				Else
					Return False
				End If

			Else
				' !!!!! error message
				Return False

			End If

		End Function

		Public Overrides Function NC_read_var_short_range(sz_VarStartAddr As String, sz_VarEndAddr As String, ByRef values() As Short) As Boolean

			Dim b_ret As Boolean = False
			Dim Buffer As Short()
			Dim n_bytes As Integer


			If Check_var_address(sz_VarStartAddr, sz_Data_type, n_address) Then

				If Check_var_address(sz_VarEndAddr, sz_Data_type, n_end_address) Then

					n_bytes = n_end_address - n_address + 1

					ReDim Buffer(n_bytes)

					b_ret = F_Read_n_Int_From_PLC(n_address, Convert_NC_Area_code(sz_Data_type), Buffer, n_bytes)

					If b_ret Then

						For n As Short = 0 To (n_bytes - 1)
							values(0) = Buffer(0)
						Next
						Return True

					Else
						Return False
					End If

				Else
					' !!!!! error message
					Return False

				End If
			Else
				' !!!!! error message
				Return False

			End If

		End Function

		Public Overrides Function NC_write_var_short(sz_VarAddr As String, ByRef value As Short) As Boolean

			Dim b_ret As Boolean = False
			Dim Buffer As Short()

			ReDim Buffer(2)

			Buffer(0) = value

			If Check_var_address(sz_VarAddr, sz_Data_type, n_address) Then

				b_ret = F_Write_n_Int_To_PLC(n_address, Convert_NC_Area_code(sz_Data_type), Buffer, 1)

				If b_ret Then
					Return True
				Else
					Return False
				End If

			Else
				' !!!!! error message
				Return False

			End If

			Return False

		End Function

		Public Overrides Function NC_read_var_bit(sz_VarAddrBit As String, ByRef b_value As Boolean) As Boolean

			Dim b_ret As Boolean = False
			Dim Buffer As Byte()
			Dim by_value As Byte

			Dim Area As PMCAreaType

			ReDim Buffer(2)

			If Check_var_bit_address(sz_VarAddrBit, sz_Data_type, n_address, n_bit) Then

				Area = Convert_NC_Area_code(sz_Data_type)

				b_ret = F_Read_n_Bytes_From_PLC(n_address, Area, Buffer, 1)

				If b_ret Then
					by_value = Buffer(0)

					b_value = Get_bit2(by_value, n_bit)

					Return b_ret
				Else
					Return False
				End If

			Else
				' !!!!! error message
				Return False

			End If

			Return False
		End Function

		Public Overrides Function NC_write_var_bit(sz_VarAddrBit As String, ByRef b_value As Boolean) As Boolean

			Dim b_ret As Boolean = False
			Dim Buffer As Byte()
			Dim by_value As Byte

			Dim Area As PMCAreaType

			ReDim Buffer(2)

			If Check_var_bit_address(sz_VarAddrBit, sz_Data_type, n_address, n_bit) Then

				Area = Convert_NC_Area_code(sz_Data_type)

				b_ret = F_Read_n_Bytes_From_PLC(n_address, Area, Buffer, 1)

				If b_ret Then
					by_value = Buffer(0)

					Set_bit2(by_value, n_bit, b_value)

					Buffer(0) = by_value

					b_ret = F_Write_n_Bytes_To_PLC(n_address, Area, Buffer, 1)

					Return b_ret
				Else
					Return False
				End If

			Else
				' !!!!! error message
				Return False

			End If

			Return False
		End Function

		Public Overrides Function NC_pulse_bit(sz_VarAddrBit As String) As Boolean

			Dim b_ret As Boolean = False
			Dim Buffer As Byte()
			Dim by_value As Byte, by_original As Byte

			Dim Area As PMCAreaType

			ReDim Buffer(2)

			If Check_var_bit_address(sz_VarAddrBit, sz_Data_type, n_address, n_bit) Then

				Area = Convert_NC_Area_code(sz_Data_type)

				b_ret = F_Read_n_Bytes_From_PLC(n_address, Area, Buffer, 1)

				If b_ret Then
					by_value = Buffer(0)
					by_original = by_value

					Set_bit2(by_value, n_bit, True)

					Buffer(0) = by_value
					b_ret = F_Write_n_Bytes_To_PLC(n_address, Area, Buffer, 1)
					If b_ret Then
						System.Threading.Thread.Sleep(50)
						Buffer(0) = by_original
						b_ret = F_Write_n_Bytes_To_PLC(n_address, Area, Buffer, 1)
					End If

				End If

				Return b_ret

			Else
				' !!!!! error message
				Return False

			End If

		End Function

		Private Function Check_var_address(sz_VarAddr As String, ByRef sz_Data_type As String, ByRef n_address As Integer) As Boolean

			Dim sz_address As String

			Try

				sz_Data_type = sz_VarAddr.Substring(0, 1)   ' primo carattere
				sz_address = sz_VarAddr.Substring(1)      ' dal secondo in poi

				If sz_address.Contains(".") Then
					Return False
				Else
					If Integer.TryParse(sz_address, n_address) Then
						Return True
					Else
						Return False
					End If
				End If

			Catch ex As Exception

				Return False
			End Try

			Return True

		End Function

		Private Function Check_var_bit_address(sz_VarAddr As String, ByRef sz_Data_type As String, ByRef n_address As Integer, ByRef n_bit_address As Integer) As Boolean

			Dim sz_tokens() As String
			Dim sz_address As String

			Try
				sz_Data_type = sz_VarAddr.Substring(0, 1)   ' primo carattere
				sz_address = sz_VarAddr.Substring(1)      ' dal secondo in poi


				If sz_address.Contains(".") Then

					sz_tokens = sz_address.Split(".")
					If Integer.TryParse(sz_tokens(0), n_address) Then

						If Integer.TryParse(sz_tokens(1), n_bit_address) Then
							Return True
						Else
							Return False
						End If
					Else
						Return False
					End If

				Else
					Return False
				End If

			Catch ex As Exception

				Return False
			End Try




			Return True

		End Function

		Private Function Convert_NC_Area_code(sz_area As String) As Short

			Select Case sz_area

				Case "G"
					Return PMCAreaType.G_AREA

				Case "F"
					Return PMCAreaType.F_AREA

				Case "Y"
					Return PMCAreaType.Y_AREA

				Case "X"
					Return PMCAreaType.X_AREA

				Case "A"
					Return PMCAreaType.A_AREA

				Case "R"
					Return PMCAreaType.R_AREA

				Case "T"
					Return PMCAreaType.T_AREA

				Case "K"
					Return PMCAreaType.K_AREA

				Case "C"
					Return PMCAreaType.C_AREA

				Case "D"
					Return PMCAreaType.D_AREA

				Case Else
					Return -1

			End Select

		End Function

		Function Get_bit(b As Byte, n_bit As Short) As Boolean

			Return (b And (1 << n_bit)) <> 0

		End Function

		Function Get_bit2(b As Byte, n_bit As Short) As Boolean

			Return (b And bit_mask(n_bit)) <> 0

		End Function

		Sub Set_bit2(ByRef b As Byte, n_bit As Short, b_val As Boolean)

			If b_val Then
				b = (b Or bit_mask(n_bit))
			Else
				b = (b And neg_bit_mask(n_bit))
			End If

		End Sub

#End Region

#Region " Metodi non utilizzati"
		'
		' Read Once position
		' returns 0 = OK ; > 0 error
		'
		Public Overrides Function DPOsition_ReadOnce() As Int16

			Return -1

		End Function

		Public Overrides Function DTool_set_read_range(n_start As Short, n_stop As Short) As Int16

			Dim nret As Int16 = -1
			Return nret

		End Function

		Public Overrides Function DTool_write_tool(n_tool_number As Short, Length_X As Double, Radius As Double, TipRadius_Z As Double,
								   DLength_X As Double, DTipRadius_Z As Double,
								   nDirection As Short, nType As Short, nH As Integer) As Int16

			Return -1

		End Function

		Public Overrides Function get_free_memory(n_zone As Int16) As Long

			Return -1

		End Function

#End Region

	End Class

End Namespace

