using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Threading; using TouchSocket.Sockets; 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(); //} /// /// 打开串口 /// /// 串口号 /// 波特率 /// 校验位None = 0,Odd = 1, Even = 2,Mark = 3,Space = 4, /// 数据位 /// 停止位 public void OpenSerialPort(string serialPort, int baudRate, int parity, int dataBits, int stopBits) { if (string.IsNullOrEmpty(serialPort)) { throw new ArgumentException("串口号不能为空"); } _serialPort = new SerialPort(serialPort, baudRate, (System.IO.Ports.Parity)parity, dataBits, (StopBits)stopBits); _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("心跳指令不进行逻辑处理"); //.Send(item.Id, "heartbeat"); _serialPort.WriteLine("heartbeat"); } } catch (Exception ex) { RefreshLogMessageEvent?.Invoke($"接收数据异常:{ex.Message}"); } } /// /// 判断是否为业务数据 /// /// /// private bool CheckReceivedData(byte[] data) { if (data.Length > 4) { return true; } return false; } /// /// 获取系统内的串口 /// /// public void GetSerialPorts(out List serialPorts) { serialPorts = SerialPort.GetPortNames().ToList(); } } }