From 0cebab830a359f90d5fb397e4cd7e48e3a39ed68 Mon Sep 17 00:00:00 2001 From: larsbrubaker Date: Wed, 5 Mar 2014 10:33:19 -0800 Subject: [PATCH] Moved frosted serial into agg changed some namespaces --- FrostedSerial/FrostedSerialPort.cs | 1002 ------------------ FrostedSerial/FrostedSerialStream.cs | 530 --------- FrostedSerial/IFrostedSerialStream.cs | 22 - FrostedSerial/TermiosH.cs | 155 --- FrostedSerial/WinSerialStream.cs | 568 ---------- PrinterCommunication/PrinterCommunication.cs | 26 +- PrinterControls/OutputScrollWindow.cs | 2 +- PrinterControls/SDCardManager.cs | 2 +- 8 files changed, 14 insertions(+), 2293 deletions(-) delete mode 100644 FrostedSerial/FrostedSerialPort.cs delete mode 100644 FrostedSerial/FrostedSerialStream.cs delete mode 100644 FrostedSerial/IFrostedSerialStream.cs delete mode 100644 FrostedSerial/TermiosH.cs delete mode 100644 FrostedSerial/WinSerialStream.cs diff --git a/FrostedSerial/FrostedSerialPort.cs b/FrostedSerial/FrostedSerialPort.cs deleted file mode 100644 index f60ea91dd..000000000 --- a/FrostedSerial/FrostedSerialPort.cs +++ /dev/null @@ -1,1002 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Text; -using System.Runtime.InteropServices; -using Microsoft.Win32; -using System.IO; - -namespace MatterHackers.MatterControl.FrostedSerial -{ - enum SerialSignal - { - None = 0, - Cd = 1, // Carrier detect - Cts = 2, // Clear to send - Dsr = 4, // Data set ready - Dtr = 8, // Data terminal ready - Rts = 16 // Request to send - } - - - public enum Handshake - { - None, - XOnXOff, - RequestToSend, - RequestToSendXOnXOff - } - - public enum StopBits - { - None, - One, - Two, - OnePointFive - } - - public enum Parity - { - None, - Odd, - Even, - Mark, - Space - } - - public enum SerialError - { - RXOver = 1, - Overrun = 2, - RXParity = 4, - Frame = 8, - TXFull = 256 - } - - public enum SerialData - { - Chars = 1, - Eof - } - - public enum SerialPinChange - { - CtsChanged = 8, - DsrChanged = 16, - CDChanged = 32, - Break = 64, - Ring = 256 - } - - public class SerialDataReceivedEventArgs : EventArgs - { - internal SerialDataReceivedEventArgs(SerialData eventType) - { - this.eventType = eventType; - } - - // properties - - public SerialData EventType - { - get - { - return eventType; - } - } - - SerialData eventType; - } - - public class SerialPinChangedEventArgs : EventArgs - { - internal SerialPinChangedEventArgs(SerialPinChange eventType) - { - this.eventType = eventType; - } - - // properties - - public SerialPinChange EventType - { - get - { - return eventType; - } - } - - SerialPinChange eventType; - } - - public class SerialErrorReceivedEventArgs : EventArgs - { - - internal SerialErrorReceivedEventArgs(SerialError eventType) - { - this.eventType = eventType; - } - - // properties - - public SerialError EventType - { - get - { - return eventType; - } - } - - SerialError eventType; - } - - [MonitoringDescription("")] - [System.ComponentModel.DesignerCategory("")] - public class FrostedSerialPort : Component - { - public const int InfiniteTimeout = -1; - const int DefaultReadBufferSize = 4096; - const int DefaultWriteBufferSize = 2048; - const int DefaultBaudRate = 9600; - const int DefaultDataBits = 8; - const Parity DefaultParity = Parity.None; - const StopBits DefaultStopBits = StopBits.One; - - bool is_open; - int baud_rate; - Parity parity; - StopBits stop_bits; - Handshake handshake; - int data_bits; - bool break_state = false; - bool dtr_enable = false; - bool rts_enable = false; - IFrostedSerialStream stream; - Encoding encoding = Encoding.ASCII; - string new_line = Environment.NewLine; - string port_name; - int read_timeout = InfiniteTimeout; - int write_timeout = InfiniteTimeout; - int readBufferSize = DefaultReadBufferSize; - int writeBufferSize = DefaultWriteBufferSize; - object error_received = new object(); - object data_received = new object(); - object pin_changed = new object(); - - public FrostedSerialPort() : - this(GetDefaultPortName(), DefaultBaudRate, DefaultParity, DefaultDataBits, DefaultStopBits) - { - } - - public FrostedSerialPort(IContainer container) - : this() - { - // TODO: What to do here? - } - - public FrostedSerialPort(string portName) : - this(portName, DefaultBaudRate, DefaultParity, DefaultDataBits, DefaultStopBits) - { - } - - public FrostedSerialPort(string portName, int baudRate) : - this(portName, baudRate, DefaultParity, DefaultDataBits, DefaultStopBits) - { - } - - public FrostedSerialPort(string portName, int baudRate, Parity parity) : - this(portName, baudRate, parity, DefaultDataBits, DefaultStopBits) - { - } - - public FrostedSerialPort(string portName, int baudRate, Parity parity, int dataBits) : - this(portName, baudRate, parity, dataBits, DefaultStopBits) - { - } - - public FrostedSerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits) - { - port_name = portName; - baud_rate = baudRate; - data_bits = dataBits; - stop_bits = stopBits; - this.parity = parity; - } - - static string GetDefaultPortName() - { - string[] ports = GetPortNames(); - if (ports.Length > 0) - { - return ports[0]; - } - else - { - int p = (int)Environment.OSVersion.Platform; - if (p == 4 || p == 128 || p == 6) - return "ttyS0"; // Default for Unix - else - return "COM1"; // Default for Windows - } - } - - [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public Stream BaseStream - { - get - { - CheckOpen(); - return (Stream)stream; - } - } - - [DefaultValueAttribute(DefaultBaudRate)] - [Browsable(true)] - [MonitoringDescription("")] - public int BaudRate - { - get - { - return baud_rate; - } - set - { - if (value <= 0) - throw new ArgumentOutOfRangeException("value"); - - if (is_open) - stream.SetAttributes(value, parity, data_bits, stop_bits, handshake); - - baud_rate = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public bool BreakState - { - get - { - return break_state; - } - set - { - CheckOpen(); - if (value == break_state) - return; // Do nothing. - - stream.SetBreakState(value); - break_state = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public int BytesToRead - { - get - { - CheckOpen(); - return stream.BytesToRead; - } - } - - [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public int BytesToWrite - { - get - { - CheckOpen(); - return stream.BytesToWrite; - } - } - - [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public bool CDHolding - { - get - { - CheckOpen(); - return (stream.GetSignals() & SerialSignal.Cd) != 0; - } - } - - [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public bool CtsHolding - { - get - { - CheckOpen(); - return (stream.GetSignals() & SerialSignal.Cts) != 0; - } - } - - [DefaultValueAttribute(DefaultDataBits)] - [Browsable(true)] - [MonitoringDescription("")] - public int DataBits - { - get - { - return data_bits; - } - set - { - if (value < 5 || value > 8) - throw new ArgumentOutOfRangeException("value"); - - if (is_open) - stream.SetAttributes(baud_rate, parity, value, stop_bits, handshake); - - data_bits = value; - } - } - - //[MonoTODO("Not implemented")] - [Browsable(true)] - [MonitoringDescription("")] - [DefaultValue(false)] - public bool DiscardNull - { - get - { - throw new NotImplementedException(); - } - set - { - // LAMESPEC: Msdn states that an InvalidOperationException exception - // is fired if the port is not open, which is *not* happening. - - throw new NotImplementedException(); - } - } - - [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public bool DsrHolding - { - get - { - CheckOpen(); - return (stream.GetSignals() & SerialSignal.Dsr) != 0; - } - } - - [DefaultValueAttribute(false)] - [Browsable(true)] - [MonitoringDescription("")] - public bool DtrEnable - { - get - { - return dtr_enable; - } - set - { - if (value == dtr_enable) - return; - if (is_open) - stream.SetSignal(SerialSignal.Dtr, value); - - dtr_enable = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - [MonitoringDescription("")] - public Encoding Encoding - { - get - { - return encoding; - } - set - { - if (value == null) - throw new ArgumentNullException("value"); - - encoding = value; - } - } - - [DefaultValueAttribute(Handshake.None)] - [Browsable(true)] - [MonitoringDescription("")] - public Handshake Handshake - { - get - { - return handshake; - } - set - { - if (value < Handshake.None || value > Handshake.RequestToSendXOnXOff) - throw new ArgumentOutOfRangeException("value"); - - if (is_open) - stream.SetAttributes(baud_rate, parity, data_bits, stop_bits, value); - - handshake = value; - } - } - - [Browsable(false)] - public bool IsOpen - { - get - { - return is_open; - } - } - - [DefaultValueAttribute("\n")] - [Browsable(false)] - [MonitoringDescription("")] - public string NewLine - { - get - { - return new_line; - } - set - { - if (value == null) - throw new ArgumentNullException("value"); - if (value.Length == 0) - throw new ArgumentException("NewLine cannot be null or empty.", "value"); - - new_line = value; - } - } - - [DefaultValueAttribute(DefaultParity)] - [Browsable(true)] - [MonitoringDescription("")] - public Parity Parity - { - get - { - return parity; - } - set - { - if (value < Parity.None || value > Parity.Space) - throw new ArgumentOutOfRangeException("value"); - - if (is_open) - stream.SetAttributes(baud_rate, value, data_bits, stop_bits, handshake); - - parity = value; - } - } - - //[MonoTODO("Not implemented")] - [Browsable(true)] - [MonitoringDescription("")] - [DefaultValue(63)] - public byte ParityReplace - { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } - } - - - [Browsable(true)] - [MonitoringDescription("")] - [DefaultValue("COM1")] // silly Windows-ism. We should ignore it. - public string PortName - { - get - { - return port_name; - } - set - { - if (is_open) - throw new InvalidOperationException("Port name cannot be set while port is open."); - if (value == null) - throw new ArgumentNullException("value"); - if (value.Length == 0 || value.StartsWith("\\\\")) - throw new ArgumentException("value"); - - port_name = value; - } - } - - [DefaultValueAttribute(DefaultReadBufferSize)] - [Browsable(true)] - [MonitoringDescription("")] - public int ReadBufferSize - { - get - { - return readBufferSize; - } - set - { - if (is_open) - throw new InvalidOperationException(); - if (value <= 0) - throw new ArgumentOutOfRangeException("value"); - if (value <= DefaultReadBufferSize) - return; - - readBufferSize = value; - } - } - - [DefaultValueAttribute(InfiniteTimeout)] - [Browsable(true)] - [MonitoringDescription("")] - public int ReadTimeout - { - get - { - return read_timeout; - } - set - { - if (value < 0 && value != InfiniteTimeout) - throw new ArgumentOutOfRangeException("value"); - - if (is_open) - stream.ReadTimeout = value; - - read_timeout = value; - } - } - - //[MonoTODO("Not implemented")] - [DefaultValueAttribute(1)] - [Browsable(true)] - [MonitoringDescription("")] - public int ReceivedBytesThreshold - { - get - { - throw new NotImplementedException(); - } - set - { - if (value <= 0) - throw new ArgumentOutOfRangeException("value"); - - throw new NotImplementedException(); - } - } - - [DefaultValueAttribute(false)] - [Browsable(true)] - [MonitoringDescription("")] - public bool RtsEnable - { - get - { - return rts_enable; - } - set - { - if (value == rts_enable) - return; - if (is_open) - stream.SetSignal(SerialSignal.Rts, value); - - rts_enable = value; - } - } - - [DefaultValueAttribute(DefaultStopBits)] - [Browsable(true)] - [MonitoringDescription("")] - public StopBits StopBits - { - get - { - return stop_bits; - } - set - { - if (value < StopBits.One || value > StopBits.OnePointFive) - throw new ArgumentOutOfRangeException("value"); - - if (is_open) - stream.SetAttributes(baud_rate, parity, data_bits, value, handshake); - - stop_bits = value; - } - } - - [DefaultValueAttribute(DefaultWriteBufferSize)] - [Browsable(true)] - [MonitoringDescription("")] - public int WriteBufferSize - { - get - { - return writeBufferSize; - } - set - { - if (is_open) - throw new InvalidOperationException(); - if (value <= 0) - throw new ArgumentOutOfRangeException("value"); - if (value <= DefaultWriteBufferSize) - return; - - writeBufferSize = value; - } - } - - [DefaultValueAttribute(InfiniteTimeout)] - [Browsable(true)] - [MonitoringDescription("")] - public int WriteTimeout - { - get - { - return write_timeout; - } - set - { - if (value < 0 && value != InfiniteTimeout) - throw new ArgumentOutOfRangeException("value"); - - if (is_open) - stream.WriteTimeout = value; - - write_timeout = value; - } - } - - // methods - - public void Close() - { - Dispose(true); - } - - protected override void Dispose(bool disposing) - { - if (!is_open) - return; - - is_open = false; - // Do not close the base stream when the finalizer is run; the managed code can still hold a reference to it. - if (disposing) - stream.Close(); - stream = null; - } - - public void DiscardInBuffer() - { - CheckOpen(); - stream.DiscardInBuffer(); - } - - public void DiscardOutBuffer() - { - CheckOpen(); - stream.DiscardOutBuffer(); - } - - public static string[] GetPortNames() - { - int p = (int)Environment.OSVersion.Platform; - List serial_ports = new List(); - - // Are we on Unix? - if (p == 4 || p == 128 || p == 6) - { - string[] ttys = Directory.GetFiles("/dev/", "tty*"); - bool linux_style = false; - - // - // Probe for Linux-styled devices: /dev/ttyS* or /dev/ttyUSB* - // - foreach (string dev in ttys) - { - if (dev.StartsWith("/dev/ttyS") || dev.StartsWith("/dev/ttyUSB")) - { - linux_style = true; - break; - } - } - - foreach (string dev in ttys) - { - if (linux_style) - { - if (dev.StartsWith("/dev/ttyS") || dev.StartsWith("/dev/ttyUSB")) - serial_ports.Add(dev); - } - else - { - if (dev != "/dev/tty" && dev.StartsWith("/dev/tty") && !dev.StartsWith("/dev/ttyC")) - serial_ports.Add(dev); - } - } - } - else - { - using (RegistryKey subkey = Registry.LocalMachine.OpenSubKey("HARDWARE\\DEVICEMAP\\SERIALCOMM")) - { - if (subkey != null) - { - string[] names = subkey.GetValueNames(); - foreach (string value in names) - { - string port = subkey.GetValue(value, "").ToString(); - if (port != "") - serial_ports.Add(port); - } - } - } - } - return serial_ports.ToArray(); - } - - static bool IsWindows - { - get - { - PlatformID id = Environment.OSVersion.Platform; - return id == PlatformID.Win32Windows || id == PlatformID.Win32NT; // WinCE not supported - } - } - - public void Open() - { - if (is_open) - throw new InvalidOperationException("Port is already open"); - -#if !TARGET_JVM - if (IsWindows) // Use windows kernel32 backend - stream = new WinSerialStream(port_name, baud_rate, data_bits, parity, stop_bits, dtr_enable, - rts_enable, handshake, read_timeout, write_timeout, readBufferSize, writeBufferSize); - else // Use standard unix backend -#endif - stream = new FrostedSerialPortStream(port_name, baud_rate, data_bits, parity, stop_bits, dtr_enable, - rts_enable, handshake, read_timeout, write_timeout, readBufferSize, writeBufferSize); - - is_open = true; - } - - public int Read(byte[] buffer, int offset, int count) - { - CheckOpen(); - 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."); - - return stream.Read(buffer, offset, count); - } - - public int Read(char[] buffer, int offset, int count) - { - CheckOpen(); - 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 c, i; - for (i = 0; i < count && (c = ReadChar()) != -1; i++) - buffer[offset + i] = (char)c; - - return i; - } - - internal int read_byte() - { - byte[] buff = new byte[1]; - if (stream.Read(buff, 0, 1) > 0) - return buff[0]; - - return -1; - } - - public int ReadByte() - { - CheckOpen(); - return read_byte(); - } - - public int ReadChar() - { - CheckOpen(); - - byte[] buffer = new byte[16]; - int i = 0; - - do - { - int b = read_byte(); - if (b == -1) - return -1; - buffer[i++] = (byte)b; - char[] c = encoding.GetChars(buffer, 0, 1); - if (c.Length > 0) - return (int)c[0]; - } while (i < buffer.Length); - - return -1; - } - - public string ReadExisting() - { - CheckOpen(); - - int count = BytesToRead; - byte[] bytes = new byte[count]; - - int n = stream.Read(bytes, 0, count); - return new String(encoding.GetChars(bytes, 0, n)); - } - - public string ReadLine() - { - return ReadTo(new_line); - } - - public string ReadTo(string value) - { - CheckOpen(); - if (value == null) - throw new ArgumentNullException("value"); - if (value.Length == 0) - throw new ArgumentException("value"); - - // Turn into byte array, so we can compare - byte[] byte_value = encoding.GetBytes(value); - int current = 0; - List seen = new List(); - - while (true) - { - int n = read_byte(); - if (n == -1) - break; - seen.Add((byte)n); - if (n == byte_value[current]) - { - current++; - if (current == byte_value.Length) - return encoding.GetString(seen.ToArray(), 0, seen.Count - byte_value.Length); - } - else - { - current = (byte_value[0] == n) ? 1 : 0; - } - } - return encoding.GetString(seen.ToArray()); - } - - public void Write(string str) - { - CheckOpen(); - if (str == null) - throw new ArgumentNullException("str"); - - byte[] buffer = encoding.GetBytes(str); - Write(buffer, 0, buffer.Length); - } - - public void Write(byte[] buffer, int offset, int count) - { - CheckOpen(); - 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."); - - stream.Write(buffer, offset, count); - } - - public void Write(char[] buffer, int offset, int count) - { - CheckOpen(); - 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."); - - byte[] bytes = encoding.GetBytes(buffer, offset, count); - stream.Write(bytes, 0, bytes.Length); - } - - public void WriteLine(string str) - { - Write(str + new_line); - } - - void CheckOpen() - { - if (!is_open) - throw new InvalidOperationException("Specified port is not open."); - } - - internal void OnErrorReceived(SerialErrorReceivedEventArgs args) - { - SerialErrorReceivedEventHandler handler = - (SerialErrorReceivedEventHandler)Events[error_received]; - - if (handler != null) - handler(this, args); - } - - internal void OnDataReceived(SerialDataReceivedEventArgs args) - { - SerialDataReceivedEventHandler handler = - (SerialDataReceivedEventHandler)Events[data_received]; - - if (handler != null) - handler(this, args); - } - - internal void OnDataReceived(SerialPinChangedEventArgs args) - { - SerialPinChangedEventHandler handler = - (SerialPinChangedEventHandler)Events[pin_changed]; - - if (handler != null) - handler(this, args); - } - - // events - [MonitoringDescription("")] - public event SerialErrorReceivedEventHandler ErrorReceived - { - add { Events.AddHandler(error_received, value); } - remove { Events.RemoveHandler(error_received, value); } - } - - [MonitoringDescription("")] - public event SerialPinChangedEventHandler PinChanged - { - add { Events.AddHandler(pin_changed, value); } - remove { Events.RemoveHandler(pin_changed, value); } - } - - [MonitoringDescription("")] - public event SerialDataReceivedEventHandler DataReceived - { - add { Events.AddHandler(data_received, value); } - remove { Events.RemoveHandler(data_received, value); } - } - } - - public delegate void SerialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e); - public delegate void SerialPinChangedEventHandler(object sender, SerialPinChangedEventArgs e); - public delegate void SerialErrorReceivedEventHandler(object sender, SerialErrorReceivedEventArgs e); -} diff --git a/FrostedSerial/FrostedSerialStream.cs b/FrostedSerial/FrostedSerialStream.cs deleted file mode 100644 index 3fc36d4ee..000000000 --- a/FrostedSerial/FrostedSerialStream.cs +++ /dev/null @@ -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."); - } - } - } -} - - - diff --git a/FrostedSerial/IFrostedSerialStream.cs b/FrostedSerial/IFrostedSerialStream.cs deleted file mode 100644 index ba7b41794..000000000 --- a/FrostedSerial/IFrostedSerialStream.cs +++ /dev/null @@ -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; } - } -} diff --git a/FrostedSerial/TermiosH.cs b/FrostedSerial/TermiosH.cs deleted file mode 100644 index 434dad4fb..000000000 --- a/FrostedSerial/TermiosH.cs +++ /dev/null @@ -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; - } - } -} - diff --git a/FrostedSerial/WinSerialStream.cs b/FrostedSerial/WinSerialStream.cs deleted file mode 100644 index 9933d5236..000000000 --- a/FrostedSerial/WinSerialStream.cs +++ /dev/null @@ -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; - } -} - - diff --git a/PrinterCommunication/PrinterCommunication.cs b/PrinterCommunication/PrinterCommunication.cs index bd6329279..a55534059 100644 --- a/PrinterCommunication/PrinterCommunication.cs +++ b/PrinterCommunication/PrinterCommunication.cs @@ -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 { diff --git a/PrinterControls/OutputScrollWindow.cs b/PrinterControls/OutputScrollWindow.cs index c1030732a..0bccfa0be 100644 --- a/PrinterControls/OutputScrollWindow.cs +++ b/PrinterControls/OutputScrollWindow.cs @@ -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 diff --git a/PrinterControls/SDCardManager.cs b/PrinterControls/SDCardManager.cs index 6be2e7264..6aabe3afc 100644 --- a/PrinterControls/SDCardManager.cs +++ b/PrinterControls/SDCardManager.cs @@ -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 {