[英]MQTT to InfluxDB giving me nothing but 0 values
currently working on a python code that subscribes to a MQTT topic published by a RaspberryPi hooked up to a BME280 sensor reading for Temperature and Humidity then saves it to a database.目前正在研究一个 python 代码,该代码订阅了一个由 RaspberryPi 发布的 MQTT 主题,该主题连接到 BME280 传感器读取温度和湿度,然后将其保存到数据库中。 I've created the database and my mqtt works after the topic with "MyMQTT" app
我已经创建了数据库,并且我的 mqtt 在使用“MyMQTT”应用程序的主题之后工作
Problems start when i try to run it and all i get is 0s in when I try to read the database.当我尝试运行它时,问题就开始了,当我尝试读取数据库时,我得到的只是 0。
Any ideas?有任何想法吗?
Publisher code:出版商代码:
import RPi.GPIO as GPIO
import time
import smbus2
import bme280
import paho.mqtt.client as mqtt
mqtt_broker = "test.mosquitto.org"
topic1 = "tp/eng/iotp_project/temp"
topic2 = "tp/eng/iotp_project/hum"
port = 1
address = 0x76
bus = smbus2.SMBus(port)
calibration_params = bme280.load_calibration_params(bus, address)
# Set the GPIO pin numbers for the fan and buzzer
fan = 23
buzzer = 22
# Set the temperature threshold for turning on the fan
fan_threshold = 24
# Set the humidity threshold for turning on the buzzer
buzzer_threshold = 80
# Initialize the GPIO pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(fan, GPIO.OUT)
GPIO.setup(buzzer, GPIO.OUT)
# Initialize the BME280 sensor
sensor = bme280.sample(bus, address, calibration_params)
temp = round(sensor.temperature, 2)
hum = round(sensor.humidity, 2)
def MQTT():
my_mqtt = mqtt.Client()
print("\nCreated client object at "+ time.strftime("%H:%M:%S"))
my_mqtt.connect(mqtt_broker, port=1883)
print("--connected to broker")
try:
my_mqtt.publish(topic1, temp)
print("--Temperature: %.2f C" % sensor.temperature)
my_mqtt.publish(topic2, hum)
print("--Humidity: %.2f %%" % sensor.humidity)
except:
print("--publishing error!")
else:
my_mqtt.disconnect()
print("--disconnected from broker")
while True:
MQTT()
#clean up the GPIO pins
GPIO.cleanup()
GPIO.setwarnings(False)
Subscriber/InfluxDB code:订阅者/InfluxDB 代码:
import argparse
from influxdb import InfluxDBClient
from influxdb.client import InfluxDBClientError
import datetime
import time
import paho.mqtt.client as mqtt
PASSWORD = 'root'
USER = 'root'
DBNAME = 'temperature'
HOST = 'localhost'
mqtt_broker ="test.mosquitto.org"
topic ="tp/iotp_project/temperature"
PORT = 8086
dbclient = None;
temp = 0.0;
def onMessage(client, userdata , message):
global temp
time.sleep(2)
temp = float(message.payload.decode())
print(temp)
def startMQTT():
my_mqtt= mqtt.Client()
my_mqtt.on_message =onMessage
my_mqtt.connect(mqtt_broker, port = 1883)
my_mqtt.subscribe(topic)
my_mqtt.loop_start()
def getSensorData():
now = time.gmtime()
pointValues= [
{
"time": time.strftime("%Y-%m-%d %H:%M:%S", now),
"measurement": 'reading',
"tags": {
"nodeId": "node_1",
},
"fields": {
"Temperature": temp
},
}
]
return(pointValues)
def main():
startMQTT()
dbclient = InfluxDBClient(HOST, PORT, USER, PASSWORD, DBNAME)
while True:
data_point = getSensorData()
dbclient.write_points(data_point)
time.sleep(2)
if __name__ == '__main__':
main()
Current output:当前output:
I tried making an if else condition in the def main(): of my subscriber but the result remained the same.我尝试在我的订户的 def main(): 中设置 if else 条件,但结果保持不变。 was suggested by my classmates to remove any time.sleep() from my publisher codes but that still didn't work.
我的同学建议从我的发布者代码中删除任何 time.sleep() ,但仍然没有用。 database entries are still at 0 value
数据库条目仍为 0 值
Attempted if/else def main():尝试 if/else def main():
def main():
startMQTT()
dbclient = InfluxDBClient(HOST, PORT, USER, PASSWORD, DBNAME)
messageReceived = False
while True:
if messageReceived:
data_point1 = getTemperatureData()
data_point2 = getHumidityData()
dbclient.write_points(data_point1)
dbclient.write_points(data_point2)
time.sleep(5)
else:
time.sleep(2)
You should put the sleep back into the publisher (and you should not be creating a new client for each loop).您应该将睡眠放回发布者(并且您不应该为每个循环创建一个新的客户端)。
Your subscriber is failing because you are missing a global temp
from the getSensorData()
function.您的订户失败是因为您缺少来自
getSensorData()
function 的global temp
。
Also remove the time.sleep(2)
from onMessage()
同时从
onMessage()
中删除time.sleep(2)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.