Imports System.Windows.Threading
Imports System.Globalization
Imports System.Collections.ObjectModel
Imports EgtUILib

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

   ' 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_IsNewConsole As Boolean = False

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

   ' Timer
   Private m_RefreshTimer 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

      ' 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()
         Else
            Refresh()
         End If

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

   End Sub

   Private Sub ReadAxesData()
      ' Nomi e indici degli assi macchina
      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 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
         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())
         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)

         ' 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

            ' Inizializzo la comunicazione
            m_CN.Init()

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

      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 & """"
                  EgtOutLog("ProcessStart : " & """" & m_sCNSiemensHMIPath & """" & " " & sArg)
                  Process.Start(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
                     ' stati bottoni parte 1
                     m_CN.DVariables_Read_Subscription(m_CN.m_szCnDataVar(CN_generico.CnData.Laser), VarType.TInteger, 0)
                     ' stati bottoni ventose
                     m_CN.DVariables_Read_Subscription(m_CN.m_szCnDataVar(CN_generico.CnData.LaserTrac), VarType.TInteger, 1)
                     'stati porte
                     m_CN.DVariables_Read_Subscription(m_CN.m_szCnDataVar(CN_generico.CnData.DoorClosed), VarType.TInteger, 2)
                     ' 
                     m_CN.DVariables_Read_Subscription(m_CN.m_szCnDataVar(CN_generico.CnData.BlowState), VarType.TInteger, 3)
                     ' stati bottoni parte 2
                     m_CN.DVariables_Read_Subscription(m_CN.m_szCnDataVar(CN_generico.CnData.CBAxes), VarType.TInteger, 4)
                     ' ampere e ampere override
                     m_CN.DVariables_Read_Subscription(m_CN.m_szCnDataVar(CN_generico.CnData.Spindle), VarType.TDouble, 0)
                     m_CN.DVariables_Read_Subscription(m_CN.m_szCnDataVar(CN_generico.CnData.SpeedOvr), VarType.TDouble, 1)

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

      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

      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)
            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

      ' 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)
            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)

            ' 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)
            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)
            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_IsNewConsole AndAlso m_MainWindow.m_ActivePage = MainWindow.Pages.Machine Then
         m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.PowerONChanged(m_CN.bPowerON)
         m_MainWindow.m_MachinePageUC.m_MachineCNPageUC.PowerOFFChanged(Not m_CN.bPowerON)
      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

   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

      If m_MainWindow.m_DirectCutPageUC.m_NewMachineButtonsType Then

         ' lettura variabili stati mancanti su Siemens
         Dim nVarValue As Integer = m_CN.n_data(0)
         EgtOutLog("Variabile PLC control addr: " & 1 & " value: " & nVarValue)
         m_CN.bSpindleState = IsSetAll(nVarValue, ControlStates.Spindle)
         m_CN.bLaserTracState = IsSetAll(nVarValue, ControlStates.LaserTrac)
         m_CN.bCoolantState = IsSetAll(nVarValue, ControlStates.Coolant)
         m_CN.bInternalCoolantState = IsSetAll(nVarValue, ControlStates.InternalCoolant)
         m_CN.bExternCoolantState = IsSetAll(nVarValue, ControlStates.ExternCoolant)
         m_CN.bCBAxesState = IsSetAll(nVarValue, ControlStates.CAxis)
         m_CN.bAirBlowState = IsSetAll(nVarValue, ControlStates.AirBlow)
         m_CN.bHomeState = IsSetAll(nVarValue, ControlStates.Home)
         m_CN.bTableUpState = IsSetAll(nVarValue, ControlStates.TableUp)
         m_CN.bTableDownState = IsSetAll(nVarValue, ControlStates.TableDown)
         m_CN.bLimitZState = IsSetAll(nVarValue, ControlStates.LimitZ)
         m_CN.b5AxesState = IsSetAll(nVarValue, ControlStates.Axis5)

         nVarValue = m_CN.n_data(1)
         'EgtOutLog("Variabile PLC vacuum  addr: " & m_CN.m_szCnDataVar(CN_generico.CnData.LaserTrac) & " value: " & nVarValue)
         m_CN.bVacuumUp = IsSetAll(nVarValue, VacuumStates.VacuumUp)
         m_CN.bVacuumDown = IsSetAll(nVarValue, VacuumStates.VacuumDown)
         m_CN.bVacuum2Up = IsSetAll(nVarValue, VacuumStates.Vacuum2Up)
         m_CN.bVacuum2Down = IsSetAll(nVarValue, VacuumStates.Vacuum2Down)
         m_CN.bVacuum1State = IsSetAll(nVarValue, VacuumStates.Vacuum1State)
         m_CN.bVacuum2State = IsSetAll(nVarValue, VacuumStates.Vacuum2State)
         m_CN.bVacuum3State = IsSetAll(nVarValue, VacuumStates.Vacuum3State)
         m_CN.bVacuum4State = IsSetAll(nVarValue, VacuumStates.Vacuum4State)
         m_CN.bVacuum5State = IsSetAll(nVarValue, VacuumStates.Vacuum5State)
         m_CN.bVacuum6State = IsSetAll(nVarValue, VacuumStates.Vacuum6State)
         m_CN.bOpenAllState = (m_CN.bVacuum1State And m_CN.bVacuum2State And m_CN.bVacuum3State And m_CN.bVacuum4State And m_CN.bVacuum5State And m_CN.bVacuum6State)
         m_CN.bCloseAllState = (Not m_CN.bVacuum1State And Not m_CN.bVacuum2State And Not m_CN.bVacuum3State And Not m_CN.bVacuum4State And Not m_CN.bVacuum5State And Not m_CN.bVacuum6State)
         m_CN.bOpen123State = (m_CN.bVacuum1State And m_CN.bVacuum2State And m_CN.bVacuum3State)
         m_CN.bOpen456State = (m_CN.bVacuum4State And m_CN.bVacuum5State And m_CN.bVacuum6State)
         m_CN.bClose123State = (Not m_CN.bVacuum1State And Not m_CN.bVacuum2State And Not m_CN.bVacuum3State)
         m_CN.bClose456State = (Not m_CN.bVacuum4State And Not m_CN.bVacuum5State And Not m_CN.bVacuum6State)
         m_CN.bBlowState = IsSetAll(nVarValue, VacuumStates.AirBlow)
         m_CN.bVacuumOn = IsSetAll(nVarValue, VacuumStates.VacuumOn)
         m_CN.bVacuumOff = IsSetAll(nVarValue, VacuumStates.VacuumOff)
         m_CN.bBypassState = IsSetAll(nVarValue, VacuumStates.BypassState)

         nVarValue = m_CN.n_data(2)
         'EgtOutLog("Variabile PLC  door addr: " & m_CN.m_szCnDataVar(CN_generico.CnData.DoorClosed) & " value: " & nVarValue)
         m_CN.nDoorClosedState = nVarValue

         nVarValue = m_CN.n_data(4)
         'EgtOutLog("Variabile PLC control 2 addr: " & 3 & " value: " & nVarValue)
         m_CN.bLaserState = IsSetAll(nVarValue, ControlStates2.Laser)
         m_CN.bHsm = IsSetAll(nVarValue, ControlStates2.Hsm)
         m_CN.bResetState = IsSetAll(nVarValue, ControlStates2.ResetState)
         m_CN.bFeedHold = IsSetAll(nVarValue, ControlStates2.FeedHold)
         m_CN.bSpeedHold = IsSetAll(nVarValue, ControlStates2.SpindleHold)

      End If

      ' 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)
            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

   End Sub

   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
      ' 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
            sNumProg = "%" & nNumProg.ToString() & ".0"
         Else
            sNumProg = nNumProg.ToString()
         End If
         ' Se richiesta successiva attivazione, faccio reset
         If bActivate Then
            m_CN.DGeneralFunctions_Reset()
         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)
            m_CN.Delete_NC_prog(sNumProg)
            ' Attesa opportuna
            System.Threading.Thread.Sleep(100)
         End If
         bOk = bOk AndAlso (m_CN.Download_NC_prog(sCncPath, sNumProg) = 0)
         ' Attesa opportuna
         System.Threading.Thread.Sleep(100)
         ' Se richiesta attivazione
         If bActivate Then
            ' Attivazione programma
            bOk = bOk AndAlso (m_CN.ActivateProgram(nNumProg) = 0)
            ' Attesa opportuna
            System.Threading.Thread.Sleep(100)
            ' Modalità automatica
            bOk = bOk AndAlso (m_CN.DGeneralFunctions_WriteCncMode(0) = 0)
         End If
         ' 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

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