Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Groovy mqtt client bluemix IoT services
@Grab(group='org.eclipse.paho', module='mqtt-client', version='0.4.0')
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence
String tmpDir = System.getProperty("")
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence("${tmpDir}/mqtt")
String org = 'myOrg'
String deviceType = 'groovy'
String deviceId = 'gc001'
// auth-token
def authToken = 'theauthtoken'.toCharArray()
String mqttHost = "tcp://${org}"
String userName = 'use-token-auth'
String hardcodedSimpleEventJson = '{"event": { "id": "123", "source": "myDevice123", "timestamp": "2015-06-22T08:00:01", "text": "A simple event", "location" : "drm3btev3e86" }}'
String clientId = "d:${org}:${deviceType}:${deviceId}"
MqttClient client = new MqttClient(mqttHost, clientId, dataStore)
MqttConnectOptions connectOptions = new MqttConnectOptions( cleanSession: true, userName: userName, password: authToken )
println "Connecting to: ${mqttHost}"
MqttMessage message = new MqttMessage(hardcodedSimpleEventJson.bytes)
message.qos = AT_LEAST_ONCE_QOS
message.retained = false
client.publish('iot-2/evt/simple-event/fmt/json', message)
println "Message published: ${hardcodedSimpleEventJson}"
println "Client disconnected."

This comment has been minimized.

Copy link

@maram2012 maram2012 commented May 2, 2018

I have a problem with mqttHost "tcp://${org}"

this is he error i got "Caused by:"

Could you help plz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment