微信小程序通过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博客

相关推荐
小蒜学长1 小时前
基于springboot 校园餐厅预约点餐微信小程序的设计与实现(代码+数据库+LW)
数据库·spring boot·微信小程序
cookqq1 小时前
Cursor和Hbuilder用5分钟开发微信小程序
微信小程序·小程序·curosor
老华带你飞3 小时前
考研论坛平台|考研论坛小程序系统|基于java和微信小程序的考研论坛平台小程序设计与实现(源码+数据库+文档)
java·vue.js·spring boot·考研·小程序·毕设·考研论坛平台小程序
毕设源码-钟学长4 小时前
【开题答辩全过程】以 基于微信小程序的美发服务系统的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
canglingyue5 小时前
微信小程序罗盘功能开发指南
微信小程序·小程序
三脚猫的喵7 小时前
微信小程序中实现AI对话、生成3D图像并使用xr-frame演示
前端·javascript·ai作画·微信小程序
2501_915106328 小时前
App Store 软件上架全流程详解,iOS 应用发布步骤、uni-app 打包上传与审核要点完整指南
android·ios·小程序·https·uni-app·iphone·webview
海绵宝宝不喜欢侬8 小时前
UniApp微信小程序-实现蓝牙功能
微信小程序·uni-app
开发加微信:hedian11610 小时前
微信推客小程序系统开发技术实践
微信·小程序
Python大数据分析11 小时前
uniapp微信小程序商品列表数据分页+本地缓存+下拉刷新+图片懒加载
缓存·微信小程序·uni-app