MicroPython – MQTT 與 ESP32/ESP8266

2021-02-20 Python與Arduino

MicroPython – MQTT 與 ESP32/ESP8266

在這個教程中,將會學習如何使用MQTT在ESP8266與MQTT 伺服器之間進行數據交換。最為一個簡單的例子,我將使用一個ESP32開發板向MQTT服

務器發送消息,同時從MQTT伺服器訂閱一個消息。

發布消息的主題(topic)為hello,定於的主題為notification。

我在這裡使用的MQTT伺服器為mosquitto,在我的Windows10系統的電腦上安裝了虛擬機,虛擬機安裝Ubuntu系統,在Ubuntu系統裡安裝的mosquitto。當然也可以安裝在樹莓派上。

準備工作:

首先需要為ESP32安裝micropython固件,MQTT伺服器已經設置好,我這裡MQTT伺服器已經安裝完成,IP位址為192.168.1.121,同時設置了連接MQTT伺服器的帳號與密碼,帳號為miss,密碼為123456。

準備ESP32:

導入umqtttsimple 庫,庫下載地址:https://raw.githubusercontent.com/RuiSantosdotme/ESP-MicroPython/master/code/MQTT/umqttsimple.py

複製代碼,在uPyCraft中新建一個文件,粘貼,保存為umqttsimple.py文件

準備boot.py

導入必要的庫:

import time

from umqttsimple import MQTTClient

import ubinascii

import machine

import micropython

import network

import esp

設置debug為None,激活垃圾收集器。

esp.osdebug(None)

import gc

gc.collect()

定義一些必要的變量,包括本地WiFi帳號與密碼,mqtt伺服器IP位址,MQTT用戶名與密碼,mqtt客戶端id,發布與訂閱的主題,接收消息的時間間隔等。

ssid = 'your-ssid'

password = 'your-pwd'

mqtt_server = '192.168.1.121'

mqtt_user='miss'

mqtt_pwd='123456'

client_id = ubinascii.hexlify(machine.unique_id())

topic_sub = b'notification'

topic_pub = b'hello'

last_message = 0

message_interval = 5

counter = 0

將ESP32連接到網絡:

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


定義一個訂閱回調函數:

def sub_cb(topic, msg):

  print((topic, msg))

  if topic == b'notification' and msg == b'received':

    print('ESP received hello message')

定義一個連接MQTT伺服器和訂閱主題的函數:

def connect_and_subscribe():

  global client_id, mqtt_server, topic_sub,mqtt_user,mqtt_pwd

  client = MQTTClient(client_id, mqtt_server,user=mqtt_user, password=mqtt_pwd, keepalive=60)

  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()

開始使用上面定義的函數連接MQTT伺服器,訂閱notification主題,並向hello主題發布消息:

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()

完整boot.py與main.py代碼可以查看下面的騰訊文檔連結

https://docs.qq.com/doc/DS1pqd25qSUdIQ3dN

運行程序與效果圖:

啟動虛擬機上的mqtt伺服器

2.上傳umqttsimple.py

3.上傳boot.py

4.上傳main.py

5.使用mosquitto_sbu命令訂閱ESP32發送的消息

6.使用mosquitto_pub命令發布消息到notification,ESP32訂閱該消息

更多教程請關注:

相關焦點

  • 【玩轉ESP32】14、esp32 mqtt client
    組件支持MQTT over TCP、SSL with mbedtls、MQTT over Websocket、 MQTT over Websocket Secure;支持訂閱、發布、身份驗證、遺囑消息、心跳、以及3個消息等級。
  • 啟明雲端分享|盤點Esp32-C3與Esp8266 的區別
    a.ESP8266 準備工具 sudo apt-get install gcc git wget make libncurses-dev flex bison gperf python python-serial.ESP32-c3 準備工具
  • ESP32S2 與 ESP32 開發方式對比,帶你入門環境搭建
    python python-pip python-setuptools python-serial python-click python-cryptography python-future python-pyparsing python-pyelftools cmake ninja-build ccache libffi-dev libssl-dev3.3 【方式一】用博主提供的方式拉取最新代碼
  • 【教程】ESP8266 連接到的免費的 EMQ X MQTT 伺服器
    #include <esp8266wifi.h> #include <pubsubclient.h>2.設置 Wi-Fi 名稱和密碼,以及 MQTT 伺服器連接地址和埠 const char *ssid = "name"; const char
  • 【ESP8266集合】微信小程序MQTT遠程控制安信可NodeMCU
    (void){ esp_mqtt_client_config_t mqtt_cfg = { .event_handle = mqtt_event_handler, .host = "xxxxxx.mqtt.iot.gz.baidubce.com", .username = "xxxxxx/device", .password = "LXSFzu50zI5ezBrl
  • ESP8266固件燒寫及連接TFT屏
    ,具體方法見官方文檔説明(http://docs.micropython.org/en/latest/esp8266/tutorial/intro.html#deploying-the-firmware)。
  • ESP8266 刷寫MicroPython固件
    即esptool.py write_flash -h。(如果在提供的Windows MSYS2環境中使用ESP32的esp-idf,則不需要此環境,該環境使用本機Windows Python並按原樣接受COM埠。)在Linux中,當前用戶可能無法訪問串行埠,並且將出現「權限被拒絕」錯誤。
  • micropython 發布 1.16 版
    some spelling mistakespyboard: fix typo in pyb.Switch tutorialesp32: add UART to quickrefesp32: add WDT to quickrefesp32: add SDCard to quickrefesp8266: add WDT to quickref
  • ESP8266開發方式知多少?
    ESP8266簡介ESP8266是樂鑫(https://www.espressif.com/zh-hans)推出的面向物聯網應用的高性價比、高度集成的Wi-Fi MCU,內置32-bit MCU和2.4GHz的Wi-Fi晶片。外設包括UART、GPIO、I2S、I2C、SDIO、PWM、ADC和SPI。
  • 使用ESP32來學習Python之開發環境搭建
    Python是近來比較火的一種語言,對嵌入式人員來說,通過ESP32來學習Python是一種比較便捷、靠譜的方法。
  • MicroPython 1.17 版本發布
    v1.17:F-strings、新 machine.I2S 類、ESP32-C3 支持和 LEGO_HUB_NO6 板此版本的 MicroPython 添加了對 f-strings (PEP-498) 的支持,與標準通 Python 相比有一些限制。F 字符串本質上是 "".format() 的語法糖,使格式化字符串更加方便。
  • ESP8266 連接到免費的公共 MQTT 伺服器
    ;}設置 MQTT 伺服器,並編寫回調函數,同時將連接信息列印到串口監視器上client.setServer(mqtt_broker, mqtt_portclient.connected()) {    Serial.println("Connecting to public emqx mqtt broker");    if (client.connect("esp8266-client")) {
  • 智能硬體晶片---------ESP32 介紹
    參考連結:https://docs.micropython.org/en/latest/esp32/tutorial/intro.htmlhttps://github.com/easytarget/esp32-cam-webserverhttps://www.espressif.com/sites/default/files/documentation/esp32_wrover_datasheet_cn.pdfhttp://m5edu.com/Product/m5stack-core-fire/https://flow.m5stack.com
  • 在 ESP32-S2 上試用 circuitpython
    ESP32-S2 是樂鑫去年推出的 SOC,它可以看作是 ESP32 的低成本簡化改進版本,在保持了 ESP32 的主要特點下,去掉了乙太網
  • ESP8266與Mqtt遠程控制
    esp8266通過使用PubSubClient庫與Mqtt實現遠程控制1.ESP8266硬體部分貼出以下代碼
  • MicroPython 2020年11月更新
    tests/micropython/extreme_exc.py: Unlink alloc'd lists earlier in chain. stm32: Support C++ code and user C modules written in C++.
  • MicroPython使用MQTT協議接入OneNET雲平臺
    需要準備的軟體有:1、ESP_DOWNLOAD_TOOL  用於下載開發板固件;2、uPyLoader 用於與開發板的文件傳輸,同時該軟體也具有終端軟體調試的功能,該軟體的使用和介紹可以在:https://github.com/BetaRavener/uPyLoader/中查看;3、第三方庫文件:umqtt,該模塊封裝了MQTT協議,該模塊可以在:https://github.com/micropython
  • ESP8266 + MQTT :如何實現 LED 燈的遠程控制
    設置 WIFI 名稱和密碼,以及 MQTT Broker 連接地址和埠const char *ssid = "mousse"; const char *password = "qweqweqwe"; const char *mqtt_broker = "broker.emqx.io";const char *topic = "esp8266/led
  • 在Jupyter Notebook中使用MicroPython從瀏覽器控制電子設備
    ~$ esptool.py --port /dev/cu.wchusbserial14630 --baud 460800 write_flash --flash_size=detect 0 /Users/kali/Downloads/esp8266-20191220-v1.12.binesptool.py v2.8Serial port /dev/cu.wchusbserial14630
  • 零基礎入門學用物聯網 - MQTT篇 2-7 ESP8266 MQTT 遺囑應用
    (9600); WiFi.mode(WIFI_STA); connectWifi(); mqttClient.setServer(mqttServer, 1883); mqttClient.setKeepAlive(10); connectMQTTserver();} void loop() { if (!