-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.py
66 lines (48 loc) · 1.68 KB
/
mqtt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
MQTT utility functions
"""
import ssl
import adafruit_logging as logging
import adafruit_minimqtt.adafruit_minimqtt as MQTT
# Avoid infinite recursion by using non-default logger in the MQTT callbacks.
MQTT_LOGGER_NAME = "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 = logging.getLogger(MQTT_LOGGER_NAME)
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 = logging.getLogger(MQTT_LOGGER_NAME)
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 = logging.getLogger(MQTT_LOGGER_NAME)
logger.info(f"Published to {topic} with PID {pid}")
def mqtt_client_setup(pool, broker, port, log_level, socket_timeout=1):
"""
Set up a MiniMQTT Client
"""
logger = logging.getLogger(MQTT_LOGGER_NAME)
logger.setLevel(log_level)
mqtt_client = MQTT.MQTT(
broker=broker,
port=port,
socket_pool=pool,
ssl_context=ssl.create_default_context(),
socket_timeout=socket_timeout,
)
# Connect callback handlers to mqtt_client
mqtt_client.on_connect = connect
mqtt_client.on_disconnect = disconnect
mqtt_client.on_publish = publish
return mqtt_client