import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "kipas-angin"
MQTT_BROKER = "0.tcp.ap.ngrok.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-kipas"
MQTT_PORT = 17555
relay_pin = 21
led_pin = 26
sensor = dht.DHT22(Pin(15))
relay = Pin(relay_pin, Pin.OUT)
led = Pin(led_pin, Pin.OUT)
def connect_wifi():
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!")
connect_wifi()
print("Connecting to MQTT server... ", end="")
client = MQTTClient(client_id=MQTT_CLIENT_ID, server=MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD, port=MQTT_PORT, keepalive=60)
time.sleep(5)
def connect_mqtt():
while True:
try:
client.connect()
print("Connected to MQTT server!")
break
except Exception as e:
print("Connection to MQTT server failed. Error:", repr(e))
time.sleep(5)
connect_mqtt()
# prev_weather = None
while True:
try:
print("Measuring weather conditions... ", end="")
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
if humidity > 30 and temperature > 30:
print("Humidity and Temperature above threshold. Turning on LED and Relay")
led.on()
relay.on()
else:
print("Humidity or Temperature below threshold. Turning off LED and Relay")
led.off()
relay.off()
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
})
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
print("Message published successfully")
time.sleep(3)
except OSError as e:
print("Error publishing message. Retrying in 5 seconds. Error:", repr(e))
time.sleep(5)
time.sleep(3)