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

Public Class NUMFlexiumComm

   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 objDGroupManager As FXServer.DGroupManager
   Private objDGeneralFunction As FXServer.DGeneralFunctions
   Private objDMainCncData As FXServer.DMainCncData
   Private objErrorHandler As FXLog.ErrorHandler
   Private objDPlcVariables As FXServer.DPlcVariables
   Private objDReadELS As FXServer.DReadELS
   Private objDFileTransfer As FXServer.DFileTransfer
   Private objDPosition As FXServer.DPosition
   Private objDMdiCommand As FXServer.DMdiCommand
   Private objDVariables As FXServer.DVariables
   Private objDCncMode As FXServer.DCncMode
   Private objDReadOperatorMessage As FXServer.DReadOperatorMessage

   Private m_IsFlexiumPlus As Boolean = False
   Friend ReadOnly Property IsFlexiumPlus As Boolean
      Get
         Return m_IsFlexiumPlus
      End Get
   End Property
   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(230) 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()
      objDRunTimeSystem = New FXServer.DRunTimeSystem()
      AddHandler objDRunTimeSystem.ServerInitializationFinished, AddressOf objDRunTimeSystem_ServerInitializationFinished
      AddHandler objDRunTimeSystem.ServerReinitializationStarted, AddressOf objDRunTimeSystem_ServerReinitializationStarted
      objDRunTimeSystem.Init()
   End Sub

   Private Sub InitFxObjects()
      objDGroupManager = New FXServer.DGroupManager()
      AddHandler objDGroupManager.ErrorHandler, AddressOf objDGroupManager_ErrorHandler
      AddHandler objDGroupManager.AssignmentChanged, AddressOf objDGroupManager_AssignmentChanged
      objDGroupManager.CncNumber = 0
      objDGroupManager.AxisGroup = 0

      objDGeneralFunction = New FXServer.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
      objDGeneralFunction.Init(objDGroupManager.Handle)
      objDMainCncData = New FXServer.DMainCncData()
      objDMainCncData.Init(objDGroupManager.Handle)
      m_LinearAxisPrecision = objDMainCncData.GetLinearPrecision()
      Dim CncFxIdentifier As String = objDMainCncData.GetCncIdentifier()
      EgtOutLog("CncFxIdentifier: " & CncFxIdentifier)

      m_IsFlexiumPlus = Not (CncFxIdentifier = "Flexium 6" OrElse CncFxIdentifier = "Flexium 8" OrElse CncFxIdentifier = "Flexium 68")

      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

      ' Initialize FXLog Objects
      objErrorHandler = New FXLog.ErrorHandler()
      AddHandler objErrorHandler.ErrorFromActiveCnc2, 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)

      objDPlcVariables = New FXServer.DPlcVariables()
      'objDPlcVariables.Symbols += New FXServer.IDPlcVariablesEvents_SymbolsEventHandler(AddressOf objDPlcVariables_Symbols)
      AddHandler objDPlcVariables.ReadVariablesChanged, AddressOf objDPlcVariables_ReadVariablesChanged
      AddHandler objDPlcVariables.InvalidReadList, AddressOf objDPlcVariables_InvalidReadList
      AddHandler objDPlcVariables.AbortReadVariables, AddressOf objDPlcVariables_AbortReadVariables
      AddHandler objDPlcVariables.VariablesWritten2, AddressOf objDPlcVariables_VariablesWritten2
      AddHandler objDPlcVariables.ReadOnceVariablesChanged, AddressOf objDPlcVariables_ReadOnceVariablesChanged
      objDPlcVariables.Flag = 3
      objDPlcVariables.Init(objDGroupManager.Handle)

      ' Initialize FXServer class DReadELS
      objDReadELS = New FXServer.DReadELS()
      AddHandler objDReadELS.ValueChanged, AddressOf objDReadELS_ValueChanged
      AddHandler objDReadELS.ValueChanged2, AddressOf objDReadELS_ValueChanged2
      ' Only for FX Server >= 3.9.0.0 
      AddHandler objDReadELS.ValueChanged3, AddressOf objDReadELS_ValueChanged3
      objDReadELS.Init(objDGroupManager.Handle)

      'Initialize FXServer class DFileTransfer
      objDFileTransfer = New FXServer.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 = New FXServer.DPosition()
      'objDPosition.ValidAxisChanged += New FXServer.IDPositionEvents_ValidAxisChangedEventHandler(AddressOf objDPosition_ValidAxisChanged)
      AddHandler objDPosition.PositionChanged, AddressOf objDPosition_PositionChanged
      'objDPosition.DeltaChanged += New FXServer.IDPositionEvents_DeltaChangedEventHandler(AddressOf objDPosition_DeltaChanged)
      'objDPosition.ReadOnceValidAxisChanged += New FXServer.IDPositionEvents_ReadOnceValidAxisChangedEventHandler(AddressOf objDPosition_ReadOnceValidAxisChanged)
      'objDPosition.ReadOncePositionChanged += New FXServer.IDPositionEvents_ReadOncePositionChangedEventHandler(AddressOf objDPosition_ReadOncePositionChanged)
      'objDPosition.ReadOnceDeltaChanged += New FXServer.IDPositionEvents_ReadOnceDeltaChangedEventHandler(AddressOf objDPosition_ReadOnceDeltaChanged)
      'objDPosition.EndposChanged += New FXServer.IDPositionEvents_EndposChangedEventHandler(AddressOf objDPosition_EndposChanged)

      objDPosition.Flag = 0
      objDPosition.ModeOP = 0
      objDPosition.FastUpdate = 0 ' Disable FastUpdate=0 To show the refresh time by Flag > 0
      objDPosition.Init(objDGroupManager.Handle)

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

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

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

      ' Initialize FXServer class DReadOperatorMessage
      objDReadOperatorMessage = New FXServer.DReadOperatorMessage()
      AddHandler objDReadOperatorMessage.ValueChanged2, AddressOf objDReadOperatorMessage_ValueChanged2
      rc = objDReadOperatorMessage.Init(objDGroupManager.Handle)
      If rc <> 0 Then EgtOutLog("Init failed ! return code : " + rc)

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

   End Sub

   Private Sub CloseFxObjects()
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objDGroupManager)
      objDGroupManager = Nothing
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objDGeneralFunction)
      objDGeneralFunction = Nothing
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objErrorHandler)
      objErrorHandler = Nothing
      objDReadELS.Close()
      objDPlcVariables.Close()
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objDReadELS)
      objDReadELS = Nothing
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objDFileTransfer)
      objDFileTransfer = Nothing
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objDPosition)
      objDPosition = Nothing
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objDMdiCommand)
      objDMdiCommand = Nothing
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objDVariables)
      objDVariables = Nothing
      objDReadOperatorMessage.Close()
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objDReadOperatorMessage)
      objDReadOperatorMessage = Nothing

   End Sub

   Private Sub GetGeneralFunctions()
      Dim _GetConnectState As Int16 = objDGeneralFunction.ConnectionStatus

      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()
            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)
      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 WriteVariable(ByVal sender As Object, ByVal e As EventArgs)
   '   Dim _E80011FxStd As Int32 = 88888
   '   Dim _FXReturn As Short = objDGeneralFunction.WriteVariable("E80011", _E80011FxStd)

   '   If _FXReturn <> 0 Then
   '      MessageBox.Show("Error from WriteVariable:" & " " & _FXReturn.ToString())
   '   End If
   'End Sub

   'Private Sub WriteVariable2(ByVal sender As Object, ByVal e As EventArgs)
   '   Dim _E80010FxPlus As Double = 51515.6161
   '   Dim _FXReturn As Short = objDGeneralFunction.WriteVariable2("E80010", _E80010FxPlus)

   '   If _FXReturn <> 0 Then
   '      MessageBox.Show("Error from WriteVariable2:" & " " & _FXReturn.ToString())
   '   End If
   'End Sub

   Private Sub ChangeChannel(Channel As Short)
      objErrorHandler.SetChannel(0, 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
      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 OrElse
            (Map.refMainMenuVM.SelPage = Pages.INPUTS AndAlso CommVar.Paragraph = CommVar.Paragraphs.INPUT) OrElse
            (Map.refMainMenuVM.SelPage = Pages.OUTPUTS AndAlso CommVar.Paragraph = CommVar.Paragraphs.OUTPUT)) Then
            PlcVariablesList.Add(CommVar.sAddress)
            CommVar.Index = nPLCVarIndex
            nPLCVarIndex += 1
         End If
      Next
      'm_PlcVariablesList.Add("Application.IOCONFIG_GLOBALS.Flexium_NCK.RCNC.General.Start")
      'm_PlcVariablesList.Add("Application.IOCONFIG_GLOBALS.Flexium_NCK.RCNC.General.Stop")
      'Dim AddressList As String = "Application.IOCONFIG_GLOBALS.Flexium_NCK.RCNC.General.Start;Application.IOCONFIG_GLOBALS.Flexium_NCK.RCNC.General.Stop"

      Dim _FXReturn As Short = objDPlcVariables.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)) 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
      '' leggo variabile E30099
      'Dim SendPermissionVariable As Variable = Map.refMachCommandMessagePanelVM.MainVariablesList.FirstOrDefault(Function(x) x.sName = SENDPERMISSION)
      'Dim dTemp As Double = 0
      'Dim nSendPermission As Integer = 0
      'EgtOutLog("Inizio invio programma")
      'While nSendPermission <> 2
      '   Dim bFirstWriteOne = True
      '   EgtOutLog("Inizio ciclo verifica diverso da 2")
      '   ' leggo valore
      '   If Not IsNothing(SendPermissionVariable.sValue) Then
      '      StringToDoubleAdv(SendPermissionVariable.sValue, dTemp)
      '      Integer.TryParse(dTemp, nSendPermission)
      '      EgtOutLog("Lettura variabile E30099: " & nSendPermission)
      '   Else
      '      EgtOutLog("nSendPermission = -1")
      '      nSendPermission = -1
      '   End If
      '   ' se uguale a zero ci scrivo uno
      '   If nSendPermission = 0 And bFirstWriteOne Then
      '      bFirstWriteOne = False
      '      SendPermissionVariable.sValue = 1
      '      EgtOutLog("Scrittura variabile E30099 = 1")
      '   End If
      '   Threading.Thread.Sleep(1000)
      'End While

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

      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 _FxReturn As Int16 = objDMdiCommand.ExecuteCommand(sCommand)

      If _FxReturn <> 0 Then
         EgtOutLog("Error ExecuteCommand :" & " " & _FxReturn.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.WriteVariables2(2, objDGroupManager.Handle, Address, dValue)

         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

   Private Sub objErrorHandler_ErrorFromActiveCnc2(ByVal CncNumber As Short, ByVal numberOfError As Short, ByVal ErrorTyp As Object, ByVal ErrorIndex As Object, ByVal ErrorNumber As Object, ByVal ErrorLine As Object, ByVal ErrorMessage As Object, ByVal ErrorAdditional As Object)
      ' resetto stati bFound
      For Each Message In m_ReadFXMessages
         Message.bFound = False
      Next
      Dim AplCnCNumber As Short = CncNumber
      Dim AplnumberofError As Short = numberOfError
      Dim AplErrorType As Object() = CType(ErrorTyp, Object())
      Dim AplErrorIndex As Object() = CType(ErrorIndex, Object())
      Dim AplErrorNumber As Object() = CType(ErrorNumber, Object())
      Dim AplErrorLine As Object() = CType(ErrorLine, Object())
      Dim AplErrorMessage As Object() = CType(ErrorMessage, Object())
      Dim AplErrorAdditional As Object() = CType(ErrorAdditional, Object())

      For index As Integer = 0 To numberOfError - 1
         Dim nIndex As Integer = index
         Dim NewMessageInList As ReadMessages = m_ReadFXMessages.FirstOrDefault(Function(x) x.CMsgCncNumber = AplCnCNumber AndAlso
                                                                                            x.CMsgErrorType = AplErrorType(nIndex).ToString() AndAlso
                                                                                            x.CMsgErrorIndex = AplErrorIndex(nIndex).ToString() AndAlso
                                                                                            x.CMsgErrorNumber = AplErrorNumber(nIndex).ToString() AndAlso
                                                                                            x.CMsgErrorLine = AplErrorLine(nIndex).ToString() AndAlso
                                                                                            x.CMsgErrorMessage = AplErrorMessage(nIndex).ToString() AndAlso
                                                                                            x.CMsgErrorAdditional = AplErrorAdditional(nIndex).ToString())
         ' 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(AplCnCNumber,
                                                           AplErrorType(index).ToString(),
                                                           AplErrorIndex(index).ToString(),
                                                           AplErrorNumber(index).ToString(),
                                                           AplErrorLine(index).ToString(),
                                                           AplErrorMessage(index).ToString(),
                                                           AplErrorAdditional(index).ToString())
            NewMessage.bFound = True
            m_ReadFXMessages.Add(NewMessage)
            m_NUMAlarmCallbackDlg(AplCnCNumber, 0, AplErrorType(index).ToString(), AplErrorIndex(index).ToString(), AplErrorNumber(index).ToString(), AplErrorLine(index).ToString(), AplErrorMessage(index).ToString(), AplErrorAdditional(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.nType = CommVar.Types.PLC AndAlso
                                                                           (x.Paragraph = CommVar.Paragraphs.MAIN OrElse
                                                                           (Map.refMainMenuVM.SelPage = Pages.INPUTS AndAlso x.Paragraph = CommVar.Paragraphs.INPUT) OrElse
                                                                           (Map.refMainMenuVM.SelPage = Pages.OUTPUTS AndAlso x.Paragraph = CommVar.Paragraphs.OUTPUT)) 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_ValueChanged2(ByVal nHandle As Integer, 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

   Private Sub objDReadELS_ValueChanged3(ByVal nHandle As Integer, ByVal value As Object, ByVal DataType As Short, ByVal Writable As Short, ByVal nerrorCode As Short)
      If nHandle < 1 OrElse nHandle > m_ReadingVars.Count - 1 Then
         EgtOutLog(" Invalid handle in Validchanged3 : " & nHandle)
         Return
      End If

      If nerrorCode <> 0 Then EgtOutLog(" Error in Validchanged3 : " & nerrorCode & " Handle : " & nHandle)
      Dim sValue As String

      Try

         Select Case DataType
            Case 0
               sValue = (CSByte(value)).ToString()
            Case 1
               sValue = (CByte(value)).ToString()
            Case 2
               sValue = (CType(value, Int16)).ToString()
            Case 3
               sValue = (CType(value, UInt16)).ToString()
            Case 4
               sValue = (CType(value, Int32)).ToString()
            Case 5
               sValue = (CType(value, UInt32)).ToString()
            Case 6
               sValue = (CDbl(value)).ToString()
            Case 7
               sValue = (CBool(value)).ToString()
            Case 8
               sValue = (CBool(value)).ToString()
            Case 9
               sValue = (CBool(value)).ToString()
            Case 10
               sValue = (CType(value, Int64)).ToString()
            Case 11
               sValue = (CType(value, UInt32)).ToString()
            Case -1
               sValue = value.ToString()
            Case Else
               sValue = String.Empty
               EgtOutLog("objDReadELS_ValueChanged3() : Unknown Datatype !")
         End Select

         m_ReadingVars(nHandle - 1).SetValue(sValue)

         '_ELS(nHandle - 1, 1).Text = sValue
         '_ELS(nHandle - 1, 2).Text = (CType(DataType, eDatatype)).ToString()
         '_ELS(nHandle - 1, 3).Text = If(Writable = 0, "No", If(Writable = 1, "Yes", Writable.ToString()))
      Catch Ex As Exception
         EgtOutLog("objDReadELS_ValueChanged3 " & Ex.Message & " Handle : " + nHandle)
      End Try
   End Sub

   Private Sub objDReadELS_ValueChanged(ByVal nHandle As Short, ByVal dValue As Double, ByVal nerrorCode As Short)
      'Throw New NotImplementedException()
   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

         If m_IsFlexiumPlus = True Then
            Dim _index1 As Int16 = CType(_indexArray.GetValue(_index), Int16)
            Dim _axisPosValue As Double = CType(_valueArray.GetValue(_index), Double)
            Dim _axisRefPosValue As Double = CType(_axisPosValue, Double) / m_LinearAxisPrecision
            m_AxisCoordinatesCallbackDlg(_axisPosValue, _index1)
         Else
            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)
         End If

      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())
   '   Dim Idx As Int16
   '   If IsFlexiumPlus Then Return

   '   For index As Integer = 0 To AplArrayIndex.Length - 1

   '      Try
   '         Idx = CType(AplArrayIndex.GetValue(index), Int16)
   '         If Idx > 8 Then Exit For
   '         _Variables(Idx, 1).Invoke(CType(Function()
   '                                            _Variables(Idx, 1).Text = (CDbl(AplArrayValue.GetValue(index))).ToString()
   '                                         End Function, MethodInvoker))
   '      Catch Ex As Exception
   '         DisplayMessage(Ex.Message)
   '      End Try
   '   Next
   'End Sub

   'Private Sub objDVariables_ValueChanged2(ByVal vtArrayIndex As Object, ByVal vtArrayValues As Object)
   '   Dim AplArrayIndex As Object() = CType(vtArrayIndex, Object())
   '   Dim AplArrayValue As Object() = CType(vtArrayValues, Object())
   '   Dim index, IdxVar, IdxData, Idx As Int16, Datatype As Int16 = -1
   '   Dim _objValue As Object = Nothing
   '   Dim sValue As String

   '   For index = 0 To AplArrayIndex.Length - 1

   '      Try
   '         Idx = CType(AplArrayIndex.GetValue(index), Int16)
   '         IdxVar = CShort((Idx / 10))
   '         IdxData = CShort((Idx Mod 10))
   '         If IdxData < 0 OrElse IdxData > 2 OrElse IdxVar > 8 Then Continue For

   '         Select Case IdxData
   '            Case 0
   '               _objValue = AplArrayValue.GetValue(index)
   '            Case 1
   '               Me.Invoke(CType(Function()
   '                                  _Variables(IdxVar, 2).Tag = CShort(AplArrayValue.GetValue(index))
   '                                  _Variables(IdxVar, 2).Text = (CType(AplArrayValue.GetValue(index), eDatatype)).ToString()
   '                               End Function, MethodInvoker))
   '            Case 2
   '               Me.Invoke(CType(Function()
   '                                  _Variables(IdxVar, 3).Text = If((CShort(AplArrayValue.GetValue(index))) = 0, "No", If((CShort(AplArrayValue.GetValue(index))) = 1, "Yes", (CShort(AplArrayValue.GetValue(index))).ToString()))
   '                               End Function, MethodInvoker))
   '         End Select

   '         Me.Invoke(CType(Function()
   '                            Datatype = If(_Variables(IdxVar, 2).Tag IsNot Nothing, CShort(_Variables(IdxVar, 2).Tag), CShort(-2))
   '                         End Function, MethodInvoker))

   '         If IdxData = 1 OrElse IdxData = 0 AndAlso Datatype <> -1 Then

   '            Select Case Datatype
   '               Case 0
   '                  sValue = (CSByte(_objValue)).ToString()
   '               Case 1
   '                  sValue = (CByte(_objValue)).ToString()
   '               Case 2
   '                  sValue = (CType(_objValue, Int16)).ToString()
   '               Case 3
   '                  sValue = (CType(_objValue, UInt16)).ToString()
   '               Case 4
   '                  sValue = (CType(_objValue, Int32)).ToString()
   '               Case 5
   '                  sValue = (CType(_objValue, UInt32)).ToString()
   '               Case 6
   '                  sValue = (CDbl(_objValue)).ToString()
   '               Case 7
   '                  sValue = (CBool(_objValue)).ToString()
   '               Case 8
   '                  sValue = (CBool(_objValue)).ToString()
   '               Case 9
   '                  sValue = (CBool(_objValue)).ToString()
   '               Case 10
   '                  sValue = (CType(_objValue, Int64)).ToString()
   '               Case 11
   '                  sValue = (CType(_objValue, UInt32)).ToString()
   '               Case -1
   '                  sValue = (CType(_objValue, Int32)).ToString()
   '               Case Else
   '                  sValue = String.Empty
   '                  DisplayMessage("objDVariables_ValueChanged2() : Unknown Datatype !")
   '            End Select

   '            Me.Invoke(CType(Function()
   '                               _Variables(IdxVar, 1).Text = sValue
   '                            End Function, MethodInvoker))
   '         End If

   '      Catch Ex As Exception
   '         DisplayMessage("objDVariables_ValueChanged2 " & Ex.Message & " Index : " + index)
   '      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_ValueChanged2(ByVal msgNumber As Object, ByVal line As Object)
      ' resetto stati bFound
      For Each Message In m_ReadOperatorMessages
         Message.bFound = False
      Next
      Dim objMsgNumber As Object() = CType(msgNumber, Object())
      Dim objLine As Object() = CType(line, Object())
      Dim OpMsgErrType As Integer = 30
      For index As Integer = 0 To objMsgNumber.Length - 1
         Dim nIndex As Integer = index
         Dim NewMessageInList As ReadMessages = m_ReadOperatorMessages.FirstOrDefault(Function(x) x.CMsgCncNumber = 0 AndAlso
                                                                                                  x.CMsgErrorType = OpMsgErrType.ToString() AndAlso
                                                                                                  x.CMsgErrorIndex = "" AndAlso
                                                                                                  x.CMsgErrorNumber = objMsgNumber(nIndex).ToString() AndAlso
                                                                                                  x.CMsgErrorLine = "" AndAlso
                                                                                                  x.CMsgErrorMessage = objLine(nIndex).ToString() 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(index).ToString()) Then
               ' lo aggiungo
               Dim NewMessage As ReadMessages = New ReadMessages(0,
                                                              OpMsgErrType.ToString(),
                                                              "",
                                                              objMsgNumber(index).ToString(),
                                                              "",
                                                              objLine(index).ToString(),
                                                              "")
               NewMessage.bFound = True
               m_ReadOperatorMessages.Add(NewMessage)
               m_NUMAlarmCallbackDlg(0, 0, OpMsgErrType.ToString(), "", objMsgNumber(index).ToString(), "", objLine(index).ToString(), "")
            End If
         End If
      Next

      ' 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

Public Class ReadMessages

   Public CMsgCncNumber As String
   Public CMsgErrorType As String
   Public CMsgErrorIndex As String
   Public CMsgErrorNumber As String
   Public CMsgErrorLine As String
   Public CMsgErrorMessage As String
   Public CMsgErrorAdditional As String
   Public bFound As Boolean = False
   Public Sub New(ByVal MsgCncNumber As Integer, ByVal MsgErrorType As String, ByVal MsgErrorIndex As String, ByVal MsgErrorNumber As String, ByVal MsgErrorLine As String, ByVal MsgErrorMessage As String, ByVal MsgErrorAdditional As String)
      CMsgCncNumber = MsgCncNumber
      CMsgErrorType = MsgErrorType
      CMsgErrorIndex = MsgErrorIndex
      CMsgErrorNumber = MsgErrorNumber
      CMsgErrorLine = MsgErrorLine
      CMsgErrorMessage = MsgErrorMessage
      CMsgErrorAdditional = MsgErrorAdditional
   End Sub

End Class
