MQTT in Xojo
Recently a client asked about whether we can do MQTT to subscribe to a topic and receive messages or even send messages.
MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for devices with limited resources and for low-bandwidth, high-latency, or unreliable networks. It operates on a publish/subscribe model which allows for efficient distribution of information to many receivers.
RabbitMQ
A quick search here found the RabbitMQ classes we have. They allow you to connect to the a server running the open source message broker software RabbitMQ. You can use our plugin to use a lot of things there and they have a MQTT plugin, so you can connect your MQTT stuff with the RabbitMQ server.
See MBS Xojo RabbitMQ Plugin, the example files and blog posts about it.
CURL
We also discovered that we have MQTT capabilities built-in to the CURL library. Just use an URL with "mqtt://" followed by IP or domain name of the server. In the path of the URL goes the subject to subscribe or post to. If you like, set a user name and password. Let us show you with some example code.
Post Message
To post you put the data into the OptionPostFields property and run the transfer. For example here we make a
On success the Perform function returns zero. In case of a failure, please check the debug log for details.
Subscribe
To subscribe you connect and then react to incoming data with Write event in your CURLSMBS subclass. But first you need to run a transfer asynchronously in the background. The connection stays open as long as you want to listen to incoming messages. Here is the sample code to setup the connection:
As you see we keep a reference to the CURLSMBS object in a property. And we use our improvements in CURLSMultiMBS class from last year to simply use the shared instance to run the transfer in the background.
Receive
When data is received, the Write event is called by curl. We get the received data and can parse it. For the MQTT messages we get two bytes with the length of the topic followed with the message data. We use a MemoryBlock to read the length field as that are the first 2 bytes.
The #pragma is there to avoid some unintentional switching to another thread, if you use a loop here. On the end we need to return the number of bytes we accepted, so we simply return data size.
Please try and let us know whether it works for you. Sending and receiving MQTT messages in Xojo applications may help you to automate a few things in your company.
If you need more we could of course add MQTT library in the future. Or you just use the new Python class in our plugin to use a MQTT module for Python to connect.