From 50f62d0b6a17677104f0e4d39c5ff7223c5239b2 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Mon, 3 Apr 2023 12:23:40 +0200 Subject: adding function to insert state without defining sql --- scripts/common/__init__.py | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) (limited to 'scripts/common/__init__.py') diff --git a/scripts/common/__init__.py b/scripts/common/__init__.py index 3c3ab1e..d434a4a 100644 --- a/scripts/common/__init__.py +++ b/scripts/common/__init__.py @@ -3,13 +3,45 @@ import os import sys +import logging +from datetime import datetime QUEUE = bool(os.environ.get('el_QUEUE', False)) name = os.path.splitext(os.path.split(sys.argv[0])[-1])[0] -# Initialize queue +log = logging.getLogger(__name__) +log.setLevel(logging.INFO) +logging.basicConfig(format="%(name)s: %(levelname)s %(message)s") + + +# Use queue or postgres if QUEUE is True: + log.debug('Importing dbi from queue') from .queue import dbi else: + log.debug('Importing dbi from postgres') from .postgres import dbi + + +# Insert state +def statein(sensor, value, device_class, unit, **kwargs): + ''' Insert new state in db ''' + verbose = bool(kwargs['verbose']) if 'verbose' in kwargs else False + + sql = """INSERT INTO states + (sensor_id, + value, + device_class, + unit, + time) + SELECT sensors.id, %s, %s, %s, %s + FROM sensors + WHERE sensors.name = %s;""" + values = (value, + device_class, + unit, + datetime.now(), + sensor) + log.debug('dbi(' + sql + ',' + str(values) + ')') + dbi(sql, values, verbose=verbose) -- cgit v1.2.3