SpSetup 类 与Globalspace类
public partial class SpSetup : Form
{
#region 定义变量
///
/// 发送报文
///
public byte[] sendData = new byte[8];
#endregion
#region 构造读取状态报文
///
/// 构造读取状态报文
///
public void GetSendData()
{
byte[] data = new byte[6];
byte[] Address = Globalspace.intToHexByte(Globalspace.startAddress);
byte[] nubmer = Globalspace.intToHexByte(Globalspace.registerNumber);
data[0] = Globalspace.ID; //从机地址
data[1] = Convert.ToByte(Globalspace.modbusPointType.readHoldingRegister); //功能号 - 读取保持寄存器
data[2] = Address[0]; //数据地址
data[3] = Address[1]; //数据地址
data[4] = nubmer[0]; //数据
data[5] = nubmer[1]; //数据
for (int i = 0; i < 6; i++)
{
sendData[i] = data[i]; //报文是用串口发送的
}
Byte[] CRC = new Byte[2];
CRC = Globalspace.CRC_16(data); //进行CRC效验
sendData[6] = CRC[0];
sendData[7] = CRC[1];
}
#endregion
}
class Globalspace
{
#region 定义变量
///
/// 定义串口
///
public static SerialPort sp = new SerialPort();
///
/// Modbus 通讯地址
///
public static byte ID = 2;
///
/// Modbus 功通讯能码
///
public enum modbusPointType
{
readCoilStatus = 01, //读取线圈状态
readInputStatus = 02, //读取输入状态
readHoldingRegister = 03, //读取保持寄存器
readInputRegister = 04, //读取输入寄存器
writeSingleCoil = 05, //强置单线圈
writeSingleRegister = 06, //保持寄存器写入(仅一点)
writeMultipleCoil = 15, //强置多线圈
writeMultipleRegister = 16,//预置多寄存器
};
///
/// 起始地址
///
public static int startAddress = 99;//读D100地址内容
///
/// 读取数量
///
public static int registerNumber = 1;//读一个
///
/// 读写标志位 true —读;false —写。
///
public static bool readORwrite = true;
///
/// 读完成标志
///
public static bool readDone = true; //读取数据完成后,清零
///
/// 写完成标志
///
public static bool writeDone = true;//写入数据完成后,清零
///
/// 创建发送表
///
public static ArrayList sendList = new ArrayList();//创建发送表
///
/// 创建接收表
///
public static ArrayList receivedList = new ArrayList();//创建接收表
///
/// 读数据定时器
///
public static System.Timers.Timer readTimer = new System.Timers.Timer(2000);
///
/// 写数据定时器
///
public static System.Timers.Timer writeTimer = new System.Timers.Timer(2000);
public static string Info = "";
///
/// 监听
///
public static TcpListener listener;
///
/// TCP/IP连接标志
///
public static bool TcpIP = false;
public static bool TH_SP = false;
///
/// PLC通讯标志
///
public static bool PLC = false;
///
/// 接收数据
///
public static ArrayList receivedDataList= new ArrayList();
///
/// 检测结果
///
public static string testResult; //1-通过;0-失败;2-定位失败!
#endregion
#region CRC_16计算
///
/// CRC_16计算
///
/// 数据
/// 返回CRC值
public static Byte[] CRC_16(Byte[] data) //CRC验证码计算
{
Byte[] CRC = new byte[2];
UInt16 Reg_Crc = 0xFFFF;
for (int i = data.Length; i > 0; i--)
{
Reg_Crc ^= data[data.Length - i];
for (int j = 0; j < 8; j++)
{
if ((Reg_Crc & 0x01) == 1)
{
Reg_Crc >>= 1;
Reg_Crc ^= 0xA001;
}
else
{
Reg_Crc >>= 1;
}
}
}
CRC[0] = (byte)(Reg_Crc & 0xFF);
CRC[1] = (byte)(Reg_Crc >>= 8);
return CRC;
}
public static Byte[] CRC_16(ArrayList sendData) //CRC验证码计算
{
byte[] send = new byte[sendData.ToArray().Length];
Object[] obj = Globalspace.sendList.ToArray();
for (int i = 0; i < sendData.ToArray().Length; i++)
{
send[i] = (byte)obj[i];
}
Byte[] CRC = new byte[2];
UInt16 Reg_Crc = 0xFFFF;
for (int i = send.Length; i > 0; i--)
{
Reg_Crc ^= send[send.Length - i];
for (int j = 0; j < 8; j++)
{
if ((Reg_Crc & 0x01) == 1)
{
Reg_Crc >>= 1;
Reg_Crc ^= 0xA001;
}
else
{
Reg_Crc >>= 1;
}
}
}
CRC[0] = (byte)(Reg_Crc & 0xFF);
CRC[1] = (byte)(Reg_Crc >>= 8);
return CRC;
}
#endregion
#region 接收数据完成事件
///
/// 接收数据完成事件
///
///
///
public static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
Control.CheckForIllegalCrossThreadCalls = false;
int n = sp.BytesToRead; //接收字节数
receivedList.Clear(); //清空接收缓存
byte[] Buuf = new byte[n]; //接收字符串
byte[] Data = new byte[n - 2];
byte[] Data_CRC = new byte[2];
sp.Read(Buuf, 0, n);
if (n <= 8)
{
for (int i = 0; i < n; i++)
{
if (i < n - 2)
{
Data[i] = Buuf[i]; //分离CRC重构字符串
}
receivedList.Add(Buuf[i]);
}
Data_CRC = CRC_16(Data); //计算CRC_16校验码
//WriteLog();
if (Data[0] == ID)
{
if (readORwrite)
{
byte[] temp = ReadData(Data, Data_CRC, Buuf, n);
if(Buuf[2]>2) //读处理
{
receivedDataList.Clear();
for(int i=0;i
{
receivedDataList.Add(temp[i]);
}
}
else
{
if(temp[1]==(byte)0x01)
{
PLC = true;
}
else
{
PLC = false;
}
}
}
else
{
//WriteData(Data, Data_CRC, Buuf, n);//写处理
writeDone = true;
}
}
else
{
//MessageBox.Show("通讯错误:设备地址错误!", "系统提示");
}
}
}
catch (Exception err)
{
//MessageBox.Show(err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
#endregion
#region 读状态方法
///
/// 读状态
///
/// 数据
/// CRC 验证码
/// 接收数据
/// 数据长度
private static byte[] ReadData(byte[] Data, byte[] Data_CRC, byte[] Buuf, int n)
{
byte[] dataTemp = new byte[Buuf.Length-5];
if(n > 6) //小于7抛弃报文
{
if (Data[1] == Convert.ToByte(modbusPointType.readHoldingRegister))
{
if (Buuf[n - 2] == Data_CRC[0] && Buuf[n - 1] == Data_CRC[1])
{
for (int i = 0; i < dataTemp.Length;i++ )
{
dataTemp[i] = Buuf[i + 3];
}
readDone = true;
return dataTemp;
}
else
{
MessageBox.Show("通讯错误:读取CRC校验码错误!", "系统提示");
return dataTemp;
}
}
else
{
MessageBox.Show("通讯错误:读取功能码错误!", "系统提示");
return dataTemp;
}
}
else
{
readDone = false;
return dataTemp;
}
}
#endregion
#region 写数据方法
///
/// 写数据
///
/// 数据
/// CRC_16校验码
/// 收到报文
/// 收到数据长度
private static void WriteData(byte[] Data, byte[] Data_CRC, byte[] Buuf, int n)
{
if (n >6)
{
if (Data[1] == Convert.ToByte(modbusPointType.writeMultipleRegister) || Data[1] == Convert.ToByte(modbusPointType.writeSingleRegister))
{
if (Buuf[n - 2] == Data_CRC[0] && Buuf[n - 1] == Data_CRC[1])
{
writeDone = true;
}
else
{
MessageBox.Show("通讯错误:写入CRC校验码错误!", "系统提示");
}
}
else
{
MessageBox.Show("通讯错误:写入功能码错误!", "系统提示");
}
}
}
#endregion
#region int转换byte
///
/// int转换byte
///
///
/param>
br />
///
returns>
/returns>
br />
public static byte[] intToHexByte(int inInt)
br />
{
br />
string hexString = inInt.ToString("x4"); //X:代表16进制 //4:代表每次的数据位数,当位数不足时自动补0
br />
byte[] returnBytes = new byte[hexString.Length / 2];
br />
for (int i = 0; i
returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return returnBytes;
}
public static byte[] intToHexByte2(int inIt)
{
byte[] returnByte = BitConverter.GetBytes(inIt);
return returnByte;
}
#endregion
#region short转换byte
///
/// short转换byte
///
///
/param>
br />
///
returns>
/returns>
br />
public static byte[] shortToByte(short inShort)
br />
{
br />
byte[] abyte0 = new byte[2];
br />
abyte0[1] = (byte)(0xff & inShort);
br />
abyte0[0] = (byte)((0xff00 & inShort) >> 8);
br />
return abyte0;
br />
}
br />
br />
public static byte[] shortToByte2(short inShort)
br />
{
br />
byte[] returnBytes = BitConverter.GetBytes(inShort);
br />
return returnBytes;
br />
}
br />
#endregion
br />
br />
#region 通讯超时处理
br />
///
summary>
/// 通讯超时处理
///
/summary>
br />
public static void Timeout()
br />
{
br />
if (readORwrite)
br />
{
br />
readTimer.Elapsed += new System.Timers.ElapsedEventHandler(ReadOut);//到达时间的时候执行事件;
br />
readTimer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
br />
readTimer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
br />
}
br />
else
br />
{
br />
writeTimer.Elapsed += new System.Timers.ElapsedEventHandler(WriteOut);//到达时间的时候执行事件;
br />
writeTimer.AutoReset = false;//设置是执行一次(false)还是一直执行(true);
br />
writeTimer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
br />
}
br />
}
br />
///
summary>
/// 读超时事件
///
/summary>
br />
///
param name="source">
///
public static void ReadOut(object source, System.Timers.ElapsedEventArgs e)
{
readDone = true;
}
///
/// 写超时事件
///
///
///
public static void WriteOut(object source, System.Timers.ElapsedEventArgs e)
{
writeDone = true;
}
#endregion
#region 报文日志
///
/// 入日志文件
///
/// 报文
public static void WriteLog()
{
FileStream tempStream = new FileStream(Environment.CurrentDirectory + @"\Log.txt", FileMode.Append);
StreamWriter writer = new StreamWriter(tempStream);
string[] data = new string[receivedList.Count];
string st = null;
for (int j = 0; j < receivedList.Count; j++)
{
data[j] = receivedList[j].ToString();
st = st + data[j] + " ";
}
writer.WriteLine("接收数据:" + st + "\n");
writer.Close();
tempStream.Close();
}
#endregion
#region 配置文件操作
///
/// 读取数据
///
/// 文件路径
/// 行数
/// 返回字符串
public static string ReadeFile(string patch, int line)
{
string readstr;
string strTemp = "";
FileStream tempStream = new FileStream(patch, FileMode.Open);
StreamReader reader = new StreamReader(tempStream);
for (int i = 1; !reader.EndOfStream; i++)
{
if (i == line)
{
strTemp = reader.ReadLine();
}
else
{
reader.ReadLine();
}
}
reader.Close();
reader.Dispose();
readstr = strTemp;
return readstr;
}
///
/// 更改数据
///
/// 修改的行数
/// 保存的值
/// 文件的路径
public static void EditFile(int curLine, string newLineValue, string patch)
{
FileStream fs = new FileStream(patch, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"));
string line = sr.ReadLine();
StringBuilder sb = new StringBuilder();
for (int i = 1; line != null; i++)
{
sb.Append(line + "\r\n");
if (i != curLine - 1)
line = sr.ReadLine();
else
{
sr.ReadLine();
line = newLineValue;
}
}
sr.Close();
fs.Close();
FileStream fs1 = new FileStream(patch, FileMode.Open, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs1);
sw.Write(sb.ToString());
sw.Close();
fs.Close();
}
#endregion
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/117309.html