Daniele P.
Daniele P.

Reputation: 98

paho.mqtt.client doesn't receive messages after subscription

I've wrote a little listener for my mosquitto server, code is provided. If i listen with the mosquitto_sub command, i correctly receive my published messages, but the python doesn't receive anything. I just have the "Connected" message. Please help.

import logging
from paho.mqtt.client import Client

logging.basicConfig(level="INFO")

def on_connect(client, userdata, flags, rc):
  logging.info("Connected")
  client.subscribe("test")

def on_message(client, userdata, msg):
  logging.info("Received " + msg)

client = Client("listener")
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost")
client.loop_forever()

Upvotes: 0

Views: 781

Answers (1)

hardillb
hardillb

Reputation: 59608

The problem is with your logging line in the on_message callback.

It doesn't know how to log the msg object

Change it to the following:

def on_message(client, userdata, msg):
  logging.info("Received " + str(msg.payload))

This converts the msg's payload to a string.

EDIT:

It is also worth pointing out that all the callbacks get run in a try/expect block that throws away any errors generated (hence the silent failure). Add your own try/expect blocks in the callback to trap and handle any errors that might occur.

Upvotes: 2

Related Questions