import network
import dht
import ujson
from machine import Pin
from utime import sleep
from machine import Pin
from umqtt.simple import MQTTClient
print("Hello, ESP32!")
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = "adipta"
MQTT_PASSWORD = "adipta"
MQTT_TOPIC = "/transformers/adipta"
def message_callback(topic, msg):
global last_topic, last_message
last_topic = topic.decode()
last_message = msg.decode()
print("Pesan diterima di topik {}: {}".format(last_topic, last_message))
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="")
sleep(0.1)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
client.set_callback(message_callback)
client.subscribe(MQTT_TOPIC)
led = Pin(15, Pin.OUT)
while True:
client.wait_msg()
if last_message == "on":
led.on()
sleep(0.5)
elif last_message == "off":
led.off()
sleep(0.5)
else:
print("message not recognized")