Modbus-TCP library for Windows Phone

First of all, I apologize for messing up the source in the Codeplex repository. I started using (Tortoise) Git, and I didn’t realize that only some files were been updated on the server.

Introduction.

So, well…this is the third (and the last?) part of the “Modbus saga” around Netduino, and the Micro Framework in general. I guess there’s enough stuffs to play with, at least for the moment.
This article is going to present the porting of the Modbus library for the Windows Phone platform. The MF library has been presented in my previous articles here and here.

The Windows Phone platform.

This is my very first application for Windows Phone. I’d say that I bought my new Nokia Lumia 800, just for experimentation other than for calling. I really can’t compare with any other phone, simply because I have no experience. By the way, it’s a very amazing machine, and if you look for genuine developing fun, that’s really satisfying.
Note that if I own a Windows Phone now, it’s because the great Paolo Patierno, giving me an excellent description of the framework/device. I was unsure, but he gave me several reasons for choosing a WP: thanks again Paolo for the good tip!
Porting the library written for the .Net MF to the Windows Phone (Mango) platform, was as easy as a walk in the park. By the way, I have a strong WPF knowledge because is my daily job, so the impact was almost insignificant. However, there are several considerations to keep in mind, because a phone is very different from a normal PC.

Probably you won’t believe me, but the most complex task was about the deployment. On a PC is trivial (especially using ClickOnce), but even on Netduino is very easy to upload an application to the board. For the Windows Phones is not so easy, instead.
To access your phone you must subscribe to the App Hub, which requires a fee yearly. Then, you have full access to upload any your app on your phone. I mean just for testing on your own device, not for distribute!. To take part of the Windows Marketplace, your app has to be certified. It’s a pretty complex task, and I still haven’t try, but I would try it.

The demo application.

The demo is very simple, yet straightforward to use.
It’s based on the raw I/Os exposed by the Netduino. It must considered the “Plus” version just because the Ethernet connection is required by the Modbus-TCP protocol.
The hardware bench can be set up in minutes. The first 8 I/Os (D0..D7) are supposed to be always inputs, while the remaining 6 I/Os of the row (D8..D13) are supposed to be always outputs. The analog inputs (A0..A5), of course, are meant as they actually are.
I have connected only 4 push-buttons for driving the inputs, and 4 leds for watching the output states. I also used a couple of trimpots for generating a variable voltage to feed two analogs. That’s enough for a small demo.

Note. The trimpots I’ve used are over 20 years old, and are clearly dirty, and full of dust. On the video below you can laugh by seeing the “effort” I’ve made to turn them.

Of course in the Netduino board I have uploaded the already known Modbus-TCP server library. So, the small board is waiting for incoming connection on the TCP port 502, as the Modbus specs suggest.
On the phone, the app firstly asks for the target host. It should asks for the Modbus address as well, but due the simplicity of the program I’ve skipped this kind of parameters. The address has been fixed to “1”, as in the Netduino is.
After the successful connection, a “panorama-page” presents the three-sections of the exposed I/Os: boolean inputs, boolean outputs (i.e. coils), and analog inputs. A clipped picture of the board helps to recognize easily the pins.

What else? The application explains by itself what to do: by pressing a button by the Netduino, the related “led” (simulated) is lighting up. Similarly, when you mark any of the outputs checkboxes, the related led will do also. For the analogs, there are three kinds of representation of the real-time value: the raw value (i.e. the ADC word read), the related voltage converted, and a percentage level bar.

The software.

Nothing much to say, other than I’ve used the new “async” features of the incoming .Net 4.5.
The application acts as a state machine, polling sequentially the input ports, then the output ports, then the analog ports, and start again. The phone framework does not allow any “synchronous” operation (I’d say also “fortunately”). That’s because the UI must be totally free from any hangs due to tight loops, or unexpected long processing. Instead, everything is async-based, and here the “async-await” pattern comes easy to help the development.
For example, the boolean inputs request can be written as follows:

        private async void QueryDiscretes()
        {
            await TaskEx.Run(() =>
            {
                //compose the Modbus command to be submitted
                var command = new ModbusCommand(ModbusCommand.FuncReadInputDiscretes);
                command.Offset = 0;
                command.Count = InputCount;

                //execute the command synchronously
                CommResponse result = App.Modbus
                    .ExecuteGeneric(App.Client, command);

                if (result.Status == CommResponse.Ack)
                {
                    //command successfully
                    Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        for (int i = 0; i < command.Count; i++)
                        {
                            var input = this._inputs[i];
                            input.Value = command.Data[input.Offset] == 0;
                        }
                    }));
                }
                else
                {
                    //some error

                }

                this._status = MachineState.CoilRequest;
            });
        }

Note the “async” modifier immediately before the routine declaration, as well as the “await” heading the “Task.Run” action.

The nice thing is that you can write “synchronous-like” a piece of code which will be executed “asynchronously”. That’s made by the “magic” pattern “async-await”, and some other simple considerations.
The only annoying thing is that the “real” code will run on a separate thread than the UI’s, thus any direct interaction with the UI must be dispatched to the main thread. If you don’t do that, you’ll get an exception.
Note that I’ve used the MVVM approach to write the app, so the interaction is made with the viewmodel, on which the “real” UI is bound. Any modification to the viewmodel is immediately reflected to the UI.

The demo video.

Okay, here is a short video about the phone-Netduino interaction via Modbus-TCP. Despite the awkward phonemes coming out my mouth, I hope it’s clear enough from the technical perspective!

Conclusions.

I hope this small demo app might be useful for someone, at least as base for something “concrete”.
I guess this experience could be tried on the Fez board, because it seems that the library has been tested successfully. About Gadgeteers or Netduino Go!, I think should be working, but any TCP/IP connection must be available.
As usual, the full sources are hosted in the Codeplex repository: http://cetdevelop.codeplex.com/

14 thoughts on “Modbus-TCP library for Windows Phone

    • Mario Vernari

      Thanks for the credit, but my name is Mario Vernari (have a look at the “About” section). Georgi is a friend of mine!

  1. treckerfreak

    Hi,

    I want to use your C# project for an other Hardware Wago PLC 750.481. I use an other modbus library for a windows application but for WP7 I can not use this library.

    If I want to open your project I get an error message can’t open this project with this version.
    I use Visual Studio 2012 C# Express for Windows Phone.

    Can yoe tell me what version I need.

    • Mario Vernari

      Sorry, but I’m not sure to understand.
      So, you want to use a Wago PLC as Modbus-TCP slave, and it is supposed to be connected via Ethernet to any Wi-Fi enabled network (e.g. a home router). Then you have a WP7 (e.g. Lumia 800) phone, and you want to edit the project using VS 2012. The phone must have the Wi-Fi connection enabled. Is it all correct?
      At the time of the develop of the libraries (both Netduino and WP7) there was not any VS 2012 version, thus I used all the VS 2010 suite. I guess to have tested them both on the Express products, as well as the professional/ultimate edition.
      I still haven’t installed VS 2012 on my home PC, but I wonder what kind of error do you see. Could you describe it?

      • treckerfreak

        Hi,
        sorry I use VS2010 C# espress and the wp7 edition.
        I have no problems with the communication between my phone (htc trophy) and my plc. Itested the modbus communication with the wp7 modbus app modbus doctor.

        My problem is to open your demo project e.g. Cet.Develop.WP.IO
        After starting VS2012 phone edition I got always the message. This typ is not supported fron this installation.

        My secound try was to open an empty WP7 project and to import the modbus .cs files. But I failed.

        Can you give me an easy project in VS2012 Express phone edition where I can export the modbus files?

        Thanks a lot

  2. matthew

    is the phone talking to the board via a usb cable or over wifi in some manner? This is not clear to me how they do basic physical communication.

    • Mario Vernari

      All my experiments were made over the normal Wi-fi. Honestly, I never tried over the cellular network, but it should working: the primary problem is the location of the IPs, which are both private.
      I don’t know any way to leverage the usb cable for tcp/ip communication.
      Cheers

  3. matthew

    Ah I see now, in my mind you would not leverage the usb cable for ip communication, you would leverage to talk serial, which is what it is natively best at😀

    My interest would be in that most devices that speak modbus don’t have wireless cards on them.

  4. Vinod

    Hi Mario,

    I’m new to windows mobile and when i tried to use your source code in VS2012, i get that Async CTP library_phone.dll not supported.

    Could you help me a more simple program to start with? I searched online but it seems Async CTP is only applicable for VS2010 SP1 update.

    I have wp8 so what do i have to do ? This is my first program.

    Please helpme.

    Vinod

    • Mario Vernari

      The original project was published when the .net 4.5 was still a preview, and the async library could be accessed only by donwloading then linking a DLL, but it was a “CTP” (=Community Tech Preview).
      If you have VS 2012 installed, you should own everything you need for the test. I never testes the phone sources for the WP8, but I guess they should be fully compatibles.
      So, take care to use the “V2” branch of the whole package only. That should be already tuned for the 2012 edition of Visual Studio. At most, the things should going even better because I hadn’t the professional version of VS, but only the free Express.
      Hope it helps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s