使用 Raspberry Pi、Prometheus 和 Grafana 监测公寓的温度和湿度
我家里一直闲置着一台树莓派。某个周末,我突然想到可以让我家的公寓“更智能”。我说的“更智能”是指它可以追踪一些周围环境的指标。
我之前用过Prometheus和Grafana,所以决定把它们整合到我的解决方案里。没错,这听起来像是把简单的任务复杂化了,你或许可以用更简单的方法达到同样的效果:)。不过对我来说,这倒是个有趣的周末项目。
在这篇文章中,我将介绍我的房间温度和湿度监测装置。
硬件组件
以下是我在项目中使用的所有组件:
- 树莓派 3 B 型
- 16 GB microSD 卡
- DHT11温湿度传感器
- 手机充电器,用于给树莓派供电
将传感器连接到树莓派
我将地线引脚连接到树莓派的地线,数据引脚连接到GPIO 14引脚,Vcc引脚连接到3.3V电源引脚。
读取传感器数据
为了读取传感器数据并将其提供给 Prometheus,我选择了DHT11_Python库,但该库相当不稳定,有时不会返回有效结果,因此您的图表中可能会出现一些空白。
此外,我还创建了一个简单的 Flask API 来为 Prometheus 提供指标:
from flask import Flask
import dht11
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
instance = dht11.DHT11(pin=14)
app = Flask(__name__)
@app.route("/metrics")
def metrics():
dht11_data = ""
result = instance.read()
if result.is_valid():
dht11_data = f"""pihome_temperature {result.temperature}
pihome_humidity {result.humidity}"""
return f"{dht11_data}", 200, {'Content-Type': 'text/plain; charset=utf-8'}
if __name__ == "__main__":
app.run(host='0.0.0.0')
普罗米修斯配置
为了从我的 Flask API 中抓取指标,我添加了以下配置prometheus.yml:
global:
scrape_interval: 30s
scrape_configs:
- job_name: 'pihome'
static_configs:
- targets: [pihome:5000]
Grafana 配置
然后,/etc/grafana/provisioning我在 中添加了数据源配置:
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
url: http://prometheus:9090/
access: proxy
isDefault: true
也可以将 Grafana 仪表板作为 json 文件添加到配置文件夹中,这样每次重新部署 Grafana 时就不需要创建新的仪表板了。
将一切连接起来
为了使所有内容都易于移植和安装,我将 Flask API 打包到 Docker 镜像中,并在其中配置了所有服务docker-compose.yaml:
version: '3'
services:
pihome:
image: pihome
build: .
restart: always
devices:
- "/dev/mem:/dev/mem"
privileged: true
ports:
- 5000:5000
prometheus:
image: prom/prometheus:v2.16.0
user: root
volumes:
- ./prometheus/:/etc/prometheus/
- /var/prometheus:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--storage.tsdb.retention.time=30d'
- '--web.console.libraries=/usr/share/prometheus/console_libraries'
- '--web.console.templates=/usr/share/prometheus/consoles'
ports:
- 9090:9090
depends_on:
- pihome
restart: always
grafana:
image: grafana/grafana:6.6.2
depends_on:
- prometheus
ports:
- 80:3000
volumes:
- ./grafana/:/etc/grafana
restart: always
结果
我让我的程序运行了一段时间,以收集一些历史数据,仪表盘看起来是这样的:
Git项目
您可以在 GitHub 上找到我的完整配置和代码:https://github.com/pdambrauskas/pihome
文章来源:https://dev.to/pdambrauskas/monitoring-apartment-Temperature-humidity-with-raspberry-pi-prometheus-grafana-1i48