## NEW FROM WOKWI
import time
import dht
import machine
import network
import json
from machine import Pin
from umqtt.simple import MQTTClient
# WIFI settings
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# MQTT settings
MQTT_BROKER = "broker.emqx.io"
CLIENT_ID = "ed223bd-esp32"
TOPIC_SENSOR = b"lnu/iot/ed223bd/sensor"
TOPIC_LED = b"lnu/iot/ed223bd/command/led"
# Define hardware
led = Pin(27, Pin.OUT)
sensor = dht.DHT22(machine.Pin(15))
# From Rob (modified)
def connect_wifi():
#Connect to WLAN
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to wifi...")
while wlan.isconnected() == False:
print('Waiting for connection...')
time.sleep(1)
print("\nConnected!")
print(wlan.ifconfig())
def on_message(topic, msg):
try:
message = json.loads(msg.decode())
print("Message: ", message)
state = message.get("state")
if state is True:
led.on()
print("LED ON")
elif state is False:
led.off()
print("LED OFF")
except Exception as e:
print("Message error: ", e)
# Start connections
connect_wifi()
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client.set_callback(on_message)
print("Connecting to MQTT...")
client.connect()
client.subscribe(TOPIC_LED)
print("Subscribed to: ", TOPIC_LED)
# Prepare the message
while True:
try:
client.check_msg()
except Exception as e:
print("MQTT error: ", e)
try:
sensor.measure()
print("Temperature: ", sensor.temperature(), "C")
print("Humidity: ", sensor.humidity(), "%")
payload = json.dumps({
"temperature": sensor.temperature(),
"humidity": sensor.humidity()
})
client.publish(
TOPIC_SENSOR,
payload
)
print("Published: ", payload)
except Exception as e:
print("Sensor error: ", e)
time.sleep(2)