前面更新了,S7协议的原理。握手,挥手,读写DB的bool,8位16位32位等等数据类型的方法。越到后面发现阅读量比较低,可能感兴趣的人少,我主要用到DB区的操作,暂时不更其他区域的报文解析方法。有人说,网上有很多开源的代码,请记住我的初衷不是为了写这个代码,而是教会大家学习研究协议的方法,授人以鱼不如授人以渔。我一直告诉的是大家原理方法,非要杠其他开源的没必要。感兴趣的话可以看看前面的文章, 《西门子S7协议抓包分析并用代码实现》
说难听点,源码在手,懂原理出问题也不怕,其他区域的操作,我用到的话会继续更新。遇到的坑,原理我在代码里面说明,好了废话少说,上源码,不到300行。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace WDBaseCommuntionHelper
{
public class S71200
{
Socket S7TcpClient;//创建socket连接对象
object lockS7 = new object();
public int SendTimeOut { get; set; } = 2000;
public int ReceiveTimeOut { get; set; } = 2000;
public int MaxDelayCycle { get; set; } = 5;//有人问我这个什么意思,就是等待CPU响应的周期数量,如果规定周期没有响应就强制返回
public bool IsConnected { get;private set; }
public ushort PDU { get;private set; }//对外开放PDU只读属性
string ip;
public bool Connect()
{
return Connect(this.ip);
}
/// <summary>
/// 连接S71200
/// </summary>
/// <param name="ip">PLC的IP地址</param>
/// <returns>是否连接成功</returns>
public bool Connect(string ip)
{
if(this.ip != ip) this.ip = ip;
S7TcpClient = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建sokcet tcp连接对象
S7TcpClient.SendTimeout = SendTimeOut;
S7TcpClient.ReceiveTimeout = ReceiveTimeOut;
IAsyncResult asyncResult=S7TcpClient.BeginConnect( new IPEndPoint(IPAddress.Parse(ip),102 ),null,null);//异步连接
asyncResult.AsyncWaitHandle.WaitOne(3000,true);//阻塞最多等待3秒
if (!asyncResult.IsCompleted)//异步操作没完成 就关掉tcp连接 返回失败
{
S7TcpClient.Close();
return false;
}
//上面的socket连接相当于执行了tcp的三次握手
byte[] cotp = new byte[] //cotp报文封装
{
0x03,0x00,0x00,0x16,0x11,0xE0,0x00,0x00,0x00,0x01,0x00,0xC0,0x01,0x0A,0xC1,
0x02,0x01,0x02,0xC2,0x02,0x01,0x00
};
byte[] s7comm = new byte[]//s7comm报文封装
{
0x03, 0x00, 0x00,0x19, 0x02, 0xf0,0x80,0x32,0x01,0x00,0x00,0xff,0xff,0x00,
0x08,0x00, 0x00, 0xf0, 0x0, 0x0, 0x3, 0x0, 0x3, 0x07, 0x80
};
try
{
//第一次握手
byte[] buffer=SendRecive(cotp);
//第二次握手
buffer = SendRecive(s7comm);
if (buffer.Length == 27)//正确返回报文字节数
{
PDU = (ushort)(buffer[25] * 256 + buffer[26]-18);//获得此CPU允许单次通讯的字节数,因为占了两个字节,高8位位权256所以乘256
}
IsConnected = true;
return true;
}
catch (Exception ex)
{
return false;
}
}
public byte[] ReadDB(int DB, int startByte, int count)
{
//通过查看报文获得读取db2.dbx0.0读取1个字节的报文
byte[] s7Comm = new byte[31]
{
0x03,0x00,0x00,0x1f,0x02,0xf0,0x80,0x32,0x01,0x00,0x00,0x00,
0x00,0x00,0x0e,0x00,0x00,0x04,0x01,0x12,0x0a,0x10,0x02,0x00,
0x02,0x00,0x02,0x84,0x00,0x00,0x00
};
refercence++; //通讯参考标识每次自增 相当于给这个报文起了个名字
byte[]bs = BitConverter.GetBytes((ushort)refercence);
s7Comm[11] = bs[1];
s7Comm[12] = bs[0];
//获得字节数组 先转为ushort类型是为了确定输出字节为2个
bs = BitConverter.GetBytes((ushort)count);
//分析报文看到规律第23(高8位)24(低8位)控制读取长度
s7Comm[23] = bs[1];
s7Comm[24] = bs[0];
//获得字节数组 先转为ushort类型是为了确定输出字节为2个
byte[] dbArry = BitConverter.GetBytes((ushort)DB);
//分析报文看到规律第25(高8位)26(低8位)控制要读取的DB号
s7Comm[25] = dbArry[1];
s7Comm[26] = dbArry[0];
//重点 分析报文看到规律第28 29 30,控制要写的地址,高21位是控制字节位置的,左移二进制把低三位位置腾出来,低3位控制bit位(2^3)不能超过8
uint startByte1 = (uint)startByte << 3;
s7Comm[28] = (byte)((startByte1 & 0xff0000) >> 16);//获取bit16-bit23字节,与0xff0000获得,再右移16位让它可以存在字节 大端存储
bs = BitConverter.GetBytes((ushort)(startByte1 & 0x00ffff)); //与0xffff获得低16位再获取2个字节
s7Comm[29] = bs[1];
s7Comm[30] = bs[0];
byte[] s7Result = SendRecive(s7Comm.ToArray());//发送s7报文并接收
if (s7Result?.Length>=(25+count)&&s7Result[21]==0xff && s7Result[11]==s7Comm[11] && s7Result[12]==s7Comm[12] )//判断一下 防止指向无效索引
{
byte[] result = new byte[count];
Array.Copy(s7Result, 25,result,0, count);
return result;
}
return null;
}
int refercence = 888;//通讯参考标识
/// <summary>
/// 写DB的方法字节排序大端 参考1413笔数据
/// </summary>
/// <param name="DB">DB号</param>
/// <param name="startByte">起始字节数</param>
/// <param name="writeBs">写多少个字节</param>
/// <returns></returns>
public bool WriteDB(int DB,int startByte, byte[] writeBs)
{
//固定35个字节,加上我要写的字节组成报文,由于长度可变我们用list
List<byte> s7Comm = new List<byte>()
{
0x03,0x00,0x00,0x25,0x02,0xf0,0x80,0x32,0x01,0x00,
0x00,0xa0,0x00,0x00,0x0e,0x00,0x06,0x05,0x01,0x12,
0x0a,0x10,0x02,0x00,0x02,0x00,0x02,0x84,0x00,0x00,
0x40,0x00,0x04,0x00,0x10//...数据区
};//0x84代表DB区
//分析报文看到规律第2(高8位)3(低8位)控制要写的报文长度 ,获得字节数组 先转为ushort类型是为了确定输出字节为2个固定35个字节
byte[] bs = BitConverter.GetBytes((ushort)(35 + writeBs.Length));
s7Comm[02] = bs[1];
s7Comm[03] = bs[0];
refercence++; //通讯参考标识每次自增 相当于给这个报文起了个名字
bs = BitConverter.GetBytes((ushort)refercence);
s7Comm[11] = bs[1];
s7Comm[12] = bs[0];
bs = BitConverter.GetBytes((ushort)(writeBs.Length+4));//data 长度 这里指的item长度 固定长度4+可变长度数据
s7Comm[15] = bs[1];
s7Comm[16] = bs[0];
bs = BitConverter.GetBytes((ushort)writeBs.Length); //分析报文看到规律第23(高8位)24(低8位)控制要写的字节数
s7Comm[23] = bs[1];
s7Comm[24] = bs[0];
bs = BitConverter.GetBytes((ushort)DB);//分析报文看到规律第25(高8位)26(低8位)控制要写的DB号
s7Comm[25] = bs[1];
s7Comm[26] = bs[0];
//重点 分析报文看到规律第28 29 30,控制要写的地址,高21位是控制字节位置的,左移二进制把低三位位置腾出来,低3位控制bit位(2^3)不能超过8
uint startByte1 = (uint)startByte << 3;
s7Comm[28] = (byte)((startByte1 & 0xff0000) >> 16);//获取bit16-bit23字节,与0xff0000获得,再右移16位让它可以存在字节 大端存储
bs = BitConverter.GetBytes((ushort)(startByte1 & 0x00ffff)); //与0xffff获得低16位再获取2个字节
s7Comm[29] = bs[1];
s7Comm[30] = bs[0];
bs = BitConverter.GetBytes((ushort)(writeBs.Length * 8)); //分析报文看到规律第33(高8位)34(低8位)控制要写的bit数量
s7Comm[33] = bs[1];
s7Comm[34] = bs[0];
s7Comm.AddRange(writeBs);//添加我们要写的字节数组数据
byte[] s7Result=SendRecive(s7Comm.ToArray());//发送s7报文并接收
if (s7Result?.Length>=21&& s7Result[21]== 0xff && s7Result[11] == s7Comm[11] && s7Result[12] == s7Comm[12]) //0xff s7协议代表着成功
{
return true;
}
return false;
}
public bool WriteDB(int DB, int startByte, bool b, int startbit = 0)
{
//固定35个字节,加上我要写的字节组成报文,由于长度可变我们用list
List<byte> s7Comm = new List<byte>()
{
0x03,0x00,0x00,0x25,0x02,0xf0,0x80,0x32,0x01,0x00,
0x00,0xa0,0x00,0x00,0x0e,0x00,0x06,0x05,0x01,0x12,
0x0a,0x10,0x02,0x00,0x02,0x00,0x02,0x84,0x00,0x00,
0x40,0x00,0x04,0x00,0x10//...数据区
};//0x84代表DB区
byte[] writeBs = new byte[] { b ? (byte)1 : (byte)0 };
//分析报文看到规律第2(高8位)3(低8位)控制要写的报文长度 ,获得字节数组 先转为ushort类型是为了确定输出字节为2个固定35个字节
byte[] bs = BitConverter.GetBytes((ushort)(35 + writeBs.Length));
s7Comm[02] = bs[1];
s7Comm[03] = bs[0];
refercence++; //通讯参考标识每次自增 相当于给这个报文起了个名字
bs = BitConverter.GetBytes((ushort)refercence);
s7Comm[11] = bs[1];
s7Comm[12] = bs[0];
bs = BitConverter.GetBytes((ushort)(writeBs.Length + 4));//data 长度 这里指的item长度 固定长度4+可变长度数据
s7Comm[15] = bs[1];
s7Comm[16] = bs[0];
s7Comm[22] = 0x01;
bs = BitConverter.GetBytes((ushort)writeBs.Length); //分析报文看到规律第23(高8位)24(低8位)控制要写的字节数
s7Comm[23] = bs[1];
s7Comm[24] = bs[0];
bs = BitConverter.GetBytes((ushort)DB);//分析报文看到规律第25(高8位)26(低8位)控制要写的DB号
s7Comm[25] = bs[1];
s7Comm[26] = bs[0];
if (startbit > 7)
{
throw new Exception("bool位范围0-7");//抛异常 一个字节只有8位 允许操作的二进制是0-7位
}
//重点 分析报文看到规律第28 29 30,控制要写的地址,高21位是控制字节位置的,左移二进制把低三位位置腾出来,低3位控制bit位(2^3)不能超过8
uint startByte1 = (uint)startByte << 3;
startByte1 |= (uint)startbit;//与要写的bit位或一下,生成具体地址
s7Comm[28] = (byte)((startByte1 & 0xff0000) >> 16);//获取bit16-bit23字节,与0xff0000获得,再右移16位让它可以存在字节 大端存储
bs = BitConverter.GetBytes((ushort)(startByte1 & 0x00ffff)); //与0xffff获得低16位再获取2个字节
s7Comm[29] = bs[1];
s7Comm[30] = bs[0];
s7Comm[32] = 0x03;
//分析报文看到规律第33(高8位)34(低8位)控制要写的bit数量
s7Comm[33] = 0x00;
s7Comm[34] = 0x01;
s7Comm.AddRange(writeBs);//添加我们要写的字节数组数据
byte[] s7Result = SendRecive(s7Comm.ToArray());//发送s7报文并接收
//0xff s7协议代表着成功 为什么要判断通讯标识符呢?因为当博图软件和上位机是同一个电脑是,底层可能会串包,我用博图软件监控调试时,就串包了。
//所以加上通讯标识符的判断
if (s7Result?.Length >= 21 && s7Result[21] == 0xff && s7Result[11] == s7Comm[11] && s7Result[12] == s7Comm[12])
{
return true;
}
return false;
}
//发送接收加锁处理 由于PLC单线程处理通讯
public byte[] SendRecive(byte[] arry)
{
int delay = 0;
try
{
Monitor.Enter(lockS7);
int reslut = S7TcpClient.Send(arry);
while (S7TcpClient.Available == 0)
{
Thread.Sleep(10);
delay++;
if (delay > MaxDelayCycle)
{
break;
}
}
byte[] ResByte = new byte[S7TcpClient.Available];
reslut = S7TcpClient.Receive(ResByte);
return ResByte;
}
catch (Exception )
{
IsConnected = false;
return null;
}
finally
{
Monitor.Exit(lockS7);
}
}
//关闭TCP连接 用于退出软件调用tcp4次挥手
public void DisConnect()
{
if (S7TcpClient != null)
{
S7TcpClient.Close();
}
}
//判断两个字节数组是否一样,我用来实现读数据有变动刷新UI,有效的节省电脑资源
//如返回false就用委托实现UI刷新,平时不刷新
public bool ByteArrayEquals(byte[] b1, byte[] b2)
{
if (b1 == null || b2 == null) return false;
if (b1.Length == 0 || b2.Length == 0 || b1.Length != b2.Length) return false;
for (int i = 0; i < b1.Length; i++)
{
if (b1[i] != b2[i])
{
return false;
}
}
return true;
}
}
}
#上位机# #PLC# #触摸屏# #西门子# #电工交流群#
本文暂时没有评论,来添加一个吧(●'◡'●)