using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ips.Cfq.SetFreqBySerialPort.Cli { public class SerialPortDevice : IDisposable { SerialPort _sPort = null; /// /// 串口号 /// String _endpoint; /// /// 串口输出 /// public String _outString; public SerialPortDevice(String endpoint) { _endpoint = endpoint; } /// /// 打开串口 /// /// public bool Open() { if (_sPort != null && _sPort.IsOpen) return true; bool result = false; if (string.IsNullOrEmpty(this._endpoint)) { result = false; } else { try { if (this._sPort == null) { this._sPort = new SerialPort(); } else { if (this._sPort.IsOpen) { result = true; return result; } } this._sPort.DataReceived += _sPort_DataReceived; this._sPort.PortName = _endpoint; this._sPort.BaudRate = 9600; this._sPort.DataBits = 8; this._sPort.StopBits = StopBits.One; this._sPort.Open(); result = true; } catch { result = false; } } return result; } /// /// 串口数据接收 /// /// /// private void _sPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { string res = string.Empty; try { res = this._sPort.ReadLine(); } catch { } if (!string.IsNullOrEmpty(res)) { this._outString = res.Replace("\0", ""); } } /// /// 发送命令 /// /// public bool SendCommand(String command, ref String errmsg) { Console.WriteLine($"in:{command}"); bool result = false; if (this._sPort == null) { errmsg = "串口未初始化"; result = false; } else { if (!this._sPort.IsOpen) { errmsg = "串口未打开"; result = false; } else { try { _outString = String.Empty; _sPort.Write(command); result = true; } catch (Exception ex) { errmsg = $"串口通讯异常:{ex.Message}"; result = false; } } } return result; } /// /// 获取串口输出 /// /// public String GetOutString() { int num = 0; string result; while (string.IsNullOrEmpty(_outString)) { num++; System.Threading.Thread.Sleep(100); if (num >= 50) { result = ""; return result; } } result = _outString; Console.WriteLine($"out:{result}"); return result; } public void Dispose() { if (_sPort != null) { _sPort.Close(); _sPort.Dispose(); _sPort = null; } } } }