c#串行端口数据接收处理程序

本文关键字:处理 程序 串行端口 数据 | 更新日期: 2023-09-27 18:12:12

当SerialPort接收到数据时,我需要知道自定义参数。当我制作SerialPort时,我知道自定义参数。同时有几个打开的端口。我需要知道哪个端口调用DataRecived和他的自定义参数。

串行端口的数量是动态的(存储在一个阵列中—下面未显示(。

自定义参数应该是一个对象,但也可以是一个字符串。每个串行端口都有一个自定义参数。2个端口=2个自定义参数。

private void Start()
{
    SerialPort _serialport1 = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
    _serialport1.Type = "Analyzer 1"; // custom parameter ?
    _serialport1.DataReceived += new SerialDataReceivedEventHandle (SerialPort_DataReceived, "Analyzer 1");
    _serialport1.Open();
    SerialPort _serialport2 = new SerialPort("COM2", 19200, Parity.None, 8, StopBits.One);
    _serialport2.Type = "Analyzer 2"; // custom parameter ?
    _serialport2.DataReceived += new SerialDataReceivedEventHandle (SerialPort_DataReceived, "Analyzer 2");
    _serialport2.Open();
}
private void SerialPort_DataReceived(object sender, object e)
{
    string _type = (string)e;
    if(_type == "Analyzer 1")
    {
        // Do something
    }
    if(_type == "Analyzer 2")
    {
        // Do something
    }
}

我应该创建一个自定义处理程序吗?还是带有自定义参数的SerialPort的自定义类?

c#串行端口数据接收处理程序

我使用的最后一个代码:

public class SerialPortA : SerialPort
{
   public string DeviceType { get; set; }
   public SerialPortA(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, string deviceType)
       : this()
   {
       //...
   }
   //...
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{ 
    if ((sender as SerialPortA).DeviceType == "Analyzer 1")
    {
        //...
    }
}

您不能控制传递给事件处理程序的内容,因为事件是由SerialPort对象本身引发的。第二个参数将始终SerialDataReceivedEventArgs的实例,您不能更改它。

但是,您可以始终检查sender参数以查看哪个SerialPort对象引发了事件:

private SerialPort _serialport1;
private SerialPort _serialport2;
private void Start()
{
    _serialport1 = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
    _serialport1.DataReceived += new SerialDataReceivedEventHandle (SerialPort_DataReceived, "User Object 1");
    _serialport1.Open();
    _serialport2 = new SerialPort("COM2", 19200, Parity.None, 8, StopBits.One);
    _serialport2.DataReceived += new SerialDataReceivedEventHandle (SerialPort_DataReceived, "User Object 2");
    _serialport2.Open();
}
private void SerialPort_DataReceived(object sender, object e)
{
    string s = null;
    if (sender == _serialPort1)
    {
        s = "User Object 1";
    }
    else if (sender == _serialPort2)
    {
        s = "User Object 1";
    }
    ...
}

附带说明:局部变量名不应该以下划线开头;该约定通常是为字段(即成员变量(保留的。只需对局部变量使用camelCase