Imports System.Runtime.InteropServices
Imports System.Threading
Imports EgtBEAMWALL.Core
Imports EgtBEAMWALL.Core.ConstMachComm
Imports EgtUILib
Imports EgtWPFLib5

Public Class NUMAxiumPcToolkitComm

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

   Enum OPOMTYPE As Integer
      OP = &H11
      OM = &H12
   End Enum

   Const MODE = 180, ACTIVE_PROG = 181

   Const DNC_MODE_FIRST = 0, DNC_MODE_CONTINUE = 1, DNC_MODE_ABORT = 2, DNC_MODE_OPEN = 3, DNC_MODE_CLOSE = 4
   Const DNC_IN_PROGRES = &HC8, DNC_OPEN = &H3A00, DNC_WRITE = &H3B00, DNC_CLOSE = &H3C00, FILE_NOT_EXIST = &HFFFE

   Const SYN = 0 ' /* synchrone */
   Const ASS = 1 ' /* assynchrone send request */
   Const ASR = 2 ' /* assynchrone read response */

   Private Enum eVarious2
      MODE = 180
      ACTIVE_PROG = 181
   End Enum

   Private Enum eVarious4
      CTRL_AXES = 143
      SPINDLE_SPEED = 144
      SPINDLE_POS = 145
      H_VAR = 147
      MOS_OK = 149
      E80000 = 150
      E81000 = 151
      E82000 = 152
      E30000 = 30 ' aggiunto da noi, non presente nella documentazione Num e gestito a parte rispetto agli altri
   End Enum

   Const R1 = &HA401, R2 = &HA402, RL = &HA442
   Const VL = &HA042

   Public Structure My_data_struct
      <MarshalAs(UnmanagedType.ByValArray, SizeConst:=256)>
      Public data As Byte()
   End Structure

   <StructLayout(LayoutKind.Explicit)>
   Public Structure tDNC20_ObjectList
      <FieldOffset(0)> Public ElemNum As UInt16
      <FieldOffset(2)> Public First As UInt16
      <FieldOffset(4)> Public Quantity As UInt16
   End Structure

   'Public Structure tDNC20_Position_OPOM
   '   Dim Valid As UINT8
   '   Dim dummy(3) As UINT8
   '   Dim Position As Int32
   '   Dim ToGo As SINT32
   '   Dim Offset As SINT32
   'End Structure

   <System.Runtime.InteropServices.DllImport("LIB_UNIT2.DLL")>
   Private Shared Function SetPLCTool(ByVal conf As String) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("LIB_UNIT2.DLL")>
   Private Shared Function Get_Port(ByRef Port As Int16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("LIB_UNIT2.DLL")>
   Private Shared Function Close_Unite() As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("LIB_UNIT2.DLL")>
   Private Shared Function Free_Port(ByVal Port As Int16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function StartNC(ByVal Port As Int16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function StopNC(ByVal Port As Int16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function InitNC(ByVal Port As Int16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function ReadObjectVarious2(ByVal Port As Int16, ByVal qui As UInt16, ByRef pData As UInt16, ByVal Mode As UInt16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function WriteObjectVarious2(ByVal Port As Int16, ByVal qui As UInt16, ByRef pData As Int32) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function DownLoadFileAsyn(ByVal Port As Int16, ByVal Prog As Int32, ByVal Filename As String, Mode As Int16, ByRef pIndex As Short) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function DncDeleteFile(ByVal Port As Int16, ByVal Prog As Int32) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc20_2.dll")>
   Private Shared Function DNC20_DialWithModes_2(ByVal Port As Int16, ByVal pstring As String, ByVal Mode As UInt16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function ReadLadderVar(ByVal Port As Int16, ByVal qui As UInt16, ByVal First As UInt16, ByVal Quantity As UInt16, ByRef pData As My_data_struct, ByVal Mode As UInt16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function WriteLadderVar(ByVal Port As Int16, ByVal qui As UInt16, ByVal First As UInt16, ByVal Quantity As UInt16, ByRef pData As Integer) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function ReadObjectVarious4(ByVal Port As Int16, ByVal qui As UInt16, ByVal First As UInt16, ByVal Quantity As UInt16, ByRef pData As My_data_struct, ByVal Mode As UInt16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc2.dll")>
   Private Shared Function WriteObjectVarious4(ByVal Port As Int16, ByVal qui As UInt16, ByVal First As UInt16, ByVal Quantity As UInt16, ByRef pData As Integer) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc20_2.dll")>
   Private Shared Function DNC20_Position_OPOM(ByVal Port As Int16, ByVal Group As UInt16, ByRef pData As My_data_struct, ByVal Mode As UInt16, ByVal OPOM As UInt16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc20_2.dll")>
   Private Shared Function DNC20_WriteE5E6(ByVal Port As Int16, ByVal Group As UInt16, ByVal ParType As UInt16, ByVal ParPos As UInt16, ByVal ParVal As UInt32, ByVal Mode As UInt16) As Int16
   End Function

   <System.Runtime.InteropServices.DllImport("dnc20_2.dll")>
   Private Shared Function DNC20_ReadExxxxx(ByVal Port As Int16, ByVal Group As UInt16, ByVal ElemNb As UInt16, ByRef DataList As tDNC20_ObjectList, ByRef Data As UInt32, ByVal Mode As UInt16) As Int16
   End Function

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

   Private m_sConnectionString As String = "XIP01,0,63,0,0,0"
   Public ReadOnly Property sConnectionString As String
      Get
         Return m_sConnectionString
      End Get
   End Property

   Private m_nPortVariables As Int16
   Public ReadOnly Property nPortVariables As Int16
      Get
         Return m_nPortVariables
      End Get
   End Property

   Private m_nPortWVariables As Int16
   Public ReadOnly Property nPortWVariables As Int16
      Get
         Return m_nPortWVariables
      End Get
   End Property

   Private m_nPortCommands As Int16
   Public ReadOnly Property nPortCommands As Int16
      Get
         Return m_nPortCommands
      End Get
   End Property

   Private m_nPortFileTransfer As Int16
   Public ReadOnly Property nPortFileTransfer As Int16
      Get
         Return m_nPortFileTransfer
      End Get
   End Property

   Private m_bIsTransferActive As Boolean = False
   Public ReadOnly Property bIsTransferActive As Boolean
      Get
         Return m_bIsTransferActive
      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 Function InitConnection() As Boolean
      ' recupero stringa di connessione
      GetPrivateProfileString(S_GENERAL, K_CONNECTIONSTRING, "XIP01,0,63,0,0,0", m_sConnectionString, CurrentMachine.sMachIniFile)
      Dim nRet, nRet2, nRet3, nRet4 As Int16
      ' inizializzo comunicazione
      nRet = SetPLCTool(sConnectionString)
      If nRet <> 0 Then
         EgtOutLog("Communication not available (SetPLCTool) : " & nRet.ToString & " - " & sConnectionString)
         Return False
      End If
      'Richiedo porta comunicazione PC-CN
      nRet = Get_Port(m_nPortVariables)
      nRet2 = Get_Port(m_nPortCommands)
      nRet3 = Get_Port(m_nPortFileTransfer)
      nRet4 = Get_Port(m_nPortWVariables)
      If nRet <> 0 OrElse nRet2 <> 0 OrElse nRet3 <> 0 OrElse nRet4 <> 0 Then
         EgtOutLog("Ports not available (Get_Port) : " & nRet.ToString() & " " & nRet2.ToString() & " " & nRet3.ToString() & " " & nRet4.ToString())
         ' Connection error
         m_MachManaging.SetConnected(False)
         m_ResultCallbackDlg(CommandTypes.CONNECT, CommandStates.ERROR_, ResultTypes.RESULT, "")
         Return False
      Else
         EgtOutLog("Port connected: " & nPortVariables.ToString() & " " & nPortCommands.ToString() & " " & nPortFileTransfer.ToString() & " " & nPortWVariables.ToString())
         ' Connected
         m_MachManaging.SetConnected(True)
         m_ResultCallbackDlg(CommandTypes.CONNECT, CommandStates.OK, ResultTypes.RESULT, "")
      End If
      'EgtOutLog("Activating program 9000")

      ' attivo programma main
      Map.refMachManaging.Num_Axium_PCToolkit.ActivateProg(9000)
      'EgtOutLog("Activated program 9000")
      Return True
   End Function

   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()
      '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()
      ' Annullo variabile E30099 per trasferimento programmi
      Dim SendPermissionVariable As Variable = Map.refMachCommandMessagePanelVM.MainVariablesList.FirstOrDefault(Function(x) x.sName = SENDPERMISSION)
      If Not IsNothing(SendPermissionVariable) Then
         SendPermissionVariable.sValue = 0
      End If
      Dim nRet As Int16 = -1
      nRet = StartNC(nPortCommands)
      If nRet <> 0 Then
         EgtOutLog("Error in start: " & nRet)
      End If
   End Sub

   Friend Sub Stop_()
      Dim nRet As Int16 = -1
      nRet = StopNC(nPortCommands)
      If nRet <> 0 Then
         EgtOutLog("Error in stop: " & nRet)
      End If
   End Sub

   Friend Sub Reset()
      Dim nRet As Int16 = -1
      nRet = InitNC(nPortCommands)
      If nRet <> 0 Then
         EgtOutLog("Error in reset: " & nRet)
      End If
   End Sub

   Friend Sub SetMode(value As CNMode)
      WriteObjectVarious2(nPortCommands, MODE, value)
   End Sub

   Friend Sub SetChannel(value As Integer)
      'ChangeChannel(CShort(value))
   End Sub

   Friend Sub ActivateProg(PartProgramNumberActivate As Integer)
      Dim nRes As Int16 = -1
      nRes = WriteObjectVarious2(nPortFileTransfer, ACTIVE_PROG, PartProgramNumberActivate)
      If nRes <> 0 Then
         EgtOutLog("Error Activate Program: " & nRes.ToString())
         'Else
         '   DbControllers.m_LogMachineController.Create(MachLog.CreateResultLog(CommandTypes.SENDPROG, CommandStates.OK, ResultTypes.EXECUTED, "Part program activated:" & " " & PartProgramNumberActivate))
      End If
      ' scrivo evento programma attivato
      DbControllers.m_LogMachineController.Create(LogEvent.CreateMachCommandLog(LogEvent.MachineCommands.PROGRAM_ACTIVATION, PartProgramNumberActivate, nRes <> 0, DbControllers.SupervisorId))
   End Sub

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

   Friend Sub StartReadList()
      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 _FXReturn As Short = objDVariables.Init(objDGroupManager.Handle, sPLCVariableList, 1) 'PlcVariablesList.ToArray().ToString())

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

   Friend Sub StartReadPLCList()
      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)

      '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)
      Try
         Dim dValue As Double = 0
         StringToDoubleAdv(value, dValue)
         Select Case Address
            Case "E30099"     ' in realta' per scrivere si usa la %RD0C.L
               Dim nRes = WriteLadderVar(m_nPortWVariables, RL, &HD0C, 1, dValue)
               EgtOutLog("Scrittura E30099 - result " & nRes)
            Case Else      ' E30000
               Dim nType As eVarious4
               Dim nValue As Integer = 0
               Dim sAddressNumber As Integer = Address.Substring(1)
               Dim nAddressNumber As Integer = 0
               If Not Integer.TryParse(sAddressNumber, nAddressNumber) Then Return
               If nAddressNumber >= 30000 AndAlso nAddressNumber < 40000 Then
                  nType = eVarious4.E30000
                  nAddressNumber -= 30000
               End If
               Dim Group As UInt16 = 0
               Dim ParType As UInt16 = 3
               Dim ParPos As UInt16 = nAddressNumber
               If Not Integer.TryParse(value, nValue) Then Return
               EgtOutLog("WritePLCVariables - nType: " & nType & " nFirst: " & nAddressNumber & " Data: " & nValue)
               EgtOutLog("WritePLCVariables - nPortVariables: " & nPortVariables & " Group: " & Group & " ParType: " & ParType & " ParPos: " & ParPos & " nValue: " & nValue)
               Dim rc As Short = DNC20_WriteE5E6(m_nPortWVariables, Group, ParType, ParPos, nValue, SYN)
               EgtOutLog("WritePLCVariables - return value: " & rc)
         End Select

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

      Catch ex As Exception
         EgtOutLog("Error in DNC20_WriteE5E6: " & ex.Message)
      End Try
   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

   Public Sub RefreshAllVars()
      For Each Var In m_ReadingVars
         ' rileggo solo variabili continue
         If Not IsNothing(Var) AndAlso Var.nReadType = CommVar.ReadTypes.CONTINUOUS Then
            Dim MyData As New My_data_struct
            If Var.nType = CommVar.Types.CN Then
               Dim nret As Short = -1
               Dim nType As eVarious4
               Dim sAddressNumber As Integer = Var.sAddress.Substring(1)
               Dim nAddressNumber As Integer = 0
               If Not Integer.TryParse(sAddressNumber, nAddressNumber) Then Return
               If nAddressNumber >= 82000 Then
                  nType = eVarious4.E82000
                  nAddressNumber -= 82000
               ElseIf nAddressNumber >= 81000 Then
                  nType = eVarious4.E81000
                  nAddressNumber -= 81000
               ElseIf nAddressNumber >= 80000 Then
                  nType = eVarious4.E80000
                  nAddressNumber -= 80000
                  'ElseIf nAddressNumber >= 30000 Then
                  '   nType = eVarious4.E30000
                  '   nAddressNumber -= 30000
                  '   EgtOutLog("E30000 var trovata")
               End If
               'If nType = eVarious4.E30000 Then
               '   Dim Group As UInt16 = 0
               '   Dim nVal As Int32
               '   Dim ObjectList As New tDNC20_ObjectList With {.ElemNum = 3,
               '                                                 .First = nAddressNumber,
               '                                                 .Quantity = 1}
               '   EgtOutLog("E30000 var trovata, valori: " & nPortVariables & " " & Group & "" & ObjectList.First & " " & nVal)

               '   nret = DNC20_ReadExxxxx(nPortVariables, Group, 1, ObjectList, nVal, SYN)
               '   EgtOutLog("E30000 var risultato: " & nret)
               '   If nret = 0 Then
               '      Var.SetValue(nVal)
               '      EgtOutLog("E30000 var assegnata: " & nVal)
               '   End If
               'Else
               nret = ReadObjectVarious4(nPortVariables, nType, nAddressNumber, 1, MyData, SYN)
               If nret = 0 Then
                  'Var.SetValue(MyData.data(0))
                  'Dim NewBytes(3) As Byte
                  'For nBIndex = 3 To 0 Step -1
                  '   NewBytes(3 - nBIndex) = MyData.data(nBIndex)
                  'Next
                  Dim nVal As Integer = BitConverter.ToInt32(MyData.data, 0)
                  Var.SetValue(nVal)
               End If
               'End If
               'EgtOutLog("Variabile: " & Var.sAddress & " Tipo: " & nType & " NAddres: " & nAddressNumber & " Valore: " & nVal)
            ElseIf Var.nType = CommVar.Types.PLC Then
               Dim nRet As Short = -1
               Dim nRes As Integer
               Select Case Var.sAddress
                  Case "%R3.2"
                     nRet = ReadLadderVar(nPortVariables, R2, &H3, 1, MyData, SYN)
                     nRes = If(MyData.data(0) <> 0, 1, 0)
                     'EgtOutLog("Variabile: " & Var.sAddress & "DVal: " & nRes & " Valore: " & MyData.data(0) & "," & MyData.data(1) & "," & MyData.data(2) & "," & MyData.data(3))
                  Case "%R3.1"
                     nRet = ReadLadderVar(nPortVariables, R1, &H3, 1, MyData, SYN)
                     nRes = If(MyData.data(0) <> 0, 1, 0)
                     'EgtOutLog("Variabile: " & Var.sAddress & "DVal: " & nRes & " Valore: " & MyData.data(0) & "," & MyData.data(1) & "," & MyData.data(2) & "," & MyData.data(3))
                  Case "%V800.L"
                     nRet = ReadLadderVar(nPortVariables, VL, &H800, 4, MyData, SYN)
                     nRes = BitConverter.ToInt32(MyData.data, 0)
                  Case "%V804.L"
                     nRet = ReadLadderVar(nPortVariables, VL, &H804, 4, MyData, SYN)
                     nRes = BitConverter.ToInt32(MyData.data, 0)
                  Case "%V808.L"
                     nRet = ReadLadderVar(nPortVariables, VL, &H808, 4, MyData, SYN)
                     nRes = BitConverter.ToInt32(MyData.data, 0)
                  Case "%V80C.L"
                     nRet = ReadLadderVar(nPortVariables, VL, &H80C, 4, MyData, SYN)
                     nRes = BitConverter.ToInt32(MyData.data, 0)
                  Case "%V810.L"
                     nRet = ReadLadderVar(nPortVariables, VL, &H810, 4, MyData, SYN)
                     nRes = BitConverter.ToInt32(MyData.data, 0)
                  Case "%V814.L"
                     nRet = ReadLadderVar(nPortVariables, VL, &H814, 4, MyData, SYN)
                     nRes = BitConverter.ToInt32(MyData.data, 0)
                  Case Else
                     Dim nType As eVarious4
                     Dim sAddressNumber As Integer = Var.sAddress.Substring(1)
                     Dim nAddressNumber As Integer = 0
                     If Not Integer.TryParse(sAddressNumber, nAddressNumber) Then Return
                     If nAddressNumber >= 30000 Then
                        nType = eVarious4.E30000
                        nAddressNumber -= 30000
                        'EgtOutLog("E30000 var trovata")
                     End If
                     If nType = eVarious4.E30000 Then
                        Dim Group As UInt16 = 0
                        Dim ObjectList As New tDNC20_ObjectList With {.ElemNum = 3,
                                                                .First = nAddressNumber,
                                                                .Quantity = 1}
                        EgtOutLog("E30000 var trovata, valori: " & nPortVariables & " " & Group & "" & ObjectList.First & " " & nRes)

                        nRet = DNC20_ReadExxxxx(nPortVariables, Group, 1, ObjectList, nRes, SYN)
                        EgtOutLog("E30000 var risultato: " & nRet)
                        If nRet = 0 Then
                           Var.SetValue(nRes)
                           EgtOutLog("E30000 var assegnata: " & nRes)
                        End If
                     End If
               End Select
               If nRet = 0 Then
                  'EgtOutLog("Variabile: " & Var.sAddress & "DVal: " & nRes & " Valore: " & MyData.data(0) & "," & MyData.data(1) & "," & MyData.data(2) & "," & MyData.data(3))
                  EgtOutLog("Variabile: " & Var.sAddress & "DVal: " & nRes)
                  Var.SetValue(nRes)
               End If
            End If
         End If
      Next
   End Sub

#Region "File transfer"

   Friend Sub FileDownload(nFileType As Integer, sFilePath As String)
      m_bIsTransferActive = True
      Dim FileTransferThread As New Thread(Sub()
                                              ' leggo variabile E30099
                                              Dim SendPermissionVariable As Variable = Map.refMachCommandMessagePanelVM.MainVariablesList.FirstOrDefault(Function(x) x.sName = SENDPERMISSION)
                                              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
                                                    Integer.TryParse(SendPermissionVariable.sValue, 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
                                              Dim nRes As Int16 = -1
                                              Dim nIndex As Int16 = 0
                                              DncDeleteFile(nPortFileTransfer, nFileType)
                                              EgtOutLog("Start download - " & nPortFileTransfer & nFileType & sFilePath & nIndex)
                                              nRes = DownLoadFileAsyn(nPortFileTransfer, nFileType, sFilePath, DNC_MODE_FIRST, nIndex)
                                              m_BytesTransferedCounter = nIndex
                                              If nRes <> DNC_IN_PROGRES Then
                                                 EgtOutLog("DownLoadFileAsyn error:" & nRes)
                                                 nRes = DownLoadFileAsyn(nPortFileTransfer, nFileType, sFilePath, DNC_MODE_ABORT, nIndex)
                                                 m_BytesTransferedCounter = 0
                                                 m_bIsTransferActive = False
                                                 Return
                                              End If
                                              While nRes = DNC_IN_PROGRES
                                                 EgtOutLog("Continuing download - " & nPortFileTransfer & nFileType & sFilePath & nIndex & nRes)
                                                 nRes = DownLoadFileAsyn(nPortFileTransfer, nFileType, sFilePath, DNC_MODE_CONTINUE, nIndex)
                                                 m_BytesTransferedCounter = nIndex
                                                 Map.refMyStatusBarVM.SetOutputMessage("Bytes sent: " & nIndex)
                                                 Threading.Thread.Sleep(100)
                                              End While
                                              If nRes <> 0 Then
                                                 EgtOutLog("DownLoadFileAsyn error: " & nRes)
                                                 Map.refMyStatusBarVM.SetOutputMessage("DownLoadFileAsyn error: " & nRes, 2)
                                              Else
                                                 EgtOutLog("DownLoadFileAsyn OK")
                                                 Map.refMyStatusBarVM.SetOutputMessage("DownLoadFileAsyn OK", 2)
                                                 ' 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)
                                                 EgtOutLog("Trovate variabili: " & ISONumVariable.sAddress & ISOSentVariable.sAddress)
                                                 Dim SentMachGroup As MyMachGroupVM = Map.refSupervisorMachGroupPanelVM.MachGroupVMList.FirstOrDefault(Function(x As MyMachGroupVM) x.bSendingToMachine)
                                                 EgtOutLog("Trovate variabili: " & ISONumVariable.sAddress & ISOSentVariable.sAddress & SentMachGroup.Name)
                                                 If Not IsNothing(SentMachGroup) Then
                                                    EgtOutLog("Trovato Machgroup")
                                                    Try
                                                       ISONumVariable.sValue = SentMachGroup.Name
                                                       ISOSentVariable.sValue = 0
                                                       'Dim TempISOSentVariable As Variable = Map.refMachCommandMessagePanelVM.MainVariablesList.FirstOrDefault(Function(x) x.sName = ISO_SENT)
                                                       'While ISOSentVariable.sValue <> "0"
                                                       '   Threading.Thread.Sleep(100)
                                                       '   EgtOutLog("Bloccato - Sent(80046): " & TempISOSentVariable.sValue & " Num(80045): " & ISONumVariable.sValue)
                                                       '   TempISOSentVariable = Map.refMachCommandMessagePanelVM.MainVariablesList.FirstOrDefault(Function(x) x.sName = ISO_SENT)
                                                       'End While
                                                       SentMachGroup.SetSentToMachine(True)
                                                    Catch ex As Exception
                                                       EgtOutLog("Error write var after download: " & ex.Message)
                                                    End Try
                                                 End If
                                              End If
                                              nRes = DownLoadFileAsyn(nPortFileTransfer, nFileType, sFilePath, DNC_MODE_ABORT, nIndex)
                                              SendPermissionVariable.sValue = 0
                                              m_BytesTransferedCounter = 0
                                              Threading.Thread.Sleep(1000)
                                              m_bIsTransferActive = False
                                              Return
                                           End Sub)
      ' avvio thread di gestione della macchina che avvia la connessione
      FileTransferThread.Start()


      'Dim nRes As Int16 = -1
      'Dim nIndex As Int16 = 0
      'nRes = DownLoadFileAsyn(nPortFileTransfer, sFileType, sFilePath, DNC_MODE_FIRST, nIndex)
      'm_BytesTransferedCounter = nIndex
      'If nRes <> DNC_IN_PROGRES Then
      '   EgtOutLog("DownLoadFileAsyn error:" & nRes)
      '   nRes = DownLoadFileAsyn(nPortFileTransfer, sFileType, sFilePath, DNC_MODE_ABORT, nIndex)
      '   m_BytesTransferedCounter = 0
      '   Return
      'End If
      'While nRes = DNC_IN_PROGRES
      '   nRes = DownLoadFileAsyn(nPortFileTransfer, sFileType, sFilePath, DNC_MODE_CONTINUE, nIndex)
      '   m_BytesTransferedCounter = nIndex
      '   Map.refMyStatusBarVM.SetOutputMessage("Bytes sent: ", 2)
      'End While
      'If nRes <> 0 Then
      '   EgtOutLog("DownLoadFileAsyn error: " & nRes)
      '   Map.refMyStatusBarVM.SetOutputMessage("DownLoadFileAsyn error: " & nRes, 2)
      'Else
      '   EgtOutLog("DownLoadFileAsyn OK")
      '   Map.refMyStatusBarVM.SetOutputMessage("DownLoadFileAsyn OK", 2)
      '   ' 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
      'nRes = DownLoadFileAsyn(nPortFileTransfer, sFileType, sFilePath, DNC_MODE_ABORT, nIndex)
      'm_BytesTransferedCounter = 0
      'Return
   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 nRes As Int16 = -1
      nRes = DncDeleteFile(nPortFileTransfer, sFileType)
      If nRes <> 0 Then
         EgtOutLog("Delete file not executed")
      End If
   End Sub

#End Region    ' File transfer

#Region "MDI"

   Friend Sub MDI_Execute(sCommand As String)
      Dim nRes As Int16 = -1
      nRes = DNC20_DialWithModes_2(nPortCommands, sCommand, SYN)
      If nRes = 0 Then
         Map.refMDIPageVM.SendMDIResult(nRes)
      Else
         EgtOutLog("DialWithModes2 error " & nRes)
      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 nType As eVarious4
         Dim nValue As Integer = 0
         Dim MyData As New My_data_struct
         Dim sAddressNumber As Integer = Address.Substring(1)
         Dim nAddressNumber As Integer = 0
         If Not Integer.TryParse(sAddressNumber, nAddressNumber) Then Return
         If nAddressNumber > 82000 Then
            nType = eVarious4.E82000
            nAddressNumber -= 82000
         ElseIf nAddressNumber > 81000 Then
            nType = eVarious4.E81000
            nAddressNumber -= 81000
         ElseIf nAddressNumber > 80000 Then
            nType = eVarious4.E80000
            nAddressNumber -= 80000
         End If
         If Not Integer.TryParse(value, nValue) Then Return
         MyData.data = BitConverter.GetBytes(CLng(nValue))
         EgtOutLog("WriteNCVariables - nType: " & nType & " nFirst: " & nAddressNumber & " Data: " & nValue)
         Dim rc As Short = WriteObjectVarious4(nPortWVariables, nType, nAddressNumber, 1, nValue)

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

      Catch ex As Exception
         EgtOutLog("Error in WriteObjectVarious4: " & 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_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 Ind 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(Ind).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 "Position"

   Friend Sub ReadPosition()
      Dim nRet As Short = -1
      Dim Group As UInt16 = 0
      Dim MyData As New My_data_struct
      nRet = DNC20_Position_OPOM(nPortVariables, Group, MyData, SYN, OPOMTYPE.OM)
      EgtOutLog("nRet: " & nRet)
      If nRet <> 0 Then
         EgtOutLog("Error in axis reading! Error: " & nRet)
         Return
      End If
      Dim AxisValid(8) As Boolean
      For AxisIndex = 0 To 8
         Dim AxisStart = AxisIndex * 16
         'Dim NbDeci, FacConv As UInt16
         'NbDeci = MyData.data(AxisStart) And &H3F
         'Select Case NbDeci
         '   Case 0
         '      FacConv = 1
         '      'FormatStr = "%9.0f"
         '   Case 1
         '      FacConv = 10
         '      'FormatStr = "%9.1f "
         '   Case 2
         '      FacConv = 100
         '      'FormatStr = "%9.2f "
         '   Case 3
         '      FacConv = 1000
         '      'FormatStr = "%9.3f "
         '   Case 4
         '      FacConv = 10000
         '      'FormatStr = "%9.4f "
         '   Case Else
         '      FacConv = 1000
         '      'FormatStr = "%9.3f "
         'End Select

         ''printf("%2x ", Data[i].Valid);
         'If MyData.data(AxisStart) And &H80 Then
         '   Dim dAxisPosition As Double = (BitConverter.ToInt32(MyData.data, AxisStart + 4)) / FacConv    'Vmminch  ' X
         '   m_AxisCoordinatesCallbackDlg(dAxisPosition, AxisIndex)
         'End If

         Dim n As Integer = AxisIndex * 16
         AxisValid(AxisIndex) = (MyData.data(n) <> 0)
         If AxisValid(AxisIndex) Then
            If AxisIndex < 6 Then
               Dim dAxisPosition As Double = (BitConverter.ToInt32(MyData.data, n + 4))      'Vmminch  ' X
               m_AxisCoordinatesCallbackDlg(dAxisPosition, AxisIndex)
               'd_axis_delta(i) = (BitConverter.ToInt32(MyData.data, n + 8)) / Vmminch
            Else
               Dim dAxisPosition As Double = (BitConverter.ToInt32(MyData.data, n + 4))            'NumCifreDecP4 ' A
               m_AxisCoordinatesCallbackDlg(dAxisPosition, AxisIndex)
               'd_axis_delta(i) = (BitConverter.ToInt32(MyData.data, n + 8)) / NumCifreDecP4
            End If
         End If
      Next
   End Sub

#End Region    ' Position

#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"

   Friend Sub ReadCncMode()
      Dim nRet As Short = -1
      Dim nMode As UInt16
      'EgtOutLog("Pre ReadObjectVarious2")
      nRet = ReadObjectVarious2(nPortVariables, eVarious2.MODE, nMode, SYN)
      'EgtOutLog("ReadObjectVarious2 Ret: " & nRet & " Mode: " & nMode)
      If nRet <> 0 Then
         EgtOutLog("Reading CncMode failed! Error: " & nRet)
         Return
      End If
      m_OpModeCallbackDlg(nMode)
   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
