"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
import json
import random
SSID = "Wokwi-GUEST"
PASSWORD = ""
MQTT_BROKER = "broker.emqx.io"
MQTT_PORT = 1883
MQTT_CLIENT_ID = "esp32_led_client"
MQTT_TOPIC_PUBLISH = "/Zigma/nadya/data_sensor"
MQTT_TOPIC_SUBSCRIBE = "/Zigma/nadya/aktuasi_led"
led_pin = Pin(32, Pin.OUT)
def connect_wifi():
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(SSID, PASSWORD)
print("Connecting to WiFi", end="")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def callback(topic, msg):
try:
message = json.loads(msg.decode())
print("Received message:", message)
action = message.get("msg", "").lower()
if action == "on":
led_pin.value(1)
print("LED ON")
elif action == "off":
led_pin.value(0)
print("LED OFF")
else:
print("Unknown command:", action)
except Exception as e:
print("Error processing message:", e)
def connect_mqtt():
print("Connecting to MQTT server...")
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT)
client.set_callback(callback)
client.connect()
print("MQTT Connected!")
client.subscribe(MQTT_TOPIC_SUBSCRIBE)
print(f"Subscribed to topic: {MQTT_TOPIC_SUBSCRIBE}")
return client
except Exception as e:
print(f"Error connecting to MQTT broker: {e}")
time.sleep(5)
return None
def publish_sensor_data(client):
sensor_data = {"temperature": random.uniform(20.0, 30.0)}
payload = json.dumps(sensor_data)
client.publish(MQTT_TOPIC_PUBLISH, payload)
print(f"Published sensor data: {payload}")
def main():
connect_wifi()
client = None
while client is None:
client = connect_mqtt()
while True:
try:
print("Checking for messages...")
client.check_msg()
publish_sensor_data(client)
time.sleep(5)
except OSError as e:
print("Error in MQTT communication:", e)
time.sleep(1)
except Exception as e:
print("Unexpected error:", e)
time.sleep(1)
main()