#Import Libraries
import time
from umqtt.simple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
import dht
#Import and use garbage collector
import gc
gc.collect()
#Disable debug output
esp.osdebug(None)
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = "Wokwi-GUEST"
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
PREV_WEATHER = ""
def sub_cb(topic, msg):
print((topic, msg))
if(top == b'temperature' and msg == b'received'):
print('Temperature received by ESP')
if(top == b'humidity' and msg == b'received'):
print('Temperature received by ESP')
#Connect ESP32 to Wifi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("Wokwi-GUEST", "")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print(sta_if.ifconfig())
#Declare sensor object and assign it PIN 15
sensor = dht.DHT22(machine.Pin(15))
def connect_and_subscribe(MQTT_CLIENT_ID, MQTT_SERVER, TOPIC_SUB, MQTT_USER, MQTT_PASSWORD,MQTT_TOPIC):
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_cb)
client.connect()
client.subscribe(TOPIC_SUB)
print('Connected to %s MQTT broker, subscribed to %s topic' % (MQTT_SERVER, TOPIC_SUB))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
try:
client = connect_and_subscribe(MQTT_CLIENT_ID, MQTT_BROKER, MQTT_TOPIC)
except OSError as e:
restart_and_reconnect()
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
if message != PREV_WEATHER:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print("No change")
time.sleep(1)
})
FPS: 0
Power: 0.00W
Power: 0.00W