This repository has been archived by the owner on Jan 15, 2024. It is now read-only.
/
pulsesToDB.py
executable file
·58 lines (43 loc) · 1.96 KB
/
pulsesToDB.py
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
#!/usr/bin/env python3
"""
Consume pulses and store counter to db.
"""
import pika, rabbitUtils, dateutil.parser, json
import sqlite3 as lite
#Global db connection
global con
def pulse_callback(ch, method, properties, body):
print("Pulse received: {}".format(body))
store_pulse_to_db(body)
def store_pulse_to_db(body):
data = json.loads(body.decode("utf-8"))
date_time = dateutil.parser.parse(data['time'])
day_string = "{:%Y-%m-%d}".format(date_time)
minute_string = "{:%Y-%m-%d %H:%M}".format(date_time)
print(minute_string)
cur = con.cursor()
cur.execute("INSERT OR IGNORE INTO counters_day (date, cnt) VALUES (\'{}\',0);".format(day_string))
cur.execute("INSERT OR IGNORE INTO counters_minute (date, cnt) VALUES (\'{}\',0);".format(minute_string))
cur.execute('UPDATE counters_day set cnt = cnt +1 where date LIKE \'{}\';'.format(day_string))
cur.execute("UPDATE counters_minute set cnt = cnt +1 where date LIKE \'{}\';".format(minute_string))
def init_lite():
'''Init sqlite3 db'''
global con
con = None
try:
con = lite.connect("{}.sqlite".format(__file__[:-3]), isolation_level=None)
cur = con.cursor()
cur.execute("CREATE TABLE if not exists currentpow (id INTEGER PRIMARY KEY, value FLOAT);")
cur.execute("CREATE TABLE if not exists counters_day (`date` date NOT NULL, `cnt` int NOT NULL, PRIMARY KEY (`date`));")
cur.execute("CREATE TABLE if not exists counters_minute (`date` date NOT NULL, `cnt` int NOT NULL, PRIMARY KEY (`date`));")
cur.execute("INSERT OR IGNORE into currentpow (id, value) values (1, 0.0);")
except lite.Error as e:
print("Error %{}:".format(e.args[0]))
sys.exit(1)
return con
def main():
con = init_lite()
channel = rabbitUtils.init_rabbit_w_pulse_callback(pulse_callback)
#Blocking call, will wait for callbacks.
channel.start_consuming()
main()