using System; using System.IO.Ports; using System.Linq; using System.Threading; namespace SlnMesnac.RfidUpload.Business { /// /// 串口通讯类 /// public class SerialPortBusiness { #region 单例实现 private static readonly Lazy _lazy = new Lazy(() => new SerialPortBusiness()); public static SerialPortBusiness Instance { get { return _lazy.Value; } } #endregion #region 委托事件 /// /// 刷新标签解析 /// public delegate void ReceivedData(byte[] buffer); public event ReceivedData ReceivedDataEvent; /// /// 刷新日志内容 /// public delegate void RefreshLogMessage(string message); public event RefreshLogMessage RefreshLogMessageEvent; #endregion private SerialPort _serialPort; private SerialPortBusiness() { } /// /// 打开串口 /// 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(); } /// /// 关闭串口 /// public void Close() { if (_serialPort != null) { _serialPort.Close(); } else { throw new ArgumentException("_serialPort == null"); } } /// /// 接收数据 /// /// /// 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}"); } } /// /// 判断是否为业务数据 /// /// /// private bool CheckReceivedData(byte[] data) { if (data.Length > 4) { return true; } return false; } } }