user5740843
user5740843

Reputation: 1620

MQTT will not publish over Python

I'm somewhat experienced when it comes to MQTT and in Python and this has baffled me for the last hour or so.

This is the script I'm working with:

#!/usr/bin/python
import json
import socket
import paho.mqtt.client as mqtt

client = mqtt.Client()
try:
        client.connect('localhost', 4444)
except:
        print "ERROR: Could not connect to MQTT."

mode_msg = {
        'mode': '2'
}

client.publish("set", payload=json.dumps(mode_msg), qos=2, retain=False)

This code won't run. I have no idea why. Most baffeling is, when I add " client.loop_forever()" at the bottom, it will run...

I've tried adding "client.disconnect()" at the bottom as well to get it to disconnect properly, but it all won't help. Is there something I'm missing right now?

Upvotes: 0

Views: 4016

Answers (2)

hardillb
hardillb

Reputation: 59638

It looks like you are trying to publish a single message, the paho client has a specific message to do just that.

#!/usr/bin/python
import paho.mqtt.publish as publish
mode_msg = {
        'mode': '2'
}

publish.single("paho/test/single", payload=json.dumps(mode_msg), qos=2, hostname="localhost", port=4444)

The problem with your original code is that you are you need to run the network loop to handle the publish (and because you are publishing with qos=2 which needs to reply to the broker acknowledgement of the publish), you can do it as follows:

#!/usr/bin/python
import json
import paho.mqtt.client as mqtt

run = True

def on_publish(client, userdata, mid):
    run = False;

client = mqtt.Client()
client.on_publish = on_publish
try:
        client.connect('localhost', 4444)
except:
        print "ERROR: Could not connect to MQTT."

mode_msg = {
        'mode': '2'
}

client.publish("set", payload=json.dumps(mode_msg), qos=2, retain=False)
while run:
    client.loop()
client.disconnect()

client.loop_forever() won't work because it does exactly what the name suggests, it loops forever, so would never reach your client.disconnect(). This uses the on_publish callback to break out of the loop calling client.loop() and then disconnect.

Upvotes: 4

nos
nos

Reputation: 229108

The paho.mqtt client library is built around an event loop that must run to properly process and maintain the MQTT protocol.

Thus to make things happen you need to call some of the loop() functions, as mentioned in the documentation

Upvotes: 0

Related Questions