560 lines
16 KiB
C#
560 lines
16 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using Community;
|
||
using System.IO.Ports;
|
||
using System.Text.RegularExpressions;
|
||
using System.Threading;
|
||
|
||
namespace Model
|
||
{
|
||
/// <summary>
|
||
/// 串口对象
|
||
/// </summary>
|
||
public class SerialComModel : NotificationObject
|
||
{
|
||
/// <summary>
|
||
/// 消息状态委托
|
||
/// </summary>
|
||
public delegate void delegateReceivePower(string str);
|
||
/// <summary>
|
||
/// 消息传递时间
|
||
/// </summary>
|
||
public event delegateReceivePower ReceiveCallback;
|
||
|
||
|
||
public int ID { get; set; }
|
||
/// <summary>
|
||
/// 软件ID
|
||
/// </summary>
|
||
public int SoftID { get; set; }
|
||
|
||
#region 串口作用名称
|
||
private string actionName;
|
||
/// <summary>
|
||
/// 串口作用名称
|
||
/// </summary>
|
||
public string ActionName
|
||
{
|
||
get { return actionName; }
|
||
set
|
||
{
|
||
actionName = value;
|
||
this.RaisePropertyChanged("ActionName");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 串口号
|
||
private string portName;
|
||
/// <summary>
|
||
/// 串口号
|
||
/// </summary>
|
||
public string PortName
|
||
{
|
||
get { return portName; }
|
||
set
|
||
{
|
||
portName = value;
|
||
this.RaisePropertyChanged("PortName");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 波特率
|
||
private int baudRate;
|
||
/// <summary>
|
||
/// 波特率
|
||
/// </summary>
|
||
public int BaudRate
|
||
{
|
||
get { return baudRate; }
|
||
set
|
||
{
|
||
baudRate = value;
|
||
this.RaisePropertyChanged("BaudRate");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 校验位
|
||
private int parityNumber;
|
||
/// <summary>
|
||
/// 校验位
|
||
/// </summary>
|
||
public int ParityNumber
|
||
{
|
||
get { return parityNumber; }
|
||
set
|
||
{
|
||
parityNumber = value;
|
||
this.RaisePropertyChanged("ParityNumber");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 数据位
|
||
private int dataBits;
|
||
/// <summary>
|
||
/// 数据位
|
||
/// </summary>
|
||
public int DataBits
|
||
{
|
||
get { return dataBits; }
|
||
set
|
||
{
|
||
dataBits = value;
|
||
this.RaisePropertyChanged("DataBits");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 停止位
|
||
private int stopBitsNumber;
|
||
/// <summary>
|
||
/// 停止位
|
||
/// </summary>
|
||
public int StopBitsNumber
|
||
{
|
||
get { return stopBitsNumber; }
|
||
set
|
||
{
|
||
stopBitsNumber = value;
|
||
this.RaisePropertyChanged("StopBitsNumber");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 串口对象
|
||
/// <summary>
|
||
/// 串口对象
|
||
/// </summary>
|
||
public SerialPort ComPort { get; set; }
|
||
#endregion
|
||
|
||
#region 串口开关
|
||
private bool serialComSwitch;
|
||
/// <summary>
|
||
/// 串口开关
|
||
/// </summary>
|
||
public bool SerialComSwitch
|
||
{
|
||
get { return serialComSwitch; }
|
||
set
|
||
{
|
||
serialComSwitch = value;
|
||
|
||
if (value)
|
||
{
|
||
OpenSerialCom();
|
||
}
|
||
else
|
||
{
|
||
CloseSerialCom();
|
||
}
|
||
|
||
this.RaisePropertyChanged("SerialComSwitch");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 接收到的字符串
|
||
|
||
private string receiveStr;
|
||
/// <summary>
|
||
/// 接收到的字符串
|
||
/// </summary>
|
||
public string ReceiveStr
|
||
{
|
||
get { return receiveStr; }
|
||
set
|
||
{
|
||
receiveStr = value;
|
||
|
||
this.RaisePropertyChanged("ReceiveStr");
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 要发送的字符串
|
||
private string sendStr;
|
||
/// <summary>
|
||
/// 要发送的字符串
|
||
/// </summary>
|
||
public string SendStr
|
||
{
|
||
get { return sendStr; }
|
||
set
|
||
{
|
||
sendStr = value;
|
||
this.RaisePropertyChanged("SendStr");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 错误信息
|
||
private string errorMag;
|
||
/// <summary>
|
||
/// 错误信息
|
||
/// </summary>
|
||
public string ErrorMag
|
||
{
|
||
get { return errorMag; }
|
||
set
|
||
{
|
||
errorMag = value;
|
||
this.RaisePropertyChanged("ErrorMag");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 连接状态
|
||
private ShowInfo connState;
|
||
/// <summary>
|
||
/// 连接状态
|
||
/// </summary>
|
||
public ShowInfo ConnState
|
||
{
|
||
get { return connState; }
|
||
set
|
||
{
|
||
connState = value;
|
||
RaisePropertyChanged("ConnState");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
|
||
#region 构造函数
|
||
/// <summary>
|
||
/// 构造函数
|
||
/// </summary>
|
||
public SerialComModel()
|
||
{
|
||
ReceiveStr = "没有接收到任何信息";
|
||
SendStr = "请输入要发送的内容";
|
||
|
||
ConnState = new ShowInfo() { StatuInfo="等待连接",StatusBackground=ColorStr.Gray};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 构造函数
|
||
/// </summary>
|
||
/// <param name="protName"></param>
|
||
/// <param name="BaudRate"></param>
|
||
/// <param name="p"></param>
|
||
/// <param name="DataBits"></param>
|
||
/// <param name="sp"></param>
|
||
public SerialComModel(string protName, int BaudRate, Parity p, int DataBits, StopBits sp)
|
||
{
|
||
try
|
||
{
|
||
ComPort = new SerialPort();
|
||
ComPort.PortName = protName; //ComPortList[0];//设置要打开的串口
|
||
ComPort.BaudRate = BaudRate;//设置当前波特率
|
||
ComPort.Parity = p;//设置当前校验位
|
||
ComPort.DataBits = DataBits;//设置当前数据位
|
||
ComPort.StopBits = sp;//设置当前停止位
|
||
ComPort.Open();//打开串口
|
||
ComPort.DataReceived += ComPort_DataReceived;
|
||
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 接收数据回调函数
|
||
/// <summary>
|
||
/// 接收数据回调函数
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
|
||
{
|
||
try
|
||
{
|
||
byte[] recBuffer = new byte[ComPort.BytesToRead];//接收数据缓存大小
|
||
ComPort.Read(recBuffer, 0, recBuffer.Length);//读取数据
|
||
ReceiveStr = ByteArrayToHexString(recBuffer); //System.Text.Encoding.Default.GetString(recBuffer);//转码
|
||
|
||
//ReceiveStr = ComPort.ReadTo("\r\n");
|
||
|
||
if (!string.IsNullOrEmpty(ReceiveStr))
|
||
{
|
||
ReceiveCallback(ReceiveStr);
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 打开串口
|
||
/// <summary>
|
||
/// 打开串口
|
||
/// </summary>
|
||
/// <param name="ComNumber">串口号</param>
|
||
public bool OpenSerialCom()
|
||
{
|
||
try
|
||
{
|
||
//如果串口已打开
|
||
if (ComPort != null && ComPort.IsOpen)
|
||
{
|
||
return true;
|
||
}
|
||
|
||
ComPort = new SerialPort();
|
||
ComPort.PortName = PortName; //ComPortList[0];//设置要打开的串口
|
||
ComPort.BaudRate = BaudRate;//设置当前波特率
|
||
ComPort.Parity = (Parity)ParityNumber; //Parity.None;//设置当前校验位
|
||
ComPort.DataBits = DataBits;//设置当前数据位
|
||
ComPort.StopBits = (StopBits)StopBitsNumber;//StopBits.One;//设置当前停止位
|
||
ComPort.Open();//打开串口
|
||
ComPort.DataReceived += ComPort_DataReceived;
|
||
ConnState = new ShowInfo() { StatuInfo = "连接正常", StatusBackground = ColorStr.Green };
|
||
return true;
|
||
}
|
||
catch (Exception)
|
||
{
|
||
ErrorMag = "无法打开串口,请检测此串口是否有效或被其他占用!";
|
||
ConnState = new ShowInfo() { StatuInfo = "无法打开串口,请检测此串口是否有效或被其他占用!", StatusBackground = ColorStr.Red };
|
||
return false;
|
||
}
|
||
|
||
}
|
||
#endregion
|
||
|
||
#region 关闭串口
|
||
/// <summary>
|
||
/// 关闭串口
|
||
/// </summary>
|
||
public void CloseSerialCom()
|
||
{
|
||
if (ComPort != null && ComPort.IsOpen)
|
||
{
|
||
ComPort.Close();
|
||
ConnState = new ShowInfo() { StatuInfo = "等待连接", StatusBackground = ColorStr.Gray };
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region ASCII码发送
|
||
private bool ascSend;
|
||
/// <summary>
|
||
/// ASCII码发送
|
||
/// </summary>
|
||
public bool AscSend
|
||
{
|
||
get { return ascSend; }
|
||
set
|
||
{
|
||
ascSend = value;
|
||
this.RaisePropertyChanged("AscSend");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region HEX发送(16进制)
|
||
private bool hexSend;
|
||
/// <summary>
|
||
/// HEX发送(16进制)
|
||
/// </summary>
|
||
public bool HexSend
|
||
{
|
||
get { return hexSend; }
|
||
set
|
||
{
|
||
hexSend = value;
|
||
this.RaisePropertyChanged("HexSend");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 发送
|
||
/// <summary>
|
||
/// 发送
|
||
/// </summary>
|
||
/// <param name="SendStr">发送内容</param>
|
||
public void Send(string SendStr)
|
||
{
|
||
try
|
||
{
|
||
ReceiveStr = "";
|
||
this.SendStr = SendStr;
|
||
if (!string.IsNullOrEmpty(SendStr))
|
||
{
|
||
if (ComPort != null && ComPort.IsOpen)
|
||
{
|
||
if (AscSend)
|
||
{
|
||
byte[] sendBuffer = System.Text.Encoding.ASCII.GetBytes(Regex.Unescape(SendStr));//转码
|
||
ComPort.Write(sendBuffer, 0, sendBuffer.Length);
|
||
}
|
||
else if (HexSend)
|
||
{
|
||
byte[] sendBuffer = HexToBytes(SendStr);//StringToBytes(Regex.Unescape(SendStr));//转码
|
||
ComPort.Write(sendBuffer, 0, sendBuffer.Length);
|
||
}
|
||
else
|
||
{
|
||
byte[] sendBuffer = System.Text.Encoding.Default.GetBytes(Regex.Unescape(SendStr));//转码
|
||
ComPort.Write(sendBuffer, 0, sendBuffer.Length);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
ErrorMag = ex.Message;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 发送
|
||
/// </summary>
|
||
public void Send()
|
||
{
|
||
|
||
|
||
//byte[] cmd2 = HexToBytes("A0 04 00 E0");
|
||
|
||
try
|
||
{
|
||
//byte[] cmd = HexToBytes("E2 BF 0B E4 A0 01 63 03 FD BA E3");
|
||
if (!string.IsNullOrEmpty(SendStr))
|
||
{
|
||
if (ComPort != null && ComPort.IsOpen)
|
||
{
|
||
if (AscSend)
|
||
{
|
||
byte[] sendBuffer = System.Text.Encoding.ASCII.GetBytes(Regex.Unescape(SendStr));//转码
|
||
ComPort.Write(sendBuffer, 0, sendBuffer.Length);
|
||
}
|
||
else if (HexSend)
|
||
{
|
||
//ComPort.Write(cmd, 0, cmd.Length);
|
||
//Thread.Sleep(1000);
|
||
//ComPort.Write(cmd2, 0, cmd2.Length);
|
||
byte[] sendBuffer = StringToBytes(Regex.Unescape(SendStr));//转码
|
||
ComPort.Write(sendBuffer, 0, sendBuffer.Length);
|
||
}
|
||
else
|
||
{
|
||
byte[] sendBuffer = System.Text.Encoding.Default.GetBytes(Regex.Unescape(SendStr));//转码
|
||
ComPort.Write(sendBuffer, 0, sendBuffer.Length);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
ErrorMag = ex.Message;
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 字符串转16进制
|
||
/// <summary>
|
||
/// 字符串转16进制
|
||
/// </summary>
|
||
/// <param name="str"></param>
|
||
/// <returns></returns>
|
||
private byte[] StringToBytes(string str)
|
||
{
|
||
try //尝试将发送的数据转为16进制Hex
|
||
{
|
||
str = StringToHex(str);
|
||
return HexToBytes(str);
|
||
}
|
||
catch //无法转为16进制时,出现异常
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// string转Hex
|
||
/// </summary>
|
||
/// <param name="s"></param>
|
||
/// <returns></returns>
|
||
public static string StringToHex(string s)
|
||
{
|
||
s = Regex.Unescape(s); //删除转义符
|
||
|
||
//byte[] bytes = System.Text.Encoding.Default.GetBytes(s);
|
||
|
||
//string str = "";
|
||
|
||
//for (int i = 0; i < bytes.Length; i++)
|
||
//{
|
||
// string a = string.Format("{0:X}", bytes[i]);
|
||
// a = a.Length > 1 ? a : "0" + a;
|
||
// str += a + " ";
|
||
|
||
//}
|
||
string str = string.Join(" ", s.Select(c => ((int)c).ToString("X2")));
|
||
return str;
|
||
}
|
||
|
||
/// <summary>
|
||
/// hex转string
|
||
/// </summary>
|
||
/// <param name="hex"></param>
|
||
/// <returns></returns>
|
||
private string HexToString(string hex)
|
||
{
|
||
string[] strArr = hex.Trim().Split(' ');
|
||
byte[] b = new byte[strArr.Length];
|
||
//逐个字符变为16进制字节数据
|
||
for (int i = 0; i < strArr.Length; i++)
|
||
{
|
||
b[i] = Convert.ToByte(strArr[i], 16);
|
||
}
|
||
//按照指定编码将字节数组变为字符串
|
||
return System.Text.Encoding.Default.GetString(b);
|
||
}
|
||
|
||
/// <summary>
|
||
/// hex转byte[]
|
||
/// </summary>
|
||
/// <param name="hs"></param>
|
||
/// <returns></returns>
|
||
public static byte[] HexToBytes(string hs)
|
||
{
|
||
string[] strArr = hs.Trim().Split(' ');
|
||
byte[] b = new byte[strArr.Length];
|
||
//逐个字符变为16进制字节数据
|
||
for (int i = 0; i < strArr.Length; i++)
|
||
{
|
||
b[i] = Convert.ToByte(strArr[i], 16);
|
||
}
|
||
//按照指定编码将字节数组变为字符串
|
||
return b;
|
||
|
||
}
|
||
|
||
#endregion
|
||
|
||
|
||
public string ByteArrayToHexString(byte[] data)
|
||
{
|
||
StringBuilder sb = new StringBuilder(data.Length * 3);
|
||
foreach (byte b in data)
|
||
{
|
||
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
|
||
}
|
||
return sb.ToString().ToUpper();
|
||
}
|
||
}
|
||
}
|