import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
import ujson
import dht
# MQTT Server Parameters
MQTT_CLIENT_ID = "WILDANFATHAN"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_SUB = "/HSC102/WILDANFATHAN/aktuasi_led/"
MQTT_TOPIC_PUB = "/HSC102/WILDANFATHAN/data_sensor"
led = Pin(2, Pin.OUT)
sensor = dht.DHT22(Pin(4))
# 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!")
# MQTT Server connection
def connect_mqtt():
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(callback)
client.connect()
client.subscribe(MQTT_TOPIC_SUB)
print("Connected!")
return client
# Set the callback function
def callback(topic, msg):
print("Received Message:", msg)
try:
# JSON parse
data = ujson.loads(msg)
if data.get("msg") == "ON":
led.on()
elif data.get("msg") == "OFF":
led.off()
except Exception as e:
print("Parse failed!, reason:", e)
# MQTT Init
client = connect_mqtt()
# Post Time Init
post_time = time.time()
# Looping Here
while True:
client.check_msg()
if time.time() - post_time == 5: #post every 5 sec
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity()
})
# Send the message
print("Sensor data published!")
client.publish(MQTT_TOPIC_PUB, message)
post_time = time.time()
time.sleep(0.5)