import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
MQTT_CLIENT_ID = "mqttx_a7c01e94"
MQTT_BROKER = "broker.hivemq.com"
MQTT_TOPIC_SENSOR = "iron/sensor"
MQTT_TOPIC_LED = "iron/led"
TOPIC_SEND = "Iron/Pheonix/pesan"
sensor1 = dht.DHT22(Pin(15))
sensor2 = dht.DHT22(Pin(2))
led = Pin(12, Pin.OUT)
led_state = False
def sub_callback(topic, msg):
global led_state
message = msg.decode('utf-8')
print("Received message on topic {}: {}".format(topic.decode('utf-8'), message))
if message == "1":
led.value(1)
led_state = True
print("LED turned ON")
elif message == "0":
led.value(0)
led_state = False
print("LED turned OFF")
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
retry_count = 0
max_retries = 10
while not sta_if.isconnected() and retry_count < max_retries:
print(".", end="")
time.sleep(0.5)
retry_count += 1
if sta_if.isconnected():
print(" Connected!")
print("IP Address:", sta_if.ifconfig()[0])
else:
print("Failed to connect to WiFi after {} attempts.".format(max_retries))
while True:
time.sleep(1)
print("Connecting to MQTT server... ", end="")
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(sub_callback)
client.connect()
print("Connected!")
client.subscribe(MQTT_TOPIC_LED)
except Exception as e:
print("Failed to connect to MQTT broker. Error:", e)
while True:
time.sleep(1)
prev_weather = ""
while True:
client.check_msg()
try:
sensor1.measure()
temp1 = sensor1.temperature()
humidity1 = sensor1.humidity()
sensor2.measure()
temp2 = sensor2.temperature()
humidity2 = sensor2.humidity()
message = ujson.dumps({
"sensor1": {
"temperature": temp1,
"humidity": humidity1,
},
"sensor2": {
"temperature": temp2,
"humidity": humidity2,
}
})
if message != prev_weather:
print("Updated sensor data!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC_SENSOR, message))
client.publish(MQTT_TOPIC_SENSOR, message)
prev_weather = message
else:
print("No change in sensor data")
except OSError as e:
print("Failed to read sensor. Error:", e)
specific_message = "Rafif Al-Bariq Hawi Iron Pheonix squad HSC462"
print("Publishing to topic {}: {}".format(TOPIC_SEND, specific_message))
client.publish(TOPIC_SEND, specific_message)
time.sleep(1)