You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
3.2 KiB
C#

using System;
using System.IO.Ports;
using System.Linq;
using System.Threading;
namespace SlnMesnac.RfidUpload.Business
{
/// <summary>
/// 串口通讯类
/// </summary>
public class SerialPortBusiness
{
#region 单例实现
private static readonly Lazy<SerialPortBusiness> _lazy = new Lazy<SerialPortBusiness>(() => new SerialPortBusiness());
public static SerialPortBusiness Instance
{
get
{
return _lazy.Value;
}
}
#endregion
#region 委托事件
/// <summary>
/// 刷新标签解析
/// </summary>
public delegate void ReceivedData(byte[] buffer);
public event ReceivedData ReceivedDataEvent;
/// <summary>
/// 刷新日志内容
/// </summary>
public delegate void RefreshLogMessage(string message);
public event RefreshLogMessage RefreshLogMessageEvent;
#endregion
private SerialPort _serialPort;
private SerialPortBusiness()
{
}
/// <summary>
/// 打开串口
/// </summary>
public void Open()
{
string port = System.IO.Ports.SerialPort.GetPortNames().FirstOrDefault();
_serialPort = new SerialPort(port, 115200, Parity.None, 8, StopBits.One);
_serialPort.DataReceived += SerialPortDataReceived;
_serialPort.Open();
}
/// <summary>
/// 关闭串口
/// </summary>
public void Close()
{
if (_serialPort != null)
{
_serialPort.Close();
}
else
{
throw new ArgumentException("_serialPort == null");
}
}
/// <summary>
/// 接收数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(200);
int bytesToRead = _serialPort.BytesToRead;
byte[] buffer = new byte[bytesToRead];
_serialPort.Read(buffer, 0, bytesToRead);
RefreshLogMessageEvent?.Invoke("Received data: " + BitConverter.ToString(buffer).Replace("-", " "));
if (CheckReceivedData(buffer))
{
ReceivedDataEvent?.Invoke(buffer);
}
else
{
RefreshLogMessageEvent?.Invoke("心跳指令不进行逻辑处理");
}
}
catch (Exception ex)
{
RefreshLogMessageEvent?.Invoke($"接收数据异常:{ex.Message}");
}
}
/// <summary>
/// 判断是否为业务数据
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private bool CheckReceivedData(byte[] data)
{
if (data.Length > 4)
{
return true;
}
return false;
}
}
}