using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace RichCreator.Utility.InputControl { /// /// 串口连接类 /// public class SerialPortConnect:IDisposable { private SerialPort serialPort; public Action DataReceiveCallback; private string comName; //private ManualResetEvent manualLock; public SerialPortConnect(string comName) { this.comName = comName; //this.dataReceiveCallback = dataReceiveCallback; //manualLock = new ManualResetEvent(false); } // Methods public Boolean Connect() { try { if (this.serialPort != null) { if (this.serialPort.IsOpen) { return true; } } else { this.serialPort = new SerialPort(); } this.serialPort.WriteTimeout = 1000; this.serialPort.PortName = comName; this.serialPort.BaudRate = 115200; this.serialPort.Parity = Parity.None; this.serialPort.StopBits = StopBits.One; this.serialPort.Open(); this.serialPort.DataReceived += new SerialDataReceivedEventHandler(this.SerialPortDataReceived); return true; } catch (Exception) { return false; } } /// /// 关闭连接 /// /// public Boolean Disconnect() { if (this.serialPort == null) { return false; } if (this.serialPort.IsOpen) { this.serialPort.Close(); } return true; } /// /// 串口状态 /// public bool SerialPortStatus { get { if (this.serialPort == null) { return false; } if (this.serialPort.IsOpen) { return true; } return false; } } /// /// 发送数据 /// /// /// /// public Boolean Send(byte[] buf, int len) { if (this.serialPort == null) { //throw new Exception("串口不存在"); return false; } if (!this.serialPort.IsOpen) { //throw new Exception("串口没打开"); return false; } try { this.serialPort.Write(buf, 0, len); return true; } catch (Exception) { return false; } } /// /// 接收数据 /// /// /// private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e) { if (this.serialPort.IsOpen) { try { if (this.serialPort.BytesToRead <= 0) { return; } byte[] buffer = new byte[this.serialPort.BytesToRead]; int num = this.serialPort.Read(buffer, 0, buffer.Length); if (this.DataReceiveCallback != null) { this.DataReceiveCallback(buffer); } } catch { } } } private bool isFinialize = false; public void Dispose() { Close(); } public void Close() { if (!isFinialize) { if (serialPort != null) { if (serialPort.IsOpen) { serialPort.Close(); } serialPort = null; } //释放锁 //this.manualLock.Close(); GC.SuppressFinalize(this); } } } }