"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
import urandom
def random_id(n=6):
chars = "abcdefghijklmnopqrstuvwxyz0123456789"
return "".join(chars[urandom.getrandbits(6) % len(chars)] for _ in range(n))
CLIENT_ID = "esp32-" + random_id()
SERVER = "5232a6122a3a401aaeaa51b71372284c.s1.eu.hivemq.cloud"
USER = "Wokwi123"
PASSWORD = "Wokwi123"
topic = "SalaFatec/weather" # "wokwi-weather" -> "SalaFatec/weather"
sensor = dht.DHT22(Pin(15))
led = Pin(13, Pin.OUT)
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("Connecting to MQTT server... ", end="")
client = MQTTClient(
client_id=CLIENT_ID,
server=SERVER,
port=8883,
user=USER,
password=PASSWORD,
ssl=True,
ssl_params={"server_hostname": SERVER}
)
client.connect()
print("Connected!")
prev_weather = ""
last_message = 0
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
# liga o led caso a humidade esteja abaixo de 40%
if sensor.humidity() <= 40:
led.on()
else:
led.off();
message = ujson.dumps({
"temp": round(sensor.temperature(), 1), # casas decimais modificadas
"humidity": round(sensor.humidity(), 1), # casas decimais modificadas
})
if message != prev_weather:
print("Updated!")
if sensor.temperature() >= 30.0:
print("Reporting to MQTT topic {}: {}".format("sala101/alerta", message))
client.publish("sala101/alerta", message) # mensagem de alerta
else:
print("Reporting to MQTT topic {}: {}".format("SalaFatec/weather", message))
client.publish("salaFatec/weather", message)
prev_weather = message
else:
print("No change")
time.sleep(5) # 1 -> 5 segundos