Skip to content

Instantly share code, notes, and snippets.

Embed
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("java.io.tmpdir")
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence("${tmpDir}/mqtt")
//org
String org = 'myOrg'
//type
String deviceType = 'groovy'
String deviceId = 'gc001'
// auth-token
def authToken = 'theauthtoken'.toCharArray()
String mqttHost = "tcp://${org}.messaging.internetofthings.ibmcloud.com:1883"
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}"
int AT_LEAST_ONCE_QOS = 0
MqttClient client = new MqttClient(mqttHost, clientId, dataStore)
MqttConnectOptions connectOptions = new MqttConnectOptions( cleanSession: true, userName: userName, password: authToken )
println "Connecting to: ${mqttHost}"
client.connect(connectOptions)
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}"
client.disconnect()
println "Client disconnected."
@maram2012

This comment has been minimized.

Copy link

maram2012 commented May 2, 2018

I have a problem with mqttHost "tcp://${org}.messaging.internetofthings.ibmcloud.com:1883"

this is he error i got "Caused by: java.net.UnknownHostException: myOrg.messaging.internetofthings.ibmcloud.com"

Could you help plz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.