Home › Forums › TrueRNG Hardware random number generator › C# Windows Sample Code for Quickstart
- This topic has 2 replies, 2 voices, and was last updated 8 years, 2 months ago by Ubld.it Staff.
-
AuthorPosts
-
September 2, 2016 at 11:03 pm #1828QuadkoMember
I’m initially using my TrueRNGPro from Windows and C#. I worked through a few initial problems to get this far, here’s some sample C# code in case it’s useful for anyone else trying to quickstart on C#.
Caveats:
* it’s doing open-read-close in one func here, but they can be split up to open once and read many times
* it’s not bug free
* it’s working short naive quickstart code
* Microsoft’s .NET SerialPort class itself has problemsSerialPort class issues, see: http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport
If I get a more recommended C# SerialPort implementation, I’ll try to post that, too.
I’m using Visual Studio 2015, .NET 4.5.2.
using System.IO.Ports; using System.Diagnostics; // ... // Class members & properties, COM3 is my TrueRNG device SerialPort port = null; string ComPort = "COM3"; // ... // Initialize the serial port port = new SerialPort(ComPort, 115200); port.DtrEnable = true; port.ReadTimeout = 1000; port.Open(); // ... // Create a byte buffer to fill byte[] data = new byte[16]; try { // read bytes into buffer in simple consumption loop int count = 0; while ((count += port.Read(data, count, data.Length - count)) != data.Length) ; } catch (Exception exception) { // Timeout exception especially, other port errors possible Debug.WriteLine(exception.ToString()); } // NB: data might not be filled if error path // ... // Do something with the data like debug output foreach (byte b in data) { Debug.Write($"{b:X2}"); } Debug.WriteLine(""); // ... // When done, release the resources // NB: Dispose calls close(). Errors appear if close // is called twice in a row too quickly, // like calling Close() Dispose() in a row. port.Dispose();
September 7, 2016 at 5:47 pm #1850QuadkoMemberHere’s the second level C# class I came up with based on the above “better approach” url to sparxeng, in case it’s useful to anyone.
It has fewer failures than above, but still some. And the failures in both cases have all been port acquisition failures, which I don’t think is a code issue so much as something in windows or running in the Visual Studio Debugger and it not letting the port go. A port acquisition failure was always solved by closing & re-running.
Still, barring any bugs I introduced when I unwrapped the highly anonymous code the sparxeng blog provided, this is supposed to be a cleaner (async) way to use the serial port from .NET, and it is working just fine for me in my C# “get some random data in various formats” app.
class SerialPortManager { SerialPort port; byte[] buffer; bool stopping = false; int _BufferSize = 10240; public int BufferSize { get { return _BufferSize; } set { _BufferSize = value; buffer = new byte[value]; } } public bool IsOpen { get { if (port == null) return false; return port.IsOpen; } } public delegate void RecieveDataHandler(byte[] data); public event RecieveDataHandler RecieveData; public delegate void ClosedHandler(); public event ClosedHandler Closed; public delegate void SerialPortErrorHandler(IOException exception); public event SerialPortErrorHandler SerialPortError; public void Open(string Name, int ReadTimeout = 1000) { stopping = false; if (buffer == null || buffer.Length != _BufferSize) { BufferSize = _BufferSize; } // Initialize the serial port port = new SerialPort(Name, 115200); port.DtrEnable = true; port.ReadTimeout = ReadTimeout; port.Open(); port.BaseStream.BeginRead(buffer, 0, buffer.Length, EndRead, null); } void EndRead(IAsyncResult result) { try { int count = port.BaseStream.EndRead(result); if (!stopping) { byte[] data = new byte[count]; Buffer.BlockCopy(buffer, 0, data, 0, count); RecieveData?.Invoke(data); } } catch (IOException exception) { SerialPortError?.Invoke(exception); Debug.WriteLine(exception.ToString()); } // Init another async read or close port as appropriate if (!stopping) { port.BaseStream.BeginRead(buffer, 0, buffer.Length, EndRead, null); } else { port.Close(); Closed?.Invoke(); } } public void InitiateClose() { stopping = true; } }
September 19, 2016 at 1:47 pm #1860Ubld.it StaffModeratorQuadko,
Thanks for sharing your code. I’ve heard complaints of serial com issues with C# and unfortunately I always see the developer just avoid using C# and go with something else entirely such as Python. Definitely report back here if you find a library that solves your issues.
-
AuthorPosts
- You must be logged in to reply to this topic.