20

I'm about to start developing a small app (C#) that communicates with a PLC and a testing unit via Serial Ports - this is my first venture into this area.

In essence, I am going to send the PLC a signal to start an operation, and then I am going to wait for the result of that operation from the test unit (which will be independently communicating with the PLC) to return a ASCII string.

Depending on the content of that string, I may want to listen to a signal from the PLC...

It's all new to me, so at the moment, I'm just researching System.IO.Ports.SerialPort; digression: are there third part products out there than simplify interaction with the Serial Port, or are the built-in classes as good as you will get? I'm thinking of ease of use as opposed to better features.

However, it will be a few weeks before the hardware is available for development and testing, so I was wondering how I could simulate communication to/from the serial port so that I can start developing my app?

[I don't yet know how the PLC and the PC are due to communicate - I understand it will be binary rather than text, but at the moment, that is all I know.]

1
  • I've always wondered this while writing some apps for my Arduino. As far as I know the only way to really simulate data on the serial port is by using a hardware loopback device (there are directions out there for making your own and it's not terribly hard). The interface answer below is a good alternative.
    – Pete
    Apr 12, 2011 at 14:23

7 Answers 7

16

Abstract away your serial port comms behind an interface so that you can code your app against the interface and then test with a 'fake' implementation. When you've got the hardware for the real thing, you can code up the 'real' implementation of the interface and swap out the fake one.

So for example, you'd have an interface

public interface ISerialComms
{
    void SendMessage(string message)
}

and you'd code your app against that interface using a fake implementation:

public class FakeSerialComms : ISerialComms
{
    public void SendMessage(string message)
    {
        //some implementation
    }
}

Hope that helps!

3
  • 2
    I like this solution. For integration testing though I often find that I don't have access to the equipment I'm interfacing with unless I'm at the customer site. This somewhat limits my ability to effectively do integration tests unless I write some kind of simulator.
    – Cole W
    Apr 12, 2011 at 14:33
  • @Cole of course, it will need some sort of simulator at some point, but for getting started the interface should be enough. @n8wrl Yeah, sure is, should have mentioned that! :)
    – DavidGouge
    Apr 12, 2011 at 14:38
  • Not done anything like this before, but makes sense...if I can figure out exactly how to do it.
    – CJM
    Apr 12, 2011 at 14:45
13

I've had some success in the past using com0com.

3
  • +1 I actually went back and used this and it works better than the app I suggested below. The app I suggested below seems to block on all calls to these ports for whatever reason.
    – Cole W
    Apr 28, 2011 at 19:22
  • Note: I changed the link to the actual project page instead of com0com.sourceforge.net: that one is partly 'taken over' by Virtual Serial Port Driver from Eltima Software. Nothing wrong with that software but we don't want to lure people into clicking their download link instead of com0com's plus it belongs in a separate answer.
    – stijn
    Dec 23, 2020 at 9:52
  • Additional note: com0com works but do read the README: at the time of writing installation on recent Windows versions will result in the driver not being loaded because it lacks signing so you need to disable "Driver Signature Enforcement" i.e. equivalent of bcdedit.exe -set TESTSIGNING ON. Use at your own risk.
    – stijn
    Dec 23, 2020 at 9:55
3

There are two pieces of software that I have found invaluable while doing serial port work.

Free Serial Port Monitor

http://www.serial-port-monitor.com

Despite the cheesy name, it is actually quite useful. Note that you should have it stop listening to your port if you go to unplug a USB-to-Serial converter. Otherwise it can crash (well... wait indefinitely on exit, which is annoying). It doesn't have to put itself in the middle of a serial connection to sniff data. It monitors the IO using the Win32 API.

Franson Serial Port Tools

http://franson.com/serialtools/

Or.. any loopback software really. There are lots out there. This allows you to send data and receive it within software. If you end up doing any GPS work, Franson also has a nice GPS simulator so you don't have to sit outside the whole time to debug code.


Finally, if you have had enough with the built-in serial class and its horrendous shortcomings, then you need a replacement, and going straight to the Win32 API will take forever.

CommStudio

I have found CommStudio to be absolutely rock solid. Quite frankly, after spending 5 months researching and buying other options, it is the only one that works perfectly with removable USB adapters. All of the other solutions have issues when the device is plugged back in. You can download their free "Express" version here: http://www.componentsource.com/products/commstudio/downloads.html?rv=42917

3

I have wrote an article on this topic using Virtual Serial Port Driver 9.0 standard using Microsoft SerialPort Class (Sytem.IO.Ports), it is of course possible to use any other comm port tool.

In the software I create 2 virtual ports COM1 and COM2.

I use COM1 to emulate as data sender.

I use COM2 to receive what ever being send from COM1.

This is helpful if you are developing Embedded or IoT solution.

Emulator (in this example as random accelerometer)

private static bool _continue;
private static SerialPort _serialPort;

public static void Main()
{
    var stringComparer = StringComparer.OrdinalIgnoreCase;
    var readThread = new Thread(Read);

    _serialPort = new SerialPort
    {
        PortName = "COM1",
        ReadTimeout = 500,
        WriteTimeout = 500
    };

    _serialPort.Open();
    _continue = true;
    readThread.Start();

    while (_continue)
    {
        var x = ValueGenerator();
        var y = ValueGenerator();
        var z = ValueGenerator();
        var message = $"x:{x};y:{y};z:{z}";

        if (stringComparer.Equals("quit", message))
        {
            _continue = false;
        }
        else
        {
            _serialPort.WriteLine(message);
            Thread.Sleep(200);
        }
    }

    readThread.Join();
    _serialPort.Close();
}

public static double ValueGenerator()
{
    const int range = 1;
    var random = new Random();
    return random.NextDouble() * range;
}

public static void Read()
{
    while (_continue)
    {
        try
        {
            var message = _serialPort.ReadLine();
            Console.WriteLine(message);
        }
        catch (TimeoutException) { }
    }
}

And my data receiver is almost similar

private static bool _continue;
private static SerialPort _serialPort;

public static void Main()
{
    var stringComparer = StringComparer.OrdinalIgnoreCase;
    var readThread = new Thread(Read);

    _serialPort = new SerialPort
    {
        PortName = "COM2",
        ReadTimeout = 500,
        WriteTimeout = 500
    };

    _serialPort.Open();
    _continue = true;
    readThread.Start();

    while (_continue)
    {
        var message = Console.ReadLine();

        if (stringComparer.Equals("quit", message))
        {
            _continue = false;
        }
        else
        {
            _serialPort.WriteLine(message);
        }
    }

    readThread.Join();
    _serialPort.Close();
}

public static void Read()
{
    while (_continue)
    {
        try
        {
            var message = _serialPort.ReadLine();
            Console.WriteLine(message);
        }
        catch (TimeoutException) { }
    }
}

Disclaimer: the link of this guideline refer to my personal web site.

2

I like David's answer above but if your looking to do integration tests and actually test your serial port communication I have used and application called ViN soft virtual serial cable in the past to basically create 2 serial ports on your machine that are connected by a virtual cable.

Also if you have a serial port on your development machine you could use it to connect to another machine that has a serial port and write an application that will basically simulate the communication of the PLC.

I would prefer to use a combination of both David's method and this method to ensure proper testing.

1
  • I have other machines available, so running a test app on one of them is entirely possible and is my fallback posiiton. I'll check out the ViN soft app as well. Thanks
    – CJM
    Apr 12, 2011 at 14:41
2

There is another resource out there that emulates serial ports for windows if anyone else is still looking for decent serial debugging tools.

The 32-bit version is free and seems pretty decent. It's called Virtual Serial Ports Emulator.

0

Very old but still might be useful to some. Instead of relying on COM interaction, just use the SerialPort.BaseStream to communicate with the port. This allows you to simply use a standard stream interface for communication, in other words, doesn't matter if you use serial ports, TCP connections, or even file streams. Perfect for simulation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.