Example #1
0
        internal WinSerialStream(string port_name, int baud_rate, int data_bits, Parity parity, StopBits sb,
                                 bool dtr_enable, bool rts_enable, Handshake hs, int read_timeout, int write_timeout,
                                 int read_buffer_size, int write_buffer_size)
        {
            handle = CreateFile(String.Format("\\\\.\\{0}", port_name), GenericRead | GenericWrite, 0, 0, OpenExisting,
                                FileFlagOverlapped, 0);

            if (handle == -1)
            {
                ReportIOError(port_name);
            }

            // Set port low level attributes
            SetAttributes(baud_rate, parity, data_bits, sb, hs);

            // Clean buffers and set sizes
            if (!PurgeComm(handle, PurgeRxClear | PurgeTxClear) ||
                !SetupComm(handle, read_buffer_size, write_buffer_size))
            {
                ReportIOError(null);
            }

            // Set timeouts
            this.read_timeout  = read_timeout;
            this.write_timeout = write_timeout;
            timeouts           = new Timeouts(read_timeout, write_timeout);
            if (!SetCommTimeouts(handle, timeouts))
            {
                ReportIOError(null);
            }

            /// Set DTR and RTS
            SetSignal(SerialSignal.Dtr, dtr_enable);

            if (hs != Handshake.RequestToSend &&
                hs != Handshake.RequestToSendXOnXOff)
            {
                SetSignal(SerialSignal.Rts, rts_enable);
            }

            // Init overlapped structures
            NativeOverlapped wo = new NativeOverlapped();

            write_event = new ManualResetEvent(false);
#if NET_2_0
            wo.EventHandle = write_event.Handle;
#else
            wo.EventHandle = write_event.SafeWaitHandle.DangerousGetHandle();
#endif
            write_overlapped = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeOverlapped)));
            Marshal.StructureToPtr(wo, write_overlapped, true);

            NativeOverlapped ro = new NativeOverlapped();
            read_event = new ManualResetEvent(false);
#if NET_2_0
            ro.EventHandle = read_event.Handle;
#else
            ro.EventHandle = read_event.SafeWaitHandle.DangerousGetHandle();
#endif
            read_overlapped = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeOverlapped)));
            Marshal.StructureToPtr(ro, read_overlapped, true);
        }
Example #2
0
 static extern bool SetCommTimeouts(int handle, Timeouts timeouts);