using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Tps_LQ_Transmitter.com
{
public class MySerial
{
SerialPort serial;
public bool IsOpen
{
get
{
if (serial == null)
return false;
return serial.IsOpen;
}
}
public MySerial()
{
}
public virtual void portClose()
{
}
public bool Init(string com)
{
serial = new SerialPort();
serial.PortName = com; //端口号设置为com_port的值
serial.BaudRate = 9600;
serial.DataBits = 8;
serial.StopBits = StopBits.One;//停止位设置为com_stop的值
serial.Parity = Parity.None;//获取奇偶校验选项的值
serial.ReadTimeout = 1000; //读取等待时间1000
// serial.ReceivedBytesThreshold = 1;
// serial.DataReceived += Serial_DataReceived;
serial.Open();
return serial.IsOpen;
}
///
/// 串口COM先写后读方法;
/// 写入的时候会自动在后面添加modbus-CRC16检验
///
/// 写入的数据
/// 返回的数据
public virtual byte[] writeAndRead(byte[] data)
{
if (data == null)
return null;
//先读空
if (serial.BytesToRead > 0)
serial.DiscardInBuffer();
byte[] crc = crc16(data);
byte[] newarray = new byte[data.Length + 2];
Array.Copy(data, newarray, data.Length);
newarray[data.Length] = crc[0];
newarray[data.Length + 1] = crc[1];
serial.Write(newarray, 0, newarray.Length);
Thread.Sleep(150);
if(serial.BytesToRead > 0)
{
byte[] dat = new byte[serial.BytesToRead];
serial.Read(dat, 0, dat.Length);
return dat;
}
else
{
return null;
}
}
///
/// modbus_CRC16校验
///
/// 需要校验的byte[]型数据
/// 校验后数据(高位在后,低位在前)
public byte[] crc16(byte[] data)
{
byte[] crc = new byte[2];
UInt16 wCrc = 0xFFFF;
for (int i = 0; i < data.Length; i++)
{
wCrc ^= Convert.ToUInt16(data[i]);
for (int j = 0; j < 8; j++)
{
if ((wCrc & 0x0001)==1)
{
wCrc >>= 1;
wCrc ^= 0xA001;//异或多项式
}
else
{
wCrc >>= 1;
}
}
}
crc[1] = (byte)((wCrc & 0xFF00) >> 8);//高位在后
crc[0] = (byte)(wCrc & 0x00FF); //低位在前
return crc;
}
private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
}
}
}