logo

openmv与阿里云平台连接,这个错误是为什么,怎么解决

2024-04-08 22:18
7
rtbi
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()
7026b04f-4224-438a-a9c9-5a050638d012.png
ab44bdf0-1ce9-4fb6-8dcd-e7cc7a903a42.png
2024-04-12 19:23
I
网红小智智 星瞳科技

看上去你的WiFi不对,没有获取到ip,检查路由器是不是有问题。

按照这个代码测试一下:

https://forum.singtown.com/topic/10751/mqtt%E5%8D%8F%E8%AE%AE%E5%92%8C%E9%98%BF%E9%87%8C%E4%BA%91%E5%B9%B3%E5%8F%B0%E8%BF%9E%E6%8E%A5%E4%B8%8D%E4%B8%8A/4