← Back to team overview

mosquitto-users team mailing list archive

Re: python daemon - on_message callback not fired

 

It looks like this is an interaction with daemon.runner. I don't know
what is causing it yet, but the modified example below works fine.

Cheers,

Roger

#!/usr/bin/python

import mosquitto
import config
import time

class Client():
    def __init__(self):
        self.mc = None
        print('Class initialization...')
        print('Creating an instance of MQ client...')
        try:
            self.mc = mosquitto.Mosquitto(config.DEVICE_NAME)
            self.mc.connect(host = config.MQ_BROKER_ADDRESS)
            print('Successfully created MQ client...')

            print('Subscribing to topics...')
            for topic in config.MQ_TOPICS:
                result = self.mc.subscribe(topic, 0)

            print('Settings up callbacks...')
            self.mc.on_message = self.on_message
            print('Done setting up callbacks')
            print('Sending self-test message...')
            self.send_message(config.MQ_TEST_TOPIC,config.MQ_TEST_MESSAGE)
            print('Finished initialization...')

        except Exception as e:
            print('Failed creating MQ client: %s' % e.message)
    def run(self):
        print('Entering running state...')
        self.mc.loop_forever()

    def on_message(self, mosq, obj, msg):
        print("Message received on topic "+msg.topic+" "+msg.payload)

    def send_message(self, topic, message):
        res = self.mc.publish(topic, message)
        print(res)

app = Client()
app.run()


Follow ups

References