'
' libreria  : VBlib
' file      : ComCNOsai 
'
' funzioni  : connessione con CN OSAI come classe  v1.1
'
' copyright 2008-2017 C.Viviani
'
Imports Microsoft.Win32

Public Class ComCNOsai

#Region "STRUCT CN"

    ' ----------------------------------------------------------------------------
    ' Struttura dati utilizzata per gestione lettura e scrittura variabili su CN
    ' ----------------------------------------------------------------------------
    Public Structure stVAR

        Dim szVarName As String
        Dim nAddress As Integer
        Dim nBit As Integer
        Dim nNumCn As Integer

    End Structure
#End Region

#Region "VARIABILI ISTANZA"


    ' -----------------------
    ' Dichiarazione costanti
    ' -----------------------
    Public Const ERRORVALUE = -9999    ' valore assegnato alla variabile in caso di errore durante la lettura
    Public Const CRASHVALUE = -9998    ' valore assegnato alla variabile in caso di grave errore durante la lettura

    ' funzione boot enquiry : BootPhaseEnquiry_C 

    Public Const EMERG_SWITCH_PHASE As Short = 1
    Public Const HW_BOOT_PHASE As Short = 2
    Public Const SW_BOOT_PHASE As Short = 3
    Public Const SYSTEM_UP_PHASE As Short = 4
    Public Const SERVER_MODE_PHASE As Short = 5
    Public Const REMOTE_SETUP_PHASE As Short = 6
    Public Const SERVICE_MODE_PHASE As Short = 7
    Public Const AX_PARAM_VERIFY_PHASE As Short = 8

    ' error codes
    Public Const AB_NO_ERROR = &H0
    Public Const AB_INIT_ERROR = &H101
    Public Const AB_CHANNEL_NOT_OPENED = &H102
    Public Const AB_WRONG_SESSION_NUMBER = &H103
    Public Const AB_TOO_MANY_OPENED_SESSION = &H104
    Public Const AB_REMOTE_CNC_ERROR = &H105
    Public Const AB_NAME_TOO_LONG = &H106
    Public Const AB_COMMAND_IN_EXECUTION = &H107
    Public Const AB_CHANNELS_BUSY = &H108
    Public Const AB_WRONG_PROCESS_NUMBER = &H109
    Public Const AB_WRONG_SELECT_MODE = &H10A
    Public Const AB_PARAM_OUT_OF_RANGE = &H10B
    Public Const AB_CALLBACK_MUST_BE_NULL = &H10C
    Public Const AB_WRONG_SYNC_CODE = &H10D
    Public Const AB_BUFFER_SIZE_ERROR = &H10E
    ' netbios error codes
    Public Const AB_NETB_NETWORK_ERROR = &H200
    Public Const AB_NETB_DUP_LOCAL_NAME = &H201
    Public Const AB_NETB_NAME_TABLE_FULL = &H202
    Public Const AB_NETB_LOCAL_SESS_TAB_FULL = &H203
    Public Const AB_NETB_NO_BODY_LISTENING = &H204
    Public Const AB_NETB_NO_ASW_FROM_REMOTE = &H205
    Public Const AB_NETB_NAME_USED_ON_REMOTE = &H206
    Public Const AB_NETB_NAME_DELETED = &H207
    Public Const AB_NETB_NAME_CONFLICT = &H208
    Public Const AB_NETB_INCOMPAT_REMOTE_DEV = &H209
    Public Const AB_NETB_TIMEOUT = &H20A
    Public Const AB_NETB_SESSION_ERR = &H20B               ' Session closed

    Public Const AB_USER_ERROR = &H300

    Public Const NO_WAIT_CNC_ANSWER = 1
    Public Const WAIT_CNC_ANSWER = 2

    Public Const ON_ = 1
    Public Const OFF_ = 0

    ' 10 Series modes
    Public Const MDI = 1
    Public Const AUTO = 2
    Public Const SEMI = 3
    Public Const MANJOG = 4
    Public Const INCJOG = 5
    Public Const PROFILE = 6
    Public Const HOME = 7

    ' 10 Series Status
   Public Const IDLE_ As Byte = 1
   Public Const CYCLE_ As Byte = 2
   Public Const HOLDA_ As Byte = 3
   Public Const RUNH_ As Byte = 4
   Public Const HRUN_ As Byte = 5
   Public Const ERRO_ As Byte = 6
   Public Const WAIT_ As Byte = 7
   Public Const RESET_ As Byte = 8
   Public Const EMERG_ As Byte = 9
   Public Const INPUT_ As Byte = 10

    ' 10 Series SubStatus
    Public Const MAS = 6
    Public Const MBR = 4


    Public Const NUM_ELEM_SEL_AXI = 9

    ' Axes Position type selector
    Public Const PROGPOS = 1   ' Programmed positions
    Public Const INTPOS = 2    ' Interpolated positions
    Public Const TRANSDPOS = 3 ' Transducer Position
    Public Const ERRPOS = 4    ' Following Errors

    Public Const MAIN_PROGR_NAME_LEN = 55

    Protected Const ERRORE_OSAI = 0

    ' ---------------------
    ' Variabili di Istanza
    ' ---------------------

    Protected mConnected As Boolean       ' Indica se il Cn è connesso o meno
    Protected mSessionOpened As Short     ' Indica il numero di sessione aperta
    Protected mNomeCN As String           ' Indica il nome del cn da aprire
    Protected mDebug As Boolean           ' Indica se la connessione è debug o meno
    Protected mVersion As Short           ' indica la versione del Cn


    Protected mErrClass As Long           ' Indice della classe d'errore
    Protected mErrNum As Long             ' Indice della classe d'errore

    Protected mErrMsg As String           ' Stringa per gestione messaggi errore
    Protected mCommunicationError as Boolean         ' Boolean che indica se è avvenuto un errore di comunicazione

    Private Server As New CndexLinkDotNet.Cndex() ' Istanza del server per comunicazione con CN

#End Region

#Region "COSTRUTTORE"

    '-------------------------
    ' Definizione Costruttore 
    '-------------------------
    Public Sub New(ByVal szCN As String, ByVal bIsDebug As Boolean, Optional ByVal sVersion As Short = 2)

        ' Inizializzazione variabili
        Connected = False
        SessionOpened = -1
        ErrClass = 0
        ErrNum = 0
        ErrMsg = ""

        ' Set variabili da parametri
        NomeCn = szCN
        Debug = bIsDebug
        Version = sVersion
    End Sub

#End Region

#Region "PROPRIETA"

    ' ----------------------------------
    ' Indica se il CN è connesso o meno 
    ' ----------------------------------
    Public Property Connected() As Boolean
        Get
            Return mConnected
        End Get
        Set(ByVal value As Boolean)
            mConnected = value
        End Set

    End Property

    ' -----------------------------
    ' Indice della classe d'errore
    ' -----------------------------
    Public Property ErrClass() As Long
        Get
            Return mErrClass
        End Get
        Set(ByVal value As Long)
            mErrClass = value
        End Set
    End Property

    ' ---------------------------
    ' Indice del numero d'errore
    ' ---------------------------
    Public Property ErrNum() As Long
        Get
            Return mErrNum
        End Get
        Set(ByVal value As Long)
            mErrNum = value
        End Set
    End Property

    ' ---------------------------------------
    ' Indica il numero della sessione aperta
    ' ---------------------------------------
    Public Property SessionOpened() As Short
        Get
            Return mSessionOpened
        End Get
        Set(ByVal value As Short)
            mSessionOpened = value
        End Set
    End Property

    ' ---------------------------------
    ' Indica la stringa di connessione
    ' ---------------------------------
    Public Property NomeCn() As String
        Get
            Return mNomeCN
        End Get
        Set(ByVal value As String)
            mNomeCN = value
        End Set
    End Property

    ' --------------------------------
    ' Indica se la connesione è Debug 
    ' --------------------------------
    Public Property Debug() As Boolean
        Get
            Return mDebug
        End Get
        Set(ByVal value As Boolean)
            mDebug = value
        End Set
    End Property

    ' --------------------------------
    ' Indica la versione Osai
    ' 1 = Prima di versione WinNbi 3.0 (Gasper,Nasi,ABB etc)
    ' 2 = Versione WinNbi > 3.0 con OS XP
    ' 3 = Versione WinNbi > 3.0 con OS 7
    ' 4 = Open Control
    ' --------------------------------
    Public Property Version() As Short
        Get
            Return mVersion
        End Get
        Set(ByVal value As Short)
            mVersion = value
        End Set
    End Property
    ' --------------------------------
    ' Stringa per gestione errori
    ' --------------------------------
    Public Property ErrMsg() As String
        Get
            Return mErrMsg
        End Get
        Set(ByVal value As String)
            mErrMsg = value
        End Set
    End Property

    ' ------------------------------------------------------------
    ' Boolean che indica se c'è stato un errore di comunicazione
    ' ------------------------------------------------------------
    Public Property Communication() As Boolean
        Get
            Return mCommunicationError
        End Get
        Set(ByVal value As Boolean)
            mCommunicationError = value
        End Set
    End Property

#End Region

#Region "METODI - Open/close connection"

    '------------------------------
    ' Lettura messaggio DIS
    '------------------------------
    Public Overridable Function ReadDisMsg(Optional ByVal nProcess As Integer = 1, Optional ByVal nMac As Integer = 1) As String

        Dim szResult As String = ""                ' Stringa risultato

        Dim n_ret_state As Short

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            n_ret_state = Server.ReadPartProgramMsg_C(SessionOpened, nProcess, szResult, ErrClass, ErrNum)

            If (n_ret_state = ERRORE_OSAI) Then

                ErrMsg = "Error on reading DIS Messages " & vbCrLf & what_happened()
                'MsgBox(ErrMsg)
                Return CShort(ERRORVALUE).ToString     ' In uscita setto variabile a ERRORVALUE errore 

            Else
                ' return con il valore letto
                Return szResult

            End If
        End If

        Return szResult
    End Function


    ' ------------------------------
    ' Apertura sessione con CN Osai
    ' ------------------------------
    Public Overridable Function OpenSession() As Boolean

        Dim nSession As Short = 0

        Select Case Debug

            Case False                              ' Se non sono in Debug = 0 

                nSession = Server.OpenSession_C(NomeCn, SessionOpened, ErrClass, ErrNum) ' Apro la sessione 

                If (nSession <> ERRORE_OSAI) Then
                    Connected = True             ' Setto connesso = true
                Else
                    Connected = False            ' Setto connesso = false
                    ErrMsg = "Error on open session" & vbCrLf & what_happened()
                End If


            Case True                              ' Se sono in Debug = 1

                Connected = True                   ' Connessione sempre OK 

        End Select

        Return Connected

    End Function

    ' ------------------------------
    ' Chiusura sessione con CN Osai
    ' ------------------------------
    Public Overridable Function CloseSession() As Boolean

        Dim nSession As Short
        Dim bOk As Boolean

        Select Case Debug

            Case False  ' Se non sono in Debug = 0 

                nSession = Server.CloseSession_C(SessionOpened, ErrClass, ErrNum) ' Chiudo la sessione

                If (nSession <> ERRORE_OSAI) Then
                    bOk = True
                Else
                    ErrMsg = "Error on closing session" & vbCrLf & what_happened()
                    bOk = False
                End If

            Case True   ' Se  sono in Debug = 1 

                bOk = True

        End Select

        Connected = False

        Return bOk

    End Function

    ' ------------------------------
    ' Verifica che il CN sia running 
    ' ------------------------------
    Public Overridable Function Is_NC_running() As Boolean

        Dim n_ret_state As Short
        Dim n_boot_Phase As Short

        n_ret_state = Server.BootPhaseEnquiry_C(SessionOpened, n_boot_Phase, ErrClass, ErrNum)

        If (n_ret_state = ERRORE_OSAI) Then
            ErrMsg = "Error on BootPhaseEnquiry_C" & vbCrLf & "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum)
            Return False
            Exit Function
        End If

        If n_boot_Phase <> SYSTEM_UP_PHASE Then
            Return False
        Else
            Return (True)
        End If

    End Function

    ' ------------------------------
    ' START PartProgram
    ' ------------------------------
    Public Overridable Function StartPP() As Boolean

        Dim n_ret_state As Short
        Dim bOk As Boolean

        Select Case Debug

            Case False  ' Se non sono in Debug = 0 

                n_ret_state = Server.Cycle_C(SessionOpened, 1, 1, ErrClass, ErrNum) ' Chiudo la sessione

                If (n_ret_state = ERRORE_OSAI) Then

                    ErrMsg = "Error on Cycle_C" & vbCrLf & vbCrLf & what_happened()
                    bOk = False
                Else
                    bOk = True
                End If

            Case True   ' Se  sono in Debug = 1 

                bOk = True

        End Select

        Return bOk

    End Function

#End Region

#Region "METODI - NC copy post Vista ...."

    '------------------------------
    ' Copia file da Pc a Cn post Vista .... ritorna zero in caso di errore.
    '------------------------------
    Public Overridable Function CopyFileToNC(ByVal sz_logical_drive As String,
                                 ByVal sz_source_filename As String,
                                 ByVal sz_dest_filename As String) As Short

        Dim n_ret_state As Short

        Select Case Debug

            Case False                              ' Se non sono in Debug = 0 

                n_ret_state = Server.LogFSTransferFileW_C(sz_logical_drive, sz_source_filename, NomeCn, sz_dest_filename, ErrClass, ErrNum)

                If (n_ret_state > 0) Then ' ritorna zero in caso di errore.
                Else
                    ErrMsg = "Error on CopyFileToNC" & vbCrLf & what_happened()
                    MsgBox(ErrMsg)

                End If

            Case True                               ' Se sono in Debug = 1

                n_ret_state = 1                     ' Connessione sempre OK 

        End Select

        Return n_ret_state

    End Function

    '------------------------------
    ' Copia file da Cn a PC post Vista ....
    '------------------------------
    Public Overridable Function CopyFileFromNc(ByVal sz_logical_drive As String,
                                 ByVal sz_source_filename As String,
                                 ByVal sz_dest_filename As String) As Short

        Dim n_ret_state As Short

        Select Case Debug

            Case False                              ' Se non sono in Debug = 0 


                n_ret_state = Server.LogFSTransferFileW_C(NomeCn, sz_source_filename, sz_logical_drive, sz_dest_filename, ErrClass, ErrNum)

                If (n_ret_state > 0) Then
                Else
                    ErrMsg = "Error on CopyFileFromNc" & vbCrLf & what_happened()
                    MsgBox(ErrMsg)

                End If


            Case True                              ' Se sono in Debug = 1

                n_ret_state = 1                   ' Connessione sempre OK 

        End Select

        Return n_ret_state

    End Function

    '------------------------------
    ' Delete file su Cn post Vista ....
    '------------------------------
    Public Overridable Function DeleteFileOnNC(ByVal sz_pathname As String, ByVal sz_filename As String) As Short

        Dim n_ret_state As Short

        Dim n_hidden_drives As Long
        Dim n_user_drives As Long
        Dim n As Short
        Dim sz_drive_name As String
        Dim sz_drive_path As String

        Select Case Debug

            Case False                              ' Se non sono in Debug = 0 

                n_ret_state = Server.LogFSGetNumDrive_C(SessionOpened, n_hidden_drives, n_user_drives, ErrClass, ErrNum)

                sz_drive_name = ""
                sz_drive_path = ""
                n = 0

                'n_ret_state = Server.LogFSGetDriveList_C(SessionOpened, sz_drive_name, n, ErrClass, ErrNum)

                'n_ret_state = Server.LogFSSetSecurityLevel_C(SessionOpened, "OEM", CndexLinkDotNet.Cndex.SECURITY_LEVEL_C.SECURITY_LEV_OEM_ADMIN_C, n, ErrClass, ErrNum)

                'n_ret_state = Server.LogFSGetDrivePath_C(SessionOpened, sz_drive_name, sz_drive_path, CndexLinkDotNet.Cndex.SECURITY_LEVEL_C.SECURITY_LEV_OEM_ADMIN_C, ErrClass, ErrNum)

                n_ret_state = Server.LogFSRemoveFile_C(SessionOpened, sz_pathname, sz_filename, ErrClass, ErrNum)

                If (n_ret_state > 0) Then
                Else
                    ErrMsg = "Error on DeleteFileOnNC" & vbCrLf & what_happened()
                    MsgBox(ErrMsg)

                End If

            Case True                              ' Se sono in Debug = 1

                n_ret_state = 1                   ' Connessione sempre OK 

        End Select

        Return n_ret_state

    End Function

#End Region

#Region "METODI - Lettura/scrittura variabili CN"

    '------------------------------
    ' Lettura variabile Bool su Cn
    '------------------------------
    Public Overridable Function ReadBoolVar(ByVal szVar As stVAR, Optional ByVal nProcess As Integer = 1) As Short

        Dim nValues(0) As Short               ' Array (lo vuole la libreria Osai) che conterrà il valore letto
        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO
        Dim nNumVarToBeReaded As Integer = 1  ' Numero di variabili da leggere (fisso a 1)


        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nValues(0) = 0

            nComOk = Server.ReadVarWord_C(SessionOpened, CndexLinkDotNet.Cndex.GW_CODE, nProcess, szVar.nAddress, nNumVarToBeReaded, nValues, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on reading bool variable" & vbCrLf & "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum)
                Return CShort(ERRORVALUE)    ' In uscita setto variabile a ERRORVALUE errore 

            Else

                If ((nValues(0) And (2 ^ szVar.nBit)) <> 0) Then     ' Maschera per controllare solo il bit che mi interessa
                    nValues(0) = 1
                Else
                    nValues(0) = 0
                End If

                ' return con il valore letto
                Return nValues(0)

            End If


        Else  ' gestione se debug

            ' ritorno valore fittzio
            Return 1

        End If

    End Function

    ' -------------------------------
    ' Scrittura variabile Bool su Cn
    '---------------------------------
    Public Overridable Function WriteBoolVar(ByVal szVar As stVAR, ByVal nValue As Short, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 scrittura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.WriteVarWordBit_C(SessionOpened, CndexLinkDotNet.Cndex.GW_CODE, nProcess, szVar.nAddress, szVar.nBit, nValue, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on writing bool variable" & vbCrLf & "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum)
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    '------------------------------
    ' Lettura variabile Short su Cn
    '------------------------------
    Public Overridable Function ReadShortVar(ByVal szVar As stVAR, Optional ByVal nProcess As Integer = 1) As Short

        Dim nValues(0) As Short               ' Array (lo vuole la libreria Osai) che conterrà il valore letto
        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO
        Dim nNumVarToBeReaded As Integer = 1  ' Numero di variabili da leggere (fisso a 1)

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nValues(0) = 0

            nComOk = Server.ReadVarWord_C(SessionOpened, CndexLinkDotNet.Cndex.GW_CODE, nProcess, szVar.nAddress, nNumVarToBeReaded, nValues, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on ReadVarWord_C" & vbCrLf & what_happened()
                Return CShort(ERRORVALUE)     ' In uscita setto variabile a ERRORVALUE errore 

            Else

                ' return con il valore letto
                Return nValues(0)

            End If

        Else  ' gestione se debug

            ' ritorno true
            Return 1

        End If

    End Function

    ' -------------------------------
    ' Scrittura variabile Short su Cn
    '---------------------------------
    Public Overridable Function WriteShortVar(ByVal szVar As stVAR, ByVal nValue As Short, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 scritt. OK Se 0 lettura KO
        Dim nValues(0) As Short               ' Array (lo vuole la libreria Osai) che conterrà il valore letto
        Dim nNumVarToBeWrited As Integer = 1  ' Numero di variabili da leggere (fisso a 1)


        nValues(0) = nValue

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.WriteVarWord_C(SessionOpened, CndexLinkDotNet.Cndex.GW_CODE, nProcess, szVar.nAddress, nNumVarToBeWrited, nValues, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on writing short variable" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    '--------------------------------
    ' Lettura variabile Double su Cn
    '--------------------------------
    Public Overridable Function ReadDoubleVar(ByVal szVar As stVAR, Optional ByVal nProcess As Integer = 1) As Double

        Dim nValues(0) As Double               ' Array (lo vuole la libreria Osai) che conterrà il valore letto
        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO
        Dim nNumVarToBeReaded As Integer = 1  ' Numero di variabili da leggere (fisso a 1)

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nValues(0) = 0

            nComOk = Server.ReadVarDouble_C(SessionOpened, CndexLinkDotNet.Cndex.GW_CODE, nProcess, szVar.nAddress, nNumVarToBeReaded, nValues, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on reading double variable" & vbCrLf & what_happened()
                Return CDbl(ERRORVALUE)     ' In uscita setto variabile a ERRORVALUE errore 

            Else

                ' return con il valore letto
                Return nValues(0)

            End If


        Else  ' gestione se debug

            ' ritorno true
            Return 1.0

        End If

    End Function

    ' ---------------------------------
    ' Scrittura variabile Double su Cn
    '----------------------------------
    Public Overridable Function WriteDoubleVar(ByVal szVar As stVAR, ByVal nValue As Double, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 scritt. OK Se 0 lettura KO
        Dim nValues(0) As Double              ' Array (lo vuole la libreria Osai) che conterrà il valore letto
        Dim nNumVarToBeWrited As Integer = 1  ' Numero di variabili da leggere (fisso a 1)


        nValues(0) = nValue

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.WriteVarDouble_C(SessionOpened, CndexLinkDotNet.Cndex.GW_CODE, nProcess, szVar.nAddress, nNumVarToBeWrited, nValues, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on writing double variable" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    '-----------------------------------
    ' Lettura variabile E (Double) su Cn
    '-----------------------------------
    Public Overridable Function ReadVarE(ByVal szVar As stVAR, Optional ByVal nProcess As Integer = 1) As Double

        Dim nValues(0) As Double              ' Array (lo vuole la libreria Osai) che conterrà il valore letto
        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO
        Dim nNumVarToBeReaded As Integer = 1  ' Numero di variabili da leggere (fisso a 1)

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nValues(0) = 0

            nComOk = Server.ReadVarDouble_C(SessionOpened, CndexLinkDotNet.Cndex.E_CODE, nProcess, szVar.nAddress, nNumVarToBeReaded, nValues, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on reading double variable" & vbCrLf & what_happened()
                Return CDbl(ERRORVALUE)     ' In uscita setto variabile a ERRORVALUE errore 

            Else

                ' return con il valore letto
                Return nValues(0)

            End If


        Else  ' gestione se debug

            ' ritorno valore fittizio
            Return 1.0

        End If

    End Function

    ' ---------------------------------
    ' Scrittura variabile E (Double) su Cn
    '----------------------------------
    Public Overridable Function WriteVarE(ByVal szVar As stVAR, ByVal nValue As Double, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 scr. OK Se 0 lettura KO
        Dim nValues(0) As Double              ' Array (lo vuole la libreria Osai) che conterrà il valore letto
        Dim nNumVarToBeWrited As Integer = 1  ' Numero di variabili da leggere (fisso a 1)


        nValues(0) = nValue

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.WriteVarDouble_C(SessionOpened, CndexLinkDotNet.Cndex.E_CODE, nProcess, szVar.nAddress, nNumVarToBeWrited, nValues, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on writing double variable" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    '--------------------------------
    ' Lettura variabile SC su Cn
    '--------------------------------
    Public Overridable Function ReadSCVar(ByVal nIndex As Integer, ByVal nNumChar As Integer, Optional ByVal nProcess As Integer = 1) As String

        Dim szValue As String = ""
        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO
        Dim szText As String = ""


        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.ReadVarText_C(SessionOpened, CndexLinkDotNet.Cndex.SC_CODE, nProcess, nIndex, nNumChar, szValue, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on reading SC variable" & vbCrLf & what_happened()
                Return ""     ' In uscita setto variabile a ERRORVALUE errore 

            Else

                ' return con il valore letto
                Return szValue

            End If


        Else  ' gestione se debug

            ' ritorno true
            Return "SC VAR - DEBUG"

        End If


    End Function

    ' ---------------------------------
    ' Scrittura variabile SC su Cn
    '----------------------------------
    Public Overridable Function WriteSCVar(ByVal nIndex As Integer, ByVal nNumChar As Integer, ByVal szText As String, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 scritt. OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.WriteVarText_C(SessionOpened, CndexLinkDotNet.Cndex.SC_CODE, nProcess, nIndex, nNumChar, szText, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on writing SC variable" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    '--------------------------------
    ' Lettura variabile MW su Cn
    '--------------------------------
    Public Overridable Function ReadVarMW(ByVal szVar As stVAR, Optional ByVal nProcess As Integer = 1) As UShort

      Dim nValues(0) As Short               ' Array (lo vuole la libreria Osai) che conterrà  il valore letto
      Dim nComOk As Short                   ' Se 1 scr. OK Se 0 lettura KO
      Dim nNumVarToRead As Short = 1  ' Numero di variabili da leggere (fisso a 1)

        ' se macchina collegata e non in debug
      If (Not (Debug)) Then

         nValues(0) = 0

         nComOk = Server.ReadVarWord_C(SessionOpened, CndexLinkDotNet.Cndex.MW_CODE, nProcess, szVar.nAddress, nNumVarToRead, nValues, ErrClass, ErrNum)

         If (nComOk = ERRORE_OSAI) Then

            ErrMsg = "Error on reading MW variable" & vbCrLf & what_happened()
            Return (9999)     ' In uscita setto variabile a ERRORVALUE errore 

         Else

            ' return con il valore letto
            Return nValues(0)

         End If


      Else  ' gestione se debug

         ' ritorno true
         Return 1

      End If

    End Function

   '--------------------------------
   ' Lettura multi variabile MW su Cn
   '--------------------------------
   Public Overridable Function ReadMultipleVarMW(ByVal nAddress As Integer, ByRef nValues() As Short, ByVal nNumVarToRead As Short, Optional ByVal nProcess As Integer = 1) As Boolean

      Dim nComOk As Short                   ' Se 1 scr. OK Se 0 lettura KO

      ' se macchina collegata e non in debug
      If (Not (Debug)) Then

         nValues(0) = 0

         nComOk = Server.ReadVarWord_C(SessionOpened, CndexLinkDotNet.Cndex.MW_CODE, nProcess, nAddress, nNumVarToRead, nValues, ErrClass, ErrNum)

         If (nComOk = ERRORE_OSAI) Then

            ErrMsg = "Error on reading multiple MW variable" & vbCrLf & what_happened()
            Return False      ' In uscita setto variabile a ERRORVALUE errore 

         Else
            Return True
         End If

      Else  ' gestione se debug
         Return True
      End If

   End Function


#End Region

#Region "METODI - Info da CN e varie"

    ' ---------------------------------
    ' Lettura Warning Msg
    '----------------------------------
    Public Overridable Function ReadWarning(ByRef szText As String) As Boolean

        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.ReadWarningMsg_C(SessionOpened, szText, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on reading Warning Messages" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    ' ---------------------------------
    ' Lettura programma corrente
    '----------------------------------
    Public Overridable Function GetActiveProgram(ByVal nProcess As Integer) As String
        Dim szMainPrg As String = ""
        Dim szSubProgram As String = ""
        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO


        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.GetActivePartProgram_C(SessionOpened, nProcess, 1, szMainPrg, szSubProgram, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on GetActivePartProgram_C" & vbCrLf & what_happened()
                Return "Error"      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                szMainPrg = Replace(szMainPrg, vbNullChar, "")    ' Pulisco i caratteri farlocchi ...
                Return szMainPrg

            End If

            ' se sono in debug
        Else

            Return "OK"

        End If                                  ' Endif gestione macchina collegata

    End Function

    ' ---------------------------------------------------------------
    ' Ritorna True se lo stato del CN è IDLE
    '----------------------------------------------------------------
    Public Overridable Function IsResetStatus(Optional ByVal nProcess As Integer = 1) As Boolean
        Dim RetVal As Short
        Dim ncInfo As New CndexLinkDotNet.Cndex.GETINFO1DATA

        RetVal = Server.GetNcInfo1_C(SessionOpened, nProcess, ncInfo, ErrClass, ErrNum)

        If RetVal > 0 Then

            If ncInfo.mode_select = 0 Then
                Return True
            Else
                Return False
            End If

        Else
            'MsgBox("Error in IsResetStatus" & vbCrLf & "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum))
            Return 0
        End If

    End Function

    ' ---------------------------------
    ' Lettura info CN 1 
    '----------------------------------
    Public Overridable Function NcInfo1(ByRef ncInfo As CndexLinkDotNet.Cndex.GETINFO1DATA, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.GetNcInfo1_C(SessionOpened, nProcess, ncInfo, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on reading NcInfo1" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    ' ---------------------------------
    ' Lettura info CN 2 
    '----------------------------------
    Public Overridable Function NcInfo2(ByRef ncInfo As CndexLinkDotNet.Cndex.GETINFO2DATA, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.GetNcInfo2_C(SessionOpened, nProcess, ncInfo, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on reading NcInfo2" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    '------------------------------
    ' Lettura process stato info Cn
    '------------------------------
    '
    ' ha causato molto dispiacere il fatto che se uso la Server.GetProcessStatus_C con winnbi < 3.1.1
    ' dà una UNRESOLVED a run time della GetProcessStatus_C8 ( notare l' "8" finale ) nella CNDEXLINK.DLL
    '
    ' soluzione : con Win Nbi recenti, uso Server.GetProcessStatus_C ; con Winnbi vecchi, faccio override
    ' di questa funzione USANDO LA STRUTTURA NUOVA CndexLinkDotNet.Cndex.PROCDATA ( altrimenti non è possibile
    ' fare override; ma poi uso una variabile locale tipo vecchio ( PROCDATA ) e in caso di esito positivo, 
    ' copio i dati risultanti.
    '
    ' Attenzione : si ha lo stesso problema anche con la Server.GetNcInfo1_C ma curiosamente non con le funzioni
    ' di lettura scrittura variabili CN .... boh !!
    Public Overridable Function NcProcessStatus(ByRef ncInfo As CndexLinkDotNet.Cndex.PROCDATA, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.GetProcessStatus_C(SessionOpened, nProcess, ncInfo, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on GetProcessStatus_C" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    ' ---------------------------------
    ' Lettura dati assi
    '----------------------------------
    Public Overridable Function GetAxesValue(ByRef AxesData() As CndexLinkDotNet.Cndex.GETINTDATA, ByVal AsciiNameAxe As Byte, ByVal nTypeCoord As Integer, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.GetAxesPosition_C(SessionOpened, nProcess, AsciiNameAxe, nTypeCoord, 1, AxesData, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = "Error on reading Axes Data" & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    ' -------------------------------------------------
    ' Lettura stato macchina su processo passato per parametro
    '--------------------------------------------------
    Public Overridable Function GetMachineStatus(Optional ByVal nProcess As Integer = 1) As Byte
        Dim RetVal As Short
        Dim ncInfo As New CndexLinkDotNet.Cndex.GETINFO1DATA
      ' se macchina collegata e non in debug

      If (Not (Debug)) Then

         RetVal = Server.GetNcInfo1_C(SessionOpened, nProcess, ncInfo, ErrClass, ErrNum)
         If RetVal > 0 Then
            Return ncInfo.status

         Else
            ErrMsg = "Error on reading Machine Status" & vbCrLf & what_happened()
            Return 0
         End If
         ' se sono in debug
      Else
         Return True
      End If
   End Function

    ' -------------------------------------------------
   ' Lettura modalità  macchina su processo passato per parametro
    '--------------------------------------------------
    Public Overridable Function GetModeSelected(Optional ByVal nProcess As Integer = 1) As Byte
        Dim RetVal As Short
        Dim ncInfo As New CndexLinkDotNet.Cndex.GETINFO1DATA

      ' se macchina collegata e non in debug
      If (Not (Debug)) Then

         RetVal = Server.GetNcInfo1_C(SessionOpened, nProcess, ncInfo, ErrClass, ErrNum)
         If RetVal > 0 Then
            Return ncInfo.mode_select

         Else
            ErrMsg = "Error on reading Machine Mode" & vbCrLf & what_happened()
            Return 0
         End If
         ' se sono in debug
      Else
         Return True
      End If
   End Function

    ' ---------------------------------
   ' CN in modalità  AUTO
    '----------------------------------
    Public Overridable Function SetAutoMode(Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1  OK ; Se 0 KO

        ' se macchina collegata e non in debug
      If (Not (Debug)) Then

         nComOk = Server.SetProcessMode_C(SessionOpened, nProcess, 2, ErrClass, ErrNum)

         If (nComOk = ERRORE_OSAI) Then

            ErrMsg = "Error on SetAutoMode" & vbCrLf & what_happened()
            Return False      ' In uscita setto variabile a ERRORVALUE errore 

         Else

            Return True

         End If

         ' se sono in debug
      Else
         Return True
      End If                                  ' Endif gestione macchina collegata

    End Function

    ' ---------------------------------
    ' Seleziona part program da rendere attivo
    '----------------------------------
    Public Overridable Function ActivateProgramOnNC(ByRef szNamePrg As String, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.SelectPartProgram_C(SessionOpened, nProcess, szNamePrg, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = Message.msg(112) & szNamePrg & vbCrLf & what_happened()
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else
         Return True
      End If                                  ' Endif gestione macchina collegata

    End Function

    Public Overridable Function ActivatePP(ByVal szPartPrg As String, Optional ByVal nProcess As UShort = 1) As Short
        Return ActivateProgramOnNC(szPartPrg, nProcess)
    End Function

    ' ---------------------------------
    ' Setta modalità CN Edit, Auto, MDI, ....
    '----------------------------------
    Public Overridable Function SetMode(ByVal nMode As Short, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.SetProcessMode_C(SessionOpened, nProcess, nMode, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = Message.msg(119) & vbCrLf & "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum)
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

    ' ---------------------------------
    ' Stringa MDI da eseguire
    '----------------------------------
    Public Overridable Function SetMdiString(ByRef szString As String, Optional ByVal nProcess As Integer = 1) As Boolean

        Dim nComOk As Short                   ' Se 1 lettura OK Se 0 lettura KO

        ' se macchina collegata e non in debug
        If (Not (Debug)) Then

            nComOk = Server.SetMdiString_C(SessionOpened, nProcess, szString, ErrClass, ErrNum)

            If (nComOk = ERRORE_OSAI) Then

                ErrMsg = Message.msg(120) & vbCrLf & "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum)
                Return False      ' In uscita setto variabile a ERRORVALUE errore 

            Else

                Return True

            End If

            ' se sono in debug
        Else

            Return True

        End If                                  ' Endif gestione macchina collegata

    End Function

#End Region

#Region " funzione nuove per open series, qui vuote"



   Public Overridable Function GetActualTool(Optional ByVal nProcess As Integer = 1) As Double
      Return 0
   End Function

   Public Overridable Function GetActualCorr(Optional ByVal nProcess As Integer = 1) As UShort
      Return 0
   End Function

   Public Overridable Function GetFeedOverride(Optional ByVal nProcess As Integer = 1) As UShort
      Return 0
   End Function

   Public Overridable Function GetRapidOverride(Optional ByVal nProcess As Integer = 1) As UShort
      Return 0
   End Function

   Public Overridable Function GetSpeedOverride(Optional ByVal nProcess As Integer = 1) As UShort
      Return 0
   End Function

   Public Overridable Function GetProgrammedRapid(Optional ByVal nProcess As Integer = 1) As Double
      Return 0.0
   End Function

   Public Overridable Function GetProgrammedFeed(Optional ByVal nProcess As Integer = 1) As Double
      Return 0.0
   End Function

   Public Overridable Function GetProgrammedSpeed(Optional ByVal nProcess As Integer = 1) As Double
      Return 0.0
   End Function

   Public Overridable Function GetActualFeed(Optional ByVal nProcess As Integer = 1) As Double
      Return 0.0
   End Function

   Public Overridable Function GetActualSpeed(Optional ByVal nProcess As Integer = 1) As Double
      Return 0.0
   End Function

    Public Overridable Function GetActualToolLen(ByVal nRecord As UInteger) As Double

        Dim n_ret As Short
        Dim pRecordBuff As CndexLinkDotNet.Cndex.OFFSET_TABLE

        If (Not (Debug)) Then

            n_ret = Server.GetOffsetTabRecord_C(SessionOpened, nRecord, pRecordBuff, ErrClass, ErrNum)

            If (n_ret = ERRORE_OSAI) Then
                ErrMsg = Message.msg(120) & vbCrLf & "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum)
                Return -999998.999      ' In uscita setto variabile a ERRORVALUE errore 
            Else
                Return pRecordBuff.tactl1
            End If
        Else             ' se sono in debug
            Return 10.0
        End If                                  ' Endif gestione macchina collegata

    End Function

    Public Overridable Function GetActualToolDiam(ByVal nRecord As UInteger) As Double

        Dim n_ret As Short
        Dim pRecordBuff As CndexLinkDotNet.Cndex.OFFSET_TABLE

        If (Not (Debug)) Then

            n_ret = Server.GetOffsetTabRecord_C(SessionOpened, nRecord, pRecordBuff, ErrClass, ErrNum)

            If (n_ret = ERRORE_OSAI) Then
                ErrMsg = Message.msg(120) & vbCrLf & "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum)
                Return -999997.999      ' In uscita setto variabile a ERRORVALUE errore 
            Else
                Return pRecordBuff.tdiameter
            End If
        Else             ' se sono in debug
            Return 20.0
        End If                                  ' Endif gestione macchina collegata

    End Function

   Public Overridable Function PutFile(ByRef szPathFile As String, ByVal szTargetPath As String, ByRef nErrClass As UInteger, ByRef nErrNum As UInteger, ByRef FileSize As Integer) As Integer
      Return 0
   End Function

   Public Overridable Function ReadPPLines(ByVal nProcess As Integer, ByRef EightLines() As String, ByRef nErrClass As UInteger, ByRef nErrNum As UInteger) As Boolean
      Return True
   End Function

#End Region

#Region "Controllo win Nbi"

    ''' <summary>
    ''' Verifica se è installata la WINNBI e se è una versione compatibile con .NET
    ''' </summary>
    ''' <param name="DotNet">Versione compatibile con framework .NET</param>
    Shared Function GetWinnbi(Optional ByRef DotNet As Boolean = False) As Boolean

        Dim DotNetMinVersion As New System.Version("3.1.1")
        Dim readValue() As String
        Dim Ver As System.Version
        Dim key As RegistryKey
        Dim b_ret As Boolean

        b_ret = False

        Try

            'leggo le versioni installate
            key = Registry.LocalMachine.OpenSubKey("SOFTWARE\OSAI\WinNBI")
            readValue = key.GetSubKeyNames
            'verifico che ci sia al massimo una versione installata
            If readValue.Count > 1 Then
                MessageBox.Show("more versions of WinNBI found." & vbNewLine &
                                "Please ckeck keys in HKEY_LOCAL_MACHINE\SOFTWARE\OSAI\WinNBI",
                                "Error on GetWinnbi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

            'MsgBox("readValue(0) = " & readValue(0) & vbCrLf & "readValue.Count = " & readValue.Count.ToString)

            ' in XP la 4.0.1 mi ritorna   3.2 ....errore di lunghezza

            If readValue(0).Length < 4 Then
                readValue(0) = readValue(0) & "0"
            End If

            'La precisione di Osai nel rilasciare le versioni !!
            '        If readValue(0) = "3.05" Then readValue(0) = "3.0.5"
            '       If readValue(0) = "3.03" Then readValue(0) = "3.0.3"

            If (readValue(0).Substring(0, 3) = "3.0") And (readValue(0).Substring(3, 1) <> ".") Then
                readValue(0) = Replace(readValue(0), "3.0", "3.0.")
            End If


            For Each szVersion As String In readValue
                Ver = New System.Version(szVersion)

                'se versione compatibile con framework .NET
                If Ver >= DotNetMinVersion Then
                    DotNet = True
                End If

                'se entro almeno una volta ho trovato almeno una versione installata
                b_ret = True

            Next


            'DotNet = False  '!!

        Catch e As Exception

            If Not b_force_S10WLK32 Then
                MsgBox("Unable to get WinNbi version... " & e.ToString, MsgBoxStyle.Critical, "error in GetWinnbi")
            End If

            b_ret = False


        End Try

        Return b_ret

    End Function

    ''' <summary>
    ''' restituisce la versione installata di WINNBI 
    ''' </summary>
    Shared Function GetWinnbi_version() As String

        Dim readValue() As String
        Dim key As RegistryKey

        Try
            'leggo le versioni installate
            key = Registry.LocalMachine.OpenSubKey("SOFTWARE\OSAI\WinNBI")
            readValue = key.GetSubKeyNames

            'La precisione di Osai nel rilasciare le versioni !!
            If readValue(0) = "3.05" Then readValue(0) = "3.0.5"
            If readValue(0) = "3.03" Then readValue(0) = "3.0.3"
            Return readValue(0)

        Catch e As Exception
            MsgBox("Unable to get WinNbi version... " & e.ToString, "error in GetWinnbi_version")

            Return "0.9.99"

        End Try




    End Function

#End Region

#Region "Explain what happened"

    ' Error codes for NETBIOS class (class 3)
    '
    ' 0x0001  Illegal buffer length
    ' 0x0003  Illegal command
    ' 0x0005  Command timed out
    ' 0x0006  Message incomplete, issue another command
    ' 0x0007  Illegal buffer address
    ' 0x0008  Session number out of range
    ' 0x0009  No resource available
    ' 0x000a  Session closed
    ' 0x000b  Command cancelled
    ' 0x000d  Duplicate name
    ' 0x000e  Name table full
    ' 0x000f  No deletions, name has active sessions
    ' 0x0011  Local session table full
    ' 0x0012  Remote session table full
    ' 0x0013  Illegal name number
    ' 0x0014  No callname
    ' 0x0015  Cannot put * in NCB_NAME
    ' 0x0016  Name in use on remote adapter
    ' 0x0017  Name deleted
    ' 0x0018  Session ended abnormally
    ' 0x0019  Name conflict detected
    ' 0x0021  Interface busy, IRET before retrying
    ' 0x0022  Too many commands outstanding, retry later
    ' 0x0023  Ncb_lana_num field invalid
    ' 0x0024  Command completed while cancel occurring
    ' 0x0026  Command not valid to cancel
    ' 0x0030  Name defined by anther local process
    ' 0x0034  Environment undefined. RESET required
    ' 0x0035  Required OS resources exhausted
    ' 0x0036  Max number of applications exceeded
    ' 0x0037  No saps available for netbios
    ' 0x0038  Requested resources are not available
    ' 0x0039  Invalid ncb address or length > segment
    ' 0x003B  Invalid NCB DDID
    ' 0x003C  Lock of user area failed
    ' 0x003f  NETBIOS not loaded
    ' 0x0040  System error

    Const NETBIOS_class As Integer = 3

    Const No_callname_err As Integer = 20 ' 0x0014  No callname

    Const CNC_Error_class As Integer = 4

    Const CL4_Syntax_error As Integer = 1
    Const CL4_Format_error As Integer = 8
    Const CL4_Undefined_symbol As Integer = 9
    Const CL4_Duplicated_label As Integer = 53
    Const CL4_Label_too_long As Integer = 55
    Const CL4_Sub_Table_overflow As Integer = 56
    Const CL4_Label_Table_overflow As Integer = 57
    Const CL4_Part_program_handling_error As Integer = 65
    Const CL4_Part_program_not_found As Integer = 66

    Const CNDEX_INTERFACE_class As Integer = 10

    Const ERR_SERVER_ALREADY_CREATED As Integer = 1 ' CNDEX server already created
    Const ERR_CREATING_SERVER_OBJECT As Integer = 2 ' Error creating CNDEX server
    Const ERR_SERVER_NOT_CREATED As Integer = 3     ' CNDEX server never created or already released
    Const ERR_INVALID_PARAMETER As Integer = 4      ' Invalid value for one or more parameters
    Const ERR_OPTION_NOT_ENABLED As Integer = 5     ' The COMMUNICATION option is not enabled for connected CNC


    Function what_happened() As String
        Dim sz_return As String

        sz_return = "Class: " & Str(ErrClass) & "  Number: 0x" & Hex(ErrNum)

        Select Case ErrClass

            Case NETBIOS_class ' --------------------------- class3 - NETBIOS -----------------

                Select Case ErrNum
                    Case No_callname_err
                        sz_return = "Please verify connection ( cable etc. )" & vbCrLf & vbCrLf & "( No call name - Class 3 err 0x14 )"

                End Select

            Case CNC_Error_class ' --------------------------- class4 - CNC_Error -----------------

                Select Case ErrNum
                    Case CL4_Syntax_error
                        sz_return = "Syntax error" & vbCrLf & vbCrLf & "( Class 4 err 1 )"

                    Case CL4_Format_error
                        sz_return = "Format error" & vbCrLf & vbCrLf & "( Class 4 err 8 )"

                    Case CL4_Undefined_symbol
                        sz_return = "Undefined symbol" & vbCrLf & vbCrLf & "( Class 4 err 9 )"

                    Case CL4_Duplicated_label
                        sz_return = "Duplicated label" & vbCrLf & vbCrLf & "( Class 4 err 53 )"

                    Case CL4_Label_too_long
                        sz_return = "Label too long" & vbCrLf & vbCrLf & "( Class 4 err 55 )"

                    Case CL4_Sub_Table_overflow
                        sz_return = "Subroutine Table overflow" & vbCrLf & vbCrLf & "( Class 4 err 56 )"

                    Case CL4_Label_Table_overflow
                        sz_return = "Label Table overflow" & vbCrLf & vbCrLf & "( Class 4 err 57 )"

                    Case CL4_Part_program_handling_error
                        sz_return = "Part_program_handling_error" & vbCrLf & vbCrLf & "( Class 4 err 65 )"

                    Case CL4_Part_program_not_found
                        sz_return = "Part_program_not_found" & vbCrLf & vbCrLf & "( Class 4 err 66 )"

                End Select ' class4 - CNC_Error 



            Case CNDEX_INTERFACE_class ' --------------------------- class 10 - CNDEX_INTERFACE -----------------

                Select Case ErrNum
                    Case ERR_SERVER_ALREADY_CREATED
                        sz_return = "CNDEX server already created ( Class 10 err 1 )"

                    Case ERR_CREATING_SERVER_OBJECT
                        sz_return = "Error creating CNDEX server ( Class 10 err 2 )"

                    Case ERR_SERVER_NOT_CREATED
                        sz_return = "CNDEX server never created or already released ( Class 10 err 3 )"

                    Case ERR_INVALID_PARAMETER
                        sz_return = "Invalid value for one or more parameters ( Class 10 err 4 )"

                    Case ERR_OPTION_NOT_ENABLED
                        sz_return = vbCrLf & "The 'A06 CndexLink communication' option is not enabled on connected CNC ( Class 10 err 5 )"
                End Select

        End Select


        Return sz_return

    End Function

#End Region

End Class

