"""
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
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "118.31.244.228"
MQTT_USER = "ce6af340-f5e5-b46e-7a77-32378a2c436b"
MQTT_PASSWORD = ""
MQTT_TOPIC = "device/attributes"
led=Pin(2,Pin.OUT)
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, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
def on_message(topic, message):
print("Received MQTT message on topic:", topic)
print("Message:", message.decode("utf-8"))
# 解析接收到的MQTT消息内容
try:
data = ujson.loads(message.decode("utf-8"))
if "switch" in data:
switch_value = data["switch"]
# 根据接收到的开关值控制LED开关状态
if switch_value == 1:
led.value(1) # LED开
elif switch_value == 0:
led.value(0) # LED关
except Exception as e:
print("Failed to process MQTT message:", e)
# 设置订阅回调函数
client.set_callback(on_message)
# 订阅MQTT主题
client.subscribe(MQTT_TOPIC)
while True:
client.check_msg() # 处理接收到的MQTT消息
# 其他代码...