Imports System.IO.Ports

Public Class Form1
    Private hPort As IntPtr
    Public Sub New()
        InitializeComponent()
        'Load com port data to comobox Object
        LoadComPort()
        btnCloseCOM.Enabled = False
    End Sub

    Private Sub LoadComPort()
        Dim ports As String() = SerialPort.GetPortNames()
        Array.Sort(ports)

        For Each port As String In ports
            If port <> "COM1" Then
                cmbComPort.Items.Add(port)
            End If            
        Next

        cmbComPort.SelectedIndex = 0

    End Sub

    Private Sub btnOpenCOM_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenCOM.Click
        'Open com port
        Me.hPort = PACNET.UART.Open(cmbComPort.Text + "," + txtBaurdRate.Text)

        If hPort = CType(-1, IntPtr) Then

            MessageBox.Show("open com error,error code " & PACNET.ErrHandling.GetLastError())
        Else
            btnOpenCOM.Enabled = False
            btnCloseCOM.Enabled = True
        End If
    End Sub

    Private Sub btnCloseCOM_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCloseCOM.Click
        'Close com port
        PACNET.UART.Close(hPort)
        btnOpenCOM.Enabled = True
        btnCloseCOM.Enabled = False
    End Sub

    Private Sub btnReadAI_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadAI.Click
        Dim fValue As Single = 0
        Dim iRet As Boolean
        Dim intReadChannel As Integer = Integer.Parse(txtReadChannel.Text)
        Dim intChannel As Integer = Integer.Parse(txtChannel.Text)
        If intReadChannel <= intChannel Then
            'Read data
            iRet = PACNET.PAC_IO.ReadAI(hPort, PACNET.PAC_IO.PAC_REMOTE_IO(Convert.ToInt32(txtAddress.Text)), intReadChannel, intChannel, fValue)
            If iRet = False Then
                MessageBox.Show("error code" & PACNET.ErrHandling.GetLastError())
            Else
                txtAIValue.Text = fValue.ToString()
            End If
        Else
            MessageBox.Show("Your read channel is error , please rewrite read channel")
        End If
    End Sub
End Class
