1
votes

I'm using the following code from MQTT Paho project to subscribe to messages from my mqtt broker. I tested the connection using mosquitto_sub and I receive the messages there. However, when I run the following code it doesn't receive any messages and no output is printed. I checked the topic and host.

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("test")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()

client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)
client.loop_forever()

The following error is logged by the broker:

Invalid protocol "MQTT" in CONNECT from ::1.
Socket read error on client (null), disconnecting.

EDIT Thanks to @hardillb for pointing out the outdated MQTT version.

Everything worked after I did the following:

  1. sudo apt-get purge mosquitto
  2. sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
  3. sudo apt-get update
  4. sudo apt-get install mosquitto
1
When you say doesn't work, do you get any output at all? Also what platform are you running this on?hardillb
No output at all.Andrei
If your not even getting the "Connected with result code..." message then you should check the broker logs to see if it shows why the client has not connected. The code you've posted is working fine herehardillb
I added the error message that is logged by the brokerAndrei
What broker and what version are you using?hardillb

1 Answers

1
votes

This is most likely because you are using an old version of mosquitto and the python is expecting a newer build that supports MQTT 3.1.1

Try changing the code as shown:

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("test")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

# Change made HERE 
client = mqtt.Client(protocol=MQTTv31)

client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)
client.loop_forever()

You should also upgrade your broker as soon as possible, that version is incredibly out of date and has a number of known issues, the current version is 1.4.10