树莓派边缘计算网关:MQTT+SQLite+Flask集成指南

树莓派边缘计算网关搭建:集成MQTT、SQLite与Flask的完整解决方案

引言

随着物联网(IoT)技术的快速发展,边缘计算因其低延迟、高可靠性和数据隐私保护等优势,成为智能设备部署的核心方案。树莓派作为低成本、高性能的单板计算机,非常适合作为边缘计算网关,连接传感器、执行器等终端设备,并实现数据的本地处理与云端交互。本文将详细介绍如何在树莓派上搭建一个完整的边缘计算网关,集成MQTT协议(轻量级消息传输)、SQLite数据库(本地数据存储)和Flask框架(Web管理界面),为开发者提供从环境配置到功能实现的完整指南。

1. 硬件与软件环境准备

硬件需求

  • 树莓派4B(推荐4GB RAM版本,支持多任务处理)
  • MicroSD卡(32GB以上,Class 10及以上)
  • 电源适配器(5V/3A,确保稳定供电)
  • 网络连接(有线或无线,建议使用有线以降低延迟)
  • 可选外设:传感器(如温湿度传感器DHT11)、执行器(如继电器模块)

软件环境

  • 操作系统:Raspberry Pi OS Lite(无桌面环境,减少资源占用)
  • Python 3.7+(树莓派默认安装)
  • pip包管理工具(用于安装第三方库)

2. MQTT协议集成:设备通信层

2.1 MQTT简介

MQTT(Message Queuing Telemetry Transport)是一种基于发布/订阅模式的轻量级消息协议,专为低带宽、高延迟或不可靠网络设计,非常适合物联网设备间的通信。

2.2 安装Mosquitto MQTT Broker

Mosquitto是开源的MQTT代理服务器,支持MQTT v3.1/v3.1.1/v5.0协议。

  1. # 更新软件包列表
  2. sudo apt update
  3. # 安装Mosquitto及其客户端工具
  4. sudo apt install mosquitto mosquitto-clients
  5. # 启动Mosquitto服务
  6. sudo systemctl enable mosquitto
  7. sudo systemctl start mosquitto

2.3 配置Mosquitto

编辑配置文件/etc/mosquitto/mosquitto.conf,添加以下内容以允许匿名访问(测试用,生产环境需配置认证):

  1. listener 1883
  2. allow_anonymous true

重启服务使配置生效:

  1. sudo systemctl restart mosquitto

2.4 Python MQTT客户端实现

使用paho-mqtt库实现MQTT客户端,用于发布和订阅消息。

  1. pip install paho-mqtt

示例代码:发布传感器数据

  1. import paho.mqtt.client as mqtt
  2. import time
  3. import random
  4. # MQTT配置
  5. BROKER = "localhost"
  6. PORT = 1883
  7. TOPIC = "sensor/temperature"
  8. def on_connect(client, userdata, flags, rc):
  9. print("Connected with result code " + str(rc))
  10. client = mqtt.Client()
  11. client.on_connect = on_connect
  12. client.connect(BROKER, PORT, 60)
  13. client.loop_start()
  14. try:
  15. while True:
  16. temp = random.uniform(20, 30) # 模拟温度数据
  17. client.publish(TOPIC, payload=str(temp), qos=1)
  18. print(f"Published temperature: {temp}")
  19. time.sleep(5)
  20. except KeyboardInterrupt:
  21. client.loop_stop()
  22. client.disconnect()

示例代码:订阅并处理消息

  1. def on_message(client, userdata, msg):
  2. print(f"Received message on topic {msg.topic}: {msg.payload.decode()}")
  3. client = mqtt.Client()
  4. client.on_connect = on_connect
  5. client.on_message = on_message
  6. client.connect(BROKER, PORT, 60)
  7. client.subscribe("sensor/#") # 订阅所有sensor主题
  8. client.loop_forever()

3. SQLite数据库集成:本地数据存储

3.1 SQLite简介

SQLite是一个轻量级的嵌入式数据库,无需单独服务器,直接通过文件存储数据,非常适合资源受限的边缘设备。

3.2 创建SQLite数据库与表

使用Python的sqlite3模块操作SQLite。

  1. import sqlite3
  2. # 连接数据库(不存在则创建)
  3. conn = sqlite3.connect('sensor_data.db')
  4. cursor = conn.cursor()
  5. # 创建表
  6. cursor.execute('''
  7. CREATE TABLE IF NOT EXISTS temperature_logs (
  8. id INTEGER PRIMARY KEY AUTOINCREMENT,
  9. timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
  10. value REAL
  11. )
  12. ''')
  13. conn.commit()
  14. conn.close()

3.3 存储MQTT接收的数据

修改订阅代码,将接收到的数据存入SQLite。

  1. def on_message(client, userdata, msg):
  2. try:
  3. value = float(msg.payload.decode())
  4. conn = sqlite3.connect('sensor_data.db')
  5. cursor = conn.cursor()
  6. cursor.execute('INSERT INTO temperature_logs (value) VALUES (?)', (value,))
  7. conn.commit()
  8. conn.close()
  9. print(f"Stored temperature: {value}")
  10. except ValueError:
  11. print("Invalid data format")
  12. # ...(其余代码同上)

4. Flask框架集成:Web管理界面

4.1 Flask简介

Flask是一个轻量级的Python Web框架,用于快速构建Web应用和API,适合作为边缘网关的管理界面。

4.2 安装Flask

  1. pip install flask

4.3 创建Flask应用

示例代码:基础Web界面

  1. from flask import Flask, render_template
  2. import sqlite3
  3. app = Flask(__name__)
  4. @app.route('/')
  5. def index():
  6. conn = sqlite3.connect('sensor_data.db')
  7. cursor = conn.cursor()
  8. cursor.execute('SELECT * FROM temperature_logs ORDER BY timestamp DESC LIMIT 10')
  9. data = cursor.fetchall()
  10. conn.close()
  11. return render_template('index.html', data=data)
  12. if __name__ == '__main__':
  13. app.run(host='0.0.0.0', port=5000, debug=True)

创建模板文件templates/index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Edge Gateway Dashboard</title>
  5. </head>
  6. <body>
  7. <h1>Recent Temperature Logs</h1>
  8. <table border="1">
  9. <tr>
  10. <th>ID</th>
  11. <th>Timestamp</th>
  12. <th>Value (°C)</th>
  13. </tr>
  14. {% for row in data %}
  15. <tr>
  16. <td>{{ row[0] }}</td>
  17. <td>{{ row[1] }}</td>
  18. <td>{{ row[2] }}</td>
  19. </tr>
  20. {% endfor %}
  21. </table>
  22. </body>
  23. </html>

4.4 启动Flask应用

运行Flask应用后,通过浏览器访问http://<树莓派IP>:5000查看数据。

5. 系统集成与自动化

5.1 使用systemd管理服务

创建systemd服务文件/etc/systemd/system/edge_gateway.service,实现开机自启。

  1. [Unit]
  2. Description=Edge Computing Gateway
  3. After=network.target mosquitto.service
  4. [Service]
  5. User=pi
  6. WorkingDirectory=/home/pi/edge_gateway
  7. ExecStart=/usr/bin/python3 /home/pi/edge_gateway/main.py
  8. Restart=always
  9. [Install]
  10. WantedBy=multi-user.target

启用并启动服务:

  1. sudo systemctl enable edge_gateway
  2. sudo systemctl start edge_gateway

5.2 日志与监控

配置日志轮转和监控工具(如htopnmon),确保系统稳定运行。

6. 安全性增强

  • MQTT认证:在Mosquitto配置中启用用户名/密码认证。
  • Flask安全:使用Flask-SecurityFlask-JWT-Extended保护API。
  • 防火墙:配置ufw限制访问端口。

7. 扩展功能

  • 多传感器支持:扩展MQTT主题和SQLite表结构。
  • 云端同步:通过MQTT或HTTP将数据上传至云端(如AWS IoT、Azure IoT Hub)。
  • 规则引擎:集成Node-RED或自定义规则实现本地自动化。

结论

本文详细介绍了如何在树莓派上搭建一个集MQTT、SQLite和Flask于一体的边缘计算网关,实现了设备通信、本地数据存储和Web管理界面的完整功能。该方案具有低成本、高灵活性和可扩展性,适用于智能家居、工业监控等多种场景。开发者可根据实际需求进一步优化和扩展功能。