Merge remote-tracking branch 'origin/development' into development

This commit is contained in:
larsbrubaker 2014-03-05 21:04:32 -08:00
commit db8ff174c2
9 changed files with 14 additions and 2298 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,530 +0,0 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using MatterHackers.TermiosH;
namespace MatterHackers.MatterControl.FrostedSerial
{
[StructLayout(LayoutKind.Sequential, Pack=1)]
public unsafe struct tDeviceInfo
{
public uint c_iflag;
public uint c_oflag;
public uint c_cflag;
public uint c_lflag;
public fixed byte c_cc[20];
public uint c_ispeed;
public uint c_ospeed;
}
class FrostedSerialPortStream : Stream, IFrostedSerialStream, IDisposable
{
int fd;
int read_timeout;
int write_timeout;
bool disposed;
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int open_serial(string portName);
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int set_attributes (int fd, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake);
public FrostedSerialPortStream(string portName, int baudRate, int dataBits, Parity parity, StopBits stopBits,
bool dtrEnable, bool rtsEnable, Handshake handshake, int readTimeout, int writeTimeout,
int readBufferSize, int writeBufferSize)
{
fd = open_serial(portName);
if (fd == -1) {
ThrowIOException ();
}
TryBaudRate(baudRate);
int canSetAttributes = set_attributes (fd, baudRate, parity, dataBits, stopBits, handshake);
if (canSetAttributes != 0)
{
throw new IOException(canSetAttributes.ToString()); // Probably Win32Exc for compatibility
}
read_timeout = readTimeout;
write_timeout = writeTimeout;
SetSignal(SerialSignal.Dtr, dtrEnable);
if (handshake != Handshake.RequestToSend &&
handshake != Handshake.RequestToSendXOnXOff)
SetSignal(SerialSignal.Rts, rtsEnable);
}
private int SetupBaudRate(int baudRate)
{
throw new NotImplementedException();
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int tcgetattr(int fd, tDeviceInfo newtio);
private int TCGetAttribute(int fd, tDeviceInfo newtio)
{
int result = tcgetattr (fd, newtio);
return result;
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int tcsetattr(int fd, uint optional_actions, tDeviceInfo newtio);
private int TCSetAttribute(int fd, uint optional_actions, tDeviceInfo newtio)
{
return tcsetattr (fd, optional_actions, newtio);
}
private int CFSetISpeed(tDeviceInfo newtio, int baudRate)
{
newtio.c_ispeed = (uint)baudRate;
return (int)newtio.c_ispeed;
}
private int CFSetOSpeed(tDeviceInfo newtio, int baudRate)
{
newtio.c_ospeed = (uint)baudRate;
return (int)newtio.c_ospeed;
}
private bool SetFrostedAttributes(int fd, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake)
{
tDeviceInfo newtio = new tDeviceInfo ();
if (TCGetAttribute (fd, newtio) == -1) {
return false;
}
newtio.c_cflag |= (uint)(e_c_oflag.CLOCAL | e_c_oflag.CREAD);
// there is no defenition for e_c_lflag.ECHOL that I can find. It was in the list of or'ed flags below
unchecked
{
newtio.c_lflag &= (uint)-(int)(e_c_lflag.ICANON | e_c_lflag.ECHO | e_c_lflag.ECHOE | e_c_lflag.ECHOK | e_c_lflag.ECHONL | e_c_lflag.ISIG | e_c_lflag.IEXTEN);
}
newtio.c_oflag &= (uint)(e_c_oflag.OPOST);
newtio.c_iflag = (uint)e_c_iflag.IGNBRK;
baudRate = SetupBaudRate (baudRate);
unchecked {
newtio.c_cflag &= (uint)-(uint)e_c_oflag.CSIZE;
}
switch (dataBits)
{
case 5:
newtio.c_cflag |= (uint)e_c_oflag.CS5;
break;
case 6:
newtio.c_cflag |= (uint)e_c_oflag.CS6;
break;
case 7:
newtio.c_cflag |= (uint)e_c_oflag.CS6;
break;
case 8:
default:
newtio.c_cflag |= (uint)e_c_oflag.CS8;
break;
}
switch (stopBits)
{
case StopBits.None:
break;
case StopBits.One:
unchecked
{
newtio.c_cflag &= (uint)-(uint)e_c_oflag.CSTOPB;
}
break;
case StopBits.Two:
newtio.c_cflag |= (uint)e_c_oflag.CSTOPB;
break;
case StopBits.OnePointFive:
break;
}
unchecked {
newtio.c_iflag &= (uint)-(uint)(e_c_iflag.INPCK | e_c_iflag.ISTRIP);
}
switch (parity)
{
case Parity.None: /* None */
newtio.c_cflag &= ~(uint)(e_c_oflag.PARENB | e_c_oflag.PARODD);
break;
case Parity.Odd: /* Odd */
newtio.c_cflag |= (uint)(e_c_oflag.PARENB | e_c_oflag.PARODD);
break;
case Parity.Even: /* Even */
newtio.c_cflag &= ~(uint)(e_c_oflag.PARODD);
newtio.c_cflag |= (uint)(e_c_oflag.PARENB);
break;
case Parity.Mark: /* Mark */
/* XXX unhandled */
break;
case Parity.Space: /* Space */
/* XXX unhandled */
break;
}
newtio.c_iflag &= ~(uint)(e_c_iflag.IXOFF | e_c_iflag.IXON);
#if CRTSCTS
newtio.c_cflag &= ~CRTSCTS;
#endif //* def CRTSCTS */
switch (handshake)
{
case Handshake.None: /* None */
/* do nothing */
break;
case Handshake.RequestToSend: /* RequestToSend (RTS) */
#if CRTSCTS
newtio.c_cflag |= CRTSCTS;
#endif //* def CRTSCTS */
break;
case Handshake.RequestToSendXOnXOff: /* RequestToSendXOnXOff (RTS + XON/XOFF) */
#if CRTSCTS
newtio.c_cflag |= CRTSCTS;
#endif //* def CRTSCTS */
/* fall through */
case Handshake.XOnXOff: /* XOnXOff */
newtio.c_iflag |= (uint)(e_c_iflag.IXOFF | e_c_iflag.IXON);
break;
}
if (CFSetOSpeed (newtio, baudRate) < 0 || CFSetISpeed (newtio, baudRate) < 0 ||
TCSetAttribute (fd, (uint)e_tcsetaatr.TCSANOW, newtio) < 0)
{
return false;
}
else
{
return true;
}
//return set_attributes(fd, baudRate, parity, dataBits, sb, hs);
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override bool CanTimeout
{
get
{
return true;
}
}
public override int ReadTimeout
{
get
{
return read_timeout;
}
set
{
if (value < 0 && value != FrostedSerialPort.InfiniteTimeout)
throw new ArgumentOutOfRangeException("value");
read_timeout = value;
}
}
public override int WriteTimeout
{
get
{
return write_timeout;
}
set
{
if (value < 0 && value != FrostedSerialPort.InfiniteTimeout)
throw new ArgumentOutOfRangeException("value");
write_timeout = value;
}
}
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
public override void Flush()
{
// If used, this _could_ flush the serial port
// buffer (not the SerialPort class buffer)
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int read_serial(int fd, byte[] buffer, int offset, int count);
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern bool poll_serial(int fd, out int error, int timeout);
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
CheckDisposed();
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException("offset or count less than zero.");
if (buffer.Length - offset < count)
throw new ArgumentException("offset+count",
"The size of the buffer is less than offset + count.");
int error;
bool poll_result = poll_serial(fd, out error, read_timeout);
if (error == -1)
ThrowIOException();
if (!poll_result)
{
// see bug 79735 http://bugzilla.ximian.com/show_bug.cgi?id=79735
// should the next line read: return -1;
throw new TimeoutException();
}
int result = read_serial(fd, buffer, offset, count);
if (result == -1)
ThrowIOException();
return result;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int write_serial(int fd, byte[] buffer, int offset, int count, int timeout);
public override void Write(byte[] buffer, int offset, int count)
{
CheckDisposed();
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException();
if (buffer.Length - offset < count)
throw new ArgumentException("offset+count",
"The size of the buffer is less than offset + count.");
// FIXME: this reports every write error as timeout
if (write_serial(fd, buffer, offset, count, write_timeout) < 0)
throw new TimeoutException("The operation has timed-out");
}
protected override void Dispose(bool disposing)
{
if (disposed)
return;
disposed = true;
if (close_serial (fd) != 0)
{
//Don't do anything
}
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int close_serial(int fd);
public override void Close()
{
((IDisposable)this).Dispose();
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~FrostedSerialPortStream()
{
Dispose(false);
}
void CheckDisposed()
{
if (disposed)
throw new ObjectDisposedException(GetType().FullName);
}
public void SetAttributes(int baud_rate, Parity parity, int data_bits, StopBits sb, Handshake hs)
{
if (!SetFrostedAttributes(fd, baud_rate, parity, data_bits, sb, hs))
ThrowIOException();
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int get_bytes_in_buffer(int fd, int input);
public int BytesToRead
{
get
{
int result = get_bytes_in_buffer(fd, 1);
if (result == -1)
ThrowIOException();
return result;
}
}
public int BytesToWrite
{
get
{
int result = get_bytes_in_buffer(fd, 0);
if (result == -1)
ThrowIOException();
return result;
}
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int discard_buffer(int fd, bool inputBuffer);
public void DiscardInBuffer()
{
if (discard_buffer(fd, true) != 0)
ThrowIOException();
}
public void DiscardOutBuffer()
{
if (discard_buffer(fd, false) != 0)
ThrowIOException();
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern SerialSignal get_signals(int fd, out int error);
public SerialSignal GetSignals()
{
int error;
SerialSignal signals = get_signals(fd, out error);
if (error == -1)
ThrowIOException();
return signals;
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int set_signal(int fd, SerialSignal signal, bool value);
public void SetSignal(SerialSignal signal, bool value)
{
if (signal < SerialSignal.Cd || signal > SerialSignal.Rts ||
signal == SerialSignal.Cd ||
signal == SerialSignal.Cts ||
signal == SerialSignal.Dsr)
throw new Exception("Invalid internal value");
if (set_signal(fd, signal, value) == -1)
ThrowIOException();
}
[DllImport("FrostedSerialHelper", SetLastError = true)]
static extern int breakprop(int fd);
public void SetBreakState(bool value)
{
if (value)
if (breakprop(fd) == -1)
ThrowIOException();
}
[DllImport("libc")]
static extern IntPtr strerror(int errnum);
static void ThrowIOException()
{
int errnum = Marshal.GetLastWin32Error();
string error_message = Marshal.PtrToStringAnsi(strerror(errnum));
throw new IOException(error_message);
}
[DllImport("FrostedSerialHelper")]
static extern bool is_baud_rate_legal(int baud_rate);
private void TryBaudRate(int baudRate)
{
if (!is_baud_rate_legal(baudRate))
{
// this kind of exception to be compatible with MSDN API
throw new ArgumentOutOfRangeException("baudRate",
"Given baud rate is not supported on this platform.");
}
}
}
}

View file

@ -1,22 +0,0 @@
using System;
namespace MatterHackers.MatterControl.FrostedSerial
{
interface IFrostedSerialStream : IDisposable
{
int Read (byte [] buffer, int offset, int count);
void Write (byte [] buffer, int offset, int count);
void SetAttributes (int baud_rate, Parity parity, int data_bits, StopBits sb, Handshake hs);
void DiscardInBuffer ();
void DiscardOutBuffer ();
SerialSignal GetSignals ();
void SetSignal (SerialSignal signal, bool value);
void SetBreakState (bool value);
void Close ();
int BytesToRead { get; }
int BytesToWrite { get; }
int ReadTimeout { get; set; }
int WriteTimeout { get; set; }
}
}

View file

@ -1,155 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MatterHackers.TermiosH
{
public enum e_cc_c
{
/* Indices into c_cc array. Default values in parentheses. POSIX Table 7-5. */
VEOF = 0, /* cc_c[VEOF] = EOF char (^D) */
VEOL = 1, /* cc_c[VEOL] = EOL char (undef) */
VERASE = 2, /* cc_c[VERASE] = ERASE char (^H) */
VINTR = 3, /* cc_c[VINTR] = INTR char (DEL) */
VKILL = 4, /* cc_c[VKILL] = KILL char (^U) */
VMIN = 5, /* cc_c[VMIN] = MIN value for timer */
VQUIT = 6, /* cc_c[VQUIT] = QUIT char (^\) */
VTIME = 7, /* cc_c[VTIME] = TIME value for timer */
VSUSP = 8, /* cc_c[VSUSP] = SUSP (^Z, ignored) */
VSTART = 9, /* cc_c[VSTART] = START char (^S) */
VSTOP = 10, /* cc_c[VSTOP] = STOP char (^Q) */
//_POSIX_VDISABLE =(cc_t)0xFF, /* You can't even generate this /*
/* character with 'normal' keyboards.
* But some language specific keyboards
* can generate 0xFF. It seems that all
* 256 are used, so cc_t should be a
* short...
*/
SIZE = 20, /* size of cc_c array, some extra space * for extensions. */
};
/* Values for termios c_iflag bit map. POSIX Table 7-2. */
[Flags]
public enum e_c_iflag
{
BRKINT = 0x0001, /* signal interrupt on break */
ICRNL = 0x0002, /* map CR to NL on input */
IGNBRK = 0x0004, /* ignore break */
IGNCR = 0x0008, /* ignore CR */
IGNPAR = 0x0010, /* ignore characters with parity errors */
INLCR = 0x0020, /* map NL to CR on input */
INPCK = 0x0040, /* enable input parity check */
ISTRIP = 0x0080, /* mask off 8th bit */
IXOFF = 0x0100, /* enable start/stop input control */
IXON = 0x0200, /* enable start/stop output control */
PARMRK = 0x0400, /* mark parity errors in the input queue */
};
/* Values for termios c_oflag bit map. POSIX Sec. 7.1.2.3. */
[Flags]
public enum e_c_oflag
{
OPOST = 0x0001, /* perform output processing */
/* Values for termios c_cflag bit map. POSIX Table 7-3. */
CLOCAL = 0x0001, /* ignore modem status lines */
CREAD = 0x0002, /* enable receiver */
CSIZE = 0x000C, /* number of bits per character */
CS5 = 0x0000, /* if CSIZE is CS5, characters are 5 bits */
CS6 = 0x0004, /* if CSIZE is CS6, characters are 6 bits */
CS7 = 0x0008, /* if CSIZE is CS7, characters are 7 bits */
CS8 = 0x000C, /* if CSIZE is CS8, characters are 8 bits */
CSTOPB = 0x0010, /* send 2 stop bits if set, else 1 */
HUPCL = 0x0020, /* hang up on last close */
PARENB = 0x0040, /* enable parity on output */
PARODD = 0x0080, /* use odd parity if set, else even */
};
/* Values for termios c_lflag bit map. POSIX Table 7-4. */
[Flags]
public enum e_c_lflag
{
ECHO = 0x0001, /* enable echoing of input characters */
ECHOE = 0x0002, /* echo ERASE as backspace */
ECHOK = 0x0004, /* echo KILL */
ECHONL = 0x0008, /* echo NL */
ICANON = 0x0010, /* canonical input (erase and kill enabled) */
IEXTEN = 0x0020, /* enable extended functions */
ISIG = 0x0040, /* enable signals */
NOFLSH = 0x0080, /* disable flush after interrupt or quit */
TOSTOP = 0x0100, /* send SIGTTOU (job control, not implemented*/
};
/* Values for the baud rate settings. POSIX Table 7-6. */
[Flags]
public enum e_baud_rate
{
B0 = 0x0000, /* hang up the line */
B50 = 0x1000, /* 50 baud */
B75 = 0x2000, /* 75 baud */
B110 = 0x3000, /* 110 baud */
B134 = 0x4000, /* 134.5 baud */
B150 = 0x5000, /* 150 baud */
B200 = 0x6000, /* 200 baud */
B300 = 0x7000, /* 300 baud */
B600 = 0x8000, /* 600 baud */
B1200 = 0x9000, /* 1200 baud */
B1800 = 0xA000, /* 1800 baud */
B2400 = 0xB000, /* 2400 baud */
B4800 = 0xC000, /* 4800 baud */
B9600 = 0xD000, /* 9600 baud */
B19200 = 0xE000, /* 19200 baud */
B38400 = 0xF000, /* 38400 baud */
};
/* Optional actions for tcsetattr(). POSIX Sec. 7.2.1.2. */
[Flags]
public enum e_tcsetaatr
{
TCSANOW = 1, /* changes take effect immediately */
TCSADRAIN = 2, /* changes take effect after output is done */
TCSAFLUSH = 3, /* wait for output to finish and flush input */
};
/* Queue_selector values for tcflush(). POSIX Sec. 7.2.2.2. */
[Flags]
public enum e_tcflush
{
TCIFLUSH = 1, /* flush accumulated input data */
TCOFLUSH = 2, /* flush accumulated output data */
TCIOFLUSH = 3, /* flush accumulated input and output data */
};
/* Action values for tcflow(). POSIX Sec. 7.2.2.2. */
[Flags]
public enum e_tcflow
{
TCOOFF = 1, /* suspend output */
TCOON = 2, /* restart suspended output */
TCIOFF = 3, /* transmit a STOP character on the line */
TCION = 4, /* transmit a START character on the line */
};
static class testCLass
{
static void TestFunc()
{
uint c_cflag = 0;
uint c_lflag = 0;
uint c_oflag = 0;
uint c_iflag = 0;
c_cflag |= (uint)(e_c_oflag.CLOCAL | e_c_oflag.CREAD);
//c_lflag &= (uint)-(e_c_lflag.ICANON | e_c_lflag.ECHO | e_c_lflag.ECHOE | e_c_lflag.ECHOK | e_c_lflag.ECHOL | e_c_lflag.ECHONL | e_c_lflag.ISIG | e_c_lflag.IEXTEN);
// not supported in docs I can find ECHOL
unchecked
{
c_lflag &= (uint)-(uint)(e_c_lflag.ICANON | e_c_lflag.ECHO | e_c_lflag.ECHOE | e_c_lflag.ECHOK | e_c_lflag.ECHONL | e_c_lflag.ISIG | e_c_lflag.IEXTEN);
}
c_oflag &= (uint)(e_c_oflag.OPOST);
c_iflag = (uint)e_c_iflag.IGNBRK;
}
}
}

View file

@ -1,568 +0,0 @@
using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.ComponentModel;
namespace MatterHackers.MatterControl.FrostedSerial
{
class WinSerialStream : Stream, IFrostedSerialStream, IDisposable
{
// Windows API Constants
const uint GenericRead = 0x80000000;
const uint GenericWrite = 0x40000000;
const uint OpenExisting = 3;
const uint FileFlagOverlapped = 0x40000000;
const uint PurgeRxClear = 0x0008;
const uint PurgeTxClear = 0x0004;
const uint WinInfiniteTimeout = 0xFFFFFFFF;
const uint FileIOPending = 997;
// Signal constants
const uint SetRts = 3;
const uint ClearRts = 4;
const uint SetDtr = 5;
const uint ClearDtr = 6;
const uint SetBreak = 8;
const uint ClearBreak = 9;
const uint CtsOn = 0x0010;
const uint DsrOn = 0x0020;
const uint RsldOn = 0x0080;
// Event constants
const uint EvRxChar = 0x0001;
const uint EvCts = 0x0008;
const uint EvDsr = 0x0010;
const uint EvRlsd = 0x0020;
const uint EvBreak = 0x0040;
const uint EvErr = 0x0080;
const uint EvRing = 0x0100;
int handle;
int read_timeout;
int write_timeout;
bool disposed;
IntPtr write_overlapped;
IntPtr read_overlapped;
ManualResetEvent read_event;
ManualResetEvent write_event;
Timeouts timeouts;
[DllImport("kernel32", SetLastError = true)]
static extern int CreateFile(string port_name, uint desired_access,
uint share_mode, uint security_attrs, uint creation, uint flags,
uint template);
[DllImport("kernel32", SetLastError = true)]
static extern bool SetupComm(int handle, int read_buffer_size, int write_buffer_size);
[DllImport("kernel32", SetLastError = true)]
static extern bool PurgeComm(int handle, uint flags);
[DllImport("kernel32", SetLastError = true)]
static extern bool SetCommTimeouts(int handle, Timeouts timeouts);
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)
{
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);
// 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);
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);
}
public override bool CanRead {
get {
return true;
}
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanTimeout {
get {
return true;
}
}
public override bool CanWrite {
get {
return true;
}
}
public override int ReadTimeout {
get {
return read_timeout;
}
set {
if (value < 0 && value != FrostedSerialPort.InfiniteTimeout)
throw new ArgumentOutOfRangeException ("value");
timeouts.SetValues (value, write_timeout);
if (!SetCommTimeouts (handle, timeouts))
ReportIOError (null);
read_timeout = value;
}
}
public override int WriteTimeout {
get {
return write_timeout;
}
set
{
if (value < 0 && value != FrostedSerialPort.InfiniteTimeout)
throw new ArgumentOutOfRangeException ("value");
timeouts.SetValues (read_timeout, value);
if (!SetCommTimeouts (handle, timeouts))
ReportIOError (null);
write_timeout = value;
}
}
public override long Length {
get {
throw new NotSupportedException ();
}
}
public override long Position {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
[DllImport("kernel32", SetLastError = true)]
static extern bool CloseHandle (int handle);
protected override void Dispose (bool disposing)
{
if (disposed)
return;
disposed = true;
CloseHandle (handle);
Marshal.FreeHGlobal (write_overlapped);
Marshal.FreeHGlobal (read_overlapped);
}
void IDisposable.Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public override void Close ()
{
((IDisposable)this).Dispose ();
}
~WinSerialStream ()
{
Dispose (false);
}
public override void Flush ()
{
CheckDisposed ();
// No dothing by now
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength (long value)
{
throw new NotSupportedException();
}
#if !TARGET_JVM
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool ReadFile (int handle, byte* buffer, int bytes_to_read,
out int bytes_read, IntPtr overlapped);
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool GetOverlappedResult (int handle, IntPtr overlapped,
ref int bytes_transfered, bool wait);
#endif
public override int Read ([In, Out] byte [] buffer, int offset, int count)
{
CheckDisposed ();
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException ("offset or count less than zero.");
if (buffer.Length - offset < count )
throw new ArgumentException ("offset+count",
"The size of the buffer is less than offset + count.");
int bytes_read;
unsafe {
fixed (byte* ptr = buffer) {
if (ReadFile (handle, ptr + offset, count, out bytes_read, read_overlapped))
return bytes_read;
// Test for overlapped behavior
if (Marshal.GetLastWin32Error () != FileIOPending)
ReportIOError (null);
if (!GetOverlappedResult (handle, read_overlapped, ref bytes_read, true))
ReportIOError (null);
}
}
if (bytes_read == 0)
throw new TimeoutException (); // We didn't get any byte
return bytes_read;
}
#if !TARGET_JVM
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool WriteFile (int handle, byte* buffer, int bytes_to_write,
out int bytes_written, IntPtr overlapped);
#endif
public override void Write (byte [] buffer, int offset, int count)
{
CheckDisposed ();
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException ();
if (buffer.Length - offset < count)
throw new ArgumentException ("offset+count",
"The size of the buffer is less than offset + count.");
int bytes_written = 0;
unsafe {
fixed (byte* ptr = buffer) {
if (WriteFile (handle, ptr + offset, count, out bytes_written, write_overlapped))
return;
if (Marshal.GetLastWin32Error() != FileIOPending)
ReportIOError (null);
if (!GetOverlappedResult(handle, write_overlapped, ref bytes_written, true))
ReportIOError (null);
}
}
// If the operation timed out, then
// we transfered less bytes than the requested ones
if (bytes_written < count)
throw new TimeoutException ();
}
[DllImport("kernel32", SetLastError = true)]
static extern bool GetCommState (int handle, [Out] DCB dcb);
[DllImport ("kernel32", SetLastError=true)]
static extern bool SetCommState (int handle, DCB dcb);
public void SetAttributes (int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs)
{
DCB dcb = new DCB ();
if (!GetCommState (handle, dcb))
ReportIOError (null);
dcb.SetValues (baud_rate, parity, data_bits, bits, hs);
if (!SetCommState (handle, dcb))
ReportIOError (null);
}
void ReportIOError(string optional_arg)
{
int error = Marshal.GetLastWin32Error ();
string message;
switch (error) {
case 2:
case 3:
message = "The port `" + optional_arg + "' does not exist.";
break;
case 87:
message = "Parameter is incorrect.";
break;
default:
// As fallback, we show the win32 error
message = new Win32Exception ().Message;
break;
}
throw new IOException (message);
}
void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException (GetType ().FullName);
}
// ISerialStream members
public void DiscardInBuffer ()
{
if (!PurgeComm (handle, PurgeRxClear))
ReportIOError (null);
}
public void DiscardOutBuffer ()
{
if (!PurgeComm (handle, PurgeTxClear))
ReportIOError (null);
}
[DllImport ("kernel32", SetLastError=true)]
static extern bool ClearCommError (int handle, out uint errors, out CommStat stat);
public int BytesToRead {
get {
uint errors;
CommStat stat;
if (!ClearCommError (handle, out errors, out stat))
ReportIOError (null);
return (int)stat.BytesIn;
}
}
public int BytesToWrite {
get {
uint errors;
CommStat stat;
if (!ClearCommError (handle, out errors, out stat))
ReportIOError (null);
return (int)stat.BytesOut;
}
}
[DllImport ("kernel32", SetLastError=true)]
static extern bool GetCommModemStatus (int handle, out uint flags);
public SerialSignal GetSignals ()
{
uint flags;
if (!GetCommModemStatus (handle, out flags))
ReportIOError (null);
SerialSignal signals = SerialSignal.None;
if ((flags & RsldOn) != 0)
signals |= SerialSignal.Cd;
if ((flags & CtsOn) != 0)
signals |= SerialSignal.Cts;
if ((flags & DsrOn) != 0)
signals |= SerialSignal.Dsr;
return signals;
}
[DllImport ("kernel32", SetLastError=true)]
static extern bool EscapeCommFunction (int handle, uint flags);
public void SetSignal (SerialSignal signal, bool value)
{
if (signal != SerialSignal.Rts && signal != SerialSignal.Dtr)
throw new Exception ("Wrong internal value");
uint flag;
if (signal == SerialSignal.Rts)
if (value)
flag = SetRts;
else
flag = ClearRts;
else
if (value)
flag = SetDtr;
else
flag = ClearDtr;
if (!EscapeCommFunction (handle, flag))
ReportIOError (null);
}
public void SetBreakState (bool value)
{
if (!EscapeCommFunction (handle, value ? SetBreak : ClearBreak))
ReportIOError (null);
}
}
[StructLayout (LayoutKind.Sequential)]
class DCB
{
public int dcb_length;
public int baud_rate;
public int flags;
public short w_reserved;
public short xon_lim;
public short xoff_lim;
public byte byte_size;
public byte parity;
public byte stop_bits;
public byte xon_char;
public byte xoff_char;
public byte error_char;
public byte eof_char;
public byte evt_char;
public short w_reserved1;
// flags:
//const int fBinary = 0x0001;
//const int fParity = 0x0002;
const int fOutxCtsFlow = 0x0004;
//const int fOutxDsrFlow1 = 0x0008;
//const int fOutxDsrFlow2 = 0x0010;
//const int fDtrControl = 0x00020;
//const int fDsrSensitivity = 0x0040;
//const int fTXContinueOnXoff = 0x0080;
const int fOutX = 0x0100;
const int fInX = 0x0200;
//const int fErrorChar = 0x0400;
//const int fNull = 0x0800;
//const int fRtsControl1 = 0x1000;
const int fRtsControl2 = 0x2000;
//const int fAbortOnError = 0x4000;
public void SetValues (int baud_rate, Parity parity, int byte_size, StopBits sb, Handshake hs)
{
switch (sb) {
case StopBits.One:
stop_bits = 0;
break;
case StopBits.OnePointFive:
stop_bits = 1;
break;
case StopBits.Two:
stop_bits = 2;
break;
default: // Shouldn't happen
break;
}
this.baud_rate = baud_rate;
this.parity = (byte)parity;
this.byte_size = (byte)byte_size;
// Clear Handshake flags
flags &= ~(fOutxCtsFlow | fOutX | fInX | fRtsControl2);
// Set Handshake flags
switch (hs)
{
case Handshake.None:
break;
case Handshake.XOnXOff:
flags |= fOutX | fInX;
break;
case Handshake.RequestToSend:
flags |= fOutxCtsFlow | fRtsControl2;
break;
case Handshake.RequestToSendXOnXOff:
flags |= fOutxCtsFlow | fOutX | fInX | fRtsControl2;
break;
default: // Shouldn't happen
break;
}
}
}
[StructLayout (LayoutKind.Sequential)]
class Timeouts
{
public uint ReadIntervalTimeout;
public uint ReadTotalTimeoutMultiplier;
public uint ReadTotalTimeoutConstant;
public uint WriteTotalTimeoutMultiplier;
public uint WriteTotalTimeoutConstant;
public const uint MaxDWord = 0xFFFFFFFF;
public Timeouts (int read_timeout, int write_timeout)
{
SetValues (read_timeout, write_timeout);
}
public void SetValues (int read_timeout, int write_timeout)
{
// FIXME: The windows api docs are not very clear about read timeouts,
// and we have to simulate infinite with a big value (uint.MaxValue - 1)
ReadIntervalTimeout = MaxDWord;
ReadTotalTimeoutMultiplier = MaxDWord;
ReadTotalTimeoutConstant = (read_timeout == -1 ? MaxDWord - 1 : (uint) read_timeout);
WriteTotalTimeoutMultiplier = 0;
WriteTotalTimeoutConstant = (write_timeout == -1 ? MaxDWord : (uint) write_timeout);
}
}
[StructLayout (LayoutKind.Sequential)]
struct CommStat
{
public uint flags;
public uint BytesIn;
public uint BytesOut;
}
}

View file

@ -180,16 +180,11 @@
<Compile Include="SlicerConfiguration\SliceSettingsOrganizer.cs" />
<Compile Include="SlicerConfiguration\SlicingQueue.cs" />
<Compile Include="Utilities\TupleList.cs" />
<Compile Include="FrostedSerial\FrostedSerialPort.cs" />
<Compile Include="FrostedSerial\FrostedSerialStream.cs" />
<Compile Include="FrostedSerial\IFrostedSerialStream.cs" />
<Compile Include="FrostedSerial\WinSerialStream.cs" />
<Compile Include="VersionManagement\WebRequestHandler.cs" />
<Compile Include="VersionManagement\VersionFileHandler.cs" />
<Compile Include="AboutPage\AboutPage.cs" />
<Compile Include="CustomWidgets\ThemeColorSelectorWidget.cs" />
<Compile Include="ControlElements\TextImageButtonFactory.cs" />
<Compile Include="FrostedSerial\TermiosH.cs" />
<Compile Include="EeProm\EePromMarlinWidget.cs" />
<Compile Include="EeProm\EePromRepetierParameter.cs" />
<Compile Include="EeProm\EePromRepetierWidget.cs" />

View file

@ -29,27 +29,25 @@ either expressed or implied, of the FreeBSD Project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using System.Globalization;
using Microsoft.Win32.SafeHandles;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using MatterHackers.MatterControl.FrostedSerial;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.VectorMath;
using MatterHackers.SerialPortConnecton;
using MatterHackers.GCodeVisualizer;
using MatterHackers.MatterControl.VersionManagement;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.SerialPortCommunication;
using MatterHackers.SerialPortCommunication.FrostedSerial;
using MatterHackers.VectorMath;
using Microsoft.Win32.SafeHandles;
namespace MatterHackers.MatterControl
{

View file

@ -33,7 +33,7 @@ using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.VectorMath;
using MatterHackers.MatterControl.PrinterControls.PrinterConnections;
using MatterHackers.SerialPortConnecton;
using MatterHackers.SerialPortCommunication;
using MatterHackers.Localizations;
namespace MatterHackers.MatterControl

View file

@ -33,7 +33,7 @@ using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.VectorMath;
using MatterHackers.MatterControl.PrinterControls.PrinterConnections;
using MatterHackers.SerialPortConnecton;
using MatterHackers.SerialPortCommunication;
namespace MatterHackers.MatterControl
{