import network
import time
from machine import Pin, ADC
from umqtt.simple import MQTTClient
import math
SSID = "Wokwi-GUEST"
PASSWORD = ""
MQTT_BROKER = "broker.hivemq.com"
TOPIC_SUB_MODE = b"esp/mode"
TOPIC_SUB_THRESHOLD = b"esp/threshold"
TOPIC_PUB = b"esp32/temp"
relay = Pin(25, Pin.OUT)
adc = ADC(Pin(34))
adc.width(ADC.WIDTH_10BIT)
def connect_wifi():
print("Connecting to Wi-Fi...")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(0.1)
print("Connected:", wlan.ifconfig())
def make_callback(client):
def esp(topic, msg):
if topic == TOPIC_SUB_MODE:
if msg == b"manual":
client.mode = "manual"
print("mode: manual")
elif msg == b"auto":
client.mode = "auto"
print("mode: auto")
if client.mode == "manual":
if msg == b"on":
relay.value(1)
print("relay is on (manual)")
elif msg == b"off":
relay.value(0)
print("relay is off (manual)")
elif topic == TOPIC_SUB_THRESHOLD:
client.new_threshold = float(msg)
print("New threshold received:", client.new_threshold)
return esp
def main():
connect_wifi()
client = MQTTClient("malak_hazem", MQTT_BROKER)
client.mode = "manual"
client.threshold = 30.0
client.new_threshold = 30.0
client.set_callback(make_callback(client))
client.connect()
print("MQTT connected")
client.subscribe(TOPIC_SUB_MODE)
client.subscribe(TOPIC_SUB_THRESHOLD)
while True:
client.check_msg()
value = adc.read()
if value > 0:
celsius = 1 / (math.log(1 / (1023 / value - 1)) / 3950 + 1.0 / 298.15) - 273.15
client.publish(TOPIC_PUB, str(celsius))
print("Temperature sent:", celsius)
if client.mode == "auto":
if client.new_threshold > client.threshold:
relay.value(1)
print("Relay ON (auto: new > default)")
else:
relay.value(0)
print("Relay OFF (auto: new <= default)")
else:
print("ADC read error, value=0")
time.sleep(2)
main()