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
        Try
            points.Columns.Add(New DataColumn("Channel", GetType(Integer))) 'make a columns
            points.Columns.Add(New DataColumn("Value", GetType(Integer)))
            DataGrid1.DataSource = points
            tableStyle.MappingName = "Points"
            DataGrid1.TableStyles.Add(tableStyle)
        Catch ex As Exception
            DataGrid1.TableStyles("Points").Dispose()
            tableStyle.Dispose()
        End Try
    End Sub
    Private masterTcpClient As TcpClient
    Private master As ModbusIpMaster
    Dim points As New System.Data.DataTable("Points")
    Dim tableStyle As New DataGridTableStyle()
    Private Sub timerScan_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerScan.Tick
        Try
            Dim slaveID As Byte = 1
            Dim startAddress As UShort = 0
            Dim numInputs As UShort = UShort.Parse(txtChannelNumber.Text)
            Dim inputs() As UShort = master.ReadInputRegisters(slaveID, startAddress, numInputs)

            For i As Integer = 0 To numInputs - 1
                points.Rows(i)(1) = Convert.ToInt32(inputs(i)) 'input the value to data table
            Next i
        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
        Dim numInputs As UShort = UShort.Parse(txtChannelNumber.Text)
        For i As Integer = 0 To numInputs - 1
            points.Rows.Add(New Object() {i, 0}) 'make a Row;
        Next i
    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
        points.Rows.Clear() 'clear row
    End Sub
End Class
