Module SpectrumModule
    Private myMgr As Ivi.Visa.Interop.ResourceManager
    Private mySpec As Ivi.Visa.Interop.FormattedIO488

    Private strQueryRes As String

    Public Function SpecOpen(SpecID As String, ToCount As Integer) As String
        Try
            SpecClear()
            myMgr = New Ivi.Visa.Interop.ResourceManager
            mySpec = New Ivi.Visa.Interop.FormattedIO488

            mySpec.IO = myMgr.Open(SpecID)
            mySpec.IO.Timeout = ToCount
            SpecDrainDeviceOutput(200)

            strQueryRes = SpecQueryStr("*IDN?")

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

    Public Sub SpecDrainDeviceOutput(Optional readTimeoutMs As Integer = 200)
        Dim prevTimeout As Integer = mySpec.IO.Timeout
        Try
            mySpec.IO.Timeout = readTimeoutMs
            Dim s As String = mySpec.ReadString
            Do While Not String.IsNullOrWhiteSpace(s)
                s = mySpec.ReadString
            Loop
        Catch
            ' 타임아웃/에러 시 그만 둠
        Finally
            mySpec.IO.Timeout = prevTimeout
        End Try
    End Sub

    Public Function RunCommand(command As String) As String
        Dim errStr As String
        Try
            mySpec.IO.Clear()
            SpecDrainDeviceOutput(200)
            mySpec.WriteString(command)
            errStr = CheckError()
            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 SpecQueryStr(query As String) As String
        Dim errStr As String
        Try
            mySpec.IO.Clear()
            SpecDrainDeviceOutput(200)
            mySpec.WriteString(query)
            SpecQueryStr = mySpec.ReadString
            errStr = CheckError()
            If errStr.Replace(" ", "") <> "" Then
                Return SpecQueryStr & " / " & errStr
            End If
            Return SpecQueryStr

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

    End Function

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

        If Not strout = "" Then
            'MsgBox(strout, vbExclamation, "INST Error Messages")
            mySpec.FlushWrite(False)
            mySpec.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

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

End Module
