1
|
|
|
import re |
2
|
|
|
|
3
|
|
|
import falcon |
4
|
|
|
import simplejson as json |
5
|
|
|
import mysql.connector |
6
|
|
|
import config |
7
|
|
|
from datetime import datetime, timedelta, timezone |
8
|
|
|
from core import utilities |
9
|
|
|
import excelexporters.metertrend |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
class Reporting: |
13
|
|
|
@staticmethod |
14
|
|
|
def __init__(): |
15
|
|
|
""""Initializes Reporting""" |
16
|
|
|
pass |
17
|
|
|
|
18
|
|
|
@staticmethod |
19
|
|
|
def on_options(req, resp): |
20
|
|
|
resp.status = falcon.HTTP_200 |
21
|
|
|
|
22
|
|
|
#################################################################################################################### |
23
|
|
|
# PROCEDURES |
24
|
|
|
# Step 1: valid parameters |
25
|
|
|
# Step 2: query the meter and energy category |
26
|
|
|
# Step 3: query associated points |
27
|
|
|
# Step 4: query reporting period points trends |
28
|
|
|
# Step 5: query tariff data |
29
|
|
|
# Step 6: construct the report |
30
|
|
|
#################################################################################################################### |
31
|
|
|
@staticmethod |
32
|
|
|
def on_get(req, resp): |
33
|
|
|
print(req.params) |
34
|
|
|
meter_id = req.params.get('meterid') |
35
|
|
|
meter_uuid = req.params.get('meteruuid') |
36
|
|
|
reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
37
|
|
|
reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') |
38
|
|
|
quick_mode = req.params.get('quickmode') |
39
|
|
|
|
40
|
|
|
################################################################################################################ |
41
|
|
|
# Step 1: valid parameters |
42
|
|
|
################################################################################################################ |
43
|
|
|
if meter_id is None and meter_uuid is None: |
44
|
|
|
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID') |
45
|
|
|
|
46
|
|
|
if meter_id is not None: |
47
|
|
|
meter_id = str.strip(meter_id) |
48
|
|
|
if not meter_id.isdigit() or int(meter_id) <= 0: |
49
|
|
|
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID') |
50
|
|
|
|
51
|
|
|
if meter_uuid is not None: |
52
|
|
|
meter_uuid = str.strip(meter_uuid) |
53
|
|
|
regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) |
54
|
|
|
match = regex.match(meter_uuid) |
55
|
|
|
if not bool(match): |
56
|
|
|
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_UUID') |
57
|
|
|
|
58
|
|
|
timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
59
|
|
|
if config.utc_offset[0] == '-': |
60
|
|
|
timezone_offset = -timezone_offset |
61
|
|
|
|
62
|
|
|
if reporting_period_start_datetime_local is None: |
63
|
|
|
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
64
|
|
|
description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
65
|
|
|
else: |
66
|
|
|
reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
67
|
|
|
try: |
68
|
|
|
reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
69
|
|
|
'%Y-%m-%dT%H:%M:%S') |
70
|
|
|
except ValueError: |
71
|
|
|
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
72
|
|
|
description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
73
|
|
|
reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
74
|
|
|
timedelta(minutes=timezone_offset) |
75
|
|
|
|
76
|
|
|
if reporting_period_end_datetime_local is None: |
77
|
|
|
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
78
|
|
|
description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
79
|
|
|
else: |
80
|
|
|
reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
81
|
|
|
try: |
82
|
|
|
reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
83
|
|
|
'%Y-%m-%dT%H:%M:%S') |
84
|
|
|
except ValueError: |
85
|
|
|
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
86
|
|
|
description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
87
|
|
|
reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
88
|
|
|
timedelta(minutes=timezone_offset) |
89
|
|
|
|
90
|
|
|
if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
91
|
|
|
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
92
|
|
|
description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
93
|
|
|
|
94
|
|
|
# if turn quick mode on, do not return parameters data and excel file |
95
|
|
|
is_quick_mode = False |
96
|
|
|
if quick_mode is not None and \ |
97
|
|
|
len(str.strip(quick_mode)) > 0 and \ |
98
|
|
|
str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
99
|
|
|
is_quick_mode = True |
100
|
|
|
|
101
|
|
|
################################################################################################################ |
102
|
|
|
# Step 2: query the meter and energy category |
103
|
|
|
################################################################################################################ |
104
|
|
|
cnx_system = mysql.connector.connect(**config.myems_system_db) |
105
|
|
|
cursor_system = cnx_system.cursor() |
106
|
|
|
|
107
|
|
|
cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
108
|
|
|
cursor_historical = cnx_historical.cursor() |
109
|
|
|
if meter_id is not None: |
110
|
|
|
cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
111
|
|
|
" ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
112
|
|
|
" FROM tbl_meters m, tbl_energy_categories ec " |
113
|
|
|
" WHERE m.id = %s AND m.energy_category_id = ec.id ", (meter_id,)) |
114
|
|
|
row_meter = cursor_system.fetchone() |
115
|
|
|
elif meter_uuid is not None: |
116
|
|
|
cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
117
|
|
|
" ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
118
|
|
|
" FROM tbl_meters m, tbl_energy_categories ec " |
119
|
|
|
" WHERE m.uuid = %s AND m.energy_category_id = ec.id ", (meter_uuid,)) |
120
|
|
|
row_meter = cursor_system.fetchone() |
121
|
|
|
if row_meter is None: |
|
|
|
|
122
|
|
|
if cursor_system: |
123
|
|
|
cursor_system.close() |
124
|
|
|
if cnx_system: |
125
|
|
|
cnx_system.disconnect() |
126
|
|
|
|
127
|
|
|
if cursor_historical: |
128
|
|
|
cursor_historical.close() |
129
|
|
|
if cnx_historical: |
130
|
|
|
cnx_historical.disconnect() |
131
|
|
|
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND') |
132
|
|
|
if meter_id is not None and int(meter_id) != int(row_meter[0]): |
133
|
|
|
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND') |
134
|
|
|
meter = dict() |
135
|
|
|
meter['id'] = row_meter[0] |
136
|
|
|
meter['name'] = row_meter[1] |
137
|
|
|
meter['cost_center_id'] = row_meter[2] |
138
|
|
|
meter['energy_category_id'] = row_meter[3] |
139
|
|
|
meter['energy_category_name'] = row_meter[4] |
140
|
|
|
meter['unit_of_measure'] = row_meter[5] |
141
|
|
|
meter['kgce'] = row_meter[6] |
142
|
|
|
meter['kgco2e'] = row_meter[7] |
143
|
|
|
|
144
|
|
|
################################################################################################################ |
145
|
|
|
# Step 3: query associated points |
146
|
|
|
################################################################################################################ |
147
|
|
|
point_list = list() |
148
|
|
|
cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
149
|
|
|
" FROM tbl_meters m, tbl_meters_points mp, tbl_points p " |
150
|
|
|
" WHERE m.id = %s AND m.id = mp.meter_id AND mp.point_id = p.id " |
151
|
|
|
" ORDER BY p.id ", (meter['id'],)) |
152
|
|
|
rows_points = cursor_system.fetchall() |
153
|
|
|
if rows_points is not None and len(rows_points) > 0: |
154
|
|
|
for row in rows_points: |
155
|
|
|
point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
156
|
|
|
|
157
|
|
|
################################################################################################################ |
158
|
|
|
# Step 4: query reporting period points trends |
159
|
|
|
################################################################################################################ |
160
|
|
|
reporting = dict() |
161
|
|
|
reporting['names'] = list() |
162
|
|
|
reporting['timestamps'] = list() |
163
|
|
|
reporting['values'] = list() |
164
|
|
|
|
165
|
|
|
for point in point_list: |
166
|
|
|
if is_quick_mode and point['object_type'] != 'ENERGY_VALUE': |
167
|
|
|
continue |
168
|
|
|
|
169
|
|
|
point_values = [] |
170
|
|
|
point_timestamps = [] |
171
|
|
|
if point['object_type'] == 'ANALOG_VALUE': |
172
|
|
|
query = (" SELECT utc_date_time, actual_value " |
173
|
|
|
" FROM tbl_analog_value " |
174
|
|
|
" WHERE point_id = %s " |
175
|
|
|
" AND utc_date_time BETWEEN %s AND %s " |
176
|
|
|
" ORDER BY utc_date_time ") |
177
|
|
|
cursor_historical.execute(query, (point['id'], |
178
|
|
|
reporting_start_datetime_utc, |
179
|
|
|
reporting_end_datetime_utc)) |
180
|
|
|
rows = cursor_historical.fetchall() |
181
|
|
|
|
182
|
|
|
if rows is not None and len(rows) > 0: |
183
|
|
|
for row in rows: |
184
|
|
|
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
185
|
|
|
timedelta(minutes=timezone_offset) |
186
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
187
|
|
|
point_timestamps.append(current_datetime) |
188
|
|
|
point_values.append(row[1]) |
189
|
|
|
|
190
|
|
|
elif point['object_type'] == 'ENERGY_VALUE': |
191
|
|
|
query = (" SELECT utc_date_time, actual_value " |
192
|
|
|
" FROM tbl_energy_value " |
193
|
|
|
" WHERE point_id = %s " |
194
|
|
|
" AND utc_date_time BETWEEN %s AND %s " |
195
|
|
|
" ORDER BY utc_date_time ") |
196
|
|
|
cursor_historical.execute(query, (point['id'], |
197
|
|
|
reporting_start_datetime_utc, |
198
|
|
|
reporting_end_datetime_utc)) |
199
|
|
|
rows = cursor_historical.fetchall() |
200
|
|
|
|
201
|
|
|
if rows is not None and len(rows) > 0: |
202
|
|
|
for row in rows: |
203
|
|
|
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
204
|
|
|
timedelta(minutes=timezone_offset) |
205
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
206
|
|
|
point_timestamps.append(current_datetime) |
207
|
|
|
point_values.append(row[1]) |
208
|
|
|
elif point['object_type'] == 'DIGITAL_VALUE': |
209
|
|
|
query = (" SELECT utc_date_time, actual_value " |
210
|
|
|
" FROM tbl_digital_value " |
211
|
|
|
" WHERE point_id = %s " |
212
|
|
|
" AND utc_date_time BETWEEN %s AND %s " |
213
|
|
|
" ORDER BY utc_date_time ") |
214
|
|
|
cursor_historical.execute(query, (point['id'], |
215
|
|
|
reporting_start_datetime_utc, |
216
|
|
|
reporting_end_datetime_utc)) |
217
|
|
|
rows = cursor_historical.fetchall() |
218
|
|
|
|
219
|
|
|
if rows is not None and len(rows) > 0: |
220
|
|
|
for row in rows: |
221
|
|
|
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
222
|
|
|
timedelta(minutes=timezone_offset) |
223
|
|
|
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
224
|
|
|
point_timestamps.append(current_datetime) |
225
|
|
|
point_values.append(row[1]) |
226
|
|
|
|
227
|
|
|
reporting['names'].append(point['name'] + ' (' + point['units'] + ')') |
228
|
|
|
reporting['timestamps'].append(point_timestamps) |
229
|
|
|
reporting['values'].append(point_values) |
230
|
|
|
|
231
|
|
|
################################################################################################################ |
232
|
|
|
# Step 5: query tariff data |
233
|
|
|
################################################################################################################ |
234
|
|
|
parameters_data = dict() |
235
|
|
|
parameters_data['names'] = list() |
236
|
|
|
parameters_data['timestamps'] = list() |
237
|
|
|
parameters_data['values'] = list() |
238
|
|
|
if not is_quick_mode: |
239
|
|
|
tariff_dict = utilities.get_energy_category_tariffs(meter['cost_center_id'], |
240
|
|
|
meter['energy_category_id'], |
241
|
|
|
reporting_start_datetime_utc, |
242
|
|
|
reporting_end_datetime_utc) |
243
|
|
|
print(tariff_dict) |
244
|
|
|
tariff_timestamp_list = list() |
245
|
|
|
tariff_value_list = list() |
246
|
|
|
for k, v in tariff_dict.items(): |
247
|
|
|
# convert k from utc to local |
248
|
|
|
k = k + timedelta(minutes=timezone_offset) |
249
|
|
|
tariff_timestamp_list.append(k.isoformat()[0:19]) |
250
|
|
|
tariff_value_list.append(v) |
251
|
|
|
|
252
|
|
|
parameters_data['names'].append('TARIFF-' + meter['energy_category_name']) |
253
|
|
|
parameters_data['timestamps'].append(tariff_timestamp_list) |
254
|
|
|
parameters_data['values'].append(tariff_value_list) |
255
|
|
|
|
256
|
|
|
################################################################################################################ |
257
|
|
|
# Step 6: construct the report |
258
|
|
|
################################################################################################################ |
259
|
|
|
if cursor_system: |
260
|
|
|
cursor_system.close() |
261
|
|
|
if cnx_system: |
262
|
|
|
cnx_system.disconnect() |
263
|
|
|
|
264
|
|
|
if cursor_historical: |
265
|
|
|
cursor_historical.close() |
266
|
|
|
if cnx_historical: |
267
|
|
|
cnx_historical.disconnect() |
268
|
|
|
|
269
|
|
|
result = { |
270
|
|
|
"meter": { |
271
|
|
|
"cost_center_id": meter['cost_center_id'], |
272
|
|
|
"energy_category_id": meter['energy_category_id'], |
273
|
|
|
"energy_category_name": meter['energy_category_name'], |
274
|
|
|
"unit_of_measure": meter['unit_of_measure'], |
275
|
|
|
"kgce": meter['kgce'], |
276
|
|
|
"kgco2e": meter['kgco2e'], |
277
|
|
|
}, |
278
|
|
|
"reporting_period": { |
279
|
|
|
"names": reporting['names'], |
280
|
|
|
"timestamps": reporting['timestamps'], |
281
|
|
|
"values": reporting['values'], |
282
|
|
|
}, |
283
|
|
|
"parameters": { |
284
|
|
|
"names": parameters_data['names'], |
285
|
|
|
"timestamps": parameters_data['timestamps'], |
286
|
|
|
"values": parameters_data['values'] |
287
|
|
|
}, |
288
|
|
|
"excel_bytes_base64": None |
289
|
|
|
} |
290
|
|
|
# export result to Excel file and then encode the file to base64 string |
291
|
|
|
if not is_quick_mode: |
292
|
|
|
result['excel_bytes_base64'] = excelexporters.metertrend.export(result, |
293
|
|
|
meter['name'], |
294
|
|
|
reporting_period_start_datetime_local, |
295
|
|
|
reporting_period_end_datetime_local, |
296
|
|
|
None) |
297
|
|
|
|
298
|
|
|
resp.text = json.dumps(result) |
299
|
|
|
|