[HELP] Running paho mqtt client on JupyterLab

Hi all!

I’m new around here. Has anyone have any experience using paho mqtt clients on Jupyter?

I’m running a local MQTT broker to which I connect using the paho module. The module works using callbacks whenever an MQTT event happens. The problem is that trying to run the code in Jupyter I ger weird results, it seems to get multiple callbacks repeating the callback time and time again. It also seems that It cannot establish a stable connection to the broker.

The code works fine outside Jupyter, I’ve added it below.

Is there a special way to deal with callback functions in Jupyter? Does Jupyter has problems accesing the MQTT broker?

I’m running W10, python 3, and running a mosquitto broker.


import paho.mqtt.client as mqttClient
import time

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print('Connected to broker')
        global Connected
        Connected = True
        print("Connection failed")

def on_message(client, userdata, message):
    print("> message:" + message.payload.decode('cp1252'), flush=True, end='')
    print("> message topic=", message.topic)
    # print("message qos=", message.qos)
    print("> message retain flag=", message.retain)

Connected = False  # global variable for keeping state of connection
brokerAddress = ''
port = 1883

client = mqttClient.Client('pytest')
client.on_connect = on_connect
client.on_message = on_message

client.connect(brokerAddress, port=port)


while Connected is not True:

print("Subscribing...", flush=True)

client.publish('test/esp32-0A/', '0'))

    while True:
        client.publish('test/esp32-0A', input("Send cmd: "))