import network
import time
from machine import Pin, PWM
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "146.190.93.211"
MQTT_PORT = "1883"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "topik/rds"
def sub_callback(topic, msg):
# print(f"Pesan diterima dari topic {topic.decode('utf-8')}: {msg.decode('utf-8')}")
print(f"{msg.decode('utf-8')}\n")
buzzer.duty(512)
time.sleep(0.1)
buzzer.duty(0)
try:
buzzer = PWM(Pin(22), freq=1000, duty=0)
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!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(
MQTT_CLIENT_ID,
MQTT_BROKER,
port=MQTT_PORT,
user=MQTT_USER,
password=MQTT_PASSWORD
)
client.set_callback(sub_callback)
client.connect()
client.subscribe(MQTT_TOPIC)
# print("Berlangganan ke topic:", MQTT_TOPIC)
print("Connected!\n")
while True:
client.wait_msg()
except Exception as e:
print(f"\n\nError : {e}\n")
finally:
client.disconnect()