using System; using System.Collections.Generic; using System.Data; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SerialCommApp.SeriallLibs { public class PSerialComm { private readonly string CRLF = "\r\n"; private SerialPort _serialPort; private string _stringBuffer; private object _receiveLock = new object(); public event EventHandler OnDataReceived; public PMessageHistory History { get; set; } public PSerialCommSetting SerialCommSetting { get; set; } public bool IsOpen { get { return _serialPort.IsOpen; } } public string PortName { get { return _serialPort.PortName; } set { _serialPort.PortName = value; } } public PSerialComm() { InitInstance(); } public PSerialComm(string port) { InitInstance(); this.PortName = port; } private void InitInstance() { if (_serialPort != null) _serialPort.Close(); _serialPort = new SerialPort(); _serialPort.DataReceived += SerialPort_DataReceived; SerialCommSetting = new PSerialCommSetting(); this.History = new PMessageHistory(10); } private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort serialPort = sender as SerialPort; if (serialPort == null) return; string data = serialPort.ReadExisting(); if (data.Length < 1) return; HandleData(data); } public static string[] GetPortNames() { return SerialPort.GetPortNames(); } public void Write(string message) { _serialPort.Write(message); } private void HandleData(string data) { _stringBuffer = string.Concat(_stringBuffer, data); if (this.OnDataReceived == null) return; while (true) { int subStringIdx = _stringBuffer.IndexOf(CRLF); if (subStringIdx < 0) break; string message = _stringBuffer.Substring(0, subStringIdx); History.Add(message); if (this.OnDataReceived != null) this.OnDataReceived(this, message); _stringBuffer = _stringBuffer.Remove(0, subStringIdx + CRLF.Length); } } public void Open() { if (string.IsNullOrEmpty(this.PortName)) throw new Exception("Port name is cannot be empty."); if (!_serialPort.IsOpen) _serialPort.Open(); } public void Close() { if (string.IsNullOrEmpty(this.PortName)) throw new Exception("Port name is cannot be empty."); if (_serialPort.IsOpen) _serialPort.Close(); } } }