hotplot / enviroplus-mqtt

A Python service for logging environmental data over MQTT
MIT License
31 stars 20 forks source link

Compensated temperature #9

Closed Aygotori closed 4 years ago

Aygotori commented 4 years ago

Hello!

Thx for this great script! Is there a way to have a temperature compensation as in: 'https://github.com/pimoroni/enviroplus-python/blob/master/examples/compensated-temperature.py' ?

sl-ux commented 4 years ago

Hello Aygotori,

I was looking into this myself and have managed to make it work with modifications to the logger.py, I'm not the most experienced in Python but I hope it helps, it includes averaging the CPU temp for less jitter:

Edit the logger.py by running sudo nano /usr/src/enviroplus-mqtt/src/logger.py

Add the following line within def __init__() (under self.latest_pms+readings is where I put this) and adjust to suit your compensation: self.comp_factor = 2.25 - Adjust the 2.25 to suit your compensation.

Add the following inside the EnvLogger class:

# Get the temperature of the CPU for compensation
    def get_cpu_temperature(self):
        with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
            self.temp = f.read()
            self.temp = int(self.temp) / 1000.0
        return self.temp

Finally add the below within def take_readings() I added before the gas_data = gas.read_all() for reference:

        cpu_temps = [self.get_cpu_temperature()] * 5
        cpu_temp = self.get_cpu_temperature()
        # Smooth out with some averaging to decrease jitter
        cpu_temps = cpu_temps[1:] + [cpu_temp]
        avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps))
        raw_temp = self.bme280.get_temperature()
        comp_temp = raw_temp - ((avg_cpu_temp - raw_temp) / self.comp_factor)

In my example I have both readings so within the def take_readings() inside the readings I added a new line for compensated temperature (above the existing temperature):

"compensated_temperature": comp_temp,
"temperature": self.bme280.get_temperature(),

This is just my own take and I'm sure there are cleaner ways but this works for my setup.

Aygotori commented 4 years ago

Hello sl-ux ! Thx a lot for your reply, it works like a charm! =)