
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Imports EgtUILib
Imports EgtWPFLib

Namespace Num
   Public Class NumNC
      ' eredito la classe CN_generico
      Inherits CN_generico


#Region " Classes"
#End Region

#Region " Enum"

      Enum eDatatype As Short
         tpUnknown = -1      ' -1 unknown ...
         tpByte = 0          ' 0: signed byte - SINT8
         tpUByte = 1         ' 1: unsigned byte - UINT8
         tpShort = 2         ' 2: short integer - SINT16
         tpUShort = 3        ' 3: unsigned short integer - UINT16
         tpLong = 4          ' 4: long integer - SINT32
         tpULong = 5         ' 5: unsigned long integer - UINT32
         tpDouble = 6        ' 6: double floating point
         tpByteMap = 7       ' 7: byte bitmap - read as UINT8, show as BOOL
         tpWordMap = 8       ' 8: word bitmap - read as UINT16, show as BOOL
         tpLongMap = 9       ' 9: long bitmap - read as UINT32, show as BOOL   
         tpLLong = 10        ' 10: 64 bits integer long      
         tpByteLongMap = 11  ' 11: long bitmap - read as UINT32, show as BYTE       
      End Enum

      Enum eCnMode As Short
         AutoM = 0
         SingleM = 1
         MDI = 2
         Manual = 7
      End Enum

#End Region

#Region " Num objects"

      ' Instance the FXServer object variables

      Dim WithEvents objDRunTimeSystem As FXServer.DRunTimeSystem
      Dim WithEvents objDGroupManager As FXServer.DGroupManager
      Dim WithEvents objDReadELS As FXServer.DReadELS
      ' questa è classe che serve a scrivere i dati nel PLC
      Dim WithEvents objDPlcVariables As FXServer.DPlcVariables
      ' questa è la classe che serve a scrivere i dati nelle variabili E
      Dim WithEvents objDVariables As FXServer.DVariables
      Dim WithEvents objDReadTestExectime As FXServer.DReadTestExectime
      Dim WithEvents objDPosition As FXServer.DPosition
      Dim WithEvents objDNCKParameter As FXServer.DNCKParameter
      ' questa è la classe che serve a scrivere i comandi MDI (come ad esempio le funzioni M)
      Dim WithEvents objDMdiCommand As FXServer.DMdiCommand
      Dim WithEvents objDMainCncData As FXServer.DMainCncData

      Dim WithEvents objDNumDirectory As FXServer.DNumDirectory
      Dim WithEvents objDInterpo As FXServer.DInterpo

      Dim WithEvents objDGeneralFunctions As FXServer.DGeneralFunctions

      Dim WithEvents objDFeedOverride As FXServer.DFeedOverride
      Dim WithEvents objDReadSpindleComplete As FXServer.DReadSpindleComplete

      Dim WithEvents objDFileTransfer As FXServer.DFileTransfer

      Dim WithEvents objDTool As FXServer.DTool

      Dim WithEvents objDFunctionsG As FXServer.DFunctionsG

      'FXLib
      Dim WithEvents objSystemFunctions As FXLib.SystemFunctions
      Dim WithEvents objCncState As FXLib.CncState

      'FXLog
      Dim WithEvents objErrorHandler As FXLog.ErrorHandler
      Dim WithEvents objConfig As FXLog.Config

#End Region

#Region " local const"
      Private Const TIMEOUT As Short = 99
      Private Const SHORTSLEEPTIME As Short = 10
      Private Const LONGSLEEPTIME As Short = 40
      Private Const SHORTSLEEPCOUNT As Short = 20
      Private Const LONGSLEEPCOUNT As Short = 200

#End Region

#Region " local var"

      Private n_dTool_range_start As Short = 1
      Private n_dTool_range_stop As Short = 2

      Private AplCncNumber As New List(Of Short)
      Private AplChannel As New List(Of Short)
      Private AplSet As New List(Of Short)
      Private AplStatus As Short

      Private ExceptStatus As Short
      Private bSetModeDone As Boolean = False
      Private nSetModeResult As Short
      Private bDownloadFailed As Boolean = False
      Private bBytesTransfer As Boolean = False
      Private nDownloadErrorSeq As Integer
      Private nDownloadErrorReason As Integer

      Private lTransferedBytes As Long

      Private l_Gcodes_1 As ULong
      Private l_Gcodes_2 As ULong
      Private l_current_Gcodes As ULong

      Private m_nCnDataVarNum As Integer = 0
      Private m_nCnDataVarInd(NUM_DATA - 1) As Integer

      Private m_ConnectionError5000 As Boolean = False

#End Region

#Region "Constructor"

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

      Public Overrides Function Init() As Boolean

         ' Initialize and start Runtime System
         InitFxServer()

         Return n_state >= 2
      End Function

#End Region

#Region "Internal Methods"

      ' Init FXServer class DRunTimeSystem

      Private Sub InitFxServer()

         n_state = 0

         'Initialize the class DRunTimeSystem 
         objDRunTimeSystem = New FXServer.DRunTimeSystem()
         objDRunTimeSystem.Init()

         n_state = 1

         Dim Index As Integer = 0

         ' CONNESSIONE AL CN      Connessione in corso...
         Dim ConnectionWnd As New EgtMsgBox(Application.Current.MainWindow, EgtMsg(MSG_EGTMSGBOX + 7),
                                            EgtMsg(MSG_EGTMSGBOX + 8), True, EgtMsgBox.Buttons.NULL, EgtMsgBox.Icons.NULL, 1)
         ConnectionWnd.LoadingPrBr_Value = 5

         Dim ConnectionError As Integer = 0

         While (n_state < 2 Or m_ConnectionError5000) And Index < 20
            System.Threading.Thread.Sleep(500)  '   0.5 sec wait
            ConnectionWnd.LoadingPrBr_Value += 5
            Index += 1
            ' Costringo ad aggiornare UI
            UpdateUI()
         End While

         If n_state < 2 Or m_ConnectionError5000 Then
            ConnectionWnd.Text = EgtMsg(MSG_EGTMSGBOX + 9)     ' Connessione non riuscita
            ' Costringo ad aggiornare UI
            UpdateUI()
            System.Threading.Thread.Sleep(1500)  '   1.5 sec wait
            ConnectionWnd.Close()
         Else
            ConnectionWnd.Text = EgtMsg(MSG_EGTMSGBOX + 10)    ' Connessione riuscita
            ConnectionWnd.LoadingPrBr_Value = 100
            ' Costringo ad aggiornare UI
            UpdateUI()
            System.Threading.Thread.Sleep(1500)  '   1.5 sec wait
            ConnectionWnd.Close()
            ' Lancio della lettura delle variabili PLC
            set_Read_PLC_var()
         End If

         sz_versionRTS = objDRunTimeSystem.GetVersionRTS
         sz_ConnectionAddress = objDRunTimeSystem.GetConnectionAddress
         sz_AffaireNumber = objDRunTimeSystem.GetAffaireNumber(1).ToString

      End Sub

      ' Init FXServer classes for application

      Private Sub InitFxObjects()

         Dim n_ret As Short

         'Initialize FXServer class DGroupManager
         objDGroupManager = New FXServer.DGroupManager()
         objDGroupManager.CncNumber = 0
         objDGroupManager.AxisGroup = 0   ' seleziona gruppo assi CH1

         'Initialize FXServer class DMdiCommand
         objDMdiCommand = New FXServer.DMdiCommand()
         objDMdiCommand.Init(objDGroupManager.Handle)

         'Initialize FXServer class DMainCncData
         objDMainCncData = New FXServer.DMainCncData()
         objDMainCncData.Init(objDGroupManager.Handle)

         'Initialize FXServer class DGeneralFunctions
         objDGeneralFunctions = New FXServer.DGeneralFunctions()
         objDGeneralFunctions.Init(objDGroupManager.Handle)

         'Initialize FXServer class DFileTransfer
         objDFileTransfer = New FXServer.DFileTransfer
         objDFileTransfer.Init(objDGroupManager.Handle)



         ' --------'Initialize FXServer class DFeedOverride
         ' --------objDFeedOverride = New FXServer.DFeedOverride()
         ' --------objDFeedOverride.Init(objDGroupManager.Handle)


         ' Detect and identify the Flexium CNC type
         sz_CncFxIdentifier = objDMainCncData.GetCncIdentifier()
         '           _txtGetCncIdentification.Invoke(DirectCast(Sub() _txtGetCncIdentification.Text = CncFxIdentifier, MethodInvoker))
         EgtOutLog("Modello Flexium: " & sz_CncFxIdentifier)
         If sz_CncFxIdentifier = "Flexium 6" OrElse sz_CncFxIdentifier = "Flexium 8" OrElse sz_CncFxIdentifier = "Flexium 68" Then
            IsFlexiumPlus = False
         Else
            IsFlexiumPlus = True
         End If

         d_LinearAxisPrecision = CDbl(objDMainCncData.GetLinearPrecision())

         d_RotaryAxisPrecision = CDbl(objDMainCncData.GetRotatePrecision())

         '
         ' Initialize FXServer class DPosition
         '
         objDPosition = New FXServer.DPosition()

         '--objDPosition.Flag = 0
         '--objDPosition.ModeOP = 0
         '--objDPosition.FastUpdate = 0 ' Disable FastUpdate=0 To show the refresh time by Flag > 0



         objDPosition.Init(objDGroupManager.Handle)

         '--objDPosition.FireValues()

         n_validaxes = objDPosition.FireValidAxis()

         '
         ' Initialize FXServer class DReadELS
         '
         objDReadELS = New FXServer.DReadELS
         objDReadELS.Init(objDGroupManager.Handle)
         'Metodi
         'objDReadELS.Flag = 0
         'objDReadELS.Init(objDGroupManager.Handle)
         'objDReadELS.AddParameter("E80000", 1)
         '            objDReadELS.AddParameter("E80001", 2)
         '            objDReadELS.AddParameter("E80002", 3)
         'objDReadELS.AddParameter("E70000", 2)
         'objDReadELS.AddParameter("L100", 3)
         '
         ' dall' esterno call ReadEls_Add_Parameter ( "E80000", 1 )
         '

         objDVariables = New FXServer.DVariables

         objDVariables.Init(objDGroupManager.Handle, "E80000", 10)  ' 10 variables



         '                                short n_c = Convert.ToInt16(_Variables[9, 1].Text );
         '        short rc = objDVariables.WriteVariables2(2, objDGroupManager.Handle, "E80000", n_c);  // era 60001

         'Dim Paras() As String = New String(1) {"E80000", "E80001"}
         'Dim Paras As String = "E80000;E80001"
         'Dim Valus As Object
         'Dim MyRnd As New Random

         'Valus = MyRnd.Next(500) & ";" & MyRnd.Next(450, 1000)

         'objDVariables.WriteVariables(objDGroupManager.Handle, Paras, Valus)


         'Initialize FXServer class DPlcVariables

         objDPlcVariables = New FXServer.DPlcVariables

         objDPlcVariables.Flag = 3 ' flag = priority 3 = 0.3 sec
         objDPlcVariables.Init(objDGroupManager.Handle)


         'Initialize FXServer class DInterpo
         '
         objDInterpo = New FXServer.DInterpo
         objDInterpo.Init(objDGroupManager.Handle)


         'Initialize FXServer class DReadSpindleComplete

         ' Only available with FX Server >= 3.9
         ' objDReadSpindleComplete.ValueChanged2 += new FXServer.IDReadSpindleCompleteEvents_ValueChanged2EventHandler(objDReadSpindleComplete_ValueChanged2);

         objDReadSpindleComplete = New FXServer.DReadSpindleComplete
         n_ret = objDReadSpindleComplete.Init(objDGroupManager.Handle)


         ' Initialize FXServer class DTool

         objDTool = New FXServer.DTool
         n_ret = objDTool.Init(objDGroupManager.Handle)


         ' Initialize FXServer class DFunctionsG

         objDFunctionsG = New FXServer.DFunctionsG()
         objDFunctionsG.Init(objDGroupManager.Handle)

         ' Initialize FXLib SystemFunctions object

         'objSystemFunctions = New FXLib.SystemFunctions()
         '       objSystemFunctions.InitWindowsEvent()

         ' Load Language Values to List
         'objSystemFunctions.FireAllLanguages()


         'Initialize FXLog Config Objects

         ' --------objConfig = New FXLog.Config()
         ' --------objConfig.Init()


         ' Initialize FXLog ErrorHandler Objects

         objErrorHandler = New FXLog.ErrorHandler()

         ' --------' Initialisation config for testing
         ' --------' Accepting all messages
         ' --------' Consult the documentation for detailed information

         objErrorHandler.AllError = 1
         objErrorHandler.ErrorGlobal = 0
         objErrorHandler.SetChannel(0, 0)
         objErrorHandler.AcceptBootSysMessage(1)
         objErrorHandler.AcceptException(0)


         ' Initialize FXLib CncState objects

         ' --------objCncState = New FXLib.CncState()
         ' --------objCncState.Init()


         ' Initializes FXServer Component DNumDirectory
         ' works with the zone 0 (Customer content)

         ' --------objDNumDirectory = New FXServer.DNumDirectory()

         ' --------objDNumDirectory.Init(objDGroupManager.Handle)
         ' --------objDNumDirectory.ReadMemorySize()


      End Sub

      ' Close FXServer objects

      Private Sub CloseFxObjects()

         ' FXServer classes without method Close() to close the object => possibilty
         ' FXServer objectvariable can dispose from memory by following procedure

         ' !!!!!!!!!!!! aggiungere release di tutti gli oggetti creati !!!!

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDGroupManager)
         objDGroupManager = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDMdiCommand)
         objDMdiCommand = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDMainCncData)
         objDMainCncData = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDGeneralFunctions)
         objDGeneralFunctions = Nothing

         ' --------System.Runtime.InteropServices.Marshal.ReleaseComObject(objDFeedOverride)
         ' --------objDFeedOverride = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDPosition)
         objDPosition = Nothing

         ' --------System.Runtime.InteropServices.Marshal.ReleaseComObject(objDReadELS)
         ' --------objDReadELS = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDVariables)
         objDVariables = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDPlcVariables)
         objDPlcVariables = Nothing


         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDInterpo)
         objDInterpo = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDReadSpindleComplete)
         objDReadSpindleComplete = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDTool)
         objDTool = Nothing

         ' --------System.Runtime.InteropServices.Marshal.ReleaseComObject(objSystemFunctions)
         ' --------objSystemFunctions = Nothing

         ' --------System.Runtime.InteropServices.Marshal.ReleaseComObject(objConfig)
         ' --------objConfig = Nothing

         System.Runtime.InteropServices.Marshal.ReleaseComObject(objErrorHandler)
         objErrorHandler = Nothing

         ' --------System.Runtime.InteropServices.Marshal.ReleaseComObject(objCncState)
         ' --------objCncState = Nothing

         ' --------System.Runtime.InteropServices.Marshal.ReleaseComObject(objDNumDirectory)
         ' --------objDNumDirectory = Nothing

         ' FXServer dispose by the class method Close()

         MessageBox.Show("CloseFxObjects")
      End Sub

      Private Sub set_Read_PLC_var()

         Dim sz_var_names As New ArrayList
         Dim n_ret As Short

         'sz_var_names.Add("Application.IOCONFIG_GLOBALS.Flexium_NCK.RCNC.General.Mode")            ' modo   0:AUTO;1:SEQ;2:MDI;3:RAPIDO;4:SERCH;5:EDIT;6:TEST;7:MANUALE;
         'sz_var_names.Add("Application.IOCONFIG_GLOBALS.Flexium_NCK.RCNC.General.JogIncrement")    ' 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;
         'sz_var_names.Add("Application.IOCONFIG_GLOBALS.Flexium_NCK.WCNC.Channel[1].FeedOveride")  ' Potenziom. Feed  = *0.47059
         'sz_var_names.Add("Application.IOCONFIG_GLOBALS.Flexium_NCK.WCNC.Spindle[2].Override")     ' segnaposto per la speed override 
         'sz_var_names.Add("Application.GVL_HMI_OMAG.HMI_Vel_prog")                                 ' FEED
         'sz_var_names.Add("Application.GVL_HMI_OMAG.HMI_LabRPM")                                   ' Speed
         'sz_var_names.Add("Application.GVL_HMI_OMAG.HMI_LabAmper")                                 ' Ampère = *0.01

         ' Creo lista nomi variabili PLC da leggere
         m_nCnDataVarNum = 0
         For nI As Integer = 0 To NUM_DATA - 1
            If Not String.IsNullOrWhiteSpace(m_szCnDataVar(nI)) AndAlso m_szCnDataVar(nI).StartsWith("PLC,") Then
               ' inserisco nome variabile in lista di variabili da leggere, tolgo "PLC,"
               sz_var_names.Add(m_szCnDataVar(nI).Substring(4))
               ' imposto indice variabile
               m_nCnDataVarInd(m_nCnDataVarNum) = nI
               ' incremento numero di variabili da leggere
               m_nCnDataVarNum += 1
            End If
         Next

         ' Imposto lettura variabili
         n_ret = objDPlcVariables.ReadVariables(sz_var_names.ToArray())

         If n_ret <> 0 Then
            EgtOutLog("Errore 3 ReadVariables: " & n_ret.ToString)
         End If

      End Sub

#End Region


#Region " Events"

#Region "-- FXServer -- DRunTimeSystem EVENTS"

      '
      ' ' ------->> FXServer Event DRunTimeSystem ServerInitializationFinished
      '
      Private Sub objDRunTimeSystem_ServerInitializationFinished() Handles objDRunTimeSystem.ServerInitializationFinished

         ' Initialize the FXServer class for application

         InitFxObjects()

         sz_ServerInitStatus = "FXServer objects initialized !"
         sz_ServerReinitStatus = "FXServer no objects closed !"

         n_state = 2

      End Sub

      '
      ' ' ------->> FXServer Event DRunTimeSystem ServerReinitializationStarted     
      '
      Private Sub objDRunTimeSystem_ServerReinitializationStarted() Handles objDRunTimeSystem.ServerReinitializationStarted

         CloseFxObjects()

         sz_ServerInitStatus = "FXServer objects closed !"
         sz_ServerReinitStatus = "FXServer objects not initialized !"

         n_state = 3

      End Sub

      'Private Delegate Sub _RTSWaitForInteraction(ByVal state As Short, ByVal question As Short, ByVal Cnc As Short, ByVal extAdr As Short, ByVal AddStrings As Object)

      Private Sub objDRunTimeSystem_RTSWaitForInteraction(ByVal state As Short, ByVal question As Short, ByVal Cnc As Short,
                                                  ByVal extAdr As Short, ByVal AddStrings As Object) Handles objDRunTimeSystem.RTSWaitForInteraction


      End Sub

      Private Sub objDRunTimeSystem_CncApplikationLoaded(ByVal value As Short) Handles objDRunTimeSystem.CncApplikationLoaded

         'If Me.InvokeRequired Then
         'Invoke(New CncApplikationLoaded(AddressOf objDRunTimeSystem_CncApplikationLoaded), value)
         'Else
         '       lstData.Items.Add("CncApplikationLoaded--> " & value ' !!!!!!!!!!!!!!!!!!!!!!
         'End If

      End Sub

#End Region

#Region "-- FXServer -- DGroupManager EVENTS"

      '
      ' ' ------->> FXServer Event DGroupManager ErrorHandler
      '
      Private Sub objDGroupManager_ErrorHandler(szError As String, nTextNumber As Short) Handles objDGroupManager.ErrorHandler
         EgtOutLog("DGroupManager.ErrorHandler message : " & szError & "ErrorHandler number : " & nTextNumber.ToString)
         If nTextNumber = 5000 Then
            m_ConnectionError5000 = True
         End If
      End Sub
#End Region

#Region "-- FXServer -- DGeneralFunctions EVENTS"

      ' ' ------->> FXServer Event GeneralFunctions ProgramActivated

      Private Sub objDGeneralFunctions_ProgramActivated(nErrorcode As Short) Handles objDGeneralFunctions.ProgramActivated
         n_activate_error_code = nErrorcode ' 0 = OK ; > 0 errorcode
      End Sub

      ' ' ------->> FXServer Event GeneralFunctions OnCncStart

      Private Sub objDGeneralFunction_OnCncStart(nErrorcode As Short) Handles objDGeneralFunctions.OnCncStart
      End Sub

      ' ' ------->> FXServer Event GeneralFunctions OnCncStop

      Private Sub objDGeneralFunction_OnCncStop(nErrorcode As Short) Handles objDGeneralFunctions.OnCncStop
      End Sub

      ' ' ------->> FXServer Event GeneralFunctions OnCncReset

      Private Sub objDGeneralFunction_OnCncReset(nErrorcode As Short) Handles objDGeneralFunctions.OnCncReset
      End Sub

      ' ' ------->> FXServer Event GeneralFunctions CncModeWritten

      Private Sub objDGeneralFunction_CncModeWritten2(nHandle As Integer, nErrorcode As Short) Handles objDGeneralFunctions.CncModeWritten2

         bSetModeDone = True
         nSetModeResult = nErrorcode

      End Sub

      ' ' ------->> FXServer Event GeneralFunctions VariableWritten

      Private Sub objDGeneralFunction_VariableWritten(nErrorcode As Short) Handles objDGeneralFunctions.VariableWritten

         If nErrorcode <> 0 Then
            MessageBox.Show("DGeneralFunctions.VariableWritten :" + " " + nErrorcode.ToString())
         End If

      End Sub

      ' ' ------->> FXServer Event GeneralFunctions OnCncStop

      Private Sub objDGeneralFunction_OnSkipLevelWritten(iHandle As Integer, nErrorcode As Short) Handles objDGeneralFunctions.OnSkipLevelWritten
      End Sub


#End Region

#Region "-- FXServer -- DFileTransfer EVENTS"

      ' ' ------->> FXServer Event DFileTransfer Completed

      Private Sub objDFileTransfer_Completed(l_Handle As Integer) Handles objDFileTransfer.Completed

         bSetModeDone = True

      End Sub

      ' ' ------->> FXServer Event DFileTransfer TransferStarted

      Private Sub objDFileTransfer_TransferStarted(l_Handle As Integer) Handles objDFileTransfer.TransferStarted

      End Sub

      ' ' ------->> FXServer Event DFileTransfer Failed

      Private Sub objDFileTransfer_Failed(l_Handle As Integer, n_seq As Short, n_reason As Short) Handles objDFileTransfer.Failed

         bDownloadFailed = True
         nDownloadErrorSeq = n_seq
         nDownloadErrorReason = n_reason
      End Sub

      ' ' ------->> FXServer Event DFileTransfer BytesTransfered

      Private Sub objDFileTransfer_BytesTransfered(l_Handle As Integer, l_bytes As Integer) Handles objDFileTransfer.BytesTransfered

         If l_bytes > 0 Then
            bBytesTransfer = True
         Else
            bBytesTransfer = False
         End If
         lTransferedBytes += l_bytes
      End Sub


#End Region

#Region "-- FXServer -- DFeedOverride EVENTS"

      ' ' ------->> FXServer Event GeneralFunctions ValueChanged

      Private Sub objDFeedOverride_ValueChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDFeedOverride.ValueChanged

         Dim n, ni As Integer
         Dim index() As Object
         Dim values() As Object

         index = vtArrayIndex
         values = vtArrayValue

         For n = 0 To index.Length - 1

            ni = CInt(index(n))
            l_channel_override(ni) = CLng(values(n))
         Next

         b_feed_changed = True
      End Sub

#End Region

#Region "-- FXServer -- DPosition EVENTS"
      '
      ' ' ------->> FXServer Event DPosition PositionChanged   
      '
      Private Sub objDposition_PositionChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDPosition.PositionChanged

         Dim n, ni As Integer

         Dim index() As Object
         Dim values() As Object

         index = vtArrayIndex
         values = vtArrayValue

         If IsFlexiumPlus Then
            For n = 0 To index.Length - 1
               ni = CInt(index(n))
               If ni <= 5 Then
                  d_axis_position(ni) = CDbl(values(n)) / d_LinearAxisPrecision
               Else
                  d_axis_position(ni) = CDbl(values(n)) / d_RotaryAxisPrecision
               End If
            Next
         Else
            For n = 0 To index.Length - 1
               ni = CInt(index(n))
               d_axis_position(ni) = CDbl(CLng(values(n))) / d_LinearAxisPrecision
            Next
         End If

         If b_axis_events_enable Then MyBase.OnNewPositionData()

      End Sub

      Private Sub objDPosition_DeltaChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDPosition.DeltaChanged

         Dim n, ni As Integer

         Dim index() As Object
         Dim values() As Object

         index = vtArrayIndex
         values = vtArrayValue

         If IsFlexiumPlus Then
            For n = 0 To index.Length - 1
               ni = CInt(index(n))
               If ni <= 5 Then
                  d_axis_delta(ni) = CDbl(values(n)) / d_LinearAxisPrecision
               Else
                  d_axis_delta(ni) = CDbl(values(n)) / d_RotaryAxisPrecision
               End If
            Next
         Else
            For n = 0 To index.Length - 1
               ni = CInt(index(n))
               d_axis_delta(ni) = CDbl(CLng(values(n))) / d_LinearAxisPrecision
            Next
         End If

         If b_axis_events_enable Then MyBase.OnNewPosDeltaData()

      End Sub

      Private Sub objDPosition_EndposChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDPosition.EndposChanged
      End Sub

      Private Sub objDPosition_OffsetChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDPosition.OffsetChanged
      End Sub

      Private Sub objDPosition_ValidAxisChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDPosition.ValidAxisChanged

         Dim valid_i() As Object
         Dim valid_v() As Object

         valid_i = vtArrayIndex
         valid_v = vtArrayValue

         For n As Integer = 0 To valid_i.Length - 1
            Dim ni As Integer = CInt(valid_v(n))
            If ni = 0 Then
               b_axis_valid(n) = False
            Else
               b_axis_valid(n) = True
            End If
         Next

      End Sub

      Private Sub objDPosition_ValuesChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDPosition.ValuesChanged
      End Sub

      Private Sub objDPosition_ReadOncePositionChanged(lHandle As Integer, vtArrayValue As Object) Handles objDPosition.ReadOncePositionChanged
      End Sub

      Private Sub objDPosition_ReadOnceDeltaChanged(lHandle As Integer, vtArrayValue As Object) Handles objDPosition.ReadOnceDeltaChanged
      End Sub

#End Region

#Region "-- FXServer -- DReadELS EVENTS"

      ''
      '' ATTENZIONE : vengono sparati tutti e 3 gli eventi..... tenerne 1 solo !!! !!! !!!
      ''
#Region " smorto"
#If False Then
        Private Sub objDReadELS_ValueChanged(ByVal nHandle As Short, ByVal dValue As Double, ByVal nErrorcode As Short) Handles objDReadELS.ValueChanged

            Dim sza As String

            If (nHandle < 1 Or nHandle > MAX_VALUES) Then
                MsgBox(" Invalid handle in Validchanged : " + nHandle.ToString)
                Exit Sub
            End If


            If (nErrorcode <> 0) Then MsgBox(" Error in Validchanged : " & nErrorcode.ToString + " Handle : " + nHandle.ToString)

            Try
                sza = dValue.ToString

            Catch Ex As Exception
                MsgBox(Ex.Message)
            End Try


        End Sub
#End If
#End Region

      Private Sub objDReadELS_ValueChanged2(nHandle As Integer, dValue As Double, nerrorCode As Short) Handles objDReadELS.ValueChanged2

         If (nHandle < 1 Or nHandle > MAX_VALUES) Then
            MsgBox(" Invalid handle in Validchanged2 : " + nHandle.ToString)
            Exit Sub
         End If


         If (nerrorCode <> 0) Then MsgBox(" Error in Validchanged2 : " & nerrorCode.ToString + " Handle : " + nHandle.ToString)

         Try

            d_DReadELS_value = dValue
            n_DReadELS_handle = CShort(nHandle)

         Catch Ex As Exception
            MsgBox(Ex.Message)
         End Try

      End Sub

#Region " smorto"
#If False Then


        ' Only for FX Server >= 3.9.0.0 
        ' poi in realtà ritorna sempre tipo = -1 per cui è eguale alle altre.....
        Private Sub objDReadELS_ValueChanged3(nHandle As Integer, value As Object, DataType As Short, Writable As Short, nerrorCode As Short) Handles objDReadELS.ValueChanged3

            Dim edata_type As eDatatype
            Dim sValue As String

            edata_type = DataType

            If (nHandle < 1 Or nHandle > MAX_VALUES) Then
                MsgBox(" Invalid handle in Validchanged3 : " + nHandle.ToString)
                Exit Sub
            End If

            If (nerrorCode <> 0) Then MsgBox(" Error in Validchanged3 : " & nerrorCode.ToString + " Handle : " + nHandle.ToString)

            Try

                Select Case (edata_type)

                    Case eDatatype.tpByte ' tpByte : signed byte - SINT8
                        sValue = CType(value, SByte).ToString

                    Case eDatatype.tpUByte ' tpUByte : unsigned byte - UINT8
                        sValue = CType(value, Byte).ToString

                    Case eDatatype.tpShort ' tpShort : short integer - SINT16
                        sValue = CType(value, Short).ToString

                    Case eDatatype.tpUShort ' tpUShort 3: unsigned short integer - UINT16
                        sValue = CType(value, UShort).ToString

                    Case eDatatype.tpLong ' tpLong : long integer - SINT32
                        sValue = CType(value, Integer).ToString

                    Case eDatatype.tpULong ' tpULong : unsigned long integer - UINT32
                        sValue = CType(value, UInteger).ToString

                    Case eDatatype.tpDouble ' tpDouble : double floating point - DOUBLE
                        sValue = CType(value, Double).ToString

                    Case eDatatype.tpByteMap ' tpByteMap : byte bitmap - read as UINT8, show as BOOL
                        sValue = CType(value, Byte).ToString

                    Case eDatatype.tpWordMap ' tpWordMap : word bitmap - read as UINT16, show as BOOL
                        sValue = CType(value, UShort).ToString

                    Case eDatatype.tpLongMap ' tpLongMap : long bitmap - read as UINT32, show as BOOL   
                        sValue = CType(value, UInteger).ToString

                    Case eDatatype.tpLLong '  tpLLong : 64 bits integer long      
                        sValue = CType(value, Long).ToString

                    Case eDatatype.tpByteLongMap ' tpByteLongMap : long bitmap - read as UINT32, show as BYTE       
                        sValue = CType(value, UInteger).ToString

                    Case eDatatype.tpUnknown ' for flexium standard we receive No datatype .. we assume it is ???? bug ... we don't know ...
                        sValue = value.ToString()

                    Case Else

                        sValue = String.Empty
                        MsgBox("objDReadELS_ValueChanged3() : Unknown Datatype !")
                End Select

            Catch Ex As Exception

                MsgBox("objDReadELS_ValueChanged3 " & Ex.Message + " Handle : " + nHandle.ToString)

            End Try

        End Sub
#End If
#End Region

#End Region

#Region "-- FXServer -- DVariables EVENTS"

      Private Sub objDVariables_ValueChanged(vtArrayIndex As Object, vtArrayValues As Object) Handles objDVariables.ValueChanged2

         Dim index() As Object
         Dim values() As Object

         index = vtArrayIndex
         values = vtArrayValues

         If IsFlexiumPlus Then Exit Sub '  This event should not be used for Flexium plus as it returns wrong datatype .. (int instead of double for example)

         For n As Integer = 0 To index.Length - 1

            Dim ni As Integer = CInt(index(n))
            d_Dvariable_values(ni) = CDbl(CLng(values(n)))
         Next

         If b_axis_events_enable Then MyBase.OnNewVarChanged()

      End Sub

      Private Sub objDVariables_ValueChanged2(vtArrayIndex As Object, vtArrayValues As Object) Handles objDVariables.ValueChanged
         '
         ' probabilmente evento non sparato nei flexium non plus.....
         '
      End Sub

      Private Sub objDVariables_VariableWritten(nErrorCode As Short) Handles objDVariables.VariableWritten

         If (nErrorCode <> 0) Then
            MsgBox(" Error in objDVariables_VariableWritten2 : " & nErrorCode.ToString)

         Else
            ' mettere qualcosa per il completamento ok della scrittura
            b_Dvariable_changed = True
         End If

      End Sub

      Private Sub objDVariables_VariableWritten2(lHandle As Integer, nErrorCode As Short) Handles objDVariables.VariableWritten2

         If (lHandle <> 2 Or nErrorCode <> 0) Then
            MsgBox(" Error in objDVariables_VariableWritten2 : " & nErrorCode.ToString + " Handle : " + lHandle.ToString)

         Else
            ' mettere qualcosa per il completamento ok della scrittura
            b_Dvariable_changed = True
         End If

      End Sub

#End Region

#Region "-- FXServer -- DPlcVariables EVENTS"

      'Private Sub objDPlcVariables_AbortReadVariables() Handles objDPlcVariables.AbortReadVariables
      'End Sub

      'Private Sub objDPlcVariables_InvalidReadList(nErrorCode As Short) Handles objDPlcVariables.InvalidReadList
      'End Sub

      'Private Sub objDPlcVariables_ReadOnceInvalidReadList(lHandle As Integer, nErrorCode As Short) Handles objDPlcVariables.ReadOnceInvalidReadList
      'End Sub

      Private Sub objDPlcVariables_ReadOnceVariablesChanged(lHandle As Integer, value As Object) Handles objDPlcVariables.ReadOnceVariablesChanged
      End Sub

      Private Sub objDPlcVariables_ReadVariablesChanged(vtArrayIndex As Object, vtArrayValues As Object) Handles objDPlcVariables.ReadVariablesChanged

         Dim index() As Object
         Dim values() As Object

         index = vtArrayIndex
         values = vtArrayValues

         For n As Integer = 0 To index.Length - 1

            Dim ni As Integer = CInt(index(n))
            If ni >= m_nCnDataVarNum Then
               Continue For
            End If

            Select Case m_nCnDataVarInd(ni)
               Case CnData.Mode       ' (0) modo   0:AUTO;1:SEQ;2:MDI;3:RAPIDO;4:SERCH;5:EDIT;6:TEST;7:MANUALE;
                  nMachineMode = CInt(values(n))
               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(CLng(values(n))) ' d_DInterpo_Prog_Feed
               Case CnData.FeedOvr    ' (3) Potenziom. Feed  = * 0.47059
                  d_DInterpo_Feed_override = CDbl(CLng(values(n))) * 0.47059
                  b_feed_changed = True
               Case CnData.Speed      ' (4) Speed
                  d_spindle_eff(0) = CDbl(values(n))
               Case CnData.SpeedOvr   ' (5) Potenziom. speed  = ...
                  n_spindle_override(0) = CShort(Math.Round((CDbl(values(n)) * 50 / 255) + 50))
               Case CnData.Power      ' (6) Ampère = * 0.01
                  d_spindle_power = CDbl(CLng(values(n))) * 0.01
                  b_spindle_power_changed = True
               Case CnData.Spindle     ' (7) Stato rotazione mandrino
                  bSpindleState = CBool(values(n))
               Case CnData.Coolant     ' (8) Stato acqua
                  bCoolantState = CBool(values(n))
               Case CnData.Laser       ' (9) Stato laser punto
                  bLaserState = CBool(values(n))
               Case CnData.LaserTrac   ' (46) Stato laser tracciatura
                  bLaserTracState = CBool(values(n))
               Case CnData.PowerOvr    ' (10) valore assorbimento massimo mandrino con l'utensile corrente
                  bPowerOvr = CDbl(values(n))
                  b_spindle_power_changed = True
               Case CnData.InternalCoolant     ' (13) Stato acqua interna
                  bInternalCoolantState = CBool(values(n))
               Case CnData.ExternCoolant     ' (14) Stato acqua esterna
                  bExternCoolantState = CBool(values(n))
               Case CnData.CBAxes     ' (15) Stato ativazione assi c e b
                  bCBAxesState = CBool(values(n))
               Case CnData.AirBlow     ' (16) Stato soffio utensile
                  bAirBlowState = CBool(values(n))
               Case CnData.Home     ' (17) Stato home
                  bHomeState = CBool(values(n))
               Case CnData.TableUp     ' (18) Stato tavolo su
                  bTableUpState = CBool(values(n))
               Case CnData.TableDown     ' (19) Stato tavolo giu'
                  bTableDownState = CBool(values(n))
               Case CnData.DoorClosed     ' (20) Stato porte
                  nDoorClosedState = CInt(values(n))
               Case CnData.LimitZ     ' (21) Stato limitazione asse Z
                  bLimitZState = CBool(values(n))
               Case CnData.VacuumUp     ' (22) Stato ventosa su'
                  bVacuumUp = CBool(values(n))
               Case CnData.VacuumDown     ' (23) Stato ventosa giu'
                  bVacuumDown = CBool(values(n))
               Case CnData.Vacuum2Up     ' (24) Stato ventosa2 su'
                  bVacuum2Up = CBool(values(n))
               Case CnData.Vacuum2Down     ' (25) Stato ventosa2 giu'
                  bVacuum2Down = CBool(values(n))
               Case CnData.Vacuum1State     ' (26) Stato ventosa 1
                  bVacuum1State = CBool(values(n))
               Case CnData.Vacuum2State     ' (27) Stato ventosa 2
                  bVacuum2State = CBool(values(n))
               Case CnData.Vacuum3State     ' (28) Stato ventosa 3
                  bVacuum3State = CBool(values(n))
               Case CnData.Vacuum4State     ' (29) Stato ventosa 4
                  bVacuum4State = CBool(values(n))
               Case CnData.Vacuum5State     ' (30) Stato ventosa 5
                  bVacuum5State = CBool(values(n))
               Case CnData.Vacuum6State     ' (31) Stato ventosa 6
                  bVacuum6State = CBool(values(n))
               Case CnData.Vacuum135State     ' (32) Stato ventose 135
                  bVacuum135State = CBool(values(n))
               Case CnData.Vacuum246State     ' (33) Stato ventose 246
                  bVacuum246State = CBool(values(n))
               Case CnData.OpenAllState     ' (34) Stato apertura ventose
                  bOpenAllState = CBool(values(n))
               Case CnData.CloseAllState     ' (35) Stato chiusura ventose
                  bCloseAllState = CBool(values(n))
               Case CnData.Open123State     ' (36) Stato apertura ventose
                  bOpen123State = CBool(values(n))
               Case CnData.Open456State     ' (37) Stato apertura ventose
                  bOpen456State = CBool(values(n))
               Case CnData.Close123State     ' (38) Stato chiusura ventose
                  bClose123State = CBool(values(n))
               Case CnData.Close456State     ' (39) Stato chiusura ventose
                  bClose456State = CBool(values(n))
               Case CnData.BlowState     ' (40) Stato soffio ventose
                  bBlowState = CBool(values(n))
               Case CnData.VacuumOn     ' (41) Stato aspirazione ventose acceso
                  bVacuumOn = CBool(values(n))
               Case CnData.BypassState     ' (42) Stato bypass
                  bBypassState = CBool(values(n))
               Case CnData.Vacuum0     ' (43) Stato rotazione ventosa 0
                  bVacuum0 = CBool(values(n))
               Case CnData.Vacuum90     ' (44) Stato rotazione ventosa 0
                  bVacuum90 = CBool(values(n))
               Case CnData.VacuumOff     ' (45) Stato aspirazione ventose spento
                  bVacuumOff = CBool(values(n))

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

               Case CnData.Parking     ' (52)
                  bParkingState = CBool(values(n))
               Case CnData.EnableZone     ' (53)
                  nEnableZone = CInt(values(n))
               Case CnData.EnablePC     ' (54)
                  nEnablePc = CInt(values(n))

            End Select
         Next

      End Sub

      Private Sub objDPlcVariables_Symbols(Name As Object, TypeId As Object, TypeName As Object, size As Object, Access As Object) Handles objDPlcVariables.Symbols
      End Sub

      'Private Sub objDPlcVariables_VariablesWritten(nErrorCode As Integer) Handles objDPlcVariables.VariablesWritten
      'End Sub

      Private Sub objDPlcVariables_VariablesWritten2(lHandle As Integer, nErrorCode As Integer) Handles objDPlcVariables.VariablesWritten2

      End Sub

#End Region

#Region "-- FXServer -- DInterpo EVENTS"
      '
      ' ' ------->> FXServer Event DInterpo MemorySize  
      '
      Private Sub objDInterpo_ValuesChanged(vtArrayValue As Object) Handles objDInterpo.ValuesChanged

         '0 = "Interpolation speed", 1= "Not used", 2 = "Distance to go", 3 = "Programmed feedrate", 4 = "Feed override [%]"

         Dim values() As Object

         values = vtArrayValue

         For n As Integer = 0 To values.Length - 1
            d_DInterpo_values(n) = CDbl(CLng(values(n)))
         Next

         d_DInterpo_Prog_Feed = d_DInterpo_values(3)
         'd_DInterpo_Feed_override = d_DInterpo_values(4)
         b_feed_changed = True
      End Sub

#End Region

#Region "-- FXServer -- DReadSpindleComplete EVENTS"
      '
      ' ' ------->> FXServer Event DReadSpindleComplete ValueChanged  
      '
      Private Sub objDReadSpindleComplete_ValueChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDReadSpindleComplete.ValueChanged

         Dim n_spindle As Short, n_info As Short

         Dim index() As Object
         Dim values() As Object

         index = vtArrayIndex
         values = vtArrayValue

         For n As Integer = 0 To index.Length - 1

            n_spindle = CShort(index(n) \ 10)
            n_info = CShort(index(n) Mod 10)

            If (n_spindle > (MAX_VALUES - 1) Or n_info > 10) Then Exit For

            Select Case n_info
               Case 2 ' % override
                  'n_spindle_override(n_spindle) = CShort(values(n))
               Case 3 ' prog speed
                  d_spindle_prog(n_spindle) = CDbl(values(n))
               Case 4 ' meas. speed
                  d_spindle_eff(n_spindle) = CDbl(values(n))
               Case Else
            End Select

         Next

         b_spindle_data_changed = True

      End Sub

#End Region

#Region "-- FXServer -- DTool EVENTS"
      '
      ' ' ------->> FXServer Event DTool ToolDataChanged  
      '
      Private Sub objDTool_ToolDataChanged(vtArrayIndex As Object, vtArrayValue As Object) Handles objDTool.ToolDataChanged

         ' Read the change of the Tools data

         Dim n_tool As Short, n_data As Short, l_value As Long, nt As Short

         Dim index() As Object
         Dim values() As Object

         index = vtArrayIndex
         values = vtArrayValue

         For n As Integer = 0 To index.Length - 1

            Try
               n_tool = CShort(index(n) \ 10)
               n_data = CShort(index(n) Mod 10)

               nt = n_tool - n_dTool_range_start
               l_value = CLng(values(n))

               If (n_tool < n_dTool_range_start Or n_tool > n_dTool_range_stop Or n_data > 7) Then Continue For

               Select Case n_data

                  Case 0 ' Tool type ( Mill / lathe )

                     If l_value = 0 Then
                        Tools(nt).type = "M"c
                     Else
                        Tools(nt).type = "L"c
                     End If

                  Case 1  ' lenght / X
                     Tools(nt).lenght = CDbl(l_value) / 1000.0

                  Case 2 ' radius / Z
                     Tools(nt).radius = CDbl(l_value) / 1000.0

                  Case 3 ' Cut radius / Cut tip
                     Tools(nt).tip = CDbl(l_value) / 1000.0

                  Case 4 ' D lenght
                     Tools(nt).D_lenght = CDbl(l_value) / 1000.0

                  Case 5 ' D_radius
                     Tools(nt).D_radius = CDbl(l_value) / 1000.0

                  Case 6 ' nose dir
                     Tools(nt).nose_dir = "C" & (l_value).ToString

                  Case 7 ' toolcom
                     Tools(nt).comp_num = CShort(l_value)

                  Case Else

               End Select
            Catch ex As Exception
               MsgBox(" Error in objDTool_ToolDataChanged : " & ex.Message)
            End Try

         Next

         b_Tool_data_changed = True
      End Sub
      '
      ' ' ------->> FXServer Event DTool ToolDataWritten  
      '
      Private Sub objDTool_ToolDataWritten(l_Handle As Integer, n_error_code As Short) Handles objDTool.ToolDataWritten

         If l_Handle <> 1 Or n_error_code <> 0 Then
            MessageBox.Show("Error: objDTool_ToolDataWritten handle : " & l_Handle.ToString & " error : " & n_error_code.ToString())
         End If

      End Sub
      '
      ' ' ------->> FXServer Event DTool DynamicToolDataWritten  
      '
      Private Sub objDTool_DynamicToolDataWritten(l_Handle As Integer, n_error_code As Short) Handles objDTool.DynamicToolDataWritten

         If l_Handle <> 2 Or n_error_code <> 0 Then
            MessageBox.Show("Error: objDTool_DynamicToolDataWritten handle : " & l_Handle.ToString & " error : " & n_error_code.ToString())
         End If

      End Sub

#End Region

#Region "-- FXServer -- DFunctionsG EVENTS"

      ' ' ------->> FXServer Event DFunctionsG GFunctionsChanged  

      Private Sub objDFunctionsG_GFunctionsChanged(vtArrayValue As Object) Handles objDFunctionsG.GFunctionsChanged

         ' Read the change of the G codes

         Dim values() As Object

         values = vtArrayValue

         l_Gcodes_1 = CULng(values(0))
         l_Gcodes_2 = CULng(values(1))
         l_current_Gcodes = CULng(values(2))

      End Sub

#End Region

#Region "-- FXServer -- DNumDirectory EVENTS"
      '
      ' ' ------->> FXServer Event DNumDirectory MemorySize  
      '
      Private Sub objDNumDirectory_MemorySize(vtArrayIndex As Object, vtArrayValue As Object) Handles objDNumDirectory.MemorySize
      End Sub
#End Region

#Region "-- FXServer -- DMdiCommand EVENTS"

      ' ------->> FXServer Event DMdiCommand CommandWritten   

      Private Sub objDMdiCommand_CommandWritten(nErrorcode As Short) Handles objDMdiCommand.CommandWritten

         bSetModeDone = True
         nSetModeResult = nErrorcode

         sz_ManualDataInput = ""    'Azzero stringa MDI

      End Sub

#End Region

#Region "-- FXLog -- ErrorHandler EVENTS"

      '
      ' ' ------->> FXLog Event ErrorHandler ErrorOnCnc .....     
      '
      Private Sub objErrorHandler_ErrorOnCnc(cnc As Short, channel As Short, nset As Short) Handles objErrorHandler.ErrorOnCnc

         '        AplCncNumber.Add(cnc)
         '       AplChannel.Add(channel)
         '       AplSet.Add(nset)
      End Sub

      Private Sub objErrorHandler_ErrorOnOtherChannel(status As Short) Handles objErrorHandler.ErrorOnOtherChannel
         AplStatus = status
      End Sub

      Private Sub objErrorHandler_Exception(status As Short) Handles objErrorHandler.Exception
         ExceptStatus = status
      End Sub


      Private Sub objErrorHandler_ErrorFromActiveCnc2 _
            (CncNumber As Short, numberOfError As Short, ErrorTyp As Object, ErrorIndex As Object, ErrorNumber As Object, ErrorLine As Object, ErrorMessage As Object, ErrorAdditional As Object) _
            Handles objErrorHandler.ErrorFromActiveCnc2

         Dim vErrorType(0 To 10) As Object
         Dim vErrorIndex(0 To 10) As Object
         Dim vErrorNumber(0 To 10) As Object
         Dim vNumberError As Object
         Dim vExtNumberError As Object = Nothing
         Dim vErrorLine(0 To 10) As Object
         '         Dim vErrorMessage(0 To 10) As Object
         Dim vErrorAdditional(0 To 10) As Object

         Dim sMessaggio As String
         'Dim sMessaggio1 As String
         Dim i As Integer
         'Dim nLinee As Integer
         Dim ClassPLCMsg As Object

         b_PLC_error = False
         b_NC_error = False
         SyncLock Me
            sz_NC_error_messages.Clear()
         End SyncLock

         If numberOfError <> 0 Then


            For i = 0 To (numberOfError - 1)

               vErrorIndex(i) = ErrorIndex(i)         ' CNmsg indica il Chx , DriveError e Drive Warning indica ind @ asse

               vErrorType(i) = ErrorTyp(i)            'Tipo errore

               vErrorNumber(i) = Str(ErrorNumber(i))  'CNC msg : Numero errore

               vErrorLine(i) = Str(ErrorLine(i))      'Linea ISO
               '              vErrorMessage(i) = ErrorMessage(i)     'Testo messaggio CNC

               'inizializzo biserrormessage
               bIsErrorMessage = False

               Select Case vErrorType(i)

                  Case 0
                     'CNC boot message
                     'sMessaggio = objSystemFunctions.GetSysErrorText(vErrorNumber(i)) ' Recupero il testo del messaggio ????
                     sMessaggio = "Boot: " & ErrorMessage(i)

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

                  Case 1
                     'CNC sys warning
                     sMessaggio = "All.Sys: " & vErrorNumber(i) & " " & ErrorMessage(i)

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

                  Case 2
                     'CNC msg
                     vNumberError = vErrorNumber(i) And &HFFFF

                     If IsFlexiumPlus Then
                        vExtNumberError = (vNumberError And &HFFFF0000) / 2 ^ 16  ' mettere sotto ..............!!!!!!
                     End If

                     If Not IsFlexiumPlus Then
                        ' Flexium 6 / 68 NCK
                        If vErrorLine(i) = 0 Then
                           sMessaggio = "CN: " & vNumberError & " " & " " & ErrorMessage(i)
                        Else
                           sMessaggio = "CN: " & vNumberError & " N" & vErrorLine(i) & " " & ErrorMessage(i)
                        End If
                     Else
                        ' Flexium 6+ / 68+ NCK ???????????????????? da verificare ?????????????????????????????
                        If vErrorLine(i) = 0 And vErrorAdditional(i) = 0 Then
                           sMessaggio = "CN: " & vNumberError & " Ext" & vExtNumberError & " " & ErrorMessage(i)
                        ElseIf vErrorLine(i) = 0 And vErrorAdditional(i) <> 0 Then
                           sMessaggio = "CN: " & vNumberError & " Ext" & vExtNumberError & " L" & vErrorAdditional(i) & ErrorMessage(i)
                        ElseIf vErrorLine(i) <> 0 And vErrorAdditional(i) = 0 Then
                           sMessaggio = "CN: " & vNumberError & " Ext" & vExtNumberError & " N" & vErrorLine(i) & " " & ErrorMessage(i)
                        Else
                           sMessaggio = "CN: " & vNumberError & " Ext" & vExtNumberError & " N" & vErrorLine(i) & " L" & vErrorAdditional(i) & ErrorMessage(i)
                        End If
                     End If

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

                  Case 3
                     'Drive Error
                     vNumberError = vErrorNumber(i) And &HFFFF0000
                     vNumberError = vNumberError / 2 ^ 16
                     vExtNumberError = vErrorNumber(i) - (vNumberError * 2 ^ 16) '--> vNumberError(i) AND &hFFFF

                     sMessaggio = "Azionamento: " & "Asse " & vErrorIndex(i) & " Errore: " & vNumberError & " Ext " & vExtNumberError & " " & ErrorMessage(i)

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

                  Case 5
                     'Communication Message
                     'sMessaggio = objFXLib_SystemFunctions.GetUniteError(vNumberError) ' Recupero il testo del messaggio  ????
                     sMessaggio = "COMM: " & vErrorNumber(i) & " " & ErrorMessage(i)

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

                  Case 6, 7, 8, 9, 10, 11, 12, 13
                     'PLC msg Reaction Class 1->8
                     ClassPLCMsg = vErrorType(i) - 5
                     sMessaggio = "PLC: " & vErrorNumber(i) & " Classe: " & ClassPLCMsg & " " & ErrorMessage(i) ' Recupero 1'riga del testo del messaggio in ../Language/xx/...

                     'For nLinee = 1 To 10            ' verifico se ho altre righe di testo
                     'sMessaggio1 = objSystemFunctions.GetPlcErrorText(vErrorNumber(i), nLinee)
                     'If sMessaggio1 = "" Then
                     'Exit For
                     'End If
                     '                    sz_NC_error_messages.Add(sMessaggio)
                     '                     sMessaggio = sMessaggio1
                     '                   Next nLinee

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

                  Case 20
                     'HMI msg
                     'sMessaggio = objSystemFunctions.GetHmiMessageText(vErrorNumber(i))  ' Recupero il testo del messaggio ????
                     sMessaggio = "HMI: " & vErrorNumber(i) & " " & ErrorMessage(i)
                     bIsErrorMessage = False
                  Case 21
                     'User msg
                     'sMessaggio = objSystemFunctions.GetUserMessageText(vErrorNumber(i))  ' Recupero il testo del messaggio ????
                     sMessaggio = "User: " & vErrorNumber(i) & " " & ErrorMessage(i)

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

                  Case 22
                     'RTS msg
                     '               sMessaggio = objSystemFunctions.GetRunTimeSystemError(vErrorNumber(i))  ' Recupero il testo del messaggio ????
                     sMessaggio = "RTS: " & vErrorNumber(i) & " " & ErrorMessage(i)
                     bIsErrorMessage = True
                  Case 23
                     'Drive Warning
                     sMessaggio = "Azionamento: " & "Asse " & vErrorIndex(i) & " Avviso: " & vErrorNumber(i) & ": " & ErrorMessage(i)

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

                  Case Else
                     sMessaggio = "Type ??: " & vErrorNumber(i) & " " & ErrorMessage(i)

                     'imposto flag errore, non messaggio generico
                     If Not bIsErrorMessage Then
                        bIsErrorMessage = True
                     End If

               End Select
               SyncLock Me
                  sz_NC_error_messages.Add(sMessaggio)
               End SyncLock
            Next i

            b_NC_error = True
         End If

      End Sub

#End Region

#Region "-- FXLib -- SystemFunctions EVENTS"

      '
      ' ' ------->> FXLib Event SystemFunctions LanguageData     
      '
      Private Sub objSystemFunctions_LanguageData(index As Short, shortName As String, languageName As String) Handles objSystemFunctions.LanguageData
      End Sub
#End Region

#Region "-- FXLib -- CncState EVENTS"
      '
      ' ' ------->> FXLib Event CncState ConfigUpdated ....     
      '
      Private Sub objCncState_ConfigUpdated() Handles objCncState.ConfigUpdated
      End Sub

      Private Sub objCncState_ValueChanged(nc As Short, Variable As String, value As Integer) Handles objCncState.ValueChanged
      End Sub

      Private Sub objCncState_NotHomed(nc As Short, value As Integer) Handles objCncState.NotHomed
      End Sub

      Private Sub objCncState_IndependentChannels(nc As Short, indep As Short) Handles objCncState.IndependentChannels
      End Sub

      Private Sub objCncState_HMIValueChange(var As String, value As Integer) Handles objCncState.HMIValueChange
      End Sub
#End Region

#End Region


#Region " Metodi pubblici"

      Public Overrides Function Stop_Connection() As Boolean
         Return True
      End Function


      Public Overrides Sub ReadEls_Add_Parameter(sz_var As String, n_par As Short)

         Dim nRet As Int16 = objDReadELS.AddParameter(sz_var, n_par)

      End Sub
      '
      '
      ' call DVariables_WriteVariables("E80000;E80001" , "1;2" )

      Public Overrides Sub DVariables_WriteVariables(sz_parameters As String, sz_values As String)

         Dim Valus As Object = sz_values

         Dim n_ret As Short

         n_ret = objDVariables.WriteVariables(objDGroupManager.Handle, sz_parameters, Valus)

      End Sub

      Public Overrides Sub DVariables_WriteVariables2(sz_parameters As String, sz_values As String)

         Dim Valus As Object = sz_values

         objDVariables.WriteVariables2(2, objDGroupManager.Handle, sz_parameters, Valus)

      End Sub

      Public Overrides Sub DPlcVariables_WriteVariables(sz_var_names As String, sz_values As String)
         Dim value As Short = 0
         If Not Short.TryParse(sz_values, value) Then
            If Not IsNothing( sz_values) then
               EgtOutLog("Write variable: " & sz_var_names & ", value:" & sz_values & " failed!")
            Else
               EgtOutLog("Write variable: " & sz_var_names & ", value:nothing failed!")
            End If
            Return
         End If
         Dim _ret As Short = objDPlcVariables.WriteVariables(sz_var_names, value)
         If _ret <> 0 Then
            EgtOutLog("Scrittura " & sz_var_names & " fallita")
         Else
            EgtOutLog("Scrittura " & sz_var_names & " riuscita")
         End If
      End Sub

      '' Funzione che legge una variabile dal CN
      'Public Function DVariables_ReadOnce(VariableName As String, ByRef Value As Int16) As Boolean

      '   Dim nRet As Integer = objDVariables.ReadOnce(2, objDGroupManager.Handle, VariableName, 1)
      '   Return If(nRet <> 0, True, False)
      'End Function

      Public Overrides Function MDI_command() As Short

         Dim nTimeOut As Integer = 0
         bSetModeDone = False

         Dim n_ret As Int16 = objDMdiCommand.ExecuteCommand(sz_ManualDataInput)

         If n_ret <> 0 Then
            EgtOutLog("Error Execute MDI Command : " + n_ret.ToString())
            Return n_ret
         End If

         While Not bSetModeDone And nTimeOut < SHORTSLEEPCOUNT
            System.Threading.Thread.Sleep(SHORTSLEEPTIME)
            nTimeOut += 1
         End While
         If Not bSetModeDone Then
            EgtOutLog("Errore eseguo comando MDI: " & TIMEOUT)
            Return TIMEOUT   'Errore di timeout
         End If
         If nSetModeResult <> 0 Then
            EgtOutLog("Errore 2 eseguo comando MDI: " & nSetModeResult)
         End If
         Return nSetModeResult

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

         Dim l_glbPartProgramNumber As Long, n_ret As Short

         l_glbPartProgramNumber = Convert.ToInt32(n_part_program)
         l_glbPartProgramNumber = l_glbPartProgramNumber * 10

         n_ret = objDGeneralFunctions.ActivateProgram(l_glbPartProgramNumber, 0)

         Return n_ret

      End Function
      '
      ' Set DPOsition Mode OP/OM
      '
      Public Overrides Sub set_OP_OM(n As Short)
         objDPosition.ModeOP = n
         objDPosition.FireValues()
      End Sub
      '
      ' Read Once position
      ' returns 0 = OK ; > 0 error
      '
      Public Overrides Function DPOsition_ReadOnce() As Int16

         Return objDPosition.ReadOnce(1, objDGroupManager.Handle, objDPosition.ModeOP)

      End Function
      '
      ' Set Cycle Start
      '
      Public Overrides Function DGeneralFunctions_CycleStart() As Int16
         objDGeneralFunctions.CncStart()
         Return 0
      End Function
      '
      ' Set Feed Hold
      '
      Public Overrides Function DGeneralFunctions_FeedHold() As Int16
         objDGeneralFunctions.CncStop()
         Return 0
      End Function
      '
      ' Set NC Reset
      '
      Public Overrides Function DGeneralFunctions_Reset() As Int16
         objDGeneralFunctions.CncReset()
         Return 0
      End Function

      Public Overrides Function DGeneralFunctions_WriteCncMode(nmode As Short) As Int16

         Dim nHandle As Integer = 57  'Numero a caso
         Dim ngroup0 As Short = 0
         Dim nTimeOut As Integer = 0
         bSetModeDone = False
         objDGeneralFunctions.WriteCncMode2(nHandle, nmode, ngroup0)
         While Not bSetModeDone And nTimeOut < SHORTSLEEPCOUNT
            System.Threading.Thread.Sleep(SHORTSLEEPTIME)
            nTimeOut += 1
         End While
         If Not bSetModeDone Then
            EgtOutLog("Errore cambio modalità in MDI: " & TIMEOUT)
            Return TIMEOUT   'Errore di timeout
         End If
         If nSetModeResult <> 0 Then
            EgtOutLog("Errore 2 cambio modalità in MDI: " & nSetModeResult)
         End If
         Return nSetModeResult

      End Function

      Public Overrides Function Write_var_1(sz_par As String, lvalue As Long) As Int16

         Dim n_ret As Short

         n_ret = objDGeneralFunctions.WriteVariable(sz_par, lvalue)

         If n_ret <> 0 Then
            EgtOutLog("error from objDGeneralFunctions.WriteVariable" & n_ret.ToString)
         End If

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


         Dim n_ret As Short
         Dim n_FileDelete As Short = 1, n_IgnoreMsgZone As Short = 0

         Dim lHandle As Long = 10 ' ??

         n_ret = objDFileTransfer.FileDownload2(lHandle, sz_NC_filename, sz_PC_filename, "", n_FileDelete, n_IgnoreMsgZone)

         If n_ret <> 0 Then
            EgtOutLog("Error: FileDownload2 error : " + n_ret.ToString())
            Return n_ret
         End If

         Return Manage_Transfer_NC_prog()

      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 n_ret As Short
         Dim lHandle As Long = 20 ' ??

         n_ret = objDFileTransfer.FileUpload(lHandle, sz_NC_filename, sz_PC_filename, "")

         If n_ret <> 0 Then
            EgtOutLog("Error: FileUpload error : " & n_ret.ToString())
            Return n_ret
         End If

         Return Manage_Transfer_NC_prog()

      End Function

      Public Overrides Function Delete_NC_prog(sz_NC_filename As String) As Int16

         Dim n_ret As Short
         Dim lHandle As Long = 20 ' ??

         n_ret = objDFileTransfer.FileDelete(lHandle, sz_NC_filename, "")

         If n_ret <> 0 Then
            EgtOutLog("Error: FileDelete error : " & n_ret.ToString())
            Return n_ret
         End If

         Return Manage_Transfer_NC_prog()

      End Function

      Private Function Manage_Transfer_NC_prog() As Int16

         Dim nTimeOut As Integer = 0
         Dim n_ret As Short

         bSetModeDone = False
         bDownloadFailed = False
         nDownloadErrorSeq = 0
         nDownloadErrorReason = 0

         n_ret = objDFileTransfer.StartTransfer()

         If n_ret <> 0 Then
            EgtOutLog("Error: StartTransfer error : " + n_ret.ToString())
            Return n_ret
         End If

         While Not bDownloadFailed And nTimeOut < LONGSLEEPCOUNT And Not bSetModeDone
            If bBytesTransfer Then
               nTimeOut = 0
               bBytesTransfer = False
            End If
            System.Threading.Thread.Sleep(LONGSLEEPTIME)
            nTimeOut += 1
         End While
         If bDownloadFailed Then
            EgtOutLog("Errore download file: " & nDownloadErrorSeq & " " & nDownloadErrorReason)
            Return nDownloadErrorSeq
         End If
         If nTimeOut >= LONGSLEEPCOUNT Then
            EgtOutLog("Errore download file: Timeout")
            Return nDownloadErrorSeq
         End If
         Return nDownloadErrorSeq

      End Function

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

         Dim n_ret As Short

         n_dTool_range_start = n_start
         n_dTool_range_stop = n_stop

         n_ret = objDTool.SetToolRange(n_start, n_stop)

         If n_ret <> 0 Then
            EgtOutLog("Error: DTool_set_red_range error : " & n_ret.ToString())
         End If
         Return n_ret

      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 Short

         Dim n_ret As Short, l_handle As Long = 1

         n_ret = objDTool.WriteToolCorr2(n_tool_number, (Length_X * 1000.0), (Radius * 1000.0), (TipRadius_Z * 1000.0), (DLength_X * 1000.0), (DTipRadius_Z * 1000.0),
         nDirection, nType, nH, objDTool.Flag, l_handle)

         If n_ret <> 0 Then
            EgtOutLog("Error: DTool_write_tool error : " & n_ret.ToString())
         End If
         Return n_ret

      End Function

      Public Overrides Function Is_G24_active() As Boolean
         Return ((l_Gcodes_2 And &H800000) <> 0)
      End Function

      Public Overrides Function Is_G26_active() As Boolean
         Return ((l_Gcodes_2 And &H100) <> 0)
      End Function

      Public Overrides Function Is_G71_active() As Boolean
         Return ((l_Gcodes_2 And &H40) <> 0)
      End Function

#End Region

   End Class

End Namespace
