Nefarius.Peripherals.Serial.../PInvokeSerialPort/SerialPort.cs

781 lines
27 KiB
C#
Raw Normal View History

2012-03-03 10:50:54 +01:00
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using PInvokeSerialPort.Win32PInvoke;
namespace PInvokeSerialPort
{
/// <summary>
2018-11-22 21:35:11 +01:00
/// PInvokeSerialPort main class.
/// Borrowed from http://msdn.microsoft.com/en-us/magazine/cc301786.aspx ;)
2012-03-03 10:50:54 +01:00
/// </summary>
public class SerialPort : IDisposable
{
2018-11-22 21:35:11 +01:00
private readonly ManualResetEvent _writeEvent = new ManualResetEvent(false);
2012-03-03 10:50:54 +01:00
private bool _auto;
private bool _checkSends = true;
2018-11-22 21:35:11 +01:00
private Handshake _handShake;
private IntPtr _hPort;
private bool _online;
private IntPtr _ptrUwo = IntPtr.Zero;
2012-03-03 10:50:54 +01:00
private Exception _rxException;
private bool _rxExceptionReported;
2018-11-22 21:35:11 +01:00
private Thread _rxThread;
2012-03-03 10:50:54 +01:00
private int _stateBrk = 2;
2018-11-22 21:35:11 +01:00
private int _stateDtr = 2;
private int _stateRts = 2;
private int _writeCount;
/// <summary>
/// If true, the port will automatically re-open on next send if it was previously closed due
/// to an error (default: false)
/// </summary>
public bool AutoReopen;
/// <summary>
/// Baud Rate (default: 2400) unsupported rates will throw "Bad settings"
/// </summary>
public int BaudRate = 115200;
/// <summary>
/// If true, subsequent Send commands wait for completion of earlier ones enabling the results
/// to be checked. If false, errors, including timeouts, may not be detected, but performance
/// may be better.
/// </summary>
public bool CheckAllSends = true;
/// <summary>
/// Number of databits 1..8 (default: 8) unsupported values will throw "Bad settings"
/// </summary>
public int DataBits = 8;
/// <summary>
/// The parity checking scheme (default: none)
/// </summary>
public Parity Parity = Parity.None;
/// <summary>
/// If true, Xon and Xoff characters are sent to control the data flow from the remote station (default: false)
/// </summary>
public bool RxFlowX;
/// <summary>
/// If true, received characters are ignored unless DSR is asserted by the remote station (default: false)
/// </summary>
public bool RxGateDsr;
/// <summary>
/// The number of free bytes in the reception queue at which flow is disabled (default: 2048)
/// </summary>
public int RxHighWater = 2048;
/// <summary>
/// The number of bytes in the reception queue at which flow is re-enabled (default: 512)
/// </summary>
public int RxLowWater = 512;
/// <summary>
/// Requested size for receive queue (default: 0 = use operating system default)
/// </summary>
public int RxQueue;
/// <summary>
/// Constant. Max time for Send in ms = (Multiplier * Characters) + Constant (default: 0)
/// </summary>
public int SendTimeoutConstant;
/// <summary>
/// Multiplier. Max time for Send in ms = (Multiplier * Characters) + Constant
/// (default: 0 = No timeout)
/// </summary>
public int SendTimeoutMultiplier;
/// <summary>
/// Number of stop bits (default: one)
/// </summary>
public StopBits StopBits = StopBits.One;
/// <summary>
/// If true, transmission is halted unless CTS is asserted by the remote station (default: false)
/// </summary>
public bool TxFlowCts;
/// <summary>
/// If true, transmission is halted unless DSR is asserted by the remote station (default: false)
/// </summary>
public bool TxFlowDsr;
/// <summary>
/// If true, transmission is halted when Xoff is received and restarted when Xon is received (default: false)
/// </summary>
public bool TxFlowX;
/// <summary>
/// Requested size for transmit queue (default: 0 = use operating system default)
/// </summary>
public int TxQueue;
/// <summary>
/// If false, transmission is suspended when this station has sent Xoff to the remote station (default: true)
/// Set false if the remote station treats any character as an Xon.
/// </summary>
public bool TxWhenRxXoff = true;
/// <summary>
/// Specidies the use to which the DTR output is put (default: none)
/// </summary>
public HsOutput UseDtr = HsOutput.None;
/// <summary>
/// Specifies the use to which the RTS output is put (default: none)
/// </summary>
public HsOutput UseRts = HsOutput.None;
2012-03-03 10:50:54 +01:00
/// <summary>
2018-11-22 21:35:11 +01:00
/// The character used to signal Xoff for X flow control (default: DC3)
/// </summary>
public ASCII XoffChar = ASCII.DC3;
/// <summary>
/// The character used to signal Xon for X flow control (default: DC1)
/// </summary>
public ASCII XonChar = ASCII.DC1;
/// <summary>
/// Class constructor
2012-03-03 10:50:54 +01:00
/// </summary>
public SerialPort(string portName)
{
PortName = portName;
}
/// <summary>
/// Class constructor
2012-03-03 10:50:54 +01:00
/// </summary>
public SerialPort(string portName, int baudRate)
{
PortName = portName;
BaudRate = baudRate;
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// True if online.
/// </summary>
public bool Online => _online && CheckOnline();
/// <summary>
/// True if the RTS pin is controllable via the RTS property
/// </summary>
protected bool RtSavailable => _stateRts < 2;
/// <summary>
/// Set the state of the RTS modem control output
/// </summary>
protected bool Rts
{
set
{
if (_stateRts > 1) return;
CheckOnline();
if (value)
{
if (Win32Com.EscapeCommFunction(_hPort, Win32Com.SETRTS))
_stateRts = 1;
else
ThrowException("Unexpected Failure");
}
else
{
if (Win32Com.EscapeCommFunction(_hPort, Win32Com.CLRRTS))
_stateRts = 1;
else
ThrowException("Unexpected Failure");
}
}
get => _stateRts == 1;
}
/// <summary>
/// True if the DTR pin is controllable via the DTR property
/// </summary>
protected bool DtrAvailable => _stateDtr < 2;
/// <summary>
/// The state of the DTR modem control output
/// </summary>
protected bool Dtr
{
set
{
if (_stateDtr > 1) return;
CheckOnline();
if (value)
{
if (Win32Com.EscapeCommFunction(_hPort, Win32Com.SETDTR))
_stateDtr = 1;
else
ThrowException("Unexpected Failure");
}
else
{
if (Win32Com.EscapeCommFunction(_hPort, Win32Com.CLRDTR))
_stateDtr = 0;
else
ThrowException("Unexpected Failure");
}
}
get => _stateDtr == 1;
}
/// <summary>
/// Assert or remove a break condition from the transmission line
/// </summary>
protected bool Break
{
set
{
if (_stateBrk > 1) return;
CheckOnline();
if (value)
{
if (Win32Com.EscapeCommFunction(_hPort, Win32Com.SETBREAK))
_stateBrk = 0;
else
ThrowException("Unexpected Failure");
}
else
{
if (Win32Com.EscapeCommFunction(_hPort, Win32Com.CLRBREAK))
_stateBrk = 0;
else
ThrowException("Unexpected Failure");
}
}
get => _stateBrk == 1;
}
/// <summary>
/// Port Name
/// </summary>
public string PortName { get; set; }
public Handshake Handshake
{
get => _handShake;
set
{
_handShake = value;
switch (_handShake)
{
case Handshake.None:
TxFlowCts = false;
TxFlowDsr = false;
TxFlowX = false;
RxFlowX = false;
UseRts = HsOutput.Online;
UseDtr = HsOutput.Online;
TxWhenRxXoff = true;
RxGateDsr = false;
break;
case Handshake.XonXoff:
TxFlowCts = false;
TxFlowDsr = false;
TxFlowX = true;
RxFlowX = true;
UseRts = HsOutput.Online;
UseDtr = HsOutput.Online;
TxWhenRxXoff = true;
RxGateDsr = false;
XonChar = ASCII.DC1;
XoffChar = ASCII.DC3;
break;
case Handshake.CtsRts:
TxFlowCts = true;
TxFlowDsr = false;
TxFlowX = false;
RxFlowX = false;
UseRts = HsOutput.Handshake;
UseDtr = HsOutput.Online;
TxWhenRxXoff = true;
RxGateDsr = false;
break;
case Handshake.DsrDtr:
TxFlowCts = false;
TxFlowDsr = true;
TxFlowX = false;
RxFlowX = false;
UseRts = HsOutput.Online;
UseDtr = HsOutput.Handshake;
TxWhenRxXoff = true;
RxGateDsr = false;
break;
}
}
}
/// <inheritdoc />
2018-11-22 21:35:11 +01:00
/// <summary>
/// For IDisposable
/// </summary>
public void Dispose()
{
Close();
}
/// <summary>
/// Opens the com port and configures it with the required settings
2012-03-03 10:50:54 +01:00
/// </summary>
/// <returns>false if the port could not be opened</returns>
public bool Open()
{
var portDcb = new DCB();
var commTimeouts = new COMMTIMEOUTS();
var wo = new OVERLAPPED();
if (_online) return false;
_hPort = Win32Com.CreateFile(PortName, Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE, 0, IntPtr.Zero,
Win32Com.OPEN_EXISTING, Win32Com.FILE_FLAG_OVERLAPPED, IntPtr.Zero);
2018-11-22 21:35:11 +01:00
if (_hPort == (IntPtr) Win32Com.INVALID_HANDLE_VALUE)
2012-03-03 10:50:54 +01:00
{
2018-11-22 21:35:11 +01:00
if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED) return false;
2012-03-03 10:50:54 +01:00
throw new CommPortException("Port Open Failure");
}
_online = true;
commTimeouts.ReadIntervalTimeout = 0;
commTimeouts.ReadTotalTimeoutConstant = 0;
commTimeouts.ReadTotalTimeoutMultiplier = 0;
commTimeouts.WriteTotalTimeoutConstant = SendTimeoutConstant;
commTimeouts.WriteTotalTimeoutMultiplier = SendTimeoutMultiplier;
2018-11-22 21:35:11 +01:00
portDcb.Init(Parity == Parity.Odd || Parity == Parity.Even, TxFlowCts, TxFlowDsr,
(int) UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int) UseRts);
2012-03-03 10:50:54 +01:00
portDcb.BaudRate = BaudRate;
2018-11-22 21:35:11 +01:00
portDcb.ByteSize = (byte) DataBits;
portDcb.Parity = (byte) Parity;
portDcb.StopBits = (byte) StopBits;
portDcb.XoffChar = (byte) XoffChar;
portDcb.XonChar = (byte) XonChar;
portDcb.XoffLim = (short) RxHighWater;
portDcb.XonLim = (short) RxLowWater;
if (RxQueue != 0 || TxQueue != 0)
if (!Win32Com.SetupComm(_hPort, (uint) RxQueue, (uint) TxQueue))
ThrowException("Bad queue settings");
2012-03-03 10:50:54 +01:00
if (!Win32Com.SetCommState(_hPort, ref portDcb)) ThrowException("Bad com settings");
if (!Win32Com.SetCommTimeouts(_hPort, ref commTimeouts)) ThrowException("Bad timeout settings");
_stateBrk = 0;
if (UseDtr == HsOutput.None) _stateDtr = 0;
if (UseDtr == HsOutput.Online) _stateDtr = 1;
if (UseRts == HsOutput.None) _stateRts = 0;
if (UseRts == HsOutput.Online) _stateRts = 1;
_checkSends = CheckAllSends;
wo.Offset = 0;
wo.OffsetHigh = 0;
wo.hEvent = _checkSends ? _writeEvent.Handle : IntPtr.Zero;
_ptrUwo = Marshal.AllocHGlobal(Marshal.SizeOf(wo));
Marshal.StructureToPtr(wo, _ptrUwo, true);
_writeCount = 0;
_rxException = null;
_rxExceptionReported = false;
_rxThread = new Thread(ReceiveThread)
2018-11-22 21:35:11 +01:00
{
Name = "CommBaseRx",
Priority = ThreadPriority.AboveNormal
};
//If not set to true, my application process will not exit completely after UI closed
_rxThread.IsBackground = true;
2012-03-03 10:50:54 +01:00
_rxThread.Start();
Thread.Sleep(1); //Give rx thread time to start. By documentation, 0 should work, but it does not!
_auto = false;
if (AfterOpen())
{
_auto = AutoReopen;
return true;
}
2018-11-22 21:35:11 +01:00
2012-03-03 10:50:54 +01:00
Close();
return false;
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Closes the com port.
2012-03-03 10:50:54 +01:00
/// </summary>
public void Close()
{
if (_online)
{
_auto = false;
BeforeClose(false);
InternalClose();
_rxException = null;
}
}
private void InternalClose()
{
Win32Com.CancelIo(_hPort);
if (_rxThread != null)
{
_rxThread.Abort();
_rxThread = null;
}
2018-11-22 21:35:11 +01:00
2012-03-03 10:50:54 +01:00
Win32Com.CloseHandle(_hPort);
if (_ptrUwo != IntPtr.Zero) Marshal.FreeHGlobal(_ptrUwo);
_stateRts = 2;
_stateDtr = 2;
_stateBrk = 2;
_online = false;
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Destructor (just in case)
2012-03-03 10:50:54 +01:00
/// </summary>
2018-11-22 21:35:11 +01:00
~SerialPort()
{
Close();
}
2012-03-03 10:50:54 +01:00
/// <summary>
2018-11-22 21:35:11 +01:00
/// Block until all bytes in the queue have been transmitted.
2012-03-03 10:50:54 +01:00
/// </summary>
public void Flush()
{
CheckOnline();
CheckResult();
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Use this to throw exceptions in derived classes. Correctly handles threading issues
/// and closes the port if necessary.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="reason">Description of fault</param>
protected void ThrowException(string reason)
{
2018-11-22 21:35:11 +01:00
if (Thread.CurrentThread == _rxThread) throw new CommPortException(reason);
2012-03-03 10:50:54 +01:00
if (_online)
{
BeforeClose(true);
InternalClose();
}
2018-11-22 21:35:11 +01:00
if (_rxException == null) throw new CommPortException(reason);
2012-03-03 10:50:54 +01:00
throw new CommPortException(_rxException);
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Queues bytes for transmission.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="toSend">Array of bytes to be sent</param>
public void Write(byte[] toSend)
{
uint sent;
CheckOnline();
CheckResult();
_writeCount = toSend.GetLength(0);
2018-11-22 21:35:11 +01:00
if (Win32Com.WriteFile(_hPort, toSend, (uint) _writeCount, out sent, _ptrUwo))
2012-03-03 10:50:54 +01:00
{
2018-11-22 21:35:11 +01:00
_writeCount -= (int) sent;
2012-03-03 10:50:54 +01:00
}
else
{
if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) ThrowException("Unexpected failure");
}
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Queues string for transmission.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="toSend">Array of bytes to be sent</param>
public void Write(string toSend)
{
Write(new ASCIIEncoding().GetBytes(toSend));
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Queues a single byte for transmission.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="toSend">Byte to be sent</param>
public void Write(byte toSend)
{
var b = new byte[1];
b[0] = toSend;
Write(b);
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Queues a single char for transmission.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="toSend">Byte to be sent</param>
public void Write(char toSend)
{
Write(toSend.ToString());
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Queues string with a new line ("\r\n") for transmission.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="toSend">Array of bytes to be sent</param>
public void WriteLine(string toSend)
{
Write(new ASCIIEncoding().GetBytes(toSend + Environment.NewLine));
}
private void CheckResult()
{
if (_writeCount <= 0) return;
uint sent;
if (Win32Com.GetOverlappedResult(_hPort, _ptrUwo, out sent, _checkSends))
{
2018-11-22 21:35:11 +01:00
_writeCount -= (int) sent;
2012-03-03 10:50:54 +01:00
if (_writeCount != 0) ThrowException("Send Timeout");
}
else
{
if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) ThrowException("Unexpected failure");
}
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Sends a protocol byte immediately ahead of any queued bytes.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="tosend">Byte to send</param>
/// <returns>False if an immediate byte is already scheduled and not yet sent</returns>
public void SendImmediate(byte tosend)
{
CheckOnline();
if (!Win32Com.TransmitCommChar(_hPort, tosend)) ThrowException("Transmission failure");
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Gets the status of the modem control input signals.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <returns>Modem status object</returns>
protected ModemStatus GetModemStatus()
{
uint f;
CheckOnline();
if (!Win32Com.GetCommModemStatus(_hPort, out f)) ThrowException("Unexpected failure");
return new ModemStatus(f);
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Get the status of the queues
2012-03-03 10:50:54 +01:00
/// </summary>
/// <returns>Queue status object</returns>
protected QueueStatus GetQueueStatus()
{
COMSTAT cs;
COMMPROP cp;
uint er;
CheckOnline();
if (!Win32Com.ClearCommError(_hPort, out er, out cs)) ThrowException("Unexpected failure");
if (!Win32Com.GetCommProperties(_hPort, out cp)) ThrowException("Unexpected failure");
return new QueueStatus(cs.Flags, cs.cbInQue, cs.cbOutQue, cp.dwCurrentRxQueue, cp.dwCurrentTxQueue);
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Override this to provide processing after the port is openned (i.e. to configure remote
/// device or just check presence).
2012-03-03 10:50:54 +01:00
/// </summary>
2018-11-22 21:35:11 +01:00
/// <returns>false to close the port again</returns>
protected virtual bool AfterOpen()
2012-03-03 10:50:54 +01:00
{
2018-11-22 21:35:11 +01:00
return true;
2012-03-03 10:50:54 +01:00
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Override this to provide processing prior to port closure.
2012-03-03 10:50:54 +01:00
/// </summary>
2018-11-22 21:35:11 +01:00
/// <param name="error">True if closing due to an error</param>
protected virtual void BeforeClose(bool error)
2012-03-03 10:50:54 +01:00
{
}
public event Action<byte> DataReceived;
2018-11-22 21:35:11 +01:00
2012-03-03 10:50:54 +01:00
/// <summary>
2018-11-22 21:35:11 +01:00
/// Override this to process received bytes.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="ch">The byte that was received</param>
protected void OnRxChar(byte ch)
{
DataReceived?.Invoke(ch);
2012-03-03 10:50:54 +01:00
}
/// <summary>
2018-11-22 21:35:11 +01:00
/// Override this to take action when transmission is complete (i.e. all bytes have actually
/// been sent, not just queued).
2012-03-03 10:50:54 +01:00
/// </summary>
2018-11-22 21:35:11 +01:00
protected virtual void OnTxDone()
{
}
2012-03-03 10:50:54 +01:00
/// <summary>
2018-11-22 21:35:11 +01:00
/// Override this to take action when a break condition is detected on the input line.
2012-03-03 10:50:54 +01:00
/// </summary>
2018-11-22 21:35:11 +01:00
protected virtual void OnBreak()
{
}
2012-03-03 10:50:54 +01:00
/// <summary>
/// Override this to take action when a ring condition is signaled by an attached modem.
2012-03-03 10:50:54 +01:00
/// </summary>
2018-11-22 21:35:11 +01:00
protected virtual void OnRing()
{
}
2012-03-03 10:50:54 +01:00
/// <summary>
2018-11-22 21:35:11 +01:00
/// Override this to take action when one or more modem status inputs change state
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="mask">The status inputs that have changed state</param>
/// <param name="state">The state of the status inputs</param>
2018-11-22 21:35:11 +01:00
protected virtual void OnStatusChange(ModemStatus mask, ModemStatus state)
{
}
2012-03-03 10:50:54 +01:00
/// <summary>
2018-11-22 21:35:11 +01:00
/// Override this to take action when the reception thread closes due to an exception being thrown.
2012-03-03 10:50:54 +01:00
/// </summary>
/// <param name="e">The exception which was thrown</param>
2018-11-22 21:35:11 +01:00
protected virtual void OnRxException(Exception e)
{
}
2012-03-03 10:50:54 +01:00
private void ReceiveThread()
{
2018-11-22 21:35:11 +01:00
var buf = new byte[1];
2012-03-03 10:50:54 +01:00
var sg = new AutoResetEvent(false);
var ov = new OVERLAPPED();
var unmanagedOv = Marshal.AllocHGlobal(Marshal.SizeOf(ov));
2018-11-22 21:35:11 +01:00
ov.Offset = 0;
ov.OffsetHigh = 0;
2012-03-03 10:50:54 +01:00
ov.hEvent = sg.Handle;
Marshal.StructureToPtr(ov, unmanagedOv, true);
uint eventMask = 0;
var uMask = Marshal.AllocHGlobal(Marshal.SizeOf(eventMask));
try
{
while (true)
{
2018-11-22 21:35:11 +01:00
if (!Win32Com.SetCommMask(_hPort,
Win32Com.EV_RXCHAR | Win32Com.EV_TXEMPTY | Win32Com.EV_CTS | Win32Com.EV_DSR
2012-03-03 10:50:54 +01:00
| Win32Com.EV_BREAK | Win32Com.EV_RLSD | Win32Com.EV_RING | Win32Com.EV_ERR))
throw new CommPortException("IO Error [001]");
Marshal.WriteInt32(uMask, 0);
if (!Win32Com.WaitCommEvent(_hPort, uMask, unmanagedOv))
{
if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING)
sg.WaitOne();
else
throw new CommPortException("IO Error [002]");
}
2018-11-22 21:35:11 +01:00
eventMask = (uint) Marshal.ReadInt32(uMask);
2012-03-03 10:50:54 +01:00
if ((eventMask & Win32Com.EV_ERR) != 0)
{
2018-11-22 21:35:11 +01:00
uint errs;
2012-03-03 10:50:54 +01:00
if (Win32Com.ClearCommError(_hPort, out errs, IntPtr.Zero))
{
var s = new StringBuilder("UART Error: ", 40);
if ((errs & Win32Com.CE_FRAME) != 0) s = s.Append("Framing,");
if ((errs & Win32Com.CE_IOE) != 0) s = s.Append("IO,");
if ((errs & Win32Com.CE_OVERRUN) != 0) s = s.Append("Overrun,");
if ((errs & Win32Com.CE_RXOVER) != 0) s = s.Append("Receive Cverflow,");
if ((errs & Win32Com.CE_RXPARITY) != 0) s = s.Append("Parity,");
if ((errs & Win32Com.CE_TXFULL) != 0) s = s.Append("Transmit Overflow,");
s.Length = s.Length - 1;
throw new CommPortException(s.ToString());
}
2018-11-22 21:35:11 +01:00
2012-03-03 10:50:54 +01:00
throw new CommPortException("IO Error [003]");
}
2018-11-22 21:35:11 +01:00
2012-03-03 10:50:54 +01:00
if ((eventMask & Win32Com.EV_RXCHAR) != 0)
{
uint gotbytes;
do
{
if (!Win32Com.ReadFile(_hPort, buf, 1, out gotbytes, unmanagedOv))
{
if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING)
{
Win32Com.CancelIo(_hPort);
gotbytes = 0;
}
else
{
throw new CommPortException("IO Error [004]");
}
}
2018-11-22 21:35:11 +01:00
2012-03-03 10:50:54 +01:00
if (gotbytes == 1) OnRxChar(buf[0]);
} while (gotbytes > 0);
}
2018-11-22 21:35:11 +01:00
if ((eventMask & Win32Com.EV_TXEMPTY) != 0) OnTxDone();
2012-03-03 10:50:54 +01:00
if ((eventMask & Win32Com.EV_BREAK) != 0) OnBreak();
uint i = 0;
if ((eventMask & Win32Com.EV_CTS) != 0) i |= Win32Com.MS_CTS_ON;
if ((eventMask & Win32Com.EV_DSR) != 0) i |= Win32Com.MS_DSR_ON;
if ((eventMask & Win32Com.EV_RLSD) != 0) i |= Win32Com.MS_RLSD_ON;
if ((eventMask & Win32Com.EV_RING) != 0) i |= Win32Com.MS_RING_ON;
if (i != 0)
{
uint f;
if (!Win32Com.GetCommModemStatus(_hPort, out f)) throw new CommPortException("IO Error [005]");
OnStatusChange(new ModemStatus(i), new ModemStatus(f));
}
}
}
catch (Exception e)
{
if (uMask != IntPtr.Zero) Marshal.FreeHGlobal(uMask);
if (unmanagedOv != IntPtr.Zero) Marshal.FreeHGlobal(unmanagedOv);
if (!(e is ThreadAbortException))
{
_rxException = e;
OnRxException(e);
}
}
}
private bool CheckOnline()
{
2018-11-22 21:35:11 +01:00
if (_rxException != null && !_rxExceptionReported)
2012-03-03 10:50:54 +01:00
{
_rxExceptionReported = true;
ThrowException("rx");
}
2018-11-22 21:35:11 +01:00
2012-03-03 10:50:54 +01:00
if (_online)
{
uint f;
if (Win32Com.GetHandleInformation(_hPort, out f)) return true;
ThrowException("Offline");
return false;
}
2018-11-22 21:35:11 +01:00
2012-03-03 10:50:54 +01:00
if (_auto)
2018-11-22 21:35:11 +01:00
if (Open())
return true;
2012-03-03 10:50:54 +01:00
ThrowException("Offline");
return false;
}
}
}