import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "demoErick"
MQTT_BROKER = "mqtt-dashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_PUB = "UNI306/fredrick/data_sensor"
MQTT_TOPIC_SUB = "UNI306/fredrick/aktuasi_led"
sensor = dht.DHT22(Pin(15)) # DHT22 on pin 15
led = Pin(12, Pin.OUT) # LED on pin 12
# WiFi Connection
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!")
# MQTT Message Callback
def on_message(topic, msg):
print(f"Received message on topic {topic.decode()}: {msg.decode()}")
if topic.decode() == MQTT_TOPIC_SUB:
if msg.decode() == "ON":
if led.value() == 1:
print("LED already ON") # Notif LED already ON
else:
print("Turning LED ON")
led.value(1)
elif msg.decode() == "OFF":
if led.value() == 0:
print("LED already OFF") # Notify LED already OFF
else:
print("Turning LED OFF")
led.value(0) # Turn LED OFF
else:
print("Unknown message received!")
# MQTT Connection
def connect_mqtt():
print("Connecting to MQTT broker... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(on_message)
client.connect()
print("Connected!")
return client
# Connect to WiFi
connect_wifi()
mqtt_client = connect_mqtt()
# Subscribe to the LED
mqtt_client.subscribe(MQTT_TOPIC_SUB)
print(f"Subscribed to {MQTT_TOPIC_SUB}")
prev_weather = ""
# Main loop
try:
while True:
# Publish sensor data
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
message = ujson.dumps({
"temp": temp,
"humidity": humidity,
})
if message != prev_weather:
print(f"Publishing updated sensor data... {message}")
mqtt_client.publish(MQTT_TOPIC_PUB, message)
prev_weather = message
else:
print("No change in sensor data.")
# Check for incoming messages
mqtt_client.check_msg()
time.sleep(2)
except KeyboardInterrupt:
print("Program stopped.")
mqtt_client.disconnect()