Smarthome Functionen
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

db.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import sqlite3
  3. db_file = os.path.join(os.path.dirname(__file__), '..', 'database.db')
  4. def get_radiator_data(topic):
  5. return __storage__().get_radiator_data(topic)
  6. def set_radiator_data(topic, away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint):
  7. return __storage__().store_radiator_data(topic, away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint)
  8. class __storage__(object):
  9. def __init__(self):
  10. self.conn = sqlite3.connect(db_file)
  11. self.c = self.conn.cursor()
  12. with self.conn:
  13. self.c.execute("""CREATE TABLE IF NOT EXISTS radiator (
  14. topic text PRIMARY KEY,
  15. away_mode integer,
  16. summer_mode integer,
  17. user_temperatur_setpoint real,
  18. temperatur_setpoint real
  19. )""")
  20. def store_radiator_data(self, topic, away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint):
  21. data = [topic, away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint]
  22. try:
  23. with self.conn:
  24. self.c.execute(
  25. 'INSERT INTO radiator VALUES (?, ?, ?, ?, ?)', data)
  26. except sqlite3.IntegrityError:
  27. data = [away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint]
  28. db_data = self.get_radiator_data(topic)
  29. if db_data != data:
  30. with self.conn:
  31. self.c.execute(
  32. 'UPDATE radiator SET away_mode = ?, summer_mode = ?, user_temperatur_setpoint = ?, temperatur_setpoint = ? WHERE topic = ?', data + [topic])
  33. def get_radiator_data(self, topic):
  34. """ returns a list [away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint] or [None, None, None, None]"""
  35. self.c.execute("SELECT * FROM radiator WHERE topic=?", (topic, ))
  36. data = self.c.fetchone()
  37. if data is not None:
  38. data = list(data)
  39. data[1] = data[1] == 1
  40. data[2] = data[2] == 1
  41. return data[1:]
  42. else:
  43. return [None, None, None, None]
  44. def __del__(self):
  45. self.conn.close()