import os import sqlite3 db_file = os.path.join(os.path.dirname(__file__), '..', 'database.db') def get_radiator_data(topic): return __storage__().get_radiator_data(topic) def set_radiator_data(topic, away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint): return __storage__().store_radiator_data(topic, away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint) class __storage__(object): def __init__(self): self.conn = sqlite3.connect(db_file) self.c = self.conn.cursor() with self.conn: self.c.execute("""CREATE TABLE IF NOT EXISTS radiator ( topic text PRIMARY KEY, away_mode integer, summer_mode integer, user_temperatur_setpoint real, temperatur_setpoint real )""") def store_radiator_data(self, topic, away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint): data = [topic, away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint] try: with self.conn: self.c.execute( 'INSERT INTO radiator VALUES (?, ?, ?, ?, ?)', data) except sqlite3.IntegrityError: data = [away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint] db_data = self.get_radiator_data(topic) if db_data != data: with self.conn: self.c.execute( 'UPDATE radiator SET away_mode = ?, summer_mode = ?, user_temperatur_setpoint = ?, temperatur_setpoint = ? WHERE topic = ?', data + [topic]) def get_radiator_data(self, topic): """ returns a list [away_mode, summer_mode, user_temperatur_setpoint, temperatur_setpoint] or [None, None, None, None]""" self.c.execute("SELECT * FROM radiator WHERE topic=?", (topic, )) data = self.c.fetchone() if data is not None: data = list(data) data[1] = data[1] == 1 data[2] = data[2] == 1 return data[1:] else: return [None, None, None, None] def __del__(self): self.conn.close()