Last active
July 30, 2019 03:34
-
-
Save magnuspalmer/bdc89e8f19ed76cf0799 to your computer and use it in GitHub Desktop.
Groovy mqtt client bluemix IoT services
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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
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