Skip to content

Instantly share code, notes, and snippets.

@xAPPO
Forked from magnuspalmer/mqttclient.groovy
Created November 9, 2018 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xAPPO/aec54f7c58545999bf2d03a16c71735f to your computer and use it in GitHub Desktop.
Save xAPPO/aec54f7c58545999bf2d03a16c71735f to your computer and use it in GitHub Desktop.
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."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment