Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports Modbus
Imports Modbus.Device
Imports Modbus.Data
Imports System.Net
Imports System.Net.Sockets
Imports System.IO.Ports
Public Class Form1

    Public Const Port As Integer = 502
    Private comPort As New SerialPort()
    Private master As IModbusSerialMaster
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        cmbBaud.SelectedIndex = 7
        cmbDataBit.SelectedIndex = 1
        cmbParity.SelectedIndex = 0
        cmbStopBit.SelectedIndex = 0
        For Each s As String In SerialPort.GetPortNames()
            cmbPort.Items.Add(s)
        Next s
        cmbPort.SelectedIndex = 0
    End Sub

    Private Sub btOpenCOM_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btOpenCOM.Click
        comPort.PortName = cmbPort.Text
        comPort.BaudRate = Integer.Parse(cmbBaud.Text)
        comPort.DataBits = Integer.Parse(cmbDataBit.Text)
        If cmbParity.Text.Substring(0, 1) = "0" Then
            comPort.Parity = Parity.None
        ElseIf cmbParity.Text.Substring(0, 1) = "1" Then
            comPort.Parity = Parity.Odd
        ElseIf cmbParity.Text.Substring(0, 1) = "2" Then
            comPort.Parity = Parity.Even
        End If
        If cmbStopBit.Text = "0" Then
            comPort.StopBits = StopBits.None
        ElseIf cmbStopBit.Text = "1" Then
            comPort.StopBits = StopBits.One
        End If
        comPort.Open()
        master = ModbusSerialMaster.CreateRtu(comPort)

        btOpenCOM.Enabled = False
        btCloseCOM.Enabled = True
        timerScan.Enabled = True
        txtChannelNumber.Enabled = False
    End Sub

    Private Sub btCloseCOM_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btCloseCOM.Click
        comPort.Close()
        btOpenCOM.Enabled = True
        btCloseCOM.Enabled = False
        timerScan.Enabled = False
        txtChannelNumber.Enabled = True
    End Sub

    Private Sub timerScan_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerScan.Tick
        Try
            Dim sKey As String = ""
            Dim slaveID As Byte = 1
            Dim startAddress As UShort = 0
            Dim numInputs As UShort = UShort.Parse(txtChannelNumber.Text)
            Dim inputs() As Boolean = master.ReadInputs(slaveID, startAddress, numInputs)

            For i As Integer = 0 To numInputs - 1
                sKey &= i.ToString() & "=>" & Convert.ToInt32(inputs(i)) & vbCr
                If (i + 1) Mod 5 = 0 Then
                    sKey &= vbLf
                End If
            Next i
            txtMsg.Text = sKey
        Catch ex As Exception
            btCloseCOM_Click_1(sender, e)
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class
