diff --git a/endpoint.py b/endpoint.py index ccceab2..cda168b 100644 --- a/endpoint.py +++ b/endpoint.py @@ -5,11 +5,9 @@ from datetime import datetime, timedelta from threading import Thread import journal - # SUPPORTED_REGISTER_TYPES = ['D', 'M'] SUPPORTED_REGISTER_TYPES = ['D'] - LOG_TYPE_ON_SCAN = 'on-scan' LOG_TYPE_ON_CHANGE = 'on-change' @@ -109,7 +107,6 @@ class Endpoint(Thread): self.ranges = parse_ranges(config) # база данных - self.connection = None self.db_table = config['database']['db-table'] self.db_col_names = '' for rn in self.ranges: @@ -134,14 +131,21 @@ class Endpoint(Thread): return values def __read_last_db_regs(self): - with self.connection.cursor() as cursor: - cursor.execute(f"select {self.db_col_names} from `{self.db_table}`" - f"order by `{self.config['database']['db-datetime-col']}` desc limit 1;") - row = cursor.fetchall() - if len(row) != 0: - return row[0] - else: - return None + with connect( + host=self.config["database"]["host"], + port=self.config["database"]["port"], + user=self.config["database"]["db-user"], + password=self.config["database"]["db-password"], + database=self.config["database"]["db-name"], + ) as connection: + with connection.cursor() as cursor: + cursor.execute(f"select {self.db_col_names} from `{self.db_table}`" + f"order by `{self.config['database']['db-datetime-col']}` desc limit 1;") + row = cursor.fetchall() + if len(row) != 0: + return row[0] + else: + return None def __insert_db_row(self, values): vals_str = "" @@ -151,10 +155,17 @@ class Endpoint(Thread): else: vals_str += f"{v}" - query = f"insert into `{self.db_table}` ({self.db_col_names}) values ({vals_str});" - journal.log(f"Executing query: {query}") - with self.connection.cursor() as cursor: - cursor.execute(query) + with connect( + host=self.config["database"]["host"], + port=self.config["database"]["port"], + user=self.config["database"]["db-user"], + password=self.config["database"]["db-password"], + database=self.config["database"]["db-name"] + ) as connection: + query = f"insert into `{self.db_table}` ({self.db_col_names}) values ({vals_str});" + journal.log(f"Executing query: {query}") + with connection.cursor() as cursor: + cursor.execute(query) def __endless_loop(self): # if self.log_type == 'on-change': @@ -174,6 +185,7 @@ class Endpoint(Thread): while True: try: row = self.__mb_read_all_regs() + if self.log_type == LOG_TYPE_ON_SCAN: self.__insert_db_row(row) last_row = row @@ -210,15 +222,6 @@ class Endpoint(Thread): port=self.config["modbus"]["port"], debug=self.config["modbus"]["debug"], auto_open=True) - with connect( - host=self.config["database"]["host"], - port=self.config["database"]["port"], - user=self.config["database"]["db-user"], - password=self.config["database"]["db-password"], - database=self.config["database"]["db-name"] - ) as _connection: - self.connection = _connection - - # запуск бесконечного цикла - self.__endless_loop() + # запуск бесконечного цикла + self.__endless_loop()