0

Im having a strange issue. I have always connected to a DB at the start, then querried as needed. However for some reason if I have my database connection outside my loop I am not reading in the latest data. If the connection is inside the main loop it works fine. However I dont feel like I should be creating a new connection every query.

In the second section of code you can see the #connect to database. Followed by the connection. I have always kept this outside the While True:

The goal of the code is to read sensor data for the last 5 minutes and average it. My sensors are wireless and on battery so I am checking that I have 4 or 5 points of data to allow it to run the furnace. The sensor updates the database with its values independently of this code every 60 seconds.

The code functions as its written. But eventually I get too many database connection errors. Sorry if my program isnt the cleanest but I am still fairly new to python.

Database Script

import mariadb
import sys
from datetime import datetime, timedelta

    class furnaceDB:
        def __init__(self, db):
            self.conn = mariadb.connect(
                user="pi",
                password="Skylar2305!",
                host="localhost",
                port=3306,
                database=db
            )
            self.cur=self.conn.cursor()
            print("Sucessfully Connect To Database")
    
        def readSensor(self,sensor, datetime):
            sql = ("""SELECT * FROM garage WHERE sensor = %s AND time > %s""")
            data = (sensor,datetime)
            self.cur.execute(sql, data)
            results = self.cur.fetchall()
            return results

        def readSetpoint(self):
            sql = ("SELECT * FROM configuration")
            data = ()
            self.cur.execute(sql, data)
            result = self.cur.fetchall()
            setpoint = result[0][0]
            return setpoint   

Main Script:

shutdownError = False

while True:

    currentTime = datetime.now()
    windowTime = timedelta(minutes = 5)
    checkTime = currentTime - windowTime

    #Connect To Database
    database = furnaceDB("furnace")
    setpoint = database.readSetpoint()
    results = database.readSensor("garage1", checkTime)

    if len(results) == 5 or len(results) == 4: # Make sure we read 4 or 5 datapoints at least 
        tempBuffer = 0.0
        for result in results:
            tempBuffer = result[1] + tempBuffer

        avgTemp = tempBuffer/len(results)
        shutdownError = False
        print(f"Setpoint: {setpoint}  5 Min Temp: {avgTemp}, Read Time {currentTime}")

    else:
        shutdownError = True 
        print(f"Incorrect Amount Of Datapoints Available. Setpoints Read: {len(results)}")

    if shutdownError == False:
        if avgTemp < setpoint:
            print(f"Turning On Furnace")
            client.publish("garage/furnace1/control", "True")

    sleep(60)
2
  • please add a question to your post
    – jsotola
    Commented Jan 31, 2022 at 23:47
  • You need to destroy your furnaceDB object when you're done using it as each new instance will instantiate a new connection to MariaDB until you run out of file handles. Take the database = furnaceDB("furnace") line out of your main while True: loop.
    – Dougie
    Commented Feb 1, 2022 at 17:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.