Unable to obtain a specified output sequence in RS232 communication

Mar 27 2009 6:52 AM
Hi to everyone.
I wrote a program in C# that implements a RS232 communication but I decided to use not the Framework SerialPort class.
The reason of this choiche is the need to replicate a specified output sequence obtained by a serial port monitor (I use this free serial monitor):

Output to replicate:

0,IRP_MJ_CREATE,DOWN,TRUE,0x0,...,
1,IRP_MJ_CREATE,UP,FALSE,0x0,,,
2,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_HANDFLOW: Set handshake information),DOWN,TRUE,0x0,00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ,................,
3,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_HANDFLOW: Set handshake information),UP,FALSE,0x0,,,
4,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_QUEUE_SIZE: Set queue size),DOWN,TRUE,0x0,00 00 00 00 00 00 00 00 ,........,
5,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_QUEUE_SIZE: Set queue size),UP,FALSE,0x0,,,
6,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_TIMEOUTS: Set timeouts),DOWN,TRUE,0x0,FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ,ÿÿÿÿ................,
7,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_TIMEOUTS: Set timeouts),UP,FALSE,0x0,,,
8,IRP_MJ_DEVICE_CONTROL,DOWN,TRUE,0x0,00 00 00 00 ,....,
9,IRP_MJ_DEVICE_CONTROL,UP,FALSE,0x0,,,
10,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_CLR_RTS: Clear RTS),DOWN,FALSE,0x0,,,
11,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_CLR_RTS: Clear RTS),UP,FALSE,0x0,,,
12,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_DTR: Set DTR),DOWN,FALSE,0x0,,,
13,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_DTR: Set DTR),UP,FALSE,0x0,,,
14,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE: Set baud rate),DOWN,TRUE,0x0,80 25 00 00 ,?%..,
15,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE: Set baud rate),UP,FALSE,0x0,,,
16,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL: Set line control),DOWN,TRUE,0x0,00 00 08 ,...,
17,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL: Set line control),UP,FALSE,0x0,,,
18,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK: Set current event mask),DOWN,TRUE,0x0,0D 00 00 00 ,....,
19,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK: Set current event mask),UP,FALSE,0x0,,,
20,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK: Wait for event),DOWN,FALSE,0x0,,,
21,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE: Set baud rate),DOWN,TRUE,0x0,80 25 00 00 ,?%..,
22,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE: Set baud rate),UP,FALSE,0x0,,,
23,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL: Set line control),DOWN,TRUE,0x0,00 00 08 ,...,
24,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL: Set line control),UP,FALSE,0x0,,,
25,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_RTS: Set RTS),DOWN,FALSE,0x0,,,
26,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_RTS: Set RTS),UP,FALSE,0x0,,,
27,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK: Wait for event),UP,TRUE,0x0,08 00 00 00 ,....,
28,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_MODEMSTATUS: Retrieve modem status),DOWN,FALSE,0x0,,,
29,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_MODEMSTATUS: Retrieve modem status),UP,TRUE,0x0,10 00 00 00 ,....,
30,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_IMMEDIATE_CHAR: Transmit immediate character),DOWN,TRUE,0x0,FF ,ÿ,
31,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK: Wait for event),DOWN,FALSE,0x0,,,
32,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_IMMEDIATE_CHAR: Transmit immediate character),UP,FALSE,0x0,,,
33,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK: Wait for event),UP,TRUE,0x0,01 00 00 00 ,....,

34,IRP_MJ_CLOSE,DOWN,FALSE,0x0,,,
35,IRP_MJ_CLOSE,UP,FALSE,0x0,,,



Output obtained:

0,IRP_MJ_CREATE,DOWN,TRUE,0x0,54 00 65 00 73 00 74 00 41 00 70 00 70 00 43 00 6F 00 6E 00 73 00 6F 00 6C 00 65 00 2E 00 76 00 73 00 68 00 6F 00 73 00 74 00 2E 00 65 00 78 00 65 00 00 00 ,T.e.s.t.A.p.p.C.o.n.s.o.l.e...v.s.h.o.s.t...e.x.e...,
1,IRP_MJ_CREATE,UP,FALSE,0x0,,,
2,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_HANDFLOW: Set handshake information),DOWN,TRUE,0x0,00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ,................,
3,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_HANDFLOW: Set handshake information),UP,FALSE,0x0,,,
4,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_QUEUE_SIZE: Set queue size),DOWN,TRUE,0x0,00 00 00 00 00 00 00 00 ,........,
5,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_QUEUE_SIZE: Set queue size),UP,FALSE,0x0,,,
6,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_TIMEOUTS: Set timeouts),DOWN,TRUE,0x0,FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ,ÿÿÿÿ................,
7,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_TIMEOUTS: Set timeouts),UP,FALSE,0x0,,,
8,IRP_MJ_DEVICE_CONTROL,DOWN,TRUE,0x0,00 00 00 00 ,....,
9,IRP_MJ_DEVICE_CONTROL,UP,FALSE,0x0,,,
10,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_CLR_RTS: Clear RTS),DOWN,FALSE,0x0,,,
11,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_CLR_RTS: Clear RTS),UP,FALSE,0x0,,,
12,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_DTR: Set DTR),DOWN,FALSE,0x0,,,
13,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_DTR: Set DTR),UP,FALSE,0x0,,,
14,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE: Set baud rate),DOWN,TRUE,0x0,80 25 00 00 ,?%..,
15,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE: Set baud rate),UP,FALSE,0x0,,,
16,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL: Set line control),DOWN,TRUE,0x0,00 00 08 ,...,
17,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL: Set line control),UP,FALSE,0x0,,,
18,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK: Set current event mask),DOWN,TRUE,0x0,0D 00 00 00 ,....,
19,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK: Set current event mask),UP,FALSE,0x0,,,
20,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK: Wait for event),DOWN,FALSE,0x0,,,
21,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE: Set baud rate),DOWN,TRUE,0x0,80 25 00 00 ,?%..,
22,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE: Set baud rate),UP,FALSE,0x0,,,
23,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL: Set line control),DOWN,TRUE,0x0,00 00 08 ,...,
24,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL: Set line control),UP,FALSE,0x0,,,
25,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_RTS: Set RTS),DOWN,FALSE,0x0,,,
26,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_RTS: Set RTS),UP,FALSE,0x0,,,
27,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK: Wait for event),UP,TRUE,0x0,08 00 00 00 ,....,
28,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_MODEMSTATUS: Retrieve modem status),DOWN,FALSE,0x0,,,
29,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_MODEMSTATUS: Retrieve modem status),UP,TRUE,0x0,10 00 00 00 ,....,
30,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_IMMEDIATE_CHAR: Transmit immediate character),DOWN,TRUE,0x0,FF ,ÿ,
31,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_IMMEDIATE_CHAR: Transmit immediate character),UP,FALSE,0x0,,,
32,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_IMMEDIATE_CHAR: Transmit immediate character),DOWN,TRUE,0x0,FF ,ÿ,
33,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK: Wait for event),DOWN,FALSE,0x0,,,
34,    IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK: Wait for event),UP,TRUE,0x0,05 00 00 00 ,....,
35,IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_IMMEDIATE_CHAR: Transmit immediate character),UP,FALSE,0x0,,,

36,IRP_MJ_CLOSE,DOWN,FALSE,0x0,,,
37,IRP_MJ_CLOSE,UP,FALSE,0x0,,,


As you can notice, the differences are from the line 30 until the end of the logs.

Here's the code:

Main.cs

#region Using

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

#endregion

namespace TestAppConsole
{
    class Program
    {
        static void Main()
        {
            SerialPort serialPort = new SerialPort();
            serialPort.Connect();
            OverlappedFunction[] functionToOverlap =
                {
                    OverlappedFunction.SetBaudRate,
                    OverlappedFunction.SetLineControl,
                    OverlappedFunction.SetRts
                };
            uint setCommMask = 0x000D;
            byte byteToSend = 0xFF;
            serialPort.OverlapCommMask(functionToOverlap, setCommMask);
            Thread.Sleep(14);
            serialPort.GetModemStatus();
            serialPort.TransmitCharOverlap(byteToSend);
            serialPort.Disconnect();
        }
    }
}


OverlappedFunction.cs

#region Using

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace TestAppConsole
{
    public enum OverlappedFunction
    {
        SetHandFlow = 1,
        SetQueueSize = 2,
        SetTimeOut = 3,
        SetFifoControl = 4,
        ClearRts = 5,
        SetDtr = 6,
        SetBaudRate = 7,
        SetLineControl = 8,
        SetRts = 9,
        GetModemStatus = 10,
    }
}


SerialPort.cs

#region Using

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;

#endregion

namespace TestAppConsole
{
    sealed internal class SerialPort
    {
        #region Class definition

        public SerialPort()
        {
        }

        #endregion

        #region Methods

        public void Connect()
        {
            fileHandle = Win32Methods.CreateFile(PortName,
                Win32Methods.GENERIC_READ | Win32Methods.GENERIC_WRITE,
                0, (IntPtr)0, Win32Methods.OPEN_EXISTING, Win32Methods.FILE_FLAG_OVERLAPPED,
                Win32Methods.NULL);
            if (fileHandle == Win32Methods.INVALID_HANDLE_VALUE)
            {
                throw new Exception("Connection not estabilished!");
            }
            SetHandFlow();
            SetQueueSize();
            SetTimeOut();
            SetFifoControl();
            ClearRts();
            SetDtr();
            SetBaudRate(BaudRate);
            SetLineControl();
        }

        public void Disconnect()
        {
            Win32Methods.CloseHandle(fileHandle);
        }
       
        public void OverlapCommMask(OverlappedFunction[] overlappedFunctions, uint setCommMask)
        {
            bool fWaitingOnStat = false;
            bool cycleActive = true;
            NativeOverlapped osStatus = new NativeOverlapped();
            osStatus.EventHandle = Win32Methods.CreateEvent((IntPtr)null, true, false, null);

            if (osStatus.EventHandle == (IntPtr)null)
            {
                // error creating event; abort
                cycleActive = false;
            }


            for (; cycleActive; )
            {
                // Issue a status event check if one hasn't been issued already.
                if (!fWaitingOnStat)
                {
                    int lpEvtMask = 0;
                    SetCommMask(setCommMask);
                    if (WaitCommEvent(ref lpEvtMask, ref osStatus) == 0)
                    {
                        if (Marshal.GetLastWin32Error() == Win32Methods.ERROR_IO_PENDING)
                        {
                            fWaitingOnStat = true;
                        }
                        else
                        {
                            // error in WaitCommEvent; abort
                            break;
                        }
                    }
                }

                // Check on overlapped operation.
                if (fWaitingOnStat)
                {
                    // Wait a little while for an event to occur.
                    UInt32 waitForSingleObjectResponse =
                        Win32Methods.WaitForSingleObject(osStatus.EventHandle, 14);
                    if (waitForSingleObjectResponse == Win32Methods.WAIT_OBJECT_0)
                    {
                        fWaitingOnStat = false;
                    }
                    else if (waitForSingleObjectResponse == Win32Methods.WAIT_TIMEOUT)
                    {
                        foreach (OverlappedFunction overlappedFunction in overlappedFunctions)
                        {
                            executeOverlappedFunction(overlappedFunction);
                        }
                        break;
                    }
                }
            }
            Win32Methods.CloseHandle((int)osStatus.EventHandle);
        }

        public void TransmitCharOverlap(byte charToSend)
        {
            bool fWaitingOnStat = false;
            bool cycleActive = true;
            NativeOverlapped osStatus = new NativeOverlapped();
            NativeOverlapped osStatus_2 = new NativeOverlapped();
            osStatus.EventHandle = Win32Methods.CreateEvent((IntPtr)null, true, false, null);
           
            if (osStatus.EventHandle == (IntPtr)null)
            {
                // error creating event; abort
                cycleActive = false;
            }
       
            for ( ; cycleActive; )
            {
                // Issue a status event check if one hasn't been issued already.
                if (!fWaitingOnStat)
                {
                    if (TransmitCommCharDeviceIO(charToSend, ref osStatus))
                    {
                        // end of the operation
                        break;
                    }
                    else
                    {
                        if (Marshal.GetLastWin32Error() == Win32Methods.ERROR_IO_PENDING)
                        {
                            fWaitingOnStat = true;
                        }
                        else
                        {
                            // error in TransmitCommCharDeviceIO; abort
                            break;
                        }
                    }
                }
       
                // Check on overlapped operation.
                if (fWaitingOnStat)
                {
                    // Wait a little while for an event to occur.
                    UInt32 waitForSingleObjectResponse = Win32Methods.WaitForSingleObject(osStatus.EventHandle, 0);
                    if (waitForSingleObjectResponse == Win32Methods.WAIT_OBJECT_0)
                    {
                        fWaitingOnStat = false;
                    }
                    else if (waitForSingleObjectResponse == Win32Methods.WAIT_TIMEOUT)
                    {
                        osStatus_2.EventHandle = Win32Methods.CreateEvent((IntPtr)null, true, false, null);
                        int lpEvtMask = 0;
                        WaitCommEvent(ref lpEvtMask, ref osStatus_2);
                        Win32Methods.CloseHandle((int)osStatus_2.EventHandle);
                        break;
                    }
                }
            }
            Win32Methods.CloseHandle((int)osStatus.EventHandle);
            Win32Methods.CloseHandle((int)osStatus_2.EventHandle);
        }

        public bool TransmitCommCharDeviceIO(byte charToSend, ref NativeOverlapped osStatus)
        {
            byte[] buffer = new byte[1];
            buffer[0] = charToSend;
            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 6, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return WriteChar(buffer, controlCode, 0, ref osStatus);
        }

        public bool WriteChar(byte[] buffer, int controlCode, int outputBufferLength,
            ref NativeOverlapped osStatus)
        {
            byte[] outputBuffer = new byte[outputBufferLength];
            int bytesReturned = new int();
            return Win32Methods.DeviceIoControl(fileHandle, controlCode, buffer, buffer.Length,
                outputBuffer, outputBufferLength, ref bytesReturned, ref osStatus);
        }

        public bool SetCommMask(uint eventToMask)
        {
            return Win32Methods.SetCommMask(fileHandle, eventToMask);
        }

        public int WaitCommEvent(ref int lpEvtMask, ref NativeOverlapped osStatus)
        {
            return Win32Methods.WaitCommEvent(fileHandle, ref lpEvtMask, ref osStatus);
        }
       
        public bool SetHandFlow()
        {
            byte[] buffer = new byte[16];
            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 25, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool SetQueueSize()
        {
            byte[] buffer = new byte[8];
            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 2, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool SetTimeOut()
        {
            byte[] buffer = new byte[20];
            for (int i = 0; i < 4; i++)
            {
                buffer[i] = 0xFF;
            }

            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 7, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool SetFifoControl()
        {
            byte[] buffer = new byte[4];
            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 39, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool ClearRts()
        {
            byte[] buffer = new byte[0];
            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 13, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool SetDtr()
        {
            byte[] buffer = new byte[0];
            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 9, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool SetBaudRate(int baudRate)
        {
            byte[] buffer = new byte[4];
            buffer[0] = (byte)(baudRate % 256);
            buffer[1] = (byte)((baudRate / 256) % 256);
            buffer[2] = (byte)((baudRate / 65536) % 256);

            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 1, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool SetLineControl()
        {
            byte[] buffer = new byte[3];
            buffer[0] = 0x00;
            buffer[1] = 0x00;
            buffer[2] = 0x08;

            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 3, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool SetRts()
        {
            byte[] buffer = new byte[0];
            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 12, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 0);
        }

        public bool GetModemStatus()
        {
            byte[] buffer = new byte[0];
            int controlCode = Win32Methods.CTL_CODE(
                Win32Methods.FILE_DEVICE_SERIAL_PORT, 26, Win32Methods.METHOD_BUFFERED,
                Win32Methods.FILE_ANY_ACCESS);
            return Write(buffer, controlCode, 4);
        }
       
        public bool Write(byte[] buffer, int controlCode, int outputBufferLength)
        {
            byte[] outputBuffer = new byte[outputBufferLength];
            int bytesReturned = new int();
            return Win32Methods.DeviceIoControl(fileHandle, controlCode, buffer, buffer.Length,
                outputBuffer, outputBufferLength, ref bytesReturned, 0);
        }
       
        private object executeOverlappedFunction(OverlappedFunction overlappedFunction)
        {
            object result;
            switch (overlappedFunction)
            {
                case OverlappedFunction.SetHandFlow:
                    result = SetHandFlow();
                    break;
                case OverlappedFunction.SetQueueSize:
                    result = SetQueueSize();
                    break;
                case OverlappedFunction.SetTimeOut:
                    result = SetTimeOut();
                    break;
                case OverlappedFunction.SetFifoControl:
                    result = SetFifoControl();
                    break;
                case OverlappedFunction.ClearRts:
                    result = ClearRts();
                    break;
                case OverlappedFunction.SetDtr:
                    result = SetDtr();
                    break;
                case OverlappedFunction.SetBaudRate:
                    result = SetBaudRate(BaudRate);
                    break;
                case OverlappedFunction.SetLineControl:
                    result = SetLineControl();
                    break;
                case OverlappedFunction.SetRts:
                    result = SetRts();
                    break;
                case OverlappedFunction.GetModemStatus:
                default:
                    result = GetModemStatus();
                    break;
            }
            return result;
        }

        #endregion

        #region Properties

        private int fileHandle = Win32Methods.INVALID_HANDLE_VALUE;

        private string _PortName = "COM1";
        public string PortName
        {
            get
            {
                return _PortName;
            }
            set
            {
                _PortName = value;
            }
        }

        private int _BaudRate = 9600;
        public int BaudRate
        {
            get
            {
                return _BaudRate;
            }
            set
            {
                _BaudRate = value;
            }
        }

        #endregion
    }
}


Win32Methods.cs

#region Using

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;

#endregion

namespace TestAppConsole
{
    [System.Security.SuppressUnmanagedCodeSecurityAttribute()]
    internal class Win32Methods
    {
        #region Constant definition

        public const int
            INVALID_HANDLE_VALUE = (-1),
            NULL = 0,
            ERROR_SUCCESS = 0,
            FILE_READ_DATA = (0x0001),
            FILE_SHARE_READ = 0x00000001,
            OPEN_EXISTING = 3,
            GENERIC_READ = unchecked((int)0x80000000),
            GENERIC_WRITE = unchecked((int)0x40000000),
            METHOD_BUFFERED = 0,
            METHOD_NEITHER = 3,
            FILE_ANY_ACCESS = 0,
            FILE_DEVICE_UNKNOWN = 0x00000022,
            FILE_DEVICE_VIRTUAL_DISK = 0x00000024,
            FILE_DEVICE_SERIAL_PORT = 0x0000001B,

            ERROR_IO_PENDING = 997,
            WAIT_ABANDONED = 0x00000080,
            WAIT_OBJECT_0 = 0x00000000,
            WAIT_TIMEOUT = 0x00000102,
            FILE_FLAG_OVERLAPPED = 0x40000000,

            /* IOCTL_SERIAL_(GET_WAIT_MASK, SET_WAIT_MASK, WAIT_ON_MASK) flags */
            SERIAL_EV_RXCHAR = 0x0001,
            SERIAL_EV_RXFLAG = 0x0002,
            SERIAL_EV_TXEMPTY = 0x0004,
            SERIAL_EV_CTS = 0x0008,
            SERIAL_EV_DSR = 0x0010,
            SERIAL_EV_RLSD = 0x0020,
            SERIAL_EV_BREAK = 0x0040,
            SERIAL_EV_ERR = 0x0080,
            SERIAL_EV_RING = 0x0100,
            SERIAL_EV_PERR = 0x0200,
            SERIAL_EV_RX80FULL = 0x0400,
            SERIAL_EV_EVENT1 = 0x0800,
            SERIAL_EV_EVENT2 = 0x1000,

            /* IOCTL_SERIAL_SET_FIFO_CONTROL constants */
            SERIAL_IOC_FCR_FIFO_ENABLE = 0x00000001,
            SERIAL_IOC_FCR_RCVR_RESET = 0x00000002,
            SERIAL_IOC_FCR_XMIT_RESET = 0x00000004,
            SERIAL_IOC_FCR_DMA_MODE = 0x00000008,
            SERIAL_IOC_FCR_RES1 = 0x00000010,
            SERIAL_IOC_FCR_RES2 = 0x00000020,
            SERIAL_IOC_FCR_RCVR_TRIGGER_LSB = 0x00000040,
            SERIAL_IOC_FCR_RCVR_TRIGGER_MSB = 0x00000080;

        #endregion

        #region Structs definition

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SECURITY_ATTRIBUTES
        {
            public int nLength;                 // DWORD
            public IntPtr lpSecurityDescriptor; // LPVOID
            public int bInheritHandle;          // BOOL
        }

        #endregion

        #region Methods

        [DllImport("kernel32.dll")]
        public static unsafe extern bool CloseHandle(int hHandle);

        // CreateFile is is Overloaded for having SecurityAttributes or not

        [DllImport("kernel32.dll")]
        public static unsafe extern int CreateFile(String lpFileName, int dwDesiredAccess,
            int dwShareMode, IntPtr lpSecurityAttributes, int dwCreationDisposition,
            int dwFlagsAndAttributes, int hTemplateFile);

        [DllImport("kernel32.dll")]
        public static unsafe extern int CreateFile(String lpFileName, int dwDesiredAccess,
            int dwShareMode, SECURITY_ATTRIBUTES lpSecurityAttributes,
            int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);

        [DllImport("kernel32.dll")]
        public static unsafe extern bool TransmitCommChar(IntPtr hFile, Byte cChar);

        [DllImport("kernel32.dll")]
        public static unsafe extern bool DeviceIoControl(int hDevice, int dwIoControlCode,
            byte[] InBuffer, int nInBufferSize, byte[] OutBuffer, int nOutBufferSize,
            ref int pBytesReturned, int pOverlapped);

        [DllImport("kernel32.dll")]
        public static unsafe extern bool DeviceIoControl(int hDevice, int dwIoControlCode,
            byte[] InBuffer, int nInBufferSize, byte[] OutBuffer, int nOutBufferSize,
            ref int pBytesReturned, ref NativeOverlapped pOverlapped);

        [DllImport("kernel32.dll")]
        public static unsafe extern bool DeviceIoControl(int hDevice, int dwIoControlCode,
            int[] InBuffer, int nInBufferSize, int[] OutBuffer, int nOutBufferSize,
            ref int pBytesReturned, int pOverlapped);

        [DllImport("kernel32.dll")]
        public static extern bool SetCommMask(int hFile, uint lpEvtMask);

        [DllImport("kernel32.dll")]
        public static extern IntPtr CreateEvent(IntPtr lpEventAttributes,
            bool bManualReset, bool bInitialState, string lpName);

        [DllImport("kernel32", SetLastError = true)]
        public static extern UInt32 WaitForSingleObject(IntPtr handle,
            Int32 milliseconds);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern int WaitCommEvent(int hFile, ref int lpEvtMask,
            ref NativeOverlapped lpOverlapped);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer,
            uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead,
            ref NativeOverlapped lpOverlapped);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool WriteFile(IntPtr hFile, byte[] lpBuffer,
            uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten,
            ref NativeOverlapped lpOverlapped);

        // These replace Macros in winioctl.h

        public static unsafe int CTL_CODE(int DeviceType, int Function, int Method,
            int Access)
        {
            return (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2)
              | (Method));
        }

        public int DEVICE_TYPE_FROM_CTL_CODE(int ctrlCode)
        {
            return (int)((ctrlCode & 0xffff0000) >> 16);
        }

        #endregion
    }
}



Can anyone help me to obtain the output to replicate?
Thanks in advance.