Imports EgtBEAMWALL.Core
Imports EgtBEAMWALL.Core.ConstMachComm
Imports EgtUILib
Imports EgtWPFLib5

Public Class NUMAxiumComm

   Enum CNMode As Integer
      AUTO = 0
      SINGLE_ = 1
      MDI = 2
      MANUAL = 7
   End Enum

   Private m_MachManaging As MachManaging
   Friend ReadOnly Property MachManaging As MachManaging
      Get
         Return m_MachManaging
      End Get
   End Property

   Public ReadOnly Property bIsTransferActive As Boolean
      Get
         Return If(Not IsNothing(objDFileTransfer), objDFileTransfer.IsTransferActive(), False)
      End Get
   End Property

   'Private objDRunTimeSystem As FXServer.DRunTimeSystem
   Private WithEvents objDGroupManager As APServer.DGroupManager
   Private WithEvents objDGeneralFunction As APServer.DGeneralFunctions
   Private WithEvents objDMainCncData As APServer.DMainCncData
   Private WithEvents objErrorHandler As APLog.ErrorHandler
   Private WithEvents objDReadELS As APServer.DReadELS
   Private WithEvents objDReadPlcVarList As APServer.DReadPlcVarList
   Private WithEvents objDFileTransfer As APServer.DFileTransfer
   Private WithEvents objDPosition As APServer.DPosition
   Private WithEvents objDMdiCommand As APServer.DMdiCommand
   Private WithEvents objDVariables As APServer.DVariables
   Private WithEvents objDCncMode As APServer.DCncMode
   Private WithEvents objDReadOperatorMessage As APServer.DReadOperatorMessage

   Private m_CNCVersion As String = ""
   Private _PartProgramNumber As Single
   Private _CNCAxisChannelArray As String() = New String() {"Channel 1", "Channel 2"}
   Private m_ChannelList As New List(Of String)
   ' Arraylist for read out the messages
   Private m_ReadFXMessages As New List(Of ReadMessages)
   Private m_ReadOperatorMessages As New List(Of ReadMessages)
   ' lista variabili in lettura
   Private Shared m_ReadingVars(100) As CommVar
   Private m_BytesTransferedCounter As Integer
   Private m_LinearAxisPrecision As Integer

   Public Sub New(MachManaging As MachManaging)
      m_MachManaging = MachManaging
   End Sub

#Region "METHODS"

   Friend Sub InitFxServer()
   End Sub

   Friend Sub InitFxObjects()
      objDGroupManager = CreateObject("APServer.DGroupManager")
      AddHandler objDGroupManager.ErrorHandler, AddressOf objDGroupManager_ErrorHandler
      AddHandler objDGroupManager.AssignmentChanged, AddressOf objDGroupManager_AssignmentChanged
      objDGroupManager.CncNumber = 0
      objDGroupManager.AxisGroup = 0

      objDMainCncData = CreateObject("APServer.DMainCncData")
      Dim s = objDMainCncData.Init(objDGroupManager.Handle)
      m_LinearAxisPrecision = objDMainCncData.GetLinearPrecision()
      Dim CncFxIdentifier As String = objDMainCncData.GetCncIdentifier()
      EgtOutLog("CncFxIdentifier: " & CncFxIdentifier)

      m_CNCVersion = objDMainCncData.GetCncVersion()

      ' Initialize for Channel Change
      Dim CncGroupNumber As Integer = objDMainCncData.GetCncGroupNumber()
      Dim PlcGroupNumber As Integer = objDMainCncData.GetPlcGroupNumber()

      Dim sumChannels As Integer = 0
      sumChannels = PlcGroupNumber + CncGroupNumber
      For i = 1 To sumChannels
         m_ChannelList.Add(i)
      Next

      objDGeneralFunction = CreateObject("APServer.DGeneralFunctions")
      AddHandler objDGeneralFunction.ProgramActivated, AddressOf objDGeneralFunction_ProgramActivated
      AddHandler objDGeneralFunction.OnCncStart, AddressOf objDGeneralFunction_OnCncStart
      AddHandler objDGeneralFunction.OnCncStop, AddressOf objDGeneralFunction_OnCncStop
      AddHandler objDGeneralFunction.OnCncReset, AddressOf objDGeneralFunction_OnCncReset
      AddHandler objDGeneralFunction.CncModeWritten, AddressOf objDGeneralFunction_CncModeWritten
      AddHandler objDGeneralFunction.VariableWritten, AddressOf objDGeneralFunction_VariableWritten
      Dim l = objDGeneralFunction.Init(objDGroupManager.Handle)
      Dim MaxWaiting As Integer = 100
      Dim WaitingIndex As Integer = 0
      While objDGeneralFunction.ConnectionStatus <> 2 AndAlso WaitingIndex < MaxWaiting
         Threading.Thread.Sleep(100)
         UpdateUI()
         WaitingIndex += 1
      End While
      Dim j = objDGeneralFunction.ConnectionStatus
      Dim oi = objDGeneralFunction.ConnectionString
      ' Initialize FXLog Objects
      objErrorHandler = CreateObject("APLog.ErrorHandler")
      'AddHandler objErrorHandler.ErrorFromActiveCnc, AddressOf objErrorHandler_ErrorFromActiveCnc2
      AddHandler objErrorHandler.ErrorOnCnc, AddressOf objErrorHandler_ErrorOnCnc
      AddHandler objErrorHandler.ErrorOnOtherChannel, AddressOf objErrorHandler_ErrorOnOtherChannel
      AddHandler objErrorHandler.Exception, AddressOf objErrorHandler_Exception
      '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 FXServer class DFileTransferv
      objDFileTransfer = CreateObject("APServer.DFileTransfer")
      AddHandler objDFileTransfer.Completed, AddressOf objDFileTransfer_Completed
      AddHandler objDFileTransfer.TransferStarted, AddressOf objDFileTransfer_TransferStarted
      AddHandler objDFileTransfer.Failed, AddressOf objDFileTransfer_Failed
      AddHandler objDFileTransfer.BytesTransfered, AddressOf objDFileTransfer_BytesTransfered
      objDFileTransfer.Init(objDGroupManager.Handle)

      objDPosition = CreateObject("APServer.DPosition")
      AddHandler objDPosition.PositionChanged, AddressOf objDPosition_PositionChanged
      objDPosition.ModeOP = 1
      objDPosition.Flag = 0
      objDPosition.Init(objDGroupManager.Handle)
      objDPosition.FireValidAxis()
      objDPosition.FireValues()

      'Initialize FXServer class DMdiCommand
      objDMdiCommand = CreateObject("APServer.DMdiCommand")
      AddHandler objDMdiCommand.CommandWritten, AddressOf objDMdiCommand_CommandWritten
      objDMdiCommand.Init(objDGroupManager.Handle)

      ' Initialize FXServer class DCncMode
      objDCncMode = CreateObject("APServer.DCncMode")
      AddHandler objDCncMode.ValueChanged, AddressOf objDCncMode_ValueChanged
      objDCncMode.Init(objDGroupManager.Handle)

      ' Initialize FXServer class DReadOperatorMessage
      objDReadOperatorMessage = CreateObject("APServer.DReadOperatorMessage")
      AddHandler objDReadOperatorMessage.ValueChanged, AddressOf objDReadOperatorMessage_ValueChanged
      Dim tc = objDReadOperatorMessage.Init(objDGroupManager.Handle)
      If tc <> 0 Then EgtOutLog("Init failed ! return code : " + tc)

      ' Initialize FXServer class DReadELS
      'objDReadELS = CreateObject("APServer.DReadELS")
      'AddHandler objDReadELS.ValueChanged, AddressOf objDReadELS_ValueChanged
      'Dim y = objDReadELS.Init(objDGroupManager.Handle)

      objDReadPlcVarList = CreateObject("APServer.DReadPlcVarList")
      AddHandler objDReadPlcVarList.ValueChanged, AddressOf objDPlcVariables_ReadPLCVariablesChanged
      ' Init & send the list of requested variables
      'tc = objDReadPlcVarList.Init(objDGroupManager.Handle)
      'If tc <> 0 Then EgtOutLog(" objDReadPlcVarList.Init() Error : " + tc)

      'Initialize FXServer class DVariables
      objDVariables = CreateObject("APServer.DVariables")
      'AddHandler objDVariables.ValueChanged, AddressOf objDVariables_ValueChanged
      ' Init & send the list of requested variables
      'Dim rc As Short = objDVariables.Init(objDGroupManager.Handle, "E80000", 0)
      AddHandler objDVariables.VariableWritten, AddressOf objDVariables_VariableWritten
      AddHandler objDVariables.ValueChanged, AddressOf objDPlcVariables_ReadVariablesChanged
      'If rc <> 0 Then EgtOutLog(" objDVariables.Init() Error : " + rc)

      ' attivo programma main
      Map.refMachManaging.Num_Axium_APServer.ActivateProg(9000)

   End Sub

   Friend Sub CloseFxObjects()
      If Not IsNothing(objDReadOperatorMessage) Then
         objDReadOperatorMessage.Close()
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDReadOperatorMessage)
         objDReadOperatorMessage = Nothing
      End If
      If Not IsNothing(objDCncMode) Then
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDCncMode)
         objDCncMode = Nothing
      End If
      If Not IsNothing(objDReadPlcVarList) Then
         objDReadPlcVarList.Close()
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDReadPlcVarList)
         objDReadPlcVarList = Nothing
      End If
      If Not IsNothing(objDVariables) Then
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDVariables)
         objDVariables = Nothing
      End If
      If Not IsNothing(objDMdiCommand) Then
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDMdiCommand)
         objDMdiCommand = Nothing
      End If
      If Not IsNothing(objDPosition) Then
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDPosition)
         objDPosition = Nothing
      End If
      If Not IsNothing(objDFileTransfer) Then
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDFileTransfer)
         objDFileTransfer = Nothing
      End If
      If Not IsNothing(objDReadELS) Then
         objDReadELS.Close()
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDReadELS)
         objDReadELS = Nothing
      End If
      If Not IsNothing(objErrorHandler) Then
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objErrorHandler)
         objErrorHandler = Nothing
      End If
      If Not IsNothing(objDGeneralFunction) Then
         objDGeneralFunction.Connect(0)
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDGeneralFunction)
         objDGeneralFunction = Nothing
      End If
      If Not IsNothing(objDMainCncData) Then
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDMainCncData)
         objDMainCncData = Nothing
      End If
      If Not IsNothing(objDGroupManager) Then
         System.Runtime.InteropServices.Marshal.ReleaseComObject(objDGroupManager)
         objDGroupManager = Nothing
      End If
      Dim ServerProcList As Process() = Process.GetProcessesByName("APServer")
      Dim LogProcList As Process() = Process.GetProcessesByName("APLog")
      For Each ServerProc In ServerProcList
         ServerProc.Kill()
      Next
      For Each LogProc In LogProcList
         LogProc.Kill()
      Next
   End Sub

   Friend Sub GetGeneralFunctions()
      Dim _GetConnectState As Int16 = 0
      Dim MaxWaiting As Integer = 100
      Dim WaitingIndex As Integer = 0
      While _GetConnectState <> 2 AndAlso WaitingIndex < MaxWaiting
         _GetConnectState = objDGeneralFunction.ConnectionStatus
         Threading.Thread.Sleep(100)
         UpdateUI()
         WaitingIndex += 1
      End While

      Select Case _GetConnectState
         Case 0
            ' Not connected
            m_MachManaging.SetConnected(False)
            m_ResultCallbackDlg(CommandTypes.CONNECT, CommandStates.NULL, ResultTypes.RESULT, "")
         Case 1
            ' Connection error
            m_MachManaging.SetConnected(False)
            m_ResultCallbackDlg(CommandTypes.CONNECT, CommandStates.ERROR_, ResultTypes.RESULT, "")
         Case 2
            ' Connected
            m_MachManaging.SetConnected(True)
            m_ResultCallbackDlg(CommandTypes.CONNECT, CommandStates.OK, ResultTypes.RESULT, "")
            ' avvio lettura variabili
            'MachManaging.CommandList.Add(ThreadCommand.CreateCommand(CommandTypes.READ_NUMFLEXIUM))
            StartReadList()
            StartReadPLCList()
            'StartReadELS()
         Case Else
      End Select
   End Sub

   Friend Sub Start()
      objDGeneralFunction.CncStart()
   End Sub

   Friend Sub Stop_()
      objDGeneralFunction.CncStop()
   End Sub

   Friend Sub Reset()
      objDGeneralFunction.CncReset()
   End Sub

   Friend Sub SetMode(value As CNMode)
      objDGeneralFunction.WriteCncMode(value, 0)
   End Sub

   Friend Sub SetChannel(value As Integer)
      ChangeChannel(CShort(value))
      'objDGroupManager.AxisGroup = CShort(value)
   End Sub

   Friend Sub ActivateProg(PartProgramNumberActivate As Integer)
      ' attivo programma main
      Dim _FXReturn As Int16 = objDGeneralFunction.ActivateProgram(PartProgramNumberActivate * 10, 0)
      If _FXReturn <> 0 Then
         EgtOutLog("Error Activate Program:" & " " & _FXReturn.ToString())
      End If
   End Sub

   Private Sub ChangeChannel(Channel As Short)
      objErrorHandler.SetChannel(1, Channel)
   End Sub

   Friend Sub StartReadList()
      'Dim AddressList() As String = (From CommVar In m_ReadingVars
      '                               Where Not IsNothing(CommVar) AndAlso CommVar.nType = CommVar.Types.PLC
      '                               Select CommVar.sAddress).ToArray()
      'm_PlcVariablesList = New ArrayList((From CommVar In m_ReadingVars
      '                                    Where Not IsNothing(CommVar) AndAlso CommVar.nType = CommVar.Types.PLC
      '                                    Select CommVar.sAddress).ToArray())
      Dim nPLCVarIndex As Integer = 0
      Dim PlcVariablesList As New ArrayList
      Dim sPLCVariableList = ""
      For VarIndex = 0 To m_ReadingVars.Length - 1
         Dim CommVar As CommVar = m_ReadingVars(VarIndex)
         If Not IsNothing(CommVar) AndAlso CommVar.Paragraph = CommVar.Paragraphs.MAIN AndAlso CommVar.nType = CommVar.Types.CN Then
            PlcVariablesList.Add(CommVar.sAddress)
            If Not String.IsNullOrWhiteSpace(sPLCVariableList) Then
               sPLCVariableList &= ","
            End If
            sPLCVariableList &= """" & CommVar.sAddress & """"
            CommVar.Index = nPLCVarIndex
            nPLCVarIndex += 1
         End If
      Next
      'Dim sPLCVariableList = ""
      'For VariableIndex = 0 To PlcVariablesList.Count - 1
      '   If VariableIndex <> 0 Then
      '      sPLCVariableList &= ","
      '   End If
      '   sPLCVariableList &= """" & PlcVariablesList(VariableIndex) & """"
      'Next
      Dim _FXReturn As Short = objDVariables.Init(objDGroupManager.Handle, sPLCVariableList, 1) 'PlcVariablesList.ToArray().ToString())
      'Dim _FXReturn As Short = objDVariables.ReadVariables(PlcVariablesList.ToArray())

      'If _FXReturn <> 0 Then
      '   EgtOutLog("Error ReadVariables:" & " " & _FXReturn.ToString())
      'End If
   End Sub

   Friend Sub StartReadPLCList()
      'Dim AddressList() As String = (From CommVar In m_ReadingVars
      '                               Where Not IsNothing(CommVar) AndAlso CommVar.nType = CommVar.Types.PLC
      '                               Select CommVar.sAddress).ToArray()
      'm_PlcVariablesList = New ArrayList((From CommVar In m_ReadingVars
      '                                    Where Not IsNothing(CommVar) AndAlso CommVar.nType = CommVar.Types.PLC
      '                                    Select CommVar.sAddress).ToArray())
      Dim nPLCVarIndex As Integer = 0
      Dim PlcVariablesList As New ArrayList
      Dim sPLCVariableList = ""
      For VarIndex = 0 To m_ReadingVars.Length - 1
         Dim CommVar As CommVar = m_ReadingVars(VarIndex)
         If Not IsNothing(CommVar) AndAlso CommVar.nType = CommVar.Types.PLC AndAlso
            CommVar.Paragraph = CommVar.Paragraphs.MAIN Then
            PlcVariablesList.Add(CommVar.sAddress)
            If Not String.IsNullOrWhiteSpace(sPLCVariableList) Then
               sPLCVariableList &= ","
            End If
            sPLCVariableList &= CommVar.sAddress
            CommVar.Index = nPLCVarIndex
            nPLCVarIndex += 1
         End If
      Next
      objDReadPlcVarList.Argument = sPLCVariableList        ' "%M5.L,%M5.B"
      Dim h = objDReadPlcVarList.Init(objDGroupManager.Handle)
      'Dim _FXReturn As Short = objDVariables.ReadVariables(PlcVariablesList.ToArray())

      'If _FXReturn <> 0 Then
      '   EgtOutLog("Error ReadVariables:" & " " & _FXReturn.ToString())
      'End If
   End Sub

   Friend Sub CloseReadList()
      'objDPlcVariables.CloseReadList()
   End Sub

   Private Sub ReadVariablesOnce(Address As String)
      'Dim _ReadSymbolicPlcVariableOnetime As String = "Application.IOCONFIG_GLOBALS.Flexium_NCK.RCNC.General.Mode"
      'Dim _FXReturn As Int16 = objDPlcVariables.ReadVariablesOnce(10, Address)

      'If _FXReturn <> 0 Then
      '   EgtOutLog("Error ReadVariablesOnce:" & " " & _FXReturn.ToString())
      'End If

   End Sub

   Friend Sub WritePlcVariables(Address As String, value As String)
      'Dim _WriteSymbolicPlcVariable As String = _txtReadWritePlcVariables0.Text
      'Dim _FXReturn As Int16 = objDPlcVariables.WriteVariables2(11, Address, value)
      '
      'If _FXReturn <> 0 Then
      '   EgtOutLog("Error WriteVariables2 :" & " " & _FXReturn.ToString())
      'End If

   End Sub

   Public Shared Function InitVar(Variable As CommVar) As CommVar
      Dim Index As Integer = Array.IndexOf(m_ReadingVars, Nothing)
      m_ReadingVars(Index) = Variable
      Return m_ReadingVars(Index)
   End Function

   Friend Sub StartReadELS()
      For Index = 0 To m_ReadingVars.Length - 1
         If IsNothing(m_ReadingVars(Index)) Then Continue For    'OrElse m_ReadingVars(Index).nType <> CommVar.Types.CN Then Continue For
         Dim rc As Short = objDReadELS.AddParameter(m_ReadingVars(Index).sAddress, Index + 1)
         If rc <> 0 Then EgtOutLog(" Error AddParameter2 : " & rc & " on Variable : " & m_ReadingVars(Index).sAddress)
      Next
   End Sub

   Friend Sub CloseReadELS()
      'objDPlcVariables.CloseReadList()
   End Sub

#Region "File transfer"

   Friend Sub FileDownload(sFileType As String, sFilePath As String)
      Dim _Return_Download As Short

      _Return_Download = objDFileTransfer.FileDownload(10, sFileType, sFilePath, "", 1)

      If _Return_Download <> 0 Then
         EgtOutLog("Error: File not stored to the job list:" & " " & _Return_Download.ToString())
      End If
   End Sub

   Private Sub FileUpload(sFileType As String, sFilePath As String)
      Dim _Return_Upload As Short
      _Return_Upload = objDFileTransfer.FileUpload(20, sFileType, sFilePath, "")

      If _Return_Upload <> 0 Then
         EgtOutLog("Error: File not stored to the job list:" & " " & _Return_Upload.ToString())
      End If
   End Sub

   Friend Sub FileDelete(sFileType As String, sFilePath As String)
      Dim _ReturnFileDelete As Short
      _ReturnFileDelete = objDFileTransfer.FileDelete(20, sFileType, "")

      If _ReturnFileDelete <> 0 Then
         EgtOutLog("Error: File not deleted:" & " " & _ReturnFileDelete.ToString())
      End If
   End Sub

   Friend Sub StartTransfer()
      Dim _Return_StartTransfer As Short
      _Return_StartTransfer = objDFileTransfer.StartTransfer()

      If _Return_StartTransfer <> 0 Then
         EgtOutLog("Error: Start transfer not executed:" & " " & _Return_StartTransfer.ToString())
      Else
         m_BytesTransferedCounter = 0
      End If
   End Sub

#End Region    ' File transfer

#Region "MDI"

   Friend Sub MDI_Execute(sCommand As String)
      Dim nRet As Int16 = objDMdiCommand.ExecuteCommand(sCommand)
      If nRet <> 0 Then
         EgtOutLog("Error ExecuteCommand :" & " " & nRet.ToString())
      End If
   End Sub

#End Region    ' MDI

#Region "Variables"

   Friend Sub WriteNCVariables(Address As String, value As String)
      Try
         Dim dValue As Double = 0
         StringToDoubleAdv(value, dValue)
         Dim rc As Short = objDVariables.WriteVariables(objDGroupManager.Handle, Address, value)

         'If rc <> 0 Then EgtOutLog(" objDVariables.WriteVariables2() Error : " & rc)

      Catch ex As Exception
         EgtOutLog(" objDVariables.WriteVariables2() Exception : " & ex.Message)
      End Try
   End Sub

#End Region    ' Variables

#End Region    ' METHODS

#Region "EVENTS"

   Private Sub objDRunTimeSystem_ServerInitializationFinished()
      InitFxObjects()
      GetGeneralFunctions()
   End Sub

   Private Sub objDRunTimeSystem_ServerReinitializationStarted()
      CloseFxObjects()
   End Sub

   Private Sub objDGeneralFunction_ProgramActivated(ByVal nerrorCode As Short)
      EgtOutLog("Part program activated:" & " " & nerrorCode)
      'DbControllers.m_LogMachineController.Create(MachLog.CreateResultLog(CommandTypes.SENDPROG, CommandStates.OK, ResultTypes.EXECUTED, "Part program activated:" & " " & nerrorCode))
      ' scrivo evento programma attivato
      DbControllers.m_LogMachineController.Create(LogEvent.CreateMachCommandLog(LogEvent.MachineCommands.PROGRAM_ACTIVATION, "", nerrorCode, DbControllers.SupervisorId))
   End Sub

   Private Sub objDGeneralFunction_OnCncStart(ByVal errorCode As Short)
      Dim bOk As Boolean = (errorCode = 0)
      m_MachManaging.SetStartPending(bOk)
      m_ResultCallbackDlg(CommandTypes.START, If(bOk, CommandStates.OK, CommandStates.ERROR_), ResultTypes.EXECUTED, If(bOk, "", "Error CNC Start: " & errorCode.ToString()))
   End Sub

   Private Sub objDGeneralFunction_OnCncStop(ByVal errorCode As Short)
      Dim bOk As Boolean = (errorCode = 0)
      m_ResultCallbackDlg(CommandTypes.STOP_, If(bOk, CommandStates.OK, CommandStates.ERROR_), ResultTypes.EXECUTED, If(bOk, "", "Error Feed Hold: " & errorCode.ToString()))
   End Sub

   Private Sub objDGeneralFunction_OnCncReset(ByVal errorCode As Short)
      Dim bOk As Boolean = (errorCode = 0)
      m_ResultCallbackDlg(CommandTypes.RESET, If(bOk, CommandStates.OK, CommandStates.ERROR_), ResultTypes.EXECUTED, If(bOk, "", "Error CNC Reset: " & errorCode.ToString()))
   End Sub

   Private Sub objDGeneralFunction_CncModeWritten(ByVal errorCode As Short)
      If errorCode <> 0 Then EgtOutLog("Error CNC Mode selection completed:" & " " & errorCode.ToString())
   End Sub

   Private Sub objDGroupManager_ErrorHandler(ByVal sError As String, ByVal nTextNumber As Short)
      EgtOutLog("ErrorHandler message:" & " " & sError & " " & "ErrorHandler number:" & " " & nTextNumber.ToString())
   End Sub

   Private Sub objDGroupManager_AssignmentChanged(ByVal CncNumber As Short, ByVal AxisGroup As Short)
      m_ChannelCallbackDlg(AxisGroup)
   End Sub

   Private Sub _comboCncAxisChannel_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
      'Select Case _comboCncAxisChannel.SelectedItem.ToString()
      '   Case "Channel 1"
      '      objDGroupManager.AxisGroup = 0
      '   Case "Channel 2"
      '      objDGroupManager.AxisGroup = 1
      '   Case Else
      'End Select
   End Sub

   Private Sub objDGeneralFunction_VariableWritten(ByVal errorCode As Short)
      If errorCode <> 0 Then
         MessageBox.Show("Error from VariableWritten:" & " " & errorCode.ToString())
      Else
         MessageBox.Show("VariableWritten successfully")
      End If
   End Sub

   Private Sub objErrorHandler_ErrorOnCnc(ByVal cnc As Short, ByVal channel As Short, ByVal [set] As Short)
      'AplCncNumber.Add(cnc)
      'AplChannel.Add(channel)
      'AplSet.Add([set])
   End Sub

   Private Sub objErrorHandler_ErrorOnOtherChannel(ByVal status As Short)
      'AplStatus = status
   End Sub

   Private Sub objErrorHandler_Exception(ByVal status As Short)
      'ExceptStatus = status
   End Sub

   Friend Sub objErrorHandler_ErrorFromActiveCnc2(ErrorNumber As List(Of Integer))
      ' resetto stati bFound
      For Each Message In m_ReadFXMessages
         Message.bFound = False
      Next

      For index As Integer = 0 To ErrorNumber.Count - 1
         Dim nIndex As Integer = index
         Dim NewMessageInList As ReadMessages = m_ReadFXMessages.FirstOrDefault(Function(x) x.CMsgCncNumber = 0.ToString() AndAlso
                                                                                            x.CMsgErrorType = 6.ToString() AndAlso
                                                                                            x.CMsgErrorIndex = "" AndAlso
                                                                                            x.CMsgErrorNumber = ErrorNumber(nIndex).ToString() AndAlso
                                                                                            x.CMsgErrorLine = "" AndAlso
                                                                                            x.CMsgErrorMessage = "")
         ' se il messaggio e' gia' in lista
         If Not IsNothing(NewMessageInList) Then
            ' lo segno come trovato
            NewMessageInList.bFound = True
         Else
            ' lo aggiungo
            Dim NewMessage As ReadMessages = New ReadMessages(0.ToString(),
                                                              6.ToString(),
                                                              "",
                                                              ErrorNumber(index).ToString(),
                                                              "",
                                                              "",
                                                              "")
            NewMessage.bFound = True
            m_ReadFXMessages.Add(NewMessage)
            m_NUMAlarmCallbackDlg(0, 0, 6.ToString(), "", ErrorNumber(index).ToString(), "", "", "")
         End If
      Next

      ' cancello messaggi non trovati
      For Index = m_ReadFXMessages.Count - 1 To 0 Step -1
         Dim Message As ReadMessages = m_ReadFXMessages(Index)
         If Not Message.bFound Then
            m_NUMAlarmCallbackDlg(Message.CMsgCncNumber, 1, Message.CMsgErrorType, Message.CMsgErrorIndex, Message.CMsgErrorNumber, Message.CMsgErrorLine, Message.CMsgErrorMessage, Message.CMsgErrorAdditional)
            m_ReadFXMessages.RemoveAt(Index)
         End If
      Next

   End Sub

#Region "PLC Variables"

   Private Sub objDPlcVariables_ReadVariablesChanged(ByVal index As Object, ByVal value As Object)
      Dim _ObjIndex As Object() = CType(index, Object())
      Dim _ObjValue As Object() = CType(value, Object())

      For index = 0 To _ObjIndex.Length - 1
         Dim nObjIndex As Integer = Integer.Parse(_ObjIndex(index).ToString())
         Dim CommVar As CommVar = m_ReadingVars.FirstOrDefault(Function(x) Not IsNothing(x) AndAlso
                                                                           x.Paragraph = CommVar.Paragraphs.MAIN AndAlso
                                                                           x.nType = CommVar.Types.CN AndAlso
                                                                           x.Index = nObjIndex)
         If Not IsNothing(CommVar) Then
            CommVar.SetValue(_ObjValue(index).ToString())
         End If
      Next
   End Sub

   Private Sub objDPlcVariables_ReadPLCVariablesChanged(ByVal index As Object, ByVal value As Object)
      Dim _ObjIndex As Object() = CType(index, Object())
      Dim _ObjValue As Object() = CType(value, Object())

      For index = 0 To _ObjIndex.Length - 1
         Dim nObjIndex As Integer = Integer.Parse(_ObjIndex(index).ToString())
         Dim CommVar As CommVar = m_ReadingVars.FirstOrDefault(Function(x) Not IsNothing(x) AndAlso
                                                                           x.Paragraph = CommVar.Paragraphs.MAIN AndAlso
                                                                           x.nType = CommVar.Types.PLC AndAlso
                                                                           x.Index = nObjIndex)
         If Not IsNothing(CommVar) Then
            CommVar.SetValue(_ObjValue(index).ToString())
         End If
      Next
   End Sub

   Private Sub objDPlcVariables_InvalidReadList(ByVal errorCode As Short)
      EgtOutLog("InvalidReadList - ErrorCode: " & errorCode)
   End Sub

   Private Sub objDPlcVariables_AbortReadVariables()
      EgtOutLog("InvalidReadList - ErrorCode: ")
   End Sub

   Private Sub objDPlcVariables_ReadOnceVariablesChanged(ByVal lHandle As Integer, ByVal value As Object)
      'Dim _ObjValue As Object() = CType(value, Object())

      'If lHandle = 10 Then

      '   For i As Integer = 0 To _ObjValue.Length - 1
      '      _ReadPlcVariableOnetime(i).Invoke(CType(Function()
      '                                                 _ReadPlcVariableOnetime(i).Text = _ObjValue(i).ToString()
      '                                              End Function, MethodInvoker))
      '   Next
      'End If
   End Sub

   Private Sub objDPlcVariables_VariablesWritten2(ByVal lHandle As Integer, ByVal errorCode As Integer)
      Dim bOk As Boolean = (errorCode <> 0)
      m_ResultCallbackDlg(CommandTypes.WRITE, If(bOk, CommandStates.OK, CommandStates.ERROR_), ResultTypes.RESULT, If(bOk, "", "Error VariablesWritten2 :" & " " & errorCode.ToString()))
   End Sub

#End Region    ' PLC Variables

#Region "ReadELS"

   Private Sub objDReadELS_ValueChanged(ByVal nHandle As Short, ByVal dValue As Double, ByVal nerrorCode As Short)
      If nHandle < 1 OrElse nHandle > m_ReadingVars.Count - 1 Then Return
      If nerrorCode <> 0 Then EgtOutLog(" Error in Validchanged2 : " & nerrorCode & " Handle : " & nHandle)

      Try
         m_ReadingVars(nHandle - 1).SetValue(dValue.ToString("F04"))
      Catch Ex As Exception
         EgtOutLog(Ex.Message)
      End Try
   End Sub

#End Region    ' ReadELS

#Region "File transfer"

   Private Sub objDFileTransfer_Completed(ByVal lHandle As Integer)
      If lHandle = 10 OrElse lHandle = 20 Then
         'resetto contatore di trasferimento
         m_BytesTransferedCounter = 0
         EgtOutLog("Up- or Download successful completed:" & " " & lHandle.ToString())
         ' aggiorno variabili del MAIN
         Dim ISONumVariable As Variable = Map.refMachCommandMessagePanelVM.MainVariablesList.FirstOrDefault(Function(x) x.sName = ISO_NUM)
         Dim ISOSentVariable As Variable = Map.refMachCommandMessagePanelVM.MainVariablesList.FirstOrDefault(Function(x) x.sName = ISO_SENT)
         Dim SentMachGroup As MyMachGroupVM = Map.refSupervisorMachGroupPanelVM.MachGroupVMList.FirstOrDefault(Function(x As MyMachGroupVM) x.bSendingToMachine)
         If Not IsNothing(SentMachGroup) Then
            ISONumVariable.sValue = SentMachGroup.Name
            ISOSentVariable.sValue = 0
            SentMachGroup.SetSentToMachine(True)
         End If
      End If
   End Sub

   Private Sub objDFileTransfer_TransferStarted(ByVal lHandle As Integer)
      EgtOutLog("Transfer has been started !")
   End Sub

   Private Sub objDFileTransfer_Failed(ByVal lHandle As Integer, ByVal nSeq As Short, ByVal nReason As Short)
      EgtOutLog("Sequence:" & " " & nSeq.ToString() & " " & "Reason:" & " " & nReason.ToString())
   End Sub

   Private Sub objDFileTransfer_BytesTransfered(ByVal lHandle As Integer, ByVal lBytes As Integer)
      m_BytesTransferedCounter += lBytes
   End Sub

#End Region    ' File transfer

#Region "Position"

   Private Sub objDPosition_PositionChanged(ByVal vtArrayIndex As Object, ByVal vtArrayValues As Object)
      Dim _indexArray As Object() = CType(vtArrayIndex, Object())
      Dim _valueArray As Object() = CType(vtArrayValues, Object())

      For _index As Integer = 0 To _indexArray.Length - 1

         Dim _index1 As Int16 = CType(_indexArray.GetValue(_index), Int16)
         Dim _axisPosValue As Int32 = CType(_valueArray.GetValue(_index), Int32)
         Dim _axisRefPosValue As Single = CSng(_axisPosValue) / m_LinearAxisPrecision
         m_AxisCoordinatesCallbackDlg(_axisPosValue, _index1)

      Next
   End Sub

#End Region    ' Position

#Region "MDI"

   Private Sub objDMdiCommand_CommandWritten(ByVal retVal As Short)
      If retVal <> 0 Then
         EgtOutLog("Error CommandWritten :" & " " & retVal.ToString())
      End If
      Map.refMDIPageVM.SendMDIResult(retVal)
   End Sub

#End Region    ' MDI

#Region "Variables"

   Private Sub objDVariables_VariableWritten2(ByVal lHandle As Integer, ByVal errorCode As Short)
      If lHandle <> 2 OrElse errorCode <> 0 Then
         EgtOutLog(" Error on objDVariables_VariableWritten2 : handle " & lHandle.ToString() & " errorCode : " & errorCode.ToString())
      End If
   End Sub

   Private Sub objDVariables_VariableWritten(ByVal errorCode As Short)
      If errorCode <> 0 Then
         EgtOutLog(" Error on objDVariables_VariableWritten errorCode : " & errorCode.ToString())
      End If
   End Sub

   Private Sub objDVariables_ValueChanged(ByVal vtArrayIndex As Object, ByVal vtArrayValues As Object)
      Dim AplArrayIndex As Object() = CType(vtArrayIndex, Object())
      Dim AplArrayValue As Object() = CType(vtArrayValues, Object())

      For index As Integer = 0 To AplArrayIndex.Length - 1
         Dim nHandle As Integer = CType(AplArrayIndex.GetValue(index), Int16)
         If nHandle < 1 OrElse nHandle > m_ReadingVars.Count - 1 Then Return
         Dim dValue As Double = CDbl(AplArrayValue.GetValue(index))
         Try
            m_ReadingVars(nHandle - 1).SetValue(dValue.ToString("F04"))
         Catch Ex As Exception
            EgtOutLog(Ex.Message)
         End Try
      Next
   End Sub

#End Region    ' Variables

#Region "CNCMode"

   Private Sub objDCncMode_ValueChanged(ByVal mode As Short, ByVal preselected As Short)
      m_OpModeCallbackDlg(mode)
   End Sub

#End Region    ' CNCMode

#Region "ReadOperatorMessage"

   Private Sub objDReadOperatorMessage_ValueChanged(ByVal line As Object)
      ' resetto stati bFound
      For Each Message In m_ReadOperatorMessages
         Message.bFound = False
      Next
      Dim objLine As String = TryCast(line, String)
      Dim OpMsgErrType As Integer = 30
      Dim NewMessageInList As ReadMessages = m_ReadOperatorMessages.FirstOrDefault(Function(x) x.CMsgCncNumber = 0 AndAlso
                                                                                               x.CMsgErrorType = OpMsgErrType.ToString() AndAlso
                                                                                               x.CMsgErrorIndex = "" AndAlso
                                                                                               x.CMsgErrorNumber = "" AndAlso
                                                                                               x.CMsgErrorLine = "" AndAlso
                                                                                               x.CMsgErrorMessage = objLine AndAlso
                                                                                               x.CMsgErrorAdditional = "")
      ' se il messaggio e' gia' in lista
      If Not IsNothing(NewMessageInList) Then
         ' lo segno come trovato
         NewMessageInList.bFound = True
      Else
         ' se e' diverso da stringa vuota
         If Not String.IsNullOrWhiteSpace(objLine.ToString()) Then
            ' lo aggiungo
            Dim NewMessage As ReadMessages = New ReadMessages(0,
                                                           OpMsgErrType.ToString(),
                                                           "",
                                                           "",
                                                           "",
                                                           objLine,
                                                           "")
            NewMessage.bFound = True
            m_ReadOperatorMessages.Add(NewMessage)
            m_NUMAlarmCallbackDlg(0, 0, OpMsgErrType.ToString(), "", "", "", objLine, "")
         End If
      End If

      ' cancello messaggi non trovati
      If m_ReadOperatorMessages.Count > 0 Then
         For Index = m_ReadOperatorMessages.Count - 1 To 0 Step -1
            Dim Message As ReadMessages = m_ReadOperatorMessages(Index)
            If Not Message.bFound Then
               m_NUMAlarmCallbackDlg(Message.CMsgCncNumber, 1, Message.CMsgErrorType, Message.CMsgErrorIndex, Message.CMsgErrorNumber, Message.CMsgErrorLine, Message.CMsgErrorMessage, Message.CMsgErrorAdditional)
               m_ReadOperatorMessages.RemoveAt(Index)
            End If
         Next
      End If

   End Sub

#End Region    ' ReadOperatorMessage

#End Region    ' EVENTS

End Class
