代码被吃了,重新发的试试:
-
- import mqtt
- import network
- import ssl
- import time
- import os
- from machine import Pin
- from umqtt.simple import MQTTClient
-
- wlan = network.WLAN(network.STA_IF)
- wlan.active(True)
- wlan.connect('WiFi名称', '密码')
- while not wlan.isconnected():
- print("try connect...")
- time.sleep(1)
-
- print("connect ok")
-
- CLIENT_ID = b'test_from_esp32c6'
- MQTT_SERVER = 'p52a5af8.ala.cn-hangzhou.emqxsl.cn'
- PORT = 8883
- USERNAME = b'esp32c6'
- PASSWORD = b'密码'
- TOPIC = b'esp32c6/test'
-
- BLOCK_MODE = True # 是否使用阻塞模式
-
- context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
- context.verify_mode = ssl.CERT_NONE
- try:
- client = MQTTClient(client_id=CLIENT_ID, # something unique to identify device, ie machine.unique_id()
- server= MQTT_SERVER,
- port=PORT, # if port ==0 AND ssl=True -> port=8883 the secure mqtt port
- user=USERNAME,
- password=PASSWORD,
- keepalive=7200,
- ssl=context
- )
-
- client.connect()
- print('Connected to %s MQTT Broker'%(MQTT_SERVER))
- except OSError as e:
- print('Failed to connect to the MQTT Broker.')
- time.sleep(5)
- machine.reset()
-
-
- def get_msg(topic, msg):
- print(msg)
- if msg == b'ON':
- led.value(True)
- elif msg == b'OFF':
- led.value(False)
-
-
- led=Pin(15, Pin.OUT)
-
- client.set_callback(get_msg)
- client.subscribe(TOPIC)
-
- counter = 0
- while True:
- try:
- counter = counter + 1
- print(counter)
- if BLOCK_MODE:
- client.wait_msg() # 阻塞
- else:
- client.check_msg() # 非租塞
- time.sleep(1)
- except Exception as e:
- print(str(e))
- time.sleep(2)
-
- print('reconnect!')
- client.connect()
-
- # 断线之后要重新订阅
- client.subscribe(TOPIC)
-
-
复制代码
|