-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger.py
204 lines (171 loc) · 6.28 KB
/
logger.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import requests
import logging
import sqlite3 as sql
import pandas as pd
from datetime import datetime, timedelta
from config import DB_PATH, GAS_ENABLED
logging.basicConfig(
format='%(name)s: %(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S',
)
class YoulessBaseLogger:
GRANULARITY_MAP = {
'minute': {'param': 'h', 'reports': 20},
'hour': {'param': 'd', 'reports': 70},
'day': {'param': 'm', 'reports': 12},
}
con = None
cur = None
report_param = None
report_pages = None
table_name = None
chart_data = pd.DataFrame()
endpoint = 'http://youless/'
default_params = {'f': 'j'} # JSON response format,
def __init__(self):
self.report_param = self.GRANULARITY_MAP[self.granularity]['param']
self.report_pages = self.GRANULARITY_MAP[self.granularity]['reports']
self.logger = logging.getLogger(
'Youless Scraper {}'.format(self.__class__.__name__)
)
@property
def youless_path(self) -> str:
raise NotImplementedError(
'youless_path attribute needs to be implemented in deriving class'
)
@property
def table_name(self) -> str:
raise NotImplementedError(
'table_name attribute needs to be implemented in deriving class'
)
@property
def granularity(self) -> str:
raise NotImplementedError(
'granularity attribute needs to be implemented in deriving class'
)
@property
def endpoint(self) -> str:
return f'http://youless/{self.youless_path}'
def fetch_data(self):
self.logger.info('Fetching new data for {} reports'.format(self.report_pages))
res = []
for page in range(self.report_pages):
data = requests.get(
self.endpoint,
params={**self.default_params, self.report_param: page + 1},
)
res += YoulessBaseLogger.convert_data(data.json())
self.logger.info('Received {} entries'.format(len(res)))
self.store_data(pd.DataFrame(res))
@staticmethod
def convert_data(data: dict) -> list:
res = []
time_format = '%Y-%m-%dT%H:%M:%S'
timestamp = datetime.strptime(data['tm'], time_format)
for val in data['val']:
if val and val != '*':
res.append(
{
'time': timestamp,
'energy_consumption': float(val.replace(',', '.')),
'unit': data['un'],
}
)
timestamp += timedelta(seconds=data['dt'])
return res
def table_exists(self) -> bool:
query = '''
SELECT name
FROM sqlite_master
WHERE
type='table'
AND name='{table_name}';
'''
with sql.connect(DB_PATH) as con:
cur = con.cursor()
listOfTables = cur.execute(
query.format(table_name=self.table_name)
).fetchall()
return len(listOfTables) > 0
def store_data(self, df):
if df.empty:
self.logger.info('No data to be stored')
return
with sql.connect(DB_PATH) as con:
if not self.table_exists():
self.logger.warning(
f'Table {self.table_name} does not exist. Creating...'
)
# Just upload all data and create the table
df.to_sql(self.table_name, con, index=False)
value_count = len(df)
else:
# Store to temporary db
df.to_sql('tmp', con, if_exists='replace', index=False)
# Update existing data
query = '''
UPDATE {table_name} AS old
SET energy_consumption = (
SELECT energy_consumption
FROM tmp
WHERE time = old.time
LIMIT 1
)
WHERE EXISTS (
SELECT energy_consumption
FROM tmp
WHERE time = old.time
)
'''
cur = con.cursor()
cur.execute(query.format(table_name=self.table_name))
con.commit()
self.logger.info('Updated {} old values'.format(cur.rowcount))
# Store new data
query = '''
INSERT INTO {table_name} (time, energy_consumption, unit)
SELECT time, energy_consumption, unit
FROM tmp AS new
WHERE NOT EXISTS (
SELECT 1 FROM {table_name} old
WHERE old.time = new.time
);
'''
cur = con.cursor()
cur.execute(query.format(table_name=self.table_name))
con.commit()
value_count = cur.rowcount
self.logger.info('Uploaded {} new values'.format(value_count))
class YoulessEnergyMinute(YoulessBaseLogger):
youless_path = 'V'
table_name = 'youless_minute'
granularity = 'minute'
class YoulessEnergyHour(YoulessBaseLogger):
youless_path = 'V'
table_name = 'youless_hour'
granularity = 'hour'
class YoulessEnergyDay(YoulessBaseLogger):
youless_path = 'V'
table_name = 'youless_day'
granularity = 'day'
class YoulessGasHour(YoulessBaseLogger):
youless_path = 'W'
table_name = 'youless_hour_gas'
granularity = 'hour'
class YoulessGasDay(YoulessBaseLogger):
youless_path = 'W'
table_name = 'youless_day_gas'
granularity = 'day'
if __name__ == '__main__':
energy_minute_scraper = YoulessEnergyMinute()
energy_minute_scraper.fetch_data()
energy_hour_scraper = YoulessEnergyHour()
energy_hour_scraper.fetch_data()
energy_day_scraper = YoulessEnergyDay()
energy_day_scraper.fetch_data()
if GAS_ENABLED:
gas_hour_scraper = YoulessGasHour()
gas_hour_scraper.fetch_data()
gas_day_scraper = YoulessGasDay()
gas_day_scraper.fetch_data()