-1

我有一个简单的 vb.net 程序,我正在尝试发送 FINS 命令并使用 UDP 接收响应。我一直使用以下问题作为参考点FINS Commands C#,但相信我的数据包有问题,或者我只是没有完全正确。

我当前的程序有 4 个文本框(TBIP, TBPORT, TBSEND, TBReceive)。当我运行程序时,我输入要发送的 IP、端口、数据包信息,然后单击一个按钮。我想要发生的是收到的信息发送到TBReceive

我的表单加载代码如下所示:

Dim publisher As New Sockets.UdpClient(0)
Dim Subsriber As New Sockets.UdpClient(9600)

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

        Subsriber.Client.ReceiveTimeout = 5000
        Subsriber.Client.Blocking = False


    End Sub

我的按钮点击:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        publisher.Connect(TBIP.Text, TBPort.Text)
        Dim Sendbytes() As Byte = ASCII.GetBytes(TBSend.Text)
        publisher.Send(Sendbytes, Sendbytes.Length)

        Subsriber.Client.Blocking = True


        Timer1.Start()

    End Sub

我的计时器:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Try
            Dim ep As IPEndPoint = New IPEndPoint(IPAddress.Any, 0)
            Dim rcvbytes As [Byte]() = Subsriber.Receive(ep)
            Dim returndata As String = ASCII.GetString(rcvbytes)

            TBReceive.Text = returndata.ToString

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class

在欧姆龙 PLC 上,我正在尝试读取 CIO 100。我的 IP 地址是 10.0.1.91,所以我的字符串在下面。(5B 是最后一个八位字节):

80 00 02 01 02 00 01 5B 00 12 01 01 00 00 12 34

为了便于阅读,我在 HEX 位之间添加了空格。

第一个问题可能是我正在转换或尝试将信息作为 ASCII 发送吗?任何帮助,将不胜感激。

4

1 回答 1

3

十六进制适用于人类,您的 PLC 将需要二进制数据。您需要在要在 TextBox 中输入的“800002010200015B0012010100001234”十六进制字符串和 PLC 喜欢的二进制字节之间进行转换。您可以使用的示例代码:

Module HexConversions
    Public Function HexToBinary(hex As String) As Byte()
        hex = hex.Replace(" ", "")
        If hex.Length mod 2 <> 0 then Throw New FormatException 
        Dim bytes = hex.Length \ 2 - 1
        Dim bin(bytes) As Byte
        For ix As Integer = 0 to bytes
            bin(ix) = Byte.Parse(hex.Substring(ix * 2, 2), Globalization.NumberStyles.HexNumber)
        Next
        Return bin
    End Function

    Public Function BinaryToHex(bytes() As Byte, Optional usespace As Boolean = False) As String
        Dim hex = BitConverter.ToString(bytes)
        Return hex.Replace("-", IIf(usespace, " ", ""))
    End Function
End Module

您将在现有代码中使用它,例如:

    Try         
        Dim Sendbytes() As Byte = HexConverter.HexToBinary(TBSend.Text)
        publisher.Send(Sendbytes, Sendbytes.Length)
    Catch ex As FormatException
        MessageBox.Show("Please enter a valid hex string")
        TBSend.Focus()
        TBSend.SelectAll()
    End Try

    Dim rcvbytes() As Byte = Subsriber.Receive(ep)
    TBReceive.Text = HexConverter.BinaryToHex(rcvbytes, True)
于 2014-06-16T15:14:01.540 回答