micropython如何使用 SSL/TLS 连接MQTT服务器

我的开发环境:MicroPython v1.23.0 on 2024-06-02; Generic ESP32S3 module with Octal-SPIRAM with ESP32S3;
使用官方DEMO: 使用 ESP32 + MicroPython 连接 | EMQX Platform 文档测试不成功,在网上搜索了很多代码也不成功。
直接连接1883端口是可以的,但用证书连接8883总是出现各种问题。可能是最新版本umqtt raw.githubusercontent.com/micropython/micropython-lib/master/micropython/umqtt.simple/umqtt/simple.py的问题。

有对 CA 进行设置么?
如果连接的是 Public Broker: 免费的公共 MQTT 服务器 | EMQ 需要下载 CA 证书。
请参考:
使用 ESP32 + MicroPython 连接 | EMQX Platform 文档

import json
import random
import ssl
import time
from cwifi import wifi_content

from umqtt.simple import MQTTClient

SERVER = "tf9f2b9f.ala.cn-hangzhou.emqxsl.cn"
PORT = 8883
CLIENT_ID = 'micropython-client-{id}'.format(id=random.getrandbits(8))
USERNAME = 'a'
PASSWORD = 'a'
TOPIC = "raspberry/mqtt"

def on_message(topic, msg):
    print("Received '{payload}' from topic '{topic}'\n".format(
        payload = msg.decode(), topic = topic.decode()))

def connect():
    with open('emqxsl-ca.crt', 'rb') as f:
        cadata = f.read()
    ssl_params = dict()
    ssl_params["cert_reqs"] = ssl.CERT_REQUIRED
    ssl_params["cadata"] = cadata
    ssl_params["server_hostname"] = SERVER
    client = MQTTClient(CLIENT_ID, SERVER, PORT, USERNAME, PASSWORD, ssl = True, ssl_params = ssl_params)
    client.connect()
    print('Connected to MQTT Broker "{server}"'.format(server = SERVER))
    return client

def subscribe(client):
    client.set_callback(on_message)
    client.subscribe(TOPIC)

def loop_publish(client):
    msg_count = 0
    while True:
        msg_dict = {
            'msg': msg_count
        }
        msg = json.dumps(msg_dict)
        result = client.publish(TOPIC, msg)
        print("Send '{msg}' to topic '{topic}'".format(msg = msg, topic = TOPIC))
        client.wait_msg()
        msg_count += 1
        time.sleep(1)

def run():
    wifi_content()
    client = connect()
    subscribe(client)
    loop_publish(client)

if __name__ == "__main__":
    run()

错误信息:
Traceback (most recent call last):
File “”, line 56, in
File “”, line 51, in run
File “”, line 27, in connect
TypeError: unexpected keyword argument ‘ssl_params’

我看umqtt/simple.py源码中好像没有ssl_params参数了。

你最终解决了吗?是不是去掉这一项参数

解决了吗?问题基本一模一样

解决了吗?

都设置了还是不对

用的 cloud 服务器,可以直接开工单,有专人服务的。