using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace JJMediSys { public class ComTool { SerialPort serialPort; /// /// 打开串口 /// /// 串口号 /// 波特率 /// 数据位 /// 停止位 /// /// 校验位 /// public bool OpenCom(string protName, int baudRate, int dataBit, float stopBits, int parity) { bool flag = true; if (serialPort == null) { serialPort = new SerialPort(); } serialPort.PortName = protName;//串口号 serialPort.BaudRate = baudRate;//波特率 float f = stopBits;//停止位 if (f == 0) { serialPort.StopBits = StopBits.None; } else if (f == 1.5) { serialPort.StopBits = StopBits.OnePointFive; } else if (f == 1) { serialPort.StopBits = StopBits.One; } else { serialPort.StopBits = StopBits.Two; } serialPort.DataBits = dataBit;//数据位 if (parity == 0) { serialPort.Parity = Parity.None; } else if (parity == 1) { serialPort.Parity = Parity.Odd; } else if (parity == 2) { serialPort.Parity = Parity.Even; } else { serialPort.Parity = Parity.None; } // sp.ReadTimeout = 1000;//设置超时读取时间 // sp.WriteTimeout = 1000;//超时写入时间 try { if (!serialPort.IsOpen) { serialPort.Open(); } } catch (Exception ex) { string msg = ex.Message; flag = false; } return flag; } /// /// 关闭端口 /// /// public bool CloseCom() { try { if (serialPort.IsOpen) { serialPort.Close(); } return true; } catch { return false; } } public bool isOpen() { return serialPort.IsOpen; } public byte[] SendAndRecv(byte[] sendData, int timeout = 5000) { //打开连接 if (!serialPort.IsOpen) serialPort.Open(); serialPort.DiscardInBuffer(); //发送数据 serialPort.Write(sendData, 0, sendData.Length); //读取返回数据 DateTime dt = DateTime.Now; while (serialPort.BytesToRead < 2) { Thread.Sleep(50); if (DateTime.Now.Subtract(dt).TotalMilliseconds > timeout) { throw new Exception("主版无响应"); } } List recList = new List(); byte[] recData = new byte[serialPort.BytesToRead]; byte[] Heard = new byte[2]; serialPort.Read(Heard, 0, 2); recList.AddRange(Heard); int length = Heard[1] + 3; //报文数据总长度 while (recList.Count < length) { if (serialPort.BytesToRead > 0) { int ToRead = 0; if (serialPort.BytesToRead > (length - recList.Count)) { ToRead = length - recList.Count; } else { ToRead = serialPort.BytesToRead; } recData = new byte[ToRead]; serialPort.Read(recData, 0, ToRead); recList.AddRange(recData); } Thread.Sleep(1); } return recList.ToArray(); } } }