from machine import Pin, Timer
import network
import time
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "mqttx_e340109a"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_SENSOR = "/EMOT/Edelyne/data_sensor"
MQTT_TOPIC_LED = "/EMOT/Edelyne/aktuasi_led"
led = Pin(14, Pin.OUT) # Pin 14 LED
sensor = dht.DHT22(Pin(2)) # Pin 2 Sensor
# Wi-Fi 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
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Callback function for MQTT subscription (LED control)
def led_control_cb(topic, msg):
print("LED control message received on topic:", topic)
print("Message:", msg)
if msg == b"ON":
led.on()
elif msg == b"OFF":
led.off()
# Callback function for MQTT subscription (Sensor data)
def sensor_data_cb(topic, msg):
print("Sensor data message received on topic:", topic)
print("Message:", msg)
# Subscribe to both topics
client.set_callback(led_control_cb)
client.subscribe(MQTT_TOPIC_LED) # LED
client.subscribe(MQTT_TOPIC_SENSOR) # Data Sensor
# Function to publish sensor data
def pub_sensor_data(tim):
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
print("Publishing to MQTT topic", MQTT_TOPIC_SENSOR, ":", message)
client.publish(MQTT_TOPIC_SENSOR, message)
# Publish sensor data every 5 seconds
tim = Timer(-1)
tim.init(period=5000, mode=Timer.PERIODIC, callback=pub_sensor_data)
while True:
client.check_msg()
time.sleep(0.1) # Small delay