2 // System.IO.Ports.WinSerialStream.cs
5 // Carlos Alberto Cortez (calberto.cortez@gmail.com)
7 // (c) Copyright 2006 Novell, Inc. (http://www.novell.com)
13 using System.Runtime.InteropServices;
14 using System.Threading;
15 using System.ComponentModel;
17 namespace System.IO.Ports
19 class WinSerialStream : Stream, ISerialStream, IDisposable
21 // Windows API Constants
22 const uint GenericRead = 0x80000000;
23 const uint GenericWrite = 0x40000000;
24 const uint OpenExisting = 3;
25 const uint FileFlagOverlapped = 0x40000000;
26 const uint PurgeRxClear = 0x0008;
27 const uint PurgeTxClear = 0x0004;
28 const uint WinInfiniteTimeout = 0xFFFFFFFF;
29 const uint FileIOPending = 997;
32 const uint SetRts = 3;
33 const uint ClearRts = 4;
34 const uint SetDtr = 5;
35 const uint ClearDtr = 6;
36 const uint SetBreak = 8;
37 const uint ClearBreak = 9;
38 const uint CtsOn = 0x0010;
39 const uint DsrOn = 0x0020;
40 const uint RsldOn = 0x0080;
43 const uint EvRxChar = 0x0001;
44 const uint EvCts = 0x0008;
45 const uint EvDsr = 0x0010;
46 const uint EvRlsd = 0x0020;
47 const uint EvBreak = 0x0040;
48 const uint EvErr = 0x0080;
49 const uint EvRing = 0x0100;
55 IntPtr write_overlapped;
56 IntPtr read_overlapped;
57 ManualResetEvent read_event;
58 ManualResetEvent write_event;
61 [DllImport("kernel32", SetLastError = true)]
62 static extern int CreateFile(string port_name, uint desired_access,
63 uint share_mode, uint security_attrs, uint creation, uint flags,
66 [DllImport("kernel32", SetLastError = true)]
67 static extern bool SetupComm(int handle, int read_buffer_size, int write_buffer_size);
69 [DllImport("kernel32", SetLastError = true)]
70 static extern bool PurgeComm(int handle, uint flags);
72 [DllImport("kernel32", SetLastError = true)]
73 static extern bool SetCommTimeouts(int handle, Timeouts timeouts);
75 public WinSerialStream (string port_name, int baud_rate, int data_bits, Parity parity, StopBits sb,
76 bool dtr_enable, bool rts_enable, Handshake hs, int read_timeout, int write_timeout,
77 int read_buffer_size, int write_buffer_size)
79 handle = CreateFile (port_name != null && !port_name.StartsWith(@"\\.\")
80 ? @"\\.\" + port_name : port_name,
81 GenericRead | GenericWrite, 0, 0, OpenExisting,
82 FileFlagOverlapped, 0);
85 ReportIOError (port_name);
87 // Set port low level attributes
88 SetAttributes (baud_rate, parity, data_bits, sb, hs);
90 // Clean buffers and set sizes
91 if (!PurgeComm (handle, PurgeRxClear | PurgeTxClear) ||
92 !SetupComm (handle, read_buffer_size, write_buffer_size))
96 this.read_timeout = read_timeout;
97 this.write_timeout = write_timeout;
98 timeouts = new Timeouts (read_timeout, write_timeout);
99 if (!SetCommTimeouts(handle, timeouts))
100 ReportIOError (null);
103 SetSignal(SerialSignal.Dtr, dtr_enable);
105 if (hs != Handshake.RequestToSend &&
106 hs != Handshake.RequestToSendXOnXOff)
107 SetSignal(SerialSignal.Rts, rts_enable);
109 // Init overlapped structures
110 NativeOverlapped wo = new NativeOverlapped ();
111 write_event = new ManualResetEvent (false);
112 #pragma warning disable 618
113 wo.EventHandle = write_event.Handle;
114 write_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped)));
115 Marshal.StructureToPtr (wo, write_overlapped, true);
117 NativeOverlapped ro = new NativeOverlapped ();
118 read_event = new ManualResetEvent (false);
119 ro.EventHandle = read_event.Handle;
120 read_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped)));
121 Marshal.StructureToPtr (ro, read_overlapped, true);
122 #pragma warning restore 618
125 public override bool CanRead {
131 public override bool CanSeek {
137 public override bool CanTimeout {
143 public override bool CanWrite {
149 public override int ReadTimeout {
154 if (value < 0 && value != SerialPort.InfiniteTimeout)
155 throw new ArgumentOutOfRangeException ("value");
157 timeouts.SetValues (value, write_timeout);
158 if (!SetCommTimeouts (handle, timeouts))
159 ReportIOError (null);
161 read_timeout = value;
165 public override int WriteTimeout {
167 return write_timeout;
171 if (value < 0 && value != SerialPort.InfiniteTimeout)
172 throw new ArgumentOutOfRangeException ("value");
174 timeouts.SetValues (read_timeout, value);
175 if (!SetCommTimeouts (handle, timeouts))
176 ReportIOError (null);
178 write_timeout = value;
182 public override long Length {
184 throw new NotSupportedException ();
188 public override long Position {
190 throw new NotSupportedException ();
193 throw new NotSupportedException ();
197 [DllImport("kernel32", SetLastError = true)]
198 static extern bool CloseHandle (int handle);
200 protected override void Dispose (bool disposing)
206 CloseHandle (handle);
207 Marshal.FreeHGlobal (write_overlapped);
208 Marshal.FreeHGlobal (read_overlapped);
211 void IDisposable.Dispose ()
214 GC.SuppressFinalize (this);
217 public override void Close ()
219 ((IDisposable)this).Dispose ();
227 public override void Flush ()
233 public override long Seek (long offset, SeekOrigin origin)
235 throw new NotSupportedException();
238 public override void SetLength (long value)
240 throw new NotSupportedException();
243 [DllImport("kernel32", SetLastError = true)]
244 static extern unsafe bool ReadFile (int handle, byte* buffer, int bytes_to_read,
245 out int bytes_read, IntPtr overlapped);
247 [DllImport("kernel32", SetLastError = true)]
248 static extern unsafe bool GetOverlappedResult (int handle, IntPtr overlapped,
249 ref int bytes_transfered, bool wait);
251 public override int Read ([In, Out] byte [] buffer, int offset, int count)
255 throw new ArgumentNullException ("buffer");
256 if (offset < 0 || count < 0)
257 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
259 if (buffer.Length - offset < count )
260 throw new ArgumentException ("offset+count",
261 "The size of the buffer is less than offset + count.");
266 fixed (byte* ptr = buffer) {
267 if (ReadFile (handle, ptr + offset, count, out bytes_read, read_overlapped))
270 // Test for overlapped behavior
271 if (Marshal.GetLastWin32Error () != FileIOPending)
272 ReportIOError (null);
274 if (!GetOverlappedResult (handle, read_overlapped, ref bytes_read, true))
275 ReportIOError (null);
281 throw new TimeoutException (); // We didn't get any byte
286 [DllImport("kernel32", SetLastError = true)]
287 static extern unsafe bool WriteFile (int handle, byte* buffer, int bytes_to_write,
288 out int bytes_written, IntPtr overlapped);
290 public override void Write (byte [] buffer, int offset, int count)
294 throw new ArgumentNullException ("buffer");
296 if (offset < 0 || count < 0)
297 throw new ArgumentOutOfRangeException ();
299 if (buffer.Length - offset < count)
300 throw new ArgumentException ("offset+count",
301 "The size of the buffer is less than offset + count.");
303 int bytes_written = 0;
306 fixed (byte* ptr = buffer) {
307 if (WriteFile (handle, ptr + offset, count, out bytes_written, write_overlapped))
309 if (Marshal.GetLastWin32Error() != FileIOPending)
310 ReportIOError (null);
312 if (!GetOverlappedResult(handle, write_overlapped, ref bytes_written, true))
313 ReportIOError (null);
317 // If the operation timed out, then
318 // we transfered less bytes than the requested ones
319 if (bytes_written < count)
320 throw new TimeoutException ();
323 [DllImport("kernel32", SetLastError = true)]
324 static extern bool GetCommState (int handle, [Out] DCB dcb);
326 [DllImport ("kernel32", SetLastError=true)]
327 static extern bool SetCommState (int handle, DCB dcb);
329 public void SetAttributes (int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs)
331 DCB dcb = new DCB ();
332 if (!GetCommState (handle, dcb))
333 ReportIOError (null);
335 dcb.SetValues (baud_rate, parity, data_bits, bits, hs);
336 if (!SetCommState (handle, dcb))
337 ReportIOError (null);
340 void ReportIOError(string optional_arg)
342 int error = Marshal.GetLastWin32Error ();
347 message = "The port `" + optional_arg + "' does not exist.";
350 message = "Parameter is incorrect.";
353 // As fallback, we show the win32 error
354 message = new Win32Exception ().Message;
358 throw new IOException (message);
361 void CheckDisposed ()
364 throw new ObjectDisposedException (GetType ().FullName);
367 // ISerialStream members
368 public void DiscardInBuffer ()
370 if (!PurgeComm (handle, PurgeRxClear))
371 ReportIOError (null);
374 public void DiscardOutBuffer ()
376 if (!PurgeComm (handle, PurgeTxClear))
377 ReportIOError (null);
380 [DllImport ("kernel32", SetLastError=true)]
381 static extern bool ClearCommError (int handle, out uint errors, out CommStat stat);
383 public int BytesToRead {
387 if (!ClearCommError (handle, out errors, out stat))
388 ReportIOError (null);
390 return (int)stat.BytesIn;
394 public int BytesToWrite {
398 if (!ClearCommError (handle, out errors, out stat))
399 ReportIOError (null);
401 return (int)stat.BytesOut;
405 [DllImport ("kernel32", SetLastError=true)]
406 static extern bool GetCommModemStatus (int handle, out uint flags);
408 public SerialSignal GetSignals ()
411 if (!GetCommModemStatus (handle, out flags))
412 ReportIOError (null);
414 SerialSignal signals = SerialSignal.None;
415 if ((flags & RsldOn) != 0)
416 signals |= SerialSignal.Cd;
417 if ((flags & CtsOn) != 0)
418 signals |= SerialSignal.Cts;
419 if ((flags & DsrOn) != 0)
420 signals |= SerialSignal.Dsr;
425 [DllImport ("kernel32", SetLastError=true)]
426 static extern bool EscapeCommFunction (int handle, uint flags);
428 public void SetSignal (SerialSignal signal, bool value)
430 if (signal != SerialSignal.Rts && signal != SerialSignal.Dtr)
431 throw new Exception ("Wrong internal value");
434 if (signal == SerialSignal.Rts)
445 if (!EscapeCommFunction (handle, flag))
446 ReportIOError (null);
449 public void SetBreakState (bool value)
451 if (!EscapeCommFunction (handle, value ? SetBreak : ClearBreak))
452 ReportIOError (null);
457 [StructLayout (LayoutKind.Sequential)]
460 public int dcb_length;
461 public int baud_rate;
463 public short w_reserved;
464 public short xon_lim;
465 public short xoff_lim;
466 public byte byte_size;
468 public byte stop_bits;
469 public byte xon_char;
470 public byte xoff_char;
471 public byte error_char;
472 public byte eof_char;
473 public byte evt_char;
474 public short w_reserved1;
477 //const int fBinary = 0x0001;
478 //const int fParity = 0x0002;
479 const int fOutxCtsFlow = 0x0004;
480 //const int fOutxDsrFlow1 = 0x0008;
481 //const int fOutxDsrFlow2 = 0x0010;
482 //const int fDtrControl = 0x00020;
483 //const int fDsrSensitivity = 0x0040;
484 //const int fTXContinueOnXoff = 0x0080;
485 const int fOutX = 0x0100;
486 const int fInX = 0x0200;
487 //const int fErrorChar = 0x0400;
488 //const int fNull = 0x0800;
489 //const int fRtsControl1 = 0x1000;
490 const int fRtsControl2 = 0x2000;
491 //const int fAbortOnError = 0x4000;
493 public void SetValues (int baud_rate, Parity parity, int byte_size, StopBits sb, Handshake hs)
499 case StopBits.OnePointFive:
505 default: // Shouldn't happen
509 this.baud_rate = baud_rate;
510 this.parity = (byte)parity;
511 this.byte_size = (byte)byte_size;
513 // Clear Handshake flags
514 flags &= ~(fOutxCtsFlow | fOutX | fInX | fRtsControl2);
516 // Set Handshake flags
521 case Handshake.XOnXOff:
522 flags |= fOutX | fInX;
524 case Handshake.RequestToSend:
525 flags |= fOutxCtsFlow | fRtsControl2;
527 case Handshake.RequestToSendXOnXOff:
528 flags |= fOutxCtsFlow | fOutX | fInX | fRtsControl2;
530 default: // Shouldn't happen
536 [StructLayout (LayoutKind.Sequential)]
539 public uint ReadIntervalTimeout;
540 public uint ReadTotalTimeoutMultiplier;
541 public uint ReadTotalTimeoutConstant;
542 public uint WriteTotalTimeoutMultiplier;
543 public uint WriteTotalTimeoutConstant;
545 public const uint MaxDWord = 0xFFFFFFFF;
547 public Timeouts (int read_timeout, int write_timeout)
549 SetValues (read_timeout, write_timeout);
552 public void SetValues (int read_timeout, int write_timeout)
554 // FIXME: The windows api docs are not very clear about read timeouts,
555 // and we have to simulate infinite with a big value (uint.MaxValue - 1)
556 ReadIntervalTimeout = MaxDWord;
557 ReadTotalTimeoutMultiplier = MaxDWord;
558 ReadTotalTimeoutConstant = (read_timeout == -1 ? MaxDWord - 1 : (uint) read_timeout);
560 WriteTotalTimeoutMultiplier = 0;
561 WriteTotalTimeoutConstant = (write_timeout == -1 ? MaxDWord : (uint) write_timeout);
566 [StructLayout (LayoutKind.Sequential)]
571 public uint BytesOut;