import network
import time
import ujson
import dht
from machine import Pin
from umqtt.simple import MQTTClient
# =====================================================
# MQTT Parameters
# =====================================================
MQTT_CLIENT_ID = "vent-dht-publisher"
MQTT_BROKER = "broker.hivemq.com"
MQTT_TOPIC = "smart/vent/system"
# =====================================================
# Sensor Setup
# =====================================================
sensor = dht.DHT22(Pin(15))
# =====================================================
# WiFi Connection
# =====================================================
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!")
# 1
# =====================================================
# MQTT Connection
# =====================================================
print("MQTT Connecting....")
client = MQTT_CLIENT_ID(MQTT_CLIENT_ID, MQTT_BROKER)
client.connect()
print("MQTT Connected")
# 2
# =====================================================
# Main Loop
# =====================================================
prev_msg = ""
while True:
print("reading value....")
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
# =================================================
# Decision Logic
# =================================================
if temp > 30:
state = "OPEN"
elif temp < 20:
state = "CLOSE"
else:
state = "HALF"
msg = ujson.dumps({
"state ":state,
"temp ": temp,
"humidity ": hum
})
# Publish only if changed
if msg != prev_msg:
client.publish(MQTT_TOPIC, msg)
print("publish: ", msg)
prev_msg = msg
time.sleep(2)