微信小程序通过mqtt控制esp32

发布于:2025-04-22 ⋅ 阅读:(20) ⋅ 点赞:(0)

目录

1.注册巴法云

2.设备连接mqtt

3.微信小程序

备注


本文esp32用的是MicroPython固件,MQTT服务用的是巴法云

本文参考巴法云官方教程:https://bemfa.blog.csdn.net/article/details/115282152

1.注册巴法云

注册登陆并新建一个topic,注意是MQTT设备云。

2.设备连接mqtt

代码如下,以点亮esp32设备上的蓝色灯举例,订阅上一步创建的topic,当设备从mqtt服务器收到“on”时,灯亮,收到“off”时灯灭。

from umqtt.simple import MQTTClient
import time
from machine import Timer, Pin

# 需要修改的地方
wifiName = "***"  # wifi 名称,不支持5G wifi
wifiPassword = "***"  # wifi 密码
clientID = "***"  # Client ID ,密钥,巴法云控制台获取
myTopic = "topic"  # 需要订阅的主题值,巴法MQTT控制台创建

# 默认设置
serverIP = "bemfa.com"  # mqtt 服务器地址
port = 9501
led_pin = Pin(2, Pin.OUT)


# WIFI 连接函数
def do_connect():
    import network

    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print("connecting to network...")
        sta_if.active(True)
        sta_if.connect(wifiName, wifiPassword)
        while not sta_if.isconnected():
            pass
    print("connect  WiFi ok")


# 接收消息,并处理
def MsgOK(topic, msg):  # 回调函数,用于收到消息
    print((topic, msg))  # 打印主题值和消息值
    if topic == myTopic.encode():  # 判断是不是发给myTopic的消息
        if msg == b"on":  # 当收到on
            print("rec on")
            led_pin.value(1)
        elif msg == b"off":  #  当收到off
            print("rec off")
            led_pin.value(0)


# 初始化mqtt连接配置
def connect_and_subscribe():
    client = MQTTClient(clientID, serverIP, port, keepalive=60)
    client.set_callback(MsgOK)
    try:
        client.connect()
        print("MQTT connected!")
    except Exception as e:
        print("MQTT connect failed:", e)
    client.subscribe(myTopic, qos=0)
    print("Connected to %s" % serverIP)
    return client


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


# 开始连接WIFI
do_connect()

# 开始连接MQTT
try:
    client = connect_and_subscribe()
except OSError as e:
    restart_and_reconnect()


# 全局变量记录定时器状态
timer_running = False


# 定时器函数
def send_ping(t):
    client.ping()
    print("Ping sent!")


# 初始化定时器
def init_timer():
    global timer_running
    if not timer_running:
        timer = Timer(-1)
        timer.init(period=30000, mode=Timer.PERIODIC, callback=send_ping)
        timer_running = True


# 程序启动时初始化定时器
init_timer()

while True:
    try:
        client.check_msg()
    except OSError as e:  # 如果出错就重新启动
        print("Failed to connect to MQTT broker. Reconnecting...")
        restart_and_reconnect()

3.微信小程序

在微信小程序中,通过wxs连接mqtt,核心代码如下:

data: {
    uid:"******",//用户密钥,巴法云控制台获取
    ledtopic:"topic",//主题,mqtt控制台创建
    client: null,//mqtt客户端,默认为空
  },

  mqttConnect(){
    var that = this
    
    //MQTT连接的配置
    var options= {
      keepalive: 60, //60s ,表示心跳间隔
      clean: true, //cleanSession不保持持久会话
      protocolVersion: 4, //MQTT v3.1.1
      clientId:this.data.uid
    }
    //初始化mqtt连接
     this.data.client = mqtt.connect('wxs://bemfa.com:9504/wss',options)
     // 连接mqtt服务器
     this.data.client.on('connect', function () {
      console.log('连接服务器成功')
    })
    //接收消息
    that.data.client.on('message', function (topic, message) {
      console.log(topic)
      var  msg = message.toString()
      //打印消息
      console.log('收到消息:'+msg)
    })

    //断线重连
    this.data.client.on("reconnect", function () {
      console.log("重新连接")
    });
  }

在小程序中添加一个按钮来往指定topic发送on/off消息,这样你的设备在收到相应的消息之后,上面的灯会点亮/熄灭。

  onChange({ detail }){
    //detail是滑块的值,检查是打开还是关闭,并更换正确图标
    this.setData({ 
      checked: detail,
     });
     if(detail == true){//如果是打开操作
      this.data.client.publish(this.data.ledtopic, 'on')//mqtt推送on
      this.setData({ 
        ledicon: "/utils/img/lighton.png",//设置led图片为on
       });
     }else{
      this.data.client.publish(this.data.ledtopic, 'off')//mqtt推送off
      this.setData({ 
        ledicon: "/utils/img/linghtoff.png",//设置led图片为off
       });
     }
  }

完整的小程序项目代码参考:点此下载

在巴法云控制台可以看到小程序发送的消息记录 :

https://cloud.bemfa.com/zip/mqtt/wxbemfa.zip

备注

(1)在手机上预览调试需要用真实的小程序id,没有的话先去去微信公众平台注册一个。在项目中添加小程序id有两种方法:1.在导入项目时填写;2.在项目根目录下的project.config.json文件中填写appid。

(2)如果小程序发不出消息,去微信公众平台,找到你当前的小程序,在request合法域名处,添加域名https://api.bemfa.com

arduino的可参考【基于Arduino IDE平台开发ESP8266连接巴法云】_esp8266巴法云-CSDN博客


网站公告

今日签到

点亮在社区的每一天
去签到