You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32+MicroPython通过TLS向ThingSpeak安全发布数据失败求助

解决ESP32+MicroPython通过8883端口安全连接ThingSpeak MQTT的问题

针对你的代码无法连接ThingSpeak MQTT服务器的问题,需要修正以下几个关键点:

  • 修正MQTT服务器地址
    代码中thingspeak_address添加了ssl://前缀是错误的,MQTTClient的server参数仅需填写主机名,ssl=True参数已负责启用SSL加密。修改为:

    thingspeak_address = 'mqtt3.thingspeak.com'
    
  • 调整证书存储与读取方式
    ESP32的MicroPython不存在Linux系统的/etc/ssl/certs/目录,你需要将thingspeak.crt上传到ESP32文件系统的根目录(可通过Thonny、ampy等工具完成)。此外,部分版本的umqtt库要求直接传入证书字节数据而非文件路径,因此需要先读取证书内容:

    # 读取证书文件内容
    with open('thingspeak.crt', 'rb') as cert_file:
        ca_certificate = cert_file.read()
    
    # 初始化MQTT客户端时传入证书数据
    client = MQTTClient(server = thingspeak_address,
                        client_id = thingspeak_mqtt_client_id, 
                        user = thingspeak_mqtt_username, 
                        password = thingspeak_mqtt_password, 
                        ssl=True,
                        port = mqtt_port,
                        ssl_params={'ca_certs': ca_certificate})
    
  • 修正无效的Client ID
    当前thingspeak_mqtt_client_id设置为空格字符串,这是无效值。请填写ThingSpeak平台为你分配的合法Client ID(在ThingSpeak的MQTT配置页面获取),确保无空格且符合平台要求的格式。

  • 优化WiFi连接逻辑(可选)
    原代码无限等待WiFi连接,可增加超时机制避免卡死:

    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.connect(wifi_ssid, wifi_password)
    
    # 设置10秒连接超时
    timeout = 10
    start_time = time.time()
    while not wifi.isconnected() and time.time() - start_time < timeout:
        time.sleep(0.5)
        print('正在连接WiFi...')
    
    if not wifi.isconnected():
        print('WiFi连接超时,请检查网络参数')
        sys.exit()
    print('WiFi已连接!网络配置:', wifi.ifconfig())
    

修正后的完整代码示例

import network
from umqtt.robust import MQTTClient
import time
import dht
from machine import Pin
import sys

# 配置参数
wifi_ssid = '你的WiFi名称'
wifi_password = '你的WiFi密码'
thingspeak_address = 'mqtt3.thingspeak.com'
thingspeak_mqtt_client_id = '你的ThingSpeak Client ID'
thingspeak_mqtt_username = '你的ThingSpeak用户名'
thingspeak_mqtt_password = '你的ThingSpeak密码'
thingspeak_channel_id = '你的频道ID'
publish_period_in_sec = 20
mqtt_port = 8883

# 连接WiFi
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(wifi_ssid, wifi_password)

# WiFi连接超时处理
timeout = 10
start_time = time.time()
while not wifi.isconnected() and time.time() - start_time < timeout:
    time.sleep(0.5)
    print('正在连接WiFi...')

if not wifi.isconnected():
    print('WiFi连接超时,请检查参数')
    sys.exit()
print('WiFi已连接!网络配置:', wifi.ifconfig())

# 读取证书文件
try:
    with open('thingspeak.crt', 'rb') as cert_file:
        ca_certificate = cert_file.read()
except Exception as e:
    print('读取证书失败:', type(e).__name__, e)
    sys.exit()

# 连接ThingSpeak MQTT服务器
client = MQTTClient(server = thingspeak_address,
                    client_id = thingspeak_mqtt_client_id, 
                    user = thingspeak_mqtt_username, 
                    password = thingspeak_mqtt_password, 
                    ssl=True,
                    port = mqtt_port,
                    ssl_params={'ca_certs': ca_certificate})

try:            
    client.connect()
    print('成功连接MQTT服务器!')
except Exception as e:
    print('连接MQTT服务器失败:', type(e).__name__, e)
    sys.exit()

# 后续DHT11数据采集与发布逻辑(示例)
sensor = dht.DHT11(Pin(4))
while True:
    try:
        sensor.measure()
        temp = sensor.temperature()
        hum = sensor.humidity()
        # 构造ThingSpeak发布主题
        publish_topic = f'channels/{thingspeak_channel_id}/publish'
        publish_payload = f'field1={temp}&field2={hum}'
        client.publish(publish_topic, publish_payload)
        print(f'已发布数据:温度{temp}℃,湿度{hum}%')
        time.sleep(publish_period_in_sec)
    except Exception as e:
        print('数据采集或发布失败:', type(e).__name__, e)
        time.sleep(2)

内容的提问来源于stack exchange,提问作者Mahsa Faraji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 07:17:08