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;
19 namespace System.IO.Ports
21 class WinSerialStream : Stream, ISerialStream, IDisposable
23 // Windows API Constants
24 const uint GenericRead = 0x80000000;
25 const uint GenericWrite = 0x40000000;
26 const uint OpenExisting = 3;
27 const uint FileFlagOverlapped = 0x40000000;
28 const uint PurgeRxClear = 0x0004;
29 const uint PurgeTxClear = 0x0008;
30 const uint WinInfiniteTimeout = 0xFFFFFFFF;
31 const uint FileIOPending = 997;
34 const uint SetRts = 3;
35 const uint ClearRts = 4;
36 const uint SetDtr = 5;
37 const uint ClearDtr = 6;
38 const uint SetBreak = 8;
39 const uint ClearBreak = 9;
40 const uint CtsOn = 0x0010;
41 const uint DsrOn = 0x0020;
42 const uint RsldOn = 0x0080;
45 const uint EvRxChar = 0x0001;
46 const uint EvCts = 0x0008;
47 const uint EvDsr = 0x0010;
48 const uint EvRlsd = 0x0020;
49 const uint EvBreak = 0x0040;
50 const uint EvErr = 0x0080;
51 const uint EvRing = 0x0100;
57 IntPtr write_overlapped;
58 IntPtr read_overlapped;
59 ManualResetEvent read_event;
60 ManualResetEvent write_event;
63 [DllImport("kernel32", SetLastError = true)]
64 static extern int CreateFile(string port_name, uint desired_access,
65 uint share_mode, uint security_attrs, uint creation, uint flags,
68 [DllImport("kernel32", SetLastError = true)]
69 static extern bool SetupComm(int handle, int read_buffer_size, int write_buffer_size);
71 [DllImport("kernel32", SetLastError = true)]
72 static extern bool PurgeComm(int handle, uint flags);
74 [DllImport("kernel32", SetLastError = true)]
75 static extern bool SetCommTimeouts(int handle, Timeouts timeouts);
77 public WinSerialStream (string port_name, int baud_rate, int data_bits, Parity parity, StopBits sb,
78 bool dtr_enable, bool rts_enable, Handshake hs, int read_timeout, int write_timeout,
79 int read_buffer_size, int write_buffer_size)
81 handle = CreateFile (port_name, 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);
113 wo.EventHandle = write_event.Handle;
115 wo.EventHandle = (int) write_event.Handle;
117 write_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped)));
118 Marshal.StructureToPtr (wo, write_overlapped, true);
120 NativeOverlapped ro = new NativeOverlapped ();
121 read_event = new ManualResetEvent (false);
123 ro.EventHandle = read_event.Handle;
125 ro.EventHandle = (int) read_event.Handle;
127 read_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped)));
128 Marshal.StructureToPtr (ro, read_overlapped, true);
131 public override bool CanRead {
137 public override bool CanSeek {
143 public override bool CanTimeout {
149 public override bool CanWrite {
155 public override int ReadTimeout {
160 if (value < 0 && value != SerialPort.InfiniteTimeout)
161 throw new ArgumentOutOfRangeException ("value");
163 timeouts.SetValues (value, write_timeout);
164 if (!SetCommTimeouts (handle, timeouts))
165 ReportIOError (null);
167 read_timeout = value;
171 public override int WriteTimeout {
173 return write_timeout;
177 if (value < 0 && value != SerialPort.InfiniteTimeout)
178 throw new ArgumentOutOfRangeException ("value");
180 timeouts.SetValues (read_timeout, value);
181 if (!SetCommTimeouts (handle, timeouts))
182 ReportIOError (null);
184 write_timeout = value;
188 public override long Length {
190 throw new NotSupportedException ();
194 public override long Position {
196 throw new NotSupportedException ();
199 throw new NotSupportedException ();
203 [DllImport("kernel32", SetLastError = true)]
204 static extern bool CloseHandle (int handle);
206 protected override void Dispose (bool disposing)
212 CloseHandle (handle);
213 Marshal.FreeHGlobal (write_overlapped);
214 Marshal.FreeHGlobal (read_overlapped);
217 void IDisposable.Dispose ()
220 GC.SuppressFinalize (this);
223 public override void Close ()
225 ((IDisposable)this).Dispose ();
233 public override void Flush ()
239 public override long Seek (long offset, SeekOrigin origin)
241 throw new NotSupportedException();
244 public override void SetLength (long value)
246 throw new NotSupportedException();
250 [DllImport("kernel32", SetLastError = true)]
251 static extern unsafe bool ReadFile (int handle, byte* buffer, int bytes_to_read,
252 out int bytes_read, IntPtr overlapped);
254 [DllImport("kernel32", SetLastError = true)]
255 static extern unsafe bool GetOverlappedResult (int handle, IntPtr overlapped,
256 ref int bytes_transfered, bool wait);
259 public override int Read ([In, Out] byte [] buffer, int offset, int count)
263 throw new ArgumentNullException ("buffer");
264 if (offset < 0 || count < 0)
265 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
267 if (buffer.Length - offset < count )
268 throw new ArgumentException ("offset+count",
269 "The size of the buffer is less than offset + count.");
274 fixed (byte* ptr = buffer) {
275 if (ReadFile (handle, ptr + offset, count, out bytes_read, read_overlapped))
278 // Test for overlapped behavior
279 if (Marshal.GetLastWin32Error () != FileIOPending)
280 ReportIOError (null);
282 if (!GetOverlappedResult (handle, read_overlapped, ref bytes_read, true))
283 ReportIOError (null);
289 throw new TimeoutException (); // We didn't get any byte
295 [DllImport("kernel32", SetLastError = true)]
296 static extern unsafe bool WriteFile (int handle, byte* buffer, int bytes_to_write,
297 out int bytes_written, IntPtr overlapped);
300 public override void Write (byte [] buffer, int offset, int count)
304 throw new ArgumentNullException ("buffer");
306 if (offset < 0 || count < 0)
307 throw new ArgumentOutOfRangeException ();
309 if (buffer.Length - offset < count)
310 throw new ArgumentException ("offset+count",
311 "The size of the buffer is less than offset + count.");
313 int bytes_written = 0;
316 fixed (byte* ptr = buffer) {
317 if (WriteFile (handle, ptr + offset, count, out bytes_written, write_overlapped))
319 if (Marshal.GetLastWin32Error() != FileIOPending)
320 ReportIOError (null);
322 if (!GetOverlappedResult(handle, write_overlapped, ref bytes_written, true))
323 ReportIOError (null);
327 // If the operation timed out, then
328 // we transfered less bytes than the requested ones
329 if (bytes_written < count)
330 throw new TimeoutException ();
333 [DllImport("kernel32", SetLastError = true)]
334 static extern bool GetCommState (int handle, [Out] DCB dcb);
336 [DllImport ("kernel32", SetLastError=true)]
337 static extern bool SetCommState (int handle, DCB dcb);
339 public void SetAttributes (int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs)
341 DCB dcb = new DCB ();
342 if (!GetCommState (handle, dcb))
343 ReportIOError (null);
345 dcb.SetValues (baud_rate, parity, data_bits, bits, hs);
346 if (!SetCommState (handle, dcb))
347 ReportIOError (null);
350 void ReportIOError(string optional_arg)
352 int error = Marshal.GetLastWin32Error ();
357 message = "The port `" + optional_arg + "' does not exist.";
360 message = "Parameter is incorrect.";
363 // As fallback, we show the win32 error
364 message = new Win32Exception ().Message;
368 throw new IOException (message);
371 void CheckDisposed ()
374 throw new ObjectDisposedException (GetType ().FullName);
377 // ISerialStream members
378 public void DiscardInBuffer ()
380 if (!PurgeComm (handle, PurgeRxClear))
381 ReportIOError (null);
384 public void DiscardOutBuffer ()
386 if (!PurgeComm (handle, PurgeRxClear))
387 ReportIOError (null);
390 [DllImport ("kernel32", SetLastError=true)]
391 static extern bool ClearCommError (int handle, out uint errors, out CommStat stat);
393 public int BytesToRead {
397 if (!ClearCommError (handle, out errors, out stat))
398 ReportIOError (null);
400 return (int)stat.BytesIn;
404 public int BytesToWrite {
408 if (!ClearCommError (handle, out errors, out stat))
409 ReportIOError (null);
411 return (int)stat.BytesOut;
415 [DllImport ("kernel32", SetLastError=true)]
416 static extern bool GetCommModemStatus (int handle, out uint flags);
418 public SerialSignal GetSignals ()
421 if (!GetCommModemStatus (handle, out flags))
422 ReportIOError (null);
424 SerialSignal signals = SerialSignal.None;
425 if ((flags & RsldOn) != 0)
426 signals |= SerialSignal.Cd;
427 if ((flags & CtsOn) != 0)
428 signals |= SerialSignal.Cts;
429 if ((flags & DsrOn) != 0)
430 signals |= SerialSignal.Dsr;
435 [DllImport ("kernel32", SetLastError=true)]
436 static extern bool EscapeCommFunction (int handle, uint flags);
438 public void SetSignal (SerialSignal signal, bool value)
440 if (signal != SerialSignal.Rts && signal != SerialSignal.Dtr)
441 throw new Exception ("Wrong internal value");
444 if (signal == SerialSignal.Rts)
455 if (!EscapeCommFunction (handle, flag))
456 ReportIOError (null);
459 public void SetBreakState (bool value)
461 if (!EscapeCommFunction (handle, value ? SetBreak : ClearBreak))
462 ReportIOError (null);
467 [StructLayout (LayoutKind.Sequential)]
470 public int dcb_length;
471 public int baud_rate;
473 public short w_reserved;
474 public short xon_lim;
475 public short xoff_lim;
476 public byte byte_size;
478 public byte stop_bits;
479 public byte xon_char;
480 public byte xoff_char;
481 public byte error_char;
482 public byte eof_char;
483 public byte evt_char;
484 public short w_reserved1;
487 //const int fBinary = 0x0001;
488 //const int fParity = 0x0002;
489 const int fOutxCtsFlow = 0x0004;
490 //const int fOutxDsrFlow1 = 0x0008;
491 //const int fOutxDsrFlow2 = 0x0010;
492 //const int fDtrControl = 0x00020;
493 //const int fDsrSensitivity = 0x0040;
494 //const int fTXContinueOnXoff = 0x0080;
495 const int fOutX = 0x0100;
496 const int fInX = 0x0200;
497 //const int fErrorChar = 0x0400;
498 //const int fNull = 0x0800;
499 //const int fRtsControl1 = 0x1000;
500 const int fRtsControl2 = 0x2000;
501 //const int fAbortOnError = 0x4000;
503 public void SetValues (int baud_rate, Parity parity, int byte_size, StopBits sb, Handshake hs)
509 case StopBits.OnePointFive:
515 default: // Shouldn't happen
519 this.baud_rate = baud_rate;
520 this.parity = (byte)parity;
521 this.byte_size = (byte)byte_size;
523 // Clear Handshake flags
524 flags &= ~(fOutxCtsFlow | fOutX | fInX | fRtsControl2);
526 // Set Handshake flags
531 case Handshake.XOnXOff:
532 flags |= fOutX | fInX;
534 case Handshake.RequestToSend:
535 flags |= fOutxCtsFlow | fRtsControl2;
537 case Handshake.RequestToSendXOnXOff:
538 flags |= fOutxCtsFlow | fOutX | fInX | fRtsControl2;
540 default: // Shouldn't happen
546 [StructLayout (LayoutKind.Sequential)]
549 public uint ReadIntervalTimeout;
550 public uint ReadTotalTimeoutMultiplier;
551 public uint ReadTotalTimeoutConstant;
552 public uint WriteTotalTimeoutMultiplier;
553 public uint WriteTotalTimeoutConstant;
555 public const uint MaxDWord = 0xFFFFFFFF;
557 public Timeouts (int read_timeout, int write_timeout)
559 SetValues (read_timeout, write_timeout);
562 public void SetValues (int read_timeout, int write_timeout)
564 // FIXME: The windows api docs are not very clear about read timeouts,
565 // and we have to simulate infinite with a big value (uint.MaxValue - 1)
566 ReadIntervalTimeout = MaxDWord;
567 ReadTotalTimeoutMultiplier = MaxDWord;
568 ReadTotalTimeoutConstant = (read_timeout == -1 ? MaxDWord - 1 : (uint) read_timeout);
570 WriteTotalTimeoutMultiplier = 0;
571 WriteTotalTimeoutConstant = (write_timeout == -1 ? MaxDWord : (uint) write_timeout);
576 [StructLayout (LayoutKind.Sequential)]
581 public uint BytesOut;