Imports System.Windows.Threading
Imports System.Globalization
Imports System.Collections.ObjectModel
Imports EgtUILib
Imports System.IO
Imports System.Text
Imports EgtWPFLib.EgtMsgBox
Imports OmagCUT.CN_generico

Public Class CNCommunication

   ' Riferimenti a pagine
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Private m_MachineStatus As MachineStatusUC = m_MainWindow.m_MachineStatusUC
   Private m_AlarmsPage As AlarmsPageUC = m_MainWindow.m_MachinePageUC.m_AlarmsPageUC
   Private m_CurrProjPage As CurrentProjectPageUC = m_MainWindow.m_CurrentProjectPageUC

   Friend m_nCountRefresh As Integer = 0

   ' Variabile per tipologia CN
   Friend m_nNCType As Integer

   ' Variabile che indica il Mode corrente
   Private m_nCurrMode As Integer = -1

   ' Variabile che contiene la path del programmino di comunicazione CN Siemens
   Public m_sCNSiemensPath As String = String.Empty
   Public m_sCNSiemensHMIPath As String = String.Empty

   ' Oggetto CN
   Public WithEvents m_CN As CN_generico

   ' NUOVO ! in fase di test
   Private ListReferenceIndex As New List(Of RefereceFlagSimens)

   ' Flag di aggiornamento dati
   Private m_bNewPosData As Boolean = True
   Private m_bNewDeltaData As Boolean = True
   Private m_bNewVarData As Boolean = False
   Private m_bTimerBusy As Boolean = False
   Private m_bTimerAxesBusy As Boolean = False

   Private m_IsNewConsole As Boolean = False

   ' Lista errori
   Friend ErrorList As New ObservableCollection(Of String)

   ' Timer
   Private m_RefreshTimer As New DispatcherTimer
   Private m_RefreshAxesFanuc As New DispatcherTimer

   ' Nomi e indici degli assi macchina
   Private m_bAxesOk As Boolean = False
   Private m_sA1 As String = "X"
   Private m_nA1 As Integer = 0
   Private m_sA2 As String = "Y"
   Private m_nA2 As Integer = 1
   Private m_sA3 As String = "Z"
   Private m_nA3 As Integer = 2
   Private m_sA4 As String = "C"
   Private m_nA4 As Integer = 8
   Private m_sA5 As String = "B"
   Private m_nA5 As Integer = 7
   Private m_sA6 As String = "A"
   Private m_nA6 As Integer = 6
   Private m_sA7 As String = "U"
   Private m_nA7 As Integer = 3
   Private m_sA8 As String = "V"
   Private m_nA8 As Integer = 4
   Private m_sA9 As String = "W"
   Private m_nA9 As Integer = 5
   Private m_sA10 As String = "Q"
   Private m_nA10 As Integer = 9
   Private m_bInInches As Boolean = False   ' Solo per comandi diretti (assi sempre in mm)


   Friend Sub CNCommunication_Initialization()

      ' Associazione
      m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.ErrorLstBx.ItemsSource = ErrorList

      ' Verifico tipologia del CN
#If TRIAL Then
      m_nNCType = 0
#Else
      If Not m_MainWindow.m_bNCLink Then
         m_nNCType = 0
      Else
         m_nNCType = GetPrivateProfileInt(S_NUMERICALCONTROL, K_TYPE, 0, m_MainWindow.GetMachIniFile())
      End If
#End If
      Dim sVal As String = String.Empty

      EgtOutLog("NcLink=" & m_MainWindow.m_bNCLink.ToString & " type=" & m_nNCType)

      ' Se CN Siemens leggo dati programma intermedio di comunicazione
      If m_nNCType = 3 Then
         Dim sExeName As String = String.Empty
         GetPrivateProfileString(S_NCSIEMENS, K_COMM_NAME, "", sExeName, m_MainWindow.m_CurrentMachine.sMachIniFile)
         m_sCNSiemensPath = m_MainWindow.GetExeRootDir() & "\" & sExeName
         GetPrivateProfileString(S_NCSIEMENS, K_PATH_HMI, "", m_sCNSiemensHMIPath, m_MainWindow.m_CurrentMachine.sMachIniFile)
      End If

      ' Inizializzo la connessione
      InitCn()

      ' Verifico se la connessione è avvenuta e in caso affermativo lancio il timer di aggiornamento dell'interfaccia
      If m_nNCType > 0 Then
         AddHandler m_RefreshTimer.Tick, AddressOf RefreshTimer_tick
         m_RefreshTimer.Interval = TimeSpan.FromMilliseconds(100)
         m_RefreshTimer.Start()
      End If
      ' solo per controllo FANUC creo un timer apposito solo per la lettura degli assi
      If m_nNCType = 4 Then
         AddHandler m_RefreshAxesFanuc.Tick, AddressOf RefreshAxesFanucTimer_tick
         m_RefreshAxesFanuc.Interval = TimeSpan.FromMilliseconds(50)
         m_RefreshAxesFanuc.Start()
      End If

      ' Leggo dati sugli assi della macchina
      ReadAxesData()
      ' Aggiorno nomi assi
      m_MachineStatus.DisplayPositionName()

   End Sub

   Private Sub RefreshTimer_tick()
      If Not m_bTimerBusy Then

         m_bTimerBusy = True
         m_RefreshTimer.Stop()

         If m_nNCType = 3 Then
            RefreshNoEvents()
         ElseIf m_nNCType = 4 Then
            RefreshFANUC()
         Else
            Refresh()
         End If

         If Not String.IsNullOrEmpty(m_MainWindow.m_CurrentMachine.sClickState) Then
            ClickOnPolishLine()
         End If

         m_bTimerBusy = False
         m_RefreshTimer.Start()
      Else
         Dim nDummy As Integer = 10
      End If

   End Sub

   Private Sub RefreshAxesFanucTimer_tick()
      If Not m_bTimerAxesBusy Then
         m_bTimerAxesBusy = True
         m_RefreshAxesFanuc.Stop()

         RefreshAxesFANUC()

         m_bTimerAxesBusy = False
         m_RefreshAxesFanuc.Start()
      Else
         Dim nDummy As Integer = 10
      End If
   End Sub

   Private Sub ReadAxesData()
      ' Nomi e indici degli assi macchina: definisco il nome degli assi da satampare nella pagina MachineStatusUC
      m_bAxesOk = True
      GetPrivateProfileString(S_AXES, K_L1NAME, "X", m_sA1, m_MainWindow.GetMachIniFile())
      m_nA1 = GetPrivateProfileInt(S_AXES, K_L1ID, 0, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA1) Then
         m_nA1 = -1
         m_bAxesOk = False
         EgtOutLog("Error on L1ID")
      End If
      GetPrivateProfileString(S_AXES, K_L2NAME, "Y", m_sA2, m_MainWindow.GetMachIniFile())
      m_nA2 = GetPrivateProfileInt(S_AXES, K_L2ID, 1, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA2) Then
         m_nA2 = -1
         m_bAxesOk = False
         EgtOutLog("Error on L2ID")
      End If
      GetPrivateProfileString(S_AXES, K_L3NAME, "Z", m_sA3, m_MainWindow.GetMachIniFile())
      m_nA3 = GetPrivateProfileInt(S_AXES, K_L3ID, 2, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA3) Then
         m_nA3 = -1
         m_bAxesOk = False
         EgtOutLog("Error on L3ID")
      End If
      GetPrivateProfileString(S_AXES, K_R1NAME, "C", m_sA4, m_MainWindow.GetMachIniFile())
      m_nA4 = GetPrivateProfileInt(S_AXES, K_R1ID, 8, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA4) Then
         m_nA4 = -1
         m_bAxesOk = False
         EgtOutLog("Error on R1ID")
      End If
      GetPrivateProfileString(S_AXES, K_R2NAME, "B", m_sA5, m_MainWindow.GetMachIniFile())
      m_nA5 = GetPrivateProfileInt(S_AXES, K_R2ID, 7, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA5) Then
         m_nA5 = -1
         m_bAxesOk = False
         EgtOutLog("Error on R2ID")
      End If
      GetPrivateProfileString(S_AXES, K_A6NAME, "A", m_sA6, m_MainWindow.GetMachIniFile())
      m_nA6 = GetPrivateProfileInt(S_AXES, K_A6ID, 6, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA6) Then
         m_nA6 = -1
         m_bAxesOk = False
         EgtOutLog("Error on A6ID")
      End If
      GetPrivateProfileString(S_AXES, K_A7NAME, "U", m_sA7, m_MainWindow.GetMachIniFile())
      m_nA7 = GetPrivateProfileInt(S_AXES, K_A7ID, 3, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA7) Then
         m_nA7 = -1
         m_bAxesOk = False
         EgtOutLog("Error on A7ID")
      End If
      GetPrivateProfileString(S_AXES, K_A8NAME, "V", m_sA8, m_MainWindow.GetMachIniFile())
      m_nA8 = GetPrivateProfileInt(S_AXES, K_A8ID, 4, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA8) Then
         m_nA8 = -1
         m_bAxesOk = False
         EgtOutLog("Error on A8ID")
      End If
      GetPrivateProfileString(S_AXES, K_A9NAME, "W", m_sA9, m_MainWindow.GetMachIniFile())
      m_nA9 = GetPrivateProfileInt(S_AXES, K_A9ID, 5, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA9) Then
         m_nA9 = -1
         m_bAxesOk = False
         EgtOutLog("Error on A9ID")
      End If
      GetPrivateProfileString(S_AXES, K_A10NAME, "P", m_sA10, m_MainWindow.GetMachIniFile())
      m_nA10 = GetPrivateProfileInt(S_AXES, K_A10ID, 5, m_MainWindow.GetMachIniFile())
      If Not m_CN.VerifyAxis(m_nA10) Then
         m_nA10 = -1
         m_bAxesOk = False
         EgtOutLog("Error on A10ID")
      End If
      ' Unità di misura
      m_bInInches = (GetPrivateProfileInt(S_AXES, K_ININCHES, 0, m_MainWindow.GetMachIniFile()) <> 0)
   End Sub

   Private Sub KillSimensCom(sProcessName As String)
      Dim sAppName As String = Path.GetFileNameWithoutExtension(sProcessName)
      Dim pList() As System.Diagnostics.Process = System.Diagnostics.Process.GetProcesses
      For Each proc As System.Diagnostics.Process In pList
         If proc.ProcessName.ToString = sAppName Then
            proc.Kill()
            EgtOutLog("ProcessKill : " & """" & sProcessName & """")
         End If
      Next
   End Sub

   Private Sub InitCn()

      m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_Yellow")

      ' istanzio l'oggetto CN e lo inizializzo
      Try
         ' Creo l'oggetto per la comunicazione
         Select Case m_nNCType
            Case 0
               m_CN = New CN_Debug
            Case 1
               m_CN = New Num.NumNCOld
            Case 2
               m_CN = New Num.NumNC
            Case 3
               m_CN = New CN_Siemens
            Case 4
               ' Fanuc
               m_CN = New Fanuc.Fanuc
               ' proveddo a sovrscrivere i datti di comunicazione PC-NC settati di default nella classe CN_Generico
               m_MainWindow.m_CurrentMachine.InitFANUC(m_CN)
         End Select
         ' Recupero la stringa di inizializzazione della comunicazione

         ' definisco il tipo di varibili che devono essere scritte nl plc
         Dim sVal As String = String.Empty
         Dim nVal As Integer = 0
         'GetPrivateProfileString(S_NCDATA, K_NEWVARIABLE, "0", sVal, m_MainWindow.GetMachIniFile())
         nVal = GetPrivateProfileInt(S_NCDATA, K_NEWVARIABLE, nVal, m_MainWindow.GetMachIniFile())
         'm_CN.m_NewVariable = sVal <> "0"
         m_CN.m_NewVariable = (nVal <> 0)
         EgtOutLog("NewVariable=" & If(m_CN.m_NewVariable, "1", "0"))

         ' Recupero e imposto le variabili per i dati del CN (feed, speed,...)
         GetPrivateProfileString(S_NCDATA, K_COMM, "XIP01, 0, 10, 0, 0, 0", sVal, m_MainWindow.GetMachIniFile())
         EgtOutLog(" → Tipo di comunicazione: " & sVal)
         m_CN.SetCnDataVar(CN_generico.CnData.Comm, sVal)
         GetPrivateProfileString(S_NCDATA, K_REFRESH, "200", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Refresh, sVal)
         GetPrivateProfileString(S_NCDATA, K_MODE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Mode, sVal)
         GetPrivateProfileString(S_NCDATA, K_JOGINCR, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.JogIncr, sVal)
         GetPrivateProfileString(S_NCDATA, K_FEED, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Feed, sVal)
         GetPrivateProfileString(S_NCDATA, K_FEEDOVR, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.FeedOvr, sVal)
         GetPrivateProfileString(S_NCDATA, K_SPEED, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Speed, sVal)
         GetPrivateProfileString(S_NCDATA, K_SPEEDOVR, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.SpeedOvr, sVal)
         GetPrivateProfileString(S_NCDATA, K_POWER, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Power, sVal)
         GetPrivateProfileString(S_NCDATA, K_SPINDLE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Spindle, sVal)
         GetPrivateProfileString(S_NCDATA, K_LASER, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Laser, sVal)
         GetPrivateProfileString(S_NCDATA, K_LASERTRAC, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.LaserTrac, sVal)
         GetPrivateProfileString(S_NCDATA, K_COOLANT, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Coolant, sVal)
         GetPrivateProfileString(S_NCDATA, K_INTERNALCOOLANT, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.InternalCoolant, sVal)
         GetPrivateProfileString(S_NCDATA, K_EXTERNCOOLANT, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.ExternCoolant, sVal)
         GetPrivateProfileString(S_NCDATA, K_CAXES, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.CBAxes, sVal)
         GetPrivateProfileString(S_NCDATA, K_AIRBLOW, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.AirBlow, sVal)
         GetPrivateProfileString(S_NCDATA, K_HOME, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Home, sVal)
         GetPrivateProfileString(S_NCDATA, K_TABLEUP, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.TableUp, sVal)
         GetPrivateProfileString(S_NCDATA, K_TABLEDOWN, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.TableDown, sVal)
         GetPrivateProfileString(S_NCDATA, K_DOORCLOSED, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.DoorClosed, sVal)
         GetPrivateProfileString(S_NCDATA, K_LIMITZ, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.LimitZ, sVal)
         GetPrivateProfileString(S_NCDATA, K_POWEROVR, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.PowerOvr, sVal)

         GetPrivateProfileString(S_NCDATA, K_PARKING, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Parking, sVal)
         GetPrivateProfileString(S_NCDATA, K_ENABLEZONE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.EnableZone, sVal)
         GetPrivateProfileString(S_NCDATA, K_ENABLEPC, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.EnablePC, sVal)

         GetPrivateProfileString(S_NCDATA, K_VACUUMUP, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.VacuumUp, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUMDOWN, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.VacuumDown, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM2UP, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum2Up, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM2DOWN, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum2Down, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM0, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum0, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM90, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum90, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM1STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum1State, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM2STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum2State, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM3STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum3State, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM4STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum4State, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM5STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum5State, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM6STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum6State, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM135STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum135State, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUM246STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Vacuum246State, sVal)
         GetPrivateProfileString(S_NCDATA, K_OPENALLSTATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.OpenAllState, sVal)
         GetPrivateProfileString(S_NCDATA, K_CLOSEALLSTATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.CloseAllState, sVal)
         GetPrivateProfileString(S_NCDATA, K_OPEN123STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Open123State, sVal)
         GetPrivateProfileString(S_NCDATA, K_OPEN456STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Open456State, sVal)
         GetPrivateProfileString(S_NCDATA, K_CLOSE123STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Close123State, sVal)
         GetPrivateProfileString(S_NCDATA, K_CLOSE456STATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.Close456State, sVal)
         GetPrivateProfileString(S_NCDATA, K_BLOWSTATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.BlowState, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUMON, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.VacuumOn, sVal)
         GetPrivateProfileString(S_NCDATA, K_VACUUMOFF, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.VacuumOff, sVal)
         GetPrivateProfileString(S_NCDATA, K_BYPASSTATE, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.BypassState, sVal)
         ' ver 2.6i1 : nuova gestione SiemensONE
         GetPrivateProfileString(S_NCDATA, K_RESETSTATUS, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.ResetStatus, sVal)

         ' nuove variabili: stato dei nuovi pulsanti
         nVal = GetPrivateProfileInt(S_NCDATA, K_NEWCONSOLE, 0, m_MainWindow.GetMachIniFile())
         m_IsNewConsole = (nVal = 1)
         If m_IsNewConsole Then
            GetPrivateProfileString(S_NCDATA, K_XYJOG, "", sVal, m_MainWindow.GetMachIniFile())
            If Not String.IsNullOrEmpty(sVal) Then m_CN.SetCnDataVar(CN_generico.CnData.XYJog, sVal)
            GetPrivateProfileString(S_NCDATA, K_ZCJOG, "", sVal, m_MainWindow.GetMachIniFile())
            If Not String.IsNullOrEmpty(sVal) Then m_CN.SetCnDataVar(CN_generico.CnData.ZCJog, sVal)
            GetPrivateProfileString(S_NCDATA, K_ZBJOG, "", sVal, m_MainWindow.GetMachIniFile())
            If Not String.IsNullOrEmpty(sVal) Then m_CN.SetCnDataVar(CN_generico.CnData.ZBJog, sVal)
            GetPrivateProfileString(S_NCDATA, K_POWERON, "", sVal, m_MainWindow.GetMachIniFile())
            If Not String.IsNullOrEmpty(sVal) Then m_CN.SetCnDataVar(CN_generico.CnData.PowerON, sVal)
            GetPrivateProfileString(S_NCDATA, K_REMOTE, "", sVal, m_MainWindow.GetMachIniFile())
            If Not String.IsNullOrEmpty(sVal) Then m_CN.SetCnDataVar(CN_generico.CnData.Remote, sVal)
         End If

         ' Solo per controllo FANUC
         GetPrivateProfileString(S_NCDATA, K_NAXES, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.nAxes, sVal)

         ' Solo per controllo speciale NUM 22/01/2025
         GetPrivateProfileString(S_NCDATA, K_CPOS, "", sVal, m_MainWindow.GetMachIniFile())
         m_CN.SetCnDataVar(CN_generico.CnData.CPos, sVal)
         If Not String.IsNullOrEmpty(sVal) Then m_CN.bCPos = True

         ' Inizializzo la comunicazione
         m_CN.Init()

      Catch ex As Exception
         ' set status to statusbar
         EgtOutLog("Error starting NC communication : " & ex.Message)
      End Try

      '' !!!!!!!!!!!!! Per forzare la lettura delle variabili siemens di configurazione !!!!!!!!!!!!!
      ' m_nNCType = 3
      '' !!!!!!!!!!!!! Per forzare la lettura delle variabili siemens di configurazione !!!!!!!!!!!!!

      Select Case m_nNCType
         Case 0   'Debug
            m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_Yellow")
         Case 1, 2  'Axium, Flexium
            If IsNothing(m_CN) OrElse m_CN.n_state < 2 Then
               ' Per evitare crash con azioni verso il controllo, avvio quello di debug
               m_nNCType = 0
               Me.m_CN = New CN_Debug
               m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_Red")
            Else
               m_CN.b_axis_events_enable = True
               m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_DarkGray")
            End If
         Case 3  'Siemens
            If IsNothing(m_CN) Then
               ' Per evitare crash con azioni verso il controllo, avvio quello di debug
               m_nNCType = 0
               Me.m_CN = New CN_Debug
               m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_Red")
            Else
               ' Avvio programmino di comunicazione
               Try
                  m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_DarkGray")
                  Dim sArg As String = "-start """ & m_sCNSiemensPath & """"

                  ' !!!!!!!!!!!!!! FORZO LA SIMULAZIONE DELLA LETTURA DELLE VARIBILI E SIEMENS !!!!!!!!!!!!!!
                  EgtOutLog("ProcessStart : " & """" & m_sCNSiemensHMIPath & """" & " " & sArg)
                  KillSimensCom(m_sCNSiemensHMIPath)
                  Process.Start(m_sCNSiemensHMIPath, sArg)
                  ' !!!!!!!!!!!!!! FORZO LA SIMULAZIONE DELLA LETTURA DELLE VARIBILI E SIEMENS !!!!!!!!!!!!!!

                  EgtOutLog("ProcessStart : " & """" & m_sCNSiemensHMIPath & """" & " " & sArg)
                  m_CN.m_IsSiemensOne = GetPrivateProfileInt(S_NCSIEMENS, K_ISSIEMENSONE, 0, m_MainWindow.GetMachIniFile()) > 0
                  m_CN.m_IsActiveModeSubscription = GetPrivateProfileInt(S_NCSIEMENS, K_ISACTIVEMODESUBSCR, 0, m_MainWindow.GetMachIniFile()) > 0
                  If m_CN.m_IsSiemensOne Then

                     ' Leggo tutte le varaibili che sono state caricate nel percorso [NcData] del file *.ini
                     Dim nIndexArrayBool As Integer = 0
                     Dim nIndexArrayInt As Integer = 0
                     Dim nIndexArrayLong As Integer = 0
                     Dim nIndexArrayDoub As Integer = 0
                     Dim nIndexArrayStr As Integer = 0
                     ' lista che associa Indice del vettore al nome (per associazioni Bit a Bit)
                     Dim ListIndexToVar As New List(Of IndexArrayToBit)
                     ' Creo un vettore che mi permetta di risalire a cosa contiene ogni vettore FLAG (di tipo Enum) 
                     For ItemIndex As Integer = 0 To m_CN.m_szCnDataVar.Count - 1
                        ' escludo i Flag 'Comm' e 'Refresh'
                        If ItemIndex = CnData.Comm Or ItemIndex = CnData.Refresh Then
                           Continue For
                        End If
                        If Not String.IsNullOrEmpty(m_CN.m_szCnDataVar(ItemIndex)) Then
                           Dim sItem As String() = m_CN.m_szCnDataVar(ItemIndex).Split(","c)
                           Dim nVarType As VarType = VarType.TInteger
                           If sItem.Count > 1 Then
                              If IsNumeric(sItem(0)) Then
                                 Select Case CInt(sItem(0))
                                    Case 0
                                       If nIndexArrayBool > 14 Then
                                          Continue For
                                       End If
                                       nVarType = VarType.TBoolean
                                       m_CN.DVariables_Read_Subscription(sItem(1), nVarType, nIndexArrayBool)
                                       Dim NewRefFlafSiemens As RefereceFlagSimens = New RefereceFlagSimens(nIndexArrayBool, ItemIndex, nVarType)
                                       If sItem.Count = 3 Then
                                          ' forzo la lettura della variabile di default (ignoro lo stato letto da CN)
                                          NewRefFlafSiemens.DefaultValue = sItem(2)
                                       End If
                                       ListReferenceIndex.Add(NewRefFlafSiemens)
                                       nIndexArrayBool += 1
                                    Case 1
                                       If nIndexArrayInt > 14 Then
                                          Continue For
                                       End If
                                       nVarType = VarType.TInteger
                                       m_CN.DVariables_Read_Subscription(sItem(1), nVarType, nIndexArrayInt)
                                       ListReferenceIndex.Add(New RefereceFlagSimens(nIndexArrayInt, ItemIndex, nVarType))
                                       nIndexArrayInt += 1
                                    Case 2
                                       If nIndexArrayLong > 14 Then
                                          Continue For
                                       End If
                                       nVarType = VarType.TLong
                                       m_CN.DVariables_Read_Subscription(sItem(1), nVarType, nIndexArrayLong)
                                       ListReferenceIndex.Add(New RefereceFlagSimens(nIndexArrayLong, ItemIndex, nVarType))
                                       nIndexArrayLong += 1
                                    Case 3
                                       If nIndexArrayDoub > 14 Then
                                          Continue For
                                       End If
                                       nVarType = VarType.TDouble
                                       m_CN.DVariables_Read_Subscription(sItem(1), nVarType, nIndexArrayDoub)
                                       ListReferenceIndex.Add(New RefereceFlagSimens(nIndexArrayDoub, ItemIndex, nVarType))
                                       nIndexArrayDoub += 1
                                    Case 4
                                       If nIndexArrayStr > 14 Then
                                          Continue For
                                       End If
                                       nVarType = VarType.TString
                                       m_CN.DVariables_Read_Subscription(sItem(1), nVarType, nIndexArrayStr)
                                       ListReferenceIndex.Add(New RefereceFlagSimens(nIndexArrayStr, ItemIndex, nVarType))
                                       nIndexArrayStr += 1
                                    Case 5
                                       If nIndexArrayInt > 14 Then
                                          Continue For
                                       End If
                                       ' verifico se devo riempire un vettore con bit
                                       Dim sSubItem As String() = sItem(1).Split("."c)
                                       ' //My. name. Is Bond._James Bond!
                                       Dim sVarName = String.Join(".", sSubItem.Take(sSubItem.Length - 1)) ' //My. name. Is Bond
                                       Dim sIndexBit = sSubItem.Last() ' //_James Bond!
                                       If sSubItem.Count > 1 And IsNumeric(sIndexBit) Then
                                          Dim bFound As Boolean = False
                                          Dim nIndexArrayInt_1 As Integer = nIndexArrayInt
                                          For Each VarSiemens As IndexArrayToBit In ListIndexToVar
                                             If VarSiemens.sNameVar.Trim = sVarName.Trim Then
                                                nIndexArrayInt_1 = VarSiemens.nIndex
                                                bFound = True
                                                Exit For
                                             End If
                                          Next
                                          nVarType = VarType.TInteger
                                          m_CN.DVariables_Read_Subscription(sVarName, nVarType, nIndexArrayInt_1)
                                          Dim NewRefFlafSiemens As RefereceFlagSimens = New RefereceFlagSimens(nIndexArrayInt_1, ItemIndex, nVarType, sIndexBit)
                                          If sItem.Count = 3 Then
                                             ' forzo la lettura della variabile di default (ignoro lo stato letto da CN)
                                             NewRefFlafSiemens.DefaultValue = sItem(2)
                                          End If
                                          ListReferenceIndex.Add(NewRefFlafSiemens)
                                          If Not bFound Then
                                             nIndexArrayInt += 1
                                             ListIndexToVar.Add(New IndexArrayToBit(nIndexArrayInt_1, sVarName.Trim))
                                          End If
                                       Else
                                          EgtOutLog(" ATTENZIONE: in [NcData] '" & m_CN.m_szCnDataVar(ItemIndex) & "' non è inidicato il bit associato")
                                       End If
                                    Case Else
                                       If nIndexArrayInt > 14 Then
                                          Continue For
                                       End If
                                       nVarType = VarType.TInteger
                                       m_CN.DVariables_Read_Subscription(sItem(1), nVarType, nIndexArrayInt)
                                       ListReferenceIndex.Add(New RefereceFlagSimens(nIndexArrayInt, ItemIndex, nVarType))
                                       nIndexArrayInt += 1
                                 End Select
                              End If
                           Else
                              EgtOutLog(" ATTENZIONE: in [NcData] '" & m_CN.m_szCnDataVar(ItemIndex) & "' non è indicato il tipo (0→Bool,1→Int,2→Long,3→Double,4→String,5→Bit)")
                           End If
                        End If
                     Next
                     ' Attraverso la funzione "RefreshNoEvents" rileggo i dati caricati

                     ' Recupero il perocorso delle variabili PLC
                     GetPrivateProfileString(S_NCSIEMENS, K_DBVARPATH, "", m_CN.m_DbVarPath, m_MainWindow.GetMachIniFile)

                  ElseIf m_CN.m_IsActiveModeSubscription Then
                     m_CN.DVariables_Read_Subscription(m_CN.m_szCnDataVar(CN_generico.CnData.BlowState), VarType.TInteger, 3)
                  End If
               Catch ex As Exception
                  EgtOutLog("Error starting Process -> NcLink=True type=0")
                  ' Per evitare crash con azioni verso il controllo, avvio quello di debug
                  Me.m_CN.Stop_Connection()
                  m_nNCType = 0
                  Me.m_CN = New CN_Debug
                  m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_Red")
               End Try
            End If
         Case 4
            If IsNothing(m_CN) OrElse m_CN.n_state < 2 Then
               ' Per evitare crash con azioni verso il controllo, avvio quello di debug
               m_nNCType = 0
               Me.m_CN = New CN_Debug
               m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_Red")
            Else
               ' ATTENZIONE: durante l'inizializzazione della classe il vettore che contiene tutti gli indirizzi di memoria non è caricato
               m_CN.b_axis_events_enable = True
               m_MachineStatus.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_DarkGray")
            End If
      End Select

      ' Assegno riferimento al CN alle diverse pagine
      m_MainWindow.m_MachineStatusUC.m_CN = Me.m_CN
      m_MainWindow.m_MachinePageUC.m_AlarmsPageUC.m_CN = Me.m_CN
      m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.m_CN = Me.m_CN
      m_MainWindow.m_DirectCutPageUC.m_MachineButtons.m_CN = Me.m_CN
      m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.m_CN = Me.m_CN
      m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.m_CN = Me.m_CN
      m_MainWindow.m_DirectCutPageUC.m_ManualAxesMove.m_CN = Me.m_CN
      m_MainWindow.m_DirectCutPageUC.m_CN = Me.m_CN
      m_MainWindow.m_RawPartPage.m_MachineButtons.m_CN = Me.m_CN
      m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.m_CN = Me.m_CN

   End Sub

   Private Sub NewVarChanged_handler(ByVal nst As Object) Handles m_CN.NewVarChanged

      m_bNewVarData = True

   End Sub

   Private Sub NewPositionData_handler(ByVal nst As Short) Handles m_CN.NewPositionData

      m_bNewPosData = True

   End Sub

   Private Sub NewPosDeltaData_handler(ByVal nst As Short) Handles m_CN.NewPosDeltaData

      m_bNewDeltaData = True

   End Sub

   Private Sub ClickOnPolishLine()
      ' Se richiesto di scattare foto sulla linea di lucidatura
      m_CN.n_DReadELS_handle = 0
      m_CN.ReadEls_Add_Parameter(m_MainWindow.m_CurrentMachine.sClickState, 1)
      Dim nClickState As Integer = 0
      For I As Integer = 0 To 10
         System.Threading.Thread.Sleep(50)
         If m_CN.n_DReadELS_handle = 1 Then
            nClickState = CInt(m_CN.d_DReadELS_value)
            If nClickState = 1 Then
               ' procedo a costruire un nuovo file nella cartella indicata in configurazione
               Try
                  Dim fs As FileStream = File.Create(m_MainWindow.m_CurrentMachine.sClickDir & "\NewClick.txt")
                  ' chiudo il file creato
                  fs.Close()
                  ' Dichiaro di aver provveduto a comunicare di scattare la foto
                  m_CN.DVariables_WriteVariables2(m_MainWindow.m_CurrentMachine.sClickState, "0")
               Catch ex As Exception
                  EgtOutLog("Error on PolishLine comunication: " & ex.ToString)
               End Try
            End If
            Exit For
         End If
      Next

   End Sub

   Private Sub Refresh()

      If m_bNewPosData Then
         m_bNewPosData = False
         m_MachineStatus.DisplayPosition()
      End If

      If m_bNewDeltaData Then
         m_bNewDeltaData = False
         m_MachineStatus.DisplayPositionDelta()
      End If

      ' ----- INIZIO: lettura diretta di specifiche vaiabili -----
      If m_CN.b_feed_changed Then
         m_CN.b_feed_changed = False
         m_MachineStatus.DisplayFeed()
      End If

      If m_CN.b_spindle_data_changed Then
         m_CN.b_spindle_data_changed = False
         m_MachineStatus.DisplaySpeed()
      End If

      If m_CN.b_spindle_power_changed Then
         m_CN.b_spindle_power_changed = False
         m_MachineStatus.DisplayPower()
      End If

      If m_bNewVarData Then
         m_bNewVarData = False
         m_MachineStatus.DisplayVar()
      End If

      If m_CN.b_Tool_data_changed Then
         m_CN.b_Tool_data_changed = False
         'FrmMain.LblToolLen.Text = cn.Tools(0).lenght.ToString
         'FrmMain.LblToolRad.Text = cn.Tools(0).radius.ToString
         'FrmMain.LblToolComp.Text = cn.Tools(0).comp_num.ToString
      End If
      ' ----- FINE : lettura diretta di specifiche vaiabili -----

      Select Case m_nNCType
         Case 1
            If m_CN.read_active_mode() <> m_nCurrMode Then
               m_nCurrMode = m_CN.read_active_mode()
               m_MachineStatus.DisplayActiveMode(m_nCurrMode)
               m_CN.nMachineMode = m_nCurrMode
            End If
         Case 2
            If m_CN.nMachineMode <> m_nCurrMode Then
               m_nCurrMode = m_CN.nMachineMode
               m_MachineStatus.DisplayActiveMode(m_nCurrMode)
            End If
      End Select

      If m_CN.b_NC_error Then
         ErrorList.Clear()
         SyncLock m_CN
            For Each Item As String In m_CN.sz_NC_error_messages
               ErrorList.Add(Item)
            Next
         End SyncLock
         m_AlarmsPage.NcError()
      Else
         If ErrorList.Count > 0 Then
            ErrorList.Clear()
            m_AlarmsPage.NcError()
         End If
      End If

      If m_CN.b_PLC_error Then
         SyncLock m_CN
            m_AlarmsPage.PlcError(m_CN.sz_PLC_error_messages)
         End SyncLock
      Else
         'Dim BackColor As SolidColorBrush = m_MainWindow.m_MachineStatusUC.MachineStatusGrid.Background
         'If Colors.Red.Equals(BackColor.Color) Then
         '   m_MainWindow.m_MachineStatusUC.MachineStatusGrid.Background = Brushes.DarkGray
         'End If
      End If

      ' QUESTE VARIABILI NON SONO LETTE IN QUANTO NON SONO STATE CARICATE → vedere come esempio il NUM che assegna queste variabili
      ' Flag e variabili per bottoni macchina, che verifico solo nelle pagine in cui ci sono
      If m_MainWindow.m_ActivePage = MainWindow.Pages.DirectCut Then
         If m_MainWindow.m_DirectCutPageUC.m_NewMachineButtonsType Then
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.SpindleStateChanged(m_CN.bSpindleState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LaserStateChanged(m_CN.bLaserState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LaserTracStateChanged(m_CN.bLaserTracState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.CoolantStateChanged(m_CN.bCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.InternalCoolantStateChanged(m_CN.bInternalCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.ExternCoolantStateChanged(m_CN.bExternCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.CBAxesStateChanged(m_CN.bCBAxesState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.AirBlowStateChanged(m_CN.bAirBlowState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.HomeStateChanged(m_CN.bHomeState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.TableUpChanged(m_CN.bTableUpState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.TableDownChanged(m_CN.bTableDownState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.DoorClosedChanged(m_CN.nDoorClosedState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LimitZChanged(m_CN.bLimitZState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.FiveAxisStateChanged(m_CN.Is_G24_active())
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.ParkingStateChanged(m_CN.bParkingState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.ZoneStateChanged(m_CN.nEnableZone)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.PcStateChanged(m_CN.nEnablePc)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumUpChanged(m_CN.bVacuumUp)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumDownChanged(m_CN.bVacuumDown)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2UpChanged(m_CN.bVacuum2Up)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2DownChanged(m_CN.bVacuum2Down)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum0Changed(m_CN.bVacuum0)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum90Changed(m_CN.bVacuum90)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum1Changed(m_CN.bVacuum1State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2Changed(m_CN.bVacuum2State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum3Changed(m_CN.bVacuum3State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum4Changed(m_CN.bVacuum4State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum5Changed(m_CN.bVacuum5State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum6Changed(m_CN.bVacuum6State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum135Changed(m_CN.bVacuum135State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum246Changed(m_CN.bVacuum246State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.OpenAllChanged(m_CN.bOpenAllState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.CloseAllChanged(m_CN.bCloseAllState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Open123Changed(m_CN.bOpen123State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Open456Changed(m_CN.bOpen456State)
            ' in assenza della configurazione delle variabili Close123 e Close456
            If Not String.IsNullOrEmpty(m_CN.m_szCnDataVar(CN_generico.CnData.Close123State)) Then
               m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close123Changed(m_CN.bClose123State)
               m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close456Changed(m_CN.bClose456State)
            Else
               m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close123Changed(Not m_CN.bOpen123State)
               m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close456Changed(Not m_CN.bOpen456State)
            End If
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.BlowChanged(m_CN.bBlowState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumOnChanged(m_CN.bVacuumOn)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumOffChanged(m_CN.bVacuumOff)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.BypassChanged(m_CN.bBypassState)

            ' Nuovi bottoni (uso joystick)
            If m_IsNewConsole Then
               m_MainWindow.m_DirectCutPageUC.XYJogChanged(m_CN.bXYJog)
               m_MainWindow.m_DirectCutPageUC.ZCJogChanged(m_CN.bZCJog)
               m_MainWindow.m_DirectCutPageUC.ZBJogChanged(m_CN.bZBCJog)
               m_MainWindow.m_DirectCutPageUC.RemoteChanged(m_CN.bRemote)
               m_MainWindow.m_DirectCutPageUC.ParkingStateChanged(m_CN.bParkingState)
            End If
         Else
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.SpindleStateChanged(m_CN.bSpindleState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.CoolantStateChanged(m_CN.bCoolantState OrElse m_CN.bInternalCoolantState OrElse m_CN.bExternCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.LaserTracStateChanged(m_CN.bLaserTracState)
            If m_CN.Is_G24_active() Then
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ThreeAxisStateChanged(False)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.FiveAxisStateChanged(True)
            Else
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ThreeAxisStateChanged(True)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.FiveAxisStateChanged(False)
            End If
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.DoorStateChanged(m_CN.nDoorClosedState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ParkingStateChanged(m_CN.bParkingState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.HomeStateChanged(m_CN.bHomeState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.EnableZoneStateChanged(m_CN.nEnableZone)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.EnablePcStateChanged(m_CN.nEnablePc)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.TableUpChanged(m_CN.bTableUpState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.TableDownChanged(m_CN.bTableDownState)

            ' Nuovi bottoni (uso joystick) per Area4
            If m_IsNewConsole Then
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.XYJogChanged(m_CN.bXYJog)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ZJogChanged(m_CN.bZCJog)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.BCJogChanged(m_CN.bZBCJog)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.RemoteChanged(m_CN.bRemote)
               m_MainWindow.m_DirectCutPageUC.ParkingStateChanged(m_CN.bParkingState)
            End If

         End If
      End If

      If m_MainWindow.m_ActivePage = MainWindow.Pages.RawPart Then
         m_MainWindow.m_RawPartPage.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
      End If

      ' Nuove bottoni (Power Macchina)
      If m_MainWindow.m_ActivePage = MainWindow.Pages.Machine Then
         If m_IsNewConsole Then
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.PowerONChanged(m_CN.bPowerON)
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.PowerOFFChanged(Not m_CN.bPowerON)
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.CncModeChange(m_CN.nMachineMode)
         End If
         m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.CncModeChange(m_CN.nMachineMode)
      End If



      If m_MainWindow.m_ActivePage = MainWindow.Pages.WorkInProgress Then
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.SpindleStateChanged(m_CN.bSpindleState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.CoolantStateChanged(m_CN.bCoolantState OrElse m_CN.bInternalCoolantState OrElse m_CN.bExternCoolantState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.LaserTracStateChanged(m_CN.bLaserTracState)
         If m_CN.Is_G24_active() Then
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.ThreeAxisStateChanged(False)
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.FiveAxisStateChanged(True)
         Else
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.ThreeAxisStateChanged(True)
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.FiveAxisStateChanged(False)
         End If
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.DoorStateChanged(m_CN.nDoorClosedState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.ParkingStateChanged(m_CN.bParkingState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.EnableZoneStateChanged(m_CN.nEnableZone)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.EnablePcStateChanged(m_CN.nEnablePc)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.TableUpChanged(m_CN.bTableUpState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.TableDownChanged(m_CN.bTableDownState)
      End If

   End Sub

   Private Sub RefreshAxesFANUC()
      ' ----- INIZIO: lettura diretta di specifiche vaiabili -----
      ' avvio lettura variabili da CN
      m_CN.Geppo()
      ' notifico valori all'interfaccia
      m_MachineStatus.DisplayPosition()
      m_MachineStatus.DisplayPositionDelta()
      m_MachineStatus.DisplayFeed()
      m_MachineStatus.DisplaySpeed()
      m_MachineStatus.DisplayPower()
   End Sub

   Private Sub RefreshFANUC()
      ' Copia della funzione Refresh

      ' ----- INIZIO: lettura diretta di specifiche vaiabili -----
      '' avvio lettura variabili da CN
      'm_CN.Geppo()
      '' notifico valori all'interfaccia
      'm_MachineStatus.DisplayPosition()
      'm_MachineStatus.DisplayPositionDelta()
      'm_MachineStatus.DisplayFeed()
      'm_MachineStatus.DisplaySpeed()
      'm_MachineStatus.DisplayPower()
      ' eventualmente carico messaggi di errore
      ErrorList.Clear()
      If m_CN.b_NC_error Then
         ErrorList.Clear()
         SyncLock m_CN
            For Each Item As String In m_CN.sz_NC_error_messages
               ErrorList.Add(Item)
            Next
         End SyncLock
      End If
      m_AlarmsPage.NcError()
      ' ----- FINE  : lettura diretta di specifiche vaiabili -----

      If m_CN.read_active_mode() <> CShort(m_nCurrMode) Then
         m_nCurrMode = CInt(m_CN.read_active_mode())
         m_MachineStatus.DisplayActiveMode(m_nCurrMode)
         m_CN.nMachineMode = m_nCurrMode
      End If

      ' QUESTE VARIABILI NON SONO LETTE IN QUANTO NON SONO STATE CARICATE → vedere come esempio il NUM che assegna queste variabili
      ' Flag e variabili per bottoni macchina, che verifico solo nelle pagine in cui ci sono
      If m_MainWindow.m_ActivePage = MainWindow.Pages.DirectCut Then
         If m_MainWindow.m_DirectCutPageUC.m_NewMachineButtonsType Then
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.SpindleStateChanged(m_CN.bSpindleState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LaserStateChanged(m_CN.bLaserState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LaserTracStateChanged(m_CN.bLaserTracState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.CoolantStateChanged(m_CN.bCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.InternalCoolantStateChanged(m_CN.bInternalCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.ExternCoolantStateChanged(m_CN.bExternCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.CBAxesStateChanged(m_CN.bCBAxesState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.AirBlowStateChanged(m_CN.bAirBlowState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.HomeStateChanged(m_CN.bHomeState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.TableUpChanged(m_CN.bTableUpState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.TableDownChanged(m_CN.bTableDownState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.DoorClosedChanged(m_CN.nDoorClosedState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LimitZChanged(m_CN.bLimitZState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.FiveAxisStateChanged(m_CN.Is_G24_active())
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.ParkingStateChanged(m_CN.bParkingState)
            'm_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.ZoneStateChanged(m_CN.nEnableZone)
            'm_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.PcStateChanged(m_CN.nEnablePc)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumUpChanged(m_CN.bVacuumUp)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumDownChanged(m_CN.bVacuumDown)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2UpChanged(m_CN.bVacuum2Up)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2DownChanged(m_CN.bVacuum2Down)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum0Changed(m_CN.bVacuum0)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum90Changed(m_CN.bVacuum90)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum1Changed(m_CN.bVacuum1State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2Changed(m_CN.bVacuum2State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum3Changed(m_CN.bVacuum3State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum4Changed(m_CN.bVacuum4State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum5Changed(m_CN.bVacuum5State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum6Changed(m_CN.bVacuum6State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum135Changed(m_CN.bVacuum135State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum246Changed(m_CN.bVacuum246State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.OpenAllChanged(m_CN.bOpenAllState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.CloseAllChanged(m_CN.bCloseAllState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Open123Changed(m_CN.bOpen123State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Open456Changed(m_CN.bOpen456State)
            ' in assenza della configurazione delle variabili Close123 e Close456
            If Not String.IsNullOrEmpty(m_CN.m_szCnDataVar(CN_generico.CnData.Close123State)) Then
               m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close123Changed(m_CN.bClose123State)
               m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close456Changed(m_CN.bClose456State)
            Else
               m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close123Changed(Not m_CN.bOpen123State)
               m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close456Changed(Not m_CN.bOpen456State)
            End If
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.BlowChanged(m_CN.bBlowState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumOnChanged(m_CN.bVacuumOn)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumOffChanged(m_CN.bVacuumOff)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.BypassChanged(m_CN.bBypassState)

            ' Nuovi bottoni (uso joystick)
            If m_IsNewConsole Then
               m_MainWindow.m_DirectCutPageUC.XYJogChanged(m_CN.bXYJog)
               m_MainWindow.m_DirectCutPageUC.ZCJogChanged(m_CN.bZCJog)
               m_MainWindow.m_DirectCutPageUC.ZBJogChanged(m_CN.bZBCJog)
               m_MainWindow.m_DirectCutPageUC.RemoteChanged(m_CN.bRemote)
               m_MainWindow.m_DirectCutPageUC.ParkingStateChanged(m_CN.bParkingState)
            End If
         Else
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.SpindleStateChanged(m_CN.bSpindleState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.CoolantStateChanged(m_CN.bCoolantState OrElse m_CN.bInternalCoolantState OrElse m_CN.bExternCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.LaserTracStateChanged(m_CN.bLaserTracState)
            If m_CN.Is_G24_active() Then
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ThreeAxisStateChanged(False)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.FiveAxisStateChanged(True)
            Else
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ThreeAxisStateChanged(True)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.FiveAxisStateChanged(False)
            End If
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.DoorStateChanged(m_CN.nDoorClosedState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ParkingStateChanged(m_CN.bParkingState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.EnableZoneStateChanged(m_CN.nEnableZone)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.EnablePcStateChanged(m_CN.nEnablePc)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.TableUpChanged(m_CN.bTableUpState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.TableDownChanged(m_CN.bTableDownState)

            ' Nuovi bottoni (uso joystick) per Area4
            If m_IsNewConsole Then
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.XYJogChanged(m_CN.bXYJog)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ZJogChanged(m_CN.bZCJog)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.BCJogChanged(m_CN.bZBCJog)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.RemoteChanged(m_CN.bRemote)
               m_MainWindow.m_DirectCutPageUC.ParkingStateChanged(m_CN.bParkingState)
            End If

         End If
      End If

      If m_MainWindow.m_ActivePage = MainWindow.Pages.RawPart Then
         m_MainWindow.m_RawPartPage.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
      End If

      ' Nuove bottoni (Power Macchina)
      If m_MainWindow.m_ActivePage = MainWindow.Pages.Machine Then
         If m_IsNewConsole Then
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.PowerONChanged(m_CN.bPowerON)
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.PowerOFFChanged(Not m_CN.bPowerON)
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.CncModeChange(m_CN.nMachineMode)
         End If
         m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.CncModeChange(m_CN.nMachineMode)
      End If



      If m_MainWindow.m_ActivePage = MainWindow.Pages.WorkInProgress Then
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.SpindleStateChanged(m_CN.bSpindleState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.CoolantStateChanged(m_CN.bCoolantState OrElse m_CN.bInternalCoolantState OrElse m_CN.bExternCoolantState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.LaserTracStateChanged(m_CN.bLaserTracState)
         If m_CN.Is_G24_active() Then
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.ThreeAxisStateChanged(False)
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.FiveAxisStateChanged(True)
         Else
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.ThreeAxisStateChanged(True)
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.FiveAxisStateChanged(False)
         End If
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.DoorStateChanged(m_CN.nDoorClosedState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.ParkingStateChanged(m_CN.bParkingState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.EnableZoneStateChanged(m_CN.nEnableZone)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.EnablePcStateChanged(m_CN.nEnablePc)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.TableUpChanged(m_CN.bTableUpState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.TableDownChanged(m_CN.bTableDownState)
      End If

   End Sub

   <Flags()>
   Public Enum ControlStates As Integer
      None = 0
      Jog = 1
      CAxis = 2
      BAxis = 4
      Axis3 = 8
      Axis5 = 16
      LimitZ = 32
      Spindle = 64
      AirBlow = 128
      LaserTrac = 256
      Coolant = 512
      InternalCoolant = 1024
      ExternCoolant = 2048
      Home = 4096
      TableUp = 8192
      TableDown = 16384
   End Enum

   <Flags()>
   Public Enum ControlStates2 As Integer
      None = 0
      Laser = 1
      Hsm = 2
      ResetState = 4
      SpindleHold = 8
      FeedHold = 16
      'LimitZ = 32
      'Spindle = 64
      'AirBlow = 128
      'LaserTrac = 256
      'Coolant = 512
      'InternalCoolant = 1024
      'ExternCoolant = 2048
      'Home = 4096
      'TableUp = 8192
      'TableDown = 16384
   End Enum

   <Flags()>
   Public Enum VacuumStates As Integer
      None = 0
      Vacuum2Down = 1
      Vacuum2Up = 2
      VacuumDown = 4
      VacuumUp = 8
      VacuumOn = 16
      AirBlow = 32
      VacuumOff = 64
      BypassState = 128
      Vacuum1State = 256
      Vacuum2State = 512
      Vacuum3State = 1024
      Vacuum4State = 2048
      Vacuum5State = 4096
      Vacuum6State = 8192
      'Laser = 16384
   End Enum

#Region "MASCHERA per conttrollo Bit a Bit"
   <Flags()>
   Public Enum Mask As Integer
      bit_Err = -1
      bit_0 = &H1       ' 1
      bit_1 = &H2       ' 2
      bit_2 = &H4       ' 4
      bit_3 = &H8       ' 8
      bit_4 = &H10      ' 16
      bit_5 = &H20      ' 32
      bit_6 = &H40      ' 64
      bit_7 = &H80      ' 128
      bit_8 = &H100     ' 256
      bit_9 = &H200     ' 512
      bit_10 = &H400     ' 1024
      bit_11 = &H800     ' 2048
      bit_12 = &H1000    ' 4096
      bit_13 = &H2000    ' 8192
      bit_14 = &H4000    ' 16384
      bit_15 = &H8000    ' 32768
   End Enum

   Public Function GetMaskByBit(IndexBit As Integer) As Mask
      Dim Bit_ As Mask = Mask.bit_Err
      Select Case IndexBit
         Case 0
            Bit_ = Mask.bit_0
         Case 1
            Bit_ = Mask.bit_1
         Case 2
            Bit_ = Mask.bit_2
         Case 3
            Bit_ = Mask.bit_3
         Case 4
            Bit_ = Mask.bit_4
         Case 5
            Bit_ = Mask.bit_5
         Case 6
            Bit_ = Mask.bit_6
         Case 7
            Bit_ = Mask.bit_7
         Case 8
            Bit_ = Mask.bit_8
         Case 9
            Bit_ = Mask.bit_9
         Case 10
            Bit_ = Mask.bit_10
         Case 11
            Bit_ = Mask.bit_11
         Case 12
            Bit_ = Mask.bit_12
         Case 13
            Bit_ = Mask.bit_13
         Case 14
            Bit_ = Mask.bit_14
         Case 15
            Bit_ = Mask.bit_15
      End Select
      Return Bit_
   End Function
#End Region    ' Maschera per controllo Bit a Bit

   Public Function IsSetAll(value As Integer, flag As Integer) As Boolean
      ' somma Bit a Bit
      Return ((value And flag) = flag)
   End Function

   Private Sub RefreshNoEvents()

      m_MachineStatus.DisplayPosition()

      m_MachineStatus.DisplayPositionDelta()

      m_MachineStatus.DisplayFeed()

      m_MachineStatus.DisplaySpeed()

      'm_MachineStatus.DisplayPower()

      m_MachineStatus.DisplayVar()
      'EgtOutLog("Modo attivato: " & m_CN.read_active_mode & " modo attivo: " & m_nCurrMode)

      'If m_nCountRefresh > 10 Then
      '   Dim TempCurrMode As Short = m_CN.read_active_mode()
      '   'EgtOutLog("Machine status: " & TempCurrMode)
      '   If TempCurrMode <> m_nCurrMode Then
      '      'EgtOutLog("Modo attivo: " & m_CN.read_active_mode)
      '      m_nCurrMode = CInt(TempCurrMode)
      '      m_MachineStatus.DisplayActiveMode(m_nCurrMode)
      '   End If
      '   m_nCountRefresh = 0
      'Else
      '   m_nCountRefresh = m_nCountRefresh + 1
      'End If

      If m_CN.b_NC_error Then
         ErrorList.Clear()
         SyncLock m_CN
            For Each Item As String In m_CN.sz_NC_error_messages
               ErrorList.Add(Item)
            Next
         End SyncLock
         m_AlarmsPage.NcError()
      Else
         If ErrorList.Count > 0 Then
            ErrorList.Clear()
            m_AlarmsPage.NcError()
         End If
      End If

      ' lettura delle variabili abbonate
      If m_MainWindow.m_DirectCutPageUC.m_NewMachineButtonsType Then

         '------------ SINUMERIK ONE ----------------------------------------------
         For IndxLst As Integer = 0 To ListReferenceIndex.Count - 1
            Dim nType As Integer = ListReferenceIndex(IndxLst).TypeArray
            Dim nFlag As Integer = ListReferenceIndex(IndxLst).FlagIndex
            Dim nIndex As Integer = ListReferenceIndex(IndxLst).SiemnesArrayIndex
            Dim nIndexBit As Integer = ListReferenceIndex(IndxLst).IndexBit
            Dim sDefaultValue As String = ListReferenceIndex(IndxLst).DefaultValue
            Dim b_temp As Boolean = False
            Dim n_temp As Integer = 0
            Dim l_temp As Long = 0.0
            Dim d_temp As Double = 0.0
            ' leggo il valore caricato 
            Select Case nType
               Case VarType.TBoolean
                  If Not String.IsNullOrEmpty(sDefaultValue) Then
                     ' ver 2.6i1
                     Try
                        b_temp = CBool(sDefaultValue)
                     Catch ex As Exception
                        EgtOutLog("Default boolean value of flag " & nFlag.ToString & " is not Boolean, verify the form: True or true or 1, False or false or 0")
                        b_temp = m_CN.b_data(nIndex)
                     End Try
                  Else
                     b_temp = m_CN.b_data(nIndex)
                  End If
               Case VarType.TInteger
                  n_temp = m_CN.n_data(nIndex)
                  ' VENTOSE: lettura dato da intero Bit a Bit (ver_2.6h1), ritorno un Boolean
                  If Not String.IsNullOrEmpty(sDefaultValue) Then
                     ' ver 2.6i1
                     Try
                        b_temp = CBool(sDefaultValue)
                     Catch ex As Exception
                        EgtOutLog("Default bit value of flag " & nFlag.ToString & " is not Boolean, verify the form: True or true or 1, False or false or 0")
                        b_temp = ReadBit(nIndexBit, n_temp)
                     End Try
                  Else
                     b_temp = ReadBit(nIndexBit, n_temp)
                  End If
               Case VarType.TLong
                  l_temp = m_CN.l_data(nIndex)
               Case VarType.TDouble
                  d_temp = m_CN.d_data(nIndex)
               Case VarType.TString
                  'b_temp = If(m_CN.d_data(nIndex) = 0, True, False)
            End Select

            Select Case nFlag
               Case CN_generico.CnData.Mode    ' (0) Stato modo attivo
                  m_CN.n_index_mode = nIndex
                  If m_nCountRefresh > 10 Then
                     Dim TempCurrMode As Short = m_CN.read_active_mode()
                     'EgtOutLog("Machine status: " & TempCurrMode)
                     If TempCurrMode <> m_nCurrMode Then
                        'EgtOutLog("Modo attivo: " & m_CN.read_active_mode)
                        m_nCurrMode = CInt(TempCurrMode)
                        m_MachineStatus.DisplayActiveMode(m_nCurrMode)
                        m_CN.nMachineMode = m_nCurrMode
                     End If
                     m_nCountRefresh = 0
                  Else
                     m_nCountRefresh = m_nCountRefresh + 1
                  End If
               Case CN_generico.CnData.Power
                  m_CN.d_spindle_power = d_temp
               Case CN_generico.CnData.Spindle     ' (7) Stato rotazione mandrino
                  m_CN.bSpindleState = b_temp
               Case CN_generico.CnData.Coolant     ' (8) Stato acqua
                  m_CN.bCoolantState = b_temp
               Case CN_generico.CnData.Laser       ' (9) Stato laser punto
                  m_CN.bLaserState = b_temp
               Case CN_generico.CnData.PowerOvr       ' (10) Amperaggio
                  m_CN.bPowerOvr = d_temp
               Case CN_generico.CnData.InternalCoolant     ' (13) Stato acqua interna
                  m_CN.bInternalCoolantState = b_temp
               Case CN_generico.CnData.ExternCoolant     ' (14) Stato acqua esterna
                  m_CN.bExternCoolantState = b_temp
               Case CN_generico.CnData.CBAxes     ' (15) Stato ativazione assi c e b
                  m_CN.bCBAxesState = b_temp
               Case CN_generico.CnData.AirBlow     ' (16) Stato soffio utensile
                  m_CN.bAirBlowState = b_temp
               Case CN_generico.CnData.Home     ' (17) Stato home
                  m_CN.bHomeState = b_temp
               Case CN_generico.CnData.TableUp     ' (18) Stato tavolo su
                  m_CN.bTableUpState = b_temp
               Case CN_generico.CnData.TableDown     ' (19) Stato tavolo giu'
                  m_CN.bTableDownState = b_temp
               Case CN_generico.CnData.DoorClosed    ' (20) Stato porte
                  m_CN.nDoorClosedState = n_temp
               Case CN_generico.CnData.LimitZ     ' (21) Stato limitazione asse Z
                  m_CN.bLimitZState = b_temp
               Case CN_generico.CnData.VacuumUp     ' (22) Stato ventosa su'
                  m_CN.bVacuumUp = b_temp
               Case CN_generico.CnData.VacuumDown     ' (23) Stato ventosa giu'
                  m_CN.bVacuumDown = b_temp
               Case CN_generico.CnData.Vacuum2Up     ' (24) Stato ventosa2 su'
                  m_CN.bVacuum2Up = b_temp
               Case CN_generico.CnData.Vacuum2Down     ' (25) Stato ventosa2 giu'
                  m_CN.bVacuum2Down = b_temp
               Case CN_generico.CnData.Vacuum1State     ' (26) Stato ventosa 1
                  m_CN.bVacuum1State = b_temp
               Case CN_generico.CnData.Vacuum2State     ' (27) Stato ventosa 2
                  m_CN.bVacuum2State = b_temp
               Case CN_generico.CnData.Vacuum3State     ' (28) Stato ventosa 3
                  m_CN.bVacuum3State = b_temp
               Case CN_generico.CnData.Vacuum4State     ' (29) Stato ventosa 4
                  m_CN.bVacuum4State = b_temp
               Case CN_generico.CnData.Vacuum5State     ' (30) Stato ventosa 5
                  m_CN.bVacuum5State = b_temp
               Case CN_generico.CnData.Vacuum6State     ' (31) Stato ventosa 6
                  m_CN.bVacuum6State = b_temp
               Case CN_generico.CnData.Vacuum135State     ' (32) Stato ventose 135
                  m_CN.bVacuum135State = b_temp
               Case CN_generico.CnData.Vacuum246State     ' (33) Stato ventose 246
                  m_CN.bVacuum246State = b_temp
               Case CN_generico.CnData.OpenAllState     ' (34) Stato apertura ventose
                  m_CN.bOpenAllState = b_temp
               Case CN_generico.CnData.CloseAllState     ' (35) Stato chiusura ventose
                  m_CN.bCloseAllState = b_temp
               Case CN_generico.CnData.Open123State     ' (36) Stato apertura ventose
                  m_CN.bOpen123State = b_temp
               Case CN_generico.CnData.Open456State     ' (37) Stato apertura ventose
                  m_CN.bOpen456State = b_temp
               Case CN_generico.CnData.Close123State     ' (38) Stato chiusura ventose
                  m_CN.bClose123State = b_temp
               Case CN_generico.CnData.Close456State     ' (39) Stato chiusura ventose
                  m_CN.bClose456State = b_temp
               Case CN_generico.CnData.BlowState     ' (40) Stato soffio ventose
                  m_CN.bBlowState = b_temp
               Case CN_generico.CnData.VacuumOn     ' (41) Stato aspirazione ventose acceso
                  m_CN.bVacuumOn = b_temp
               Case CN_generico.CnData.BypassState     ' (42) Stato bypass
                  m_CN.bBypassState = b_temp
               Case CN_generico.CnData.Vacuum0     ' (43) Stato rotazione ventosa 0
                  m_CN.bVacuum0 = b_temp
               Case CN_generico.CnData.Vacuum90     ' (44) Stato rotazione ventosa 0
                  m_CN.bVacuum90 = b_temp
               Case CN_generico.CnData.VacuumOff     ' (45) Stato aspirazione ventose spento
                  m_CN.bVacuumOff = b_temp
               Case CN_generico.CnData.LaserTrac   ' (46) Stato laser tracciatura
                  m_CN.bLaserTracState = b_temp
               Case CN_generico.CnData.XYJog     ' (47) 
                  m_CN.bXYJog = b_temp
               Case CN_generico.CnData.ZCJog     ' (48)
                  m_CN.bZCJog = b_temp
               Case CN_generico.CnData.ZBJog     ' (49)
                  m_CN.bZBCJog = b_temp
               Case CN_generico.CnData.PowerON     ' (50)
                  m_CN.bPowerON = b_temp
               Case CN_generico.CnData.Remote     ' (51)
                  m_CN.bRemote = b_temp
               Case CN_generico.CnData.Parking     ' (52)
                  m_CN.bParkingState = b_temp
               Case CN_generico.CnData.nAxes     ' (55)
                  m_CN.n_index_is_G24_active = nIndex
                  m_CN.b5AxesState = b_temp
               Case CN_generico.CnData.ResetStatus     ' (56)
                  m_CN.bResetState = b_temp

            End Select
         Next
         '------------ SINUMERIK ONE ----------------------------------------------

      End If

      m_MachineStatus.DisplayPower()

      ' Flag e variabili per bottoni macchina, che verifico solo nelle pagine in cui ci sono
      If m_MainWindow.m_ActivePage = MainWindow.Pages.DirectCut Then
         If m_MainWindow.m_DirectCutPageUC.m_NewMachineButtonsType Then
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.SpindleStateChanged(m_CN.bSpindleState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LaserStateChanged(m_CN.bLaserState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LaserTracStateChanged(m_CN.bLaserTracState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.CoolantStateChanged(m_CN.bCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.InternalCoolantStateChanged(m_CN.bInternalCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.ExternCoolantStateChanged(m_CN.bExternCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.CBAxesStateChanged(m_CN.bCBAxesState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.AirBlowStateChanged(m_CN.bAirBlowState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.HomeStateChanged(m_CN.bHomeState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.TableUpChanged(m_CN.bTableUpState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.TableDownChanged(m_CN.bTableDownState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.DoorClosedChanged(m_CN.nDoorClosedState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.LimitZChanged(m_CN.bLimitZState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.FiveAxisStateChanged(m_CN.b5AxesState)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.HSMChanged(m_CN.bHsm)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.FeedHoldChanged(m_CN.bFeedHold)
            m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.SpeedHoldChanged(m_CN.bSpeedHold)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumUpChanged(m_CN.bVacuumUp)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumDownChanged(m_CN.bVacuumDown)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2UpChanged(m_CN.bVacuum2Up)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2DownChanged(m_CN.bVacuum2Down)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum0Changed(m_CN.bVacuum0)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum90Changed(m_CN.bVacuum90)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum1Changed(m_CN.bVacuum1State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum2Changed(m_CN.bVacuum2State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum3Changed(m_CN.bVacuum3State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum4Changed(m_CN.bVacuum4State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum5Changed(m_CN.bVacuum5State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum6Changed(m_CN.bVacuum6State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum135Changed(m_CN.bVacuum135State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Vacuum246Changed(m_CN.bVacuum246State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.OpenAllChanged(m_CN.bOpenAllState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.CloseAllChanged(m_CN.bCloseAllState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Open123Changed(m_CN.bOpen123State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Open456Changed(m_CN.bOpen456State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close123Changed(m_CN.bClose123State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.Close456Changed(m_CN.bClose456State)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.BlowChanged(m_CN.bBlowState)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumOnChanged(m_CN.bVacuumOn)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.VacuumOffChanged(m_CN.bVacuumOff)
            m_MainWindow.m_DirectCutPageUC.m_VacuumMachineButton.BypassChanged(m_CN.bBypassState)
         Else
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.SpindleStateChanged(m_CN.bSpindleState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.CoolantStateChanged(m_CN.bCoolantState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
            m_MainWindow.m_DirectCutPageUC.m_MachineButtons.LaserTracStateChanged(m_CN.bLaserTracState)
            ' modalità vecchia
            If m_CN.Is_G24_active() Then
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ThreeAxisStateChanged(False)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.FiveAxisStateChanged(True)
            Else
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.ThreeAxisStateChanged(True)
               m_MainWindow.m_DirectCutPageUC.m_MachineButtons.FiveAxisStateChanged(False)
            End If
         End If
      End If

      If m_MainWindow.m_ActivePage = MainWindow.Pages.RawPart Then
         m_MainWindow.m_RawPartPage.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
      End If

      If m_MainWindow.m_ActivePage = MainWindow.Pages.WorkInProgress Then
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.SpindleStateChanged(m_CN.bSpindleState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.CoolantStateChanged(m_CN.bCoolantState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.LaserStateChanged(m_CN.bLaserState)
         m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.LaserTracStateChanged(m_CN.bLaserTracState)
         If m_CN.Is_G24_active() Then
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.ThreeAxisStateChanged(False)
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.FiveAxisStateChanged(True)
         Else
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.ThreeAxisStateChanged(True)
            m_MainWindow.m_WorkInProgressPageUC.m_MachineButtons.FiveAxisStateChanged(False)
         End If
      End If

      If m_MainWindow.m_ActivePage = MainWindow.Pages.Machine Then
         If m_IsNewConsole Then
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.PowerONChanged(m_CN.bPowerON)
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.PowerOFFChanged(Not m_CN.bPowerON)
            m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.CncModeChange(m_CN.nMachineMode)
         End If
         m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.CncModeChange(m_CN.nMachineMode)
      End If

   End Sub

   Private Function ReadBit(IndexBit As Integer, Val As Integer) As Boolean
      If IndexBit < 0 Then Return False
      Dim _mask = GetMaskByBit(IndexBit)
      If _mask = Mask.bit_Err Then Return False
      If (Val And _mask) = 0 Then Return False
      Return True
   End Function

   Friend Function SetProgramMainOrSub(bMain As Boolean) As Boolean
      Return m_CN.SetProgramMainOrSub(bMain)
   End Function

   Friend Function SendProgram(ByVal sCncPath As String, ByVal nNumProg As Integer,
                               Optional bActivate As Boolean = True) As Boolean
      Dim bOk As Boolean = True

      ' !!!!!!!!!!!!!!!!!! FORZO IL PROGRAMMA !!!!!!!!!!!!!!!!!!
      ' m_nNCType = 2
      ' !!!!!!!!!!!!!!!!!! FORZO IL PROGRAMMA !!!!!!!!!!!!!!!!!!

      ' Download programma
      If m_MainWindow.m_bNCLink Then
         bOk = (m_nNCType > 0)
         Dim sNumProg As String = String.Empty
         If m_nNCType = 1 Or m_nNCType = 2 Then
            Dim sExtFileCN As String = m_MainWindow.m_CurrentMachine.sExtFileCN
            sNumProg = "%" & nNumProg.ToString() & sExtFileCN
         Else
            sNumProg = nNumProg.ToString()
         End If
         ' Se richiesta successiva attivazione, faccio reset
         If bActivate Then
            EgtOutLog("Call function: DGeneralFunctions_Reset")
            TimeSpanInit()
            m_CN.DGeneralFunctions_Reset()
            EgtOutLog(TimeSpanEnd())
         End If
         ' Attesa opportuna
         System.Threading.Thread.Sleep(m_MainWindow.m_CurrentMachine.nResetSendDelay)
         If m_nNCType = 1 Then
            ' Cancellazione eventuale file già presente con lo stesso nome (ignoro eventuale errore)
            EgtOutLog("Delete_NC_prog(sNumProg)")
            TimeSpanInit()
            m_CN.Delete_NC_prog(sNumProg)
            EgtOutLog(TimeSpanEnd())
            ' Attesa opportuna
            System.Threading.Thread.Sleep(100)
         ElseIf m_nNCType = 4 Then
            ' FANUC: imposto modalità EDIT 
            bOk = bOk AndAlso (m_CN.DGeneralFunctions_WriteCncMode(1) = 0)
            ' Attesa opportuna
            System.Threading.Thread.Sleep(m_MainWindow.m_CurrentMachine.nThreadSleep)
         End If
         EgtOutLog("Download_NC_prog(" & sCncPath & ", " & sNumProg.ToString & ")")
         ' -------------- START DOWNLOAD -------------- 
         TimeSpanInit()
         bOk = bOk AndAlso (m_CN.Download_NC_prog(sCncPath, sNumProg) = 0)
         ' Attesa opportuna
         System.Threading.Thread.Sleep(100)
         ' FANUC: genero un file 901 vuoto da aspedire, attivare; poi rispedisco il file 900
         If m_nNCType = 4 And Not bOk Then
            bOk = True
            Dim sCncPath1 As String = m_MainWindow.GetCncDir() & "\PlaceHolder" & m_MainWindow.m_CurrentMachine.sIsoFileExt
            Dim fs As FileStream = File.Create(sCncPath1)
            ' Add text to the file.
            Dim info As Byte() = New UTF8Encoding(True).GetBytes(vbLf & "(PlaceHolder)")
            fs.Write(info, 0, info.Length)
            fs.Close()
            bOk = bOk AndAlso (m_CN.Download_NC_prog(sCncPath1, "901") = 0)
            ' Attesa opportuna
            System.Threading.Thread.Sleep(m_MainWindow.m_CurrentMachine.nThreadSleep)
            If bActivate Then
               bOk = bOk AndAlso (m_CN.ActivateProgram("901") = 0)
               ' Attesa opportuna
               System.Threading.Thread.Sleep(m_MainWindow.m_CurrentMachine.nThreadSleep)
            End If
            ' riprovo ad eseguire il programma 900
            bOk = True
            bOk = bOk AndAlso (m_CN.Download_NC_prog(sCncPath, sNumProg) = 0)
            ' Attesa opportuna
            System.Threading.Thread.Sleep(m_MainWindow.m_CurrentMachine.nThreadSleep)
         End If
         EgtOutLog("Nc Type : " & m_nNCType.ToString)
         ' AXIUM (NUM OLD): se DripFeed non esegluo attivazione programma)
         If m_nNCType = 1 AndAlso m_CN.bIsDripFeed Then
            ' eventauli cambi di stato sono trattati all'interno della funzione DownLoad_NC_prog
            Return True
         End If
         EgtOutLog(TimeSpanEnd())
         ' --------------  END  DOWNLOAD -------------- 
         ' -------------- START ACTIVATE -------------- 
         ' Se richiesta attivazione
         If bActivate Then
            ' Attivazione programma
            EgtOutLog("ActivateProgram(" & nNumProg.ToString & ")")
            TimeSpanInit()
            bOk = bOk AndAlso (m_CN.ActivateProgram(nNumProg) = 0)
            EgtOutLog(TimeSpanEnd())
            ' Attesa opportuna
            System.Threading.Thread.Sleep(100)
            ' Attivo la modalità AUTO prima per preparar il cyclo start
            bOk = bOk AndAlso (m_CN.DGeneralFunctions_WriteCncMode(0) = 0)
            ' Attesa opportuna
            System.Threading.Thread.Sleep(100)
            ' Modalità automatica
            EgtOutLog("DGeneralFunctions_WriteCncMode(0)")
            TimeSpanInit()
            EgtOutLog(TimeSpanEnd())
         End If
         ' --------------  END  ACTIVATE -------------- 
         ' Messaggio con risultato
         If bOk Then
            m_CurrProjPage.SetInfoMessage(EgtMsg(90317))        'Programma CN trasmesso con successo
         Else
            m_CurrProjPage.SetErrorMessage(EgtMsg(90315))       'Errore nella trasmissione del programma CN
         End If
      Else
         m_CurrProjPage.SetWarningMessage(EgtMsg(90316))        'Non connesso alla macchina
      End If

      Return bOk
   End Function

   Private Sub GetSpecialCAxes()
      If m_CN.bCPos Then
         m_CN.d_axis_position(m_nA4) = m_CN.dCPos
      End If
   End Sub

   Friend Function GetAxesPositions(ByRef dA1 As Double, ByRef dA2 As Double, ByRef dA3 As Double,
                                    ByRef dA4 As Double, ByRef dA5 As Double, ByRef dA6 As Double,
                                    ByRef dA7 As Double, ByRef dA8 As Double, ByRef dA9 As Double, ByRef dA10 As Double) As Boolean
      ' gestione speciale asse C
      GetSpecialCAxes()
      dA1 = If(m_nA1 >= 0, m_CN.d_axis_position(m_nA1), 0)
      dA2 = If(m_nA2 >= 0, m_CN.d_axis_position(m_nA2), 0)
      dA3 = If(m_nA3 >= 0, m_CN.d_axis_position(m_nA3), 0)
      dA4 = If(m_nA4 >= 0, m_CN.d_axis_position(m_nA4), 0)
      dA5 = If(m_nA5 >= 0, m_CN.d_axis_position(m_nA5), 0)
      dA6 = If(m_nA6 >= 0, m_CN.d_axis_position(m_nA6), 0)
      dA7 = If(m_nA7 >= 0, m_CN.d_axis_position(m_nA7), 0)
      dA8 = If(m_nA8 >= 0, m_CN.d_axis_position(m_nA8), 0)
      dA9 = If(m_nA9 >= 0, m_CN.d_axis_position(m_nA9), 0)
      dA10 = If(m_nA10 >= 0, m_CN.d_axis_position(m_nA10), 0)
      ' sono già in mm
      Return m_bAxesOk
   End Function

   Friend Function GetAxesPositions(ByRef dA1 As Double, ByRef dA2 As Double, ByRef dA3 As Double,
                                    ByRef dA4 As Double, ByRef dA5 As Double) As Boolean
      ' gestione speciale asse C
      GetSpecialCAxes()
      dA1 = If(m_nA1 >= 0, m_CN.d_axis_position(m_nA1), 0)
      dA2 = If(m_nA2 >= 0, m_CN.d_axis_position(m_nA2), 0)
      dA3 = If(m_nA3 >= 0, m_CN.d_axis_position(m_nA3), 0)
      dA4 = If(m_nA4 >= 0, m_CN.d_axis_position(m_nA4), 0)
      dA5 = If(m_nA5 >= 0, m_CN.d_axis_position(m_nA5), 0)
      ' sono già in mm
      Return m_bAxesOk
   End Function

   Friend Function GetLinearAxesPositions(ByRef dL1 As Double, ByRef dL2 As Double, ByRef dL3 As Double) As Boolean
      dL1 = If(m_nA1 >= 0, m_CN.d_axis_position(m_nA1), 0)
      dL2 = If(m_nA2 >= 0, m_CN.d_axis_position(m_nA2), 0)
      dL3 = If(m_nA3 >= 0, m_CN.d_axis_position(m_nA3), 0)
      ' sono già in mm
      Return m_bAxesOk
   End Function

   Friend Function GetRotaryAxesPositions(ByRef dR1 As Double, ByRef dR2 As Double) As Boolean
      ' gestione speciale asse C
      GetSpecialCAxes()
      dR1 = If(m_nA4 >= 0, m_CN.d_axis_position(m_nA4), 0)
      dR2 = If(m_nA5 >= 0, m_CN.d_axis_position(m_nA5), 0)
      Return m_bAxesOk
   End Function

   Friend Function GetAxesDeltas(ByRef dA1 As Double, ByRef dA2 As Double, ByRef dA3 As Double,
                                 ByRef dA4 As Double, ByRef dA5 As Double, ByRef dA6 As Double,
                                 ByRef dA7 As Double, ByRef dA8 As Double, ByRef dA9 As Double, ByRef dA10 As Double) As Boolean
      dA1 = If(m_nA1 >= 0, m_CN.d_axis_delta(m_nA1), 0)
      dA2 = If(m_nA2 >= 0, m_CN.d_axis_delta(m_nA2), 0)
      dA3 = If(m_nA3 >= 0, m_CN.d_axis_delta(m_nA3), 0)
      dA4 = If(m_nA4 >= 0, m_CN.d_axis_delta(m_nA4), 0)
      dA5 = If(m_nA5 >= 0, m_CN.d_axis_delta(m_nA5), 0)
      dA6 = If(m_nA6 >= 0, m_CN.d_axis_delta(m_nA6), 0)
      dA7 = If(m_nA7 >= 0, m_CN.d_axis_delta(m_nA7), 0)
      dA8 = If(m_nA8 >= 0, m_CN.d_axis_delta(m_nA8), 0)
      dA9 = If(m_nA9 >= 0, m_CN.d_axis_delta(m_nA9), 0)
      dA10 = If(m_nA10 >= 0, m_CN.d_axis_delta(m_nA10), 0)
      ' sono già in mm
      Return m_bAxesOk
   End Function

   Friend Function GetAxesDeltas(ByRef dA1 As Double, ByRef dA2 As Double, ByRef dA3 As Double,
                                 ByRef dA4 As Double, ByRef dA5 As Double) As Boolean
      dA1 = If(m_nA1 >= 0, m_CN.d_axis_delta(m_nA1), 0)
      dA2 = If(m_nA2 >= 0, m_CN.d_axis_delta(m_nA2), 0)
      dA3 = If(m_nA3 >= 0, m_CN.d_axis_delta(m_nA3), 0)
      dA4 = If(m_nA4 >= 0, m_CN.d_axis_delta(m_nA4), 0)
      dA5 = If(m_nA5 >= 0, m_CN.d_axis_delta(m_nA5), 0)
      ' sono già in mm
      Return m_bAxesOk
   End Function

   Friend Function GetAxesNames(ByRef sA1 As String, ByRef sA2 As String, ByRef sA3 As String,
                                ByRef sA4 As String, ByRef sA5 As String, ByRef sA6 As String,
                                ByRef sA7 As String, ByRef sA8 As String, ByRef sA9 As String, ByRef sA10 As String) As Boolean
      sA1 = m_sA1
      sA2 = m_sA2
      sA3 = m_sA3
      sA4 = m_sA4
      sA5 = m_sA5
      sA6 = m_sA6
      sA7 = m_sA7
      sA8 = m_sA8
      sA9 = m_sA9
      sA10 = m_sA10
      Return m_bAxesOk
   End Function

   Friend Function GetAxesNames(ByRef sA1 As String, ByRef sA2 As String, ByRef sA3 As String,
                                ByRef sA4 As String, ByRef sA5 As String) As Boolean
      sA1 = m_sA1
      sA2 = m_sA2
      sA3 = m_sA3
      sA4 = m_sA4
      sA5 = m_sA5
      Return m_bAxesOk
   End Function

   Friend Function GetMachineInInches() As Boolean
      Return m_bInInches
   End Function

End Class

Public Class RefereceFlagSimens

   Private m_SiemnesArrayIndex As Integer
   Private m_FlagIndex As Integer
   Private m_TypeArray As Integer
   ' Opzionale
   Private m_IndexBit As Integer = -1
   Private m_DefaultValue As String = ""

   Public Property SiemnesArrayIndex As Integer
      Get
         Return m_SiemnesArrayIndex
      End Get
      Set(value As Integer)
         m_SiemnesArrayIndex = value
      End Set
   End Property

   Public Property FlagIndex As Integer
      Get
         Return m_FlagIndex
      End Get
      Set(value As Integer)
         m_FlagIndex = value
      End Set
   End Property

   Public Property TypeArray As Integer
      Get
         Return m_TypeArray
      End Get
      Set(value As Integer)
         m_TypeArray = value
      End Set
   End Property

   Public Property IndexBit As String
      Get
         Return m_IndexBit
      End Get
      Set(value As String)
         m_IndexBit = value
      End Set
   End Property

   Public Property DefaultValue As String
      Get
         Return m_DefaultValue
      End Get
      Set(value As String)
         m_DefaultValue = value
      End Set
   End Property

   Sub New(IndArray As Integer, Flag As Integer, nType As Integer)
      m_SiemnesArrayIndex = IndArray
      m_FlagIndex = Flag
      m_TypeArray = nType
   End Sub

   Sub New(IndArray As Integer, Flag As Integer, nType As Integer, nIndBit As Integer)
      m_SiemnesArrayIndex = IndArray
      m_FlagIndex = Flag
      m_TypeArray = nType
      m_IndexBit = nIndBit
   End Sub

End Class

Public Class IndexArrayToBit

   Private m_nIndex As Integer = 0
   Public ReadOnly Property nIndex As Integer
      Get
         Return m_nIndex
      End Get
   End Property

   Private m_sNameVar As String = ""
   Public ReadOnly Property sNameVar As String
      Get
         Return m_sNameVar
      End Get
   End Property

   Sub New(Index As Integer, NameVar As String)
      m_nIndex = Index
      m_sNameVar = NameVar
   End Sub

End Class