using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using SerialPortDemon.Properties;
namespace SerialPortDemon
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
this.Load += FrmMain_Load;
}
private void FrmMain_Load(object sender, EventArgs e)
{
InitialSetting();
this.skinEngine1.SkinFile = Application.StartupPath + "\\IrisSkin4\\Skins\\OneBlue.ssk";
}
//串口对象
private SerialPort serialPort = null;
private Encoding encoding = Encoding.Default;
private System.Timers.Timer AutoSendTimer = new System.Timers.Timer();
private int ClearLimitNum = 4096;
private Settings DefaultSetting = Settings.Default;
#region 初始化配置信息
private void InitialSetting()
{
this.AutoSendTimer.Elapsed += AutoSendTimer_Elapsed;
string[] PortList = SerialPort.GetPortNames();
if (PortList.Length > 0)
{
this.cmb_Port.DataSource = PortList;
this.cmb_Port.SelectedIndex = 0;
}
//波特率 9600
string[] BaudList = new string[] { "2400", "4800", "9600", "19200", "38400" };
this.cmb_Baud.DataSource = BaudList;
this.cmb_Baud.SelectedIndex = 2;
//校验位 N
this.cmb_Parity.DataSource = Enum.GetNames(typeof(Parity));
this.cmb_Parity.SelectedIndex = 0;
//停止位 1
this.cmb_StopBits.DataSource = Enum.GetNames(typeof(StopBits));
this.cmb_StopBits.SelectedIndex = 1;
//数据位 8
int[] DataList = new int[] { 5, 6, 7, 8 };
this.cmb_DataBits.DataSource = DataList;
this.cmb_DataBits.SelectedIndex = 3;
//校验方式
this.cmb_ParityMethod.DataSource = Enum.GetNames(typeof(ParityMethod));
this.cmb_ParityMethod.SelectedIndex = 0;
//设置命令按钮
}
private void AutoSendTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Invoke(new Action(() =>
{
SendData();
}));
}
#endregion
//串口状态
private bool isOpen = false;
public bool IsOpen
{
get { return isOpen; }
set
{
isOpen = value;
if (value)
{
this.btn_Open.Text = "关闭串口";
this.btn_Open.Image = Properties.Resources.poweron;
}
else
{
this.btn_Open.Text = "打开串口";
this.btn_Open.Image = Properties.Resources.poweroff;
}
}
}
/// <summary>
/// 发送字节计数
/// </summary>
private int totalSendNum = 0;
public int TotalSendNum
{
get { return totalSendNum; }
set
{
totalSendNum = value;
this.tssl_SendCount.Text = value.ToString();
}
}
//暂停接收
private bool isPause = false;
public bool IsPause
{
get { return isPause; }
set
{
isPause = value;
if (value)
{
this.btn_Pause.Text = "继续接收";
}
else
{
this.btn_Pause.Text = "暂时接收";
}
}
}
private int totalRcvNum = 0;
public int TotalRcvNum
{
get { return totalRcvNum; }
set
{
totalRcvNum = value;
this.tssl_ReceiveCount.Text = value.ToString();
}
}
//保存文件的名称
private string SaveFile
{
get { return DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; }
}
//发送数据
#region 发送数据
private void SendData()
{
if (this.chk_HexSend.Checked)
{
//去掉空格 01 04 50
string temp = this.rtb_Send.Text.Replace(" ", "");
try
{
byte[] b = HexHelper.HexStringToBytes(temp);
serialPort.Write(b, 0, b.Length);
TotalSendNum += b.Length;
}
catch (Exception ex)
{
this.tssl_Status.Text = "发送失败:" + ex.Message;
IsOpen = false;
}
}
else
{
try
{
string temp;
if (this.cbNewLine.Checked)
{
temp = this.rtb_Send.Text + "\r\n";
}
else
{
temp = this.rtb_Send.Text;
}
byte[] b = encoding.GetBytes(temp);
serialPort.Write(b, 0, b.Length);
TotalSendNum += b.Length;
}
catch (Exception ex)
{
this.tssl_Status.Text = "发送失败:" + ex.Message;
IsOpen = false;
}
}
}
#endregion
/// <summary>
/// 接收字节计数
/// </summary>
#region 串口接收事件
/// <summary>
/// 串口接收事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (IsPause) return; //暂停接收
Invoke(new Action(() =>
{
//定义最终的字符串
string Result = string.Empty;
if (this.chk_HexShow.Checked)
{
//定义一个字节数组
try
{
byte[] data = new byte[serialPort.BytesToRead];
//读取缓冲区值到字节数组
this.serialPort.Read(data, 0, data.Length);
//拼接显示
foreach (byte item in data)
{
string hex = Convert.ToString(item, 16).ToUpper(); //转换为16进制大写字符串
Result += (hex.Length == 1 ? "0" + hex : hex) + " ";// 16进制数,如果长度为1,则前面补0
}
//显示
this.rtb_Receive.AppendText(Result + Environment.NewLine);
//更新接收字节总数
TotalRcvNum += data.Length;
}
catch (Exception ex)
{
this.tssl_Status.Text = "接收出现错误:" + ex.Message;
}
}
else
{
try
{
Result = this.serialPort.ReadExisting();
//显示
this.rtb_Receive.AppendText(Result + Environment.NewLine);
//更新接收字节总数
TotalRcvNum += this.serialPort.Encoding.GetByteCount(Result);
}
catch (Exception ex)
{
this.tssl_Status.Text = "接收出现错误:" + ex.Message;
}
}
//是否开启自动清空
if (this.chk_AutoClear.Checked)
{
if (this.rtb_Receive.Text.Length > ClearLimitNum)
{
this.rtb_Receive.Clear();
}
}
}));
}
#endregion
private void btn_Open_Click(object sender, EventArgs e)
{
if (IsOpen)
{
//串口关闭
if (this.serialPort != null)
{
if (this.serialPort.IsOpen)
{
this.serialPort.Close();
}
IsOpen = false;
this.tssl_Status.Text = this.cmb_Port.Text + " 串口关闭成功";
}
}
else
{
//串口打开
//实例化对象
this.serialPort = new SerialPort();
//设置串口属性
try
{
this.serialPort.PortName = this.cmb_Port.Text.Trim();
this.serialPort.BaudRate = Convert.ToInt32(this.cmb_Baud.Text.Trim());
this.serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), this.cmb_Parity.Text.Trim(), true);
this.serialPort.DataBits = Convert.ToInt32(this.cmb_DataBits.Text.Trim());
this.serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), this.cmb_StopBits.Text.Trim(), true);
this.serialPort.RtsEnable = this.chk_Rts.Checked;
this.serialPort.DtrEnable = this.chk_Dtr.Checked;
this.serialPort.Encoding = this.encoding; //编码格式
this.serialPort.ReceivedBytesThreshold = 1;
this.serialPort.DataReceived += SerialPort_DataReceived;
if (this.serialPort.IsOpen)
{
this.serialPort.Close();
}
this.serialPort.Open();
IsOpen = true;
this.tssl_Status.Text = this.cmb_Port.Text + " 串口打开成功";
}
catch (Exception ex)
{
this.tssl_Status.Text = this.cmb_Port.Text + " 串口打开失败:" + ex.Message;
}
}
}
//手动发送
private void btn_HandSend_Click(object sender, EventArgs e)
{
SendData();
}
//发送清除
private void btn_SendClear_Click(object sender, EventArgs e)
{
this.rtb_Send.Clear();
}
//自动发送
private void chk_AutoSend_CheckedChanged(object sender, EventArgs e)
{
if (isOpen==false && this.chk_AutoSend.CheckState == CheckState.Checked)
{
this.chk_AutoSend.CheckState = CheckState.Unchecked;
//停止定时器
this.AutoSendTimer.Enabled = false;
this.tssl_Status.Text = "自动发送失败,串口未打开";
return;
}
if (IsOpen == true && this.chk_AutoSend.CheckState == CheckState.Checked)
{
//禁用手动发送
this.btn_HandSend.Enabled = false;
//获取时间周期
int interval = 0;
if (int.TryParse(this.txt_Period.Text.Trim(), out interval))
{
if (interval < 1 || interval > 60000)
{
interval = 1000;
txt_Period.Text = "1000";
this.tssl_Status.Text = "周期设定过大,限制为1000ms";
}
//开始自动发送
this.AutoSendTimer.Interval = interval;
this.AutoSendTimer.Enabled = true;
//禁用周期设置
this.txt_Period.Enabled = false;
}
else
{
this.chk_AutoSend.CheckState = CheckState.Unchecked;
//停止定时器
this.AutoSendTimer.Enabled = false;
this.tssl_Status.Text = "自动发送失败,周期设定格式不正确";
return;
}
}
else
{
this.btn_HandSend.Enabled = true;
this.txt_Period.Enabled = true;
this.AutoSendTimer.Enabled = false;
}
}
//选择文件
private void btn_OpenFile_Click(object sender, EventArgs e)
{
//创建OpenFileDialog
OpenFileDialog dialog = new OpenFileDialog();
//设置OpenFileDialog属性
dialog.Title = "请选择要发送的文件";
dialog.Filter = "文本文件(*.txt)|*.txt|二进制文件(*.bin)|*.bin|HEX文件(*.hex)|*.hex";
dialog.RestoreDirectory = true;
//打开OpenFileDialog
if (dialog.ShowDialog() == DialogResult.OK)
{
//把十六进制的选择取消
this.chk_HexSend.Checked = false;
//获取文件的名称并显示
string fileName = dialog.FileName;
this.txt_SendPath.Text = fileName;
//读取内容显示
StreamReader sr = new StreamReader(fileName, encoding);
this.rtb_Send.Text = sr.ReadToEnd();
sr.Close();
}
}
//暂停接收
private void btn_Pause_Click(object sender, EventArgs e)
{
IsPause = !IsPause;
}
//选择路径
private void btn_SelectPath_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
this.txt_SavePath.Text = dialog.SelectedPath;
}
}
//保存数据
private void btn_SaveFile_Click(object sender, EventArgs e)
{
if (this.rtb_Receive.Text.Length == 0)
{
this.tssl_Status.Text = "接收数据为空,请检查!";
return;
}
if (this.txt_SavePath.Text.Length == 0)
{
this.tssl_Status.Text = "请先设置要保存的路径!";
return;
}
string savePath = this.txt_SavePath.Text + "\\" + SaveFile;
//创建写入器
StreamWriter sw = new StreamWriter(savePath);
sw.Write(this.rtb_Receive.Text);
sw.Flush();
sw.Close();
this.tssl_Status.Text = "文件" + SaveFile + "保存成功";
}
//命令模式
private void btn_SendCommand_Click(object sender, EventArgs e)
{
//验证数据
bool DataVerify = true;
if (this.chk_Head.Checked)
{
DataVerify &= VerifyHexString(this.txt_Head.Text.Trim());
}
if (this.chk_Data.Checked)
{
DataVerify &= VerifyHexString(this.txt_Data.Text.Trim());
}
if (this.chk_Tail.Checked)
{
DataVerify &= VerifyHexString(this.txt_Tail.Text.Trim());
}
if (!DataVerify)
{
this.tssl_Status.Text = "命令模式填写的数据格式不正确!";
return;
}
if (IsOpen)
{
string fullCmd = string.Empty;
//是否选择帧头
if (this.chk_Head.Checked)
{
fullCmd += this.txt_Head.Text;
}
//是否选择数据
if (this.chk_Data.Checked)
{
fullCmd += this.txt_Data.Text;
}
//是否选择校验
if (this.chk_Parity.Checked)
{
fullCmd = fullCmd.Replace(" ", "");
ParityMethod parityMethod = (ParityMethod)Enum.Parse(typeof(ParityMethod), this.cmb_ParityMethod.Text, true);
switch (parityMethod)
{
case ParityMethod.XOR异或:
fullCmd = HexHelper.BytesToHexString(ParityHelper.DataXORFull(HexHelper.HexStringToBytes(fullCmd)));
break;
case ParityMethod.SUM8累加:
fullCmd = HexHelper.BytesToHexString(ParityHelper.DataSum8Full(HexHelper.HexStringToBytes(fullCmd)));
break;
case ParityMethod.SUM16大端:
fullCmd = HexHelper.BytesToHexString(ParityHelper.DataSum16Full(HexHelper.HexStringToBytes(fullCmd), ParityHelper.BigOrLittle.BigEndian));
break;
case ParityMethod.SUM16小端:
fullCmd = HexHelper.BytesToHexString(ParityHelper.DataSum16Full(HexHelper.HexStringToBytes(fullCmd), ParityHelper.BigOrLittle.LittleEndian));
break;
case ParityMethod.CRC16大端:
fullCmd = HexHelper.BytesToHexString(ParityHelper.DataCrc16Full_Ccitt(HexHelper.HexStringToBytes(fullCmd), ParityHelper.BigOrLittle.BigEndian));
break;
case ParityMethod.CRC16小端:
fullCmd = HexHelper.BytesToHexString(ParityHelper.DataCrc16Full_Ccitt(HexHelper.HexStringToBytes(fullCmd), ParityHelper.BigOrLittle.LittleEndian));
break;
case ParityMethod.ModbusCRC大端:
fullCmd = HexHelper.BytesToHexString(ParityHelper.DataCrc16Full_Modbus(HexHelper.HexStringToBytes(fullCmd), ParityHelper.BigOrLittle.BigEndian));
break;
case ParityMethod.ModbusCRC小端:
fullCmd = HexHelper.BytesToHexString(ParityHelper.DataCrc16Full_Modbus(HexHelper.HexStringToBytes(fullCmd), ParityHelper.BigOrLittle.LittleEndian));
break;
default:
break;
}
}
//是否选择帧尾
if (this.chk_Tail.Checked)
{
fullCmd += this.txt_Tail.Text;
}
this.rtb_Send.Text = fullCmd;
SendCommand(fullCmd);
}
else
{
this.tssl_Status.Text = "命令模式发送失败:串口未连接";
}
}
#region 发送字符串命令
/// <summary>
/// 发送字符串命令
/// </summary>
/// <param name="cmdContent">发送的16进制字符串</param>
private void SendCommand(string cmdContent)
{
this.rtb_Send.Text = cmdContent;
//处理空格
cmdContent = cmdContent.Replace(" ", "");
try
{
this.serialPort.Write(HexHelper.HexStringToBytes(cmdContent), 0, HexHelper.GetByteCount(cmdContent));
//更新发送计数
TotalSendNum += HexHelper.GetByteCount(cmdContent);
}
catch (Exception ex)
{
this.tssl_Status.Text = "发送失败:" + ex.Message;
}
}
#endregion
/// <summary>
/// 验证数据是否为16进制字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private bool VerifyHexString(string str)
{
string temp = str.Replace(" ", "");
return HexHelper.IsHexString(temp) && temp.Length % 2 == 0;
}
private void btn_HandClear_Click(object sender, EventArgs e)
{
this.rtb_Receive.Clear();
}
private void chk_Rts_CheckedChanged(object sender, EventArgs e)
{
if (this.serialPort != null)
{
this.serialPort.RtsEnable = this.chk_Rts.Checked; //数据终端准备好
}
}
/*
DB9只有9根线,遵循RS232标准。定义如下:
DTR,DSR------DTE设备准备好/DCE设备准备好。主流控信号。
RTS,CTS------请求发送/清除发送。用于半双工时,收发切换。属于辅助流控信号。半双工的意思是说,发的时候不收,收的时候不发。
*/
private void chk_Dtr_CheckedChanged(object sender, EventArgs e)
{
if (this.serialPort != null)
{
this.serialPort.DtrEnable = this.chk_Dtr.Checked; //请求发送 RTS
}
}
private void tssl_Clear_Click(object sender, EventArgs e)
{
TotalSendNum = TotalRcvNum = 0;
}
#region 编码格式设置
//
private void tsmi_Ascii_Click(object sender, EventArgs e)
{
this.encoding = Encoding.ASCII;
}
private void tsmi_Utf8_Click(object sender, EventArgs e)
{
this.encoding = Encoding.UTF8;
}
private void tsmi_default_Click(object sender, EventArgs e)
{
this.encoding = Encoding.Default;
}
private void tsmi_unicode_Click(object sender, EventArgs e)
{
this.encoding = Encoding.Unicode;
}
private void tsmi_gb3212_Click(object sender, EventArgs e)
{
this.encoding = Encoding.GetEncoding("GB2312");
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SerialPortDemon
{
public class HexHelper
{
#region 判断是否为16进制字符串
/// <summary>
/// 判断是否为16进制字符串
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static bool IsHexString(string hexString)
{
//十六进制发送时,发送框数据进行十六进制数据正则校验
if (Regex.IsMatch(hexString, "^[0-9A-Fa-f]+$"))
{
//校验成功
return true;
}
//校验失败
return false;
}
#endregion
#region 将ASCII码字符串转换成16进制字符串
/// <summary>
/// 将ascii字符串转换成Hex显示
/// </summary>
/// <param name="asciiString"></param>
/// <returns></returns>
public static string ConvertStringToHexString(string asciiString,Encoding encoding)
{
string hexString = "";
asciiString = asciiString.Replace("\n", "\r\n"); //解决richTextBox获取不到"\r\n"换行符
byte[] arrByte = encoding.GetBytes(asciiString);
foreach (char c in arrByte)
{
int tmp = c;
hexString += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString())).ToUpper() + " ";
}
return hexString;
}
#endregion
#region 将16进制字符串转换成ASCII码字符串
/// <summary>
/// 将Hex转换成ascii字符串显示
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static string ConvertHexStringToString(string hexString, Encoding encoding)
{
string result = string.Empty;
hexString = hexString.Replace(" ", "");
//解决十六进制出现单数据问题,以补0
if (hexString.Length % 2 == 1)
{
hexString = hexString.Insert(hexString.Length - 1, "0");
}
byte[] arrByte = new byte[hexString.Length / 2];
int index = 0;
for (int i = 0; i < hexString.Length; i += 2)
{
//Convert.ToByte(string,16)把十六进制string转化成byte
arrByte[index++] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
result = encoding.GetString(arrByte);
return result;
}
#endregion
#region 获取16进制字符串的字节数
/// <summary>
/// 获取hexString中Byte数量
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static int GetByteCount(string hexString)
{
if (IsHexString(hexString) && (hexString.Length % 2 == 0))
{
// 2 characters per byte
return hexString.Length / 2;
}
else
{
return 0;
}
}
#endregion
#region 单个16进制数转字节
/// <summary>
/// 16进制数转字节
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
private static byte HexToByte(string hex)
{
if (hex.Length > 2 || hex.Length <= 0)
throw new ArgumentException("hex must be 1 or 2 characters in length");
byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return newByte;
}
#endregion
#region 16进制字符串转换成字节数组
/// <summary>
/// 16进制字符串转换成字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] HexStringToBytes(string hexString)
{
//string newString = "";
if (IsHexString(hexString) == false)
{ return null; }
int byteLength = hexString.Length / 2;
byte[] bytes = new byte[byteLength];
string hex;
int j = 0;
for (int i = 0; i < bytes.Length; i++)
{
hex = new String(new Char[] { hexString[j], hexString[j + 1] });
bytes[i] = HexToByte(hex);
j = j + 2;
}
return bytes;
}
#endregion
#region 字节数组转换成16进制字符串
/// <summary>
/// 字节数组转出成16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string BytesToHexString(byte[] bytes)
{
string hexString = "";
for (int i = 0; i < bytes.Length; i++)
{
hexString += bytes[i].ToString("X2");
}
return hexString;
}
#endregion
#region 拼接字节数组
public static byte[] ConcatArrays(byte[] first, byte[] second)
{
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}
public static byte[] ConcatArrays(byte[] first, byte[] second, byte[] third)
{
byte[] ret = new byte[first.Length + second.Length + third.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
third.Length);
return ret;
}
public static byte[] ConcatArrays(params byte[][] arrays)
{
byte[] ret = new byte[arrays.Sum(x => x.Length)];
int offset = 0;
foreach (byte[] data in arrays)
{
Buffer.BlockCopy(data, 0, ret, offset, data.Length);
offset += data.Length;
}
return ret;
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SerialPortDemon
{
public class ParityHelper
{
/// <summary>
/// 校验类型
/// </summary>
public const string XOR异或校验 = "XOR异或校验";
public const string SUM8累加校验 = "SUM8累加校验";
public const string ModBusLRC校验 = "ModBusLRC校验";
public const string CRC16小端 = "CRC16小端";
public const string CRC16大端 = "CRC16大端";
public const string SUM16小端 = "SUM16小端";
public const string SUM16大端 = "SUM16大端";
public const string ModBusCRC小端 = "ModBusCRC小端";
public const string ModBusCRC大端 = "ModBusCRC大端";
/// <summary>
/// 大小端数据模式
/// </summary>
public enum BigOrLittle
{
//大端
BigEndian = 0,
//小端
LittleEndian = 1
}
#region 数据翻转
/// <summary>
/// 翻转byte数组
/// </summary>
/// <param name="bytes"></param>
public static void ReverseBytes(byte[] bytes)
{
byte tmp;
int len = bytes.Length;
for (int i = 0; i < len / 2; i++)
{
tmp = bytes[len - 1 - i];
bytes[len - 1 - i] = bytes[i];
bytes[i] = tmp;
}
}
/// <summary>
/// 规定转换起始位置和长度
/// </summary>
/// <param name="bytes"></param>
/// <param name="start"></param>
/// <param name="len"></param>
public static void ReverseBytes(byte[] bytes, int start, int len)
{
int end = start + len - 1;
byte tmp;
int i = 0;
for (int index = start; index < start + len / 2; index++, i++)
{
tmp = bytes[end - i];
bytes[end - i] = bytes[index];
bytes[index] = tmp;
}
}
/// <summary>
/// 翻转字节顺序 (16-bit)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static UInt16 ReverseBytes(UInt16 value)
{
return (UInt16)((value & 0xFFU) << 8 | (value & 0xFF00U) >> 8);
}
/// <summary>
/// 翻转字节顺序 (32-bit)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static UInt32 ReverseBytes(UInt32 value)
{
return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
(value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;
}
/// <summary>
/// 翻转字节顺序 (64-bit)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static UInt64 ReverseBytes(UInt64 value)
{
return (value & 0x00000000000000FFUL) << 56 | (value & 0x000000000000FF00UL) << 40 |
(value & 0x0000000000FF0000UL) << 24 | (value & 0x00000000FF000000UL) << 8 |
(value & 0x000000FF00000000UL) >> 8 | (value & 0x0000FF0000000000UL) >> 24 |
(value & 0x00FF000000000000UL) >> 40 | (value & 0xFF00000000000000UL) >> 56;
}
#endregion
#region 校验和
/// <summary>
/// 异或校验和
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <returns>校验和值</returns>
public static byte[] DataXOR(byte[] data)
{
byte check = 0;
for (int i = 0; i < data.Length; i++)
{
check ^= data[i];
}
return new byte[] { check };
}
/// <summary>
/// 异或校验和
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <returns>校验的数据数组+校验和</returns>
public static byte[] DataXORFull(byte[] data)
{
byte[] check = DataXOR(data);
List<byte> newdata = new List<byte>();
newdata.AddRange(data);
newdata.AddRange(check);
return newdata.ToArray();
}
/// <summary>
/// 累加校验和
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <returns>返回校验和结果</returns>
public static byte[] DataSum8(byte[] data)
{
byte check = 0;
for (int i = 0; i < data.Length; i++)
{
check = (byte)((check + data[i]) % 0xff);
}
//返回累加校验和
return new byte[] { check };
}
/// <summary>
/// 累加校验和
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <returns>校验的数据数组+校验和</returns>
public static byte[] DataSum8Full(byte[] data)
{
byte[] check = DataSum8(data);
List<byte> newdata = new List<byte>();
newdata.AddRange(data);
newdata.AddRange(check);
return newdata.ToArray();
}
/// <summary>
/// 累加校验和
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <param name="mode">大小端模式</param>
/// <returns>返回校验和结果</returns>
public static byte[] DataSum16(byte[] data, BigOrLittle mode)
{
int num = 0;
for (int i = 0; i < data.Length; i++)
{
num = (num + data[i]) % 0xffff;
}
//返回累加校验和
if (mode == BigOrLittle.LittleEndian)
return BitConverter.GetBytes(ReverseBytes((UInt16)num));
else
return BitConverter.GetBytes((UInt16)num);
}
/// <summary>
/// 累加校验和
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <param name="mode">大小端模式</param>
/// <returns>校验的数据数组+校验和</returns>
public static byte[] DataSum16Full(byte[] data, BigOrLittle mode)
{
byte[] check = DataSum16(data, mode);
List<byte> newdata = new List<byte>();
newdata.AddRange(data);
newdata.AddRange(check);
return newdata.ToArray();
}
#endregion
#region CRC校验
/// <summary>
/// CRC16-CCITT(初始值FFFF,多项式1021,异或值FFFF,异或输出,表逆序,算法逆序)
/// </summary>
private static int[] CRC16_CCITT_TABLE = {
0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
};
/// <summary>
/// CRC16-CCITT CRC校验
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <param name="mode">大小端模式</param>
/// <returns>校验结果</returns>
public static byte[] DataCrc16_Ccitt(byte[] data, BigOrLittle mode)
{
UInt16 check = 0x0000;
int i, j;
for (i = 0; i < data.Length; i++)
{
check ^= (UInt16)((UInt16)data[i] << 8);
for (j = 0; j < 8; j++)
{
if ((check & 0x8000) != 0)
{
check <<= 1;
check ^= 0x1021;
}
else
{
check <<= 1;
}
}
}
if (mode == BigOrLittle.LittleEndian)
return BitConverter.GetBytes(ReverseBytes(check));
else
return BitConverter.GetBytes(check);
}
/// <summary>
/// CRC16-CCITT CRC校验
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <param name="mode">大小端模式</param>
/// <returns>校验是数据数组+校验值</returns>
public static byte[] DataCrc16Full_Ccitt(byte[] data, BigOrLittle mode)
{
byte[] check = DataCrc16_Ccitt(data, mode);
List<byte> newdata = new List<byte>();
newdata.AddRange(data);
newdata.AddRange(check);
return newdata.ToArray();
}
/// <summary>
/// CRC16-MODBUS CRC校验
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <param name="mode">大小端模式</param>
/// <returns>校验值</returns>
public static byte[] DataCrc16_Modbus(byte[] data, BigOrLittle mode)
{
UInt16 check = 0xFFFF;
int i, j;
for (i = 0; i < data.Length; i++)
{
check ^= data[i];
for (j = 0; j < 8; j++)
{
if ((check & 0x0001) != 0)
{
check >>= 1;
check ^= 0xA001;
}
else
{
check >>= 1;
}
}
}
if (mode == BigOrLittle.LittleEndian)
return BitConverter.GetBytes(check);
else
return BitConverter.GetBytes(ReverseBytes(check));
}
/// <summary>
/// CRC16-MODBUS CRC
/// </summary>
/// <param name="data">要校验的数据数组</param>
/// <param name="mode">大小端模式</param>
/// <returns>校验是数据数组+校验值</returns>
public static byte[] DataCrc16Full_Modbus(byte[] data, BigOrLittle mode)
{
byte[] check = DataCrc16_Modbus(data, mode);
List<byte> newdata = new List<byte>();
newdata.AddRange(data);
newdata.AddRange(check);
return newdata.ToArray();
}
#endregion
#region LRC校验
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SerialPortDemon
{
public enum ParityMethod
{
XOR异或,
SUM8累加,
SUM16大端,
SUM16小端,
CRC16大端,
CRC16小端,
ModbusCRC大端,
ModbusCRC小端,
}
}