import network
import time
import dht
import machine
import ujson
from umqtt.simple import MQTTClient
# ─── Config ────────────────────────────────────────────────────
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
MQTT_BROKER = "broker.hivemq.com"
MQTT_PORT = 1883
MQTT_CLIENT = b"esp32_energy_monitor_001"
TOPIC_DATA = b"energy/monitor/data"
TOPIC_CONTROL = b"energy/monitor/control"
# ─── Pin Config ────────────────────────────────────────────────
DHT_PIN = machine.Pin(15)
RELAY_PIN = machine.Pin(26, machine.Pin.OUT)
sensor = dht.DHT22(DHT_PIN)
RELAY_PIN.value(1) # Start relay ON
# ─── State ─────────────────────────────────────────────────────
relay_state = True
energy_kwh = 0.0
# ─── WiFi ──────────────────────────────────────────────────────
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
# This is the line your professor wants to see
print("Connecting to WiFi", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\n WiFi connected! IP:", wlan.ifconfig()[0])
# ─── MQTT Callback ──────────────────
def on_message(topic, msg):
global relay_state
print("📩 Command received:", msg)
try:
data = ujson.loads(msg)
etat = data.get("etat", "")
if etat == "OFF":
relay_state = False
RELAY_PIN.value(0)
print(" Relay turned OFF")
elif etat == "ON":
relay_state = True
RELAY_PIN.value(1)
print(" Relay turned ON")
except Exception as e:
print(" JSON parse error:", e)
# ─── MQTT Connect ──────────────────────────────────────────────
def connect_mqtt():
client = MQTTClient(MQTT_CLIENT, MQTT_BROKER, port=MQTT_PORT)
client.set_callback(on_message)
# Added the specific print message here
print("Connecting to MQTT broker...", end="")
client.connect()
print(" Connected!")
client.subscribe(TOPIC_CONTROL)
print(" Subscribed to:", TOPIC_CONTROL.decode()) # Decode for cleaner print
return client
# ─── Main Loop ─────────────────────────────────────────────────
def main():
global energy_kwh, relay_state
# Start the connections
connect_wifi()
client = connect_mqtt()
last_send = time.time()
while True:
# Check for incoming commands (non-blocking)
try:
client.check_msg()
except:
pass
now = time.time()
# Accumulate energy when relay is ON
if relay_state:
energy_kwh += 0.0003
# Publish every 3 seconds
if now - last_send >= 3:
last_send = now
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
payload = ujson.dumps({
"energy_kwh": round(energy_kwh, 4),
"status": "ON" if relay_state else "OFF",
"temp": temp,
"humidity": hum
})
client.publish(TOPIC_DATA, payload)
print(" Published:", payload)
except Exception as e:
print(" Sensor or MQTT error:", e)
time.sleep(0.1) # Faster response for commands
# Run the program
if __name__ == "__main__":
main()