pythonmqtt

I cannot connect to a broker in mqtt and I would like to know why?


There are three files: broker.py; sub.py; pub.py;

broker.py:

import logging
import asyncio
from hbmqtt.broker import Broker

logger = logging.getLogger(__name__)

config = {
    'listeners': {
        'default':{
            'type': 'tcp',
            'bind': 'localhost:9999' 
        }
    },
    'sys_interval': 10,
    'topic-check':{
        'enabled': False
    }
}

broker = Broker(config)

@asyncio.coroutine
def startBroker():
yield from broker.start()

if __name__ == '__main__':
formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
logging.basicConfig(level=logging.INFO, format=formatter)
asyncio.get_event_loop().run_until_complete(startBroker())
asyncio.get_event_loop().run_forever()

sub.py:

import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect('localhost', 9999)

def on_connect(client, userdata, flags, rc):
    print("Connected to a broker!")
    client.subscribe("LINTANGtopic/test")

def on_message(client, userdata, message):
    print(message.payload.decode())

while True:
    client.on_connect = on_connect
    client.on_message = on_message
    client.loop_forever

pub.py:

import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect('localhost', 9999)

while True:
    client.publish("LINTANGtopic/test", input('Message: '))

So I first opened three terminals: In the first terminal, I entered "py broker.py" and it works well; In the second terminal, I entered "py sub.py" and it does not work and show nothing in the second terminal which should show "Connected to a broker" although it made the first terminal to show that :

[2020-07-29 14:01:41,925] :: INFO :: hbmqtt.broker :: Listener 'default': 1 connections acquired        
[2020-07-29 14:01:41,926] :: INFO :: hbmqtt.broker :: Connection from ::1:50450 on listener 'default'   
[2020-07-29 14:01:41,937] :: INFO :: transitions.core :: Exited state new
[2020-07-29 14:01:41,937] :: INFO :: transitions.core :: Entered state connected

In the third terminal, I entered "py pub.py" and it showed like this:

D:\MQTT>py pub.py
Message: 

I need to make the subscriber to be connected to a broker and I would like to know why this happened?


Solution

  • sub.py won't work as you have it.

    First client.loop_forever is a function so needs to be called with ().

    Second, the while True: loop is redundant and you shouldn't be setting the callback repeatedly.

    Try the following:

    import paho.mqtt.client as mqtt
    
    def on_connect(client, userdata, flags, rc):
        print("Connected to a broker!")
        client.subscribe("LINTANGtopic/test")
    
    def on_message(client, userdata, message):
        print(message.payload.decode())
    
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect('localhost', 9999)
    client.loop_forever()