问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

MQTT + 微信小程序:打造你的掌上ESP32智能鱼缸,远程监控,实时掌控

创作时间:
作者:
@小白创作中心

MQTT + 微信小程序:打造你的掌上ESP32智能鱼缸,远程监控,实时掌控

引用
CSDN
1.
https://blog.csdn.net/qq_40431685/article/details/140065101

厌倦了传统鱼缸的繁琐管理?想要随时随地了解鱼儿的生活状态?本项目将带你使用ESP32开发板、MQTT通信协议和微信小程序,打造一个功能完善的智能鱼缸系统。实时监测水温、远程控制灯光、定时定量喂食……一切尽在掌握!

一、项目概述

本项目将使用ESP32开发板、MQTT通信协议和微信小程序,打造一个功能完善的智能鱼缸系统。系统能够实时监测水温、远程控制灯光、定时定量喂食等,实现对鱼缸环境的全面监控和管理。

二、系统架构

本系统采用典型的物联网架构,主要分为硬件层、软件层和云平台三个部分:

2.1 硬件层

  • ESP32开发板:系统的控制核心,负责采集传感器数据、控制外设以及与云端进行通信。
  • 传感器:水温传感器(DS18B20)、光照传感器(BH1750)等,实时监测鱼缸环境参数。
  • 执行器:LED灯带(WS2812B)、水泵、喂食器等,用于调节鱼缸环境和实现自动化功能。

2.2 软件层

  • ESP32程序:负责读取传感器数据、控制外设、连接WiFi和MQTT Broker,并将数据发布到云端。
  • 微信小程序:提供用户界面,用于显示鱼缸状态、发送控制指令以及设置定时任务等。

2.3 云平台

  • MQTT Broker:负责接收来自ESP32的数据,并转发至订阅该主题的客户端,例如微信小程序。

2.4 系统架构图

三、实例代码介绍

3.1 ESP32代码(部分)

#include <WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// 引脚定义
#define ONE_WIRE_BUS 2  // DS18B20 数据引脚

// WiFi 和 MQTT Broker 信息
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";
const char* mqtt_server = "your_mqtt_broker_ip";
const int mqtt_port = 1883;

// 创建 OneWire 和 Dallas Temperature 对象
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// 创建 WiFi 和 MQTT 客户端
WiFiClient espClient;
PubSubClient client(espClient);

// ... 其他变量和函数定义 ...

void setup() {
  Serial.begin(115200);
  // 初始化传感器
  sensors.begin();
  // 连接 WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  // 连接 MQTT Broker
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
    Serial.println("Connecting to MQTT Broker...");
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
      // 订阅控制指令主题
      client.subscribe("fishTank/control");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void loop() {
  // MQTT 连接保持
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  // 读取水温数据
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);
  // 发布数据到 MQTT 主题
  char tempString[8];
  dtostrf(temperatureC, 6, 2, tempString);
  client.publish("fishTank/temperature", tempString);
  // ... 其他传感器数据读取和发布 ...
  // ... 其他控制逻辑 ...
  delay(1000); 
}

// MQTT 回调函数,处理接收到的控制指令
void callback(char* topic, byte* payload, unsigned int length) {
  // ... 解析控制指令并控制相应的外设 ...
}

// 重新连接 MQTT Broker
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
      // 重新订阅主题
      client.subscribe("fishTank/control");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}  

3.2 微信小程序代码(部分)

// pages/index/index.js
Page({
  data: {
    temperature: '--', // 水温
    lightIntensity: '--', // 光照强度
    // ... 其他数据 ...
  },
  // 页面加载时连接 MQTT Broker
  onLoad: function () {
    // 初始化 MQTT 客户端
    this.client = mqtt.connect('wss://your_mqtt_broker_ip:8083/mqtt', {
      username: 'your_mqtt_username',
      password: 'your_mqtt_password',
    });
    // 订阅数据主题
    this.client.on('connect', () => {
      this.client.subscribe('fishTank/temperature', (err) => {
        if (!err) {
          console.log('Subscribed to fishTank/temperature');
        }
      });
      // ... 订阅其他数据主题 ...
    });
    // 处理接收到的数据
    this.client.on('message', (topic, message) => {
      switch (topic) {
        case 'fishTank/temperature':
          this.setData({ temperature: message.toString() });
          break;
        // ... 处理其他数据 ...
      }
    });
  },
  // 页面卸载时断开 MQTT 连接
  onUnload: function () {
    this.client.end();
  },
  // 控制灯光开关
  toggleLight: function () {
    // 发送控制指令
    this.client.publish('fishTank/control', 'toggleLight');
  },
  // ... 其他控制函数 ...
});

3.3 MQTT服务端代码(python)

本示例使用库创建一个简单的MQTT Broker,并监听来自ESP32和微信小程序的消息。

import asyncio
from hbmqtt.broker import Broker

# MQTT Broker 配置
config = {
    'listeners': {
        'default': {
            'type': 'tcp',
            'bind': '0.0.0.0:1883'  # 监听所有接口的 1883 端口
        },
        'ws-mqtt': {
            'bind': '0.0.0.0:8083',
            'type': 'ws',
            'websocket_path': '/mqtt'
        }
    },
    'sys_interval': 10,
    'auth': {
        'allow-anonymous': True,  # 允许匿名访问,实际项目中建议关闭
    }
}

# 启动 Broker
async def startBroker():
    broker = Broker(config)
    await broker.start()

if __name__ == '__main__':
    formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
    logging.basicConfig(level=logging.INFO, format=formatter)
    asyncio.get_event_loop().run_until_complete(startBroker())
    asyncio.get_event_loop().run_forever()

四、总结和知识点归纳(附部分知识点链接)

通过以上代码示例,我们可以清晰地了解到智能鱼缸系统各个部分是如何协同工作的。当然,实际项目中还需要根据具体需求进行更复杂的逻辑处理和功能扩展。

  • ESP32开发板

  • 简介:ESP32 Wi-Fi & 蓝牙 SoC | 乐鑫科技

  • 购买链接:ESP32 Wi-Fi & 蓝牙 SoC | 乐鑫科技(官方商城或其他电商平台)

  • DS18B20温度传感器

  • 简介:DS18B20数据手册和产品信息 | Analog Devices

  • 购买链接:各大电子元器件商城

  • Arduino IDE

  • 下载地址:Software | Arduino

  • ESP32开发环境配置:Welcome to ESP32 Arduino Core’s documentation - - — Arduino ESP32 latest documentation

  • 微信开发者工具

  • 下载地址:微信开发者工具下载地址与更新日志 | 微信开放文档

  • MQTT库:https://developers.weixin.qq.com/miniprogram/dev/api/network/mqtt/MqttContext.html

  • MQTT代理

  • EMQX:EMQX:用于物联网、车联网和工业物联网的企业级MQTT平台(开源、功能强大)

  • Mosquitto:Eclipse Mosquitto(轻量级、易于部署)

  • 云服务:阿里云、腾讯云等云服务商提供的MQTT服务

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号