public 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) { Console.WriteLine("WinSerialStream: CreateFile"); handle = CreateFile(port_name != null && !port_name.StartsWith(@"\\.\") ? @"\\.\" + port_name : port_name, GenericRead | GenericWrite, 0, 0, OpenExisting, FileFlagOverlapped, 0); if (handle == -1) { ReportIOError(port_name); } Console.WriteLine("WinSerialStream: SetAttributes"); // Set port low level attributes SetAttributes(baud_rate, parity, data_bits, sb, hs); Console.WriteLine("WinSerialStream: PurgeComm"); // Clean buffers and set sizes if (!PurgeComm(handle, PurgeRxClear | PurgeTxClear) || !SetupComm(handle, read_buffer_size, write_buffer_size)) { ReportIOError(null); } Console.WriteLine("WinSerialStream: SetCommTimeouts"); // 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); #pragma warning disable 618 wo.EventHandle = write_event.Handle; write_overlapped = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeOverlapped))); Marshal.StructureToPtr(wo, write_overlapped, true); NativeOverlapped ro = new NativeOverlapped(); read_event = new ManualResetEvent(false); ro.EventHandle = read_event.Handle; read_overlapped = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeOverlapped))); Marshal.StructureToPtr(ro, read_overlapped, true); #pragma warning restore 618 }
static extern bool SetCommTimeouts(int handle, Timeouts timeouts);