repository to manage all files related to the makeathon farm bot project (Software + Documentation).
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

plantdatabase.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. # file to create a database via python script
  2. import sqlite3
  3. from typing import Optional
  4. class PlantDataBase:
  5. """
  6. Class to create Makeathon database
  7. """
  8. def __init__(self, database_name: str):
  9. self.db_file = database_name # 'backend_database.db'
  10. self.conn = None
  11. try:
  12. self.conn = sqlite3.connect(self.db_file, check_same_thread=False)
  13. print(sqlite3.version)
  14. except sqlite3.Error as e:
  15. print(e)
  16. self.cur = self.conn.cursor()
  17. def create_tables(self):
  18. try:
  19. table_config = "CREATE TABLE IF NOT EXISTS plants " \
  20. "(PlantID INTEGER PRIMARY KEY," \
  21. "PlantName TEXT)"
  22. self.cur.execute(table_config)
  23. table_config = "CREATE TABLE IF NOT EXISTS measurement_values " \
  24. "(measurementID INTEGER PRIMARY KEY," \
  25. "Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP," \
  26. "PlantID INTEGER, " \
  27. "AirTemperature REAL," \
  28. "AirHumidity REAL," \
  29. "SoilMoisture REAL," \
  30. "Brightness REAL," \
  31. "FOREIGN KEY (PlantID)" \
  32. "REFERENCES plants (PlantID) )"
  33. self.cur.execute(table_config)
  34. return True
  35. except sqlite3.Warning as e:
  36. return e
  37. def insert_plant(self, plantname: str, plant_id: int):
  38. try:
  39. self.cur.execute("INSERT INTO plants (PlantName, PlantID) VALUES (?,?)", (plantname, plant_id))
  40. self.conn.commit()
  41. return True
  42. except (sqlite3.NotSupportedError, sqlite3.Warning) as e:
  43. return e
  44. def configure_plant(self, plant_id: int, plantname: str):
  45. try:
  46. self.cur.execute("UPDATE plants SET PlantID = ?, PlantName = ? WHERE PlantID= ?",
  47. (plant_id, plantname, plant_id))
  48. self.conn.commit()
  49. return True
  50. except (sqlite3.NotSupportedError, sqlite3.Warning) as e:
  51. return e
  52. def delete_plant(self, plant_id):
  53. try:
  54. self.cur.execute('DELETE FROM plants WHERE PlantID = ?', (plant_id,))
  55. self.conn.commit()
  56. return True
  57. except (sqlite3.NotSupportedError, sqlite3.Warning) as e:
  58. return e
  59. def insert_measurement_data(self, plant_id,
  60. sensordata_temp,
  61. sensordata_humidity,
  62. sensordata_soil_moisture,
  63. sensordata_brightness) -> bool:
  64. try:
  65. self.cur.execute(f"INSERT INTO measurement_values (PlantID, AirTemperature, AirHumidity,"
  66. f"SoilMoisture, Brightness) VALUES "
  67. f"({plant_id}, {sensordata_temp}, {sensordata_humidity}, {sensordata_soil_moisture}"
  68. f", {sensordata_brightness})")
  69. self.conn.commit()
  70. return True
  71. except (sqlite3.NotSupportedError, sqlite3.Warning) as e:
  72. return e
  73. def get_latest_data(self, plant_name: Optional[str] = None, plant_id: Optional[int] = None):
  74. """
  75. Gets the newest parameter of specific plant and returns all parameters in json format
  76. :param plant_id:
  77. :param plant_name:
  78. :return:
  79. """
  80. try:
  81. if plant_name is not None and plant_id is None:
  82. self.cur.execute("SELECT PlantID FROM plants where PlantName = ?", (plant_name,))
  83. plant_id = self.cur.fetchone()[0]
  84. elif (plant_id is not None and plant_name is not None) or (plant_id is None and plant_name is None):
  85. raise TypeError("Can't pass plant_id and plant_name to the function. Just one allowed !")
  86. self.cur.execute("SELECT * FROM measurement_values where PlantID = ? ORDER BY Timestamp DESC LIMIT 1",
  87. (plant_id,))
  88. data = self.cur.fetchone()
  89. json_file = {
  90. "MeasurementID": data[0],
  91. "PlantID": data[2],
  92. "Timestamp": data[1],
  93. "AirTemperature": data[3],
  94. "AirHumidity": data[4],
  95. "SoilMoisture": data[5],
  96. "Brightness": data[6],
  97. "PlantName": plant_name
  98. }
  99. return json_file
  100. except (sqlite3.Warning, TypeError) as e:
  101. return e
  102. def delete_data(self, table_name):
  103. self.cur.execute(f'DELETE FROM {table_name}')
  104. self.conn.commit()
  105. return True
  106. # TODO: Kemals Scheiß implementieren
  107. def plant_count(self) -> int:
  108. """
  109. returns the number of plants registered in the database
  110. :return:
  111. """
  112. self.cur.execute("SELECT COUNT(*) FROM plants")
  113. return self.cur.fetchone()[0]
  114. def __del__(self):
  115. self.conn.close()