adafruit / Adafruit_CircuitPython_MiniMQTT

MQTT Client Library for CircuitPython
Other
72 stars 50 forks source link

no need to pass self to _handle_on_message() #179

Closed vladak closed 8 months ago

vladak commented 8 months ago

Found when evaluating #178.

vladak commented 8 months ago

Tested on Adafruit CircuitPython 8.2.6 on 2023-09-12; Adafruit QT Py ESP32-S3 no psram with ESP32S3 with the following code:

import adafruit_logging as logging
import socketpool
import ssl
import sys
import time
import wifi

from secrets import secrets

import adafruit_minimqtt.adafruit_minimqtt as MQTT

# pylint: disable=unused-argument, redefined-outer-name
def connect(mqtt_client, userdata, flags, rc):
    logger = logging.getLogger(__name__)
    logger.debug("Connected to MQTT Broker!")
    logger.debug("Flags: {0}\n RC: {1}".format(flags, rc))

def subscribe(mqtt_client, userdata, topic, granted_qos):
    logger = logging.getLogger(__name__)
    logger.debug("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))

def message(client, topic, message):
    logger = logging.getLogger(__name__)
    logger.debug("New message on topic {0}: {1}".format(topic, message))

    logger.debug("Checking client")
    assert isinstance(client, MQTT.MQTT)
    logger.debug("client check done")

# pylint: disable=too-many-statements,too-many-locals
def main():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    # Connect to Wi-Fi
    logger.info("Connecting to wifi")
    wifi.radio.connect(secrets["SSID"], secrets["password"], timeout=10)
    logger.info(f"Connected to {secrets['SSID']}")
    logger.debug(f"IP: {wifi.radio.ipv4_address}")

    pool = socketpool.SocketPool(wifi.radio)

    # connect to MQTT broker
    mqtt = MQTT.MQTT(
        broker="172.40.0.3",
        port=1883,
        socket_pool=pool,
        ssl_context=ssl.create_default_context(),
    )

    mqtt.on_connect = connect
    mqtt.on_subscribe = subscribe
    mqtt.on_message = message

    logger.info("Connecting to MQTT broker")
    mqtt.connect()
    mqtt.subscribe("devices/#", qos=0)

    i = 0
    while True:
        # Make sure to stay connected to the broker e.g. in case of keep alive.
        i += 1
        logger.debug(f"Loop {i}")
        mqtt.loop(1)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        sys.exit(0)