This change allows to set the opaque user data in the init method. Works like this:
"""
MQTT utility functions
"""
import ssl
import adafruit_logging as logging
import adafruit_minimqtt.adafruit_minimqtt as MQTT
# pylint: disable=unused-argument, redefined-outer-name, invalid-name
def connect(mqtt_client, userdata, flags, rc):
"""
This function will be called when the mqtt_client is connected
successfully to the broker.
"""
logger = userdata
logger.info("Connected to MQTT Broker!")
logger.debug(f"Flags: {flags}\n RC: {rc}")
# pylint: disable=unused-argument, invalid-name
def disconnect(mqtt_client, userdata, rc):
"""
This method is called when the mqtt_client disconnects from the broker.
"""
logger = userdata
logger.info("Disconnected from MQTT Broker!")
def publish(mqtt_client, userdata, topic, pid):
"""
This method is called when the mqtt_client publishes data to a feed.
"""
logger = userdata
logger.info(f"Published to {topic} with PID {pid}")
def mqtt_client_setup(pool, broker, port):
"""
Set up a MiniMQTT Client
"""
logger = logging.getLogger("mqtt")
logger.setLevel(logging.DEBUG)
mqtt_client = MQTT.MQTT(
broker=broker,
port=port,
socket_pool=pool,
ssl_context=ssl.create_default_context(),
user_data=logger,
)
mqtt_client.on_connect = connect
mqtt_client.on_disconnect = disconnect
mqtt_client.on_publish = publish
return mqtt_client
def main():
import socket
mqtt_client = mqtt_client_setup(broker="localhost", port=1883, pool=socket)
mqtt_client.connect()
mqtt_client.publish("foo/bar", "msg")
if __name__ == "__main__":
main()
Tested with CPython against custom MQTT broker implementation, produces the following output:
601394.401: INFO - Connected to MQTT Broker!
601394.401: DEBUG - Flags: 0
RC: 0
601394.401: INFO - Published to foo/bar with PID 0
This change allows to set the opaque user data in the init method. Works like this:
Tested with CPython against custom MQTT broker implementation, produces the following output: