public static class SerialPortUtils
{
public static List<SerialPort> serialPorts = new List<SerialPort>();
public static string[] GetPortNames()
{
return SerialPort.GetPortNames();
}
public static SerialPort OpenpPort(string comName, int baudRate)
{
SerialPort serialPort = new SerialPort();
try
{
serialPort.PortName = comName;
serialPort.BaudRate = baudRate;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
serialPort.Parity = Parity.None;
serialPort.DataReceived += ReceiveData;
serialPort.Open();
string msg = "串口" + comName + "打开成功!";
serialPorts.Add(serialPort);
Log.Write(msg, msg, Color.Green);
return serialPort;
}
catch (Exception ex)
{
string errorMsg = "打开串口" + comName + "失败," + (ex.InnerException == null ? ex.Message : ex.InnerException.Message);
Log.Write(errorMsg, errorMsg, Color.Red);
return null;
}
}
public static void OpenAllSerialPort()
{
string[] coms = GetPortNames();
foreach (var com in coms)
{
if (int.Parse(com.Replace("COM", "")) >= 10)
serialPorts.Add(OpenpPort(com, 9600));
}
}
public static void SendData(string data)
{
foreach (var serialPort in serialPorts)
{
try
{
byte[] bytes = System.Text.Encoding.Default.GetBytes(data);
serialPort.Write(bytes, 0, data.Length);
string msg = "串口" + serialPort.PortName + "数据" + data + "发送成功!";
Log.Write(msg, msg, Color.Red);
}
catch (Exception ex)
{
string errorMsg = "串口" + serialPort.PortName + "数据发送失败," + (ex.InnerException == null ? ex.Message : ex.InnerException.Message);
Log.Write(errorMsg, errorMsg, Color.Red);
}
}
}
public static void SendBytesData(byte[] bytes)
{
foreach (var serialPort in serialPorts)
{
try
{
serialPort.Write(bytes, 0, bytes.Count());
}
catch (Exception ex)
{
string errorMsg = "串口" + serialPort.PortName + "数据发送失败," + (ex.InnerException == null ? ex.Message : ex.InnerException.Message);
Log.Write(errorMsg, errorMsg, Color.Red);
}
}
}
public static void SendBytesDataByComo(SerialPort serialPort, byte[] bytes,string data)
{
try
{
serialPort.Write(bytes, 0, bytes.Count());
string msg = "串口" + serialPort.PortName + "数据" + data + "发送成功!";
Log.Write(msg, msg, Color.Red);
}
catch (Exception ex)
{
string errorMsg = "串口" + serialPort.PortName + "数据发送失败," + (ex.InnerException == null ? ex.Message : ex.InnerException.Message);
Log.Write(errorMsg, errorMsg, Color.Red);
}
}
public static void ReceiveData(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort _SerialPort = (SerialPort)sender;
int _bytesToRead = _SerialPort.BytesToRead;
byte[] recvData = new byte[_bytesToRead];
_SerialPort.Read(recvData, 0, _bytesToRead);
string result = System.Text.Encoding.Default.GetString(recvData);
string msg = "串口" + _SerialPort.PortName + "接收数据成功:" + result;
Log.Write(msg, msg, Color.Green);
}
catch (Exception ex)
{
string errorMsg = "串口数据读取失败," + (ex.InnerException == null ? ex.Message : ex.InnerException.Message);
}
}
}
|