Adding MQTT connection to your UI

At some point you may want to connect your UI to a Pub Sub service like MQTT. Here is some example code that uses the miniMQTT and PyPortal libraries to connect with a hosted MQTT server. See is you can add some of these UI elements to the example.

# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import adafruit_pyportal

import adafruit_minimqtt.adafruit_minimqtt as MQTT

pyportal = adafruit_pyportal.PyPortal()

### WiFi ###

# Get wifi details and more from a file
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in, please add them there!")

# ------------- MQTT Topic Setup ------------- #
mqtt_topic = "test/topic"

### Code ###
# Define callback methods which are called when events occur
# pylint: disable=unused-argument, redefined-outer-name
def connected(client, userdata, flags, rc):
    # This function will be called when the client is connected
    # successfully to the broker.
    print("Subscribing to %s" % (mqtt_topic))

def disconnected(client, userdata, rc):
    # This method is called when the client is disconnected
    print("Disconnected from MQTT Broker!")

def message(client, topic, message):
    """Method callled when a client's subscribed feed has a new
    :param str topic: The topic of the feed with a new value.
    :param str message: The new value
    print("New message on topic {0}: {1}".format(topic, message))

# Connect to WiFi
print("Connecting to WiFi...")

# Initialize MQTT interface with the esp interface
# pylint: disable=protected-access

# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(

# Setup the callback methods above
mqtt_client.on_connect = connected
mqtt_client.on_disconnect = disconnected
mqtt_client.on_message = message

# Connect the client to the MQTT broker.

photocell_val = 0
while True:
    # Poll the message queue

    # Send a new message
    print("Sending photocell value: %d" % photocell_val)
    mqtt_client.publish(mqtt_topic, photocell_val)
    photocell_val += 1

This guide was first published on Feb 10, 2020. It was last updated on Jan 16, 2020.

This page (Make it your own) was last updated on Mar 19, 2023.

Text editor powered by tinymce.