from machine import Pin
from umqtt.simple import MQTTClient
from time import sleep
import network
import dht
from random import randint
# For which pin to use, refer to the pin manual
LED_PIN: int = 4
DHT_I2C_SDA_PIN: int = 22
CLIENT_ID: str = "somerandomgarbage34343852"
SERVER_URL: str = "broker.emqx.io"
# Apparently the /mqtt path isn't part of the topic
PUBLISH_TOPIC: bytes = b"fahri/esp32/random"
SUBSCRIBE_TOPIC: bytes = b"fahri/esp32/led"
# Assign names to the pins
led = Pin(LED_PIN, Pin.OUT)
dht22 = dht.DHT22(Pin(DHT_I2C_SDA_PIN, Pin.IN, Pin.PULL_UP))
# Set the callback, topic is ignored
def callback(_topic: bytes, msg: bytes):
print("Received message:", msg)
if msg == b"LED ON":
led.on()
elif msg == b"LED OFF":
led.off()
# Connect to WIFI, basically template
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST") # Name of WOKWI wifi, password is an optional argument
while not wlan.isconnected():
print(".", end="")
sleep(0.1)
print("\nConnected")
# Setup MQTT
client = MQTTClient(CLIENT_ID, SERVER_URL)
client.connect()
# Subscribe to the topic
client.set_callback(callback)
client.subscribe(SUBSCRIBE_TOPIC, qos=1)
while True:
sleep(3)
# Get measurements
dht22.measure()
humidity = dht22.humidity()
temperature = dht22.temperature()
# Publish message
message = f"Humidity: {humidity}\nTemperature: {temperature}".encode("UTF-8")
print("Sending:", message)
client.publish(PUBLISH_TOPIC, message, qos=1)
# Process incoming message if it exists, don't do anything otherwise
client.check_msg()