1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#!/usr/bin/env python3
""" common functions and stuff """
import logging
import os
import sys
from datetime import datetime
# Get env var
def env(var_name, default=None):
value = os.getenv(var_name)
if value is not None:
return value
if default is not None:
return default
print(f"Error: Could not find environment variable '{var_name}'")
print("That variable is required for running this program.")
sys.exit(1)
QUEUE = bool(env("el_QUEUE", False))
name = os.path.splitext(os.path.split(sys.argv[0])[-1])[0]
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.utcnow(), sensor)
log.debug("dbi(" + sql + "," + str(values) + ")")
dbi(sql, values, verbose=verbose)
|