微信小程序通过mqtt控制esp32

目录

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"时灯灭。

python 复制代码
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,核心代码如下:

javascript 复制代码
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消息,这样你的设备在收到相应的消息之后,上面的灯会点亮/熄灭。

javascript 复制代码
  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博客

相关推荐
哈罗哈皮3 小时前
trea也很强,我撸一个给你看(附教程)
前端·人工智能·微信小程序
0xDevNull4 小时前
基于Java的小程序地理围栏实现原理
java·小程序
Kingexpand_com4 小时前
实用技巧:小程序积分体系的功能拆解与高效利用指南
小程序·仓库管理·库存管理·小程序定制开发
毕设源码-赖学姐4 小时前
【开题答辩全过程】以 居家养老服务微信小程序设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
RuoyiOffice5 小时前
SpringBoot+Vue3+Uniapp实现PC+APP双端考勤打卡设计:GPS围栏/内网双模打卡、节假日方案、定时预生成——附数据结构和核心源码讲解
java·spring·小程序·uni-app·vue·产品运营·ruoyi
杰建云1677 小时前
企业内部是否需要技术团队做小程序
小程序·小程序制作
2501_915921437 小时前
2026 iOS 上架新趋势 iOS 发布流程模块化
android·ios·小程序·https·uni-app·iphone·webview
码视野8 小时前
#Cursor加Specs编程,3小时上线一个有管理后台和移动端的检举举报全流程平台(完全开源)
spring boot·小程序·ai编程
Emma_Maria8 小时前
【小程序】插件开发总结
微信小程序
2501_933907219 小时前
如何选择宁波小程序公司,实现高效的小程序开发?
科技·微信小程序·小程序