原文链接:https://randomnerdtutorials.com/micropython-mqtt-esp32-esp8266/
QQ截图20230705230336.png

首先esp32C3需要安装micropython环境

参考之前的博文:
Micropython 合宙ESP32-C3的安装方法

安装 Mqtt所需库文件:umqttsimple.py

下载地址:
umqttsimple.rar

配置启动文件boot.py和main.py

boot.py 会在通电或者重置(reset)后首先执行,而 main.py 将会在 boot.py 之后执行,我们一般把我们的代码写在 main.py 里。

以下程序实现了订阅一个名为notification的主题,并发布了一个名为hello的主题,每 5 秒发送一条新消息"hello".

# boot.py
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import webrepl
#webrepl.start()

# Complete project details at https://RandomNerdTutorials.com

import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
esp.osdebug(None)
import gc
gc.collect()

ssid = '42101'
password = '15657859912'
mqtt_server = 'nbzch.cn'

client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'notification'
topic_pub = b'hello'

last_message = 0
message_interval = 5
counter = 0

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')
print(station.ifconfig())
# main.py
# Complete project details at https://RandomNerdTutorials.com

def sub_cb(topic, msg):
  print((topic, msg))
  if topic == b'notification' and msg == b'received':
    print('ESP received hello message')

def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub
  client = MQTTClient(client_id, mqtt_server)
  client.set_callback(sub_cb)
  client.connect()
  client.subscribe(topic_sub)
  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
  return client

def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()

try:
  client = connect_and_subscribe()
except OSError as e:
  restart_and_reconnect()

while True:
  try:
    client.check_msg()
    if (time.time() - last_message) > message_interval:
      msg = b'Hello #%d' % counter
      client.publish(topic_pub, msg)
      last_message = time.time()
      counter += 1
  except OSError as e:
    restart_and_reconnect()

发表评论