奇怪的行为SerialPort.DataReceived

时间:2018-01-15 17:31:57

标签: c# multithreading serial-port

我无法弄清楚我的SerialPort.DataReceived事件处理程序正在做什么......当我的控制器没有发送数据时,它会被触发,只是在非常特殊的情况下。

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // Invoke all code in another method to enable GUI updates from subthread
    if (this.InvokeRequired)
    {
        this.Invoke((MethodInvoker)(() => OnDataReceived(sender, e)));
    }
    else
    {
        OnDataReceived(sender, e);
    }
}

private void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // COPY DATA FROM SERIAL BUFFER AND DISPLAY
    SerialPort spL = (SerialPort)sender;
    byte[] buf = new byte[spL.BytesToRead];
    Console.WriteLine("DATA RECEIVED!");
    spL.Read(buf, 0, buf.Length);
    foreach (Byte b in buf)
    {
        Console.Write(b.ToString() + " ");
    }
    Console.WriteLine();
    //Console.WriteLine(BitConverter.ToString(buf, 0, buf.Length)); // hexString
    switch (buf[0])
    {
        case GEN:
            if (next_op == rdGEN) // if General data requested, decode it
            {
                DecodeGEN(buf);
            }
            break;
        case BAS:
            if (next_op == rdSingle || next_op == rdAll) // if BAS or All data requested, decode BAS (and continue if All)
            {
                DecodeBAS(buf);
            }
            else if (next_op == wrSingle || next_op == wrAll) // if BAS or All data written, decode BAS response (and continue if All)
            {
                DecodeBASerr(buf);
            }
            break;
        case PAS:
            if (next_op == rdSingle || next_op == rdAll) // if PAS or All data requested, decode PAS (and continue if All)
            {
                DecodePAS(buf);
            }
            else if (next_op == wrSingle || next_op == wrAll);  // if PAS or All data written, decode PAS response (and continue if All)
            {
                DecodePASerr(buf);
            }
            break;
        case THR:
            if (next_op == rdSingle || next_op == rdAll) // if THR or All data requested, decode THR (and discard further data)
            {
                DecodeTHR(buf);
            }
            else if (next_op == wrSingle || next_op == wrAll) // if THR or All data written, decode THR response (and discard further data)
            {
                DecodeTHRerr(buf);
            }
            break;
    }
}

基本上我得到了一个从我的控制器发送的字节序列,然后我解码它们来更新GUI控件。这是一个例子:

82 24 41 18 0 15 26 35 50 60 70 80 90 100 0 80 85 90 100 100 100 100 100 100 54 1 43 
DATA RECEIVED!

奇怪的是,在唯一且非常特殊的情况下,我的字节数组包含数字" 26"作为[6]元素,serialPort1_DataReceived被称为额外时间,基本上我的程序在switch buf [0]指令处崩溃,因为缓冲区为空https://i.imgur.com/5iZd0lj.png。奇怪的是DataReceived事件甚至不会被触发而没有传递数据!我尝试了我的程序的所有可接受的值,从0到100,并且只有" 26"触发这种奇怪的行为,对我来说毫无意义......

0 个答案:

没有答案