Home Forums TrueRNG Hardware random number generator C# Windows Sample Code for Quickstart

This topic contains 2 replies, has 2 voices, and was last updated by  ubld.it 1 year, 2 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #1828

    Quadko
    Member

    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 problems

    SerialPort 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();
    
    #1850

    Quadko
    Member

    Here’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;
            }
        }
    
    #1860

    ubld.it
    Keymaster

    Quadko,

    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.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.