Skip to content
Permalink
edc9e2e0cf
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
29 lines (22 sloc) 876 Bytes
import paho.mqtt.client as mqtt
import json
from prometheus_client import start_http_server, Gauge
# 定义 Prometheus 指标
TEMPERATURE_GAUGE = Gauge('temperature', 'Temperature from sensor')
PRESSURE_GAUGE = Gauge('pressure', 'Pressure from sensor')
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("sensor/data")
def on_message(client, userdata, msg):
data = json.loads(msg.payload)
print(f"Temperature: {data['temperature']}, Pressure: {data['pressure']}")
TEMPERATURE_GAUGE.set(data['temperature'])
PRESSURE_GAUGE.set(data['pressure'])
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("admin", "public")
client.connect("localhost", 1883, 60)
# 启动 Prometheus HTTP 服务器
start_http_server(8000)
client.loop_forever()