How do I use C# to control my Ethernet to Serial device?

FAQs


Brainboxes provides a .NET API which allows easy integration of Brainboxes Ethernet to Serial modules into your Windows software applications, (or general .NET application which can also be run under Linux using .NET CORE or Mono).

The Brainboxes.IO .NET API does not use the serial port API, instead it communicates with the Ethernet to Serial Devices using raw TCP. One benefit of this is that Brainboxes Windows COM port drivers don’t need be to installed on any machine. On the Brainboxes Ethernet to serial device, a configuration step is required to allow raw TCP communication.

The Brainboxes Ethernet to Serial device then takes care of handshaking and com port settings with the serial connected device. Alternatively in Windows the Ethernet to Serial can be installed using Brainboxes Virtual Com ports, and the standard windows serial API can be used.

Requirements

Configure Brainboxes Ethernet to Serial for Raw TCP

files/pages/support/faqs/Images/ethernet-to-serial/configure-ethernet-to-serial-raw-tcp.png

  1. Navigate to the homepage of your brainboxes ethernet to serial device in a web browser
  2. Click on the serial port bottom on the left hand side navigation
  3. Set the appropriate settings for you serial port connection and then check the “always use these settings checkbox”
  4. Change the Protocol Type to “Raw TCP”
  5. Click Save
  6. You can test this set up by connecting to the IP address and port using a terminal such as Putty

C# Code Sample

Brainboxes.IO C# API in visual studio for Ethernet to serial

The following code works in C# targeted at .net version 2.0 and above

using System;
using System.Diagnostics;

namespace Brainboxes.IO.Samples.ES.ConsoleApplication
{
    class Program
    {

        static void Main(string[] args)
        {
            ESDevice es = new ES246("192.168.2.144");
            try
            {
                Console.WriteLine("Connecting to " + es);
                //connect method opens all serial ports of the device, an es-246 only has 1 port
                es.Connect();
                //alternatively just open the port you need
                //es.Ports[0].Connect();

                es.Ports[0].Label = "Serial Weighing scale"; //you can give each port a label, useful for debugging

                Console.WriteLine("Sending Commands");

                //es-246 only has one port, note the ports are indexed from 0
                //the default protocol automatically appends newline n to the end of a message and encodes data into UTF-8
                es.Ports[0].Send("HELLO ... ");
                es.Ports[0].Send("HELLO AGAIN...");

                //you can use a different protocol to suit the device you are communicating with like this:
                es.Ports[0].Protocol = new DefaultSerialProtocol()
                {
                    TerminatingCharacters = "rn", //you can set multiple char line endings with the default protocol
                    Encoding = System.Text.Encoding.Unicode, //you can also change the character encoding
                };
                //alternatively create a class which implements ISerialProtocol

                // 1 minutes in milliseconds
                int msToRx = 1 * 60 * 1000;

                Console.WriteLine("Waiting " + (msToRx / 1000) + " seconds for data to be received");
                Stopwatch sw = Stopwatch.StartNew();

                while (sw.ElapsedMilliseconds < msToRx)
                {
                    try
                    {
                        //write any received data out to the console
                        //note this is a blocking function, if you have many connections, or a UI
                        //you will need to do this in another thread
                        //the default protocol waits for the terminating character (by default a /n NEW LINE) to determine the end of a message
                        //the default protocol removes the terminating character before returning the message as a string
                        // note if the other device is being controlled by PUTTY,
                        // Putty will only send r when the ENTER key is pressed, to add a n type CNTRL+J into the putty window
                        string recievedData = es.Ports[0].Receive();
                        Console.WriteLine("Received DATA : " + recievedData);
                    }
                    catch (TimeoutException)
                    {
                        //if the receive function times out it throws an exception
                        //but it doesn't matter as we are just waiting for data in this example
                        Console.WriteLine("No data received within timeout");
                    }
                }
                sw.Stop();

                es.Ports[0].Send("GOODBYE!!!!!!!");
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred");
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadKey();

                Console.WriteLine("Disconnecting");
                es.Disconnect();
            }

        }
    }
}

Example 2: Auto-reconnect when device becomes available on the network

This more complex example shows how to auto-reconnect when a device becomes available on the network. Useful in more challenging network environments. The example also demonstrates sending a receiving data in a separate thread

using System;
using System.Threading;
using Brainboxes.IO;

namespace NetCore_Ethernet_Serial_Console_App
{
    class Program
    {
        private static ESDevice es;
        private const string IP = "enter ip here";

        private static AutoResetEvent preventExit;
        static void Main(string[] args)
        {
            Console.WriteLine("Ethernet to Serial TX/RX Test program");

            es = new ES511(IP);  // could be set to any brainboxes ES device


            es.Ports[0].Protocol = new DefaultSerialProtocol
            {
                // set the terminating character to rn, this will be auto appended and removed from any sent/recieved messages
                TerminatingCharacters = "rn",
                // Encoding = defaults to UTF-8 which covers ASCII and more
            };

            // with brainboxes ED range there is one connection to a device, however with ES, there is one connection per ethernet port
            // each serial port maintains its own connection so attach events to the port rather than the ESDevice
            // note the device will only disconnect/ be considered offline after the timeout expires without being able to communicate
            // connection status events are propagated up, so only attach to the port and not the connection , it provides the same information
            es.Ports[0].DeviceStatusChangedEvent += DeviceStatusChangedEvent;

            if (es.Ports[0].IsAvailable)
            {
                // put the function in a new thread
                new Thread(() => { ConnectAndTxRx(); }).Start();
            }

            // otherwise wait for the device to be online, then start comms
            // the device status change event will handle this

            // pause the main thread
            using (preventExit = new AutoResetEvent(false))
            {
                //pause current thread keep app running
                preventExit.WaitOne();
            }
            Console.WriteLine("Exiting");
        }

        private static void DeviceStatusChangedEvent(IDevice device, string property, bool newValue)
        {
            Console.WriteLine($"ES Device status change-- {property}:{newValue}");
            // if the device has just come back online start messaging
            if (property == "IsAvailable" && newValue)
            {
                Console.WriteLine("Reconnecting to the device");
                // put the function in a new thread
                new Thread(() => { ConnectAndTxRx(); }).Start();

            }
        }

        public static void ConnectAndTxRx()
        {
            try
            {
                // just open the port we are interested in
                es.Ports[0].Connect();
                // alternatively this function connects all ports on the device (if multi port)
                // es.Connect();
                // only gets here if the connection is successful
                string buffer = string.Empty;
                string recievedData;
                while (buffer != "quit")
                {
                    Console.WriteLine("Enter Value to send to other device");
                    buffer = Console.ReadLine();
                    Console.WriteLine($"TX => {buffer}");
                    // the terminating character(s) is automatically appended
                    es.Ports[0].Send(buffer);
                    Console.WriteLine("Waiting for response from other device");
                    // note if the other device is being controlled by PUTTY,
                    // Putty will only send r when the ENTER key is pressed, to add a n type CONTROL+J into the putty window
                    recievedData = es.Ports[0].Receive();
                    Console.WriteLine($"RX <= {recievedData}");
                }
                // only get here if the buffer == quit, signal the main thread to quit as well
                preventExit.Set();
            }
            catch(Exception e)
            {
                Console.WriteLine("Error " + e);
            }
            finally
            {
                Console.WriteLine("disconnecting");
                // if the device has already disconnected, this is not a harmful call
                es.Disconnect();
            }

        }

    }

}
FAQs