The code first connects the ESP32 to the wireless network you specified in the settings.toml file on your CIRCUITPY drive.

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(
            os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")
        )
    except RuntimeError as e:
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)

Then, it initializes a MQTT object using the network interface (esp, ethernet) you are using:

# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)

Once a WiFi network connection has been established, the code sets up a new MiniMQTT client instance

client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=aio_username,
    password=aio_key,
)

Then, the code attaches callback handler methods to the client. 

# Connect callback handlers to client
client.on_connect = connect
client.on_disconnect = disconnect
client.on_subscribe = subscribe
client.on_unsubscribe = unsubscribe
client.on_publish = publish

MiniMQTT Callback Methods

We're going to stop here to explain the utility and operation of the callback methods which are an important part of building programs with MiniMQTT.

Further up in the code, there are methods named connect(), publish(), subscribe(), unsubscribe() and disconnect()

def connect(client, userdata, flags, rc):
    # This function will be called when the client is connected
    # successfully to the broker.
    print('Connected to MQTT Broker!')
    print('Flags: {0}\n RC: {1}'.format(flags, rc))

def disconnect(client, userdata, rc):
    # This method is called when the client disconnects
    # from the broker.
    print('Disconnected from MQTT Broker!')

def subscribe(client, userdata, topic, granted_qos):
    # This method is called when the client subscribes to a new feed.
    print('Subscribed to {0} with QOS level {1}'.format(topic, granted_qos))

def unsubscribe(client, userdata, topic, pid):
    # This method is called when the client unsubscribes from a feed.
    print('Unsubscribed from {0} with PID {1}'.format(topic, pid))

def publish(client, userdata, topic, pid):
    # This method is called when the client publishes data to a feed.
    print('Published to {0} with PID {1}'.format(topic, pid))

Each of these methods is executed when a callback is successfully read back from a MQTT control packet sent by the client.

This means that whenever MiniMQTT sends a CONNECT command to the MQTT broker, the broker should respond that it received it and send another packet back to MiniMQTT (called a CONNACK packet).

If MiniMQTT receives this CONNACK packet, it will execute the client's on_connect method. It'll raise an error if it did not connect successfully. 

As an example, we'll set up a connect callback method named connect. This method will print the string, Connected to MQTT Broker, if it successfully connects to your MQTT broker.

def connect(client, userdata, flags, rc):
    print('Connected to MQTT Broker!')

Then, we'll set the client's on_connect property to the connect method.

client.on_connect = connect

To connect the MiniMQTT client to the broker, we'll run the following line:

client.connect()

When the client's connect() method runs, it sends a CONNECT command to the MQTT broker with information including the broker's address and waits for the CONNACK.

Once the CONNACK is received, MiniMQTT calls on_connect from "behind the scenes". Since connect is attached to on_connect, connect will execute and print out the following message:

Connected to MQTT Broker!

Ok - we now understand how the connect method callback works. The rest of the example calls more functions which also execute similar callback methods.

First, the code attempts to connect to the MQTT broker you specified.

print('Attempting to connect to %s'%client.broker)
client.connect()

If the CircuitPython board connects successfully, it'll run the connect method.

The code will next attempt to subscribe to a mqtt_topic you defined earlier in the code.

print('Subscribing to %s'%mqtt_topic)
client.subscribe(mqtt_topic)

If the client successfully subscribes to the mqtt_topic, the subscribe method will execute. 

Once the client successfully subscribes - it'll publish to the mqtt_topic.

print('Publishing to %s'%mqtt_topic)
client.publish(mqtt_topic, 'Hello Broker!')

After publishing, your broker should display that it received a value from the client. In addition, the publish method should run.

Next, the client unsubscribes from the mqtt_topic and disconnects from the broker.

print('Unsubscribing from %s'%mqtt_topic)
client.unsubscribe(mqtt_topic)

print('Disconnecting from %s'%client.broker)
client.disconnect()

These two methods should call the unsubscribe and disconnect methods.

That's it! The next page will go over some of the more advanced features of this library.

This guide was first published on Jul 23, 2019. It was last updated on Jul 23, 2019.

This page (Code Walkthrough) was last updated on Jul 07, 2023.

Text editor powered by tinymce.