我有一个简单的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发送? 任何帮助将不胜感激。
答案 0 :(得分:3)
Hex适用于人类,您的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)