using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Ports; namespace SerialPortControl { class SerialEventArgs { public SerialEventArgs() { } public string Code { get; internal set; } } class SerailPortDevice { enum SerialDataType { HEX, ASCII, UTF8, UNICODE, } private SerialPort m_serialPort = null; private int m_type = (int)SerialDataType.ASCII; public bool openSerialPort(string portName, int baudRate = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One) { try { if (m_serialPort != null) { m_serialPort.Close(); } m_serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits); m_serialPort.Open(); m_serialPort.DataReceived += new SerialDataReceivedEventHandler(onReceiveSerailData); return true; } catch(Exception e) { Console.WriteLine("open error:", e); return false; } } public void closeSerialPort() { if (isOpen) { m_serialPort.Close(); m_serialPort = null; } } public bool isOpen { get { return (m_serialPort != null && m_serialPort.IsOpen); } } public static string[] allSerialPort() { //foreach (string name in SerialPort.GetPortNames()) //{ // Console.WriteLine(name); //} return SerialPort.GetPortNames(); } public bool sendSerailData(string msg) { if (isOpen) { try { m_serialPort.Write(msg); return true; } catch(Exception err) { Console.WriteLine("send err:", err); return false; } } else { return false; } } public int setSerailType { get { return m_type; } set { if (value > 3) { m_type = (int)SerialDataType.ASCII; } else { m_type = value; } } } private void parseSerailData(byte[] data) { string strResult; // 数据转换 if (m_type == (int)SerialDataType.HEX) { StringBuilder strBuild = new StringBuilder(); for (int i = 0; i < data.Length; i++) { strBuild.AppendFormat("{0:x2}" + " ", data[i]); } strResult = strBuild.ToString().ToUpper(); } else if (m_type == (int)SerialDataType.ASCII) { strResult = new ASCIIEncoding().GetString(data); } else if (m_type == (int)SerialDataType.UTF8) { strResult = new UTF8Encoding().GetString(data); } else { strResult = new UnicodeEncoding().GetString(data); } if (this.sigDataReceived != null) { sigDataReceived(this, new SerialEventArgs() { Code = strResult }); } } private void onReceiveSerailData(object sender, SerialDataReceivedEventArgs e) { byte[] ReDatas = new byte[m_serialPort.BytesToRead]; int result = m_serialPort.Read(ReDatas, 0, ReDatas.Length); if (result <= 0) { return; } parseSerailData(ReDatas); m_serialPort.DiscardInBuffer(); } public event EventHandler<SerialEventArgs> sigDataReceived; } }
界面程序接收串口消息:
m_serailPortDevice = new SerailPortDevice(); m_serailPortDevice.sigDataReceived += onHandleSerialEvent; private void onHandleSerialEvent(object sender, SerialEventArgs e) { string code = e.Code; //程序出错,添加以下代码 BeginInvoke(new MethodInvoker(delegate { this.richTextBox.AppendText(code); })); }