[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.

Thanks!

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
    else:
        print("Connection failed")


def on_message(client, userdata, message):
    print("-----------------")
    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)
    print("-----------------")


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

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

client.connect(brokerAddress, port=port)

client.loop_start()

while Connected is not True:
    time.sleep(0.1)

print("Subscribing...", flush=True)
client.subscribe('test/#')

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

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