Files
Pond-Level-Sensor/python_driver/calibration_db.py
Patrick McDonagh 9e18117778 Completes MAXH2O-51.
Allows input of tank strapping table
2017-12-01 17:57:19 -06:00

80 lines
2.6 KiB
Python

"""Test database functions for storing configuration data."""
import sqlite3
SQLITE_DB = "cal_data.db"
SQLITE_CONN = sqlite3.connect(SQLITE_DB, check_same_thread=False)
def setup_calibration_table(drop_first=False):
"""Setup the calibration table."""
cursor = SQLITE_CONN.cursor()
if drop_first:
cursor.execute("DROP TABLE IF EXISTS cal_data")
create_query = ("CREATE TABLE IF NOT EXISTS cal_data ("
"id integer PRIMARY KEY, "
"height float, "
"volume float)")
cursor.execute(create_query)
def insert_calibration_data(height, volume):
"""Insert an entry into the calibration table."""
cursor = SQLITE_CONN.cursor()
insert_query = "INSERT INTO cal_data (height, volume) VALUES (?, ?)"
cursor.execute(insert_query, [height, volume])
return cursor.lastrowid
def delete_calibration_data(id):
"""Delete an entry from the calibration table."""
cursor = SQLITE_CONN.cursor()
delete_query = "DELETE FROM cal_data WHERE id = ?"
cursor.execute(delete_query, [id])
return cursor.rowcount
def get_calibration_data(single_entry=False):
"""Retrieve either a single entry or all calibration data."""
single_entry = int(single_entry)
cursor = SQLITE_CONN.cursor()
get_single_query = "SELECT * FROM cal_data WHERE id = ?"
get_all_query = "SELECT * FROM cal_data ORDER BY height ASC"
if(single_entry > 0):
cursor.execute(get_single_query, [single_entry])
return cursor.fetchone()
else:
return [list(row) for row in cursor.execute(get_all_query)]
def get_volume_for_height(height):
"""Interpret a volume for a given height."""
calibration_data = get_calibration_data()
print("Calibration Data\n===")
print(calibration_data)
cal_min_height = calibration_data[0][1]
cal_max_height = calibration_data[-1][1]
lower_cal = [0.0, 0.0]
upper_cal = [0.0, 0.0]
if (height <= cal_max_height and height >= cal_min_height):
for i in range(0, len(calibration_data) - 1):
if (height >= calibration_data[i][1] and height <= calibration_data[i+1][1]):
lower_cal = calibration_data[i][1:3]
upper_cal = calibration_data[i+1][1:3]
elif height > cal_max_height:
lower_cal = calibration_data[-2][1:3]
upper_cal = calibration_data[-1][1:3]
elif height < cal_min_height:
lower_cal = calibration_data[0][1:3]
upper_cal = calibration_data[1][1:3]
line_m = (upper_cal[1] - lower_cal[1]) / (upper_cal[0] - lower_cal[0])
line_b = upper_cal[1] - line_m * upper_cal[0]
return line_m * height + line_b