681 lines
20 KiB
C#
681 lines
20 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.Collections.ObjectModel;
|
||
using System.Windows;
|
||
|
||
namespace Model
|
||
{
|
||
/// <summary>
|
||
/// 串口对象
|
||
/// </summary>
|
||
public class SerialComModel : NotificationObject
|
||
{
|
||
/// <summary>
|
||
/// 接受消息的委托
|
||
/// </summary>
|
||
/// <param name="hv"></param>
|
||
public delegate void delegeateReceive(string str);
|
||
/// <summary>
|
||
/// 接受消息的委托事件
|
||
/// </summary>
|
||
public event delegeateReceive 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
|
||
|
||
private string notes;
|
||
/// <summary>
|
||
/// 备注(这里备注了此串口连接的舵机控制板对应的舵机所在载具的序号)
|
||
/// </summary>
|
||
public string Notes
|
||
{
|
||
get { return notes; }
|
||
set
|
||
{
|
||
notes = value;
|
||
}
|
||
}
|
||
|
||
|
||
#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 ShowInfo showmsg;
|
||
/// <summary>
|
||
/// 连接状态
|
||
/// </summary>
|
||
public ShowInfo Showmsg
|
||
{
|
||
get { return showmsg; }
|
||
set
|
||
{
|
||
showmsg = value;
|
||
this.RaisePropertyChanged("Showmsg");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 接收到的字符串
|
||
|
||
private string receiveStr;
|
||
/// <summary>
|
||
/// 接收到的字符串
|
||
/// </summary>
|
||
public string ReceiveStr
|
||
{
|
||
get { return receiveStr; }
|
||
set
|
||
{
|
||
receiveStr = value;
|
||
if(!string.IsNullOrEmpty(value)&& ReceiveCallback!=null)
|
||
{
|
||
ReceiveCallback(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 构造函数
|
||
/// <summary>
|
||
/// 构造函数
|
||
/// </summary>
|
||
public SerialComModel()
|
||
{
|
||
ReceiveStr = "没有接收到任何信息";
|
||
SendStr = "请输入要发送的内容";
|
||
Showmsg = new ShowInfo();
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
Showmsg.StatuInfo = "等待连接";
|
||
|
||
|
||
//COM.COM.ReceivedBytesThreshold = 1;
|
||
//COM.COM.DataReceived += COM_DataReceived;
|
||
|
||
|
||
}
|
||
|
||
/// <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)
|
||
{
|
||
SerialPort acom = sender as SerialPort;
|
||
//byte[] recBuffer = new byte[acom.BytesToRead];//接收数据缓存大小
|
||
//ComPort.Read(recBuffer, 0, recBuffer.Length);//读取数据
|
||
////ReceiveStr = System.Text.Encoding.Default.GetString(recBuffer);//转码
|
||
//ReceiveStr = System.Text.Encoding.Default.GetString(recBuffer);//转码
|
||
//ReceiveStr += acom.ReadExisting();
|
||
|
||
|
||
//ReceiveStr = ComPort.ReadTo("\r\n");
|
||
//ReceiveCallback(ReceiveStr);
|
||
|
||
|
||
|
||
byte[] recBuffer = new byte[acom.BytesToRead];//接收数据缓存大小
|
||
acom.Read(recBuffer, 0, recBuffer.Length);//读取数据
|
||
string rStr = Int16Tostr(recBuffer);
|
||
|
||
if (!string.IsNullOrEmpty(rStr))
|
||
{
|
||
string s = rStr.Replace(" ", ""); //去除所有空格
|
||
ReceiveStr = Regex.Replace(s, @"(\w{4})", "$1 ").Trim(' '); //字符串每隔4位加一个空格
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
}
|
||
#endregion
|
||
|
||
#region 打开串口
|
||
/// <summary>
|
||
/// 打开串口
|
||
/// </summary>
|
||
/// <param name="ComNumber">串口号</param>
|
||
public bool OpenSerialCom()
|
||
{
|
||
ErrorMag = "";
|
||
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.Handshake = Handshake.None;
|
||
ComPort.Open();//打开串口
|
||
ComPort.DataReceived += ComPort_DataReceived;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
Showmsg.StatuInfo = "连接正常";
|
||
return true;
|
||
}
|
||
catch (Exception)
|
||
{
|
||
ErrorMag = "无法打开串口,请检测此串口是否有效或被其他占用!";
|
||
|
||
Showmsg.StatusForeground = ColorStr.Red;
|
||
Showmsg.StatuInfo = "连接失败";
|
||
|
||
return false;
|
||
}
|
||
|
||
}
|
||
#endregion
|
||
|
||
#region 关闭串口
|
||
/// <summary>
|
||
/// 关闭串口
|
||
/// </summary>
|
||
public void CloseSerialCom()
|
||
{
|
||
if (ComPort != null && ComPort.IsOpen)
|
||
{
|
||
ComPort.Close();
|
||
}
|
||
}
|
||
#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
|
||
{
|
||
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 = StringToBytes(Regex.Unescape(SendStr));//转码
|
||
byte[] sendBuffer = StrToInt16(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;
|
||
Showmsg.StatusForeground = ColorStr.Red;
|
||
Showmsg.StatuInfo = "连接异常";
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 发送
|
||
/// </summary>
|
||
public void Send()
|
||
{
|
||
try
|
||
{
|
||
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 = StrToInt16(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>
|
||
/// <param name="sends"></param>
|
||
public void Send(byte[] sends)
|
||
{
|
||
try
|
||
{
|
||
if (sends != null && sends.Count() > 0)
|
||
{
|
||
if (ComPort != null && ComPort.IsOpen)
|
||
{
|
||
ComPort.Write(sends, 0, sends.Length);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
ErrorMag = ex.Message;
|
||
Showmsg.StatusForeground = ColorStr.Red;
|
||
Showmsg.StatuInfo = "连接异常";
|
||
}
|
||
}
|
||
#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
|
||
|
||
|
||
/// <summary>
|
||
/// HEX转16进制
|
||
/// </summary>
|
||
/// <param name="str"></param>
|
||
/// <returns></returns>
|
||
public static byte[] StrToInt16(string str)
|
||
{
|
||
try //尝试将发送的数据转为16进制Hex
|
||
{
|
||
//str = str.Replace(" ", "");//去除16进制数据中所有空格
|
||
//str = str.Replace("\r", "");//去除16进制数据中所有换行
|
||
//str = str.Replace("\n", "");//去除16进制数据中所有换行
|
||
//if (str.Length == 1)//数据长度为1的时候,在数据前补0
|
||
//{
|
||
// str = "0" + str;
|
||
//}
|
||
//else if (str.Length % 2 != 0)//数据长度为奇数位时,去除最后一位数据
|
||
//{
|
||
// str = str.Remove(str.Length - 1, 1);
|
||
//}
|
||
|
||
//string stre = System.Text.RegularExpressions.Regex.Replace(str, @"(\w{2})", "$1 ").Trim(' '); //字符串每隔2位加一个空格
|
||
|
||
//List<string> sendData16 = stre.Split(' ').ToList();
|
||
|
||
//byte[] sendBuffer = new byte[sendData16.Count];//sendBuffer的长度设置为:发送的数据2合1后的字节数
|
||
//for (int i = 0; i < sendData16.Count; i++)
|
||
//{
|
||
// sendBuffer[i] = (byte)(Convert.ToInt32(sendData16[i], 16));//发送数据改为16进制
|
||
//}
|
||
|
||
|
||
MatchCollection matches = Regex.Matches(str, @"[0-9A-Fa-f]{2}");
|
||
byte[] sendBuffer = new byte[matches.Count];
|
||
|
||
for (int i = 0; i < sendBuffer.Length; i++)
|
||
{
|
||
sendBuffer[i] = byte.Parse(matches[i].Value, System.Globalization.NumberStyles.AllowHexSpecifier);
|
||
}
|
||
|
||
return sendBuffer;
|
||
}
|
||
catch //无法转为16进制时,出现异常
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 16进制转字符串
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public static string Int16Tostr(byte[] datainfo)
|
||
{
|
||
if (datainfo.Length > 0)
|
||
{
|
||
StringBuilder recBuffer16 = new StringBuilder();//定义16进制接收缓存
|
||
for (int i = 0; i < datainfo.Length; i++)
|
||
{
|
||
recBuffer16.AppendFormat("{0:X2}" + " ", datainfo[i]);//X2表示十六进制格式(大写),域宽2位,不足的左边填0。
|
||
}
|
||
return recBuffer16.ToString();
|
||
}
|
||
else
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
}
|
||
}
|