Module ScopeMoudule
    Public myMgr As Ivi.Visa.Interop.ResourceManager
    Public myscope As Ivi.Visa.Interop.FormattedIO488

    Private strQueryResult As String

    Public Function ScopeOpen(ScopeID As String, timeoutNum As Integer) As String

        Try
            ScopeClear()

            If ScopeID = "" Then
                Return "FAIL"
            End If
            myMgr = New Ivi.Visa.Interop.ResourceManager
            myscope = New Ivi.Visa.Interop.FormattedIO488
            myscope.IO = myMgr.Open(ScopeID)
            myscope.IO.Timeout = timeoutNum
            DrainDeviceOutput()
            strQueryResult = DoQueryString("*IDN?")
            Debug.Print("Identification string: " + strQueryResult)

            Return strQueryResult
        Catch ex As System.Runtime.InteropServices.COMException
            Debug.Print("ErrorCode 값: " & ex.ErrorCode)
            Debug.Print("ErroMassage 값: " & ex.Message.ToString)
            Debug.Print("HResult 값: " & ex.HResult)
            Return "FAIL"
        Catch ex As Exception
            Return "FAIL"
        End Try
    End Function

    ''계측기 쪽 버퍼 비우기
    Public Sub DrainDeviceOutput(Optional readTimeoutMs As Integer = 200)
        Dim prevTimeout As Integer = myscope.IO.Timeout
        Try
            myscope.IO.Timeout = readTimeoutMs
            Dim s As String = myscope.ReadString
            Debug.Print("남아있는 데이터: " + s)
            Do While Not String.IsNullOrWhiteSpace(s)
                s = myscope.ReadString
            Loop
        Catch
            checkError()
        Finally
            myscope.IO.Timeout = prevTimeout
        End Try
    End Sub


    Public Function DoCommand(command As String) As String
        Dim errStr As String

        Try
            myscope.WriteString(command)
            errStr = CheckInstrumentErrors()
            If errStr.Replace(" ", "") <> "" Then
                Return errStr
            End If

            Return "PASS"
        Catch ex As Exception
            Return "VISA COM Error: " + vbCrLf + CStr(Err.Number) + ", " + Err.Source + "," + Err.Description
        End Try

    End Function


    Public Function DoQueryString(query As String) As String
        Dim errStr As String
        Try

            myscope.WriteString(query)
            DoQueryString = myscope.ReadString
            errStr = CheckInstrumentErrors()
            If errStr.Replace(" ", "") <> "" Then
                Return DoQueryString & " / " & errStr
            End If
            Return DoQueryString

        Catch ex As Exception
            Try
                DrainDeviceOutput()
            Catch
            End Try
            Return "VISA COM Error: " + vbCrLf + CStr(Err.Number) + ", " + Err.Source + "," + Err.Description
        End Try

    End Function

    Private Function CheckInstrumentErrors() As String
        Dim strerrval As String
        Dim strout As String = ""
        Try
            myscope.WriteString(":SYSTem:ERRor?")
        strerrval = myscope.ReadString
        While Val(strerrval) <> 0
            strout = "INST Error: " + strerrval
            myscope.WriteString(":SYSTem:ERRor?")
            strerrval = myscope.ReadString
        End While

        If Not strout = "" Then
            MsgBox(strout, vbExclamation, "INST Error Messages")
            myscope.FlushWrite(False)
            myscope.FlushRead()
            Return strout
        End If

            Return ""

        Catch ex As Exception
            Main_Form.txbWindow.AppendText("Error check Message Error:" & ex.Message & vbCrLf)
            Return ex.Message
        End Try

    End Function

    Private Sub checkError()
        Dim strerrval As String
        Try
            myscope.WriteString(":SYSTem:ERRor?")
            strerrval = myscope.ReadString
            While Val(strerrval) <> 0
                myscope.WriteString(":SYSTem:ERRor?")
                strerrval = myscope.ReadString
            End While
        Catch ex As Exception
            Main_Form.txbWindow.AppendText("VISA BUFFER CLEAR ERROR:" & ex.Message & vbCrLf)
        End Try
    End Sub


    ''' <summary>스코프 버퍼 초기화. 연결된 경우에만 동작.</summary>
    Public Sub ScopeClear()
        Try
            If myscope IsNot Nothing AndAlso myscope.IO IsNot Nothing Then
                myscope.IO.Clear()
            End If
        Catch
            ' 연결 해제 등으로 접근 불가 시 무시
        End Try
    End Sub

End Module
