1

Following this great tutorial on implementing MQTT in Python. Works fine when I run the publisher script but hangs on the subscriber script. I am running both scripts at the same time in separate command lines. Here are both my codes:

#pub.py

import paho.mqtt.client as mqtt
import logging
import json
import time
import random
logging.basicConfig(level=logging.INFO)
# use DEBUG, INFO, WARNING

username="xxxxx"
password="xxxxx"
broker_url ='xxxxx'
broker_port=0000
client_id=f"client-{random.randint(0, 100)}"
to_wait=5
topic='hey-hey'
publish_count = 3
msg= 'Hey'

def on_log(client, userdata, level, buf):
    logging.info(buf)
    client.on_log = on_log

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            logging.info("Connected to Broker!: {}".format(rc))
        else:
            logging.info("Failed to Connect with code: "+str(rc))
    
    client = mqtt.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker_url, broker_port)
    return client

def on_publish(client):
    count = 1
    while count <= publish_count:
        time.sleep(to_wait)
        message = str(msg)
        result = client.publish(topic, message, 1, 1)
        status = result[0]
        if status == 0:
            published= client_id+ ' sent the message: ' +message)
            print(published)
        else:
            print(f"Failed to send the message")
        count +=1
        
def run():
    device1 = connect_mqtt()
    device1.loop_start
    on_publish(device1)
    device1.loop_stop()
    
if __name__ == '__main__':
    run()

And I get:

client-27 sent the message: Hey
client-27 sent the message: Hey
client-27 sent the message: Hey

However, for sub.py:

import paho.mqtt.client as mqtt
import logging
import json
import time
import random
logging.basicConfig(level=logging.INFO)
from datetime import datetime 
# use DEBUG, INFO, WARNING

username="xxxx"
password="xxxxxx"
broker_url ='xxxxx'
broker_port=0000
client_id=f"client-{random.randint(0, 100)}"
to_wait=5
topic='hey-hey'
publish_count = 3

def on_log(client, userdata, level, buf):
    logging.info(buf)
    client.on_log = on_log

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            logging.info("Connected to Broker!: {}".format(rc))
        else:
            print("Failed to Connect with code: "+str(rc))
            client.loop_stop()
    
    client = mqtt.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker_url, broker_port, 60)
    return client

def subscribe(client):
    def on_subscribe(client,userdata, mid, granted_qos):
        logging.info('subscribed')
        
    client.subscribe(topic)
    client.subscribe = on_subscribe


def process_message(client, userdata, message):
    msgr=str(message.payload.decode('utf-8'))
    msgr='Message Received' + msgr
    logging.info(msgr)
        
def run():
    device2 = connect_mqtt()
    device2.on_message = process_message
    device2.loop_forever()
    
    
if __name__ == '__main__':
    run()

It just hangs and times out. Am I missing something?

Ddota
  • 163
  • 1
  • 3
  • 14
  • "It just hangs and times out" - what times out (seems unlikely it's the connection as the code that established the connection looks identical), do you get any output (e.g. "Connected to Broker!"). – Brits Apr 19 '21 at 09:42
  • @Brits Nothing happens, not even the "Connected to Broker!".Just hangs in the terminal. – Ddota Apr 19 '21 at 09:54
  • OK [add](https://stackoverflow.com/questions/38537905/set-logging-levels/38537983) `logging.getLogger().setLevel(logging.INFO)`. Please confirm that you are running `sub.py` and then, in a separate terminal window, `pub.py`. – Brits Apr 19 '21 at 10:09
  • Yeah running sub.py first followed by pub.py and have also added the suggestion and facing same issue. – Ddota Apr 19 '21 at 11:46
  • `on_publish` is a bad choice for a function name in the publishing code. That name is usually used for the callback from the client to signify a message has been sent to the broker. Using it will just cause confusion. – hardillb Apr 19 '21 at 16:52

1 Answers1

3

You never call subscribe() in your subscriber code, so it never tells the broker what topics it wants to receive.

hardillb
  • 54,545
  • 11
  • 67
  • 105