Hi all,
i wanted to share my mqtt eperiences, trying to find a fast way to implement MQTT in xojo is pretty hard since MQTT can get pretty complex. So i found that CURL has MQTT (limited) implemented and is usable with the CURLSMBS class (maybe using CURLMBS etc also).
You need a subclass of CURLSMBS named myCURLSMBS, add the “Write” event:
Function Write(data as string, dataSize as Integer) Handles Write as integer
Var packet As MemoryBlock = data
packet.LittleEndian = False
Var stream As New BinaryStream(packet)
var topic_length As UInt16 = stream.ReadUInt16
Var topic As String = stream.Read(topic_length, Encodings.UTF8)
var payload As String = stream.Read(stream.Length - (2 + topic_length))
System.DebugLog "Topic: " + topic
System.DebugLog "Payload: " + payload
Return dataSize
End Function
On your main window add “c As myCURLSMBS” (to receive/subscribe) and “c1 As myCURLSMBS” (to send/publish) as a property.
So this is how to get started to SUBSCRIBE:
c = New myCURLSMBS
'c.OptionVerbose=true
'c.CollectDebugMessages = True
c.YieldTime = True
c.OptionGet = True
c.OptionURL = "mqtt://broker.hivemq.com:1883/testing123"
Var status As Integer = c.Perform
What is happening is we request the “mqtt://” protocol to be used as a GET request, internally this means “subscribe to an mqtt topic given by the OptionURL”. We set the required values, you could optionally set the optionVerbose and CollectDebugMessages to get more info.
Now we can also PUBLISH to a topic:
c1 = New CURLSMBS
c1.OptionUserAgent = "Xojo CURL MQTT 1"
c1.CollectDebugMessages = True
c1.CollectOutputData = true
c1.OptionVerbose=true
c1.YieldTime = True
c1.OptionURL = "mqtt://broker.hivemq.com:1883/testing123"
c1.OptionPostFields = "Hello World from Xojo"
c1.OptionPost = True
Var status As Integer = c1.Perform
System.DebugLog CurrentMethodName + ", code: " + status.ToString
System.DebugLog c1.DebugMessages
System.DebugLog c1.OutputData
System.DebugLog "------------------"
I’ve commented out some additionals so you can easily enable them. We set the same topic and host, but this time we set OptionPOST = True and we create a new instance since this just publishes and quits.
Currently CURL doesn’t support all mqtt features like client id (i tried the useragent option but it didn’t work).
So there are some limitations:
- Only QoS level 0 is implemented for publish
- No way to set retain flag for publish
- No TLS (mqtts) support
- Naive EAGAIN handling will not handle split messages
I hope you have a happy day using MQTT with CURL provided by Xojo, CURL and MBS.