import time
import network
import usocket as socket
from mqtt import MQTTClient
# WiFi连接配置
WIFI_SSID = "wifi"
WIFI_PASSWORD = "tttt1234"
# 阿里云IoT平台MQTT服务器配置
# 阿里云IoT平台MQTT服务器配置
ALIYUN_SERVER = "iot-060abets.mqtt.iothub.aliyuncs.com"
CLIENT_ID = "k0zvw5MlCDl.TC6ICgOHb7cVk3Roy1cN|securemode=2,signmethod=hmacsha256,timestamp=1711519481150|"
USERNAME = "TC6ICgOHb7cVk3Roy1cN&k0zvw5MlCDl"
PASSWORD = "4b7b97817bc41a9df9f07af8cccf4b11673f61539907d42339a72af8c4a031e0"
PORT = 1883
# WiFi连接
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
pass
print("WiFi Connected!")
print("IP Address:", wlan.ifconfig()[0])
# MQTT消息回调函数
def mqtt_callback(topic, msg):
print("Received message from topic: {}, Message: {}".format(topic, msg))
# 连接到阿里云IoT平台的MQTT服务器
def connect_mqtt():
client = MQTTClient(CLIENT_ID, ALIYUN_SERVER, 1883, USERNAME, PASSWORD)
client.set_callback(mqtt_callback)
client.connect()
print("Connected to Aliyun IoT Platform!")
return client
# 订阅主题
def subscribe_topic(client, topic):
client.subscribe(topic)
print("Subscribed to topic:", topic)
# 发布消息
def publish_message(client, topic, message):
client.publish(topic, message)
print("Published message to topic:", topic)
def main():
connect_wifi()
mqtt_client = connect_mqtt()
subscribe_topic(mqtt_client, "your_subscribed_topic")
# 模拟数据,并发布到指定的主题
while True:
data = "Your sensor data" # 替换成您的传感器数据
publish_message(mqtt_client, "your_published_topic", data)
time.sleep(5) # 每隔5秒发送一次数据
if __name__ == "__main__":
main()
wifi连接成功了