From 4f7a5b3f7b14f9862f51704ca41b8ccef95f4f31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 17:25:19 +0200 Subject: [PATCH 01/14] Works with test hardware --- .gitignore | 1 + Nefarius.Peripherals.SerialPort.sln | 12 ++-- .../Nefarius.Peripherals.SerialPort.csproj | 5 +- .../PInvokeSerialPort.Sample.csproj | 71 +++---------------- PInvokeSerialPort.Sample/Program.cs | 30 ++++---- .../Properties/AssemblyInfo.cs | 25 ------- .../PInvokeSerialPortTest.cs | 1 + 7 files changed, 39 insertions(+), 106 deletions(-) diff --git a/.gitignore b/.gitignore index d29d198..af5c6a9 100755 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,4 @@ _ReSharper*/ /packages /.tmp *.DotSettings +/misc diff --git a/Nefarius.Peripherals.SerialPort.sln b/Nefarius.Peripherals.SerialPort.sln index 3b5a375..0275349 100644 --- a/Nefarius.Peripherals.SerialPort.sln +++ b/Nefarius.Peripherals.SerialPort.sln @@ -1,9 +1,9 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29613.14 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32825.248 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PInvokeSerialPort", "Nefarius.Peripherals.SerialPort\Nefarius.Peripherals.SerialPort.csproj", "{AEC711A5-AA9B-4127-A82C-C4D8FDA9741A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Nefarius.Peripherals.SerialPort", "Nefarius.Peripherals.SerialPort\Nefarius.Peripherals.SerialPort.csproj", "{AEC711A5-AA9B-4127-A82C-C4D8FDA9741A}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{99052083-B245-462F-8778-4C94662ABABE}" ProjectSection(SolutionItems) = preProject @@ -49,12 +49,14 @@ Global {928609B4-70AB-4D93-A43E-4BE75C279066}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {928609B4-70AB-4D93-A43E-4BE75C279066}.Release|Mixed Platforms.Build.0 = Release|Any CPU {928609B4-70AB-4D93-A43E-4BE75C279066}.Release|x86.ActiveCfg = Release|Any CPU - {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Debug|Any CPU.ActiveCfg = Debug|x86 + {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Debug|Any CPU.Build.0 = Debug|Any CPU {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Debug|Mixed Platforms.Build.0 = Debug|x86 {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Debug|x86.ActiveCfg = Debug|x86 {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Debug|x86.Build.0 = Debug|x86 - {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Release|Any CPU.ActiveCfg = Release|x86 + {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Release|Any CPU.Build.0 = Release|Any CPU {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Release|Mixed Platforms.ActiveCfg = Release|x86 {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Release|Mixed Platforms.Build.0 = Release|x86 {76FAB402-7515-4A9B-8605-4FEC0736C78A}.Release|x86.ActiveCfg = Release|x86 diff --git a/Nefarius.Peripherals.SerialPort/Nefarius.Peripherals.SerialPort.csproj b/Nefarius.Peripherals.SerialPort/Nefarius.Peripherals.SerialPort.csproj index ce80c6b..c462703 100644 --- a/Nefarius.Peripherals.SerialPort/Nefarius.Peripherals.SerialPort.csproj +++ b/Nefarius.Peripherals.SerialPort/Nefarius.Peripherals.SerialPort.csproj @@ -17,9 +17,10 @@ latest - - + + + diff --git a/PInvokeSerialPort.Sample/PInvokeSerialPort.Sample.csproj b/PInvokeSerialPort.Sample/PInvokeSerialPort.Sample.csproj index 3582d0a..5777734 100755 --- a/PInvokeSerialPort.Sample/PInvokeSerialPort.Sample.csproj +++ b/PInvokeSerialPort.Sample/PInvokeSerialPort.Sample.csproj @@ -1,69 +1,18 @@ - - + - Debug - x86 8.0.30703 - 2.0 {76FAB402-7515-4A9B-8605-4FEC0736C78A} Exe - Properties - PInvokeSerialPort.Sample - PInvokeSerialPort.Sample - v4.6.1 - - - 512 - - - x86 - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - x86 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false + net6 + PInvokeSerialPort.Sample + PInvokeSerialPort.Sample + Copyright © 2012 + bin\$(Configuration)\ + latest + - - - - - - - + - - - - - - - {AEC711A5-AA9B-4127-A82C-C4D8FDA9741A} - PInvokeSerialPort - - - - - - - + \ No newline at end of file diff --git a/PInvokeSerialPort.Sample/Program.cs b/PInvokeSerialPort.Sample/Program.cs index 926e95c..0d3358f 100755 --- a/PInvokeSerialPort.Sample/Program.cs +++ b/PInvokeSerialPort.Sample/Program.cs @@ -1,19 +1,23 @@ using System; -using PInvokeSerialPort; +using Nefarius.Peripherals.SerialPort; -namespace PInvokeSerialPort.Sample +namespace PInvokeSerialPort.Sample; + +internal class Program { - class Program + private static void Main(string[] args) { - static void Main(string[] args) + var serialPort = new SerialPort("com7") { UseRts = HsOutput.Online }; + + serialPort.DataReceived += x => { - var serialPort = new SerialPort("com1", 14400); - serialPort.DataReceived += x => Console.Write((char)x); - serialPort.Open(); - while (true) - { - serialPort.Write(Console.ReadKey().KeyChar); - } - } + Console.Write($"{x:X2} "); + }; + + serialPort.Open(); + + serialPort.Write("START\r\n"); + + Console.ReadKey(); } -} +} \ No newline at end of file diff --git a/PInvokeSerialPort.Sample/Properties/AssemblyInfo.cs b/PInvokeSerialPort.Sample/Properties/AssemblyInfo.cs index 6d4480c..5dcf965 100755 --- a/PInvokeSerialPort.Sample/Properties/AssemblyInfo.cs +++ b/PInvokeSerialPort.Sample/Properties/AssemblyInfo.cs @@ -2,18 +2,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("PInvokeSerialPort.Sample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("PInvokeSerialPort.Sample")] -[assembly: AssemblyCopyright("Copyright © 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. @@ -21,16 +9,3 @@ using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9628528d-5e4d-4071-aad1-b1f85f3d45d5")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/PInvokeSerialPort.Test/PInvokeSerialPortTest.cs b/PInvokeSerialPort.Test/PInvokeSerialPortTest.cs index e1553f5..cddff64 100755 --- a/PInvokeSerialPort.Test/PInvokeSerialPortTest.cs +++ b/PInvokeSerialPort.Test/PInvokeSerialPortTest.cs @@ -2,6 +2,7 @@ using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading; +using Nefarius.Peripherals.SerialPort; namespace PInvokeSerialPort.Test { From e1cfa9647bab2771d9ef9b020f5b90617a7799d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 17:26:15 +0200 Subject: [PATCH 02/14] Added missing native type --- Nefarius.Peripherals.SerialPort/NativeMethods.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Nefarius.Peripherals.SerialPort/NativeMethods.txt b/Nefarius.Peripherals.SerialPort/NativeMethods.txt index c2b548f..e754077 100644 --- a/Nefarius.Peripherals.SerialPort/NativeMethods.txt +++ b/Nefarius.Peripherals.SerialPort/NativeMethods.txt @@ -1,4 +1,4 @@ -CreateFile +CreateFile GetHandleInformation SetCommState SetCommTimeouts @@ -13,4 +13,5 @@ EscapeCommFunction GetCommModemStatus GetOverlappedResult ClearCommError -GetCommProperties \ No newline at end of file +GetCommProperties +WIN32_ERROR \ No newline at end of file From e9c761631ba1a771534693c73acbd572401540df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 17:30:39 +0200 Subject: [PATCH 03/14] Updated to VS 2022 --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 960a63b..9cd4246 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,5 +1,5 @@ version: 1.0.{build} -image: Visual Studio 2019 +image: Visual Studio 2022 configuration: - Release install: From 01fb988c89e8a778d53cc2c5ea7b42b0728735e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 17:36:44 +0200 Subject: [PATCH 04/14] Migrated CreateFile --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 60 ++++++++++--------- 1 file changed, 32 insertions(+), 28 deletions(-) diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index 673e2a5..c95069e 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -2,6 +2,9 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Windows.Win32; +using Windows.Win32.Storage.FileSystem; +using Microsoft.Win32.SafeHandles; using Nefarius.Peripherals.SerialPort.Win32PInvoke; namespace Nefarius.Peripherals.SerialPort @@ -19,7 +22,7 @@ namespace Nefarius.Peripherals.SerialPort private bool _checkSends = true; private Handshake _handShake; - private IntPtr _hPort; + private SafeFileHandle _hPort; private bool _online; private IntPtr _ptrUwo = IntPtr.Zero; private Exception _rxException; @@ -188,14 +191,14 @@ namespace Nefarius.Peripherals.SerialPort CheckOnline(); if (value) { - if (Win32Com.EscapeCommFunction(_hPort, Win32Com.SETRTS)) + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETRTS)) _stateRts = 1; else ThrowException("Unexpected Failure"); } else { - if (Win32Com.EscapeCommFunction(_hPort, Win32Com.CLRRTS)) + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRRTS)) _stateRts = 1; else ThrowException("Unexpected Failure"); @@ -220,14 +223,14 @@ namespace Nefarius.Peripherals.SerialPort CheckOnline(); if (value) { - if (Win32Com.EscapeCommFunction(_hPort, Win32Com.SETDTR)) + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETDTR)) _stateDtr = 1; else ThrowException("Unexpected Failure"); } else { - if (Win32Com.EscapeCommFunction(_hPort, Win32Com.CLRDTR)) + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRDTR)) _stateDtr = 0; else ThrowException("Unexpected Failure"); @@ -247,14 +250,14 @@ namespace Nefarius.Peripherals.SerialPort CheckOnline(); if (value) { - if (Win32Com.EscapeCommFunction(_hPort, Win32Com.SETBREAK)) + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETBREAK)) _stateBrk = 0; else ThrowException("Unexpected Failure"); } else { - if (Win32Com.EscapeCommFunction(_hPort, Win32Com.CLRBREAK)) + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRBREAK)) _stateBrk = 0; else ThrowException("Unexpected Failure"); @@ -345,10 +348,11 @@ namespace Nefarius.Peripherals.SerialPort var wo = new OVERLAPPED(); if (_online) return false; + + _hPort = PInvoke.CreateFile(PortName, FILE_ACCESS_FLAGS.FILE_GENERIC_READ | FILE_ACCESS_FLAGS.FILE_GENERIC_WRITE, 0, + null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_OVERLAPPED, null); - _hPort = Win32Com.CreateFile(PortName, Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE, 0, IntPtr.Zero, - Win32Com.OPEN_EXISTING, Win32Com.FILE_FLAG_OVERLAPPED, IntPtr.Zero); - if (_hPort == (IntPtr) Win32Com.INVALID_HANDLE_VALUE) + if (_hPort.IsInvalid) { if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED) return false; throw new CommPortException("Port Open Failure"); @@ -372,10 +376,10 @@ namespace Nefarius.Peripherals.SerialPort portDcb.XoffLim = (short) RxHighWater; portDcb.XonLim = (short) RxLowWater; if (RxQueue != 0 || TxQueue != 0) - if (!Win32Com.SetupComm(_hPort, (uint) RxQueue, (uint) TxQueue)) + if (!Win32Com.SetupComm(_hPort.DangerousGetHandle(), (uint) RxQueue, (uint) TxQueue)) ThrowException("Bad queue settings"); - if (!Win32Com.SetCommState(_hPort, ref portDcb)) ThrowException("Bad com settings"); - if (!Win32Com.SetCommTimeouts(_hPort, ref commTimeouts)) ThrowException("Bad timeout settings"); + if (!Win32Com.SetCommState(_hPort.DangerousGetHandle(), ref portDcb)) ThrowException("Bad com settings"); + if (!Win32Com.SetCommTimeouts(_hPort.DangerousGetHandle(), ref commTimeouts)) ThrowException("Bad timeout settings"); _stateBrk = 0; switch (UseDtr) @@ -445,14 +449,14 @@ namespace Nefarius.Peripherals.SerialPort private void InternalClose() { - Win32Com.CancelIo(_hPort); + Win32Com.CancelIo(_hPort.DangerousGetHandle()); if (_rxThread != null) { _rxThread.Abort(); _rxThread = null; } - Win32Com.CloseHandle(_hPort); + _hPort.Dispose(); if (_ptrUwo != IntPtr.Zero) Marshal.FreeHGlobal(_ptrUwo); _stateRts = 2; _stateDtr = 2; @@ -505,7 +509,7 @@ namespace Nefarius.Peripherals.SerialPort CheckOnline(); CheckResult(); _writeCount = toSend.GetLength(0); - if (Win32Com.WriteFile(_hPort, toSend, (uint) _writeCount, out sent, _ptrUwo)) + if (Win32Com.WriteFile(_hPort.DangerousGetHandle(), toSend, (uint) _writeCount, out sent, _ptrUwo)) { _writeCount -= (int) sent; } @@ -557,7 +561,7 @@ namespace Nefarius.Peripherals.SerialPort { if (_writeCount <= 0) return; uint sent; - if (Win32Com.GetOverlappedResult(_hPort, _ptrUwo, out sent, _checkSends)) + if (Win32Com.GetOverlappedResult(_hPort.DangerousGetHandle(), _ptrUwo, out sent, _checkSends)) { _writeCount -= (int) sent; if (_writeCount != 0) ThrowException("Send Timeout"); @@ -576,7 +580,7 @@ namespace Nefarius.Peripherals.SerialPort public void SendImmediate(byte tosend) { CheckOnline(); - if (!Win32Com.TransmitCommChar(_hPort, tosend)) ThrowException("Transmission failure"); + if (!Win32Com.TransmitCommChar(_hPort.DangerousGetHandle(), tosend)) ThrowException("Transmission failure"); } /// @@ -588,7 +592,7 @@ namespace Nefarius.Peripherals.SerialPort uint f; CheckOnline(); - if (!Win32Com.GetCommModemStatus(_hPort, out f)) ThrowException("Unexpected failure"); + if (!Win32Com.GetCommModemStatus(_hPort.DangerousGetHandle(), out f)) ThrowException("Unexpected failure"); return new ModemStatus(f); } @@ -604,8 +608,8 @@ namespace Nefarius.Peripherals.SerialPort uint er; CheckOnline(); - if (!Win32Com.ClearCommError(_hPort, out er, out cs)) ThrowException("Unexpected failure"); - if (!Win32Com.GetCommProperties(_hPort, out cp)) ThrowException("Unexpected failure"); + if (!Win32Com.ClearCommError(_hPort.DangerousGetHandle(), out er, out cs)) ThrowException("Unexpected failure"); + if (!Win32Com.GetCommProperties(_hPort.DangerousGetHandle(), out cp)) ThrowException("Unexpected failure"); return new QueueStatus(cs.Flags, cs.cbInQue, cs.cbOutQue, cp.dwCurrentRxQueue, cp.dwCurrentTxQueue); } @@ -696,12 +700,12 @@ namespace Nefarius.Peripherals.SerialPort { while (true) { - if (!Win32Com.SetCommMask(_hPort, + if (!Win32Com.SetCommMask(_hPort.DangerousGetHandle(), Win32Com.EV_RXCHAR | Win32Com.EV_TXEMPTY | Win32Com.EV_CTS | Win32Com.EV_DSR | 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 (!Win32Com.WaitCommEvent(_hPort.DangerousGetHandle(), uMask, unmanagedOv)) { if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) sg.WaitOne(); @@ -713,7 +717,7 @@ namespace Nefarius.Peripherals.SerialPort if ((eventMask & Win32Com.EV_ERR) != 0) { uint errs; - if (Win32Com.ClearCommError(_hPort, out errs, IntPtr.Zero)) + if (Win32Com.ClearCommError(_hPort.DangerousGetHandle(), out errs, IntPtr.Zero)) { var s = new StringBuilder("UART Error: ", 40); if ((errs & Win32Com.CE_FRAME) != 0) s = s.Append("Framing,"); @@ -734,11 +738,11 @@ namespace Nefarius.Peripherals.SerialPort uint gotbytes; do { - if (!Win32Com.ReadFile(_hPort, buf, 1, out gotbytes, unmanagedOv)) + if (!Win32Com.ReadFile(_hPort.DangerousGetHandle(), buf, 1, out gotbytes, unmanagedOv)) { if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) { - Win32Com.CancelIo(_hPort); + Win32Com.CancelIo(_hPort.DangerousGetHandle()); gotbytes = 0; } else @@ -762,7 +766,7 @@ namespace Nefarius.Peripherals.SerialPort if (i != 0) { uint f; - if (!Win32Com.GetCommModemStatus(_hPort, out f)) throw new CommPortException("IO Error [005]"); + if (!Win32Com.GetCommModemStatus(_hPort.DangerousGetHandle(), out f)) throw new CommPortException("IO Error [005]"); OnStatusChange(new ModemStatus(i), new ModemStatus(f)); } } @@ -790,7 +794,7 @@ namespace Nefarius.Peripherals.SerialPort if (_online) { uint f; - if (Win32Com.GetHandleInformation(_hPort, out f)) return true; + if (Win32Com.GetHandleInformation(_hPort.DangerousGetHandle(), out f)) return true; ThrowException("Offline"); return false; } From 59a094b949951ed83b9d67e3e468405f0aaafbbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 17:37:39 +0200 Subject: [PATCH 05/14] Minor clean-up --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index c95069e..c6655c6 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -365,7 +365,7 @@ namespace Nefarius.Peripherals.SerialPort commTimeouts.ReadTotalTimeoutMultiplier = 0; commTimeouts.WriteTotalTimeoutConstant = SendTimeoutConstant; commTimeouts.WriteTotalTimeoutMultiplier = SendTimeoutMultiplier; - portDcb.Init(Parity == Parity.Odd || Parity == Parity.Even, TxFlowCts, TxFlowDsr, + portDcb.Init(Parity is Parity.Odd or Parity.Even, TxFlowCts, TxFlowDsr, (int) UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int) UseRts); portDcb.BaudRate = BaudRate; portDcb.ByteSize = (byte) DataBits; From 3040660d64f946baa9a9bbecfce7d1699a73100f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 17:38:55 +0200 Subject: [PATCH 06/14] Added extension method --- Nefarius.Peripherals.SerialPort/Util.cs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Nefarius.Peripherals.SerialPort/Util.cs diff --git a/Nefarius.Peripherals.SerialPort/Util.cs b/Nefarius.Peripherals.SerialPort/Util.cs new file mode 100644 index 0000000..c0f22b0 --- /dev/null +++ b/Nefarius.Peripherals.SerialPort/Util.cs @@ -0,0 +1,23 @@ +using Windows.Win32.Devices.Communication; + +namespace Nefarius.Peripherals.SerialPort; + +internal static class DCBExtensions +{ + public static void Init(this DCB dcb, bool parity, bool outCts, bool outDsr, int dtr, bool inDsr, bool txc, + bool xOut, + bool xIn, int rts) + { + dcb.DCBlength = 28; + dcb._bitfield = 0x8001; + if (parity) dcb._bitfield |= 0x0002; + if (outCts) dcb._bitfield |= 0x0004; + if (outDsr) dcb._bitfield |= 0x0008; + dcb._bitfield |= (uint)((dtr & 0x0003) << 4); + if (inDsr) dcb._bitfield |= 0x0040; + if (txc) dcb._bitfield |= 0x0080; + if (xOut) dcb._bitfield |= 0x0100; + if (xIn) dcb._bitfield |= 0x0200; + dcb._bitfield |= (uint)((rts & 0x0003) << 12); + } +} \ No newline at end of file From d04267250ca4c8ec78adb50d8615eb24d97d9cbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 17:46:48 +0200 Subject: [PATCH 07/14] Formatting --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index c6655c6..3d46611 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -375,11 +375,16 @@ namespace Nefarius.Peripherals.SerialPort portDcb.XonChar = (byte) XonChar; portDcb.XoffLim = (short) RxHighWater; portDcb.XonLim = (short) RxLowWater; + if (RxQueue != 0 || TxQueue != 0) if (!Win32Com.SetupComm(_hPort.DangerousGetHandle(), (uint) RxQueue, (uint) TxQueue)) ThrowException("Bad queue settings"); - if (!Win32Com.SetCommState(_hPort.DangerousGetHandle(), ref portDcb)) ThrowException("Bad com settings"); - if (!Win32Com.SetCommTimeouts(_hPort.DangerousGetHandle(), ref commTimeouts)) ThrowException("Bad timeout settings"); + + if (!Win32Com.SetCommState(_hPort.DangerousGetHandle(), ref portDcb)) + ThrowException("Bad com settings"); + + if (!Win32Com.SetCommTimeouts(_hPort.DangerousGetHandle(), ref commTimeouts)) + ThrowException("Bad timeout settings"); _stateBrk = 0; switch (UseDtr) From 91159c3643b33f7951645acf16e8234d3010b6ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 17:58:42 +0200 Subject: [PATCH 08/14] Fixed SetCommState --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 52 +++++++++++-------- Nefarius.Peripherals.SerialPort/Util.cs | 2 +- 2 files changed, 31 insertions(+), 23 deletions(-) diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index 3d46611..5c8b1b5 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -3,9 +3,15 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading; using Windows.Win32; +using Windows.Win32.Devices.Communication; +using Windows.Win32.Foundation; using Windows.Win32.Storage.FileSystem; using Microsoft.Win32.SafeHandles; using Nefarius.Peripherals.SerialPort.Win32PInvoke; +using COMMPROP = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMMPROP; +using COMMTIMEOUTS = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMMTIMEOUTS; +using COMSTAT = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMSTAT; +using DCB = Windows.Win32.Devices.Communication.DCB; namespace Nefarius.Peripherals.SerialPort { @@ -348,7 +354,7 @@ namespace Nefarius.Peripherals.SerialPort var wo = new OVERLAPPED(); if (_online) return false; - + _hPort = PInvoke.CreateFile(PortName, FILE_ACCESS_FLAGS.FILE_GENERIC_READ | FILE_ACCESS_FLAGS.FILE_GENERIC_WRITE, 0, null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_OVERLAPPED, null); @@ -366,24 +372,24 @@ namespace Nefarius.Peripherals.SerialPort commTimeouts.WriteTotalTimeoutConstant = SendTimeoutConstant; commTimeouts.WriteTotalTimeoutMultiplier = SendTimeoutMultiplier; portDcb.Init(Parity is Parity.Odd or Parity.Even, TxFlowCts, TxFlowDsr, - (int) UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int) UseRts); - portDcb.BaudRate = BaudRate; - 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; + (int)UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int)UseRts); + portDcb.BaudRate = (uint)BaudRate; + portDcb.ByteSize = (byte)DataBits; + portDcb.Parity = (DCB_PARITY)Parity; + portDcb.StopBits = (DCB_STOP_BITS)StopBits; + portDcb.XoffChar = (CHAR)(byte)XoffChar; + portDcb.XonChar = (CHAR)(byte)XonChar; + portDcb.XoffLim = (ushort)RxHighWater; + portDcb.XonLim = (ushort)RxLowWater; if (RxQueue != 0 || TxQueue != 0) - if (!Win32Com.SetupComm(_hPort.DangerousGetHandle(), (uint) RxQueue, (uint) TxQueue)) + if (!Win32Com.SetupComm(_hPort.DangerousGetHandle(), (uint)RxQueue, (uint)TxQueue)) ThrowException("Bad queue settings"); - - if (!Win32Com.SetCommState(_hPort.DangerousGetHandle(), ref portDcb)) + + if (!PInvoke.SetCommState(_hPort, portDcb)) ThrowException("Bad com settings"); - - if (!Win32Com.SetCommTimeouts(_hPort.DangerousGetHandle(), ref commTimeouts)) + + if (!Win32Com.SetCommTimeouts(_hPort.DangerousGetHandle(), ref commTimeouts)) ThrowException("Bad timeout settings"); _stateBrk = 0; @@ -417,13 +423,15 @@ namespace Nefarius.Peripherals.SerialPort _rxException = null; _rxExceptionReported = false; - + // TODO: utilize Task Parallel Library here _rxThread = new Thread(ReceiveThread) { - Name = "CommBaseRx", Priority = ThreadPriority.AboveNormal, IsBackground = true + Name = "CommBaseRx", + Priority = ThreadPriority.AboveNormal, + IsBackground = true }; - + _rxThread.Start(); Thread.Sleep(1); //Give rx thread time to start. By documentation, 0 should work, but it does not! @@ -514,9 +522,9 @@ namespace Nefarius.Peripherals.SerialPort CheckOnline(); CheckResult(); _writeCount = toSend.GetLength(0); - if (Win32Com.WriteFile(_hPort.DangerousGetHandle(), toSend, (uint) _writeCount, out sent, _ptrUwo)) + if (Win32Com.WriteFile(_hPort.DangerousGetHandle(), toSend, (uint)_writeCount, out sent, _ptrUwo)) { - _writeCount -= (int) sent; + _writeCount -= (int)sent; } else { @@ -568,7 +576,7 @@ namespace Nefarius.Peripherals.SerialPort uint sent; if (Win32Com.GetOverlappedResult(_hPort.DangerousGetHandle(), _ptrUwo, out sent, _checkSends)) { - _writeCount -= (int) sent; + _writeCount -= (int)sent; if (_writeCount != 0) ThrowException("Send Timeout"); } else @@ -718,7 +726,7 @@ namespace Nefarius.Peripherals.SerialPort throw new CommPortException("IO Error [002]"); } - eventMask = (uint) Marshal.ReadInt32(uMask); + eventMask = (uint)Marshal.ReadInt32(uMask); if ((eventMask & Win32Com.EV_ERR) != 0) { uint errs; diff --git a/Nefarius.Peripherals.SerialPort/Util.cs b/Nefarius.Peripherals.SerialPort/Util.cs index c0f22b0..72774af 100644 --- a/Nefarius.Peripherals.SerialPort/Util.cs +++ b/Nefarius.Peripherals.SerialPort/Util.cs @@ -4,7 +4,7 @@ namespace Nefarius.Peripherals.SerialPort; internal static class DCBExtensions { - public static void Init(this DCB dcb, bool parity, bool outCts, bool outDsr, int dtr, bool inDsr, bool txc, + public static void Init(this ref DCB dcb, bool parity, bool outCts, bool outDsr, int dtr, bool inDsr, bool txc, bool xOut, bool xIn, int rts) { From 4617c69206295abe7c604576a875a0da6453a71d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 18:01:15 +0200 Subject: [PATCH 09/14] Clean-up --- .../Win32PInvoke/DCB.cs | 41 ------------------- .../Win32PInvoke/Win32Com.cs | 17 +------- 2 files changed, 1 insertion(+), 57 deletions(-) delete mode 100644 Nefarius.Peripherals.SerialPort/Win32PInvoke/DCB.cs diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/DCB.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/DCB.cs deleted file mode 100644 index ff3bee2..0000000 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/DCB.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Nefarius.Peripherals.SerialPort.Win32PInvoke -{ - [StructLayout(LayoutKind.Sequential)] - internal struct DCB - { - internal Int32 DCBlength; - internal Int32 BaudRate; - internal Int32 PackedValues; - internal Int16 wReserved; - internal Int16 XonLim; - internal Int16 XoffLim; - internal Byte ByteSize; - internal Byte Parity; - internal Byte StopBits; - internal Byte XonChar; - internal Byte XoffChar; - internal Byte ErrorChar; - internal Byte EofChar; - internal Byte EvtChar; - internal Int16 wReserved1; - - internal void Init(bool parity, bool outCts, bool outDsr, int dtr, bool inDsr, bool txc, bool xOut, - bool xIn, int rts) - { - DCBlength = 28; PackedValues = 0x8001; - if (parity) PackedValues |= 0x0002; - if (outCts) PackedValues |= 0x0004; - if (outDsr) PackedValues |= 0x0008; - PackedValues |= ((dtr & 0x0003) << 4); - if (inDsr) PackedValues |= 0x0040; - if (txc) PackedValues |= 0x0080; - if (xOut) PackedValues |= 0x0100; - if (xIn) PackedValues |= 0x0200; - PackedValues |= ((rts & 0x0003) << 12); - - } - } -} \ No newline at end of file diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs index cd2cbb7..9bf4895 100644 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs +++ b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs @@ -32,9 +32,6 @@ namespace Nefarius.Peripherals.SerialPort.Win32PInvoke internal const UInt32 GENERIC_READ = 0x80000000; internal const UInt32 GENERIC_WRITE = 0x40000000; - [DllImport("kernel32.dll")] - internal static extern Boolean CloseHandle(IntPtr hObject); - [DllImport("kernel32.dll")] internal static extern Boolean GetHandleInformation(IntPtr hObject, out UInt32 lpdwFlags); @@ -42,19 +39,7 @@ namespace Nefarius.Peripherals.SerialPort.Win32PInvoke /// /// Manipulating the communications settings. /// - - [DllImport("kernel32.dll")] - internal static extern Boolean GetCommState(IntPtr hFile, ref DCB lpDCB); - - [DllImport("kernel32.dll")] - internal static extern Boolean GetCommTimeouts(IntPtr hFile, out COMMTIMEOUTS lpCommTimeouts); - - [DllImport("kernel32.dll")] - internal static extern Boolean BuildCommDCBAndTimeouts(String lpDef, ref DCB lpDCB, ref COMMTIMEOUTS lpCommTimeouts); - - [DllImport("kernel32.dll")] - internal static extern Boolean SetCommState(IntPtr hFile, [In] ref DCB lpDCB); - + [DllImport("kernel32.dll")] internal static extern Boolean SetCommTimeouts(IntPtr hFile, [In] ref COMMTIMEOUTS lpCommTimeouts); From 2a23da6db556fa3f03ef00b14a85c4496001a7a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 19:03:33 +0200 Subject: [PATCH 10/14] Ported more code --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 9 +++--- .../Win32PInvoke/COMMTIMEOUTS.cs | 15 ---------- .../Win32PInvoke/Win32Com.cs | 29 ------------------- 3 files changed, 4 insertions(+), 49 deletions(-) delete mode 100644 Nefarius.Peripherals.SerialPort/Win32PInvoke/COMMTIMEOUTS.cs diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index 5c8b1b5..d4ea3d5 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -9,7 +9,6 @@ using Windows.Win32.Storage.FileSystem; using Microsoft.Win32.SafeHandles; using Nefarius.Peripherals.SerialPort.Win32PInvoke; using COMMPROP = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMMPROP; -using COMMTIMEOUTS = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMMTIMEOUTS; using COMSTAT = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMSTAT; using DCB = Windows.Win32.Devices.Communication.DCB; @@ -369,8 +368,8 @@ namespace Nefarius.Peripherals.SerialPort commTimeouts.ReadIntervalTimeout = 0; commTimeouts.ReadTotalTimeoutConstant = 0; commTimeouts.ReadTotalTimeoutMultiplier = 0; - commTimeouts.WriteTotalTimeoutConstant = SendTimeoutConstant; - commTimeouts.WriteTotalTimeoutMultiplier = SendTimeoutMultiplier; + commTimeouts.WriteTotalTimeoutConstant = (uint)SendTimeoutConstant; + commTimeouts.WriteTotalTimeoutMultiplier = (uint)SendTimeoutMultiplier; portDcb.Init(Parity is Parity.Odd or Parity.Even, TxFlowCts, TxFlowDsr, (int)UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int)UseRts); portDcb.BaudRate = (uint)BaudRate; @@ -383,13 +382,13 @@ namespace Nefarius.Peripherals.SerialPort portDcb.XonLim = (ushort)RxLowWater; if (RxQueue != 0 || TxQueue != 0) - if (!Win32Com.SetupComm(_hPort.DangerousGetHandle(), (uint)RxQueue, (uint)TxQueue)) + if (!PInvoke.SetupComm(_hPort, (uint)RxQueue, (uint)TxQueue)) ThrowException("Bad queue settings"); if (!PInvoke.SetCommState(_hPort, portDcb)) ThrowException("Bad com settings"); - if (!Win32Com.SetCommTimeouts(_hPort.DangerousGetHandle(), ref commTimeouts)) + if (!PInvoke.SetCommTimeouts(_hPort, commTimeouts)) ThrowException("Bad timeout settings"); _stateBrk = 0; diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMMTIMEOUTS.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMMTIMEOUTS.cs deleted file mode 100644 index 6f74e2b..0000000 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMMTIMEOUTS.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Nefarius.Peripherals.SerialPort.Win32PInvoke -{ - [StructLayout(LayoutKind.Sequential)] - internal struct COMMTIMEOUTS - { - internal Int32 ReadIntervalTimeout; - internal Int32 ReadTotalTimeoutMultiplier; - internal Int32 ReadTotalTimeoutConstant; - internal Int32 WriteTotalTimeoutMultiplier; - internal Int32 WriteTotalTimeoutConstant; - } -} \ No newline at end of file diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs index 9bf4895..58b9e11 100644 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs +++ b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs @@ -5,33 +5,10 @@ namespace Nefarius.Peripherals.SerialPort.Win32PInvoke { internal class Win32Com { - /// - /// Opening Testing and Closing the Port Handle. - /// - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern IntPtr CreateFile(String lpFileName, UInt32 dwDesiredAccess, UInt32 dwShareMode, - IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition, UInt32 dwFlagsAndAttributes, - IntPtr hTemplateFile); - //Constants for errors: - internal const UInt32 ERROR_FILE_NOT_FOUND = 2; - internal const UInt32 ERROR_INVALID_NAME = 123; internal const UInt32 ERROR_ACCESS_DENIED = 5; internal const UInt32 ERROR_IO_PENDING = 997; - //Constants for return value: - internal const Int32 INVALID_HANDLE_VALUE = -1; - - //Constants for dwFlagsAndAttributes: - internal const UInt32 FILE_FLAG_OVERLAPPED = 0x40000000; - - //Constants for dwCreationDisposition: - internal const UInt32 OPEN_EXISTING = 3; - - //Constants for dwDesiredAccess: - internal const UInt32 GENERIC_READ = 0x80000000; - internal const UInt32 GENERIC_WRITE = 0x40000000; - [DllImport("kernel32.dll")] internal static extern Boolean GetHandleInformation(IntPtr hObject, out UInt32 lpdwFlags); @@ -40,12 +17,6 @@ namespace Nefarius.Peripherals.SerialPort.Win32PInvoke /// Manipulating the communications settings. /// - [DllImport("kernel32.dll")] - internal static extern Boolean SetCommTimeouts(IntPtr hFile, [In] ref COMMTIMEOUTS lpCommTimeouts); - - [DllImport("kernel32.dll")] - internal static extern Boolean SetupComm(IntPtr hFile, UInt32 dwInQueue, UInt32 dwOutQueue); - /// /// Reading and writing. /// From b9ac62bbfd5bbd59128deec9521ade246dc27532 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 19:09:40 +0200 Subject: [PATCH 11/14] Ported more code --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 1500 ++++++++--------- 1 file changed, 749 insertions(+), 751 deletions(-) diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index d4ea3d5..8d58f3f 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -10,812 +10,810 @@ using Microsoft.Win32.SafeHandles; using Nefarius.Peripherals.SerialPort.Win32PInvoke; using COMMPROP = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMMPROP; using COMSTAT = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMSTAT; -using DCB = Windows.Win32.Devices.Communication.DCB; -namespace Nefarius.Peripherals.SerialPort +namespace Nefarius.Peripherals.SerialPort; + +/// +/// PInvokeSerialPort main class. +/// Borrowed from http://msdn.microsoft.com/en-us/magazine/cc301786.aspx ;) +/// +public class SerialPort : IDisposable { + /// /// - /// PInvokeSerialPort main class. - /// Borrowed from http://msdn.microsoft.com/en-us/magazine/cc301786.aspx ;) + /// For IDisposable /// - public class SerialPort : IDisposable + public void Dispose() { - #region Private fields + Close(); + } - private readonly ManualResetEvent _writeEvent = new ManualResetEvent(false); - private bool _auto; - private bool _checkSends = true; + /// + /// Opens the com port and configures it with the required settings + /// + /// false if the port could not be opened + public bool Open() + { + var portDcb = new DCB(); + var commTimeouts = new COMMTIMEOUTS(); - private Handshake _handShake; - private SafeFileHandle _hPort; - private bool _online; - private IntPtr _ptrUwo = IntPtr.Zero; - private Exception _rxException; - private bool _rxExceptionReported; - private Thread _rxThread; - private int _stateBrk = 2; - private int _stateDtr = 2; - private int _stateRts = 2; - private int _writeCount; + if (_online) return false; - #endregion + _hPort = PInvoke.CreateFile(PortName, + FILE_ACCESS_FLAGS.FILE_GENERIC_READ | FILE_ACCESS_FLAGS.FILE_GENERIC_WRITE, 0, + null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_OVERLAPPED, null); - #region Public properties - - /// - /// Class constructor - /// - public SerialPort(string portName) + if (_hPort.IsInvalid) { - PortName = portName; + if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED) return false; + throw new CommPortException("Port Open Failure"); } - /// - /// - /// Class constructor - /// - public SerialPort(string portName, int baudRate) : this(portName) + _online = true; + + commTimeouts.ReadIntervalTimeout = 0; + commTimeouts.ReadTotalTimeoutConstant = 0; + commTimeouts.ReadTotalTimeoutMultiplier = 0; + commTimeouts.WriteTotalTimeoutConstant = (uint)SendTimeoutConstant; + commTimeouts.WriteTotalTimeoutMultiplier = (uint)SendTimeoutMultiplier; + portDcb.Init(Parity is Parity.Odd or Parity.Even, TxFlowCts, TxFlowDsr, + (int)UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int)UseRts); + portDcb.BaudRate = (uint)BaudRate; + portDcb.ByteSize = (byte)DataBits; + portDcb.Parity = (DCB_PARITY)Parity; + portDcb.StopBits = (DCB_STOP_BITS)StopBits; + portDcb.XoffChar = (CHAR)(byte)XoffChar; + portDcb.XonChar = (CHAR)(byte)XonChar; + portDcb.XoffLim = (ushort)RxHighWater; + portDcb.XonLim = (ushort)RxLowWater; + + if (RxQueue != 0 || TxQueue != 0) + if (!PInvoke.SetupComm(_hPort, (uint)RxQueue, (uint)TxQueue)) + ThrowException("Bad queue settings"); + + if (!PInvoke.SetCommState(_hPort, portDcb)) + ThrowException("Bad com settings"); + + if (!PInvoke.SetCommTimeouts(_hPort, commTimeouts)) + ThrowException("Bad timeout settings"); + + _stateBrk = 0; + switch (UseDtr) { - BaudRate = baudRate; + case HsOutput.None: + _stateDtr = 0; + break; + case HsOutput.Online: + _stateDtr = 1; + break; } - /// - /// If true, the port will automatically re-open on next send if it was previously closed due - /// to an error (default: false) - /// - public bool AutoReopen { get; set; } - - /// - /// Baud Rate (default: 115200) - /// - /// Unsupported rates will throw "Bad settings". - public int BaudRate { get; set; } = 115200; - - /// - /// 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. - /// - public bool CheckAllSends { get; set; } = true; - - /// - /// Number of databits 1..8 (default: 8) unsupported values will throw "Bad settings" - /// - public int DataBits { get; set; } = 8; - - /// - /// The parity checking scheme (default: none) - /// - public Parity Parity { get; set; } = Parity.None; - - /// - /// If true, Xon and Xoff characters are sent to control the data flow from the remote station (default: false) - /// - public bool RxFlowX { get; set; } - - /// - /// If true, received characters are ignored unless DSR is asserted by the remote station (default: false) - /// - public bool RxGateDsr { get; set; } - - /// - /// The number of free bytes in the reception queue at which flow is disabled (default: 2048) - /// - public int RxHighWater { get; set; } = 2048; - - /// - /// The number of bytes in the reception queue at which flow is re-enabled (default: 512) - /// - public int RxLowWater { get; set; } = 512; - - /// - /// Requested size for receive queue (default: 0 = use operating system default) - /// - public int RxQueue { get; set; } - - /// - /// Constant. Max time for Send in ms = (Multiplier * Characters) + Constant (default: 0) - /// - public int SendTimeoutConstant { get; set; } - - /// - /// Multiplier. Max time for Send in ms = (Multiplier * Characters) + Constant - /// (default: 0 = No timeout) - /// - public int SendTimeoutMultiplier { get; set; } - - /// - /// Number of stop bits (default: one) - /// - public StopBits StopBits { get; set; } = StopBits.One; - - /// - /// If true, transmission is halted unless CTS is asserted by the remote station (default: false) - /// - public bool TxFlowCts { get; set; } - - /// - /// If true, transmission is halted unless DSR is asserted by the remote station (default: false) - /// - public bool TxFlowDsr { get; set; } - - /// - /// If true, transmission is halted when Xoff is received and restarted when Xon is received (default: false) - /// - public bool TxFlowX { get; set; } - - /// - /// Requested size for transmit queue (default: 0 = use operating system default) - /// - public int TxQueue { get; set; } - - /// - /// 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. - /// - public bool TxWhenRxXoff { get; set; } = true; - - /// - /// Specidies the use to which the DTR output is put (default: none) - /// - public HsOutput UseDtr { get; set; } = HsOutput.None; - - /// - /// Specifies the use to which the RTS output is put (default: none) - /// - public HsOutput UseRts { get; set; } = HsOutput.None; - - /// - /// The character used to signal Xoff for X flow control (default: DC3) - /// - public ASCII XoffChar { get; set; } = ASCII.DC3; - - /// - /// The character used to signal Xon for X flow control (default: DC1) - /// - public ASCII XonChar { get; set; } = ASCII.DC1; - - /// - /// True if online. - /// - public bool Online => _online && CheckOnline(); - - /// - /// True if the RTS pin is controllable via the RTS property - /// - protected bool RtSavailable => _stateRts < 2; - - /// - /// Set the state of the RTS modem control output - /// - protected bool Rts + switch (UseRts) { - set - { - if (_stateRts > 1) return; - CheckOnline(); - if (value) - { - if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETRTS)) - _stateRts = 1; - else - ThrowException("Unexpected Failure"); - } - else - { - if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRRTS)) - _stateRts = 1; - else - ThrowException("Unexpected Failure"); - } - } - get => _stateRts == 1; + case HsOutput.None: + _stateRts = 0; + break; + case HsOutput.Online: + _stateRts = 1; + break; } - /// - /// True if the DTR pin is controllable via the DTR property - /// - protected bool DtrAvailable => _stateDtr < 2; + _checkSends = CheckAllSends; + _ptrUwo.EventHandle = _checkSends ? _writeEvent.SafeWaitHandle.DangerousGetHandle() : IntPtr.Zero; + _writeCount = 0; - /// - /// The state of the DTR modem control output - /// - protected bool Dtr + _rxException = null; + _rxExceptionReported = false; + + // TODO: utilize Task Parallel Library here + _rxThread = new Thread(ReceiveThread) { - set - { - if (_stateDtr > 1) return; - CheckOnline(); - if (value) - { - if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETDTR)) - _stateDtr = 1; - else - ThrowException("Unexpected Failure"); - } - else - { - if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRDTR)) - _stateDtr = 0; - else - ThrowException("Unexpected Failure"); - } - } - get => _stateDtr == 1; - } + Name = "CommBaseRx", + Priority = ThreadPriority.AboveNormal, + IsBackground = true + }; - /// - /// Assert or remove a break condition from the transmission line - /// - protected bool Break - { - set - { - if (_stateBrk > 1) return; - CheckOnline(); - if (value) - { - if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETBREAK)) - _stateBrk = 0; - else - ThrowException("Unexpected Failure"); - } - else - { - if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRBREAK)) - _stateBrk = 0; - else - ThrowException("Unexpected Failure"); - } - } - get => _stateBrk == 1; - } - - - /// - /// Port Name - /// - 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; - } - } - } - - #endregion - - /// - /// - /// For IDisposable - /// - public void Dispose() - { - Close(); - } - - /// - /// Opens the com port and configures it with the required settings - /// - /// false if the port could not be opened - public bool Open() - { - var portDcb = new DCB(); - var commTimeouts = new COMMTIMEOUTS(); - var wo = new OVERLAPPED(); - - if (_online) return false; - - _hPort = PInvoke.CreateFile(PortName, FILE_ACCESS_FLAGS.FILE_GENERIC_READ | FILE_ACCESS_FLAGS.FILE_GENERIC_WRITE, 0, - null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_OVERLAPPED, null); - - if (_hPort.IsInvalid) - { - if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED) return false; - throw new CommPortException("Port Open Failure"); - } - - _online = true; - - commTimeouts.ReadIntervalTimeout = 0; - commTimeouts.ReadTotalTimeoutConstant = 0; - commTimeouts.ReadTotalTimeoutMultiplier = 0; - commTimeouts.WriteTotalTimeoutConstant = (uint)SendTimeoutConstant; - commTimeouts.WriteTotalTimeoutMultiplier = (uint)SendTimeoutMultiplier; - portDcb.Init(Parity is Parity.Odd or Parity.Even, TxFlowCts, TxFlowDsr, - (int)UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int)UseRts); - portDcb.BaudRate = (uint)BaudRate; - portDcb.ByteSize = (byte)DataBits; - portDcb.Parity = (DCB_PARITY)Parity; - portDcb.StopBits = (DCB_STOP_BITS)StopBits; - portDcb.XoffChar = (CHAR)(byte)XoffChar; - portDcb.XonChar = (CHAR)(byte)XonChar; - portDcb.XoffLim = (ushort)RxHighWater; - portDcb.XonLim = (ushort)RxLowWater; - - if (RxQueue != 0 || TxQueue != 0) - if (!PInvoke.SetupComm(_hPort, (uint)RxQueue, (uint)TxQueue)) - ThrowException("Bad queue settings"); - - if (!PInvoke.SetCommState(_hPort, portDcb)) - ThrowException("Bad com settings"); - - if (!PInvoke.SetCommTimeouts(_hPort, commTimeouts)) - ThrowException("Bad timeout settings"); - - _stateBrk = 0; - switch (UseDtr) - { - case HsOutput.None: - _stateDtr = 0; - break; - case HsOutput.Online: - _stateDtr = 1; - break; - } - - switch (UseRts) - { - case HsOutput.None: - _stateRts = 0; - break; - case HsOutput.Online: - _stateRts = 1; - break; - } - - _checkSends = CheckAllSends; - wo.Offset = 0; - wo.OffsetHigh = 0; - wo.hEvent = _checkSends ? _writeEvent.SafeWaitHandle.DangerousGetHandle() : IntPtr.Zero; - _ptrUwo = Marshal.AllocHGlobal(Marshal.SizeOf(wo)); - Marshal.StructureToPtr(wo, _ptrUwo, true); - _writeCount = 0; - - _rxException = null; - _rxExceptionReported = false; - - // TODO: utilize Task Parallel Library here - _rxThread = new Thread(ReceiveThread) - { - Name = "CommBaseRx", - Priority = ThreadPriority.AboveNormal, - IsBackground = true - }; - - _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; - } - - Close(); - return false; - } - - /// - /// Closes the com port. - /// - public void Close() - { - if (_online) - { - _auto = false; - BeforeClose(false); - InternalClose(); - _rxException = null; - } - } - - private void InternalClose() - { - Win32Com.CancelIo(_hPort.DangerousGetHandle()); - if (_rxThread != null) - { - _rxThread.Abort(); - _rxThread = null; - } - - _hPort.Dispose(); - if (_ptrUwo != IntPtr.Zero) Marshal.FreeHGlobal(_ptrUwo); - _stateRts = 2; - _stateDtr = 2; - _stateBrk = 2; - _online = false; - } - - /// - /// Destructor (just in case) - /// - ~SerialPort() - { - Close(); - } - - /// - /// Block until all bytes in the queue have been transmitted. - /// - public void Flush() - { - CheckOnline(); - CheckResult(); - } - - /// - /// Use this to throw exceptions in derived classes. Correctly handles threading issues - /// and closes the port if necessary. - /// - /// Description of fault - protected void ThrowException(string reason) - { - if (Thread.CurrentThread == _rxThread) throw new CommPortException(reason); - if (_online) - { - BeforeClose(true); - InternalClose(); - } - - if (_rxException == null) throw new CommPortException(reason); - throw new CommPortException(_rxException); - } - - /// - /// Queues bytes for transmission. - /// - /// Array of bytes to be sent - public void Write(byte[] toSend) - { - uint sent; - CheckOnline(); - CheckResult(); - _writeCount = toSend.GetLength(0); - if (Win32Com.WriteFile(_hPort.DangerousGetHandle(), toSend, (uint)_writeCount, out sent, _ptrUwo)) - { - _writeCount -= (int)sent; - } - else - { - if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) ThrowException("Unexpected failure"); - } - } - - /// - /// Queues string for transmission. - /// - /// Array of bytes to be sent - public void Write(string toSend) - { - Write(new ASCIIEncoding().GetBytes(toSend)); - } - - /// - /// Queues a single byte for transmission. - /// - /// Byte to be sent - public void Write(byte toSend) - { - var b = new byte[1]; - b[0] = toSend; - Write(b); - } - - /// - /// Queues a single char for transmission. - /// - /// Byte to be sent - public void Write(char toSend) - { - Write(toSend.ToString()); - } - - /// - /// Queues string with a new line ("\r\n") for transmission. - /// - /// Array of bytes to be sent - 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.DangerousGetHandle(), _ptrUwo, out sent, _checkSends)) - { - _writeCount -= (int)sent; - if (_writeCount != 0) ThrowException("Send Timeout"); - } - else - { - if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) ThrowException("Unexpected failure"); - } - } - - /// - /// Sends a protocol byte immediately ahead of any queued bytes. - /// - /// Byte to send - /// False if an immediate byte is already scheduled and not yet sent - public void SendImmediate(byte tosend) - { - CheckOnline(); - if (!Win32Com.TransmitCommChar(_hPort.DangerousGetHandle(), tosend)) ThrowException("Transmission failure"); - } - - /// - /// Gets the status of the modem control input signals. - /// - /// Modem status object - protected ModemStatus GetModemStatus() - { - uint f; - - CheckOnline(); - if (!Win32Com.GetCommModemStatus(_hPort.DangerousGetHandle(), out f)) ThrowException("Unexpected failure"); - return new ModemStatus(f); - } - - - /// - /// Get the status of the queues - /// - /// Queue status object - protected QueueStatus GetQueueStatus() - { - COMSTAT cs; - COMMPROP cp; - uint er; - - CheckOnline(); - if (!Win32Com.ClearCommError(_hPort.DangerousGetHandle(), out er, out cs)) ThrowException("Unexpected failure"); - if (!Win32Com.GetCommProperties(_hPort.DangerousGetHandle(), out cp)) ThrowException("Unexpected failure"); - return new QueueStatus(cs.Flags, cs.cbInQue, cs.cbOutQue, cp.dwCurrentRxQueue, cp.dwCurrentTxQueue); - } - - /// - /// Override this to provide processing after the port is opened (i.e. to configure remote - /// device or just check presence). - /// - /// false to close the port again - protected virtual bool AfterOpen() + _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; } - /// - /// Override this to provide processing prior to port closure. - /// - /// True if closing due to an error - protected virtual void BeforeClose(bool error) + Close(); + return false; + } + + /// + /// Closes the com port. + /// + public void Close() + { + if (_online) { + _auto = false; + BeforeClose(false); + InternalClose(); + _rxException = null; + } + } + + private void InternalClose() + { + Win32Com.CancelIo(_hPort.DangerousGetHandle()); + if (_rxThread != null) + { + _rxThread.Abort(); + _rxThread = null; } - public event Action DataReceived; + _hPort.Dispose(); + _stateRts = 2; + _stateDtr = 2; + _stateBrk = 2; + _online = false; + } - /// - /// Override this to process received bytes. - /// - /// The byte that was received - protected void OnRxChar(byte ch) + /// + /// Destructor (just in case) + /// + ~SerialPort() + { + Close(); + } + + /// + /// Block until all bytes in the queue have been transmitted. + /// + public void Flush() + { + CheckOnline(); + CheckResult(); + } + + /// + /// Use this to throw exceptions in derived classes. Correctly handles threading issues + /// and closes the port if necessary. + /// + /// Description of fault + protected void ThrowException(string reason) + { + if (Thread.CurrentThread == _rxThread) throw new CommPortException(reason); + if (_online) { - DataReceived?.Invoke(ch); + BeforeClose(true); + InternalClose(); } - /// - /// Override this to take action when transmission is complete (i.e. all bytes have actually - /// been sent, not just queued). - /// - protected virtual void OnTxDone() + if (_rxException == null) throw new CommPortException(reason); + throw new CommPortException(_rxException); + } + + /// + /// Queues bytes for transmission. + /// + /// Array of bytes to be sent + public unsafe void Write(byte[] toSend) + { + uint sent; + CheckOnline(); + CheckResult(); + _writeCount = toSend.GetLength(0); + + fixed (byte* ptr = toSend) + fixed (NativeOverlapped* ptrOl = &_ptrUwo) { - } - - /// - /// Override this to take action when a break condition is detected on the input line. - /// - protected virtual void OnBreak() - { - } - - /// - /// Override this to take action when a ring condition is signaled by an attached modem. - /// - protected virtual void OnRing() - { - } - - /// - /// Override this to take action when one or more modem status inputs change state - /// - /// The status inputs that have changed state - /// The state of the status inputs - protected virtual void OnStatusChange(ModemStatus mask, ModemStatus state) - { - } - - /// - /// Override this to take action when the reception thread closes due to an exception being thrown. - /// - /// The exception which was thrown - protected virtual void OnRxException(Exception e) - { - } - - private void ReceiveThread() - { - var buf = new byte[1]; - - var sg = new AutoResetEvent(false); - var ov = new OVERLAPPED(); - var unmanagedOv = Marshal.AllocHGlobal(Marshal.SizeOf(ov)); - ov.Offset = 0; - ov.OffsetHigh = 0; - ov.hEvent = sg.SafeWaitHandle.DangerousGetHandle(); - Marshal.StructureToPtr(ov, unmanagedOv, true); - - uint eventMask = 0; - var uMask = Marshal.AllocHGlobal(Marshal.SizeOf(eventMask)); - - try + if (PInvoke.WriteFile(_hPort, ptr, (uint)_writeCount, &sent, ptrOl)) { - while (true) - { - if (!Win32Com.SetCommMask(_hPort.DangerousGetHandle(), + _writeCount -= (int)sent; + } + else + { + if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) ThrowException("Unexpected failure"); + } + } + } + + /// + /// Queues string for transmission. + /// + /// Array of bytes to be sent + public void Write(string toSend) + { + Write(new ASCIIEncoding().GetBytes(toSend)); + } + + /// + /// Queues a single byte for transmission. + /// + /// Byte to be sent + public void Write(byte toSend) + { + var b = new byte[1]; + b[0] = toSend; + Write(b); + } + + /// + /// Queues a single char for transmission. + /// + /// Byte to be sent + public void Write(char toSend) + { + Write(toSend.ToString()); + } + + /// + /// Queues string with a new line ("\r\n") for transmission. + /// + /// Array of bytes to be sent + public void WriteLine(string toSend) + { + Write(new ASCIIEncoding().GetBytes(toSend + Environment.NewLine)); + } + + private void CheckResult() + { + if (_writeCount <= 0) return; + if (PInvoke.GetOverlappedResult(_hPort, _ptrUwo, out var sent, _checkSends)) + { + _writeCount -= (int)sent; + if (_writeCount != 0) ThrowException("Send Timeout"); + } + else + { + if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) ThrowException("Unexpected failure"); + } + } + + /// + /// Sends a protocol byte immediately ahead of any queued bytes. + /// + /// Byte to send + /// False if an immediate byte is already scheduled and not yet sent + public void SendImmediate(byte tosend) + { + CheckOnline(); + if (!Win32Com.TransmitCommChar(_hPort.DangerousGetHandle(), tosend)) ThrowException("Transmission failure"); + } + + /// + /// Gets the status of the modem control input signals. + /// + /// Modem status object + protected ModemStatus GetModemStatus() + { + uint f; + + CheckOnline(); + if (!Win32Com.GetCommModemStatus(_hPort.DangerousGetHandle(), out f)) ThrowException("Unexpected failure"); + return new ModemStatus(f); + } + + + /// + /// Get the status of the queues + /// + /// Queue status object + protected QueueStatus GetQueueStatus() + { + COMSTAT cs; + COMMPROP cp; + uint er; + + CheckOnline(); + if (!Win32Com.ClearCommError(_hPort.DangerousGetHandle(), out er, out cs)) ThrowException("Unexpected failure"); + if (!Win32Com.GetCommProperties(_hPort.DangerousGetHandle(), out cp)) ThrowException("Unexpected failure"); + return new QueueStatus(cs.Flags, cs.cbInQue, cs.cbOutQue, cp.dwCurrentRxQueue, cp.dwCurrentTxQueue); + } + + /// + /// Override this to provide processing after the port is opened (i.e. to configure remote + /// device or just check presence). + /// + /// false to close the port again + protected virtual bool AfterOpen() + { + return true; + } + + /// + /// Override this to provide processing prior to port closure. + /// + /// True if closing due to an error + protected virtual void BeforeClose(bool error) + { + } + + public event Action DataReceived; + + /// + /// Override this to process received bytes. + /// + /// The byte that was received + protected void OnRxChar(byte ch) + { + DataReceived?.Invoke(ch); + } + + /// + /// Override this to take action when transmission is complete (i.e. all bytes have actually + /// been sent, not just queued). + /// + protected virtual void OnTxDone() + { + } + + /// + /// Override this to take action when a break condition is detected on the input line. + /// + protected virtual void OnBreak() + { + } + + /// + /// Override this to take action when a ring condition is signaled by an attached modem. + /// + protected virtual void OnRing() + { + } + + /// + /// Override this to take action when one or more modem status inputs change state + /// + /// The status inputs that have changed state + /// The state of the status inputs + protected virtual void OnStatusChange(ModemStatus mask, ModemStatus state) + { + } + + /// + /// Override this to take action when the reception thread closes due to an exception being thrown. + /// + /// The exception which was thrown + protected virtual void OnRxException(Exception e) + { + } + + private void ReceiveThread() + { + var buf = new byte[1]; + + var sg = new AutoResetEvent(false); + var ov = new OVERLAPPED(); + var unmanagedOv = Marshal.AllocHGlobal(Marshal.SizeOf(ov)); + ov.Offset = 0; + ov.OffsetHigh = 0; + ov.hEvent = sg.SafeWaitHandle.DangerousGetHandle(); + Marshal.StructureToPtr(ov, unmanagedOv, true); + + uint eventMask = 0; + var uMask = Marshal.AllocHGlobal(Marshal.SizeOf(eventMask)); + + try + { + while (true) + { + if (!Win32Com.SetCommMask(_hPort.DangerousGetHandle(), Win32Com.EV_RXCHAR | Win32Com.EV_TXEMPTY | Win32Com.EV_CTS | Win32Com.EV_DSR | 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.DangerousGetHandle(), uMask, unmanagedOv)) + throw new CommPortException("IO Error [001]"); + Marshal.WriteInt32(uMask, 0); + if (!Win32Com.WaitCommEvent(_hPort.DangerousGetHandle(), uMask, unmanagedOv)) + { + if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) + sg.WaitOne(); + else + throw new CommPortException("IO Error [002]"); + } + + eventMask = (uint)Marshal.ReadInt32(uMask); + if ((eventMask & Win32Com.EV_ERR) != 0) + { + uint errs; + if (Win32Com.ClearCommError(_hPort.DangerousGetHandle(), out errs, IntPtr.Zero)) { - if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) - sg.WaitOne(); - else - throw new CommPortException("IO Error [002]"); + 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 Overflow,"); + 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()); } - eventMask = (uint)Marshal.ReadInt32(uMask); - if ((eventMask & Win32Com.EV_ERR) != 0) + throw new CommPortException("IO Error [003]"); + } + + if ((eventMask & Win32Com.EV_RXCHAR) != 0) + { + uint gotbytes; + do { - uint errs; - if (Win32Com.ClearCommError(_hPort.DangerousGetHandle(), out errs, IntPtr.Zero)) + if (!Win32Com.ReadFile(_hPort.DangerousGetHandle(), buf, 1, out gotbytes, unmanagedOv)) { - 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 Overflow,"); - 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()); + if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) + { + Win32Com.CancelIo(_hPort.DangerousGetHandle()); + gotbytes = 0; + } + else + { + throw new CommPortException("IO Error [004]"); + } } - throw new CommPortException("IO Error [003]"); - } - - if ((eventMask & Win32Com.EV_RXCHAR) != 0) - { - uint gotbytes; - do - { - if (!Win32Com.ReadFile(_hPort.DangerousGetHandle(), buf, 1, out gotbytes, unmanagedOv)) - { - if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) - { - Win32Com.CancelIo(_hPort.DangerousGetHandle()); - gotbytes = 0; - } - else - { - throw new CommPortException("IO Error [004]"); - } - } - - if (gotbytes == 1) OnRxChar(buf[0]); - } while (gotbytes > 0); - } - - if ((eventMask & Win32Com.EV_TXEMPTY) != 0) OnTxDone(); - 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.DangerousGetHandle(), out f)) throw new CommPortException("IO Error [005]"); - OnStatusChange(new ModemStatus(i), new ModemStatus(f)); - } + if (gotbytes == 1) OnRxChar(buf[0]); + } while (gotbytes > 0); } - } - catch (Exception e) - { - if (uMask != IntPtr.Zero) Marshal.FreeHGlobal(uMask); - if (unmanagedOv != IntPtr.Zero) Marshal.FreeHGlobal(unmanagedOv); - if (!(e is ThreadAbortException)) + + if ((eventMask & Win32Com.EV_TXEMPTY) != 0) OnTxDone(); + 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) { - _rxException = e; - OnRxException(e); + uint f; + if (!Win32Com.GetCommModemStatus(_hPort.DangerousGetHandle(), out f)) + throw new CommPortException("IO Error [005]"); + OnStatusChange(new ModemStatus(i), new ModemStatus(f)); } } } - - private bool CheckOnline() + catch (Exception e) { - if (_rxException != null && !_rxExceptionReported) + if (uMask != IntPtr.Zero) Marshal.FreeHGlobal(uMask); + if (unmanagedOv != IntPtr.Zero) Marshal.FreeHGlobal(unmanagedOv); + if (!(e is ThreadAbortException)) { - _rxExceptionReported = true; - ThrowException("rx"); + _rxException = e; + OnRxException(e); } + } + } - if (_online) - { - uint f; - if (Win32Com.GetHandleInformation(_hPort.DangerousGetHandle(), out f)) return true; - ThrowException("Offline"); - return false; - } + private bool CheckOnline() + { + if (_rxException != null && !_rxExceptionReported) + { + _rxExceptionReported = true; + ThrowException("rx"); + } - if (_auto) - if (Open()) - return true; + if (_online) + { + uint f; + if (Win32Com.GetHandleInformation(_hPort.DangerousGetHandle(), out f)) return true; ThrowException("Offline"); return false; } + + if (_auto) + if (Open()) + return true; + ThrowException("Offline"); + return false; } + + #region Private fields + + private readonly ManualResetEvent _writeEvent = new(false); + private bool _auto; + private bool _checkSends = true; + + private Handshake _handShake; + private SafeFileHandle _hPort; + private bool _online; + private NativeOverlapped _ptrUwo; + private Exception _rxException; + private bool _rxExceptionReported; + private Thread _rxThread; + private int _stateBrk = 2; + private int _stateDtr = 2; + private int _stateRts = 2; + private int _writeCount; + + #endregion + + #region Public properties + + /// + /// Class constructor + /// + public SerialPort(string portName) + { + PortName = portName; + } + + /// + /// + /// Class constructor + /// + public SerialPort(string portName, int baudRate) : this(portName) + { + BaudRate = baudRate; + } + + /// + /// If true, the port will automatically re-open on next send if it was previously closed due + /// to an error (default: false) + /// + public bool AutoReopen { get; set; } + + /// + /// Baud Rate (default: 115200) + /// + /// Unsupported rates will throw "Bad settings". + public int BaudRate { get; set; } = 115200; + + /// + /// 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. + /// + public bool CheckAllSends { get; set; } = true; + + /// + /// Number of databits 1..8 (default: 8) unsupported values will throw "Bad settings" + /// + public int DataBits { get; set; } = 8; + + /// + /// The parity checking scheme (default: none) + /// + public Parity Parity { get; set; } = Parity.None; + + /// + /// If true, Xon and Xoff characters are sent to control the data flow from the remote station (default: false) + /// + public bool RxFlowX { get; set; } + + /// + /// If true, received characters are ignored unless DSR is asserted by the remote station (default: false) + /// + public bool RxGateDsr { get; set; } + + /// + /// The number of free bytes in the reception queue at which flow is disabled (default: 2048) + /// + public int RxHighWater { get; set; } = 2048; + + /// + /// The number of bytes in the reception queue at which flow is re-enabled (default: 512) + /// + public int RxLowWater { get; set; } = 512; + + /// + /// Requested size for receive queue (default: 0 = use operating system default) + /// + public int RxQueue { get; set; } + + /// + /// Constant. Max time for Send in ms = (Multiplier * Characters) + Constant (default: 0) + /// + public int SendTimeoutConstant { get; set; } + + /// + /// Multiplier. Max time for Send in ms = (Multiplier * Characters) + Constant + /// (default: 0 = No timeout) + /// + public int SendTimeoutMultiplier { get; set; } + + /// + /// Number of stop bits (default: one) + /// + public StopBits StopBits { get; set; } = StopBits.One; + + /// + /// If true, transmission is halted unless CTS is asserted by the remote station (default: false) + /// + public bool TxFlowCts { get; set; } + + /// + /// If true, transmission is halted unless DSR is asserted by the remote station (default: false) + /// + public bool TxFlowDsr { get; set; } + + /// + /// If true, transmission is halted when Xoff is received and restarted when Xon is received (default: false) + /// + public bool TxFlowX { get; set; } + + /// + /// Requested size for transmit queue (default: 0 = use operating system default) + /// + public int TxQueue { get; set; } + + /// + /// 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. + /// + public bool TxWhenRxXoff { get; set; } = true; + + /// + /// Specidies the use to which the DTR output is put (default: none) + /// + public HsOutput UseDtr { get; set; } = HsOutput.None; + + /// + /// Specifies the use to which the RTS output is put (default: none) + /// + public HsOutput UseRts { get; set; } = HsOutput.None; + + /// + /// The character used to signal Xoff for X flow control (default: DC3) + /// + public ASCII XoffChar { get; set; } = ASCII.DC3; + + /// + /// The character used to signal Xon for X flow control (default: DC1) + /// + public ASCII XonChar { get; set; } = ASCII.DC1; + + /// + /// True if online. + /// + public bool Online => _online && CheckOnline(); + + /// + /// True if the RTS pin is controllable via the RTS property + /// + protected bool RtSavailable => _stateRts < 2; + + /// + /// Set the state of the RTS modem control output + /// + protected bool Rts + { + set + { + if (_stateRts > 1) return; + CheckOnline(); + if (value) + { + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETRTS)) + _stateRts = 1; + else + ThrowException("Unexpected Failure"); + } + else + { + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRRTS)) + _stateRts = 1; + else + ThrowException("Unexpected Failure"); + } + } + get => _stateRts == 1; + } + + /// + /// True if the DTR pin is controllable via the DTR property + /// + protected bool DtrAvailable => _stateDtr < 2; + + /// + /// The state of the DTR modem control output + /// + protected bool Dtr + { + set + { + if (_stateDtr > 1) return; + CheckOnline(); + if (value) + { + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETDTR)) + _stateDtr = 1; + else + ThrowException("Unexpected Failure"); + } + else + { + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRDTR)) + _stateDtr = 0; + else + ThrowException("Unexpected Failure"); + } + } + get => _stateDtr == 1; + } + + /// + /// Assert or remove a break condition from the transmission line + /// + protected bool Break + { + set + { + if (_stateBrk > 1) return; + CheckOnline(); + if (value) + { + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.SETBREAK)) + _stateBrk = 0; + else + ThrowException("Unexpected Failure"); + } + else + { + if (Win32Com.EscapeCommFunction(_hPort.DangerousGetHandle(), Win32Com.CLRBREAK)) + _stateBrk = 0; + else + ThrowException("Unexpected Failure"); + } + } + get => _stateBrk == 1; + } + + + /// + /// Port Name + /// + 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; + } + } + } + + #endregion } \ No newline at end of file From aabf3897fdcd09bcd1d95e133a89e1bf86d4beec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 19:16:35 +0200 Subject: [PATCH 12/14] Migrated more types --- .../QueueStatus.cs | 20 +++++++---- Nefarius.Peripherals.SerialPort/SerialPort.cs | 33 ++++++++++--------- .../Win32PInvoke/COMSTAT.cs | 20 ----------- .../Win32PInvoke/Win32Com.cs | 5 --- 4 files changed, 32 insertions(+), 46 deletions(-) delete mode 100644 Nefarius.Peripherals.SerialPort/Win32PInvoke/COMSTAT.cs diff --git a/Nefarius.Peripherals.SerialPort/QueueStatus.cs b/Nefarius.Peripherals.SerialPort/QueueStatus.cs index 69bf8de..63469fd 100644 --- a/Nefarius.Peripherals.SerialPort/QueueStatus.cs +++ b/Nefarius.Peripherals.SerialPort/QueueStatus.cs @@ -23,35 +23,43 @@ namespace Nefarius.Peripherals.SerialPort _outQueueSize = outQs; } + internal const uint fCtsHold = 0x1; + internal const uint fDsrHold = 0x2; + internal const uint fRlsdHold = 0x4; + internal const uint fXoffHold = 0x8; + internal const uint fXoffSent = 0x10; + internal const uint fEof = 0x20; + internal const uint fTxim = 0x40; + /// /// Output is blocked by CTS handshaking. /// - public bool CtsHold => (_status & COMSTAT.fCtsHold) != 0; + public bool CtsHold => (_status & fCtsHold) != 0; /// /// Output is blocked by DRS handshaking. /// - public bool DsrHold => (_status & COMSTAT.fDsrHold) != 0; + public bool DsrHold => (_status & fDsrHold) != 0; /// /// Output is blocked by RLSD handshaking. /// - public bool RlsdHold => (_status & COMSTAT.fRlsdHold) != 0; + public bool RlsdHold => (_status & fRlsdHold) != 0; /// /// Output is blocked because software handshaking is enabled and XOFF was received. /// - public bool XoffHold => (_status & COMSTAT.fXoffHold) != 0; + public bool XoffHold => (_status & fXoffHold) != 0; /// /// Output was blocked because XOFF was sent and this station is not yet ready to receive. /// - public bool XoffSent => (_status & COMSTAT.fXoffSent) != 0; + public bool XoffSent => (_status & fXoffSent) != 0; /// /// There is a character waiting for transmission in the immediate buffer. /// - public bool ImmediateWaiting => (_status & COMSTAT.fTxim) != 0; + public bool ImmediateWaiting => (_status & fTxim) != 0; /// /// Number of bytes waiting in the input queue. diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index 8d58f3f..dd22fb5 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -9,7 +9,6 @@ using Windows.Win32.Storage.FileSystem; using Microsoft.Win32.SafeHandles; using Nefarius.Peripherals.SerialPort.Win32PInvoke; using COMMPROP = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMMPROP; -using COMSTAT = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMSTAT; namespace Nefarius.Peripherals.SerialPort; @@ -298,16 +297,20 @@ public class SerialPort : IDisposable /// Get the status of the queues /// /// Queue status object - protected QueueStatus GetQueueStatus() + protected unsafe QueueStatus GetQueueStatus() { COMSTAT cs; COMMPROP cp; - uint er; + CLEAR_COMM_ERROR_FLAGS er; CheckOnline(); - if (!Win32Com.ClearCommError(_hPort.DangerousGetHandle(), out er, out cs)) ThrowException("Unexpected failure"); - if (!Win32Com.GetCommProperties(_hPort.DangerousGetHandle(), out cp)) ThrowException("Unexpected failure"); - return new QueueStatus(cs.Flags, cs.cbInQue, cs.cbOutQue, cp.dwCurrentRxQueue, cp.dwCurrentTxQueue); + if (!PInvoke.ClearCommError(_hPort, &er, &cs)) + ThrowException("Unexpected failure"); + + if (!Win32Com.GetCommProperties(_hPort.DangerousGetHandle(), out cp)) + ThrowException("Unexpected failure"); + + return new QueueStatus(cs._bitfield, cs.cbInQue, cs.cbOutQue, cp.dwCurrentRxQueue, cp.dwCurrentTxQueue); } /// @@ -378,7 +381,7 @@ public class SerialPort : IDisposable { } - private void ReceiveThread() + private unsafe void ReceiveThread() { var buf = new byte[1]; @@ -413,16 +416,16 @@ public class SerialPort : IDisposable eventMask = (uint)Marshal.ReadInt32(uMask); if ((eventMask & Win32Com.EV_ERR) != 0) { - uint errs; - if (Win32Com.ClearCommError(_hPort.DangerousGetHandle(), out errs, IntPtr.Zero)) + CLEAR_COMM_ERROR_FLAGS errs; + if (PInvoke.ClearCommError(_hPort, &errs, null)) { 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 Overflow,"); - if ((errs & Win32Com.CE_RXPARITY) != 0) s = s.Append("Parity,"); - if ((errs & Win32Com.CE_TXFULL) != 0) s = s.Append("Transmit Overflow,"); + if (((uint)errs & Win32Com.CE_FRAME) != 0) s = s.Append("Framing,"); + if (((uint)errs & Win32Com.CE_IOE) != 0) s = s.Append("IO,"); + if (((uint)errs & Win32Com.CE_OVERRUN) != 0) s = s.Append("Overrun,"); + if (((uint)errs & Win32Com.CE_RXOVER) != 0) s = s.Append("Receive Overflow,"); + if (((uint)errs & Win32Com.CE_RXPARITY) != 0) s = s.Append("Parity,"); + if (((uint)errs & Win32Com.CE_TXFULL) != 0) s = s.Append("Transmit Overflow,"); s.Length = s.Length - 1; throw new CommPortException(s.ToString()); } diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMSTAT.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMSTAT.cs deleted file mode 100644 index 523182c..0000000 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMSTAT.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Nefarius.Peripherals.SerialPort.Win32PInvoke -{ - [StructLayout(LayoutKind.Sequential)] - internal struct COMSTAT - { - internal const uint fCtsHold = 0x1; - internal const uint fDsrHold = 0x2; - internal const uint fRlsdHold = 0x4; - internal const uint fXoffHold = 0x8; - internal const uint fXoffSent = 0x10; - internal const uint fEof = 0x20; - internal const uint fTxim = 0x40; - internal UInt32 Flags; - internal UInt32 cbInQue; - internal UInt32 cbOutQue; - } -} \ No newline at end of file diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs index 58b9e11..3a89c67 100644 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs +++ b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs @@ -88,11 +88,6 @@ namespace Nefarius.Peripherals.SerialPort.Win32PInvoke internal static extern Boolean GetOverlappedResult(IntPtr hFile, IntPtr lpOverlapped, out UInt32 nNumberOfBytesTransferred, Boolean bWait); - [DllImport("kernel32.dll")] - internal static extern Boolean ClearCommError(IntPtr hFile, out UInt32 lpErrors, IntPtr lpStat); - [DllImport("kernel32.dll")] - internal static extern Boolean ClearCommError(IntPtr hFile, out UInt32 lpErrors, out COMSTAT cs); - //Constants for lpErrors: internal const UInt32 CE_RXOVER = 0x0001; internal const UInt32 CE_OVERRUN = 0x0002; From e48d103c63eee7f7a539ed32f00c849fe637df1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 19:17:59 +0200 Subject: [PATCH 13/14] Migrated mroe code --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 5 ++-- .../Win32PInvoke/COMMPROP.cs | 28 ------------------- .../Win32PInvoke/Win32Com.cs | 14 +--------- 3 files changed, 3 insertions(+), 44 deletions(-) delete mode 100644 Nefarius.Peripherals.SerialPort/Win32PInvoke/COMMPROP.cs diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index dd22fb5..36f23d3 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -8,7 +8,6 @@ using Windows.Win32.Foundation; using Windows.Win32.Storage.FileSystem; using Microsoft.Win32.SafeHandles; using Nefarius.Peripherals.SerialPort.Win32PInvoke; -using COMMPROP = Nefarius.Peripherals.SerialPort.Win32PInvoke.COMMPROP; namespace Nefarius.Peripherals.SerialPort; @@ -300,14 +299,14 @@ public class SerialPort : IDisposable protected unsafe QueueStatus GetQueueStatus() { COMSTAT cs; - COMMPROP cp; + var cp = new COMMPROP(); CLEAR_COMM_ERROR_FLAGS er; CheckOnline(); if (!PInvoke.ClearCommError(_hPort, &er, &cs)) ThrowException("Unexpected failure"); - if (!Win32Com.GetCommProperties(_hPort.DangerousGetHandle(), out cp)) + if (!PInvoke.GetCommProperties(_hPort, ref cp)) ThrowException("Unexpected failure"); return new QueueStatus(cs._bitfield, cs.cbInQue, cs.cbOutQue, cp.dwCurrentRxQueue, cp.dwCurrentTxQueue); diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMMPROP.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMMPROP.cs deleted file mode 100644 index bbd37be..0000000 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/COMMPROP.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Nefarius.Peripherals.SerialPort.Win32PInvoke -{ - [StructLayout(LayoutKind.Sequential)] - internal struct COMMPROP - { - internal UInt16 wPacketLength; - internal UInt16 wPacketVersion; - internal UInt32 dwServiceMask; - internal UInt32 dwReserved1; - internal UInt32 dwMaxTxQueue; - internal UInt32 dwMaxRxQueue; - internal UInt32 dwMaxBaud; - internal UInt32 dwProvSubType; - internal UInt32 dwProvCapabilities; - internal UInt32 dwSettableParams; - internal UInt32 dwSettableBaud; - internal UInt16 wSettableData; - internal UInt16 wSettableStopParity; - internal UInt32 dwCurrentTxQueue; - internal UInt32 dwCurrentRxQueue; - internal UInt32 dwProvSpec1; - internal UInt32 dwProvSpec2; - internal Byte wcProvChar; - } -} \ No newline at end of file diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs index 3a89c67..4c5f52f 100644 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs +++ b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs @@ -12,18 +12,7 @@ namespace Nefarius.Peripherals.SerialPort.Win32PInvoke [DllImport("kernel32.dll")] internal static extern Boolean GetHandleInformation(IntPtr hObject, out UInt32 lpdwFlags); - - /// - /// Manipulating the communications settings. - /// - /// - /// Reading and writing. - /// - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern Boolean WriteFile(IntPtr fFile, Byte[] lpBuffer, UInt32 nNumberOfBytesToWrite, - out UInt32 lpNumberOfBytesWritten, IntPtr lpOverlapped); - [DllImport("kernel32.dll")] internal static extern Boolean SetCommMask(IntPtr hFile, UInt32 dwEvtMask); @@ -100,7 +89,6 @@ namespace Nefarius.Peripherals.SerialPort.Win32PInvoke internal const UInt32 CE_DNS = 0x0800; internal const UInt32 CE_OOP = 0x1000; internal const UInt32 CE_MODE = 0x8000; - [DllImport("kernel32.dll")] - internal static extern Boolean GetCommProperties(IntPtr hFile, out COMMPROP cp); + } } \ No newline at end of file From 6f9ec4d2a4051c556287c7769775c6d39c216001 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Mon, 3 Oct 2022 19:20:01 +0200 Subject: [PATCH 14/14] Migrated more types --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 13 +++++++------ .../Win32PInvoke/Win32Com.cs | 3 --- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index 36f23d3..cfddb9a 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -43,7 +43,7 @@ public class SerialPort : IDisposable if (_hPort.IsInvalid) { - if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED) return false; + if (Marshal.GetLastWin32Error() == (int)WIN32_ERROR.ERROR_ACCESS_DENIED) return false; throw new CommPortException("Port Open Failure"); } @@ -210,7 +210,8 @@ public class SerialPort : IDisposable } else { - if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) ThrowException("Unexpected failure"); + if (Marshal.GetLastWin32Error() != (int)WIN32_ERROR.ERROR_IO_PENDING) + ThrowException("Unexpected failure"); } } } @@ -263,7 +264,7 @@ public class SerialPort : IDisposable } else { - if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) ThrowException("Unexpected failure"); + if (Marshal.GetLastWin32Error() != (int)WIN32_ERROR.ERROR_IO_PENDING) ThrowException("Unexpected failure"); } } @@ -406,7 +407,7 @@ public class SerialPort : IDisposable Marshal.WriteInt32(uMask, 0); if (!Win32Com.WaitCommEvent(_hPort.DangerousGetHandle(), uMask, unmanagedOv)) { - if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) + if (Marshal.GetLastWin32Error() == (int)WIN32_ERROR.ERROR_IO_PENDING) sg.WaitOne(); else throw new CommPortException("IO Error [002]"); @@ -425,7 +426,7 @@ public class SerialPort : IDisposable if (((uint)errs & Win32Com.CE_RXOVER) != 0) s = s.Append("Receive Overflow,"); if (((uint)errs & Win32Com.CE_RXPARITY) != 0) s = s.Append("Parity,"); if (((uint)errs & Win32Com.CE_TXFULL) != 0) s = s.Append("Transmit Overflow,"); - s.Length = s.Length - 1; + s.Length -= 1; throw new CommPortException(s.ToString()); } @@ -439,7 +440,7 @@ public class SerialPort : IDisposable { if (!Win32Com.ReadFile(_hPort.DangerousGetHandle(), buf, 1, out gotbytes, unmanagedOv)) { - if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) + if (Marshal.GetLastWin32Error() == (int)WIN32_ERROR.ERROR_IO_PENDING) { Win32Com.CancelIo(_hPort.DangerousGetHandle()); gotbytes = 0; diff --git a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs index 4c5f52f..a8ee677 100644 --- a/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs +++ b/Nefarius.Peripherals.SerialPort/Win32PInvoke/Win32Com.cs @@ -5,9 +5,6 @@ namespace Nefarius.Peripherals.SerialPort.Win32PInvoke { internal class Win32Com { - //Constants for errors: - internal const UInt32 ERROR_ACCESS_DENIED = 5; - internal const UInt32 ERROR_IO_PENDING = 997; [DllImport("kernel32.dll")] internal static extern Boolean GetHandleInformation(IntPtr hObject, out UInt32 lpdwFlags);