from machine import Pin
import time
import network
from umqtt.simple import MQTTClient
import dht
pin15 = Pin(15, Pin.OUT)
# STEP 1: CONNECT WIFI
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# STEP 2: CONNECT MQTT SENSOR
MQTT_CLIENT_ID = "mqttx_gilbertDHT22" # <- harus beda
MQTT_BROKER = "broker.emqx.io"
MQTT_TOPIC_SENSOR = "/HSC400/Gilbert Janong/data_sensor"
mqtt_sensor = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
mqtt_sensor.connect()
# STEP 3: COLLECT SENSOR DATA
sensor = dht.DHT22(Pin(2))
# STEP 4: CONNECT MQTT LED
MQTT_CLIENT_ID = "clientId-viKIXa5f92222323sdfwerwerwe56et6eLAMPU" # <- harus beda
MQTT_BROKER = "broker.hivemq.com"
MQTT_TOPIC_LED = "/HSC400/Gilbert Janong/aktuasi_led"
mqtt_led = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
def on_message(topic, message):
topic = str(topic, "UTF-8")
message = str(message, "UTF-8")
if message == "off":
pin15.off()
elif message == "on":
pin15.on()
mqtt_led.set_callback(on_message)
mqtt_led.connect()
mqtt_led.subscribe(MQTT_TOPIC_LED)
# STEP 5: RUN EVERYTHING!
while True:
time.sleep(1)
mqtt_led.check_msg()
sensor.measure()
hum = sensor.humidity()
temp = sensor.temperature()
print("Publish data sensor")
mqtt_sensor.publish(MQTT_TOPIC_SENSOR, f"Temperatur: {temp}, Kelembapan: {hum}")