1414import adafruit_minimqtt .adafruit_minimqtt as MQTT
1515
1616# Get WiFi details and broker keys, ensure these are setup in settings.toml
17+ # (visit io.adafruit.com if you need to create an account, or if you need your Adafruit IO key.)
1718ssid = getenv ("CIRCUITPY_WIFI_SSID" )
1819password = getenv ("CIRCUITPY_WIFI_PASSWORD" )
19- broker = getenv ("broker" )
20- broker_port = getenv ("broker_port" )
20+ aio_username = getenv ("ADAFRUIT_AIO_USERNAME" )
21+ aio_key = getenv ("ADAFRUIT_AIO_KEY" )
22+ broker = getenv ("broker" , "io.adafruit.com" )
23+ broker_port = int (getenv ("broker_port" , "8883" )) # Port 1883 insecure, 8883 secure
2124
2225### WiFi ###
2326
@@ -75,7 +78,7 @@ def on_battery_msg(client, topic, message):
7578 # Method called when device/batteryLife has a new value
7679 print (f"Battery level: { message } v" )
7780
78- # client.remove_topic_callback(aio_username + " /feeds/device.batterylevel")
81+ # client.remove_topic_callback(f"{aio_username} /feeds/device.batterylevel")
7982
8083
8184def on_message (client , topic , message ):
@@ -95,6 +98,8 @@ def on_message(client, topic, message):
9598client = MQTT .MQTT (
9699 broker = broker ,
97100 port = broker_port ,
101+ username = aio_username ,
102+ password = aio_key ,
98103 socket_pool = pool ,
99104 ssl_context = ssl_context ,
100105)
@@ -105,14 +110,14 @@ def on_message(client, topic, message):
105110client .on_subscribe = subscribe
106111client .on_unsubscribe = unsubscribe
107112client .on_message = on_message
108- client .add_topic_callback (aio_username + " /feeds/device.batterylevel" , on_battery_msg )
113+ client .add_topic_callback (f" { aio_username } /feeds/device.batterylevel" , on_battery_msg )
109114
110115# Connect the client to the MQTT broker.
111116print ("Connecting to MQTT broker..." )
112117client .connect ()
113118
114119# Subscribe to all notifications on the device group
115- client .subscribe (aio_username + " /groups/device" , 1 )
120+ client .subscribe (f" { aio_username } /groups/device" , 1 )
116121
117122# Start a blocking message loop...
118123# NOTE: NO code below this loop will execute
0 commit comments