问题
我想用 MQTT 连接 ESP32 到 demo thingsboard,我用 umqtt.simple 连接,但是有问题。每当我尝试连接时,它都会给我这个(文件“umqtt/simple.py”,第 99 行,连接中)或(文件“umqtt/simple.py”,第 57 行,连接中
索引器错误:列表索引超出范围),我相信它们是相同的。尽管当我尝试将 ESP32 连接到 thingspeak(进行一些编辑)时,它可以完美地连接、发送和接收数据。那么问题是什么?
我的代码:
- import machine
- import time
- from machine import Pin, PWM
- from umqtt.simple import MQTTClient
- from time import sleep
- import random
- import json
- import network
- #################MQTT###################
- def connect():
- username="USER_NAME"
- broker= "demo.thngsboard.io"
- topic = "v1/devices/me/telemetry"
- client = MQTTClient(username,broker)
- try:
- print("uuuuuuuuuu")
- client.connect()
- except OSError:
- print('Connection failed')
- sys.exit()
- data = dict()
- data["see"] = 15
- data2=json.dumps(data)#convert it to json
- print('connection finished')
- client.publish(topic,data2)
- print("kkkkkkkkkkkkkkkkkk")
- time.sleep(5)
- #print("Sending OFF")
- connect()
复制代码
我也看到了一个问题,他也有类似的问题,但是他没有提供解决方案就解决了:
设备未使用 MQTT 连接到 Thingsboard
当然,我会将它连接到互联网。
回答
问题似乎是micropython中的umqtt只支持不认证或者用户密码认证。
所以我将代码编辑如下:
- import machine
- import time
- from machine import Pin, PWM
- from umqtt.simple import MQTTClient
- from time import sleep
- import random
- import json
- import network
- #################MQTT###################
- def connect():
- username="Your_Token"
- broker= "demo.thingsboard.io"
- topic = "v1/devices/me/telemetry"
- Mqtt_CLIENT_ID = "Client_ID" # Max. Number is 23 due to MQTT specs
- PASSWORD=""
- client = MQTTClient(client_id=Mqtt_CLIENT_ID, server=broker, port=1883, user=username, password=PASSWORD, keepalive=10000)
- try:
- client.connect()
- except OSError:
- print('Connection failed')
- sys.exit()
- data = dict()
- data["see"] = 15
- data2=json.dumps(data)#convert it to json
- print('connection finished')
- client.publish(topic,data2)
- print("Data_Published")
- time.sleep(5)
- #print("Sending OFF")
- connect()
复制代码
|