-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathminimqtt_multipub_simpletest.py
More file actions
130 lines (108 loc) · 4.12 KB
/
minimqtt_multipub_simpletest.py
File metadata and controls
130 lines (108 loc) · 4.12 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# SPDX-FileCopyrightText: 2023 DJDevon3
# SPDX-License-Identifier: MIT
# MQTT Multi-Feed Publish Example
# Coded for Circuit Python 8.2.x
import traceback
import os
import time
import ssl
import wifi
import socketpool
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_minimqtt.adafruit_minimqtt import MMQTTException
# Initialize Web Sockets (This should always be near the top of a script!)
# There can be only one pool
pool = socketpool.SocketPool(wifi.radio)
# Add settings.toml to your filesystem
# CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys
# with your WiFi credentials. Add your Adafruit IO username and key as well.
# DO NOT share that file or commit it into Git or other source control.
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
appw = os.getenv("CIRCUITPY_WIFI_PASSWORD")
aio_username = os.getenv("aio_username")
aio_key = os.getenv("aio_key")
# MQTT Topic
# Use this format for a standard MQTT broker
feed_01 = aio_username + "/feeds/BME280-RealTemp"
feed_02 = aio_username + "/feeds/BME280-Pressure"
feed_03 = aio_username + "/feeds/BME280-Humidity"
feed_04 = aio_username + "/feeds/BME280-Altitude"
# Time in seconds between updates (polling)
# 600 = 10 mins, 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
sleep_time = 900
# Converts seconds to minutes/hours/days
# Attribution: Written by DJDevon3 & refined by Elpekenin
def time_calc(input_time):
if input_time < 60:
return f"{input_time:.0f} seconds"
if input_time < 3600:
return f"{input_time / 60:.0f} minutes"
if input_time < 86400:
return f"{input_time / 60 / 60:.0f} hours"
return f"{input_time / 60 / 60 / 24:.1f} days"
# Define callback methods which are called when events occur
# pylint: disable=unused-argument, redefined-outer-name
def connect(client, userdata, flags, rc):
# Method when mqtt_client connected to the broker.
print("| | ✅ Connected to MQTT Broker!")
def disconnect(client, userdata, rc):
# Method when the mqtt_client disconnects from broker.
print("| | ✂️ Disconnected from MQTT Broker")
def publish(client, userdata, topic, pid):
# Method when the mqtt_client publishes data to a feed.
print("| | | Published to {0} with PID {1}".format(topic, pid))
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
port=8883,
username=aio_username,
password=aio_key,
socket_pool=pool,
ssl_context=ssl.create_default_context(),
is_ssl=True,
)
# Connect callback handlers to mqtt_client
mqtt_client.on_connect = connect
mqtt_client.on_disconnect = disconnect
mqtt_client.on_publish = publish
while True:
# These are fake values, replace with sensor variables.
BME280_temperature = 80
BME280_pressure = round(1014.89, 1)
BME280_humidity = round(49.57, 1)
BME280_altitude = round(100.543, 2)
print("===============================")
# Board Uptime
print("Board Uptime: ", time_calc(time.monotonic()))
print("| Connecting to WiFi...")
while not wifi.radio.ipv4_address:
try:
wifi.radio.connect(ssid, appw)
except ConnectionError as e:
print("Connection Error:", e)
print("Retrying in 10 seconds")
time.sleep(10)
print("| ✅ WiFi!")
while wifi.radio.ipv4_address:
try:
# Connect to MQTT Broker
mqtt_client.connect()
mqtt_client.publish(feed_01, BME280_temperature)
# slight delay required between publishes!
# otherwise only the 1st publish will succeed
time.sleep(0.001)
mqtt_client.publish(feed_02, BME280_pressure)
time.sleep(1)
mqtt_client.publish(feed_03, BME280_humidity)
time.sleep(1)
mqtt_client.publish(feed_04, BME280_altitude)
time.sleep(1)
except MMQTTException as e:
print("| | ❌ MMQTTException", e)
traceback.print_exception(e, e, e.__traceback__)
break
mqtt_client.disconnect()
print("| ✂️ Disconnected from Wifi")
print("Next Update: ", time_calc(sleep_time))
time.sleep(sleep_time)
break