Michael Nielsen
Michael Nielsen

Reputation: 1242

Python Paho MQTT og IBM Watson IoT

I'm trying to push JSON data to the IBM Watson IoT platform with Python 2.7 and Paho MQTT 1.3.1.

It does work with the IoT Python client from IBM's Github, but my device-enviroment doesn't allow this extension.

I've disabled TLS encryption in my IBM Watson IoT when testing.

This is my code:

import json
import paho.mqtt.client as mqtt

client = mqtt.Client('d:ORG-ID:DEVICE-TYPE:DEVICE-ID')

client.username_pw_set('use-token-auth', 'TOKEN')
client.connect('ORG-ID.messaging.internetofthings.ibmcloud.com', 1883, 60)

payload = { 'temperature': 20 }
client.publish('iot-2/evt/test/fmt/json', json.dumps(payload))

client.disconnect()

I'm not getting errors, and my IBM Watson IoT dashboard does say:

Connected on Tuesday, October 10, 2017 at 12:42:26 PM from MY-IP with an insecure connection

But the data is not shown...

Upvotes: 0

Views: 1313

Answers (2)

Liyakat Shaikh
Liyakat Shaikh

Reputation: 115

you need to change your payload format as below

payload = {'d':{'temperature':20}}

Upvotes: 0

hardillb
hardillb

Reputation: 59608

You need to run the MQTT network loop to make sure that the data is sent after the publish and before you disconnect. There are a couple of ways to do this.

The simplest is just to add the client.loop() call between the publish and disconnect calls:

import json
import paho.mqtt.client as mqtt

client = mqtt.Client('d:ORG-ID:DEVICE-TYPE:DEVICE-ID')

client.username_pw_set('use-token-auth', 'TOKEN')
client.connect('ORG-ID.messaging.internetofthings.ibmcloud.com', 1883, 60)

payload = { 'temperature': 20 }
client.publish('iot-2/evt/test/fmt/json', json.dumps(payload))

client.loop()

client.disconnect()

The other is to use the single shot publish call that does the connect, publish and disconnect all in one go.

single(topic, payload=None, qos=0, retain=False, hostname="localhost",
port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None,
protocol=mqtt.MQTTv311)

Full details about the single shot method are in the docs here:

Upvotes: 2

Related Questions