none
In C#, are there other ways to do Serial Communications programming apart from using the SerialPort class? RRS feed

  • Question

  • Just need to check if there are other options apart from using the SerialPort class.

    Thank you!!

    Sunday, January 26, 2014 9:31 AM

Answers

  • By Metro, do you mean designs for WinRT?  Metro is a style (also called Modern, I think) and applies to Windows 8+.  WinRT tablets use a subset of Windows 8, and there is no documented Serial communications support.  That it one of the reasons that I have little interest in such devices, and limit myself to full Window, x86 based, tablets and Desktops.

    The only information that I have (I have no insider insight) is that Microsoft has no plans to add serial device support.  For that reason, I have my doubts that WinRT provides the required APIs.  Why, you might ask?  The real issue is that device drivers have to be written by manufacturers that target the processor used in WinRT -- since these devices are not x86, completely new device drivers would have to be written.  Microsoft could do most of this work, but serial device manufacturers have very low profit margins.  Thus, the sales in the WinRT market, almost certainly, doesn't justify the additional effort that they would have to provide.  If the average USB serial adapter chipset sells for $3 to the USB device manufacturer, the sales volumes would have to be in the millions of units to justify the extra work.  Color me skeptical.

    Now, it isn't unreasonable to suggest that Bluetooth SPP (Serial Port Protocol) should be fully supported, since other BT device protocols are.  However, I haven't seen any evidence that this will be done any time soon.  If it is, I suspect that .NET support will follow.  And, at that point, we would have one mechanism to consume serial data in a WinRT device.

    Dick


    Dick Grier. Author of Visual Basic Programmer's Guide to Serial Communications 4. See www.hardandsoftware.net.

    Friday, January 31, 2014 2:01 AM
  • There are other options. We've used Sockets in the System.Net.Sockets namespace. For sending, we broadcast using UDP, for receiving, we listen to a specific port. I haven't yet written a blog post about it, but perhaps I should. 

    Be sure to add both "using System.Net;" and  "using System.Net.Sockets;"

    // Sending via UDP "broadcast"
    UdpClient client = new UdpClient(this.PortNumber);
    client.Connect(System.Net.IPAddress.Parse(this.IPAddress), this.PortNumber);
    string message = "Whatever I send to the Port";
    byte[] bytes = Encoding.ASCII.GetBytes(message);
    client.Send(bytes, message.Length);
    client.Close();
    

    // Listening to specific port
    byte[] receive_byte_array = new byte[1024];
    string received_data;
    using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    {
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, this.PortNumber);
        socket.Bind(endpoint);
    
        SocketState s = new SocketState();
        s.EndPoint = endpoint;
    
        int bytesRec = socket.Receive(receive_byte_array);
        received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length).Substring(0, bytesRec);
    
        this.ProcessReceivedData(received_data);
    }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, January 26, 2014 3:42 PM
    Moderator
  • You can use the Windows serial APIs.  These aren't too hard to implement... But, I'd have to ask why you might want to do so?  BTW, I have extensive API examples in my book, and there are examples available online -- but I still use the SerialPort class (type) for 99.99% of my needs.

    Dick


    Dick Grier. Author of Visual Basic Programmer's Guide to Serial Communications 4. See www.hardandsoftware.net.

    Sunday, January 26, 2014 6:49 PM
  • Celbester,

    Don't know if you've had a chance to look at anything I wrote here, but I think I may have jumped the gun a bit with my posts. The above stuff was really written for TCP/IP ports, not actually for serial ports. If I'm not mistaken, serial ports are going to require a bit more work (incoming data needs to be buffered, for one thing). In the next week or two, our next project is going to be accessing serial ports, so I will have a better handle on it then and can maybe offer up a better solution for you.

    Sorry!!


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Thursday, January 30, 2014 5:51 AM
    Moderator

All replies

  • There are other options. We've used Sockets in the System.Net.Sockets namespace. For sending, we broadcast using UDP, for receiving, we listen to a specific port. I haven't yet written a blog post about it, but perhaps I should. 

    Be sure to add both "using System.Net;" and  "using System.Net.Sockets;"

    // Sending via UDP "broadcast"
    UdpClient client = new UdpClient(this.PortNumber);
    client.Connect(System.Net.IPAddress.Parse(this.IPAddress), this.PortNumber);
    string message = "Whatever I send to the Port";
    byte[] bytes = Encoding.ASCII.GetBytes(message);
    client.Send(bytes, message.Length);
    client.Close();
    

    // Listening to specific port
    byte[] receive_byte_array = new byte[1024];
    string received_data;
    using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    {
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, this.PortNumber);
        socket.Bind(endpoint);
    
        SocketState s = new SocketState();
        s.EndPoint = endpoint;
    
        int bytesRec = socket.Receive(receive_byte_array);
        received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length).Substring(0, bytesRec);
    
        this.ProcessReceivedData(received_data);
    }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, January 26, 2014 3:42 PM
    Moderator
  • Hi, you can use P/Invoke to call windows API to do serial communication, see below link:

    http://msdn.microsoft.com/en-us/magazine/cc301786.aspx#S2

    http://msdn.microsoft.com/en-us/library/ff802693.aspx

    Sunday, January 26, 2014 4:43 PM
  • You can use the Windows serial APIs.  These aren't too hard to implement... But, I'd have to ask why you might want to do so?  BTW, I have extensive API examples in my book, and there are examples available online -- but I still use the SerialPort class (type) for 99.99% of my needs.

    Dick


    Dick Grier. Author of Visual Basic Programmer's Guide to Serial Communications 4. See www.hardandsoftware.net.

    Sunday, January 26, 2014 6:49 PM
  • Hi Dick,

    Thank you for the response!

    In Metro Apps, there's no equivalent Serial Port class. However, my requirement is to talk to the device over a serial port. Thus, was checking out other approaches that can be used.

    Monday, January 27, 2014 1:34 AM
  • Thank you, Bonnie! Will research further on this.
    Monday, January 27, 2014 1:34 AM
  • Thank you, lapheal! Will need to take time to research on this further.
    Monday, January 27, 2014 1:37 AM
  • You're welcome, Celbester! Let me know if you have any further questions about using the Socket classes.


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Monday, January 27, 2014 2:20 AM
    Moderator
  • Hi Bonnie,

    It'd greatly help if you have some full solution samples uploaded in your blog perhaps? Sorry pretty new on this. :s


    • Edited by Celbester Monday, January 27, 2014 2:55 AM Update
    Monday, January 27, 2014 2:54 AM
  • So you're looking for a sample for sending info to the port or listening to and reading from the port? Or both? Sending info is pretty easy ... the code I previously posted is pretty much all you need. Listening to a port requires a little more work, but not much. What I previously posted simply needs to be put into a separate thread that is constantly monitoring the port. Pretty simple actually, if you're familiar with threading at all.

    I can post a more detailed example later, maybe tomorrow (just finished watching a movie and it's just about bedtime now). And, unfortunately, I have an early morning meeting that will last a couple of hours. I do need a blog post on this topic, but I'll probably post here first (it'll be quicker than a blog post, I'll put in on my blog later).  So, hang in there for another 12-15 hours and after my morning meeting (which means probably after lunch), I'll try to throw something together for you.


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Monday, January 27, 2014 6:04 AM
    Moderator
  • Meeting is over, not lunch time yet ... you're in luck. Here's a class you can use for listening to the port:

    using System.Threading;
    
    public class SocketListener
    {
        // Declarations
        private Thread thread;
        private bool EndLoop;
        public int PortNumber { get; set; }
    
        // Constructor
        public SocketListener()
        {
            ThreadStart threadStart = new ThreadStart(this.Run);
            this.thread = new Thread(threadStart);
        }
        // Methods
        public void Start()
        {
            this.thread.Start();
        }
        public void Stop()
        {
            EndLoop = true;
        }
        private void Run()
        {
            while (EndLoop != true)
            {
                this.DoWork();
            }
        }
        private void DoWork()
        {
            this.ReceiveMessages();
            Thread.Sleep(1);
        }
        private void ReceiveMessages()
        {
            // here is where you put the code that I posted previously
            // for listening to the Port
        }
        private void ProcessReceivedData(string received_data)
        {
            // the previously posted code called this method
            // which is obviously where you'd process the data 
            // you received from the port
        }
    }
    

    Then, from your app, you'd start this process like this:

    SocketListener listener = new SocketListener();
    listener.Port = whatever port # you want to listen to
    listener.Start();

    The above class was just typed here free-hand, not copy/pasted from somewhere, so please excuse any typos there might be. 


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Monday, January 27, 2014 7:24 PM
    Moderator
  • Celbester,

    Don't know if you've had a chance to look at anything I wrote here, but I think I may have jumped the gun a bit with my posts. The above stuff was really written for TCP/IP ports, not actually for serial ports. If I'm not mistaken, serial ports are going to require a bit more work (incoming data needs to be buffered, for one thing). In the next week or two, our next project is going to be accessing serial ports, so I will have a better handle on it then and can maybe offer up a better solution for you.

    Sorry!!


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Thursday, January 30, 2014 5:51 AM
    Moderator
  • By Metro, do you mean designs for WinRT?  Metro is a style (also called Modern, I think) and applies to Windows 8+.  WinRT tablets use a subset of Windows 8, and there is no documented Serial communications support.  That it one of the reasons that I have little interest in such devices, and limit myself to full Window, x86 based, tablets and Desktops.

    The only information that I have (I have no insider insight) is that Microsoft has no plans to add serial device support.  For that reason, I have my doubts that WinRT provides the required APIs.  Why, you might ask?  The real issue is that device drivers have to be written by manufacturers that target the processor used in WinRT -- since these devices are not x86, completely new device drivers would have to be written.  Microsoft could do most of this work, but serial device manufacturers have very low profit margins.  Thus, the sales in the WinRT market, almost certainly, doesn't justify the additional effort that they would have to provide.  If the average USB serial adapter chipset sells for $3 to the USB device manufacturer, the sales volumes would have to be in the millions of units to justify the extra work.  Color me skeptical.

    Now, it isn't unreasonable to suggest that Bluetooth SPP (Serial Port Protocol) should be fully supported, since other BT device protocols are.  However, I haven't seen any evidence that this will be done any time soon.  If it is, I suspect that .NET support will follow.  And, at that point, we would have one mechanism to consume serial data in a WinRT device.

    Dick


    Dick Grier. Author of Visual Basic Programmer's Guide to Serial Communications 4. See www.hardandsoftware.net.

    Friday, January 31, 2014 2:01 AM
  • Hey Bonnie,

    Still thanks for sharing your time and help!! Really appreciate it!

    Friday, January 31, 2014 8:35 AM
  • Hi Dick! Thank you for the insights!
    Friday, January 31, 2014 1:02 PM