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

相关推荐
李慕婉学姐16 小时前
【开题答辩过程】以《基于微信小程序的线上讲座管理系统》为例,不会开题答辩的可以进来看看
javascript·mysql·微信小程序
2501_9159184117 小时前
iOS 上架应用市场全流程指南,App Store 审核机制、证书管理与跨平台免 Mac 上传发布方案(含开心上架实战)
android·macos·ios·小程序·uni-app·cocoa·iphone
Mr.Aholic18 小时前
分享几个开源的系统,包括小程序、商城系统、二手交易等常见的系统、很容易进行二次开发 【可以参考学习】
微信小程序·小程序·毕业设计·课程设计
2501_9159090619 小时前
HTTPS 错误排查实战,从握手到应用层的工程化流程
网络协议·http·ios·小程序·https·uni-app·iphone
JIngJaneIL1 天前
口腔健康系统|口腔医疗|基于java和小程序的口腔健康系统小程序设计与实现(源码+数据库+文档)
java·数据库·spring boot·小程序·论文·毕设·口腔医疗小程序
小光学长1 天前
基于微信小程序的背单词系统x1o5sz72(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·微信小程序·小程序
晨旭缘1 天前
解决小程序样式隔离styleIsolation
小程序
开发加微信:hedian1161 天前
“十五五”规划前瞻:短剧小程序系统开发的技术浪潮与开发新机遇
微信·小程序
weixin_177297220691 天前
剧本杀小程序系统开发:如何打造“爆款”剧本的数字引擎?
小程序·剧本杀
2501_915106321 天前
“HTTPS Everywhere” 的工程化实践,从全面加密到排查与真机取证
网络协议·http·ios·小程序·https·uni-app·iphone