From 6133b81b05cd69fb10448649baf2606ed6335c43 Mon Sep 17 00:00:00 2001 From: "Maxime Alves LIRMM@home" Date: Sun, 2 Aug 2020 14:58:01 +0200 Subject: [PATCH] [models] update of the model classes --- pyheatpump/models/variable.py | 45 ++++++++++++++++++++++++------ pyheatpump/models/variable_type.py | 1 + 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/pyheatpump/models/variable.py b/pyheatpump/models/variable.py index 39e709b..94b7b6f 100644 --- a/pyheatpump/models/variable.py +++ b/pyheatpump/models/variable.py @@ -13,9 +13,38 @@ class Variable(RowClass): type: VariableType = None def __init__(self, **kwargs): + if 'type' in kwargs.keys() and type(kwargs['type']) != VariableType: + kwargs['type'] = VariableType.get(kwargs['type']) + super().__init__(**kwargs) + def insert(self): + + try: + sql( + """INSERT INTO variable + (type, address) + VALUES + ('{}', {}) + """.format( + self.type, self.address + )) + return True + except Exception as e: + print(e) + return False + + + def exists(self): + try: + return bool(next(sql( + """SELECT 1 FROM variable + WHERE type = '{}' AND address = {} + """.format(self.type, self.address)))) + except StopIteration: + return False + @staticmethod def getall(): return dict([ @@ -29,12 +58,11 @@ class Variable(RowClass): return dict([ (row['address'], Variable(**dict(row))) for row in sql( - """ - SELECT * FROM variable + """SELECT * FROM variable WHERE type = '{}' AND address >= {} - AND address <= {} - """.format(type, type.start_address, type.end_address)) + AND address <= {}""".format( + type, type.start_address, type.end_address)) ]) @@ -43,17 +71,16 @@ class Variable(RowClass): return dict([ (row['address'], row['value']) for row in sql( - """ - SELECT var.address, val.value FROM variable var + """SELECT var.address, val.value FROM variable var LEFT JOIN var_value val ON var.type = val.type AND var.address = val.address - AND var.last_update = var.time + AND var.last_update = val.time WHERE var.type = '{}' AND var.address >= {} - AND var.address <= {} - """.format(type, type.start_address, type.end_address)) + AND var.address <= {}""".format( + type, type.start_address, type.end_address)) ]) diff --git a/pyheatpump/models/variable_type.py b/pyheatpump/models/variable_type.py index 3750c08..754ce79 100644 --- a/pyheatpump/models/variable_type.py +++ b/pyheatpump/models/variable_type.py @@ -56,6 +56,7 @@ class VariableType(RowClass): return Variable.getall_of_type(self) def get_variables_values(self): + from .variable import Variable return Variable.getall_values_of_type(self) @staticmethod