【MQTT】在ESP32平台上用microPython实现MQTT通信

想要搭建MQTT服务器,请参考

☞☞ 搭建MQTT服务器篇

服务器平台:Ubuntu20.04 + mosquitto
硬件平台:ESP32开发板
MQTT客户端:mosquitto、 通信猫、 mqttfx等等
开发平台:Thoony 3.2

先看下 microPython 支持哪些模块吧:

>>> help('modules')
__main__          gc                ubinascii         upysh
_boot             inisetup          ubluetooth        urandom
_onewire          machine           ucollections      ure
_thread           math              ucryptolib        urequests
_uasyncio         micropython       uctypes           uselect
_webrepl          neopixel          uerrno            usocket
apa106            network           uhashlib          ussl
btree             ntptime           uhashlib          ustruct
builtins          onewire           uheapq            usys
cmath             uarray            uio               utime
dht               uasyncio/__init__ ujson             utimeq
ds18x20           uasyncio/core     umqtt/robust      uwebsocket
esp               uasyncio/event    umqtt/simple      uzlib
esp32             uasyncio/funcs    uos               webrepl
flashbdev         uasyncio/lock     upip              webrepl_setup
framebuf          uasyncio/stream   upip_utarfile     websocket_helper
Plus any modules on the filesystem

我们这里将用到 umqtt/simple模块中的mqtt客户端、 machine模块中的Pin、network模块、time模块。

这里主要演示如何远程点led灯和监控led灯的状态。

用microPython写l简单的测试demo程序

from umqtt.simple import MQTTClient
from machine import Pin
import network
import time

ssid='your ssid'
passwd='your passwd'
client_id = "slim_id"
mserver = '192.168.0.135'
port=1883

topic_ctl = b'led_ctl'#设备订阅的主题,客户端推送消息的主题
topic_sta = b'led_sta'#客户端订阅的主题,设备推送消息的主题
client = None
wlan = None

led1=Pin(2, Pin.OUT, value=1)
led2=Pin(5, Pin.OUT, value=1)
    
def sub_callback(topic, msg):
    """
    收到订阅消息回调
    """
    global client
    print((topic_ctl, msg))
    if msg == b'led1 ON' or msg == b'led1 on':
        pub_msg = 'LED1: ON-state'
        led1.value(0)
    elif msg == b'led1 OFF' or msg == b'led1 off':
        pub_msg = 'LED1: OFF-state'
        led1.value(1)
    elif msg == b'led2 ON' or msg == b'led2 on':
        pub_msg = 'LED2: ON-state'
        led2.value(0)
    elif msg == b'led2 OFF' or msg == b'led2 off':
        pub_msg = 'LED2: OFF-state'
        led2.value(1)
    else:
        pub_msg = 'other msg'
    client.publish(topic_sta, pub_msg, retain=True)

def connectWiFi():
    """
    连接到WiFi网络
    """
    global wlan
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.disconnect()
    wlan.connect(ssid, passwd)
    while(wlan.ifconfig()[0]=='0.0.0.0'):
        time.sleep(1)

try:
    connectWiFi()
    client = MQTTClient(client_id, mserver, 0)
    client.set_callback(sub_callback)
    client.connect()
    client.subscribe(topic_ctl)
    client.publish(topic_sta, 'ESP32 Device online', retain=True)
    print("Connected to %s, subscribed to %s topic" % (mserver, topic_ctl))
    while True:
        client.wait_msg()
finally:
    if client is not None:
        print('off line')
        client.disconnect()
    wlan.disconnect()
    wlan.active(False)

测试

通信猫测试端

订阅: led_sta
发布: led_ctl

【MQTT】在ESP32平台上用microPython实现MQTT通信_第1张图片

Thonny ESP32端

设备终端
订阅:led_ctl
发布:led_sta

【MQTT】在ESP32平台上用microPython实现MQTT通信_第2张图片

手机APP端

【MQTT】在ESP32平台上用microPython实现MQTT通信_第3张图片

服务器端

mosquitto mqtt服务器
订阅: led_sta 、 led_ctl

【MQTT】在ESP32平台上用microPython实现MQTT通信_第4张图片

一个物联网属性的LED灯就做好了

你可能感兴趣的:(无线物联网,ESP32,Python,MQTT,microPython,ESP32,umqtt)