#2947 MQTT Via Paho MQTT - MWE

Nick Yesterday

I really struggled with getting the interop types to work for a MWE to use the paho MQTT Java client library. Wanted to share for anyone else trying to do the same, and quite possibly myself 6 months from now when I forgot.

First you need to put the jar file in the /lib/java/ext directory of your Fantom installation. I'm sure there is a way to add this to a specific directory in you project and make it work, but I put it every location that I thought was referenced in the Class Path - Compiler section but none of them seemed to work.

The root of my trouble was trying to get the password and message as bytes and I needed the fanx.interop::ByteArray for that. Hopefully this helps someone else.

//Needed to get the MqttClient class
using [java]org.eclipse.paho.mqttv5.client

// Needed to get the MqttMessage class. Not strictly needed
//as you can publish with a topic, message, qos, retained flag manually
using [java]org.eclipse.paho.mqttv5.common

//Interop type to make the byte arrays work
using [java]fanx.interop::ByteArray

class Stmts{

    //Static helper to make the byte arrays
    static ByteArray strToBA(Str str) { 
        array := ByteArray.make(str.size)
        str.each |char, i| { array[i] = char } 
        return array
    }

    Void main(){
        //setup
        un := "YourUsername"
        pw := "YourPassword" 
        broker := "YourBroker"
        clientId := "fantomclient"
        //
        client := MqttClient(broker,clientId)
        options := MqttConnectionOptions()
            options.setUserName(un)
            options.setPassword(strToBA(pw))
        client.connect(options)
        //message details
        topic := "fantomtopic"
        qos := 1
        //Publish a message with the current time
        msg := "from fantom" + " at " + Time.now().toStr
        msgBytes := Stmts.strToBA(msg)
        // Build an MqttMessage object
        mqm := MqttMessage(msgBytes)
            mqm.setQos(qos)
            mqm.setRetained(false)
        //Publish the message
        client.publish(topic,mqm)
        //Disconnect and close the client
        client.disconnect()
        client.close()
    }
}

brian Yesterday

Its actually better to turn a jar file into a pod file so its a normal Fantom module. A good example is how we turn "sedona.jar" into "sedona.pod" in Haxall here. Note the key line in build.fan is this one:

resDirs = [`sedona.jar`]

Then you don't require special jars to be installed, its just a normal pod.

Login or Signup to reply.