1 | from datetime import datetime, timedelta, timezone |
||
2 | from decimal import Decimal |
||
3 | import falcon |
||
4 | import mysql.connector |
||
5 | import simplejson as json |
||
6 | from core import utilities |
||
7 | import config |
||
8 | from core.useractivity import access_control, api_key_control |
||
9 | |||
10 | |||
11 | View Code Duplication | class Reporting: |
|
0 ignored issues
–
show
Duplication
introduced
by
![]() |
|||
12 | def __init__(self): |
||
13 | """Initializes Class""" |
||
14 | pass |
||
15 | |||
16 | @staticmethod |
||
17 | def on_options(req, resp): |
||
18 | _ = req |
||
19 | resp.status = falcon.HTTP_200 |
||
20 | |||
21 | #################################################################################################################### |
||
22 | # PROCEDURES |
||
23 | # Step 1: valid parameters |
||
24 | # Step 2: query the energy storage power station list |
||
25 | # Step 3: query charge carbon data in 7 days |
||
26 | # Step 5: query charge carbon data in this month |
||
27 | # Step 7: query charge carbon data in this year |
||
28 | # Step 9: construct the report |
||
29 | #################################################################################################################### |
||
30 | @staticmethod |
||
31 | def on_get(req, resp): |
||
32 | if 'API-KEY' not in req.headers or \ |
||
33 | not isinstance(req.headers['API-KEY'], str) or \ |
||
34 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
35 | access_control(req) |
||
36 | else: |
||
37 | api_key_control(req) |
||
38 | user_uuid = req.params.get('useruuid') |
||
39 | |||
40 | ################################################################################################################ |
||
41 | # Step 1: valid parameters |
||
42 | ################################################################################################################ |
||
43 | if user_uuid is None: |
||
44 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_USER_UUID') |
||
45 | else: |
||
46 | user_uuid = str.strip(user_uuid) |
||
47 | if len(user_uuid) != 36: |
||
48 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
49 | description='API.INVALID_USER_UUID') |
||
50 | |||
51 | ################################################################################################################ |
||
52 | # Step 2: query the energy storage power station list |
||
53 | ################################################################################################################ |
||
54 | cnx_user = mysql.connector.connect(**config.myems_user_db) |
||
55 | cursor_user = cnx_user.cursor() |
||
56 | cursor_user.execute(" SELECT id, is_admin, privilege_id " |
||
57 | " FROM tbl_users " |
||
58 | " WHERE uuid = %s ", (user_uuid,)) |
||
59 | row_user = cursor_user.fetchone() |
||
60 | if row_user is None: |
||
61 | if cursor_user: |
||
62 | cursor_user.close() |
||
63 | if cnx_user: |
||
64 | cnx_user.close() |
||
65 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
66 | description='API.USER_NOT_FOUND') |
||
67 | |||
68 | user = {'id': row_user[0], 'is_admin': row_user[1], 'privilege_id': row_user[2]} |
||
69 | |||
70 | # Get energy storage power stations |
||
71 | cnx_system_db = mysql.connector.connect(**config.myems_system_db) |
||
72 | cursor_system_db = cnx_system_db.cursor() |
||
73 | query = (" SELECT m.id, m.name, m.uuid " |
||
74 | " FROM tbl_photovoltaic_power_stations m, tbl_photovoltaic_power_stations_users mu " |
||
75 | " WHERE m.phase_of_lifecycle != '3installation' " |
||
76 | " AND m.id = mu.photovoltaic_power_station_id " |
||
77 | " AND mu.user_id = %s " |
||
78 | " ORDER BY id ") |
||
79 | cursor_system_db.execute(query, (user['id'],)) |
||
80 | rows_photovoltaic_power_stations = cursor_system_db.fetchall() |
||
81 | |||
82 | photovoltaic_power_station_list = list() |
||
83 | photovoltaic_power_station_names = list() |
||
84 | if rows_photovoltaic_power_stations is not None and len(rows_photovoltaic_power_stations) > 0: |
||
85 | for row in rows_photovoltaic_power_stations: |
||
86 | meta_result = {"id": row[0], |
||
87 | "name": row[1], |
||
88 | "uuid": row[2]} |
||
89 | photovoltaic_power_station_list.append(meta_result) |
||
90 | photovoltaic_power_station_names.append(row[1]) |
||
91 | ################################################################################################################ |
||
92 | # Step 3: query generation carbon data in 7 days |
||
93 | ################################################################################################################ |
||
94 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
95 | if config.utc_offset[0] == '-': |
||
96 | timezone_offset = -timezone_offset |
||
97 | reporting = dict() |
||
98 | reporting['generation_7_days'] = dict() |
||
99 | reporting['generation_this_month'] = dict() |
||
100 | reporting['generation_this_year'] = dict() |
||
101 | |||
102 | end_datetime_utc = datetime.utcnow() |
||
103 | end_datetime_local = datetime.utcnow() + timedelta(minutes=timezone_offset) |
||
104 | period_type = 'daily' |
||
105 | start_datetime_local = end_datetime_local.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=6) |
||
106 | start_datetime_utc = start_datetime_local - timedelta(minutes=timezone_offset) |
||
107 | print('start_datetime_local:' + start_datetime_local.isoformat()) |
||
108 | print('end_datetime_local:' + end_datetime_local.isoformat()) |
||
109 | print('start_datetime_utc:' + start_datetime_utc.isoformat()) |
||
110 | print('end_datetime_utc:' + end_datetime_utc.isoformat()) |
||
111 | |||
112 | cnx_carbon_db = mysql.connector.connect(**config.myems_carbon_db) |
||
113 | cursor_carbon_db = cnx_carbon_db.cursor() |
||
114 | |||
115 | reporting['generation_7_days'] = dict() |
||
116 | reporting['generation_7_days']['timestamps_array'] = list() |
||
117 | reporting['generation_7_days']['values_array'] = list() |
||
118 | |||
119 | for photovoltaic_power_station in photovoltaic_power_station_list: |
||
120 | timestamps = list() |
||
121 | values = list() |
||
122 | query = (" SELECT start_datetime_utc, actual_value " |
||
123 | " FROM tbl_photovoltaic_power_station_generation_hourly " |
||
124 | " WHERE photovoltaic_power_station_id = %s " |
||
125 | " AND start_datetime_utc >= %s " |
||
126 | " AND start_datetime_utc < %s " |
||
127 | " ORDER BY start_datetime_utc ") |
||
128 | cursor_carbon_db.execute(query, (photovoltaic_power_station['id'], start_datetime_utc, end_datetime_utc)) |
||
129 | rows_generation_hourly = cursor_carbon_db.fetchall() |
||
130 | |||
131 | rows_generation_periodically = utilities.aggregate_hourly_data_by_period(rows_generation_hourly, |
||
132 | start_datetime_utc, |
||
133 | end_datetime_utc, |
||
134 | period_type) |
||
135 | for row_generation_periodically in rows_generation_periodically: |
||
136 | current_datetime_local = row_generation_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
137 | timedelta(minutes=timezone_offset) |
||
138 | if period_type == 'hourly': |
||
139 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
140 | elif period_type == 'daily': |
||
141 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
142 | elif period_type == 'weekly': |
||
143 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
144 | elif period_type == 'monthly': |
||
145 | current_datetime = current_datetime_local.isoformat()[0:7] |
||
146 | elif period_type == 'yearly': |
||
147 | current_datetime = current_datetime_local.isoformat()[0:4] |
||
148 | |||
149 | actual_value = Decimal(0.0) if row_generation_periodically[1] is None else \ |
||
150 | row_generation_periodically[1] |
||
151 | timestamps.append(current_datetime) |
||
0 ignored issues
–
show
|
|||
152 | values.append(actual_value) |
||
153 | reporting['generation_7_days']['timestamps_array'].append(timestamps) |
||
154 | reporting['generation_7_days']['values_array'].append(values) |
||
155 | |||
156 | ################################################################################################################ |
||
157 | # Step 5: query generation carbon data in this month |
||
158 | ################################################################################################################ |
||
159 | end_datetime_utc = datetime.utcnow() |
||
160 | end_datetime_local = datetime.utcnow() + timedelta(minutes=timezone_offset) |
||
161 | period_type = 'daily' |
||
162 | start_datetime_local = end_datetime_local.replace(day=1, hour=0, minute=0, second=0, microsecond=0) |
||
163 | start_datetime_utc = start_datetime_local - timedelta(minutes=timezone_offset) |
||
164 | print('start_datetime_local:' + start_datetime_local.isoformat()) |
||
165 | print('end_datetime_local:' + end_datetime_local.isoformat()) |
||
166 | print('start_datetime_utc:' + start_datetime_utc.isoformat()) |
||
167 | print('end_datetime_utc:' + end_datetime_utc.isoformat()) |
||
168 | |||
169 | reporting['generation_this_month'] = dict() |
||
170 | reporting['generation_this_month']['timestamps_array'] = list() |
||
171 | reporting['generation_this_month']['values_array'] = list() |
||
172 | |||
173 | for photovoltaic_power_station in photovoltaic_power_station_list: |
||
174 | timestamps = list() |
||
175 | values = list() |
||
176 | query = (" SELECT start_datetime_utc, actual_value " |
||
177 | " FROM tbl_photovoltaic_power_station_generation_hourly " |
||
178 | " WHERE photovoltaic_power_station_id = %s " |
||
179 | " AND start_datetime_utc >= %s " |
||
180 | " AND start_datetime_utc < %s " |
||
181 | " ORDER BY start_datetime_utc ") |
||
182 | cursor_carbon_db.execute(query, (photovoltaic_power_station['id'], start_datetime_utc, end_datetime_utc)) |
||
183 | rows_generation_hourly = cursor_carbon_db.fetchall() |
||
184 | |||
185 | rows_generation_periodically = utilities.aggregate_hourly_data_by_period(rows_generation_hourly, |
||
186 | start_datetime_utc, |
||
187 | end_datetime_utc, |
||
188 | period_type) |
||
189 | |||
190 | for row_generation_periodically in rows_generation_periodically: |
||
191 | current_datetime_local = row_generation_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
192 | timedelta(minutes=timezone_offset) |
||
193 | if period_type == 'hourly': |
||
194 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
195 | elif period_type == 'daily': |
||
196 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
197 | elif period_type == 'weekly': |
||
198 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
199 | elif period_type == 'monthly': |
||
200 | current_datetime = current_datetime_local.isoformat()[0:7] |
||
201 | elif period_type == 'yearly': |
||
202 | current_datetime = current_datetime_local.isoformat()[0:4] |
||
203 | |||
204 | actual_value = Decimal(0.0) if row_generation_periodically[1] is None else \ |
||
205 | row_generation_periodically[1] |
||
206 | timestamps.append(current_datetime) |
||
207 | values.append(actual_value) |
||
208 | reporting['generation_this_month']['timestamps_array'].append(timestamps) |
||
209 | reporting['generation_this_month']['values_array'].append(values) |
||
210 | |||
211 | ################################################################################################################ |
||
212 | # Step 7: query generation carbon data in this year |
||
213 | ################################################################################################################ |
||
214 | end_datetime_utc = datetime.utcnow() |
||
215 | end_datetime_local = datetime.utcnow() + timedelta(minutes=timezone_offset) |
||
216 | period_type = 'monthly' |
||
217 | start_datetime_local = end_datetime_local.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) |
||
218 | start_datetime_utc = start_datetime_local - timedelta(minutes=timezone_offset) |
||
219 | print('start_datetime_local:' + start_datetime_local.isoformat()) |
||
220 | print('end_datetime_local:' + end_datetime_local.isoformat()) |
||
221 | print('start_datetime_utc:' + start_datetime_utc.isoformat()) |
||
222 | print('end_datetime_utc:' + end_datetime_utc.isoformat()) |
||
223 | |||
224 | reporting['generation_this_year'] = dict() |
||
225 | reporting['generation_this_year']['timestamps_array'] = list() |
||
226 | reporting['generation_this_year']['values_array'] = list() |
||
227 | |||
228 | for photovoltaic_power_station in photovoltaic_power_station_list: |
||
229 | timestamps = list() |
||
230 | values = list() |
||
231 | query = (" SELECT start_datetime_utc, actual_value " |
||
232 | " FROM tbl_photovoltaic_power_station_generation_hourly " |
||
233 | " WHERE photovoltaic_power_station_id = %s " |
||
234 | " AND start_datetime_utc >= %s " |
||
235 | " AND start_datetime_utc < %s " |
||
236 | " ORDER BY start_datetime_utc ") |
||
237 | cursor_carbon_db.execute(query, (photovoltaic_power_station['id'], start_datetime_utc, end_datetime_utc)) |
||
238 | rows_generation_hourly = cursor_carbon_db.fetchall() |
||
239 | |||
240 | rows_generation_periodically = utilities.aggregate_hourly_data_by_period(rows_generation_hourly, |
||
241 | start_datetime_utc, |
||
242 | end_datetime_utc, |
||
243 | period_type) |
||
244 | for row_generation_periodically in rows_generation_periodically: |
||
245 | current_datetime_local = row_generation_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
246 | timedelta(minutes=timezone_offset) |
||
247 | if period_type == 'hourly': |
||
248 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
249 | elif period_type == 'daily': |
||
250 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
251 | elif period_type == 'weekly': |
||
252 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
253 | elif period_type == 'monthly': |
||
254 | current_datetime = current_datetime_local.isoformat()[0:7] |
||
255 | elif period_type == 'yearly': |
||
256 | current_datetime = current_datetime_local.isoformat()[0:4] |
||
257 | |||
258 | actual_value = Decimal(0.0) if row_generation_periodically[1] is None else \ |
||
259 | row_generation_periodically[1] |
||
260 | timestamps.append(current_datetime) |
||
261 | values.append(actual_value) |
||
262 | reporting['generation_this_year']['timestamps_array'].append(timestamps) |
||
263 | reporting['generation_this_year']['values_array'].append(values) |
||
264 | |||
265 | ################################################################################################################ |
||
266 | # Step 9: construct the report |
||
267 | ################################################################################################################ |
||
268 | if cursor_system_db: |
||
269 | cursor_system_db.close() |
||
270 | if cnx_system_db: |
||
271 | cnx_system_db.close() |
||
272 | |||
273 | if cursor_carbon_db: |
||
274 | cursor_carbon_db.close() |
||
275 | if cnx_carbon_db: |
||
276 | cnx_carbon_db.close() |
||
277 | |||
278 | result = dict() |
||
279 | result['photovoltaic_power_station_names'] = photovoltaic_power_station_names |
||
280 | result['reporting'] = reporting |
||
281 | resp.text = json.dumps(result) |
||
282 |