using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.IO.Ports; using System.Windows.Forms; namespace ns_Comm { public class ClsSerialPort { #region normal serialPort public static Dictionary dictSerialPort = new Dictionary(); public static int iSerialPortNo = 0; public static string[] arrStrPortList; public ClsSerialPort() { for(int i = 0;i < PortNameList().Length;i++) { CreatSerialPort(arrStrPortList[i], "9600", "8", "NONE", "1"); } } public static string[] PortNameList()//获取当前计算机串口名称数组 { string[] arrStrPortList = SerialPort.GetPortNames();//获取当前计算机串口名称数组 if (arrStrPortList.Length < 1) { MessageBox.Show("本机没有串口!", "Error"); return null; } else { return arrStrPortList; } } public static bool CreatSerialPort(string portName, string baudRate, string dataBit, string parity, string stopBit) { try { SerialPort serialPort = new SerialPort(); serialPort.PortName = portName; serialPort.BaudRate = Convert.ToInt32(baudRate); serialPort.DataBits = Convert.ToInt32(dataBit); switch (parity) { case "NONE": serialPort.Parity = Parity.None; break; case "ODD": serialPort.Parity = Parity.Odd; break; case "EVEN": serialPort.Parity = Parity.Even; break; case "Space": serialPort.Parity = Parity.Space; break; case "Mark": serialPort.Parity = Parity.Mark; break; } switch (stopBit) { case "1": serialPort.StopBits = StopBits.One; break; case "1.5": serialPort.StopBits = StopBits.OnePointFive; break; case "2": serialPort.StopBits = StopBits.Two; break; } //if (!listSerialPort.Contains(serialPort)) //{ // listSerialPort.Add(serialPort); //} //serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceived); if(dictSerialPort.ContainsKey(portName)) { if (serialPort.IsOpen) return true; dictSerialPort.Remove(portName); Thread.Sleep(100); } dictSerialPort.Add(portName, serialPort); return true; } catch (Exception exx) { MessageBox.Show(exx.ToString()); return false; } } private static void DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; if (dictSerialPort.ContainsValue(sp)) { } } public static void SerialOpen(SerialPort sp) { if (!sp.IsOpen) { try { sp.Open(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } else { MessageBox.Show("当前串口已打开\r\nThe serial port is currently open"); } } /// /// 创建并打开指定串口 /// /// /// /// /// /// /// public SerialPort CreatSerialPort1(string portName, string baudRate, string dataBit, string parity, string stopBit) { SerialPort serialPort = new SerialPort(); try { serialPort.PortName = portName; serialPort.BaudRate = Convert.ToInt32(baudRate); serialPort.DataBits = Convert.ToInt32(dataBit); switch (parity) { case "NONE": serialPort.Parity = System.IO.Ports.Parity.None; break; case "ODD": serialPort.Parity = System.IO.Ports.Parity.Odd; break; case "EVEN": serialPort.Parity = System.IO.Ports.Parity.Even; break; } switch (stopBit) { case "1": serialPort.StopBits = System.IO.Ports.StopBits.One; break; case "1.5": serialPort.StopBits = System.IO.Ports.StopBits.OnePointFive; break; case "2": serialPort.StopBits = System.IO.Ports.StopBits.Two; break; } if (!serialPort.IsOpen) { try { serialPort.Open(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } return serialPort; } catch (Exception exx) { MessageBox.Show(exx.ToString()); return null; } } public static void SerialPortSendData(SerialPort sp, string strData) { try { if (!sp.IsOpen) { MessageBox.Show("当前串口未打开\r\nThe serial port is not open"); return; } byte[] sendBuffer; sendBuffer = Encoding.ASCII.GetBytes(strData + "\r\n");//将字符串中的所有字符编码为一个字节序列 //(txtSend.Text+"\r\n").ToCharArray();//将字符复制到Unicode字符数组,将字符串转换为字符数组 sp.DiscardOutBuffer();//清除缓冲区里的内容 sp.DiscardInBuffer(); sp.Write(sendBuffer, 0, sendBuffer.Length);//发送数据 } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } public static void SerialPortSendData(SerialPort sp, byte[] byteArrayData) //Modbus发送 { try { if (!sp.IsOpen) { MessageBox.Show("当前串口未打开\r\nThe serial port is not open"); return; } sp.DiscardOutBuffer();//清除缓冲区里的内容 sp.DiscardInBuffer(); sp.Write(byteArrayData, 0, byteArrayData.Length);//发送数据 } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } public static object lockRecv = new object(); public static string SerialPortReceiveData(SerialPort sp) { lock (lockRecv) { byte[] readBuffer; int length = 0; string strReceive; if (!sp.IsOpen) { MessageBox.Show("请打开串口", "Error"); return "error"; } try { int i = 0; do { i++; Thread.Sleep(10); if (i > 500) break; } while (sp.BytesToRead < 5 );//等待读到所有数据设定读取时间 length = sp.BytesToRead;//获取接收缓冲区中数据的字节数 if (length <= 0) return string.Empty; readBuffer = new byte[length];//创建字节数组 sp.Read(readBuffer, 0, length); strReceive = Encoding.ASCII.GetString(readBuffer, 0, readBuffer.Length); if (i >= 500) { // MessageBox.Show($"读取串口{sp.PortName}超时--2秒!"); } i = 0; return strReceive; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return "error"; } } } /// /// 发送数据并接收数据 /// /// /// /// public string SerialSendAndReceive(SerialPort sp, string sendCommand) { try { byte[] sendBuffer; byte[] readBuffer; int length = 0; sendBuffer = Encoding.ASCII.GetBytes(sendCommand + "\r\n");//将字符串中的所有字符编码为一个字节序列 //(txtSend.Text+"\r\n").ToCharArray();//将字符复制到Unicode字符数组,将字符串转换为字符数组 sp.DiscardOutBuffer();//清除缓冲区里的内容 sp.Write(sendBuffer, 0, sendBuffer.Length);//发送数据 int i = 0; do { i++; Thread.Sleep(50); } while (sp.BytesToRead < 10 && i < 200);//等待读到所有数据设定读取时间 string strReceive; length = sp.BytesToRead;//获取接收缓冲区中数据的字节数 readBuffer = new byte[length]; sp.Read(readBuffer, 0, length); strReceive = Encoding.ASCII.GetString(readBuffer, 0, readBuffer.Length); i = 0; return strReceive; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return ex.ToString(); } } public static void SerialClose(SerialPort sp) { try { sp.Close(); } catch { } } #endregion } }