Search code examples
c#rfidhidcustom-keyboard

C# Serial Port gives unwanted IRP messages


I am trying to send commands to and RFID reader through a serial port (it acts like a keyboard, M302 made by KKMOON).

I have this piece of code in order to send instructions:

SerialPort sp = new SerialPort();
sp.PortName = "COM3";
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.DataBits = 8;
sp.StopBits = StopBits.One;

sp.DataReceived += myRecieved;

sp.Open();
byte[] bytestosend = { 0x03, 0x0a, 0x00, 0x0d };
sp.Write(bytestosend, 0, bytestosend.Length);

bytestosend = new byte[]{ 0x04, 0x05, 0x00, 0x00, 0x09 };
sp.Write(bytestosend, 0, bytestosend.Length);

bytestosend = new byte[] { 0x03, 0x06, 0x00, 0x09 };
sp.Write(bytestosend, 0, bytestosend.Length);

if (beep)
{
    running = false;
    bytestosend = new byte[] { 0x02, 0x13, 0x15 };
    sp.Write(bytestosend, 0, bytestosend.Length);
}

sp.Close();
sp.Dispose();
sp = null;

and I'm getting this output from a serial port listener: The Current Output from the Serial Program

The output that I need to get in order to read the data is The required data


Solution

  • So after Hans Passant's comment I realised that the problem was actually just not reading the serial port correctly!

    In order to read the full extent of the message I built a method that reads the entire buffer:

    private static string readData()
    {
        int reads = sp.BytesToRead;
    
        byte[] bytesRead = new byte[reads];
    
        try
        {
            sp.Read(bytesRead, 0, reads);
    
            return BitConverter.ToString(bytesRead).Trim(' ') != "" ? BitConverter.ToString(bytesRead) : "-1";
        }
        catch
        {
            return "-1";
        }
    }
    

    and then read the entire buffer until the wanted return data is found

    while ((data += readData()) != "02-05-07")
    {
        if (data.Contains("-1"))
        {
            data = "";
        }
        Console.WriteLine(data);
        Console.ReadLine();
    }
    

    This will allow me to read all the data from my RFID reader and I hope this helps anyone else who might have a problem!