Imports System
Imports System.IO
Imports System.Windows.Forms
Imports Ivi.Visa.Interop			'VISA library namespace specification

' Sample code for control of measuring instruments (power supply and load devices, etc.)
' using KI-VISA
' Copyright by Kikusui Electronics Corp. 2020
' Code creation: SE Section 2, Yajima.
'
' 2020.09.01 Ver1.00e  English version(Ver1.01 based)

Public Class Form1

	'Create resource manager object
    Dim rm As IResourceManager3
    Dim msg As IMessage

	'Dialog box title
    Dim sAppTitle = "KI-VISA Sample for VB.net"

	'Main form
    Public Sub New()
        InitializeComponent()

		'Specify form display position in screen center
        Me.StartPosition = FormStartPosition.CenterScreen

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

		'Storage variable of VISA resource list found by FindResource
        Dim foundResources() As String

		'Initialize the Resource Manager
        rm = New ResourceManager()

		'Get the name of a VISA resource containing an INSTR available in FindResource
		'For more information, please refer to KI-VISA Library VISA COM Guidebook 8 - Dynamically Setting VISA Addresses (starting on page 48).
        Try
            foundResources = rm.FindRsrc("?*INSTR")

        Catch ex As Exception
			MessageBox.Show _
				("No available VISA resources found on the computer." _
				 + vbCrLf + "Make sure your device is connected",
				 sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Exit Sub

        End Try


		'Add the acquired VISA resource name to the VISA Resource Name combo box.
        cmb_Resources.DataSource = foundResources

		'Add a setting command to the combo box.
		'Commands not listed in the combo box can be entered manually at run time.
		'If you edit the commands here, you can select any command from the pull-down menu.
		'As a typical example, the following commands are available for the 
		'PMX18-5A (DC power supply 18V/5A model).
        cmb_CommandString.Items.Add("SYST:REMOTE")
        cmb_CommandString.Items.Add("SYST:LOCAL")
        cmb_CommandString.Items.Add("*CLS")
        cmb_CommandString.Items.Add("OUTP ON")
        cmb_CommandString.Items.Add("OUTP OFF")
        cmb_CommandString.Items.Add("VOLT 10")
        cmb_CommandString.Items.Add("VOLT 1")
        cmb_CommandString.Items.Add("CURR 1")
        cmb_CommandString.Items.Add("CURR 0.1")
		cmb_CommandString.SelectedIndex = 0		   'Display the first command

		'Add a query command to the combo box
        cmb_QueryString.Items.Add("*IDN?")
        cmb_QueryString.Items.Add("*STB?")
        cmb_QueryString.Items.Add("SYST:ERR?")
        cmb_QueryString.Items.Add("OUTP?")
        cmb_QueryString.Items.Add("VOLT?")
        cmb_QueryString.Items.Add("CURR?")
        cmb_QueryString.Items.Add("READ:VOLT?")
        cmb_QueryString.Items.Add("READ:CURR?")
		cmb_QueryString.SelectedIndex = 0			 'Show the first query command

		'Disable button before opening a VISA session.
        btn_SendCommand.Enabled = False
        btn_SendQuery.Enabled = False
        btn_SerialPolling.Enabled = False

        '----------------------------------------------------------------------
		' [Caution] Searching for LAN Devices
		' Dynamic search may not be available for LAN devices.
		' In that case, you can use it by Finding with KI-VISA Instruments Explorer.
        '----------------------------------------------------------------------

    End Sub
	'Open VISA session
    Private Sub btn_Open_Click(sender As Object, e As EventArgs) Handles btn_Open.Click
		'For more information, see KI-VISA Library VISA COM Guidebook 6 - Opening VISA Sessions (starting on page 35).
        Dim gpib As IGpib
        Dim seri As ISerial
        Dim tcp As ITcpipInstr
        Dim usb As IUsb

		'Open a VISA session with the resource name specified in the combo box
        Try
			msg = rm.Open(cmb_Resources.Text, AccessMode.NO_LOCK, 0, "") 'Support the change of timeout specification in NI-VISA 
			MessageBox.Show("VISA session opened successfully!" + vbCrLf +
							cmb_Resources.Text, sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Asterisk)

        Catch ex As Exception
			MessageBox.Show("VISA session opening failed." + vbCrLf +
							cmb_Resources.Text, sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Exit Sub

        End Try

		'Configuration by Interface Type
		'Please refer to KI-VISA Library VISA COM Guidebook 7 - Basic IO (from page 39 onwards) for details.
        msg.TerminationCharacter = 10
		msg.TerminationCharacterEnabled = True	'When performing ReadString() on an IEEE 488.2 measuring instrument,
											' "true" setting is recommended for correct terminating.
        msg.SendEndEnabled = True

		'Configure interface type by HardwareInterfaceType
        Select Case msg.HardwareInterfaceType
            Case 1
                'GPIB
                gpib = msg
                gpib.RepeatAddressingEnabled = True
                gpib.UnaddressingEnabled = False

				'Enable the serial polling button (since only GPIB and USB can be used)
                btn_SerialPolling.Enabled = True

            Case 4
				'ASRL(Serial port)
				'You can set the baud rate by changing the parameters here.
                seri = msg
				seri.BaudRate = 19200								'baud rate　19200bps
				seri.DataBits = 8									'Data Bits 8bit
				seri.StopBits = SerialStopBits.ASRL_STOP_ONE			'Stop Bits 1bit
				seri.Parity = SerialParity.ASRL_PAR_NONE				'No parity
				seri.FlowControl = SerialFlowControl.ASRL_FLOW_NONE	'Without flow control

				'Disabling the serial polling button
                btn_SerialPolling.Enabled = False

            Case 6
                'LAN
				' [Caution] Dynamic search may not be available for LAN devices.
				' In that case, you can use it by Finding with KI-VISA Instruments Explorer.
                tcp = msg

				'Disabling the serial polling button
                btn_SerialPolling.Enabled = False

            Case 7
                'USB
                usb = msg

				'Enable the serial polling button(since only GPIB and USB can be used)
                btn_SerialPolling.Enabled = True

        End Select

		'Enable the button.
        btn_SendCommand.Enabled = True
        btn_SendQuery.Enabled = True

    End Sub

	'Sending commands
    Private Sub btn_writeString_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_SendCommand.Click
        Dim r As Integer

		'Send the command selected by cmb_CommandString
		r = msg.WriteString(cmb_CommandString.Text + vbLf)	 'Add a delimiter after the command message


		'If you want to write the command directly, you can also write it like this.
		'r = msg.WriteString("VOLT 10" + vbLf)
		'r = msg.WriteString("OUTP ON" + vbLf)

	End Sub

	'Example of sending query command and receiving result
    Private Sub btn_SendQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_SendQuery.Click
        Dim r As Integer
        Dim strret As String = ""

		'query command transmission
		r = msg.WriteString(cmb_QueryString.Text + vbLf)		'Add a delimiter after the command message


		'Receive query results
        Try
			strret = msg.ReadString(1024)					'Buffer size 1024 bytes

        Catch ex As Exception
			MessageBox.Show("Failed to receive query message.",
							sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Exit Sub

        End Try
		'Returns the value received by ReadString.
        tb_Result.Text = strret
    End Sub

	'Example of serial polling the status byte register
    Private Sub btn_SerialPolling_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_SerialPolling.Click

        Dim stb As Short

		'Serial polling the status byte register.
		'ReadSTB is only available for GPIB and USB interfaces.  
		'For other interfaces, the button are disabled. (because exception is occur)
        stb = msg.ReadSTB()

		'Write result data to text box
        tb_Result.Text = stb.ToString()
    End Sub

	'Processing when the form was closed
    Private Sub quitQToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles QuitQToolStripMenuItem.Click
		'Close the VISA session     
        If Not msg Is Nothing Then
            msg.Close()
        End If
		'Close the form
        Me.Close()
    End Sub

	'Clear the Result text box
    Private Sub btn_ClearRersult_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_ClearRersult.Click

		'Clear the Result text box
        tb_Result.Text = ""
    End Sub

	'AboutBox Version/Contact Information Display
    Private Sub aboutToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles AboutAToolStripMenuItem.Click

		MessageBox.Show(
			"Samplecode for KI-VISA for VB.net Ver1.00e" + vbCrLf +
			"Copyright by Kikusui Electronics Corp. 2020" + vbCrLf + sAppTitle)

    End Sub


End Class
