Issue
I have a bme688 sensor (from Pimoroni) connected to a RPI ZERO. I have the PAHO MQTT library so I can send the data to the broker.
If you see code below, in the very last line, I have a "time.sleep(5)". The code below works perfectly well. It takes the readings and sends them via the MQTT. The problem I have is that if I change the time from 5 seconds to 300 seconds (10 minutes), the MQTT does not seem to send the data. The RPI ZERO has the raspbian desktop installed so I ran it using Thonny to see if I get an error but everything works fine with the 300 second delay... but it does not send the data across to the broker.
Any thoughts?
import bme680
import time
import pandas as pd
from datetime import datetime
import csv
import paho.mqtt.client as mqtt
#Set client
mqttBroker = "192.168.86.62"
client = mqtt.Client("the-sensor")
client.connect(mqttBroker)
client.subscribe("sensor/temp")
client.subscribe("sensor/pres")
client.subscribe("sensor/humi")
client.subscribe("sensor/gas")
print("connecting...")
time.sleep(5)
#Set bme688 sensor
sensor = bme680.BME680(0x76)
sensor.set_humidity_oversample(bme680.OS_2X)
sensor.set_pressure_oversample(bme680.OS_4X)
sensor.set_temperature_oversample(bme680.OS_8X)
sensor.set_filter(bme680.FILTER_SIZE_3)
sensor.set_gas_status(bme680.ENABLE_GAS_MEAS)
sensor.set_gas_heater_temperature(320)
sensor.set_gas_heater_duration(150)
sensor.select_gas_heater_profile(0)
while True:
if sensor.get_sensor_data() and sensor.data.heat_stable:
print('getting date, temp, press, humi, gas, fed')
now = datetime.now()
date = now.strftime("%d/%m/%Y %H:%M:%S")
data = [date, sensor.data.temperature, sensor.data.pressure, sensor.data.humidity, sensor.data.gas_resistance]
print(data)
temp = sensor.data.temperature
pres = sensor.data.pressure
humi = sensor.data.humidity
gas = sensor.data.gas_resistance
client.publish("sensor/temp", str(temp))
client.publish("sensor/pres", str(pres))
client.publish("sensor/humi", str(humi))
client.publish("sensor/gas", str(gas))
with open('output.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(data)
csvFile.close()
print("waiting...")
time.sleep(5)
Solution
You are not starting the client network loop or manually calling it.
https://www.eclipse.org/paho/index.php?page=clients/python/docs/index.php#network-loop
You probably want to add client.loop_start()
after client.connect()
Answered By - hardillb