Project Mercury Part I – Subscribing to an MQTT Topic

MQTT is a wonderful tool for the smart home enthusiast. Many different products and applications support it, allowing you to tie a lot of different technologies together in one cohesive home automation system. It is even more useful when you’ve got devices that do not support MQTT directly but do allow programmatic access through an SDK or API, which allows you to put together a custom app that combines MQTT with that other product. An interesting challenge I’ve come across, though, is that while most of the examples for SDKs that I use are written in VB.Net and there are NO examples of using MQTT in VB.Net….

The lack of examples isn’t all that surprising. VB.Net is considered more of a hobbyist’s language and the more professional .Net language is C#. For me, personally, that’s a challenge, because most of my desktop language experience (professionally) has been with VB and almost none with C#. I really do best when I have examples to work with, as I’m not any kind of great programmer – I may not even be as good as you are, so please don’t feel intimidated by trying new projects!

There are converters out there which will translate C# into VB, but my day job is working with web code, not desktop – I don’t have a strong enough grasp of either language to really tell when the translator has messed up. To really complicate matters, I work exclusively with procedural code (actions are executed in order, from the first line of code through to the end, with a few exceptions, such as JavaScript validation, etc). MQTT requires you to work with asynchronous code, so this is a real learning opportunity for me.

This entry is going to cover adding the MQTTnet library to VB.Net and setting up a very simple Windows Form app that displays messages published to an MQTT topic. The post assumes that you’ve got Visual Studio 2017 Community Edition installed and that you’ve read the prior blog entry on MQTT (HERE). If you’re using a newer version of VS, you may need to make adjustments. The best part of this example is that it takes less than 30 lines of code to set up a working example of an MQTT subscriber/reader!

First, create a new Windows Form app in Visual Studio. I generally set the project name (as well as the text displayed on the form) at the start, then add any controls – in this case, a text box, which I name “txtLog,” set to “MultiLine” and resize to use most of the form’s available real estate.

We’re not going to keep the default code, but here’s what it will look like before we do any other modifications.

I then double-click the form to open the code. Also, I rename Form1.Vb to Mercury.vb – not necessary at all, just a personal preference – I’ll avoid questions by explaining it ahead of time!

In Solution Explorer, right click the solution and select “Manage Nuget Packages for Solution.” Click the BROWSE tab and enter MQTTnet in the search field. Select v2.8.5 (or newer, if available).

If your project is not checked, select the checkbox, then click the Install button below. After installing, you can close the Nuget tab.

The code itself is only 27 lines, most of it your basic housekeeping.

1) Import required libraries
2) Declare the Class
3) Initialize the strong that will hold our MQTT messages

The next step is interesting – we initialize the MQTT client at form load, so we change the load sub to an Async Function.

4) Modify Form load
5) Initialize the MQTT class and the client class.
6) Set up the event handler (we’re listening for messages, the event handler tells the code what to do when a message arrives)
7) Set up connection options for the MQTT broker – note that I’m not connecting to the default port of 1883 – I handle this through NAT in my router, to keep pranksters out.
8) Connect to the broker
9) Set the thread to subscribe to
10) Subscribe to the thread

The next section is the event handler mentioned in step 6.

11) Format the message – the reason for the Encoding.UTF8.ToString function is because the data is returned as Byte. Not very useful for us since we are looking for string data. I added VB Carriage Return line Feed at the end so it will display 1 message per 1 line in the text box.
12) Call append textbox function – here we could do anything – evaluate the message value, call a database query, execute a command to send a return message, whatever

The next two sections are interesting – because the text box is loaded by the form, in the first function, you get a threading error if you try to append text on the form in the sub handling the message received from the MQTT broker.

13) Set up a delegate to handle the thread if needed
14) Check to see if the command to append text was called from a separate thread – if so, use the delegate. if not, just append the text

End. As you can see in this picture, the app easily picks up messages from the broker.

It turns out that the library is a LOT easier to use than I initially expected. Part of the trouble was trying to translate C# apps into VB. Once I decided to settle down and read the definitions in the code, it got a lot easier. Though there are no VB examples for this on the Internet (aside from this one, now!), there were some great explanations and examples of how to use invokerequired and invoke.

The next entry in this series will show how to PUBLISH messages to the broker, send options, and other important functions. Future entries will show you how to take the data you receive and do more advanced actions!

SmarterHome.club is the website for our Facebook community, The Smarter Home Club – which is an umbrella for all kinds of smart home technologies – home automation, security, custom electronics, weather stations, alternative energy, you name it. DIY focused.

If you’re interested in joining the Smarter Home Club’s Facebook group, please follow this link:

The Smarter Home Club on Facebook