- 基于Modbus tcp 协议的数据抓取,并解析,源码使用C#开发
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace modbus
{
class Program
{
#region 字节转换为16进制字符
static string ByteToHexString(byte[] data)
{
string strTemp = "";
for (int i = 2; i < data.Length; i++)
{
string a = Convert.ToString(data[i], 16).PadLeft(2, '0');
strTemp = strTemp + a;
}
return strTemp.Substring(0, 100);
}
#endregion
#region 16进制字符转换为字节
static byte[] HexString(string hs)
{
hs = hs.Replace(" ", "");
string strTemp = "";
byte[] b = new byte[hs.Length / 2];
for (int i = 0; i < hs.Length / 2; i++)
{
strTemp = hs.Substring(i * 2, 2);
b[i] = Convert.ToByte(strTemp, 16);
}
return b;
}
#endregion
#region 发送、接收报文并返回报文
static string SendPack(string sendCodeMeg, string IpAddress, int port)
{
IPAddress ip = IPAddress.Parse(IpAddress);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
Console.WriteLine("開始發送數據。。。");
clientSocket.Connect(new IPEndPoint(ip, port));
Console.WriteLine("服务器连接成功");
}
catch
{
Console.WriteLine("连接服务器失败\n");
return null;
}
try
{
string sendMessage = sendCodeMeg;
var sendData = HexString(sendMessage);
string recvStr = null;
int bytes;
try
{
Console.WriteLine("发送报文:{0}", sendMessage);
clientSocket.Send(sendData);
byte[] recvBytes = new byte[1024];
clientSocket.ReceiveTimeout = 5000;
bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0);
recvStr += ByteToHexString(recvBytes);
}
catch (Exception ex)
{
Console.WriteLine("出现错误!\n{0}\n\n", ex);
recvStr = null;
}
if (recvStr != null)
{
Console.WriteLine("获取成功!\n 获得数据:{0}\n\n", recvStr);
}
clientSocket.Close();
return recvStr;
}
catch
{
Console.WriteLine("出现错误!\n");
return null;
}
}
#endregion
static void Main(string[] args)
{
Console.WriteLine("开始!");
string IP = "10.139.49.61";
int port = 502;
int fnu = 4;
string a = fnu.ToString("x2");
string sendCodeMeg1 = "02 00 00 00 00 06 01 03 01 10 00 02";
string sendCodeMeg2 = "03 00 00 00 00 06 01 03 01 0A 00 02";
string data1 = null;
string data2 = null;
for (int num = 0; num < 5; num++)
{
Console.WriteLine("第{0}次调用Get_Fan函数!\n", num + 1);
data1 = SendPack(sendCodeMeg1, IP, port);
if (data1 != null)
{
break;
}
}
for (int num = 0; num < 5; num++)
{
Console.WriteLine("第{0}次调用Get_Fan函数!\n", num + 1);
data2 = SendPack(sendCodeMeg2, IP, port);
if (data2 != null)
{
break;
}
}
Console.WriteLine("结束");
Console.ReadKey();
}
}
}
|