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


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

    End Sub
    Private masterTcpClient As TcpClient
    Private master As ModbusIpMaster
    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
            btDisconnect_Click(sender, e)
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btConnect.Click
        Dim port As Integer
        port = Convert.ToInt16(txtPort.Text)
        masterTcpClient = New TcpClient(txtIP.Text, port)
        master = ModbusIpMaster.CreateIp(masterTcpClient)
        txtChannelNumber.Enabled = False
        btConnect.Enabled = False
        btDisconnect.Enabled = True
        timerScan.Enabled = True
    End Sub

    Private Sub btDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btDisconnect.Click
        masterTcpClient.Close()
        btConnect.Enabled = True
        btDisconnect.Enabled = False
        timerScan.Enabled = False
        txtChannelNumber.Enabled = True
    End Sub
End Class
