I am publishing some data from a bme280 sensor to a mosquitto broker. I want do this every 3 seconds.
The readings from sensor are always ok but the publish to mosquitto very often loose some message. I can check this with a external MQTT subscrive client.
Where is the error? Here my code,It was assembled from some examples so sorry for non very good code.... Thanks.
#!/usr/bin/python3
import smbus2
import bme280
from paho.mqtt import client as mqttClient
import random
import time
lst2 = [None] * 2
lst2[0] = 'Temperatura stanzino'
lst2[1] = 'Umidita stanzino'
parolatot2 = [None] * 2
def on_connect(client, userdata, flags, rc):
if rc == 0:
pass
global Connected
Connected = True
else:
pass
Connected = False
broker_address= "192.168.1.250"
port = 1883
user = "xxx"
password = "xxx"
topic = "python/mqtt/"
client = mqttClient.Client("Python")
client.username_pw_set(user, password=password)
client.on_connect= on_connect
client.connect(broker_address, port=port)
client.loop_start()
while Connected != True:
time.sleep(0.1)
def calcoloTotale():
msg2_count = 0
port = 1
address = 0x76
bus = smbus2.SMBus(port)
calibration_params = bme280.load_calibration_params(bus, address)
data = bme280.sample(bus, address, calibration_params)
parolatot2[0] = round(data.temperature,1)
parolatot2[1] = round(data.humidity,1)
print (parolatot2)
while msg2_count < 2:
topicnew2 = topic + lst2[msg2_count]
time.sleep(.001)
msg2 = f"{parolatot2[msg2_count]}"
client.publish(topicnew2, msg2)
msg2_count += 1
try:
while True:
calcoloTotale()
time.sleep(3.0)
except:
print ("errore")
client.disconnect()
client.loop_stop()
The client.publish
method never throws an error. If you want to make sure that the message has really been published (and/or understand why not), I would recommend the following:
message_info = client.publish(topic, message, qos=1)
message_info.wait_for_publish(timeout=2) # will throw error if message isn't published within timeout.
Notes:
qos=1
: use at least qos 1 if you want to make sure your message got published at least once. wait_for_publish
method.Thanks my friend,i have changed approach to this.I'm using now "publish.single" istruction.So my code was reduced a lot. Now just a single shot to public and no more loose message. I have used this:
import paho.mqtt.publish as publish
publish.single(topicnew2, msg2, qos=1, retain=False, hostname="192.168.1.250", auth={'username':" ", 'password':" "})
But now another issue,the qos is always 0 in the client.Some idea? Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.