using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace NSSerialPortCommunication
{
public class SerialPortParameter
{
private string portName;
private int baudRate;
private Parity parity;
private int dataBits;
private StopBits stopBits;
public String PortName { get; set; }
public int BaudRate { get; set; }
public Parity Parity { get; set; }
public int DataBits { get; set; }
public StopBits StopBits { get; set; }
}
public class ClsSerialPortCommunication
{
//private static ClsSerialPortCommunication instance;
//private static object lockObject = new object();
private SerialPort serialPort;
private Queue<string> messages;
//public ClsSerialPortCommunication GetInstance()//不能用单例,可能会有多设备用
//{
// lock(lockObject)
// {
// if (instance == null)
// {
// instance = new ClsSerialPortCommunication();
// }
// return instance;
// }
//}
//private ClsSerialPortCommunication() { }
public void Connect(SerialPortParameter parameter)
{
try
{
if (serialPort?.IsOpen == true)
{
serialPort?.Close();
Console.WriteLine($"[{serialPort.PortName}] closed");
}
serialPort = new SerialPort(parameter.PortName, parameter.BaudRate, parameter.Parity, parameter.DataBits, parameter.StopBits);
Console.WriteLine($"[{parameter.PortName}] opening,parameter:\n" +
$" BaudRate:{parameter.BaudRate}\n" +
$" Parity:{parameter.Parity}\n" +
$" DataBits:{parameter.DataBits}\n" +
$" StopBits:{parameter.StopBits}");
serialPort.Open();
serialPort.DataReceived += Receive;
Console.WriteLine($"[{serialPort.PortName}] opened");
}
catch (Exception ex)
{
Console.WriteLine($"Error,message:{ex.Message}");
}
}
public void Send(string message)
{
try
{
if (serialPort?.IsOpen == true)
{
serialPort.Write(message);
Console.WriteLine($"Send [{message}] to [{serialPort.PortName}]");
}
else
{
throw new Exception($"[{serialPort.PortName}] is not open");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error,message:{ex.Message}");
}
}
public void Receive(object sender, SerialDataReceivedEventArgs e)
{
SerialPort serialPort=(SerialPort)sender;
string message;
message=serialPort.ReadLine();
messages.Enqueue(message);
Console.WriteLine($"[{serialPort.PortName}] Receive message:[{message}]");
}
}
}