core.microgrid.MicrogridGeneratorItem.on_put()   F
last analyzed

Complexity

Conditions 23

Size

Total Lines 114
Code Lines 89

Duplication

Lines 114
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 89
dl 114
loc 114
rs 0
c 0
b 0
f 0
cc 23
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like core.microgrid.MicrogridGeneratorItem.on_put() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import uuid
2
from datetime import datetime, timedelta
3
import falcon
4
import mysql.connector
5
import simplejson as json
6
from core.useractivity import user_logger, admin_control, access_control
7
import config
8
9
10
class MicrogridCollection:
11
    def __init__(self):
12
        """"Initializes MicrogridCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
20
    def on_get(req, resp):
21
        access_control(req)
22
        cnx = mysql.connector.connect(**config.myems_system_db)
23
        cursor = cnx.cursor()
24
25
        query = (" SELECT id, name, uuid "
26
                 " FROM tbl_contacts ")
27
        cursor.execute(query)
28
        rows_contacts = cursor.fetchall()
29
30
        contact_dict = dict()
31
        if rows_contacts is not None and len(rows_contacts) > 0:
32
            for row in rows_contacts:
33
                contact_dict[row[0]] = {"id": row[0],
34
                                        "name": row[1],
35
                                        "uuid": row[2]}
36
37
        query = (" SELECT id, name, uuid "
38
                 " FROM tbl_cost_centers ")
39
        cursor.execute(query)
40
        rows_cost_centers = cursor.fetchall()
41
42
        cost_center_dict = dict()
43
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
44
            for row in rows_cost_centers:
45
                cost_center_dict[row[0]] = {"id": row[0],
46
                                            "name": row[1],
47
                                            "uuid": row[2]}
48
        svg_dict = dict()
49
50
        query = (" SELECT id, name, uuid "
51
                 " FROM tbl_svgs ")
52
        cursor.execute(query)
53
        rows_svgs = cursor.fetchall()
54
        if rows_svgs is not None and len(rows_svgs) > 0:
55
            for row in rows_svgs:
56
                svg_dict[row[0]] = {"id": row[0],
57
                                    "name": row[1],
58
                                    "uuid": row[2]}
59
60
        query = (" SELECT id, name, uuid, "
61
                 "        address, postal_code, latitude, longitude, rated_capacity, rated_power, "
62
                 "        contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, "
63
                 "        phase_of_lifecycle, description "
64
                 " FROM tbl_microgrids "
65
                 " ORDER BY id ")
66
        cursor.execute(query)
67
        rows_microgrids = cursor.fetchall()
68
69
        result = list()
70
        if rows_microgrids is not None and len(rows_microgrids) > 0:
71
            for row in rows_microgrids:
72
                meta_result = {"id": row[0],
73
                               "name": row[1],
74
                               "uuid": row[2],
75
                               "address": row[3],
76
                               "postal_code": row[4],
77
                               "latitude": row[5],
78
                               "longitude": row[6],
79
                               "rated_capacity": row[7],
80
                               "rated_power": row[8],
81
                               "contact": contact_dict.get(row[9], None),
82
                               "cost_center": cost_center_dict.get(row[10], None),
83
                               "serial_number": row[11],
84
                               "svg": svg_dict.get(row[12], None),
85
                               "is_cost_data_displayed": bool(row[13]),
86
                               "phase_of_lifecycle": row[14],
87
                               "description": row[15],
88
                               "qrcode": 'microgrid:' + row[2]}
89
                result.append(meta_result)
90
91
        cursor.close()
92
        cnx.close()
93
        resp.text = json.dumps(result)
94
95
    @staticmethod
96
    @user_logger
97
    def on_post(req, resp):
98
        """Handles POST requests"""
99
        admin_control(req)
100
        try:
101
            raw_json = req.stream.read().decode('utf-8')
102
        except Exception as ex:
103
            raise falcon.HTTPError(status=falcon.HTTP_400,
104
                                   title='API.BAD_REQUEST',
105
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
106
107
        new_values = json.loads(raw_json)
108
109
        if 'name' not in new_values['data'].keys() or \
110
                not isinstance(new_values['data']['name'], str) or \
111
                len(str.strip(new_values['data']['name'])) == 0:
112
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
113
                                   description='API.INVALID_MICROGRID_NAME')
114
        name = str.strip(new_values['data']['name'])
115
116
        if 'address' not in new_values['data'].keys() or \
117
                not isinstance(new_values['data']['address'], str) or \
118
                len(str.strip(new_values['data']['address'])) == 0:
119
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
120
                                   description='API.INVALID_ADDRESS_VALUE')
121
        address = str.strip(new_values['data']['address'])
122
123
        if 'postal_code' not in new_values['data'].keys() or \
124
                not isinstance(new_values['data']['postal_code'], str) or \
125
                len(str.strip(new_values['data']['postal_code'])) == 0:
126
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
127
                                   description='API.INVALID_POSTAL_CODE_VALUE')
128
        postal_code = str.strip(new_values['data']['postal_code'])
129
130
        if 'latitude' not in new_values['data'].keys() or \
131
                not (isinstance(new_values['data']['latitude'], float) or
132
                     isinstance(new_values['data']['latitude'], int)) or \
133
                new_values['data']['latitude'] < -90.0 or \
134
                new_values['data']['latitude'] > 90.0:
135
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
136
                                   description='API.INVALID_LATITUDE_VALUE')
137
        latitude = new_values['data']['latitude']
138
139
        if 'longitude' not in new_values['data'].keys() or \
140
                not (isinstance(new_values['data']['longitude'], float) or
141
                     isinstance(new_values['data']['longitude'], int)) or \
142
                new_values['data']['longitude'] < -180.0 or \
143
                new_values['data']['longitude'] > 180.0:
144
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
145
                                   description='API.INVALID_LONGITUDE_VALUE')
146
        longitude = new_values['data']['longitude']
147
148
        if 'rated_capacity' not in new_values['data'].keys() or \
149
                not (isinstance(new_values['data']['rated_capacity'], float) or
150
                     isinstance(new_values['data']['rated_capacity'], int)) or \
151
                new_values['data']['rated_capacity'] <= 0.0:
152
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
153
                                   description='API.INVALID_RATED_CAPACITY')
154
        rated_capacity = new_values['data']['rated_capacity']
155
156
        if 'rated_power' not in new_values['data'].keys() or \
157
                not (isinstance(new_values['data']['rated_power'], float) or
158
                     isinstance(new_values['data']['rated_power'], int)) or \
159
                new_values['data']['rated_power'] <= 0.0:
160
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
161
                                   description='API.INVALID_RATED_POWER_VALUE')
162
        rated_power = new_values['data']['rated_power']
163
164
        if 'contact_id' not in new_values['data'].keys() or \
165
                not isinstance(new_values['data']['contact_id'], int) or \
166
                new_values['data']['contact_id'] <= 0:
167
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
168
                                   description='API.INVALID_CONTACT_ID')
169
        contact_id = new_values['data']['contact_id']
170
171
        if 'cost_center_id' not in new_values['data'].keys() or \
172
                not isinstance(new_values['data']['cost_center_id'], int) or \
173
                new_values['data']['cost_center_id'] <= 0:
174
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
175
                                   description='API.INVALID_COST_CENTER_ID')
176
        cost_center_id = new_values['data']['cost_center_id']
177
178
        if 'serial_number' not in new_values['data'].keys() or \
179
                not isinstance(new_values['data']['serial_number'], str) or \
180
                len(str.strip(new_values['data']['serial_number'])) == 0:
181
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
182
                                   description='API.INVALID_SERIAL_NUMBER')
183
        serial_number = str.strip(new_values['data']['serial_number'])
184
185
        if 'svg_id' not in new_values['data'].keys() or \
186
                not isinstance(new_values['data']['svg_id'], int) or \
187
                new_values['data']['svg_id'] <= 0:
188
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
189
                                   description='API.INVALID_SVG_ID')
190
        svg_id = new_values['data']['svg_id']
191
192
        if 'is_cost_data_displayed' not in new_values['data'].keys() or \
193
                not isinstance(new_values['data']['is_cost_data_displayed'], bool):
194
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
195
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED')
196
        is_cost_data_displayed = new_values['data']['is_cost_data_displayed']
197
198
        if 'phase_of_lifecycle' not in new_values['data'].keys() or \
199
                not isinstance(new_values['data']['phase_of_lifecycle'], str) or \
200
                len(str.strip(new_values['data']['phase_of_lifecycle'])) == 0:
201
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
202
                                   description='API.INVALID_PHASE_OF_LIFECYCLE')
203
        phase_of_lifecycle = str.strip(new_values['data']['phase_of_lifecycle'])
204
205
        if 'description' in new_values['data'].keys() and \
206
                new_values['data']['description'] is not None and \
207
                len(str(new_values['data']['description'])) > 0:
208
            description = str.strip(new_values['data']['description'])
209
        else:
210
            description = None
211
212
        cnx = mysql.connector.connect(**config.myems_system_db)
213
        cursor = cnx.cursor()
214
215
        cursor.execute(" SELECT name "
216
                       " FROM tbl_microgrids "
217
                       " WHERE name = %s ", (name,))
218
        if cursor.fetchone() is not None:
219
            cursor.close()
220
            cnx.close()
221
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
222
                                   description='API.MICROGRID_NAME_IS_ALREADY_IN_USE')
223
224
        cursor.execute(" SELECT name "
225
                       " FROM tbl_contacts "
226
                       " WHERE id = %s ",
227
                       (new_values['data']['contact_id'],))
228
        row = cursor.fetchone()
229
        if row is None:
230
            cursor.close()
231
            cnx.close()
232
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
233
                                   description='API.CONTACT_NOT_FOUND')
234
235
        cursor.execute(" SELECT name "
236
                       " FROM tbl_cost_centers "
237
                       " WHERE id = %s ",
238
                       (new_values['data']['cost_center_id'],))
239
        row = cursor.fetchone()
240
        if row is None:
241
            cursor.close()
242
            cnx.close()
243
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
244
                                   description='API.COST_CENTER_NOT_FOUND')
245
246
        cursor.execute(" SELECT name "
247
                       " FROM tbl_svgs "
248
                       " WHERE id = %s ",
249
                       (svg_id,))
250
        row = cursor.fetchone()
251
        if row is None:
252
            cursor.close()
253
            cnx.close()
254
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
255
                                   description='API.SVG_NOT_FOUND')
256
257
        add_values = (" INSERT INTO tbl_microgrids "
258
                      "    (name, uuid, address, postal_code, latitude, longitude, rated_capacity, rated_power, "
259
                      "     contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, "
260
                      "     phase_of_lifecycle, description) "
261
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
262
        cursor.execute(add_values, (name,
263
                                    str(uuid.uuid4()),
264
                                    address,
265
                                    postal_code,
266
                                    latitude,
267
                                    longitude,
268
                                    rated_capacity,
269
                                    rated_power,
270
                                    contact_id,
271
                                    cost_center_id,
272
                                    serial_number,
273
                                    svg_id,
274
                                    is_cost_data_displayed,
275
                                    phase_of_lifecycle,
276
                                    description))
277
        new_id = cursor.lastrowid
278
        cnx.commit()
279
        cursor.close()
280
        cnx.close()
281
282
        resp.status = falcon.HTTP_201
283
        resp.location = '/microgrids/' + str(new_id)
284
285
286
class MicrogridItem:
287
    def __init__(self):
288
        """"Initializes MicrogridItem"""
289
        pass
290
291
    @staticmethod
292
    def on_options(req, resp, id_):
293
        resp.status = falcon.HTTP_200
294
295 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
296
    def on_get(req, resp, id_):
297
        access_control(req)
298
        if not id_.isdigit() or int(id_) <= 0:
299
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
300
                                   description='API.INVALID_MICROGRID_ID')
301
302
        cnx = mysql.connector.connect(**config.myems_system_db)
303
        cursor = cnx.cursor()
304
305
        query = (" SELECT id, name, uuid "
306
                 " FROM tbl_contacts ")
307
        cursor.execute(query)
308
        rows_contacts = cursor.fetchall()
309
310
        contact_dict = dict()
311
        if rows_contacts is not None and len(rows_contacts) > 0:
312
            for row in rows_contacts:
313
                contact_dict[row[0]] = {"id": row[0],
314
                                        "name": row[1],
315
                                        "uuid": row[2]}
316
317
        query = (" SELECT id, name, uuid "
318
                 " FROM tbl_cost_centers ")
319
        cursor.execute(query)
320
        rows_cost_centers = cursor.fetchall()
321
322
        cost_center_dict = dict()
323
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
324
            for row in rows_cost_centers:
325
                cost_center_dict[row[0]] = {"id": row[0],
326
                                            "name": row[1],
327
                                            "uuid": row[2]}
328
        svg_dict = dict()
329
330
        query = (" SELECT id, name, uuid "
331
                 " FROM tbl_svgs ")
332
        cursor.execute(query)
333
        rows_svgs = cursor.fetchall()
334
        if rows_svgs is not None and len(rows_svgs) > 0:
335
            for row in rows_svgs:
336
                svg_dict[row[0]] = {"id": row[0],
337
                                    "name": row[1],
338
                                    "uuid": row[2]}
339
340
        query = (" SELECT id, name, uuid, "
341
                 "        address, postal_code, latitude, longitude, rated_capacity, rated_power, "
342
                 "        contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, "
343
                 "        phase_of_lifecycle, description "
344
                 " FROM tbl_microgrids "
345
                 " WHERE id = %s ")
346
        cursor.execute(query, (id_,))
347
        row = cursor.fetchone()
348
        cursor.close()
349
        cnx.close()
350
351
        if row is None:
352
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
353
                                   description='API.MICROGRID_NOT_FOUND')
354
        else:
355
            meta_result = {"id": row[0],
356
                           "name": row[1],
357
                           "uuid": row[2],
358
                           "address": row[3],
359
                           "postal_code": row[4],
360
                           "latitude": row[5],
361
                           "longitude": row[6],
362
                           "rated_capacity": row[7],
363
                           "rated_power": row[8],
364
                           "contact": contact_dict.get(row[9], None),
365
                           "cost_center": cost_center_dict.get(row[10], None),
366
                           "serial_number": row[11],
367
                           "svg": svg_dict.get(row[12], None),
368
                           "is_cost_data_displayed": bool(row[13]),
369
                           "phase_of_lifecycle": row[14],
370
                           "description": row[15],
371
                           "qrcode": 'microgrid:' + row[2]}
372
373
        resp.text = json.dumps(meta_result)
374
375
    @staticmethod
376
    @user_logger
377
    def on_delete(req, resp, id_):
378
        admin_control(req)
379
        if not id_.isdigit() or int(id_) <= 0:
380
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
381
                                   description='API.INVALID_MICROGRID_ID')
382
383
        cnx = mysql.connector.connect(**config.myems_system_db)
384
        cursor = cnx.cursor()
385
386
        cursor.execute(" SELECT name "
387
                       " FROM tbl_microgrids "
388
                       " WHERE id = %s ", (id_,))
389
        if cursor.fetchone() is None:
390
            cursor.close()
391
            cnx.close()
392
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
393
                                   description='API.MICROGRID_NOT_FOUND')
394
395
        # check relation with power plants
396
        cursor.execute(" SELECT id "
397
                       " FROM tbl_virtual_power_plants_microgrids "
398
                       " WHERE microgrid_id = %s ",
399
                       (id_,))
400
        rows_power_plants = cursor.fetchall()
401
        if rows_power_plants is not None and len(rows_power_plants) > 0:
402
            cursor.close()
403
            cnx.close()
404
            raise falcon.HTTPError(status=falcon.HTTP_400,
405
                                   title='API.BAD_REQUEST',
406
                                   description='API.THERE_IS_RELATION_WITH_VIRTUAL_POWER_PLANTS')
407
408
        cursor.execute(" DELETE FROM tbl_microgrids_batteries WHERE microgrid_id = %s ", (id_,))
409
        cnx.commit()
410
        cursor.execute(" DELETE FROM tbl_microgrids_commands WHERE microgrid_id = %s ", (id_,))
411
        cnx.commit()
412
        cursor.execute(" DELETE FROM tbl_microgrids_power_conversion_systems WHERE microgrid_id = %s ", (id_,))
413
        cnx.commit()
414
        cursor.execute(" DELETE FROM tbl_microgrids_evchargers WHERE microgrid_id = %s ", (id_,))
415
        cnx.commit()
416
        cursor.execute(" DELETE FROM tbl_microgrids_generators WHERE microgrid_id = %s ", (id_,))
417
        cnx.commit()
418
        cursor.execute(" DELETE FROM tbl_microgrids_grids WHERE microgrid_id = %s ", (id_,))
419
        cnx.commit()
420
        cursor.execute(" DELETE FROM tbl_microgrids_heatpumps WHERE microgrid_id = %s ", (id_,))
421
        cnx.commit()
422
        cursor.execute(" DELETE FROM tbl_microgrids_loads WHERE microgrid_id = %s ", (id_,))
423
        cnx.commit()
424
        cursor.execute(" DELETE FROM tbl_microgrids_photovoltaics WHERE microgrid_id = %s ", (id_,))
425
        cnx.commit()
426
        cursor.execute(" DELETE FROM tbl_microgrids_sensors WHERE microgrid_id = %s ", (id_,))
427
        cnx.commit()
428
        cursor.execute(" DELETE FROM tbl_microgrids_users WHERE microgrid_id = %s ", (id_,))
429
        cnx.commit()
430
        cursor.execute(" DELETE FROM tbl_microgrids WHERE id = %s ", (id_,))
431
        cnx.commit()
432
433
        cursor.close()
434
        cnx.close()
435
436
        resp.status = falcon.HTTP_204
437
438
    @staticmethod
439
    @user_logger
440
    def on_put(req, resp, id_):
441
        """Handles PUT requests"""
442
        admin_control(req)
443
        try:
444
            raw_json = req.stream.read().decode('utf-8')
445
        except Exception as ex:
446
            raise falcon.HTTPError(status=falcon.HTTP_400,
447
                                   title='API.BAD_REQUEST',
448
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
449
450
        if not id_.isdigit() or int(id_) <= 0:
451
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
452
                                   description='API.INVALID_MICROGRID_ID')
453
454
        new_values = json.loads(raw_json)
455
456
        if 'name' not in new_values['data'].keys() or \
457
                not isinstance(new_values['data']['name'], str) or \
458
                len(str.strip(new_values['data']['name'])) == 0:
459
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
460
                                   description='API.INVALID_MICROGRID_NAME')
461
        name = str.strip(new_values['data']['name'])
462
463
        if 'address' not in new_values['data'].keys() or \
464
                not isinstance(new_values['data']['address'], str) or \
465
                len(str.strip(new_values['data']['address'])) == 0:
466
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
467
                                   description='API.INVALID_ADDRESS_VALUE')
468
        address = str.strip(new_values['data']['address'])
469
470
        if 'postal_code' not in new_values['data'].keys() or \
471
                not isinstance(new_values['data']['postal_code'], str) or \
472
                len(str.strip(new_values['data']['postal_code'])) == 0:
473
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
474
                                   description='API.INVALID_POSTAL_CODE_VALUE')
475
        postal_code = str.strip(new_values['data']['postal_code'])
476
477
        if 'latitude' not in new_values['data'].keys() or \
478
                not (isinstance(new_values['data']['latitude'], float) or
479
                     isinstance(new_values['data']['latitude'], int)) or \
480
                new_values['data']['latitude'] < -90.0 or \
481
                new_values['data']['latitude'] > 90.0:
482
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
483
                                   description='API.INVALID_LATITUDE_VALUE')
484
        latitude = new_values['data']['latitude']
485
486
        if 'longitude' not in new_values['data'].keys() or \
487
                not (isinstance(new_values['data']['longitude'], float) or
488
                     isinstance(new_values['data']['longitude'], int)) or \
489
                new_values['data']['longitude'] < -180.0 or \
490
                new_values['data']['longitude'] > 180.0:
491
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
492
                                   description='API.INVALID_LONGITUDE_VALUE')
493
        longitude = new_values['data']['longitude']
494
495
        if 'rated_capacity' not in new_values['data'].keys() or \
496
                not (isinstance(new_values['data']['rated_capacity'], float) or
497
                     isinstance(new_values['data']['rated_capacity'], int)) or \
498
                new_values['data']['rated_capacity'] <= 0.0:
499
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
500
                                   description='API.INVALID_RATED_CAPACITY')
501
        rated_capacity = new_values['data']['rated_capacity']
502
503
        if 'rated_power' not in new_values['data'].keys() or \
504
                not (isinstance(new_values['data']['rated_power'], float) or
505
                     isinstance(new_values['data']['rated_power'], int)) or \
506
                new_values['data']['rated_power'] <= 0.0:
507
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
508
                                   description='API.INVALID_RATED_POWER_VALUE')
509
        rated_power = new_values['data']['rated_power']
510
511
        if 'contact_id' not in new_values['data'].keys() or \
512
                not isinstance(new_values['data']['contact_id'], int) or \
513
                new_values['data']['contact_id'] <= 0:
514
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
515
                                   description='API.INVALID_CONTACT_ID')
516
        contact_id = new_values['data']['contact_id']
517
518
        if 'cost_center_id' not in new_values['data'].keys() or \
519
                not isinstance(new_values['data']['cost_center_id'], int) or \
520
                new_values['data']['cost_center_id'] <= 0:
521
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
522
                                   description='API.INVALID_COST_CENTER_ID')
523
        cost_center_id = new_values['data']['cost_center_id']
524
525
        if 'serial_number' not in new_values['data'].keys() or \
526
                not isinstance(new_values['data']['serial_number'], str) or \
527
                len(str.strip(new_values['data']['serial_number'])) == 0:
528
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
529
                                   description='API.INVALID_SERIAL_NUMBER')
530
        serial_number = str.strip(new_values['data']['serial_number'])
531
532
        if 'svg_id' not in new_values['data'].keys() or \
533
                not isinstance(new_values['data']['svg_id'], int) or \
534
                new_values['data']['svg_id'] <= 0:
535
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
536
                                   description='API.INVALID_SVG_ID')
537
        svg_id = new_values['data']['svg_id']
538
539
        if 'is_cost_data_displayed' not in new_values['data'].keys() or \
540
                not isinstance(new_values['data']['is_cost_data_displayed'], bool):
541
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
542
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED')
543
        is_cost_data_displayed = new_values['data']['is_cost_data_displayed']
544
545
        if 'phase_of_lifecycle' not in new_values['data'].keys() or \
546
                not isinstance(new_values['data']['phase_of_lifecycle'], str) or \
547
                len(str.strip(new_values['data']['phase_of_lifecycle'])) == 0:
548
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
549
                                   description='API.INVALID_MICROGRID_PHASE_OF_LIFECYCLE')
550
        phase_of_lifecycle = str.strip(new_values['data']['phase_of_lifecycle'])
551
552
        if 'description' in new_values['data'].keys() and \
553
                new_values['data']['description'] is not None and \
554
                len(str(new_values['data']['description'])) > 0:
555
            description = str.strip(new_values['data']['description'])
556
        else:
557
            description = None
558
559
        cnx = mysql.connector.connect(**config.myems_system_db)
560
        cursor = cnx.cursor()
561
562
        cursor.execute(" SELECT name "
563
                       " FROM tbl_microgrids "
564
                       " WHERE id = %s ", (id_,))
565
        if cursor.fetchone() is None:
566
            cursor.close()
567
            cnx.close()
568
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
569
                                   description='API.MICROGRID_NOT_FOUND')
570
571
        cursor.execute(" SELECT name "
572
                       " FROM tbl_microgrids "
573
                       " WHERE name = %s AND id != %s ", (name, id_))
574
        if cursor.fetchone() is not None:
575
            cursor.close()
576
            cnx.close()
577
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
578
                                   description='API.MICROGRID_NAME_IS_ALREADY_IN_USE')
579
580
        cursor.execute(" SELECT name "
581
                       " FROM tbl_contacts "
582
                       " WHERE id = %s ",
583
                       (new_values['data']['contact_id'],))
584
        row = cursor.fetchone()
585
        if row is None:
586
            cursor.close()
587
            cnx.close()
588
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
589
                                   description='API.CONTACT_NOT_FOUND')
590
591
        cursor.execute(" SELECT name "
592
                       " FROM tbl_cost_centers "
593
                       " WHERE id = %s ",
594
                       (new_values['data']['cost_center_id'],))
595
        row = cursor.fetchone()
596
        if row is None:
597
            cursor.close()
598
            cnx.close()
599
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
600
                                   description='API.COST_CENTER_NOT_FOUND')
601
602
        cursor.execute(" SELECT name "
603
                       " FROM tbl_svgs "
604
                       " WHERE id = %s ",
605
                       (new_values['data']['svg_id'],))
606
        row = cursor.fetchone()
607
        if row is None:
608
            cursor.close()
609
            cnx.close()
610
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
611
                                   description='API.SVG_NOT_FOUND')
612
613
        update_row = (" UPDATE tbl_microgrids "
614
                      " SET name = %s, address = %s, postal_code = %s, latitude = %s, longitude = %s, "
615
                      "     rated_capacity = %s, rated_power = %s, "
616
                      "     contact_id = %s, cost_center_id = %s, "
617
                      "     serial_number = %s, svg_id = %s, is_cost_data_displayed = %s, phase_of_lifecycle = %s, "
618
                      "     description = %s "
619
                      " WHERE id = %s ")
620
        cursor.execute(update_row, (name,
621
                                    address,
622
                                    postal_code,
623
                                    latitude,
624
                                    longitude,
625
                                    rated_capacity,
626
                                    rated_power,
627
                                    contact_id,
628
                                    cost_center_id,
629
                                    serial_number,
630
                                    svg_id,
631
                                    is_cost_data_displayed,
632
                                    phase_of_lifecycle,
633
                                    description,
634
                                    id_))
635
        cnx.commit()
636
637
        cursor.close()
638
        cnx.close()
639
640
        resp.status = falcon.HTTP_200
641
642
643
class MicrogridBatteryCollection:
644
    def __init__(self):
645
        """Initializes MicrogridBatteryCollection"""
646
        pass
647
648
    @staticmethod
649
    def on_options(req, resp, id_):
650
        resp.status = falcon.HTTP_200
651
652 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
653
    def on_get(req, resp, id_):
654
        access_control(req)
655
        if not id_.isdigit() or int(id_) <= 0:
656
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
657
                                   description='API.INVALID_MICROGRID_ID')
658
659
        cnx = mysql.connector.connect(**config.myems_system_db)
660
        cursor = cnx.cursor()
661
662
        cursor.execute(" SELECT name "
663
                       " FROM tbl_microgrids "
664
                       " WHERE id = %s ", (id_,))
665
        if cursor.fetchone() is None:
666
            cursor.close()
667
            cnx.close()
668
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
669
                                   description='API.MICROGRID_NOT_FOUND')
670
671
        # query meter dict
672
        query = (" SELECT id, name, uuid "
673
                 " FROM tbl_meters ")
674
        cursor.execute(query)
675
        rows_meters = cursor.fetchall()
676
677
        meter_dict = dict()
678
        if rows_meters is not None and len(rows_meters) > 0:
679
            for row in rows_meters:
680
                meter_dict[row[0]] = {"id": row[0],
681
                                      "name": row[1],
682
                                      "uuid": row[2]}
683
        # query point dict
684
        query = (" SELECT id, name "
685
                 " FROM tbl_points ")
686
        cursor.execute(query)
687
        rows_points = cursor.fetchall()
688
689
        point_dict = dict()
690
        if rows_points is not None and len(rows_points) > 0:
691
            for row in rows_points:
692
                point_dict[row[0]] = {"id": row[0],
693
                                      "name": row[1]}
694
695
        query = (" SELECT id, name, uuid, "
696
                 "        battery_state_point_id, soc_point_id, power_point_id, "
697
                 "        charge_meter_id, discharge_meter_id, rated_capacity, rated_power, nominal_voltage "
698
                 " FROM tbl_microgrids_batteries "
699
                 " WHERE microgrid_id = %s "
700
                 " ORDER BY name ")
701
        cursor.execute(query, (id_,))
702
        rows = cursor.fetchall()
703
704
        result = list()
705
        if rows is not None and len(rows) > 0:
706
            for row in rows:
707
                meta_result = {"id": row[0],
708
                               "name": row[1],
709
                               "uuid": row[2],
710
                               "battery_state_point": point_dict.get(row[3]),
711
                               "soc_point": point_dict.get(row[4]),
712
                               "power_point": point_dict.get(row[5]),
713
                               "charge_meter": meter_dict.get(row[6]),
714
                               "discharge_meter": meter_dict.get(row[7]),
715
                               "rated_capacity": row[8],
716
                               "rated_power": row[9],
717
                               "nominal_voltage": row[10]}
718
                result.append(meta_result)
719
720
        resp.text = json.dumps(result)
721
722
    @staticmethod
723
    @user_logger
724
    def on_post(req, resp, id_):
725
        """Handles POST requests"""
726
        admin_control(req)
727
        try:
728
            raw_json = req.stream.read().decode('utf-8')
729
        except Exception as ex:
730
            raise falcon.HTTPError(status=falcon.HTTP_400,
731
                                   title='API.BAD_REQUEST',
732
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
733
734
        if not id_.isdigit() or int(id_) <= 0:
735
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
736
                                   description='API.INVALID_MICROGRID_ID')
737
738
        cnx = mysql.connector.connect(**config.myems_system_db)
739
        cursor = cnx.cursor()
740
741
        cursor.execute(" SELECT name "
742
                       " FROM tbl_microgrids "
743
                       " WHERE id = %s ", (id_,))
744
        if cursor.fetchone() is None:
745
            cursor.close()
746
            cnx.close()
747
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
748
                                   description='API.MICROGRID_NOT_FOUND')
749
750
        new_values = json.loads(raw_json)
751
752
        if 'name' not in new_values['data'].keys() or \
753
                not isinstance(new_values['data']['name'], str) or \
754
                len(str.strip(new_values['data']['name'])) == 0:
755
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
756
                                   description='API.INVALID_MICROGRID_BATTERY_NAME')
757
        name = str.strip(new_values['data']['name'])
758
759
        if 'battery_state_point_id' not in new_values['data'].keys() or \
760
                not isinstance(new_values['data']['battery_state_point_id'], int) or \
761
                new_values['data']['battery_state_point_id'] <= 0:
762
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
763
                                   description='API.INVALID_BATTERY_STATE_POINT_ID')
764
        battery_state_point_id = new_values['data']['battery_state_point_id']
765
766
        if 'soc_point_id' not in new_values['data'].keys() or \
767
                not isinstance(new_values['data']['soc_point_id'], int) or \
768
                new_values['data']['soc_point_id'] <= 0:
769
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
770
                                   description='API.INVALID_SOC_POINT_ID')
771
        soc_point_id = new_values['data']['soc_point_id']
772
773
        if 'power_point_id' not in new_values['data'].keys() or \
774
                not isinstance(new_values['data']['power_point_id'], int) or \
775
                new_values['data']['power_point_id'] <= 0:
776
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
777
                                   description='API.INVALID_POWER_POINT_ID')
778
        power_point_id = new_values['data']['power_point_id']
779
780
        if 'charge_meter_id' not in new_values['data'].keys() or \
781
                not isinstance(new_values['data']['charge_meter_id'], int) or \
782
                new_values['data']['charge_meter_id'] <= 0:
783
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
784
                                   description='API.INVALID_CHARGE_METER_ID')
785
        charge_meter_id = new_values['data']['charge_meter_id']
786
787
        if 'discharge_meter_id' not in new_values['data'].keys() or \
788
                not isinstance(new_values['data']['discharge_meter_id'], int) or \
789
                new_values['data']['discharge_meter_id'] <= 0:
790
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
791
                                   description='API.INVALID_DISCHARGE_METER_ID')
792
        discharge_meter_id = new_values['data']['discharge_meter_id']
793
794
        if 'rated_capacity' not in new_values['data'].keys() or \
795
                not (isinstance(new_values['data']['rated_capacity'], float) or
796
                     isinstance(new_values['data']['rated_capacity'], int)):
797
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
798
                                   description='API.INVALID_RATED_CAPACITY')
799
        rated_capacity = float(new_values['data']['rated_capacity'])
800
801
        if 'rated_power' not in new_values['data'].keys() or \
802
                not (isinstance(new_values['data']['rated_power'], float) or
803
                     isinstance(new_values['data']['rated_power'], int)):
804
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
805
                                   description='API.INVALID_RATED_POWER')
806
        rated_power = float(new_values['data']['rated_power'])
807
808
        if 'nominal_voltage' not in new_values['data'].keys() or \
809
                not (isinstance(new_values['data']['nominal_voltage'], float) or
810
                     isinstance(new_values['data']['nominal_voltage'], int)):
811
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
812
                                   description='API.INVALID_NOMINAL_VOLTAGE')
813
        nominal_voltage = float(new_values['data']['nominal_voltage'])
814
815
        cnx = mysql.connector.connect(**config.myems_system_db)
816
        cursor = cnx.cursor()
817
818
        cursor.execute(" SELECT name "
819
                       " FROM tbl_microgrids_batteries "
820
                       " WHERE microgrid_id = %s AND name = %s ",
821
                       (id_, name,))
822
        if cursor.fetchone() is not None:
823
            cursor.close()
824
            cnx.close()
825
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
826
                                   description='API.MICROGRID_BATTERY_NAME_IS_ALREADY_IN_USE')
827
828
        cursor.execute(" SELECT name "
829
                       " FROM tbl_points "
830
                       " WHERE id = %s ",
831
                       (battery_state_point_id,))
832
        if cursor.fetchone() is None:
833
            cursor.close()
834
            cnx.close()
835
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
836
                                   description='API.BATTERY_STATE_POINT_NOT_FOUND')
837
838
        cursor.execute(" SELECT name "
839
                       " FROM tbl_points "
840
                       " WHERE id = %s ",
841
                       (soc_point_id,))
842
        if cursor.fetchone() is None:
843
            cursor.close()
844
            cnx.close()
845
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
846
                                   description='API.SOC_POINT_NOT_FOUND')
847
848
        cursor.execute(" SELECT name "
849
                       " FROM tbl_points "
850
                       " WHERE id = %s ",
851
                       (power_point_id,))
852
        if cursor.fetchone() is None:
853
            cursor.close()
854
            cnx.close()
855
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
856
                                   description='API.POWER_POINT_NOT_FOUND')
857
858
        cursor.execute(" SELECT name "
859
                       " FROM tbl_meters "
860
                       " WHERE id = %s ",
861
                       (charge_meter_id,))
862
        if cursor.fetchone() is None:
863
            cursor.close()
864
            cnx.close()
865
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
866
                                   description='API.CHARGE_METER_NOT_FOUND')
867
868
        cursor.execute(" SELECT name "
869
                       " FROM tbl_meters "
870
                       " WHERE id = %s ",
871
                       (discharge_meter_id,))
872
        if cursor.fetchone() is None:
873
            cursor.close()
874
            cnx.close()
875
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
876
                                   description='API.DISCHARGE_METER_NOT_FOUND')
877
878
        add_values = (" INSERT INTO tbl_microgrids_batteries "
879
                      "    (name, uuid, microgrid_id, "
880
                      "     battery_state_point_id, soc_point_id, power_point_id, "
881
                      "     charge_meter_id, discharge_meter_id, rated_capacity, rated_power, nominal_voltage) "
882
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
883
        cursor.execute(add_values, (name,
884
                                    str(uuid.uuid4()),
885
                                    id_,
886
                                    battery_state_point_id,
887
                                    soc_point_id,
888
                                    power_point_id,
889
                                    charge_meter_id,
890
                                    discharge_meter_id,
891
                                    rated_capacity,
892
                                    rated_power,
893
                                    nominal_voltage))
894
        new_id = cursor.lastrowid
895
        cnx.commit()
896
        cursor.close()
897
        cnx.close()
898
899
        resp.status = falcon.HTTP_201
900
        resp.location = '/microgrids/' + str(id_) + '/batteries/' + str(new_id)
901
902
903
class MicrogridBatteryItem:
904
    def __init__(self):
905
        """Initializes MicrogridBatteryItem"""
906
        pass
907
908
    @staticmethod
909
    def on_options(req, resp, id_, bid):
910
        resp.status = falcon.HTTP_200
911
912 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
913
    def on_get(req, resp, id_, bid):
914
        access_control(req)
915
        if not id_.isdigit() or int(id_) <= 0:
916
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
917
                                   description='API.INVALID_MICROGRID_ID')
918
        if not bid.isdigit() or int(bid) <= 0:
919
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
920
                                   description='API.INVALID_MICROGRID_BATTERY_ID')
921
922
        cnx = mysql.connector.connect(**config.myems_system_db)
923
        cursor = cnx.cursor()
924
925
        cursor.execute(" SELECT name "
926
                       " FROM tbl_microgrids "
927
                       " WHERE id = %s ", (id_,))
928
        if cursor.fetchone() is None:
929
            cursor.close()
930
            cnx.close()
931
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
932
                                   description='API.MICROGRID_NOT_FOUND')
933
934
        # query microgrid dict
935
        query = (" SELECT id, name, uuid "
936
                 " FROM tbl_microgrids ")
937
        cursor.execute(query)
938
        rows_microgrids = cursor.fetchall()
939
940
        microgrid_dict = dict()
941
        if rows_microgrids is not None and len(rows_microgrids) > 0:
942
            for row in rows_microgrids:
943
                microgrid_dict[row[0]] = {"id": row[0],
944
                                          "name": row[1],
945
                                          "uuid": row[2]}
946
        # query meter dict
947
        query = (" SELECT id, name, uuid "
948
                 " FROM tbl_meters ")
949
        cursor.execute(query)
950
        rows_meters = cursor.fetchall()
951
952
        meter_dict = dict()
953
        if rows_meters is not None and len(rows_meters) > 0:
954
            for row in rows_meters:
955
                meter_dict[row[0]] = {"id": row[0],
956
                                      "name": row[1],
957
                                      "uuid": row[2]}
958
        # query point dict
959
        query = (" SELECT id, name "
960
                 " FROM tbl_points ")
961
        cursor.execute(query)
962
        rows_points = cursor.fetchall()
963
964
        point_dict = dict()
965
        if rows_points is not None and len(rows_points) > 0:
966
            for row in rows_points:
967
                point_dict[row[0]] = {"id": row[0],
968
                                      "name": row[1]}
969
970
        query = (" SELECT id, name, uuid, microgrid_id, "
971
                 "       battery_state_point_id, soc_point_id, power_point_id, "
972
                 "       charge_meter_id, discharge_meter_id, rated_capacity, rated_power, nominal_voltage "
973
                 " FROM tbl_microgrids_batteries "
974
                 " WHERE id = %s ")
975
        cursor.execute(query, (bid,))
976
        row = cursor.fetchone()
977
        cursor.close()
978
        cnx.close()
979
980
        if row is None:
981
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
982
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
983
        else:
984
            meta_result = {"id": row[0],
985
                           "name": row[1],
986
                           "uuid": row[2],
987
                           "microgrid": microgrid_dict.get(row[3]),
988
                           "battery_state_point": point_dict.get(row[4]),
989
                           "soc_point": point_dict.get(row[5]),
990
                           "power_point": point_dict.get(row[6]),
991
                           "charge_meter": meter_dict.get(row[7]),
992
                           "discharge_meter": meter_dict.get(row[8]),
993
                           "rated_capacity": row[9],
994
                           "rated_power": row[10],
995
                           "nominal_voltage": row[11]}
996
997
        resp.text = json.dumps(meta_result)
998
999
    @staticmethod
1000
    @user_logger
1001
    def on_delete(req, resp, id_, bid):
1002
        admin_control(req)
1003
        if not id_.isdigit() or int(id_) <= 0:
1004
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1005
                                   description='API.INVALID_MICROGRID_ID')
1006
        if not bid.isdigit() or int(bid) <= 0:
1007
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1008
                                   description='API.INVALID_MICROGRID_BATTERY_ID')
1009
1010
        cnx = mysql.connector.connect(**config.myems_system_db)
1011
        cursor = cnx.cursor()
1012
1013
        cursor.execute(" SELECT name "
1014
                       " FROM tbl_microgrids "
1015
                       " WHERE id = %s ", (id_,))
1016
        if cursor.fetchone() is None:
1017
            cursor.close()
1018
            cnx.close()
1019
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1020
                                   description='API.MICROGRID_NOT_FOUND')
1021
1022
        cursor.execute(" SELECT name "
1023
                       " FROM tbl_microgrids_batteries "
1024
                       " WHERE id = %s ", (bid,))
1025
        if cursor.fetchone() is None:
1026
            cursor.close()
1027
            cnx.close()
1028
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1029
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
1030
1031
        cursor.execute(" DELETE FROM tbl_microgrids_batteries "
1032
                       " WHERE id = %s ", (bid,))
1033
        cnx.commit()
1034
1035
        cursor.close()
1036
        cnx.close()
1037
1038
        resp.status = falcon.HTTP_204
1039
1040
    @staticmethod
1041
    @user_logger
1042
    def on_put(req, resp, id_, bid):
1043
        """Handles PUT requests"""
1044
        admin_control(req)
1045
        try:
1046
            raw_json = req.stream.read().decode('utf-8')
1047
        except Exception as ex:
1048
            raise falcon.HTTPError(status=falcon.HTTP_400,
1049
                                   title='API.BAD_REQUEST',
1050
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1051
        if not id_.isdigit() or int(id_) <= 0:
1052
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1053
                                   description='API.INVALID_MICROGRID_ID')
1054
        if not bid.isdigit() or int(bid) <= 0:
1055
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1056
                                   description='API.INVALID_MICROGRID_BATTERY_ID')
1057
1058
        new_values = json.loads(raw_json)
1059
1060
        if 'name' not in new_values['data'].keys() or \
1061
                not isinstance(new_values['data']['name'], str) or \
1062
                len(str.strip(new_values['data']['name'])) == 0:
1063
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1064
                                   description='API.INVALID_MICROGRID_BATTERY_NAME')
1065
        name = str.strip(new_values['data']['name'])
1066
1067
        if 'battery_state_point_id' not in new_values['data'].keys() or \
1068
                not isinstance(new_values['data']['battery_state_point_id'], int) or \
1069
                new_values['data']['battery_state_point_id'] <= 0:
1070
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1071
                                   description='API.INVALID_BATTERY_STATE_POINT_ID')
1072
        battery_state_point_id = new_values['data']['battery_state_point_id']
1073
1074
        if 'soc_point_id' not in new_values['data'].keys() or \
1075
                not isinstance(new_values['data']['soc_point_id'], int) or \
1076
                new_values['data']['soc_point_id'] <= 0:
1077
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1078
                                   description='API.INVALID_SOC_POINT_ID')
1079
        soc_point_id = new_values['data']['soc_point_id']
1080
1081
        if 'power_point_id' not in new_values['data'].keys() or \
1082
                not isinstance(new_values['data']['power_point_id'], int) or \
1083
                new_values['data']['power_point_id'] <= 0:
1084
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1085
                                   description='API.INVALID_POWER_POINT_ID')
1086
        power_point_id = new_values['data']['power_point_id']
1087
1088
        if 'charge_meter_id' not in new_values['data'].keys() or \
1089
                not isinstance(new_values['data']['charge_meter_id'], int) or \
1090
                new_values['data']['charge_meter_id'] <= 0:
1091
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1092
                                   description='API.INVALID_CHARGE_METER_ID')
1093
        charge_meter_id = new_values['data']['charge_meter_id']
1094
1095
        if 'discharge_meter_id' not in new_values['data'].keys() or \
1096
                not isinstance(new_values['data']['discharge_meter_id'], int) or \
1097
                new_values['data']['discharge_meter_id'] <= 0:
1098
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1099
                                   description='API.INVALID_DISCHARGE_METER_ID')
1100
        discharge_meter_id = new_values['data']['discharge_meter_id']
1101
1102
        if 'rated_capacity' not in new_values['data'].keys() or \
1103
                not (isinstance(new_values['data']['rated_capacity'], float) or
1104
                     isinstance(new_values['data']['rated_capacity'], int)):
1105
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1106
                                   description='API.INVALID_RATED_CAPACITY')
1107
        rated_capacity = float(new_values['data']['rated_capacity'])
1108
1109
        if 'rated_power' not in new_values['data'].keys() or \
1110
                not (isinstance(new_values['data']['rated_power'], float) or
1111
                     isinstance(new_values['data']['rated_power'], int)):
1112
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1113
                                   description='API.INVALID_RATED_POWER')
1114
        rated_power = float(new_values['data']['rated_power'])
1115
1116
        if 'nominal_voltage' not in new_values['data'].keys() or \
1117
                not (isinstance(new_values['data']['nominal_voltage'], float) or
1118
                     isinstance(new_values['data']['nominal_voltage'], int)):
1119
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1120
                                   description='API.INVALID_NOMINAL_VOLTAGE')
1121
        nominal_voltage = float(new_values['data']['nominal_voltage'])
1122
1123
        cnx = mysql.connector.connect(**config.myems_system_db)
1124
        cursor = cnx.cursor()
1125
1126
        cursor.execute(" SELECT name "
1127
                       " FROM tbl_microgrids "
1128
                       " WHERE id = %s ",
1129
                       (id_,))
1130
        if cursor.fetchone() is None:
1131
            cursor.close()
1132
            cnx.close()
1133
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1134
                                   description='API.MICROGRID_NOT_FOUND')
1135
1136
        cursor.execute(" SELECT name "
1137
                       " FROM tbl_microgrids_batteries "
1138
                       " WHERE id = %s ", (bid,))
1139
        if cursor.fetchone() is None:
1140
            cursor.close()
1141
            cnx.close()
1142
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1143
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
1144
1145
        cursor.execute(" SELECT name "
1146
                       " FROM tbl_microgrids_batteries "
1147
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
1148
                       (id_, name, bid))
1149
        if cursor.fetchone() is not None:
1150
            cursor.close()
1151
            cnx.close()
1152
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1153
                                   description='API.MICROGRID_BATTERY_NAME_IS_ALREADY_IN_USE')
1154
1155
        cursor.execute(" SELECT name "
1156
                       " FROM tbl_points "
1157
                       " WHERE id = %s ",
1158
                       (battery_state_point_id,))
1159
        if cursor.fetchone() is None:
1160
            cursor.close()
1161
            cnx.close()
1162
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1163
                                   description='API.BATTERY_STATE_POINT_NOT_FOUND')
1164
1165
        cursor.execute(" SELECT name "
1166
                       " FROM tbl_points "
1167
                       " WHERE id = %s ",
1168
                       (soc_point_id,))
1169
        if cursor.fetchone() is None:
1170
            cursor.close()
1171
            cnx.close()
1172
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1173
                                   description='API.SOC_POINT_NOT_FOUND')
1174
1175
        cursor.execute(" SELECT name "
1176
                       " FROM tbl_points "
1177
                       " WHERE id = %s ",
1178
                       (power_point_id,))
1179
        if cursor.fetchone() is None:
1180
            cursor.close()
1181
            cnx.close()
1182
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1183
                                   description='API.POWER_POINT_NOT_FOUND')
1184
1185
        cursor.execute(" SELECT name "
1186
                       " FROM tbl_meters "
1187
                       " WHERE id = %s ",
1188
                       (charge_meter_id,))
1189
        if cursor.fetchone() is None:
1190
            cursor.close()
1191
            cnx.close()
1192
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1193
                                   description='API.CHARGE_METER_NOT_FOUND')
1194
1195
        cursor.execute(" SELECT name "
1196
                       " FROM tbl_meters "
1197
                       " WHERE id = %s ",
1198
                       (discharge_meter_id,))
1199
        if cursor.fetchone() is None:
1200
            cursor.close()
1201
            cnx.close()
1202
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1203
                                   description='API.DISCHARGE_METER_NOT_FOUND')
1204
1205
        update_row = (" UPDATE tbl_microgrids_batteries "
1206
                      " SET name = %s, microgrid_id = %s, "
1207
                      "     battery_state_point_id = %s, soc_point_id = %s, power_point_id = %s, "
1208
                      "     charge_meter_id = %s, discharge_meter_id = %s, rated_capacity = %s, rated_power = %s,"
1209
                      "     nominal_voltage = %s "
1210
                      " WHERE id = %s ")
1211
        cursor.execute(update_row, (name,
1212
                                    id_,
1213
                                    battery_state_point_id,
1214
                                    soc_point_id,
1215
                                    power_point_id,
1216
                                    charge_meter_id,
1217
                                    discharge_meter_id,
1218
                                    rated_capacity,
1219
                                    rated_power,
1220
                                    nominal_voltage,
1221
                                    bid))
1222
        cnx.commit()
1223
1224
        cursor.close()
1225
        cnx.close()
1226
1227
        resp.status = falcon.HTTP_200
1228
1229
1230
class MicrogridCommandCollection:
1231
    def __init__(self):
1232
        """Initializes Class"""
1233
        pass
1234
1235
    @staticmethod
1236
    def on_options(req, resp, id_):
1237
        resp.status = falcon.HTTP_200
1238
1239
    @staticmethod
1240
    def on_get(req, resp, id_):
1241
        access_control(req)
1242
        if not id_.isdigit() or int(id_) <= 0:
1243
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1244
                                   description='API.INVALID_MICROGRID_ID')
1245
1246
        cnx = mysql.connector.connect(**config.myems_system_db)
1247
        cursor = cnx.cursor()
1248
1249
        cursor.execute(" SELECT name "
1250
                       " FROM tbl_microgrids "
1251
                       " WHERE id = %s ", (id_,))
1252
        if cursor.fetchone() is None:
1253
            cursor.close()
1254
            cnx.close()
1255
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1256
                                   description='API.MICROGRID_NOT_FOUND')
1257
1258
        query = (" SELECT c.id, c.name, c.uuid "
1259
                 " FROM tbl_microgrids m, tbl_microgrids_commands mc, tbl_commands c "
1260
                 " WHERE mc.microgrid_id = m.id AND c.id = mc.command_id AND m.id = %s "
1261
                 " ORDER BY c.id ")
1262
        cursor.execute(query, (id_,))
1263
        rows = cursor.fetchall()
1264
1265
        result = list()
1266
        if rows is not None and len(rows) > 0:
1267
            for row in rows:
1268
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1269
                result.append(meta_result)
1270
1271
        resp.text = json.dumps(result)
1272
1273
1274 View Code Duplication
class MicrogridEVChargerCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1275
    def __init__(self):
1276
        """Initializes MicrogridEVChargerCollection"""
1277
        pass
1278
1279
    @staticmethod
1280
    def on_options(req, resp, id_):
1281
        resp.status = falcon.HTTP_200
1282
1283
    @staticmethod
1284
    def on_get(req, resp, id_):
1285
        access_control(req)
1286
        if not id_.isdigit() or int(id_) <= 0:
1287
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1288
                                   description='API.INVALID_MICROGRID_ID')
1289
1290
        cnx = mysql.connector.connect(**config.myems_system_db)
1291
        cursor = cnx.cursor()
1292
1293
        cursor.execute(" SELECT name "
1294
                       " FROM tbl_microgrids "
1295
                       " WHERE id = %s ", (id_,))
1296
        if cursor.fetchone() is None:
1297
            cursor.close()
1298
            cnx.close()
1299
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1300
                                   description='API.MICROGRID_NOT_FOUND')
1301
1302
        # query meter dict
1303
        query = (" SELECT id, name, uuid "
1304
                 " FROM tbl_meters ")
1305
        cursor.execute(query)
1306
        rows_meters = cursor.fetchall()
1307
1308
        meter_dict = dict()
1309
        if rows_meters is not None and len(rows_meters) > 0:
1310
            for row in rows_meters:
1311
                meter_dict[row[0]] = {"id": row[0],
1312
                                      "name": row[1],
1313
                                      "uuid": row[2]}
1314
        # query point dict
1315
        query = (" SELECT id, name "
1316
                 " FROM tbl_points ")
1317
        cursor.execute(query)
1318
        rows_points = cursor.fetchall()
1319
1320
        point_dict = dict()
1321
        if rows_points is not None and len(rows_points) > 0:
1322
            for row in rows_points:
1323
                point_dict[row[0]] = {"id": row[0],
1324
                                      "name": row[1]}
1325
1326
        query = (" SELECT id, name, uuid, "
1327
                 "       power_point_id, meter_id, rated_output_power "
1328
                 " FROM tbl_microgrids_evchargers "
1329
                 " WHERE microgrid_id = %s "
1330
                 " ORDER BY name ")
1331
        cursor.execute(query, (id_,))
1332
        rows = cursor.fetchall()
1333
1334
        result = list()
1335
        if rows is not None and len(rows) > 0:
1336
            for row in rows:
1337
                meta_result = {"id": row[0],
1338
                               "name": row[1],
1339
                               "uuid": row[2],
1340
                               "power_point": point_dict.get(row[3]),
1341
                               "meter": meter_dict.get(row[4]),
1342
                               "rated_output_power": row[5]}
1343
                result.append(meta_result)
1344
1345
        resp.text = json.dumps(result)
1346
1347
    @staticmethod
1348
    @user_logger
1349
    def on_post(req, resp, id_):
1350
        """Handles POST requests"""
1351
        admin_control(req)
1352
        try:
1353
            raw_json = req.stream.read().decode('utf-8')
1354
        except Exception as ex:
1355
            raise falcon.HTTPError(status=falcon.HTTP_400,
1356
                                   title='API.BAD_REQUEST',
1357
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1358
1359
        if not id_.isdigit() or int(id_) <= 0:
1360
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1361
                                   description='API.INVALID_MICROGRID_ID')
1362
1363
        cnx = mysql.connector.connect(**config.myems_system_db)
1364
        cursor = cnx.cursor()
1365
1366
        cursor.execute(" SELECT name "
1367
                       " FROM tbl_microgrids "
1368
                       " WHERE id = %s ", (id_,))
1369
        if cursor.fetchone() is None:
1370
            cursor.close()
1371
            cnx.close()
1372
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1373
                                   description='API.MICROGRID_NOT_FOUND')
1374
1375
        new_values = json.loads(raw_json)
1376
1377
        if 'name' not in new_values['data'].keys() or \
1378
                not isinstance(new_values['data']['name'], str) or \
1379
                len(str.strip(new_values['data']['name'])) == 0:
1380
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1381
                                   description='API.INVALID_MICROGRID_EVCHARGER_NAME')
1382
        name = str.strip(new_values['data']['name'])
1383
1384
        if 'power_point_id' not in new_values['data'].keys() or \
1385
                not isinstance(new_values['data']['power_point_id'], int) or \
1386
                new_values['data']['power_point_id'] <= 0:
1387
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1388
                                   description='API.INVALID_POWER_POINT_ID')
1389
        power_point_id = new_values['data']['power_point_id']
1390
1391
        if 'meter_id' not in new_values['data'].keys() or \
1392
                not isinstance(new_values['data']['meter_id'], int) or \
1393
                new_values['data']['meter_id'] <= 0:
1394
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1395
                                   description='API.INVALID_METER_ID')
1396
        meter_id = new_values['data']['meter_id']
1397
1398
        if 'rated_output_power' not in new_values['data'].keys() or \
1399
                not (isinstance(new_values['data']['rated_output_power'], float) or
1400
                     isinstance(new_values['data']['rated_output_power'], int)):
1401
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1402
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1403
        rated_output_power = float(new_values['data']['rated_output_power'])
1404
1405
        cnx = mysql.connector.connect(**config.myems_system_db)
1406
        cursor = cnx.cursor()
1407
1408
        cursor.execute(" SELECT name "
1409
                       " FROM tbl_microgrids "
1410
                       " WHERE id = %s ",
1411
                       (id_,))
1412
        if cursor.fetchone() is None:
1413
            cursor.close()
1414
            cnx.close()
1415
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1416
                                   description='API.MICROGRID_NOT_FOUND')
1417
1418
        cursor.execute(" SELECT name "
1419
                       " FROM tbl_microgrids_evchargers "
1420
                       " WHERE microgrid_id = %s AND name = %s ",
1421
                       (id_, name,))
1422
        if cursor.fetchone() is not None:
1423
            cursor.close()
1424
            cnx.close()
1425
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1426
                                   description='API.MICROGRID_EVCHARGER_NAME_IS_ALREADY_IN_USE')
1427
1428
        cursor.execute(" SELECT name "
1429
                       " FROM tbl_points "
1430
                       " WHERE id = %s ",
1431
                       (power_point_id,))
1432
        if cursor.fetchone() is None:
1433
            cursor.close()
1434
            cnx.close()
1435
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1436
                                   description='API.POWER_POINT_NOT_FOUND')
1437
1438
        cursor.execute(" SELECT name "
1439
                       " FROM tbl_meters "
1440
                       " WHERE id = %s ",
1441
                       (meter_id,))
1442
        if cursor.fetchone() is None:
1443
            cursor.close()
1444
            cnx.close()
1445
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1446
                                   description='API.METER_NOT_FOUND')
1447
1448
        add_values = (" INSERT INTO tbl_microgrids_evchargers "
1449
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power) "
1450
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
1451
        cursor.execute(add_values, (name,
1452
                                    str(uuid.uuid4()),
1453
                                    id_,
1454
                                    power_point_id,
1455
                                    meter_id,
1456
                                    rated_output_power))
1457
        new_id = cursor.lastrowid
1458
        cnx.commit()
1459
        cursor.close()
1460
        cnx.close()
1461
1462
        resp.status = falcon.HTTP_201
1463
        resp.location = '/microgrids/' + id_ + '/evchargers/' + str(new_id)
1464
1465
1466 View Code Duplication
class MicrogridEVChargerItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1467
    def __init__(self):
1468
        """Initializes MicrogridEVChargerItem"""
1469
        pass
1470
1471
    @staticmethod
1472
    def on_options(req, resp, id_, eid):
1473
        resp.status = falcon.HTTP_200
1474
1475
    @staticmethod
1476
    def on_get(req, resp, id_, eid):
1477
        access_control(req)
1478
        if not id_.isdigit() or int(id_) <= 0:
1479
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1480
                                   description='API.INVALID_MICROGRID_ID')
1481
        if not eid.isdigit() or int(eid) <= 0:
1482
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1483
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1484
1485
        cnx = mysql.connector.connect(**config.myems_system_db)
1486
        cursor = cnx.cursor()
1487
1488
        cursor.execute(" SELECT name "
1489
                       " FROM tbl_microgrids "
1490
                       " WHERE id = %s ", (id_,))
1491
        if cursor.fetchone() is None:
1492
            cursor.close()
1493
            cnx.close()
1494
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1495
                                   description='API.MICROGRID_NOT_FOUND')
1496
1497
        # query microgrid dict
1498
        query = (" SELECT id, name, uuid "
1499
                 " FROM tbl_microgrids ")
1500
        cursor.execute(query)
1501
        rows_microgrids = cursor.fetchall()
1502
1503
        microgrid_dict = dict()
1504
        if rows_microgrids is not None and len(rows_microgrids) > 0:
1505
            for row in rows_microgrids:
1506
                microgrid_dict[row[0]] = {"id": row[0],
1507
                                          "name": row[1],
1508
                                          "uuid": row[2]}
1509
        # query meter dict
1510
        query = (" SELECT id, name, uuid "
1511
                 " FROM tbl_meters ")
1512
        cursor.execute(query)
1513
        rows_meters = cursor.fetchall()
1514
1515
        meter_dict = dict()
1516
        if rows_meters is not None and len(rows_meters) > 0:
1517
            for row in rows_meters:
1518
                meter_dict[row[0]] = {"id": row[0],
1519
                                      "name": row[1],
1520
                                      "uuid": row[2]}
1521
        # query point dict
1522
        query = (" SELECT id, name "
1523
                 " FROM tbl_points ")
1524
        cursor.execute(query)
1525
        rows_points = cursor.fetchall()
1526
1527
        point_dict = dict()
1528
        if rows_points is not None and len(rows_points) > 0:
1529
            for row in rows_points:
1530
                point_dict[row[0]] = {"id": row[0],
1531
                                      "name": row[1]}
1532
1533
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power "
1534
                 " FROM tbl_microgrids_evchargers "
1535
                 " WHERE id = %s ")
1536
        cursor.execute(query, (eid,))
1537
        row = cursor.fetchone()
1538
        cursor.close()
1539
        cnx.close()
1540
1541
        if row is None:
1542
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1543
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1544
        else:
1545
            meta_result = {"id": row[0],
1546
                           "name": row[1],
1547
                           "uuid": row[2],
1548
                           "microgrid": microgrid_dict.get(row[3]),
1549
                           "power_point": point_dict.get(row[4]),
1550
                           "meter": meter_dict.get(row[5]),
1551
                           "rated_output_power": row[6]}
1552
1553
        resp.text = json.dumps(meta_result)
1554
1555
    @staticmethod
1556
    @user_logger
1557
    def on_delete(req, resp, id_, eid):
1558
        admin_control(req)
1559
        if not id_.isdigit() or int(id_) <= 0:
1560
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1561
                                   description='API.INVALID_MICROGRID_ID')
1562
        if not eid.isdigit() or int(eid) <= 0:
1563
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1564
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1565
        cnx = mysql.connector.connect(**config.myems_system_db)
1566
        cursor = cnx.cursor()
1567
1568
        cursor.execute(" SELECT name "
1569
                       " FROM tbl_microgrids "
1570
                       " WHERE id = %s ", (id_,))
1571
        if cursor.fetchone() is None:
1572
            cursor.close()
1573
            cnx.close()
1574
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1575
                                   description='API.MICROGRID_NOT_FOUND')
1576
1577
        cursor.execute(" SELECT name "
1578
                       " FROM tbl_microgrids_evchargers "
1579
                       " WHERE id = %s ", (eid,))
1580
        if cursor.fetchone() is None:
1581
            cursor.close()
1582
            cnx.close()
1583
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1584
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1585
1586
        cursor.execute(" DELETE FROM tbl_microgrids_evchargers "
1587
                       " WHERE id = %s ", (eid,))
1588
        cnx.commit()
1589
1590
        cursor.close()
1591
        cnx.close()
1592
1593
        resp.status = falcon.HTTP_204
1594
1595
    @staticmethod
1596
    @user_logger
1597
    def on_put(req, resp, id_, eid):
1598
        """Handles PUT requests"""
1599
        admin_control(req)
1600
        try:
1601
            raw_json = req.stream.read().decode('utf-8')
1602
        except Exception as ex:
1603
            raise falcon.HTTPError(status=falcon.HTTP_400,
1604
                                   title='API.BAD_REQUEST',
1605
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1606
        if not id_.isdigit() or int(id_) <= 0:
1607
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1608
                                   description='API.INVALID_MICROGRID_ID')
1609
        if not eid.isdigit() or int(eid) <= 0:
1610
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1611
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1612
1613
        new_values = json.loads(raw_json)
1614
1615
        if 'name' not in new_values['data'].keys() or \
1616
                not isinstance(new_values['data']['name'], str) or \
1617
                len(str.strip(new_values['data']['name'])) == 0:
1618
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1619
                                   description='API.INVALID_MICROGRID_EVCHARGER_NAME')
1620
        name = str.strip(new_values['data']['name'])
1621
1622
        if 'power_point_id' not in new_values['data'].keys() or \
1623
                not isinstance(new_values['data']['power_point_id'], int) or \
1624
                new_values['data']['power_point_id'] <= 0:
1625
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1626
                                   description='API.INVALID_POWER_POINT_ID')
1627
        power_point_id = new_values['data']['power_point_id']
1628
1629
        if 'meter_id' not in new_values['data'].keys() or \
1630
                not isinstance(new_values['data']['meter_id'], int) or \
1631
                new_values['data']['meter_id'] <= 0:
1632
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1633
                                   description='API.INVALID_METER_ID')
1634
        meter_id = new_values['data']['meter_id']
1635
1636
        if 'rated_output_power' not in new_values['data'].keys() or \
1637
                not (isinstance(new_values['data']['rated_output_power'], float) or
1638
                     isinstance(new_values['data']['rated_output_power'], int)):
1639
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1640
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1641
        rated_output_power = float(new_values['data']['rated_output_power'])
1642
1643
        cnx = mysql.connector.connect(**config.myems_system_db)
1644
        cursor = cnx.cursor()
1645
1646
        cursor.execute(" SELECT name "
1647
                       " FROM tbl_microgrids "
1648
                       " WHERE id = %s ", (id_,))
1649
        if cursor.fetchone() is None:
1650
            cursor.close()
1651
            cnx.close()
1652
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1653
                                   description='API.MICROGRID_NOT_FOUND')
1654
1655
        cursor.execute(" SELECT name "
1656
                       " FROM tbl_microgrids_evchargers "
1657
                       " WHERE id = %s ", (eid,))
1658
        if cursor.fetchone() is None:
1659
            cursor.close()
1660
            cnx.close()
1661
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1662
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1663
1664
        cursor.execute(" SELECT name "
1665
                       " FROM tbl_microgrids_evchargers "
1666
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
1667
                       (id_, name, eid))
1668
        if cursor.fetchone() is not None:
1669
            cursor.close()
1670
            cnx.close()
1671
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1672
                                   description='API.MICROGRID_EVCHARGER_NAME_IS_ALREADY_IN_USE')
1673
1674
        cursor.execute(" SELECT name "
1675
                       " FROM tbl_points "
1676
                       " WHERE id = %s ",
1677
                       (power_point_id,))
1678
        if cursor.fetchone() is None:
1679
            cursor.close()
1680
            cnx.close()
1681
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1682
                                   description='API.POWER_POINT_NOT_FOUND')
1683
1684
        cursor.execute(" SELECT name "
1685
                       " FROM tbl_meters "
1686
                       " WHERE id = %s ",
1687
                       (meter_id,))
1688
        if cursor.fetchone() is None:
1689
            cursor.close()
1690
            cnx.close()
1691
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1692
                                   description='API.METER_NOT_FOUND')
1693
1694
        update_row = (" UPDATE tbl_microgrids_evchargers "
1695
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_output_power = %s "
1696
                      " WHERE id = %s ")
1697
        cursor.execute(update_row, (name,
1698
                                    id_,
1699
                                    power_point_id,
1700
                                    meter_id,
1701
                                    rated_output_power,
1702
                                    eid))
1703
        cnx.commit()
1704
1705
        cursor.close()
1706
        cnx.close()
1707
1708
        resp.status = falcon.HTTP_200
1709
1710
1711 View Code Duplication
class MicrogridGeneratorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1712
    def __init__(self):
1713
        """Initializes MicrogridGeneratorCollection"""
1714
        pass
1715
1716
    @staticmethod
1717
    def on_options(req, resp, id_):
1718
        resp.status = falcon.HTTP_200
1719
1720
    @staticmethod
1721
    def on_get(req, resp, id_):
1722
        access_control(req)
1723
        if not id_.isdigit() or int(id_) <= 0:
1724
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1725
                                   description='API.INVALID_MICROGRID_ID')
1726
1727
        cnx = mysql.connector.connect(**config.myems_system_db)
1728
        cursor = cnx.cursor()
1729
1730
        cursor.execute(" SELECT name "
1731
                       " FROM tbl_microgrids "
1732
                       " WHERE id = %s ", (id_,))
1733
        if cursor.fetchone() is None:
1734
            cursor.close()
1735
            cnx.close()
1736
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1737
                                   description='API.MICROGRID_NOT_FOUND')
1738
1739
        # query meter dict
1740
        query = (" SELECT id, name, uuid "
1741
                 " FROM tbl_meters ")
1742
        cursor.execute(query)
1743
        rows_meters = cursor.fetchall()
1744
1745
        meter_dict = dict()
1746
        if rows_meters is not None and len(rows_meters) > 0:
1747
            for row in rows_meters:
1748
                meter_dict[row[0]] = {"id": row[0],
1749
                                      "name": row[1],
1750
                                      "uuid": row[2]}
1751
        # query point dict
1752
        query = (" SELECT id, name "
1753
                 " FROM tbl_points ")
1754
        cursor.execute(query)
1755
        rows_points = cursor.fetchall()
1756
1757
        point_dict = dict()
1758
        if rows_points is not None and len(rows_points) > 0:
1759
            for row in rows_points:
1760
                point_dict[row[0]] = {"id": row[0],
1761
                                      "name": row[1]}
1762
1763
        query = (" SELECT id, name, uuid, "
1764
                 "        power_point_id, meter_id, rated_output_power "
1765
                 " FROM tbl_microgrids_generators "
1766
                 " WHERE microgrid_id = %s "
1767
                 " ORDER BY name ")
1768
        cursor.execute(query, (id_,))
1769
        rows = cursor.fetchall()
1770
1771
        result = list()
1772
        if rows is not None and len(rows) > 0:
1773
            for row in rows:
1774
                meta_result = {"id": row[0],
1775
                               "name": row[1],
1776
                               "uuid": row[2],
1777
                               "power_point": point_dict.get(row[3]),
1778
                               "meter": meter_dict.get(row[4]),
1779
                               "rated_output_power": row[5]}
1780
                result.append(meta_result)
1781
1782
        resp.text = json.dumps(result)
1783
1784
    @staticmethod
1785
    @user_logger
1786
    def on_post(req, resp, id_):
1787
        """Handles POST requests"""
1788
        admin_control(req)
1789
        try:
1790
            raw_json = req.stream.read().decode('utf-8')
1791
        except Exception as ex:
1792
            raise falcon.HTTPError(status=falcon.HTTP_400,
1793
                                   title='API.BAD_REQUEST',
1794
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1795
        if not id_.isdigit() or int(id_) <= 0:
1796
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1797
                                   description='API.INVALID_MICROGRID_ID')
1798
1799
        cnx = mysql.connector.connect(**config.myems_system_db)
1800
        cursor = cnx.cursor()
1801
1802
        cursor.execute(" SELECT name "
1803
                       " FROM tbl_microgrids "
1804
                       " WHERE id = %s ", (id_,))
1805
        if cursor.fetchone() is None:
1806
            cursor.close()
1807
            cnx.close()
1808
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1809
                                   description='API.MICROGRID_NOT_FOUND')
1810
1811
        new_values = json.loads(raw_json)
1812
1813
        if 'name' not in new_values['data'].keys() or \
1814
                not isinstance(new_values['data']['name'], str) or \
1815
                len(str.strip(new_values['data']['name'])) == 0:
1816
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1817
                                   description='API.INVALID_MICROGRID_GENERATOR_NAME')
1818
        name = str.strip(new_values['data']['name'])
1819
1820
        if 'power_point_id' not in new_values['data'].keys() or \
1821
                not isinstance(new_values['data']['power_point_id'], int) or \
1822
                new_values['data']['power_point_id'] <= 0:
1823
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1824
                                   description='API.INVALID_POWER_POINT_ID')
1825
        power_point_id = new_values['data']['power_point_id']
1826
1827
        if 'meter_id' not in new_values['data'].keys() or \
1828
                not isinstance(new_values['data']['meter_id'], int) or \
1829
                new_values['data']['meter_id'] <= 0:
1830
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1831
                                   description='API.INVALID_METER_ID')
1832
        meter_id = new_values['data']['meter_id']
1833
1834
        if 'rated_output_power' not in new_values['data'].keys() or \
1835
                not (isinstance(new_values['data']['rated_output_power'], float) or
1836
                     isinstance(new_values['data']['rated_output_power'], int)):
1837
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1838
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1839
        rated_output_power = float(new_values['data']['rated_output_power'])
1840
1841
        cnx = mysql.connector.connect(**config.myems_system_db)
1842
        cursor = cnx.cursor()
1843
1844
        cursor.execute(" SELECT name "
1845
                       " FROM tbl_microgrids "
1846
                       " WHERE id = %s ",
1847
                       (id_,))
1848
        if cursor.fetchone() is None:
1849
            cursor.close()
1850
            cnx.close()
1851
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1852
                                   description='API.MICROGRID_NOT_FOUND')
1853
1854
        cursor.execute(" SELECT name "
1855
                       " FROM tbl_microgrids_generators "
1856
                       " WHERE microgrid_id = %s AND name = %s ",
1857
                       (id_, name,))
1858
        if cursor.fetchone() is not None:
1859
            cursor.close()
1860
            cnx.close()
1861
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1862
                                   description='API.MICROGRID_GENERATOR_NAME_IS_ALREADY_IN_USE')
1863
1864
        cursor.execute(" SELECT name "
1865
                       " FROM tbl_points "
1866
                       " WHERE id = %s ",
1867
                       (power_point_id,))
1868
        if cursor.fetchone() is None:
1869
            cursor.close()
1870
            cnx.close()
1871
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1872
                                   description='API.POWER_POINT_NOT_FOUND')
1873
1874
        cursor.execute(" SELECT name "
1875
                       " FROM tbl_meters "
1876
                       " WHERE id = %s ",
1877
                       (meter_id,))
1878
        if cursor.fetchone() is None:
1879
            cursor.close()
1880
            cnx.close()
1881
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1882
                                   description='API.METER_NOT_FOUND')
1883
1884
        add_values = (" INSERT INTO tbl_microgrids_generators "
1885
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power) "
1886
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
1887
        cursor.execute(add_values, (name,
1888
                                    str(uuid.uuid4()),
1889
                                    id_,
1890
                                    power_point_id,
1891
                                    meter_id,
1892
                                    rated_output_power))
1893
        new_id = cursor.lastrowid
1894
        cnx.commit()
1895
        cursor.close()
1896
        cnx.close()
1897
1898
        resp.status = falcon.HTTP_201
1899
        resp.location = '/microgrids/' + str(id_) + '/generators/' + str(new_id)
1900
1901
1902 View Code Duplication
class MicrogridGeneratorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1903
    def __init__(self):
1904
        """Initializes MicrogridGeneratorItem"""
1905
        pass
1906
1907
    @staticmethod
1908
    def on_options(req, resp, id_, gid):
1909
        resp.status = falcon.HTTP_200
1910
1911
    @staticmethod
1912
    def on_get(req, resp, id_, gid):
1913
        access_control(req)
1914
        if not id_.isdigit() or int(id_) <= 0:
1915
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1916
                                   description='API.INVALID_MICROGRID_ID')
1917
        if not gid.isdigit() or int(gid) <= 0:
1918
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1919
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
1920
1921
        cnx = mysql.connector.connect(**config.myems_system_db)
1922
        cursor = cnx.cursor()
1923
1924
        cursor.execute(" SELECT name "
1925
                       " FROM tbl_microgrids "
1926
                       " WHERE id = %s ", (id_,))
1927
        if cursor.fetchone() is None:
1928
            cursor.close()
1929
            cnx.close()
1930
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1931
                                   description='API.MICROGRID_NOT_FOUND')
1932
1933
        # query microgrid dict
1934
        query = (" SELECT id, name, uuid "
1935
                 " FROM tbl_microgrids ")
1936
        cursor.execute(query)
1937
        rows_microgrids = cursor.fetchall()
1938
1939
        microgrid_dict = dict()
1940
        if rows_microgrids is not None and len(rows_microgrids) > 0:
1941
            for row in rows_microgrids:
1942
                microgrid_dict[row[0]] = {"id": row[0],
1943
                                          "name": row[1],
1944
                                          "uuid": row[2]}
1945
        # query meter dict
1946
        query = (" SELECT id, name, uuid "
1947
                 " FROM tbl_meters ")
1948
        cursor.execute(query)
1949
        rows_meters = cursor.fetchall()
1950
1951
        meter_dict = dict()
1952
        if rows_meters is not None and len(rows_meters) > 0:
1953
            for row in rows_meters:
1954
                meter_dict[row[0]] = {"id": row[0],
1955
                                      "name": row[1],
1956
                                      "uuid": row[2]}
1957
        # query point dict
1958
        query = (" SELECT id, name "
1959
                 " FROM tbl_points ")
1960
        cursor.execute(query)
1961
        rows_points = cursor.fetchall()
1962
1963
        point_dict = dict()
1964
        if rows_points is not None and len(rows_points) > 0:
1965
            for row in rows_points:
1966
                point_dict[row[0]] = {"id": row[0],
1967
                                      "name": row[1]}
1968
1969
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power "
1970
                 " FROM tbl_microgrids_generators "
1971
                 " WHERE id = %s ")
1972
        cursor.execute(query, (gid,))
1973
        row = cursor.fetchone()
1974
        cursor.close()
1975
        cnx.close()
1976
1977
        if row is None:
1978
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1979
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
1980
        else:
1981
            meta_result = {"id": row[0],
1982
                           "name": row[1],
1983
                           "uuid": row[2],
1984
                           "microgrid": microgrid_dict.get(row[3]),
1985
                           "power_point": point_dict.get(row[4]),
1986
                           "meter": meter_dict.get(row[5]),
1987
                           "rated_output_power": row[6]}
1988
1989
        resp.text = json.dumps(meta_result)
1990
1991
    @staticmethod
1992
    @user_logger
1993
    def on_delete(req, resp, id_, gid):
1994
        admin_control(req)
1995
        if not id_.isdigit() or int(id_) <= 0:
1996
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1997
                                   description='API.INVALID_MICROGRID_ID')
1998
        if not gid.isdigit() or int(gid) <= 0:
1999
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2000
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
2001
2002
        cnx = mysql.connector.connect(**config.myems_system_db)
2003
        cursor = cnx.cursor()
2004
2005
        cursor.execute(" SELECT name "
2006
                       " FROM tbl_microgrids "
2007
                       " WHERE id = %s ", (id_,))
2008
        if cursor.fetchone() is None:
2009
            cursor.close()
2010
            cnx.close()
2011
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2012
                                   description='API.MICROGRID_NOT_FOUND')
2013
2014
        cursor.execute(" SELECT name "
2015
                       " FROM tbl_microgrids_generators "
2016
                       " WHERE id = %s ", (gid,))
2017
        if cursor.fetchone() is None:
2018
            cursor.close()
2019
            cnx.close()
2020
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2021
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2022
2023
        cursor.execute(" DELETE FROM tbl_microgrids_generators "
2024
                       " WHERE id = %s ", (gid,))
2025
        cnx.commit()
2026
2027
        cursor.close()
2028
        cnx.close()
2029
2030
        resp.status = falcon.HTTP_204
2031
2032
    @staticmethod
2033
    @user_logger
2034
    def on_put(req, resp, id_, gid):
2035
        """Handles PUT requests"""
2036
        admin_control(req)
2037
        try:
2038
            raw_json = req.stream.read().decode('utf-8')
2039
        except Exception as ex:
2040
            raise falcon.HTTPError(status=falcon.HTTP_400,
2041
                                   title='API.BAD_REQUEST',
2042
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2043
        if not id_.isdigit() or int(id_) <= 0:
2044
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2045
                                   description='API.INVALID_MICROGRID_ID')
2046
        if not gid.isdigit() or int(gid) <= 0:
2047
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2048
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
2049
2050
        new_values = json.loads(raw_json)
2051
2052
        if 'name' not in new_values['data'].keys() or \
2053
                not isinstance(new_values['data']['name'], str) or \
2054
                len(str.strip(new_values['data']['name'])) == 0:
2055
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2056
                                   description='API.INVALID_MICROGRID_GENERATOR_NAME')
2057
        name = str.strip(new_values['data']['name'])
2058
2059
        if 'power_point_id' not in new_values['data'].keys() or \
2060
                not isinstance(new_values['data']['power_point_id'], int) or \
2061
                new_values['data']['power_point_id'] <= 0:
2062
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2063
                                   description='API.INVALID_POWER_POINT_ID')
2064
        power_point_id = new_values['data']['power_point_id']
2065
2066
        if 'meter_id' not in new_values['data'].keys() or \
2067
                not isinstance(new_values['data']['meter_id'], int) or \
2068
                new_values['data']['meter_id'] <= 0:
2069
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2070
                                   description='API.INVALID_METER_ID')
2071
        meter_id = new_values['data']['meter_id']
2072
2073
        if 'rated_output_power' not in new_values['data'].keys() or \
2074
                not (isinstance(new_values['data']['rated_output_power'], float) or
2075
                     isinstance(new_values['data']['rated_output_power'], int)):
2076
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2077
                                   description='API.INVALID_RATED_OUTPUT_POWER')
2078
        rated_output_power = float(new_values['data']['rated_output_power'])
2079
2080
        cnx = mysql.connector.connect(**config.myems_system_db)
2081
        cursor = cnx.cursor()
2082
2083
        cursor.execute(" SELECT name "
2084
                       " FROM tbl_microgrids "
2085
                       " WHERE id = %s ", (id_,))
2086
        if cursor.fetchone() is None:
2087
            cursor.close()
2088
            cnx.close()
2089
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2090
                                   description='API.MICROGRID_NOT_FOUND')
2091
2092
        cursor.execute(" SELECT name "
2093
                       " FROM tbl_microgrids_generators "
2094
                       " WHERE id = %s ", (gid,))
2095
        if cursor.fetchone() is None:
2096
            cursor.close()
2097
            cnx.close()
2098
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2099
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2100
2101
        cursor.execute(" SELECT name "
2102
                       " FROM tbl_microgrids_generators "
2103
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
2104
                       (id_, name, gid))
2105
        if cursor.fetchone() is not None:
2106
            cursor.close()
2107
            cnx.close()
2108
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2109
                                   description='API.MICROGRID_GENERATOR_NAME_IS_ALREADY_IN_USE')
2110
2111
        cursor.execute(" SELECT name "
2112
                       " FROM tbl_points "
2113
                       " WHERE id = %s ",
2114
                       (power_point_id,))
2115
        if cursor.fetchone() is None:
2116
            cursor.close()
2117
            cnx.close()
2118
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2119
                                   description='API.POWER_POINT_NOT_FOUND')
2120
2121
        cursor.execute(" SELECT name "
2122
                       " FROM tbl_meters "
2123
                       " WHERE id = %s ",
2124
                       (meter_id,))
2125
        if cursor.fetchone() is None:
2126
            cursor.close()
2127
            cnx.close()
2128
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2129
                                   description='API.METER_NOT_FOUND')
2130
2131
        update_row = (" UPDATE tbl_microgrids_generators "
2132
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_output_power = %s "
2133
                      " WHERE id = %s ")
2134
        cursor.execute(update_row, (name,
2135
                                    id_,
2136
                                    power_point_id,
2137
                                    meter_id,
2138
                                    rated_output_power,
2139
                                    gid))
2140
        cnx.commit()
2141
2142
        cursor.close()
2143
        cnx.close()
2144
2145
        resp.status = falcon.HTTP_200
2146
2147
2148 View Code Duplication
class MicrogridGridCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2149
    def __init__(self):
2150
        """Initializes MicrogridGridCollection"""
2151
        pass
2152
2153
    @staticmethod
2154
    def on_options(req, resp, id_):
2155
        resp.status = falcon.HTTP_200
2156
2157
    @staticmethod
2158
    def on_get(req, resp, id_):
2159
        access_control(req)
2160
        if not id_.isdigit() or int(id_) <= 0:
2161
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2162
                                   description='API.INVALID_MICROGRID_ID')
2163
2164
        cnx = mysql.connector.connect(**config.myems_system_db)
2165
        cursor = cnx.cursor()
2166
2167
        cursor.execute(" SELECT name "
2168
                       " FROM tbl_microgrids "
2169
                       " WHERE id = %s ", (id_,))
2170
        if cursor.fetchone() is None:
2171
            cursor.close()
2172
            cnx.close()
2173
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2174
                                   description='API.MICROGRID_NOT_FOUND')
2175
2176
        # query meter dict
2177
        query = (" SELECT id, name, uuid "
2178
                 " FROM tbl_meters ")
2179
        cursor.execute(query)
2180
        rows_meters = cursor.fetchall()
2181
2182
        meter_dict = dict()
2183
        if rows_meters is not None and len(rows_meters) > 0:
2184
            for row in rows_meters:
2185
                meter_dict[row[0]] = {"id": row[0],
2186
                                      "name": row[1],
2187
                                      "uuid": row[2]}
2188
        # query point dict
2189
        query = (" SELECT id, name "
2190
                 " FROM tbl_points ")
2191
        cursor.execute(query)
2192
        rows_points = cursor.fetchall()
2193
2194
        point_dict = dict()
2195
        if rows_points is not None and len(rows_points) > 0:
2196
            for row in rows_points:
2197
                point_dict[row[0]] = {"id": row[0],
2198
                                      "name": row[1]}
2199
2200
        query = (" SELECT id, name, uuid, "
2201
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2202
                 " FROM tbl_microgrids_grids "
2203
                 " WHERE microgrid_id = %s "
2204
                 " ORDER BY name ")
2205
        cursor.execute(query, (id_,))
2206
        rows = cursor.fetchall()
2207
2208
        result = list()
2209
        if rows is not None and len(rows) > 0:
2210
            for row in rows:
2211
                meta_result = {"id": row[0],
2212
                               "name": row[1],
2213
                               "uuid": row[2],
2214
                               "power_point": point_dict.get(row[3]),
2215
                               "buy_meter": meter_dict.get(row[4]),
2216
                               "sell_meter": meter_dict.get(row[5]),
2217
                               "capacity": row[6]}
2218
                result.append(meta_result)
2219
2220
        resp.text = json.dumps(result)
2221
2222
    @staticmethod
2223
    @user_logger
2224
    def on_post(req, resp, id_):
2225
        """Handles POST requests"""
2226
        admin_control(req)
2227
        try:
2228
            raw_json = req.stream.read().decode('utf-8')
2229
        except Exception as ex:
2230
            raise falcon.HTTPError(status=falcon.HTTP_400,
2231
                                   title='API.BAD_REQUEST',
2232
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2233
        if not id_.isdigit() or int(id_) <= 0:
2234
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2235
                                   description='API.INVALID_MICROGRID_ID')
2236
2237
        cnx = mysql.connector.connect(**config.myems_system_db)
2238
        cursor = cnx.cursor()
2239
2240
        cursor.execute(" SELECT name "
2241
                       " FROM tbl_microgrids "
2242
                       " WHERE id = %s ", (id_,))
2243
        if cursor.fetchone() is None:
2244
            cursor.close()
2245
            cnx.close()
2246
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2247
                                   description='API.MICROGRID_NOT_FOUND')
2248
2249
        new_values = json.loads(raw_json)
2250
2251
        if 'name' not in new_values['data'].keys() or \
2252
                not isinstance(new_values['data']['name'], str) or \
2253
                len(str.strip(new_values['data']['name'])) == 0:
2254
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2255
                                   description='API.INVALID_MICROGRID_GRID_NAME')
2256
        name = str.strip(new_values['data']['name'])
2257
2258
        if 'power_point_id' not in new_values['data'].keys() or \
2259
                not isinstance(new_values['data']['power_point_id'], int) or \
2260
                new_values['data']['power_point_id'] <= 0:
2261
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2262
                                   description='API.INVALID_POWER_POINT_ID')
2263
        power_point_id = new_values['data']['power_point_id']
2264
2265
        if 'buy_meter_id' not in new_values['data'].keys() or \
2266
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2267
                new_values['data']['buy_meter_id'] <= 0:
2268
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2269
                                   description='API.INVALID_BUY_METER_ID')
2270
        buy_meter_id = new_values['data']['buy_meter_id']
2271
2272
        if 'sell_meter_id' not in new_values['data'].keys() or \
2273
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2274
                new_values['data']['sell_meter_id'] <= 0:
2275
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2276
                                   description='API.INVALID_SELL_METER_ID')
2277
        sell_meter_id = new_values['data']['sell_meter_id']
2278
2279
        if 'capacity' not in new_values['data'].keys() or \
2280
                not (isinstance(new_values['data']['capacity'], float) or
2281
                     isinstance(new_values['data']['capacity'], int)):
2282
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2283
                                   description='API.INVALID_CAPACITY')
2284
        capacity = float(new_values['data']['capacity'])
2285
2286
        cnx = mysql.connector.connect(**config.myems_system_db)
2287
        cursor = cnx.cursor()
2288
2289
        cursor.execute(" SELECT name "
2290
                       " FROM tbl_microgrids "
2291
                       " WHERE id = %s ",
2292
                       (id_,))
2293
        if cursor.fetchone() is None:
2294
            cursor.close()
2295
            cnx.close()
2296
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2297
                                   description='API.MICROGRID_NOT_FOUND')
2298
2299
        cursor.execute(" SELECT name "
2300
                       " FROM tbl_microgrids_grids "
2301
                       " WHERE microgrid_id = %s AND name = %s ",
2302
                       (id_, name,))
2303
        if cursor.fetchone() is not None:
2304
            cursor.close()
2305
            cnx.close()
2306
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2307
                                   description='API.MICROGRID_GRID_NAME_IS_ALREADY_IN_USE')
2308
2309
        cursor.execute(" SELECT name "
2310
                       " FROM tbl_points "
2311
                       " WHERE id = %s ",
2312
                       (power_point_id,))
2313
        if cursor.fetchone() is None:
2314
            cursor.close()
2315
            cnx.close()
2316
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2317
                                   description='API.POWER_POINT_NOT_FOUND')
2318
2319
        cursor.execute(" SELECT name "
2320
                       " FROM tbl_meters "
2321
                       " WHERE id = %s ",
2322
                       (buy_meter_id,))
2323
        if cursor.fetchone() is None:
2324
            cursor.close()
2325
            cnx.close()
2326
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2327
                                   description='API.BUY_METER_NOT_FOUND')
2328
2329
        cursor.execute(" SELECT name "
2330
                       " FROM tbl_meters "
2331
                       " WHERE id = %s ",
2332
                       (sell_meter_id,))
2333
        if cursor.fetchone() is None:
2334
            cursor.close()
2335
            cnx.close()
2336
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2337
                                   description='API.SELL_METER_NOT_FOUND')
2338
2339
        add_values = (" INSERT INTO tbl_microgrids_grids "
2340
                      "    (name, uuid, microgrid_id, power_point_id, buy_meter_id, sell_meter_id, capacity) "
2341
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2342
        cursor.execute(add_values, (name,
2343
                                    str(uuid.uuid4()),
2344
                                    id_,
2345
                                    power_point_id,
2346
                                    buy_meter_id,
2347
                                    sell_meter_id,
2348
                                    capacity))
2349
        new_id = cursor.lastrowid
2350
        cnx.commit()
2351
        cursor.close()
2352
        cnx.close()
2353
2354
        resp.status = falcon.HTTP_201
2355
        resp.location = '/microgrids/' + str(id_) + '/grids/' + str(new_id)
2356
2357
2358 View Code Duplication
class MicrogridGridItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2359
    def __init__(self):
2360
        """Initializes MicrogridGridItem"""
2361
        pass
2362
2363
    @staticmethod
2364
    def on_options(req, resp, id_, gid):
2365
        resp.status = falcon.HTTP_200
2366
2367
    @staticmethod
2368
    def on_get(req, resp, id_, gid):
2369
        access_control(req)
2370
        if not id_.isdigit() or int(id_) <= 0:
2371
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2372
                                   description='API.INVALID_MICROGRID_ID')
2373
        if not gid.isdigit() or int(gid) <= 0:
2374
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2375
                                   description='API.INVALID_MICROGRID_GRID_ID')
2376
2377
        cnx = mysql.connector.connect(**config.myems_system_db)
2378
        cursor = cnx.cursor()
2379
2380
        cursor.execute(" SELECT name "
2381
                       " FROM tbl_microgrids "
2382
                       " WHERE id = %s ", (id_,))
2383
        if cursor.fetchone() is None:
2384
            cursor.close()
2385
            cnx.close()
2386
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2387
                                   description='API.MICROGRID_NOT_FOUND')
2388
2389
        # query microgrid dict
2390
        query = (" SELECT id, name, uuid "
2391
                 " FROM tbl_microgrids ")
2392
        cursor.execute(query)
2393
        rows_microgrids = cursor.fetchall()
2394
2395
        microgrid_dict = dict()
2396
        if rows_microgrids is not None and len(rows_microgrids) > 0:
2397
            for row in rows_microgrids:
2398
                microgrid_dict[row[0]] = {"id": row[0],
2399
                                          "name": row[1],
2400
                                          "uuid": row[2]}
2401
        # query meter dict
2402
        query = (" SELECT id, name, uuid "
2403
                 " FROM tbl_meters ")
2404
        cursor.execute(query)
2405
        rows_meters = cursor.fetchall()
2406
2407
        meter_dict = dict()
2408
        if rows_meters is not None and len(rows_meters) > 0:
2409
            for row in rows_meters:
2410
                meter_dict[row[0]] = {"id": row[0],
2411
                                      "name": row[1],
2412
                                      "uuid": row[2]}
2413
        # query point dict
2414
        query = (" SELECT id, name "
2415
                 " FROM tbl_points ")
2416
        cursor.execute(query)
2417
        rows_points = cursor.fetchall()
2418
2419
        point_dict = dict()
2420
        if rows_points is not None and len(rows_points) > 0:
2421
            for row in rows_points:
2422
                point_dict[row[0]] = {"id": row[0],
2423
                                      "name": row[1]}
2424
2425
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, buy_meter_id, sell_meter_id, capacity "
2426
                 " FROM tbl_microgrids_grids "
2427
                 " WHERE id = %s ")
2428
        cursor.execute(query, (gid,))
2429
        row = cursor.fetchone()
2430
        cursor.close()
2431
        cnx.close()
2432
2433
        if row is None:
2434
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2435
                                   description='API.MICROGRID_GRID_NOT_FOUND')
2436
        else:
2437
            meta_result = {"id": row[0],
2438
                           "name": row[1],
2439
                           "uuid": row[2],
2440
                           "microgrid": microgrid_dict.get(row[3]),
2441
                           "power_point": point_dict.get(row[4]),
2442
                           "buy_meter": meter_dict.get(row[5]),
2443
                           "sell_meter": meter_dict.get(row[6]),
2444
                           "capacity": row[7]}
2445
2446
        resp.text = json.dumps(meta_result)
2447
2448
    @staticmethod
2449
    @user_logger
2450
    def on_delete(req, resp, id_, gid):
2451
        admin_control(req)
2452
        if not id_.isdigit() or int(id_) <= 0:
2453
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2454
                                   description='API.INVALID_MICROGRID_ID')
2455
        if not gid.isdigit() or int(gid) <= 0:
2456
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2457
                                   description='API.INVALID_MICROGRID_GRID_ID')
2458
2459
        cnx = mysql.connector.connect(**config.myems_system_db)
2460
        cursor = cnx.cursor()
2461
2462
        cursor.execute(" SELECT name "
2463
                       " FROM tbl_microgrids "
2464
                       " WHERE id = %s ", (id_,))
2465
        if cursor.fetchone() is None:
2466
            cursor.close()
2467
            cnx.close()
2468
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2469
                                   description='API.MICROGRID_NOT_FOUND')
2470
2471
        cursor.execute(" SELECT name "
2472
                       " FROM tbl_microgrids_grids "
2473
                       " WHERE id = %s ", (gid,))
2474
        if cursor.fetchone() is None:
2475
            cursor.close()
2476
            cnx.close()
2477
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2478
                                   description='API.MICROGRID_GRID_NOT_FOUND')
2479
2480
        cursor.execute(" DELETE FROM tbl_microgrids_grids "
2481
                       " WHERE id = %s ", (gid,))
2482
        cnx.commit()
2483
2484
        cursor.close()
2485
        cnx.close()
2486
2487
        resp.status = falcon.HTTP_204
2488
2489
    @staticmethod
2490
    @user_logger
2491
    def on_put(req, resp, id_, gid):
2492
        """Handles PUT requests"""
2493
        admin_control(req)
2494
        try:
2495
            raw_json = req.stream.read().decode('utf-8')
2496
        except Exception as ex:
2497
            raise falcon.HTTPError(status=falcon.HTTP_400,
2498
                                   title='API.BAD_REQUEST',
2499
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2500
        if not id_.isdigit() or int(id_) <= 0:
2501
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2502
                                   description='API.INVALID_MICROGRID_ID')
2503
2504
        if not gid.isdigit() or int(gid) <= 0:
2505
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2506
                                   description='API.INVALID_MICROGRID_GRID_ID')
2507
2508
        new_values = json.loads(raw_json)
2509
2510
        if 'name' not in new_values['data'].keys() or \
2511
                not isinstance(new_values['data']['name'], str) or \
2512
                len(str.strip(new_values['data']['name'])) == 0:
2513
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2514
                                   description='API.INVALID_MICROGRID_GRID_NAME')
2515
        name = str.strip(new_values['data']['name'])
2516
2517
        if 'power_point_id' not in new_values['data'].keys() or \
2518
                not isinstance(new_values['data']['power_point_id'], int) or \
2519
                new_values['data']['power_point_id'] <= 0:
2520
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2521
                                   description='API.INVALID_POWER_POINT_ID')
2522
        power_point_id = new_values['data']['power_point_id']
2523
2524
        if 'buy_meter_id' not in new_values['data'].keys() or \
2525
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2526
                new_values['data']['buy_meter_id'] <= 0:
2527
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2528
                                   description='API.INVALID_BUY_METER_ID')
2529
        buy_meter_id = new_values['data']['buy_meter_id']
2530
2531
        if 'sell_meter_id' not in new_values['data'].keys() or \
2532
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2533
                new_values['data']['sell_meter_id'] <= 0:
2534
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2535
                                   description='API.INVALID_METER_ID')
2536
        sell_meter_id = new_values['data']['sell_meter_id']
2537
2538
        if 'capacity' not in new_values['data'].keys() or \
2539
                not (isinstance(new_values['data']['capacity'], float) or
2540
                     isinstance(new_values['data']['capacity'], int)):
2541
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2542
                                   description='API.INVALID_CAPACITY')
2543
        capacity = float(new_values['data']['capacity'])
2544
2545
        cnx = mysql.connector.connect(**config.myems_system_db)
2546
        cursor = cnx.cursor()
2547
2548
        cursor.execute(" SELECT name "
2549
                       " FROM tbl_microgrids "
2550
                       " WHERE id = %s ", (id_,))
2551
        if cursor.fetchone() is None:
2552
            cursor.close()
2553
            cnx.close()
2554
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2555
                                   description='API.MICROGRID_NOT_FOUND')
2556
2557
        cursor.execute(" SELECT name "
2558
                       " FROM tbl_microgrids_grids "
2559
                       " WHERE id = %s ", (gid,))
2560
        if cursor.fetchone() is None:
2561
            cursor.close()
2562
            cnx.close()
2563
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2564
                                   description='API.MICROGRID_GRID_NOT_FOUND')
2565
2566
        cursor.execute(" SELECT name "
2567
                       " FROM tbl_microgrids_grids "
2568
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
2569
                       (id_, name, gid))
2570
        if cursor.fetchone() is not None:
2571
            cursor.close()
2572
            cnx.close()
2573
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2574
                                   description='API.MICROGRID_GRID_NAME_IS_ALREADY_IN_USE')
2575
2576
        cursor.execute(" SELECT name "
2577
                       " FROM tbl_points "
2578
                       " WHERE id = %s ",
2579
                       (power_point_id,))
2580
        if cursor.fetchone() is None:
2581
            cursor.close()
2582
            cnx.close()
2583
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2584
                                   description='API.POWER_POINT_NOT_FOUND')
2585
2586
        cursor.execute(" SELECT name "
2587
                       " FROM tbl_meters "
2588
                       " WHERE id = %s ",
2589
                       (buy_meter_id,))
2590
        if cursor.fetchone() is None:
2591
            cursor.close()
2592
            cnx.close()
2593
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2594
                                   description='API.BUY_METER_NOT_FOUND')
2595
2596
        cursor.execute(" SELECT name "
2597
                       " FROM tbl_meters "
2598
                       " WHERE id = %s ",
2599
                       (sell_meter_id,))
2600
        if cursor.fetchone() is None:
2601
            cursor.close()
2602
            cnx.close()
2603
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2604
                                   description='API.SELL_METER_NOT_FOUND')
2605
2606
        update_row = (" UPDATE tbl_microgrids_grids "
2607
                      " SET name = %s, microgrid_id = %s, "
2608
                      "     power_point_id = %s, buy_meter_id = %s, sell_meter_id = %s, capacity = %s "
2609
                      " WHERE id = %s ")
2610
        cursor.execute(update_row, (name,
2611
                                    id_,
2612
                                    power_point_id,
2613
                                    buy_meter_id,
2614
                                    sell_meter_id,
2615
                                    capacity,
2616
                                    gid))
2617
        cnx.commit()
2618
2619
        cursor.close()
2620
        cnx.close()
2621
2622
        resp.status = falcon.HTTP_200
2623
2624
2625
class MicrogridHeatpumpCollection:
2626
    def __init__(self):
2627
        """Initializes MicrogridHeatpumpCollection"""
2628
        pass
2629
2630
    @staticmethod
2631
    def on_options(req, resp, id_):
2632
        resp.status = falcon.HTTP_200
2633
2634
    @staticmethod
2635
    def on_get(req, resp, id_):
2636
        access_control(req)
2637
        if not id_.isdigit() or int(id_) <= 0:
2638
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2639
                                   description='API.INVALID_MICROGRID_ID')
2640
2641
        cnx = mysql.connector.connect(**config.myems_system_db)
2642
        cursor = cnx.cursor()
2643
2644
        cursor.execute(" SELECT name "
2645
                       " FROM tbl_microgrids "
2646
                       " WHERE id = %s ", (id_,))
2647
        if cursor.fetchone() is None:
2648
            cursor.close()
2649
            cnx.close()
2650
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2651
                                   description='API.MICROGRID_NOT_FOUND')
2652
2653
        # query meter dict
2654
        query = (" SELECT id, name, uuid "
2655
                 " FROM tbl_meters ")
2656
        cursor.execute(query)
2657
        rows_meters = cursor.fetchall()
2658
2659
        meter_dict = dict()
2660
        if rows_meters is not None and len(rows_meters) > 0:
2661
            for row in rows_meters:
2662
                meter_dict[row[0]] = {"id": row[0],
2663
                                      "name": row[1],
2664
                                      "uuid": row[2]}
2665
        # query point dict
2666
        query = (" SELECT id, name "
2667
                 " FROM tbl_points ")
2668
        cursor.execute(query)
2669
        rows_points = cursor.fetchall()
2670
2671
        point_dict = dict()
2672
        if rows_points is not None and len(rows_points) > 0:
2673
            for row in rows_points:
2674
                point_dict[row[0]] = {"id": row[0],
2675
                                      "name": row[1]}
2676
2677
        query = (" SELECT id, name, uuid, "
2678
                 "        power_point_id, electricity_meter_id, heat_meter_id, cooling_meter_id, rated_input_power "
2679
                 " FROM tbl_microgrids_heatpumps "
2680
                 " WHERE microgrid_id = %s "
2681
                 " ORDER BY name ")
2682
        cursor.execute(query, (id_,))
2683
        rows = cursor.fetchall()
2684
2685
        result = list()
2686
        if rows is not None and len(rows) > 0:
2687
            for row in rows:
2688
                meta_result = {"id": row[0],
2689
                               "name": row[1],
2690
                               "uuid": row[2],
2691
                               "power_point": point_dict.get(row[3], None),
2692
                               "electricity_meter": meter_dict.get(row[4], None),
2693
                               "heat_meter": meter_dict.get(row[5], None),
2694
                               "cooling_meter": meter_dict.get(row[6], None),
2695
                               "rated_input_power": row[7]}
2696
                result.append(meta_result)
2697
2698
        resp.text = json.dumps(result)
2699
2700
    @staticmethod
2701
    @user_logger
2702
    def on_post(req, resp, id_):
2703
        """Handles POST requests"""
2704
        admin_control(req)
2705
        try:
2706
            raw_json = req.stream.read().decode('utf-8')
2707
        except Exception as ex:
2708
            raise falcon.HTTPError(status=falcon.HTTP_400,
2709
                                   title='API.BAD_REQUEST',
2710
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2711
        if not id_.isdigit() or int(id_) <= 0:
2712
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2713
                                   description='API.INVALID_MICROGRID_ID')
2714
2715
        cnx = mysql.connector.connect(**config.myems_system_db)
2716
        cursor = cnx.cursor()
2717
2718
        cursor.execute(" SELECT name "
2719
                       " FROM tbl_microgrids "
2720
                       " WHERE id = %s ", (id_,))
2721
        if cursor.fetchone() is None:
2722
            cursor.close()
2723
            cnx.close()
2724
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2725
                                   description='API.MICROGRID_NOT_FOUND')
2726
2727
        new_values = json.loads(raw_json)
2728
2729
        if 'name' not in new_values['data'].keys() or \
2730
                not isinstance(new_values['data']['name'], str) or \
2731
                len(str.strip(new_values['data']['name'])) == 0:
2732
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2733
                                   description='API.INVALID_MICROGRID_HEATPUMP_NAME')
2734
        name = str.strip(new_values['data']['name'])
2735
2736
        if 'power_point_id' not in new_values['data'].keys() or \
2737
                not isinstance(new_values['data']['power_point_id'], int) or \
2738
                new_values['data']['power_point_id'] <= 0:
2739
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2740
                                   description='API.INVALID_POWER_POINT_ID')
2741
        power_point_id = new_values['data']['power_point_id']
2742
2743
        if 'electricity_meter_id' not in new_values['data'].keys() or \
2744
                not isinstance(new_values['data']['electricity_meter_id'], int) or \
2745
                new_values['data']['electricity_meter_id'] <= 0:
2746
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2747
                                   description='API.INVALID_ELECTRICITY_METER_ID')
2748
        electricity_meter_id = new_values['data']['electricity_meter_id']
2749
2750
        if 'heat_meter_id' not in new_values['data'].keys() or \
2751
                not isinstance(new_values['data']['heat_meter_id'], int) or \
2752
                new_values['data']['heat_meter_id'] <= 0:
2753
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2754
                                   description='API.INVALID_SELL_METER_ID')
2755
        heat_meter_id = new_values['data']['heat_meter_id']
2756
2757
        if 'cooling_meter_id' not in new_values['data'].keys() or \
2758
                not isinstance(new_values['data']['cooling_meter_id'], int) or \
2759
                new_values['data']['cooling_meter_id'] <= 0:
2760
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2761
                                   description='API.INVALID_COOLING_METER_ID')
2762
        cooling_meter_id = new_values['data']['cooling_meter_id']
2763
2764
        if 'rated_input_power' not in new_values['data'].keys() or \
2765
                not (isinstance(new_values['data']['rated_input_power'], float) or
2766
                     isinstance(new_values['data']['rated_input_power'], int)):
2767
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2768
                                   description='API.INVALID_RATED_INPUT_POWER')
2769
        rated_input_power = float(new_values['data']['rated_input_power'])
2770
2771
        cnx = mysql.connector.connect(**config.myems_system_db)
2772
        cursor = cnx.cursor()
2773
2774
        cursor.execute(" SELECT name "
2775
                       " FROM tbl_microgrids "
2776
                       " WHERE id = %s ",
2777
                       (id_,))
2778
        if cursor.fetchone() is None:
2779
            cursor.close()
2780
            cnx.close()
2781
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2782
                                   description='API.MICROGRID_NOT_FOUND')
2783
2784
        cursor.execute(" SELECT name "
2785
                       " FROM tbl_microgrids_heatpumps "
2786
                       " WHERE microgrid_id = %s AND name = %s ",
2787
                       (id_, name,))
2788
        if cursor.fetchone() is not None:
2789
            cursor.close()
2790
            cnx.close()
2791
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2792
                                   description='API.MICROGRID_HEATPUMP_NAME_IS_ALREADY_IN_USE')
2793
2794
        cursor.execute(" SELECT name "
2795
                       " FROM tbl_points "
2796
                       " WHERE id = %s ",
2797
                       (power_point_id,))
2798
        if cursor.fetchone() is None:
2799
            cursor.close()
2800
            cnx.close()
2801
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2802
                                   description='API.POWER_POINT_NOT_FOUND')
2803
2804
        cursor.execute(" SELECT name "
2805
                       " FROM tbl_meters "
2806
                       " WHERE id = %s ",
2807
                       (electricity_meter_id,))
2808
        if cursor.fetchone() is None:
2809
            cursor.close()
2810
            cnx.close()
2811
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2812
                                   description='API.ELECTRICITY_METER_NOT_FOUND')
2813
2814
        cursor.execute(" SELECT name "
2815
                       " FROM tbl_meters "
2816
                       " WHERE id = %s ",
2817
                       (heat_meter_id,))
2818
        if cursor.fetchone() is None:
2819
            cursor.close()
2820
            cnx.close()
2821
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2822
                                   description='API.HEAT_METER_NOT_FOUND')
2823
2824
        cursor.execute(" SELECT name "
2825
                       " FROM tbl_meters "
2826
                       " WHERE id = %s ",
2827
                       (cooling_meter_id,))
2828
        if cursor.fetchone() is None:
2829
            cursor.close()
2830
            cnx.close()
2831
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2832
                                   description='API.COOLING_METER_NOT_FOUND')
2833
2834
        add_values = (" INSERT INTO tbl_microgrids_heatpumps "
2835
                      "    (name, uuid, microgrid_id, "
2836
                      "     power_point_id, electricity_meter_id, heat_meter_id, cooling_meter_id, rated_input_power) "
2837
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ")
2838
        cursor.execute(add_values, (name,
2839
                                    str(uuid.uuid4()),
2840
                                    id_,
2841
                                    power_point_id,
2842
                                    electricity_meter_id,
2843
                                    heat_meter_id,
2844
                                    cooling_meter_id,
2845
                                    rated_input_power))
2846
        new_id = cursor.lastrowid
2847
        cnx.commit()
2848
        cursor.close()
2849
        cnx.close()
2850
2851
        resp.status = falcon.HTTP_201
2852
        resp.location = '/microgrids/' + str(id_) + '/heatpumps/' + str(new_id)
2853
2854
2855
class MicrogridHeatpumpItem:
2856
    def __init__(self):
2857
        """Initializes MicrogridHeatpumpItem"""
2858
        pass
2859
2860
    @staticmethod
2861
    def on_options(req, resp, id_, hid):
2862
        resp.status = falcon.HTTP_200
2863
2864
    @staticmethod
2865
    def on_get(req, resp, id_, hid):
2866
        access_control(req)
2867
        if not id_.isdigit() or int(id_) <= 0:
2868
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2869
                                   description='API.INVALID_MICROGRID_ID')
2870
        if not hid.isdigit() or int(hid) <= 0:
2871
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2872
                                   description='API.INVALID_MICROGRID_HEATPUMP_ID')
2873
2874
        cnx = mysql.connector.connect(**config.myems_system_db)
2875
        cursor = cnx.cursor()
2876
2877
        cursor.execute(" SELECT name "
2878
                       " FROM tbl_microgrids "
2879
                       " WHERE id = %s ", (id_,))
2880
        if cursor.fetchone() is None:
2881
            cursor.close()
2882
            cnx.close()
2883
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2884
                                   description='API.MICROGRID_NOT_FOUND')
2885
2886
        # query microgrid dict
2887
        query = (" SELECT id, name, uuid "
2888
                 " FROM tbl_microgrids ")
2889
        cursor.execute(query)
2890
        rows_microgrids = cursor.fetchall()
2891
2892
        microgrid_dict = dict()
2893
        if rows_microgrids is not None and len(rows_microgrids) > 0:
2894
            for row in rows_microgrids:
2895
                microgrid_dict[row[0]] = {"id": row[0],
2896
                                          "name": row[1],
2897
                                          "uuid": row[2]}
2898
        # query meter dict
2899
        query = (" SELECT id, name, uuid "
2900
                 " FROM tbl_meters ")
2901
        cursor.execute(query)
2902
        rows_meters = cursor.fetchall()
2903
2904
        meter_dict = dict()
2905
        if rows_meters is not None and len(rows_meters) > 0:
2906
            for row in rows_meters:
2907
                meter_dict[row[0]] = {"id": row[0],
2908
                                      "name": row[1],
2909
                                      "uuid": row[2]}
2910
        # query point dict
2911
        query = (" SELECT id, name "
2912
                 " FROM tbl_points ")
2913
        cursor.execute(query)
2914
        rows_points = cursor.fetchall()
2915
2916
        point_dict = dict()
2917
        if rows_points is not None and len(rows_points) > 0:
2918
            for row in rows_points:
2919
                point_dict[row[0]] = {"id": row[0],
2920
                                      "name": row[1]}
2921
2922
        query = (" SELECT id, name, uuid, microgrid_id, "
2923
                 "        power_point_id, electricity_meter_id, heat_meter_id, cooling_meter_id, rated_input_power "
2924
                 " FROM tbl_microgrids_heatpumps "
2925
                 " WHERE id = %s ")
2926
        cursor.execute(query, (hid,))
2927
        row = cursor.fetchone()
2928
        cursor.close()
2929
        cnx.close()
2930
2931
        if row is None:
2932
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2933
                                   description='API.MICROGRID_HEATPUMP_NOT_FOUND')
2934
        else:
2935
            meta_result = {"id": row[0],
2936
                           "name": row[1],
2937
                           "uuid": row[2],
2938
                           "microgrid": microgrid_dict.get(row[3], None),
2939
                           "power_point": point_dict.get(row[4], None),
2940
                           "electricity_meter": meter_dict.get(row[5], None),
2941
                           "heat_meter": meter_dict.get(row[6], None),
2942
                           "cooling_meter": meter_dict.get(row[7], None),
2943
                           "rated_input_power": row[8]}
2944
2945
        resp.text = json.dumps(meta_result)
2946
2947
    @staticmethod
2948
    @user_logger
2949
    def on_delete(req, resp, id_, hid):
2950
        admin_control(req)
2951
        if not id_.isdigit() or int(id_) <= 0:
2952
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2953
                                   description='API.INVALID_MICROGRID_ID')
2954
        if not hid.isdigit() or int(hid) <= 0:
2955
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2956
                                   description='API.INVALID_MICROGRID_HEATPUMP_ID')
2957
2958
        cnx = mysql.connector.connect(**config.myems_system_db)
2959
        cursor = cnx.cursor()
2960
2961
        cursor.execute(" SELECT name "
2962
                       " FROM tbl_microgrids "
2963
                       " WHERE id = %s ", (id_,))
2964
        if cursor.fetchone() is None:
2965
            cursor.close()
2966
            cnx.close()
2967
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2968
                                   description='API.MICROGRID_NOT_FOUND')
2969
2970
        cursor.execute(" SELECT name "
2971
                       " FROM tbl_microgrids_heatpumps "
2972
                       " WHERE id = %s ", (hid,))
2973
        if cursor.fetchone() is None:
2974
            cursor.close()
2975
            cnx.close()
2976
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2977
                                   description='API.MICROGRID_HEATPUMP_NOT_FOUND')
2978
2979
        cursor.execute(" DELETE FROM tbl_microgrids_heatpumps "
2980
                       " WHERE id = %s ", (hid,))
2981
        cnx.commit()
2982
2983
        cursor.close()
2984
        cnx.close()
2985
2986
        resp.status = falcon.HTTP_204
2987
2988
    @staticmethod
2989
    @user_logger
2990
    def on_put(req, resp, id_, hid):
2991
        """Handles PUT requests"""
2992
        admin_control(req)
2993
        try:
2994
            raw_json = req.stream.read().decode('utf-8')
2995
        except Exception as ex:
2996
            raise falcon.HTTPError(status=falcon.HTTP_400,
2997
                                   title='API.BAD_REQUEST',
2998
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2999
        if not id_.isdigit() or int(id_) <= 0:
3000
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3001
                                   description='API.INVALID_MICROGRID_ID')
3002
        if not hid.isdigit() or int(hid) <= 0:
3003
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3004
                                   description='API.INVALID_MICROGRID_HEATPUMP_ID')
3005
3006
        new_values = json.loads(raw_json)
3007
3008
        if 'name' not in new_values['data'].keys() or \
3009
                not isinstance(new_values['data']['name'], str) or \
3010
                len(str.strip(new_values['data']['name'])) == 0:
3011
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3012
                                   description='API.INVALID_MICROGRID_HEATPUMP_NAME')
3013
        name = str.strip(new_values['data']['name'])
3014
3015
        if 'power_point_id' not in new_values['data'].keys() or \
3016
                not isinstance(new_values['data']['power_point_id'], int) or \
3017
                new_values['data']['power_point_id'] <= 0:
3018
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3019
                                   description='API.INVALID_POWER_POINT_ID')
3020
        power_point_id = new_values['data']['power_point_id']
3021
3022
        if 'electricity_meter_id' not in new_values['data'].keys() or \
3023
                not isinstance(new_values['data']['electricity_meter_id'], int) or \
3024
                new_values['data']['electricity_meter_id'] <= 0:
3025
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3026
                                   description='API.INVALID_ELECTRICITY_METER_ID')
3027
        electricity_meter_id = new_values['data']['electricity_meter_id']
3028
3029
        if 'heat_meter_id' not in new_values['data'].keys() or \
3030
                not isinstance(new_values['data']['heat_meter_id'], int) or \
3031
                new_values['data']['heat_meter_id'] <= 0:
3032
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3033
                                   description='API.INVALID_HEAT_METER_ID')
3034
        heat_meter_id = new_values['data']['heat_meter_id']
3035
3036
        if 'cooling_meter_id' not in new_values['data'].keys() or \
3037
                not isinstance(new_values['data']['cooling_meter_id'], int) or \
3038
                new_values['data']['cooling_meter_id'] <= 0:
3039
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3040
                                   description='API.INVALID_COOLING_METER_ID')
3041
        cooling_meter_id = new_values['data']['cooling_meter_id']
3042
3043
        if 'rated_input_power' not in new_values['data'].keys() or \
3044
                not (isinstance(new_values['data']['rated_input_power'], float) or
3045
                     isinstance(new_values['data']['rated_input_power'], int)):
3046
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3047
                                   description='API.INVALID_RATED_INPUT_POWER')
3048
        rated_input_power = float(new_values['data']['rated_input_power'])
3049
3050
        cnx = mysql.connector.connect(**config.myems_system_db)
3051
        cursor = cnx.cursor()
3052
3053
        cursor.execute(" SELECT name "
3054
                       " FROM tbl_microgrids "
3055
                       " WHERE id = %s ", (id_,))
3056
        if cursor.fetchone() is None:
3057
            cursor.close()
3058
            cnx.close()
3059
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3060
                                   description='API.MICROGRID_NOT_FOUND')
3061
3062
        cursor.execute(" SELECT name "
3063
                       " FROM tbl_microgrids_heatpumps "
3064
                       " WHERE id = %s ", (hid,))
3065
        if cursor.fetchone() is None:
3066
            cursor.close()
3067
            cnx.close()
3068
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3069
                                   description='API.MICROGRID_HEATPUMP_NOT_FOUND')
3070
3071
        cursor.execute(" SELECT name "
3072
                       " FROM tbl_microgrids_heatpumps "
3073
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
3074
                       (id_, name, hid))
3075
        if cursor.fetchone() is not None:
3076
            cursor.close()
3077
            cnx.close()
3078
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3079
                                   description='API.MICROGRID_HEATPUMP_NAME_IS_ALREADY_IN_USE')
3080
3081
        cursor.execute(" SELECT name "
3082
                       " FROM tbl_points "
3083
                       " WHERE id = %s ",
3084
                       (power_point_id,))
3085
        if cursor.fetchone() is None:
3086
            cursor.close()
3087
            cnx.close()
3088
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3089
                                   description='API.POWER_POINT_NOT_FOUND')
3090
3091
        cursor.execute(" SELECT name "
3092
                       " FROM tbl_meters "
3093
                       " WHERE id = %s ",
3094
                       (electricity_meter_id,))
3095
        if cursor.fetchone() is None:
3096
            cursor.close()
3097
            cnx.close()
3098
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3099
                                   description='API.ELECTRICITY_METER_NOT_FOUND')
3100
3101
        cursor.execute(" SELECT name "
3102
                       " FROM tbl_meters "
3103
                       " WHERE id = %s ",
3104
                       (heat_meter_id,))
3105
        if cursor.fetchone() is None:
3106
            cursor.close()
3107
            cnx.close()
3108
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3109
                                   description='API.HEAT_METER_NOT_FOUND')
3110
3111
        cursor.execute(" SELECT name "
3112
                       " FROM tbl_meters "
3113
                       " WHERE id = %s ",
3114
                       (cooling_meter_id,))
3115
        if cursor.fetchone() is None:
3116
            cursor.close()
3117
            cnx.close()
3118
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3119
                                   description='API.COOLING_METER_NOT_FOUND')
3120
3121
        update_row = (" UPDATE tbl_microgrids_heatpumps "
3122
                      " SET name = %s, microgrid_id = %s, "
3123
                      "     power_point_id = %s, electricity_meter_id = %s, heat_meter_id = %s, cooling_meter_id = %s, "
3124
                      "     rated_input_power = %s "
3125
                      " WHERE id = %s ")
3126
        cursor.execute(update_row, (name,
3127
                                    id_,
3128
                                    power_point_id,
3129
                                    electricity_meter_id,
3130
                                    heat_meter_id,
3131
                                    heat_meter_id,
3132
                                    rated_input_power,
3133
                                    hid))
3134
        cnx.commit()
3135
3136
        cursor.close()
3137
        cnx.close()
3138
3139
        resp.status = falcon.HTTP_200
3140
3141
3142 View Code Duplication
class MicrogridLoadCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3143
    def __init__(self):
3144
        """Initializes MicrogridLoadCollection"""
3145
        pass
3146
3147
    @staticmethod
3148
    def on_options(req, resp, id_):
3149
        resp.status = falcon.HTTP_200
3150
3151
    @staticmethod
3152
    def on_get(req, resp, id_):
3153
        access_control(req)
3154
        if not id_.isdigit() or int(id_) <= 0:
3155
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3156
                                   description='API.INVALID_MICROGRID_ID')
3157
3158
        cnx = mysql.connector.connect(**config.myems_system_db)
3159
        cursor = cnx.cursor()
3160
3161
        cursor.execute(" SELECT name "
3162
                       " FROM tbl_microgrids "
3163
                       " WHERE id = %s ", (id_,))
3164
        if cursor.fetchone() is None:
3165
            cursor.close()
3166
            cnx.close()
3167
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3168
                                   description='API.MICROGRID_NOT_FOUND')
3169
3170
        # query meter dict
3171
        query = (" SELECT id, name, uuid "
3172
                 " FROM tbl_meters ")
3173
        cursor.execute(query)
3174
        rows_meters = cursor.fetchall()
3175
3176
        meter_dict = dict()
3177
        if rows_meters is not None and len(rows_meters) > 0:
3178
            for row in rows_meters:
3179
                meter_dict[row[0]] = {"id": row[0],
3180
                                      "name": row[1],
3181
                                      "uuid": row[2]}
3182
        # query point dict
3183
        query = (" SELECT id, name "
3184
                 " FROM tbl_points ")
3185
        cursor.execute(query)
3186
        rows_points = cursor.fetchall()
3187
3188
        point_dict = dict()
3189
        if rows_points is not None and len(rows_points) > 0:
3190
            for row in rows_points:
3191
                point_dict[row[0]] = {"id": row[0],
3192
                                      "name": row[1]}
3193
3194
        query = (" SELECT id, name, uuid, "
3195
                 "        power_point_id, meter_id, rated_input_power "
3196
                 " FROM tbl_microgrids_loads "
3197
                 " WHERE microgrid_id = %s "
3198
                 " ORDER BY name ")
3199
        cursor.execute(query, (id_,))
3200
        rows = cursor.fetchall()
3201
3202
        result = list()
3203
        if rows is not None and len(rows) > 0:
3204
            for row in rows:
3205
                meta_result = {"id": row[0],
3206
                               "name": row[1],
3207
                               "uuid": row[2],
3208
                               "power_point": point_dict.get(row[3], None),
3209
                               "meter": meter_dict.get(row[4], None),
3210
                               "rated_input_power": row[5]}
3211
                result.append(meta_result)
3212
3213
        resp.text = json.dumps(result)
3214
3215
    @staticmethod
3216
    @user_logger
3217
    def on_post(req, resp, id_):
3218
        """Handles POST requests"""
3219
        admin_control(req)
3220
        try:
3221
            raw_json = req.stream.read().decode('utf-8')
3222
        except Exception as ex:
3223
            raise falcon.HTTPError(status=falcon.HTTP_400,
3224
                                   title='API.BAD_REQUEST',
3225
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3226
        if not id_.isdigit() or int(id_) <= 0:
3227
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3228
                                   description='API.INVALID_MICROGRID_ID')
3229
3230
        cnx = mysql.connector.connect(**config.myems_system_db)
3231
        cursor = cnx.cursor()
3232
3233
        cursor.execute(" SELECT name "
3234
                       " FROM tbl_microgrids "
3235
                       " WHERE id = %s ", (id_,))
3236
        if cursor.fetchone() is None:
3237
            cursor.close()
3238
            cnx.close()
3239
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3240
                                   description='API.MICROGRID_NOT_FOUND')
3241
3242
        new_values = json.loads(raw_json)
3243
3244
        if 'name' not in new_values['data'].keys() or \
3245
                not isinstance(new_values['data']['name'], str) or \
3246
                len(str.strip(new_values['data']['name'])) == 0:
3247
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3248
                                   description='API.INVALID_MICROGRID_LOAD_NAME')
3249
        name = str.strip(new_values['data']['name'])
3250
3251
        if 'power_point_id' not in new_values['data'].keys() or \
3252
                not isinstance(new_values['data']['power_point_id'], int) or \
3253
                new_values['data']['power_point_id'] <= 0:
3254
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3255
                                   description='API.INVALID_POWER_POINT_ID')
3256
        power_point_id = new_values['data']['power_point_id']
3257
3258
        if 'meter_id' not in new_values['data'].keys() or \
3259
                not isinstance(new_values['data']['meter_id'], int) or \
3260
                new_values['data']['meter_id'] <= 0:
3261
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3262
                                   description='API.INVALID_METER_ID')
3263
        meter_id = new_values['data']['meter_id']
3264
3265
        if 'rated_input_power' not in new_values['data'].keys() or \
3266
                not (isinstance(new_values['data']['rated_input_power'], float) or
3267
                     isinstance(new_values['data']['rated_input_power'], int)):
3268
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3269
                                   description='API.INVALID_RATED_INPUT_POWER')
3270
        rated_input_power = float(new_values['data']['rated_input_power'])
3271
3272
        cnx = mysql.connector.connect(**config.myems_system_db)
3273
        cursor = cnx.cursor()
3274
3275
        cursor.execute(" SELECT name "
3276
                       " FROM tbl_microgrids "
3277
                       " WHERE id = %s ",
3278
                       (id_,))
3279
        if cursor.fetchone() is None:
3280
            cursor.close()
3281
            cnx.close()
3282
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3283
                                   description='API.MICROGRID_NOT_FOUND')
3284
3285
        cursor.execute(" SELECT name "
3286
                       " FROM tbl_microgrids_loads "
3287
                       " WHERE microgrid_id = %s AND name = %s ",
3288
                       (id_, name,))
3289
        if cursor.fetchone() is not None:
3290
            cursor.close()
3291
            cnx.close()
3292
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3293
                                   description='API.MICROGRID_LOAD_NAME_IS_ALREADY_IN_USE')
3294
3295
        cursor.execute(" SELECT name "
3296
                       " FROM tbl_points "
3297
                       " WHERE id = %s ",
3298
                       (power_point_id,))
3299
        if cursor.fetchone() is None:
3300
            cursor.close()
3301
            cnx.close()
3302
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3303
                                   description='API.POWER_POINT_NOT_FOUND')
3304
3305
        cursor.execute(" SELECT name "
3306
                       " FROM tbl_meters "
3307
                       " WHERE id = %s ",
3308
                       (meter_id,))
3309
        if cursor.fetchone() is None:
3310
            cursor.close()
3311
            cnx.close()
3312
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3313
                                   description='API.METER_NOT_FOUND')
3314
3315
        add_values = (" INSERT INTO tbl_microgrids_loads "
3316
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_input_power) "
3317
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3318
        cursor.execute(add_values, (name,
3319
                                    str(uuid.uuid4()),
3320
                                    id_,
3321
                                    power_point_id,
3322
                                    meter_id,
3323
                                    rated_input_power))
3324
        new_id = cursor.lastrowid
3325
        cnx.commit()
3326
        cursor.close()
3327
        cnx.close()
3328
3329
        resp.status = falcon.HTTP_201
3330
        resp.location = '/microgrids/' + str(id_) + '/loads/' + str(new_id)
3331
3332
3333 View Code Duplication
class MicrogridLoadItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3334
    def __init__(self):
3335
        """Initializes MicrogridLoadItem"""
3336
        pass
3337
3338
    @staticmethod
3339
    def on_options(req, resp, id_, lid):
3340
        resp.status = falcon.HTTP_200
3341
3342
    @staticmethod
3343
    def on_get(req, resp, id_, lid):
3344
        access_control(req)
3345
        if not id_.isdigit() or int(id_) <= 0:
3346
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3347
                                   description='API.INVALID_MICROGRID_ID')
3348
        if not lid.isdigit() or int(lid) <= 0:
3349
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3350
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3351
3352
        cnx = mysql.connector.connect(**config.myems_system_db)
3353
        cursor = cnx.cursor()
3354
3355
        cursor.execute(" SELECT name "
3356
                       " FROM tbl_microgrids "
3357
                       " WHERE id = %s ", (id_,))
3358
        if cursor.fetchone() is None:
3359
            cursor.close()
3360
            cnx.close()
3361
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3362
                                   description='API.MICROGRID_NOT_FOUND')
3363
3364
        # query microgrid dict
3365
        query = (" SELECT id, name, uuid "
3366
                 " FROM tbl_microgrids ")
3367
        cursor.execute(query)
3368
        rows_microgrids = cursor.fetchall()
3369
3370
        microgrid_dict = dict()
3371
        if rows_microgrids is not None and len(rows_microgrids) > 0:
3372
            for row in rows_microgrids:
3373
                microgrid_dict[row[0]] = {"id": row[0],
3374
                                          "name": row[1],
3375
                                          "uuid": row[2]}
3376
        # query meter dict
3377
        query = (" SELECT id, name, uuid "
3378
                 " FROM tbl_meters ")
3379
        cursor.execute(query)
3380
        rows_meters = cursor.fetchall()
3381
3382
        meter_dict = dict()
3383
        if rows_meters is not None and len(rows_meters) > 0:
3384
            for row in rows_meters:
3385
                meter_dict[row[0]] = {"id": row[0],
3386
                                      "name": row[1],
3387
                                      "uuid": row[2]}
3388
        # query point dict
3389
        query = (" SELECT id, name "
3390
                 " FROM tbl_points ")
3391
        cursor.execute(query)
3392
        rows_points = cursor.fetchall()
3393
3394
        point_dict = dict()
3395
        if rows_points is not None and len(rows_points) > 0:
3396
            for row in rows_points:
3397
                point_dict[row[0]] = {"id": row[0],
3398
                                      "name": row[1]}
3399
3400
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_input_power "
3401
                 " FROM tbl_microgrids_loads "
3402
                 " WHERE id = %s ")
3403
        cursor.execute(query, (lid,))
3404
        row = cursor.fetchone()
3405
        cursor.close()
3406
        cnx.close()
3407
3408
        if row is None:
3409
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3410
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3411
        else:
3412
            meta_result = {"id": row[0],
3413
                           "name": row[1],
3414
                           "uuid": row[2],
3415
                           "microgrid": microgrid_dict.get(row[3], None),
3416
                           "power_point": point_dict.get(row[4], None),
3417
                           "meter": meter_dict.get(row[5], None),
3418
                           "rated_input_power": row[6]}
3419
3420
        resp.text = json.dumps(meta_result)
3421
3422
    @staticmethod
3423
    @user_logger
3424
    def on_delete(req, resp, id_, lid):
3425
        admin_control(req)
3426
        if not id_.isdigit() or int(id_) <= 0:
3427
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3428
                                   description='API.INVALID_MICROGRID_ID')
3429
        if not lid.isdigit() or int(lid) <= 0:
3430
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3431
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3432
3433
        cnx = mysql.connector.connect(**config.myems_system_db)
3434
        cursor = cnx.cursor()
3435
3436
        cursor.execute(" SELECT name "
3437
                       " FROM tbl_microgrids "
3438
                       " WHERE id = %s ", (id_,))
3439
        if cursor.fetchone() is None:
3440
            cursor.close()
3441
            cnx.close()
3442
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3443
                                   description='API.MICROGRID_NOT_FOUND')
3444
3445
        cursor.execute(" SELECT name "
3446
                       " FROM tbl_microgrids_loads "
3447
                       " WHERE id = %s ", (lid,))
3448
        if cursor.fetchone() is None:
3449
            cursor.close()
3450
            cnx.close()
3451
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3452
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3453
3454
        cursor.execute(" DELETE FROM tbl_microgrids_loads "
3455
                       " WHERE id = %s ", (lid,))
3456
        cnx.commit()
3457
3458
        cursor.close()
3459
        cnx.close()
3460
3461
        resp.status = falcon.HTTP_204
3462
3463
    @staticmethod
3464
    @user_logger
3465
    def on_put(req, resp, id_, lid):
3466
        """Handles PUT requests"""
3467
        admin_control(req)
3468
        try:
3469
            raw_json = req.stream.read().decode('utf-8')
3470
        except Exception as ex:
3471
            raise falcon.HTTPError(status=falcon.HTTP_400,
3472
                                   title='API.BAD_REQUEST',
3473
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3474
        if not id_.isdigit() or int(id_) <= 0:
3475
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3476
                                   description='API.INVALID_MICROGRID_ID')
3477
        if not lid.isdigit() or int(lid) <= 0:
3478
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3479
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3480
3481
        new_values = json.loads(raw_json)
3482
3483
        if 'name' not in new_values['data'].keys() or \
3484
                not isinstance(new_values['data']['name'], str) or \
3485
                len(str.strip(new_values['data']['name'])) == 0:
3486
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3487
                                   description='API.INVALID_MICROGRID_LOAD_NAME')
3488
        name = str.strip(new_values['data']['name'])
3489
3490
        if 'power_point_id' not in new_values['data'].keys() or \
3491
                not isinstance(new_values['data']['power_point_id'], int) or \
3492
                new_values['data']['power_point_id'] <= 0:
3493
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3494
                                   description='API.INVALID_POWER_POINT_ID')
3495
        power_point_id = new_values['data']['power_point_id']
3496
3497
        if 'meter_id' not in new_values['data'].keys() or \
3498
                not isinstance(new_values['data']['meter_id'], int) or \
3499
                new_values['data']['meter_id'] <= 0:
3500
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3501
                                   description='API.INVALID_METER_ID')
3502
        meter_id = new_values['data']['meter_id']
3503
3504
        if 'rated_input_power' not in new_values['data'].keys() or \
3505
                not (isinstance(new_values['data']['rated_input_power'], float) or
3506
                     isinstance(new_values['data']['rated_input_power'], int)):
3507
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3508
                                   description='API.INVALID_RATED_INPUT_POWER')
3509
        rated_input_power = float(new_values['data']['rated_input_power'])
3510
3511
        cnx = mysql.connector.connect(**config.myems_system_db)
3512
        cursor = cnx.cursor()
3513
3514
        cursor.execute(" SELECT name "
3515
                       " FROM tbl_microgrids "
3516
                       " WHERE id = %s ", (id_,))
3517
        if cursor.fetchone() is None:
3518
            cursor.close()
3519
            cnx.close()
3520
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3521
                                   description='API.MICROGRID_NOT_FOUND')
3522
3523
        cursor.execute(" SELECT name "
3524
                       " FROM tbl_microgrids_loads "
3525
                       " WHERE id = %s ", (lid,))
3526
        if cursor.fetchone() is None:
3527
            cursor.close()
3528
            cnx.close()
3529
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3530
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3531
3532
        cursor.execute(" SELECT name "
3533
                       " FROM tbl_microgrids_loads "
3534
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
3535
                       (id_, name, lid))
3536
        if cursor.fetchone() is not None:
3537
            cursor.close()
3538
            cnx.close()
3539
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3540
                                   description='API.MICROGRID_LOAD_NAME_IS_ALREADY_IN_USE')
3541
3542
        cursor.execute(" SELECT name "
3543
                       " FROM tbl_points "
3544
                       " WHERE id = %s ",
3545
                       (power_point_id,))
3546
        if cursor.fetchone() is None:
3547
            cursor.close()
3548
            cnx.close()
3549
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3550
                                   description='API.POWER_POINT_NOT_FOUND')
3551
3552
        cursor.execute(" SELECT name "
3553
                       " FROM tbl_meters "
3554
                       " WHERE id = %s ",
3555
                       (meter_id,))
3556
        if cursor.fetchone() is None:
3557
            cursor.close()
3558
            cnx.close()
3559
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3560
                                   description='API.METER_NOT_FOUND')
3561
3562
        update_row = (" UPDATE tbl_microgrids_loads "
3563
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_input_power = %s "
3564
                      " WHERE id = %s ")
3565
        cursor.execute(update_row, (name,
3566
                                    id_,
3567
                                    power_point_id,
3568
                                    meter_id,
3569
                                    rated_input_power,
3570
                                    lid))
3571
        cnx.commit()
3572
3573
        cursor.close()
3574
        cnx.close()
3575
3576
        resp.status = falcon.HTTP_200
3577
3578
3579 View Code Duplication
class MicrogridPhotovoltaicCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3580
    def __init__(self):
3581
        """Initializes MicrogridPhotovoltaicCollection"""
3582
        pass
3583
3584
    @staticmethod
3585
    def on_options(req, resp, id_):
3586
        resp.status = falcon.HTTP_200
3587
3588
    @staticmethod
3589
    def on_get(req, resp, id_):
3590
        access_control(req)
3591
        if not id_.isdigit() or int(id_) <= 0:
3592
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3593
                                   description='API.INVALID_MICROGRID_ID')
3594
3595
        cnx = mysql.connector.connect(**config.myems_system_db)
3596
        cursor = cnx.cursor()
3597
3598
        cursor.execute(" SELECT name "
3599
                       " FROM tbl_microgrids "
3600
                       " WHERE id = %s ", (id_,))
3601
        if cursor.fetchone() is None:
3602
            cursor.close()
3603
            cnx.close()
3604
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3605
                                   description='API.MICROGRID_NOT_FOUND')
3606
3607
        # query meter dict
3608
        query = (" SELECT id, name, uuid "
3609
                 " FROM tbl_meters ")
3610
        cursor.execute(query)
3611
        rows_meters = cursor.fetchall()
3612
3613
        meter_dict = dict()
3614
        if rows_meters is not None and len(rows_meters) > 0:
3615
            for row in rows_meters:
3616
                meter_dict[row[0]] = {"id": row[0],
3617
                                      "name": row[1],
3618
                                      "uuid": row[2]}
3619
        # query point dict
3620
        query = (" SELECT id, name "
3621
                 " FROM tbl_points ")
3622
        cursor.execute(query)
3623
        rows_points = cursor.fetchall()
3624
3625
        point_dict = dict()
3626
        if rows_points is not None and len(rows_points) > 0:
3627
            for row in rows_points:
3628
                point_dict[row[0]] = {"id": row[0],
3629
                                      "name": row[1]}
3630
3631
        query = (" SELECT id, name, uuid, "
3632
                 "        power_point_id, meter_id, rated_power "
3633
                 " FROM tbl_microgrids_photovoltaics "
3634
                 " WHERE microgrid_id = %s "
3635
                 " ORDER BY name ")
3636
        cursor.execute(query, (id_,))
3637
        rows = cursor.fetchall()
3638
3639
        result = list()
3640
        if rows is not None and len(rows) > 0:
3641
            for row in rows:
3642
                meta_result = {"id": row[0],
3643
                               "name": row[1],
3644
                               "uuid": row[2],
3645
                               "power_point": point_dict.get(row[3], None),
3646
                               "meter": meter_dict.get(row[4], None),
3647
                               "rated_power": row[5],
3648
                               }
3649
                result.append(meta_result)
3650
3651
        resp.text = json.dumps(result)
3652
3653
    @staticmethod
3654
    @user_logger
3655
    def on_post(req, resp, id_):
3656
        """Handles POST requests"""
3657
        admin_control(req)
3658
        try:
3659
            raw_json = req.stream.read().decode('utf-8')
3660
        except Exception as ex:
3661
            raise falcon.HTTPError(status=falcon.HTTP_400,
3662
                                   title='API.BAD_REQUEST',
3663
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3664
        if not id_.isdigit() or int(id_) <= 0:
3665
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3666
                                   description='API.INVALID_MICROGRID_ID')
3667
3668
        cnx = mysql.connector.connect(**config.myems_system_db)
3669
        cursor = cnx.cursor()
3670
3671
        cursor.execute(" SELECT name "
3672
                       " FROM tbl_microgrids "
3673
                       " WHERE id = %s ", (id_,))
3674
        if cursor.fetchone() is None:
3675
            cursor.close()
3676
            cnx.close()
3677
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3678
                                   description='API.MICROGRID_NOT_FOUND')
3679
3680
        new_values = json.loads(raw_json)
3681
3682
        if 'name' not in new_values['data'].keys() or \
3683
                not isinstance(new_values['data']['name'], str) or \
3684
                len(str.strip(new_values['data']['name'])) == 0:
3685
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3686
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_NAME')
3687
        name = str.strip(new_values['data']['name'])
3688
3689
        if 'power_point_id' not in new_values['data'].keys() or \
3690
                not isinstance(new_values['data']['power_point_id'], int) or \
3691
                new_values['data']['power_point_id'] <= 0:
3692
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3693
                                   description='API.INVALID_POWER_POINT_ID')
3694
        power_point_id = new_values['data']['power_point_id']
3695
3696
        if 'meter_id' not in new_values['data'].keys() or \
3697
                not isinstance(new_values['data']['meter_id'], int) or \
3698
                new_values['data']['meter_id'] <= 0:
3699
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3700
                                   description='API.INVALID_METER_ID')
3701
        meter_id = new_values['data']['meter_id']
3702
3703
        if 'rated_power' not in new_values['data'].keys() or \
3704
                not (isinstance(new_values['data']['rated_power'], float) or
3705
                     isinstance(new_values['data']['rated_power'], int)):
3706
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3707
                                   description='API.INVALID_RATED_POWER')
3708
        rated_power = float(new_values['data']['rated_power'])
3709
3710
        cnx = mysql.connector.connect(**config.myems_system_db)
3711
        cursor = cnx.cursor()
3712
3713
        cursor.execute(" SELECT name "
3714
                       " FROM tbl_microgrids "
3715
                       " WHERE id = %s ",
3716
                       (id_,))
3717
        if cursor.fetchone() is None:
3718
            cursor.close()
3719
            cnx.close()
3720
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3721
                                   description='API.MICROGRID_NOT_FOUND')
3722
3723
        cursor.execute(" SELECT name "
3724
                       " FROM tbl_microgrids_photovoltaics "
3725
                       " WHERE microgrid_id = %s AND name = %s ",
3726
                       (id_, name,))
3727
        if cursor.fetchone() is not None:
3728
            cursor.close()
3729
            cnx.close()
3730
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3731
                                   description='API.MICROGRID_PHOTOVOLTAIC_NAME_IS_ALREADY_IN_USE')
3732
3733
        cursor.execute(" SELECT name "
3734
                       " FROM tbl_points "
3735
                       " WHERE id = %s ",
3736
                       (power_point_id,))
3737
        if cursor.fetchone() is None:
3738
            cursor.close()
3739
            cnx.close()
3740
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3741
                                   description='API.POWER_POINT_NOT_FOUND')
3742
3743
        cursor.execute(" SELECT name "
3744
                       " FROM tbl_meters "
3745
                       " WHERE id = %s ",
3746
                       (meter_id,))
3747
        if cursor.fetchone() is None:
3748
            cursor.close()
3749
            cnx.close()
3750
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3751
                                   description='API.METER_NOT_FOUND')
3752
3753
        add_values = (" INSERT INTO tbl_microgrids_photovoltaics "
3754
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_power) "
3755
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3756
        cursor.execute(add_values, (name,
3757
                                    str(uuid.uuid4()),
3758
                                    id_,
3759
                                    power_point_id,
3760
                                    meter_id,
3761
                                    rated_power))
3762
        new_id = cursor.lastrowid
3763
        cnx.commit()
3764
        cursor.close()
3765
        cnx.close()
3766
3767
        resp.status = falcon.HTTP_201
3768
        resp.location = '/microgrids' + str(id_) + '/photovoltaics/' + str(new_id)
3769
3770
3771 View Code Duplication
class MicrogridPhotovoltaicItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3772
    def __init__(self):
3773
        """Initializes MicrogridPhotovoltaicItem"""
3774
        pass
3775
3776
    @staticmethod
3777
    def on_options(req, resp, id_, pid):
3778
        resp.status = falcon.HTTP_200
3779
3780
    @staticmethod
3781
    def on_get(req, resp, id_, pid):
3782
        access_control(req)
3783
        if not id_.isdigit() or int(id_) <= 0:
3784
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3785
                                   description='API.INVALID_MICROGRID_ID')
3786
        if not pid.isdigit() or int(pid) <= 0:
3787
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3788
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
3789
3790
        cnx = mysql.connector.connect(**config.myems_system_db)
3791
        cursor = cnx.cursor()
3792
3793
        cursor.execute(" SELECT name "
3794
                       " FROM tbl_microgrids "
3795
                       " WHERE id = %s ", (id_,))
3796
        if cursor.fetchone() is None:
3797
            cursor.close()
3798
            cnx.close()
3799
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3800
                                   description='API.MICROGRID_NOT_FOUND')
3801
3802
        # query microgrid dict
3803
        query = (" SELECT id, name, uuid "
3804
                 " FROM tbl_microgrids ")
3805
        cursor.execute(query)
3806
        rows_microgrids = cursor.fetchall()
3807
3808
        microgrid_dict = dict()
3809
        if rows_microgrids is not None and len(rows_microgrids) > 0:
3810
            for row in rows_microgrids:
3811
                microgrid_dict[row[0]] = {"id": row[0],
3812
                                          "name": row[1],
3813
                                          "uuid": row[2]}
3814
        # query meter dict
3815
        query = (" SELECT id, name, uuid "
3816
                 " FROM tbl_meters ")
3817
        cursor.execute(query)
3818
        rows_meters = cursor.fetchall()
3819
3820
        meter_dict = dict()
3821
        if rows_meters is not None and len(rows_meters) > 0:
3822
            for row in rows_meters:
3823
                meter_dict[row[0]] = {"id": row[0],
3824
                                      "name": row[1],
3825
                                      "uuid": row[2]}
3826
        # query point dict
3827
        query = (" SELECT id, name "
3828
                 " FROM tbl_points ")
3829
        cursor.execute(query)
3830
        rows_points = cursor.fetchall()
3831
3832
        point_dict = dict()
3833
        if rows_points is not None and len(rows_points) > 0:
3834
            for row in rows_points:
3835
                point_dict[row[0]] = {"id": row[0],
3836
                                      "name": row[1]}
3837
3838
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_power "
3839
                 " FROM tbl_microgrids_photovoltaics "
3840
                 " WHERE id = %s ")
3841
        cursor.execute(query, (pid,))
3842
        row = cursor.fetchone()
3843
        cursor.close()
3844
        cnx.close()
3845
3846
        if row is None:
3847
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3848
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
3849
        else:
3850
            meta_result = {"id": row[0],
3851
                           "name": row[1],
3852
                           "uuid": row[2],
3853
                           "microgrid": microgrid_dict.get(row[3], None),
3854
                           "power_point": point_dict.get(row[4], None),
3855
                           "meter": meter_dict.get(row[5], None),
3856
                           "rated_power": row[6]}
3857
3858
        resp.text = json.dumps(meta_result)
3859
3860
    @staticmethod
3861
    @user_logger
3862
    def on_delete(req, resp, id_, pid):
3863
        admin_control(req)
3864
        if not id_.isdigit() or int(id_) <= 0:
3865
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3866
                                   description='API.INVALID_MICROGRID_ID')
3867
        if not pid.isdigit() or int(pid) <= 0:
3868
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3869
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
3870
3871
        cnx = mysql.connector.connect(**config.myems_system_db)
3872
        cursor = cnx.cursor()
3873
3874
        cursor.execute(" SELECT name "
3875
                       " FROM tbl_microgrids "
3876
                       " WHERE id = %s ", (id_,))
3877
        if cursor.fetchone() is None:
3878
            cursor.close()
3879
            cnx.close()
3880
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3881
                                   description='API.MICROGRID_NOT_FOUND')
3882
3883
        cursor.execute(" SELECT name "
3884
                       " FROM tbl_microgrids_photovoltaics "
3885
                       " WHERE id = %s ", (pid,))
3886
        if cursor.fetchone() is None:
3887
            cursor.close()
3888
            cnx.close()
3889
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3890
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
3891
3892
        cursor.execute(" DELETE FROM tbl_microgrids_photovoltaics "
3893
                       " WHERE id = %s ", (pid,))
3894
        cnx.commit()
3895
3896
        cursor.close()
3897
        cnx.close()
3898
3899
        resp.status = falcon.HTTP_204
3900
3901
    @staticmethod
3902
    @user_logger
3903
    def on_put(req, resp, id_, pid):
3904
        """Handles PUT requests"""
3905
        admin_control(req)
3906
        try:
3907
            raw_json = req.stream.read().decode('utf-8')
3908
        except Exception as ex:
3909
            raise falcon.HTTPError(status=falcon.HTTP_400,
3910
                                   title='API.BAD_REQUEST',
3911
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3912
        if not id_.isdigit() or int(id_) <= 0:
3913
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3914
                                   description='API.INVALID_MICROGRID_ID')
3915
        if not pid.isdigit() or int(pid) <= 0:
3916
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3917
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
3918
3919
        new_values = json.loads(raw_json)
3920
3921
        if 'name' not in new_values['data'].keys() or \
3922
                not isinstance(new_values['data']['name'], str) or \
3923
                len(str.strip(new_values['data']['name'])) == 0:
3924
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3925
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_NAME')
3926
        name = str.strip(new_values['data']['name'])
3927
3928
        if 'power_point_id' not in new_values['data'].keys() or \
3929
                not isinstance(new_values['data']['power_point_id'], int) or \
3930
                new_values['data']['power_point_id'] <= 0:
3931
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3932
                                   description='API.INVALID_POWER_POINT_ID')
3933
        power_point_id = new_values['data']['power_point_id']
3934
3935
        if 'meter_id' not in new_values['data'].keys() or \
3936
                not isinstance(new_values['data']['meter_id'], int) or \
3937
                new_values['data']['meter_id'] <= 0:
3938
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3939
                                   description='API.INVALID_METER_ID')
3940
        meter_id = new_values['data']['meter_id']
3941
3942
        if 'rated_power' not in new_values['data'].keys() or \
3943
                not (isinstance(new_values['data']['rated_power'], float) or
3944
                     isinstance(new_values['data']['rated_power'], int)):
3945
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3946
                                   description='API.INVALID_RATED_POWER')
3947
        rated_power = float(new_values['data']['rated_power'])
3948
3949
        cnx = mysql.connector.connect(**config.myems_system_db)
3950
        cursor = cnx.cursor()
3951
3952
        cursor.execute(" SELECT name "
3953
                       " FROM tbl_microgrids "
3954
                       " WHERE id = %s ", (id_,))
3955
        if cursor.fetchone() is None:
3956
            cursor.close()
3957
            cnx.close()
3958
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3959
                                   description='API.MICROGRID_NOT_FOUND')
3960
3961
        cursor.execute(" SELECT name "
3962
                       " FROM tbl_microgrids_photovoltaics "
3963
                       " WHERE id = %s ", (pid,))
3964
        if cursor.fetchone() is None:
3965
            cursor.close()
3966
            cnx.close()
3967
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3968
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
3969
3970
        cursor.execute(" SELECT name "
3971
                       " FROM tbl_microgrids_photovoltaics "
3972
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
3973
                       (id_, name, pid))
3974
        if cursor.fetchone() is not None:
3975
            cursor.close()
3976
            cnx.close()
3977
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3978
                                   description='API.MICROGRID_PHOTOVOLTAIC_NAME_IS_ALREADY_IN_USE')
3979
3980
        cursor.execute(" SELECT name "
3981
                       " FROM tbl_points "
3982
                       " WHERE id = %s ",
3983
                       (power_point_id,))
3984
        if cursor.fetchone() is None:
3985
            cursor.close()
3986
            cnx.close()
3987
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3988
                                   description='API.POWER_POINT_NOT_FOUND')
3989
3990
        cursor.execute(" SELECT name "
3991
                       " FROM tbl_meters "
3992
                       " WHERE id = %s ",
3993
                       (meter_id,))
3994
        if cursor.fetchone() is None:
3995
            cursor.close()
3996
            cnx.close()
3997
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3998
                                   description='API.METER_NOT_FOUND')
3999
4000
        update_row = (" UPDATE tbl_microgrids_photovoltaics "
4001
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_power = %s "
4002
                      " WHERE id = %s ")
4003
        cursor.execute(update_row, (name,
4004
                                    id_,
4005
                                    power_point_id,
4006
                                    meter_id,
4007
                                    rated_power,
4008
                                    pid))
4009
        cnx.commit()
4010
4011
        cursor.close()
4012
        cnx.close()
4013
4014
        resp.status = falcon.HTTP_200
4015
4016
4017
class MicrogridPowerconversionsystemCollection:
4018
    def __init__(self):
4019
        """Initializes MicrogridPowerconversionsystemCollection"""
4020
        pass
4021
4022
    @staticmethod
4023
    def on_options(req, resp, id_):
4024
        resp.status = falcon.HTTP_200
4025
4026
    @staticmethod
4027
    def on_get(req, resp, id_):
4028
        access_control(req)
4029
        if not id_.isdigit() or int(id_) <= 0:
4030
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4031
                                   description='API.INVALID_MICROGRID_ID')
4032
4033
        cnx = mysql.connector.connect(**config.myems_system_db)
4034
        cursor = cnx.cursor()
4035
4036
        cursor.execute(" SELECT name "
4037
                       " FROM tbl_microgrids "
4038
                       " WHERE id = %s ", (id_,))
4039
        if cursor.fetchone() is None:
4040
            cursor.close()
4041
            cnx.close()
4042
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4043
                                   description='API.MICROGRID_NOT_FOUND')
4044
4045
        # query point dict
4046
        query = (" SELECT id, name "
4047
                 " FROM tbl_points ")
4048
        cursor.execute(query)
4049
        rows_points = cursor.fetchall()
4050
4051
        point_dict = dict()
4052
        if rows_points is not None and len(rows_points) > 0:
4053
            for row in rows_points:
4054
                point_dict[row[0]] = {"id": row[0],
4055
                                      "name": row[1]}
4056
        # query command dict
4057
        query = (" SELECT id, name "
4058
                 " FROM tbl_commands ")
4059
        cursor.execute(query)
4060
        rows_commands = cursor.fetchall()
4061
4062
        command_dict = dict()
4063
        if rows_commands is not None and len(rows_commands) > 0:
4064
            for row in rows_commands:
4065
                command_dict[row[0]] = {"id": row[0],
4066
                                        "name": row[1]}
4067
4068
        query = (" SELECT id, name, uuid, run_state_point_id, rated_output_power, "
4069
                 "        today_charge_energy_point_id, today_discharge_energy_point_id, "
4070
                 "        total_charge_energy_point_id, total_discharge_energy_point_id "
4071
                 " FROM tbl_microgrids_power_conversion_systems "
4072
                 " WHERE microgrid_id = %s "
4073
                 " ORDER BY name ")
4074
        cursor.execute(query, (id_,))
4075
        rows = cursor.fetchall()
4076
4077
        result = list()
4078
        if rows is not None and len(rows) > 0:
4079
            for row in rows:
4080
                meta_result = {"id": row[0],
4081
                               "name": row[1],
4082
                               "uuid": row[2],
4083
                               "run_state_point": point_dict.get(row[3]),
4084
                               "rated_output_power": row[4],
4085
                               "today_charge_energy_point": point_dict.get(row[5]),
4086
                               "today_discharge_energy_point": point_dict.get(row[6]),
4087
                               "total_charge_energy_point": point_dict.get(row[7]),
4088
                               "total_discharge_energy_point": point_dict.get(row[8])}
4089
                result.append(meta_result)
4090
4091
        resp.text = json.dumps(result)
4092
4093
    @staticmethod
4094
    @user_logger
4095
    def on_post(req, resp, id_):
4096
        """Handles POST requests"""
4097
        admin_control(req)
4098
        try:
4099
            raw_json = req.stream.read().decode('utf-8')
4100
        except Exception as ex:
4101
            raise falcon.HTTPError(status=falcon.HTTP_400,
4102
                                   title='API.BAD_REQUEST',
4103
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4104
        if not id_.isdigit() or int(id_) <= 0:
4105
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4106
                                   description='API.INVALID_MICROGRID_ID')
4107
4108
        cnx = mysql.connector.connect(**config.myems_system_db)
4109
        cursor = cnx.cursor()
4110
4111
        cursor.execute(" SELECT name "
4112
                       " FROM tbl_microgrids "
4113
                       " WHERE id = %s ", (id_,))
4114
        if cursor.fetchone() is None:
4115
            cursor.close()
4116
            cnx.close()
4117
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4118
                                   description='API.MICROGRID_NOT_FOUND')
4119
4120
        new_values = json.loads(raw_json)
4121
4122
        if 'name' not in new_values['data'].keys() or \
4123
                not isinstance(new_values['data']['name'], str) or \
4124
                len(str.strip(new_values['data']['name'])) == 0:
4125
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4126
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_NAME')
4127
        name = str.strip(new_values['data']['name'])
4128
4129
        if 'run_state_point_id' not in new_values['data'].keys() or \
4130
                not isinstance(new_values['data']['run_state_point_id'], int) or \
4131
                new_values['data']['run_state_point_id'] <= 0:
4132
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4133
                                   description='API.INVALID_RUN_STATE_POINT_ID')
4134
        run_state_point_id = new_values['data']['run_state_point_id']
4135
4136
        if 'rated_output_power' not in new_values['data'].keys() or \
4137
                not (isinstance(new_values['data']['rated_output_power'], float) or
4138
                     isinstance(new_values['data']['rated_output_power'], int)):
4139
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4140
                                   description='API.INVALID_RATED_OUTPUT_POWER')
4141
        rated_output_power = float(new_values['data']['rated_output_power'])
4142
4143
        if 'today_charge_energy_point_id' not in new_values['data'].keys() or \
4144
                not isinstance(new_values['data']['today_charge_energy_point_id'], int) or \
4145
                new_values['data']['today_charge_energy_point_id'] <= 0:
4146
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4147
                                   description='API.INVALID_TODAY_CHARGE_ENERGY_POINT_ID')
4148
        today_charge_energy_point_id = new_values['data']['today_charge_energy_point_id']
4149
4150
        if 'today_discharge_energy_point_id' not in new_values['data'].keys() or \
4151
                not isinstance(new_values['data']['today_discharge_energy_point_id'], int) or \
4152
                new_values['data']['today_discharge_energy_point_id'] <= 0:
4153
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4154
                                   description='API.INVALID_TODAY_DISCHARGE_ENERGY_POINT_ID')
4155
        today_discharge_energy_point_id = new_values['data']['today_discharge_energy_point_id']
4156
4157
        if 'total_charge_energy_point_id' not in new_values['data'].keys() or \
4158
                not isinstance(new_values['data']['total_charge_energy_point_id'], int) or \
4159
                new_values['data']['total_charge_energy_point_id'] <= 0:
4160
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4161
                                   description='API.INVALID_TOTAL_CHARGE_POINT_ID')
4162
        total_charge_energy_point_id = new_values['data']['total_charge_energy_point_id']
4163
4164
        if 'total_discharge_energy_point_id' not in new_values['data'].keys() or \
4165
                not isinstance(new_values['data']['total_discharge_energy_point_id'], int) or \
4166
                new_values['data']['total_discharge_energy_point_id'] <= 0:
4167
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4168
                                   description='API.INVALID_TOTAL_DISCHARGE_POINT_ID')
4169
        total_discharge_energy_point_id = new_values['data']['total_discharge_energy_point_id']
4170
4171
        cnx = mysql.connector.connect(**config.myems_system_db)
4172
        cursor = cnx.cursor()
4173
4174
        cursor.execute(" SELECT name "
4175
                       " FROM tbl_microgrids "
4176
                       " WHERE id = %s ",
4177
                       (id_,))
4178
        if cursor.fetchone() is None:
4179
            cursor.close()
4180
            cnx.close()
4181
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4182
                                   description='API.MICROGRID_NOT_FOUND')
4183
4184
        cursor.execute(" SELECT name "
4185
                       " FROM tbl_microgrids_power_conversion_systems "
4186
                       " WHERE microgrid_id = %s AND name = %s ",
4187
                       (id_, name,))
4188
        if cursor.fetchone() is not None:
4189
            cursor.close()
4190
            cnx.close()
4191
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4192
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NAME_IS_ALREADY_IN_USE')
4193
4194
        add_values = (" INSERT INTO tbl_microgrids_power_conversion_systems "
4195
                      "     (name, uuid, microgrid_id, run_state_point_id, rated_output_power, "
4196
                      "      today_charge_energy_point_id, today_discharge_energy_point_id, "
4197
                      "      total_charge_energy_point_id, total_discharge_energy_point_id) "
4198
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ")
4199
        cursor.execute(add_values, (name,
4200
                                    str(uuid.uuid4()),
4201
                                    id_,
4202
                                    run_state_point_id,
4203
                                    rated_output_power,
4204
                                    today_charge_energy_point_id,
4205
                                    today_discharge_energy_point_id,
4206
                                    total_charge_energy_point_id,
4207
                                    total_discharge_energy_point_id
4208
                                    ))
4209
        new_id = cursor.lastrowid
4210
        cnx.commit()
4211
        cursor.close()
4212
        cnx.close()
4213
4214
        resp.status = falcon.HTTP_201
4215
        resp.location = '/microgridpowerconversionsystems/' + str(new_id)
4216
4217
4218
class MicrogridPowerconversionsystemItem:
4219
    def __init__(self):
4220
        """Initializes MicrogridPowerconversionsystemItem"""
4221
        pass
4222
4223
    @staticmethod
4224
    def on_options(req, resp, id_, pid):
4225
        resp.status = falcon.HTTP_200
4226
4227
    @staticmethod
4228
    def on_get(req, resp, id_, pid):
4229
        access_control(req)
4230
        if not id_.isdigit() or int(id_) <= 0:
4231
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4232
                                   description='API.INVALID_MICROGRID_ID')
4233
        if not pid.isdigit() or int(pid) <= 0:
4234
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4235
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_ID')
4236
4237
        cnx = mysql.connector.connect(**config.myems_system_db)
4238
        cursor = cnx.cursor()
4239
4240
        cursor.execute(" SELECT name "
4241
                       " FROM tbl_microgrids "
4242
                       " WHERE id = %s ", (id_,))
4243
        if cursor.fetchone() is None:
4244
            cursor.close()
4245
            cnx.close()
4246
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4247
                                   description='API.MICROGRID_NOT_FOUND')
4248
4249
        # query microgrid dict
4250
        query = (" SELECT id, name, uuid "
4251
                 " FROM tbl_microgrids ")
4252
        cursor.execute(query)
4253
        rows_microgrids = cursor.fetchall()
4254
4255
        microgrid_dict = dict()
4256
        if rows_microgrids is not None and len(rows_microgrids) > 0:
4257
            for row in rows_microgrids:
4258
                microgrid_dict[row[0]] = {"id": row[0],
4259
                                          "name": row[1],
4260
                                          "uuid": row[2]}
4261
        # query meter dict
4262
        query = (" SELECT id, name, uuid "
4263
                 " FROM tbl_meters ")
4264
        cursor.execute(query)
4265
        rows_meters = cursor.fetchall()
4266
4267
        meter_dict = dict()
4268
        if rows_meters is not None and len(rows_meters) > 0:
4269
            for row in rows_meters:
4270
                meter_dict[row[0]] = {"id": row[0],
4271
                                      "name": row[1],
4272
                                      "uuid": row[2]}
4273
        # query point dict
4274
        query = (" SELECT id, name "
4275
                 " FROM tbl_points ")
4276
        cursor.execute(query)
4277
        rows_points = cursor.fetchall()
4278
4279
        point_dict = dict()
4280
        if rows_points is not None and len(rows_points) > 0:
4281
            for row in rows_points:
4282
                point_dict[row[0]] = {"id": row[0],
4283
                                      "name": row[1]}
4284
4285
        # query command dict
4286
        query = (" SELECT id, name "
4287
                 " FROM tbl_commands ")
4288
        cursor.execute(query)
4289
        rows_commands = cursor.fetchall()
4290
4291
        command_dict = dict()
4292
        if rows_commands is not None and len(rows_commands) > 0:
4293
            for row in rows_commands:
4294
                command_dict[row[0]] = {"id": row[0],
4295
                                        "name": row[1]}
4296
4297
        query = (" SELECT id, name, uuid, microgrid_id, run_state_point_id, rated_output_power, "
4298
                 "        today_charge_energy_point_id, today_discharge_energy_point_id, "
4299
                 "        total_charge_energy_point_id, total_discharge_energy_point_id "
4300
                 " FROM tbl_microgrids_power_conversion_systems "
4301
                 " WHERE id = %s ")
4302
        cursor.execute(query, (pid,))
4303
        row = cursor.fetchone()
4304
        cursor.close()
4305
        cnx.close()
4306
4307
        if row is None:
4308
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4309
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
4310
        else:
4311
            meta_result = {"id": row[0],
4312
                           "name": row[1],
4313
                           "uuid": row[2],
4314
                           "microgrid": microgrid_dict.get(row[3]),
4315
                           "run_state_point": point_dict.get(row[4]),
4316
                           "rated_output_power": row[5],
4317
                           "today_charge_energy_point": point_dict.get(row[6]),
4318
                           "today_discharge_energy_point": point_dict.get(row[7]),
4319
                           "total_charge_energy_point": point_dict.get(row[8]),
4320
                           "total_discharge_energy_point": point_dict.get(row[9])}
4321
4322
        resp.text = json.dumps(meta_result)
4323
4324
    @staticmethod
4325
    @user_logger
4326
    def on_delete(req, resp, id_, pid):
4327
        admin_control(req)
4328
        if not id_.isdigit() or int(id_) <= 0:
4329
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4330
                                   description='API.INVALID_MICROGRID_ID')
4331
        if not pid.isdigit() or int(pid) <= 0:
4332
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4333
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_ID')
4334
4335
        cnx = mysql.connector.connect(**config.myems_system_db)
4336
        cursor = cnx.cursor()
4337
4338
        cursor.execute(" SELECT name "
4339
                       " FROM tbl_microgrids "
4340
                       " WHERE id = %s ", (id_,))
4341
        if cursor.fetchone() is None:
4342
            cursor.close()
4343
            cnx.close()
4344
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4345
                                   description='API.MICROGRID_NOT_FOUND')
4346
4347
        cursor.execute(" SELECT name "
4348
                       " FROM tbl_microgrids_power_conversion_systems "
4349
                       " WHERE id = %s ", (pid,))
4350
        if cursor.fetchone() is None:
4351
            cursor.close()
4352
            cnx.close()
4353
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4354
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
4355
4356
        cursor.execute(" DELETE FROM tbl_microgrids_power_conversion_systems "
4357
                       " WHERE id = %s ", (pid,))
4358
        cnx.commit()
4359
4360
        cursor.close()
4361
        cnx.close()
4362
4363
        resp.status = falcon.HTTP_204
4364
4365
    @staticmethod
4366
    @user_logger
4367
    def on_put(req, resp, id_, pid):
4368
        """Handles PUT requests"""
4369
        admin_control(req)
4370
        try:
4371
            raw_json = req.stream.read().decode('utf-8')
4372
        except Exception as ex:
4373
            raise falcon.HTTPError(status=falcon.HTTP_400,
4374
                                   title='API.BAD_REQUEST',
4375
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4376
        if not id_.isdigit() or int(id_) <= 0:
4377
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4378
                                   description='API.INVALID_MICROGRID_ID')
4379
        if not pid.isdigit() or int(pid) <= 0:
4380
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4381
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_ID')
4382
4383
        new_values = json.loads(raw_json)
4384
4385
        if 'name' not in new_values['data'].keys() or \
4386
                not isinstance(new_values['data']['name'], str) or \
4387
                len(str.strip(new_values['data']['name'])) == 0:
4388
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4389
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_NAME')
4390
        name = str.strip(new_values['data']['name'])
4391
4392
        if 'run_state_point_id' not in new_values['data'].keys() or \
4393
                not isinstance(new_values['data']['run_state_point_id'], int) or \
4394
                new_values['data']['run_state_point_id'] <= 0:
4395
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4396
                                   description='API.INVALID_RUN_STATE_POINT_ID')
4397
        run_state_point_id = new_values['data']['run_state_point_id']
4398
4399
        if 'rated_output_power' not in new_values['data'].keys() or \
4400
                not (isinstance(new_values['data']['rated_output_power'], float) or
4401
                     isinstance(new_values['data']['rated_output_power'], int)):
4402
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4403
                                   description='API.INVALID_RATED_OUTPUT_POWER')
4404
        rated_output_power = float(new_values['data']['rated_output_power'])
4405
4406
        if 'today_charge_energy_point_id' not in new_values['data'].keys() or \
4407
                not isinstance(new_values['data']['today_charge_energy_point_id'], int) or \
4408
                new_values['data']['today_charge_energy_point_id'] <= 0:
4409
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4410
                                   description='API.INVALID_TODAY_CHARGE_ENERGY_POINT_ID')
4411
        today_charge_energy_point_id = new_values['data']['today_charge_energy_point_id']
4412
4413
        if 'today_discharge_energy_point_id' not in new_values['data'].keys() or \
4414
                not isinstance(new_values['data']['today_discharge_energy_point_id'], int) or \
4415
                new_values['data']['today_discharge_energy_point_id'] <= 0:
4416
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4417
                                   description='API.INVALID_TODAY_DISCHARGE_ENERGY_POINT_ID')
4418
        today_discharge_energy_point_id = new_values['data']['today_discharge_energy_point_id']
4419
4420
        if 'total_charge_energy_point_id' not in new_values['data'].keys() or \
4421
                not isinstance(new_values['data']['total_charge_energy_point_id'], int) or \
4422
                new_values['data']['total_charge_energy_point_id'] <= 0:
4423
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4424
                                   description='API.INVALID_TOTAL_CHARGE_POINT_ID')
4425
        total_charge_energy_point_id = new_values['data']['total_charge_energy_point_id']
4426
4427
        if 'total_discharge_energy_point_id' not in new_values['data'].keys() or \
4428
                not isinstance(new_values['data']['total_discharge_energy_point_id'], int) or \
4429
                new_values['data']['total_discharge_energy_point_id'] <= 0:
4430
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4431
                                   description='API.INVALID_TOTAL_DISCHARGE_POINT_ID')
4432
        total_discharge_energy_point_id = new_values['data']['total_discharge_energy_point_id']
4433
4434
        cnx = mysql.connector.connect(**config.myems_system_db)
4435
        cursor = cnx.cursor()
4436
4437
        cursor.execute(" SELECT name "
4438
                       " FROM tbl_microgrids "
4439
                       " WHERE id = %s ", (id_,))
4440
        if cursor.fetchone() is None:
4441
            cursor.close()
4442
            cnx.close()
4443
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4444
                                   description='API.MICROGRID_NOT_FOUND')
4445
4446
        cursor.execute(" SELECT name "
4447
                       " FROM tbl_microgrids_power_conversion_systems "
4448
                       " WHERE id = %s ", (pid,))
4449
        if cursor.fetchone() is None:
4450
            cursor.close()
4451
            cnx.close()
4452
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4453
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
4454
4455
        cursor.execute(" SELECT name "
4456
                       " FROM tbl_microgrids_power_conversion_systems "
4457
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
4458
                       (id_, name, pid))
4459
        if cursor.fetchone() is not None:
4460
            cursor.close()
4461
            cnx.close()
4462
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4463
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NAME_IS_ALREADY_IN_USE')
4464
4465
        update_row = (" UPDATE tbl_microgrids_power_conversion_systems "
4466
                      " SET name = %s, microgrid_id = %s, run_state_point_id = %s, rated_output_power = %s, "
4467
                      "     today_charge_energy_point_id = %s, today_discharge_energy_point_id = %s, "
4468
                      "     total_charge_energy_point_id = %s, total_discharge_energy_point_id = %s "
4469
                      " WHERE id = %s ")
4470
        cursor.execute(update_row, (name,
4471
                                    id_,
4472
                                    run_state_point_id,
4473
                                    rated_output_power,
4474
                                    today_charge_energy_point_id,
4475
                                    today_discharge_energy_point_id,
4476
                                    total_charge_energy_point_id,
4477
                                    total_discharge_energy_point_id,
4478
                                    pid))
4479
        cnx.commit()
4480
4481
        cursor.close()
4482
        cnx.close()
4483
4484
        resp.status = falcon.HTTP_200
4485
4486
4487 View Code Duplication
class MicrogridScheduleCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4488
    def __init__(self):
4489
        """Initializes Class"""
4490
        pass
4491
4492
    @staticmethod
4493
    def on_options(req, resp, id_):
4494
        resp.status = falcon.HTTP_200
4495
4496
    @staticmethod
4497
    def on_get(req, resp, id_):
4498
        access_control(req)
4499
        if not id_.isdigit() or int(id_) <= 0:
4500
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4501
                                   description='API.INVALID_MICROGRID_ID')
4502
4503
        cnx = mysql.connector.connect(**config.myems_system_db)
4504
        cursor = cnx.cursor()
4505
4506
        cursor.execute(" SELECT name "
4507
                       " FROM tbl_microgrids "
4508
                       " WHERE id = %s ", (id_,))
4509
        if cursor.fetchone() is None:
4510
            cursor.close()
4511
            cnx.close()
4512
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4513
                                   description='API.MICROGRID_NOT_FOUND')
4514
4515
        query = (" SELECT id, start_time_of_day, end_time_of_day, peak_type, power "
4516
                 " FROM tbl_microgrids_schedules "
4517
                 " WHERE microgrid_id = %s "
4518
                 " ORDER BY start_time_of_day ")
4519
        cursor.execute(query, (id_,))
4520
        rows = cursor.fetchall()
4521
4522
        result = list()
4523
        if rows is not None and len(rows) > 0:
4524
            for row in rows:
4525
                meta_result = {"id": row[0],
4526
                               "start_time_of_day": str(row[1]),
4527
                               "end_time_of_day": str(row[2]),
4528
                               "peak_type": row[3],
4529
                               "power": row[4],
4530
                               }
4531
                result.append(meta_result)
4532
4533
        resp.text = json.dumps(result)
4534
4535
    @staticmethod
4536
    @user_logger
4537
    def on_post(req, resp, id_):
4538
        """Handles POST requests"""
4539
        admin_control(req)
4540
        try:
4541
            raw_json = req.stream.read().decode('utf-8')
4542
        except Exception as ex:
4543
            raise falcon.HTTPError(status=falcon.HTTP_400,
4544
                                   title='API.BAD_REQUEST',
4545
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4546
        if not id_.isdigit() or int(id_) <= 0:
4547
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4548
                                   description='API.INVALID_MICROGRID_ID')
4549
4550
        cnx = mysql.connector.connect(**config.myems_system_db)
4551
        cursor = cnx.cursor()
4552
4553
        cursor.execute(" SELECT name "
4554
                       " FROM tbl_microgrids "
4555
                       " WHERE id = %s ", (id_,))
4556
        if cursor.fetchone() is None:
4557
            cursor.close()
4558
            cnx.close()
4559
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4560
                                   description='API.MICROGRID_NOT_FOUND')
4561
4562
        new_values = json.loads(raw_json)
4563
4564
        cnx = mysql.connector.connect(**config.myems_system_db)
4565
        cursor = cnx.cursor()
4566
4567
        cursor.execute(" SELECT name "
4568
                       " FROM tbl_microgrids "
4569
                       " WHERE id = %s ",
4570
                       (id_,))
4571
        if cursor.fetchone() is None:
4572
            cursor.close()
4573
            cnx.close()
4574
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4575
                                   description='API.MICROGRID_NOT_FOUND')
4576
4577
        add_schedule = (" INSERT INTO tbl_microgrids_schedules "
4578
                        "     (microgrid_id, start_time_of_day, end_time_of_day, peak_type, power) "
4579
                        " VALUES (%s, %s, %s, %s, %s) ")
4580
        cursor.execute(add_schedule, (id_,
4581
                                      new_values['data']['start_time_of_day'],
4582
                                      new_values['data']['end_time_of_day'],
4583
                                      new_values['data']['peak_type'],
4584
                                      new_values['data']['power']))
4585
        new_id = cursor.lastrowid
4586
        cnx.commit()
4587
        cursor.close()
4588
        cnx.close()
4589
        resp.status = falcon.HTTP_201
4590
        resp.location = '/energystoragecontainerschedules/' + str(new_id)
4591
4592
4593 View Code Duplication
class MicrogridScheduleItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4594
    def __init__(self):
4595
        """Initializes Class"""
4596
        pass
4597
4598
    @staticmethod
4599
    def on_options(req, resp, id_, sid):
4600
        resp.status = falcon.HTTP_200
4601
4602
    @staticmethod
4603
    def on_get(req, resp, id_, sid):
4604
        access_control(req)
4605
        if not id_.isdigit() or int(id_) <= 0:
4606
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4607
                                   description='API.INVALID_MICROGRID_ID')
4608
        if not sid.isdigit() or int(sid) <= 0:
4609
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4610
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4611
4612
        cnx = mysql.connector.connect(**config.myems_system_db)
4613
        cursor = cnx.cursor()
4614
4615
        cursor.execute(" SELECT name "
4616
                       " FROM tbl_microgrids "
4617
                       " WHERE id = %s ", (id_,))
4618
        if cursor.fetchone() is None:
4619
            cursor.close()
4620
            cnx.close()
4621
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4622
                                   description='API.MICROGRID_NOT_FOUND')
4623
4624
        query = (" SELECT id, name, uuid "
4625
                 " FROM tbl_microgrids ")
4626
        cursor.execute(query)
4627
        rows_energystoragecontainers = cursor.fetchall()
4628
4629
        microgrid_dict = dict()
4630
        if rows_energystoragecontainers is not None and len(rows_energystoragecontainers) > 0:
4631
            for row in rows_energystoragecontainers:
4632
                microgrid_dict[row[0]] = {"id": row[0],
4633
                                          "name": row[1],
4634
                                          "uuid": row[2]}
4635
4636
        query = (" SELECT id, start_time_of_day, end_time_of_day, peak_type, power "
4637
                 " FROM tbl_microgrids_schedules "
4638
                 " WHERE id = %s ")
4639
        cursor.execute(query, (sid,))
4640
        row = cursor.fetchone()
4641
        cursor.close()
4642
        cnx.close()
4643
4644
        if row is None:
4645
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4646
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4647
        else:
4648
            meta_result = {"id": row[0],
4649
                           "start_time_of_day": str(row[1]),
4650
                           "end_time_of_day": str(row[2]),
4651
                           "peak_type": row[3],
4652
                           "power": row[4]}
4653
4654
        resp.text = json.dumps(meta_result)
4655
4656
    @staticmethod
4657
    @user_logger
4658
    def on_delete(req, resp, id_, sid):
4659
        admin_control(req)
4660
        if not id_.isdigit() or int(id_) <= 0:
4661
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4662
                                   description='API.INVALID_MICROGRID_ID')
4663
        if not sid.isdigit() or int(sid) <= 0:
4664
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4665
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4666
4667
        cnx = mysql.connector.connect(**config.myems_system_db)
4668
        cursor = cnx.cursor()
4669
4670
        cursor.execute(" SELECT name "
4671
                       " FROM tbl_microgrids "
4672
                       " WHERE id = %s ", (id_,))
4673
        if cursor.fetchone() is None:
4674
            cursor.close()
4675
            cnx.close()
4676
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4677
                                   description='API.MICROGRID_NOT_FOUND')
4678
4679
        cursor.execute(" SELECT id "
4680
                       " FROM tbl_microgrids_schedules "
4681
                       " WHERE id = %s ", (sid,))
4682
        if cursor.fetchone() is None:
4683
            cursor.close()
4684
            cnx.close()
4685
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4686
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4687
4688
        cursor.execute(" DELETE FROM tbl_microgrids_schedules "
4689
                       " WHERE id = %s ", (sid,))
4690
        cnx.commit()
4691
4692
        cursor.close()
4693
        cnx.close()
4694
4695
        resp.status = falcon.HTTP_204
4696
4697
    @staticmethod
4698
    @user_logger
4699
    def on_put(req, resp, id_, sid):
4700
        """Handles PUT requests"""
4701
        admin_control(req)
4702
        try:
4703
            raw_json = req.stream.read().decode('utf-8')
4704
        except Exception as ex:
4705
            raise falcon.HTTPError(status=falcon.HTTP_400,
4706
                                   title='API.BAD_REQUEST',
4707
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4708
        if not id_.isdigit() or int(id_) <= 0:
4709
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4710
                                   description='API.INVALID_MICROGRID_ID')
4711
        if not sid.isdigit() or int(sid) <= 0:
4712
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4713
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4714
4715
        new_values = json.loads(raw_json)
4716
4717
        if 'start_time_of_day' not in new_values['data'].keys() or \
4718
                not isinstance(new_values['data']['start_time_of_day'], str) or \
4719
                len(str.strip(new_values['data']['start_time_of_day'])) == 0:
4720
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4721
                                   description='API.INVALID_START_TIME_OF_DAY')
4722
        start_time_of_day = str.strip(new_values['data']['start_time_of_day'])
4723
4724
        if 'end_time_of_day' not in new_values['data'].keys() or \
4725
                not isinstance(new_values['data']['end_time_of_day'], str) or \
4726
                len(str.strip(new_values['data']['end_time_of_day'])) == 0:
4727
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4728
                                   description='API.INVALID_END_TIME_OF_DAY')
4729
        end_time_of_day = str.strip(new_values['data']['end_time_of_day'])
4730
4731
        if 'peak_type' not in new_values['data'].keys() or \
4732
                not isinstance(new_values['data']['peak_type'], str) or \
4733
                len(str.strip(new_values['data']['peak_type'])) == 0:
4734
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4735
                                   description='API.INVALID_PEAK_TYPE')
4736
        peak_type = str.strip(new_values['data']['peak_type'])
4737
4738
        if 'power' not in new_values['data'].keys() or \
4739
                not (isinstance(new_values['data']['power'], float) or
4740
                     isinstance(new_values['data']['power'], int)):
4741
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4742
                                   description='API.INVALID_POWER')
4743
        power = float(new_values['data']['power'])
4744
4745
        cnx = mysql.connector.connect(**config.myems_system_db)
4746
        cursor = cnx.cursor()
4747
4748
        cursor.execute(" SELECT name "
4749
                       " FROM tbl_microgrids "
4750
                       " WHERE id = %s ", (id_,))
4751
        if cursor.fetchone() is None:
4752
            cursor.close()
4753
            cnx.close()
4754
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4755
                                   description='API.MICROGRID_NOT_FOUND')
4756
4757
        cursor.execute(" SELECT id "
4758
                       " FROM tbl_microgrids_schedules "
4759
                       " WHERE id = %s ", (sid,))
4760
        if cursor.fetchone() is None:
4761
            cursor.close()
4762
            cnx.close()
4763
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4764
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4765
4766
        update_row = (" UPDATE tbl_microgrids_schedules "
4767
                      " SET start_time_of_day = %s, end_time_of_day = %s, peak_type = %s, power = %s "
4768
                      " WHERE id = %s ")
4769
        cursor.execute(update_row, (start_time_of_day,
4770
                                    end_time_of_day,
4771
                                    peak_type,
4772
                                    power,
4773
                                    sid))
4774
        cnx.commit()
4775
4776
        cursor.close()
4777
        cnx.close()
4778
4779
        resp.status = falcon.HTTP_200
4780
4781
4782 View Code Duplication
class MicrogridSensorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4783
    def __init__(self):
4784
        """Initializes Class"""
4785
        pass
4786
4787
    @staticmethod
4788
    def on_options(req, resp, id_):
4789
        resp.status = falcon.HTTP_200
4790
4791
    @staticmethod
4792
    def on_get(req, resp, id_):
4793
        access_control(req)
4794
        if not id_.isdigit() or int(id_) <= 0:
4795
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4796
                                   description='API.INVALID_MICROGRID_ID')
4797
4798
        cnx = mysql.connector.connect(**config.myems_system_db)
4799
        cursor = cnx.cursor()
4800
4801
        cursor.execute(" SELECT name "
4802
                       " FROM tbl_microgrids "
4803
                       " WHERE id = %s ", (id_,))
4804
        if cursor.fetchone() is None:
4805
            cursor.close()
4806
            cnx.close()
4807
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4808
                                   description='API.MICROGRID_NOT_FOUND')
4809
4810
        query = (" SELECT s.id, s.name, s.uuid "
4811
                 " FROM tbl_microgrids m, tbl_microgrids_sensors ms, tbl_sensors s "
4812
                 " WHERE ms.microgrid_id = m.id AND s.id = ms.sensor_id AND m.id = %s "
4813
                 " ORDER BY s.id ")
4814
        cursor.execute(query, (id_,))
4815
        rows = cursor.fetchall()
4816
4817
        result = list()
4818
        if rows is not None and len(rows) > 0:
4819
            for row in rows:
4820
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
4821
                result.append(meta_result)
4822
4823
        resp.text = json.dumps(result)
4824
4825
    @staticmethod
4826
    @user_logger
4827
    def on_post(req, resp, id_):
4828
        """Handles POST requests"""
4829
        admin_control(req)
4830
        try:
4831
            raw_json = req.stream.read().decode('utf-8')
4832
        except Exception as ex:
4833
            raise falcon.HTTPError(status=falcon.HTTP_400,
4834
                                   title='API.BAD_REQUEST',
4835
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4836
4837
        if not id_.isdigit() or int(id_) <= 0:
4838
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4839
                                   description='API.INVALID_MICROGRID_ID')
4840
4841
        new_values = json.loads(raw_json)
4842
4843
        if 'sensor_id' not in new_values['data'].keys() or \
4844
                not isinstance(new_values['data']['sensor_id'], int) or \
4845
                new_values['data']['sensor_id'] <= 0:
4846
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4847
                                   description='API.INVALID_SENSOR_ID')
4848
        sensor_id = new_values['data']['sensor_id']
4849
4850
        cnx = mysql.connector.connect(**config.myems_system_db)
4851
        cursor = cnx.cursor()
4852
4853
        cursor.execute(" SELECT name "
4854
                       " from tbl_microgrids "
4855
                       " WHERE id = %s ", (id_,))
4856
        if cursor.fetchone() is None:
4857
            cursor.close()
4858
            cnx.close()
4859
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4860
                                   description='API.MICROGRID_NOT_FOUND')
4861
4862
        cursor.execute(" SELECT name "
4863
                       " FROM tbl_sensors "
4864
                       " WHERE id = %s ", (sensor_id,))
4865
        if cursor.fetchone() is None:
4866
            cursor.close()
4867
            cnx.close()
4868
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4869
                                   description='API.SENSOR_NOT_FOUND')
4870
4871
        query = (" SELECT id " 
4872
                 " FROM tbl_microgrids_sensors "
4873
                 " WHERE microgrid_id = %s AND sensor_id = %s")
4874
        cursor.execute(query, (id_, sensor_id,))
4875
        if cursor.fetchone() is not None:
4876
            cursor.close()
4877
            cnx.close()
4878
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4879
                                   description='API.MICROGRID_SENSOR_RELATION_EXISTS')
4880
4881
        add_row = (" INSERT INTO tbl_microgrids_sensors (microgrid_id, sensor_id) "
4882
                   " VALUES (%s, %s) ")
4883
        cursor.execute(add_row, (id_, sensor_id,))
4884
        cnx.commit()
4885
        cursor.close()
4886
        cnx.close()
4887
4888
        resp.status = falcon.HTTP_201
4889
        resp.location = '/microgrids/' + str(id_) + '/sensors/' + str(sensor_id)
4890
4891
4892 View Code Duplication
class MicrogridSensorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4893
    def __init__(self):
4894
        """Initializes Class"""
4895
        pass
4896
4897
    @staticmethod
4898
    def on_options(req, resp, id_, sid):
4899
        resp.status = falcon.HTTP_200
4900
4901
    @staticmethod
4902
    @user_logger
4903
    def on_delete(req, resp, id_, sid):
4904
        admin_control(req)
4905
        if not id_.isdigit() or int(id_) <= 0:
4906
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4907
                                   description='API.INVALID_MICROGRID_ID')
4908
4909
        if not sid.isdigit() or int(sid) <= 0:
4910
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4911
                                   description='API.INVALID_SENSOR_ID')
4912
4913
        cnx = mysql.connector.connect(**config.myems_system_db)
4914
        cursor = cnx.cursor()
4915
4916
        cursor.execute(" SELECT name "
4917
                       " FROM tbl_microgrids "
4918
                       " WHERE id = %s ", (id_,))
4919
        if cursor.fetchone() is None:
4920
            cursor.close()
4921
            cnx.close()
4922
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4923
                                   description='API.MICROGRID_NOT_FOUND')
4924
4925
        cursor.execute(" SELECT name "
4926
                       " FROM tbl_sensors "
4927
                       " WHERE id = %s ", (sid,))
4928
        if cursor.fetchone() is None:
4929
            cursor.close()
4930
            cnx.close()
4931
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4932
                                   description='API.SENSOR_NOT_FOUND')
4933
4934
        cursor.execute(" SELECT id "
4935
                       " FROM tbl_microgrids_sensors "
4936
                       " WHERE microgrid_id = %s AND sensor_id = %s ", (id_, sid))
4937
        if cursor.fetchone() is None:
4938
            cursor.close()
4939
            cnx.close()
4940
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4941
                                   description='API.MICROGRID_SENSOR_RELATION_NOT_FOUND')
4942
4943
        cursor.execute(" DELETE FROM tbl_microgrids_sensors "
4944
                       " WHERE microgrid_id = %s AND sensor_id = %s ", (id_, sid))
4945
        cnx.commit()
4946
4947
        cursor.close()
4948
        cnx.close()
4949
4950
        resp.status = falcon.HTTP_204
4951
4952
4953 View Code Duplication
class MicrogridUserCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4954
    def __init__(self):
4955
        """Initializes Class"""
4956
        pass
4957
4958
    @staticmethod
4959
    def on_options(req, resp, id_):
4960
        resp.status = falcon.HTTP_200
4961
4962
    @staticmethod
4963
    def on_get(req, resp, id_):
4964
        access_control(req)
4965
        if not id_.isdigit() or int(id_) <= 0:
4966
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4967
                                   description='API.INVALID_MICROGRID_ID')
4968
4969
        cnx = mysql.connector.connect(**config.myems_system_db)
4970
        cursor = cnx.cursor()
4971
        cursor.execute(" SELECT name "
4972
                       " FROM tbl_microgrids "
4973
                       " WHERE id = %s ", (id_,))
4974
        if cursor.fetchone() is None:
4975
            cursor.close()
4976
            cnx.close()
4977
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4978
                                   description='API.MICROGRID_NOT_FOUND')
4979
4980
        query = (" SELECT u.id, u.name, u.uuid "
4981
                 " FROM tbl_microgrids m, tbl_microgrids_users mu, "
4982
                 + config.myems_user_db['database'] + ".tbl_users u "
4983
                 " WHERE mu.microgrid_id = m.id AND u.id = mu.user_id AND m.id = %s "
4984
                 " ORDER BY u.id ")
4985
        cursor.execute(query, (id_,))
4986
        rows = cursor.fetchall()
4987
        result = list()
4988
        if rows is not None and len(rows) > 0:
4989
            for row in rows:
4990
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
4991
                result.append(meta_result)
4992
4993
        cursor.close()
4994
        cnx.close()
4995
        resp.text = json.dumps(result)
4996
4997
    @staticmethod
4998
    @user_logger
4999
    def on_post(req, resp, id_):
5000
        """Handles POST requests"""
5001
        admin_control(req)
5002
        try:
5003
            raw_json = req.stream.read().decode('utf-8')
5004
        except Exception as ex:
5005
            raise falcon.HTTPError(status=falcon.HTTP_400,
5006
                                   title='API.BAD_REQUEST',
5007
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5008
5009
        if not id_.isdigit() or int(id_) <= 0:
5010
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5011
                                   description='API.INVALID_MICROGRID_ID')
5012
5013
        new_values = json.loads(raw_json)
5014
        if 'user_id' not in new_values['data'].keys() or \
5015
                not isinstance(new_values['data']['user_id'], int) or \
5016
                new_values['data']['user_id'] <= 0:
5017
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5018
                                   description='API.INVALID_USER_ID')
5019
        user_id = new_values['data']['user_id']
5020
        cnx = mysql.connector.connect(**config.myems_system_db)
5021
        cursor = cnx.cursor()
5022
        cursor.execute(" SELECT name "
5023
                       " from tbl_microgrids "
5024
                       " WHERE id = %s ", (id_,))
5025
        if cursor.fetchone() is None:
5026
            cursor.close()
5027
            cnx.close()
5028
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5029
                                   description='API.MICROGRID_NOT_FOUND')
5030
5031
        cnx_user = mysql.connector.connect(**config.myems_user_db)
5032
        cursor_user = cnx_user.cursor()
5033
        cursor_user.execute(" SELECT name"
5034
                            " FROM tbl_users "
5035
                            " WHERE id = %s ", (user_id,))
5036
        if cursor_user.fetchone() is None:
5037
            cursor_user.close()
5038
            cnx_user.close()
5039
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5040
                                   description='API.USER_NOT_FOUND')
5041
        query = (" SELECT id "
5042
                 " FROM tbl_microgrids_users "
5043
                 " WHERE microgrid_id = %s AND user_id = %s")
5044
        cursor.execute(query, (id_, user_id,))
5045
        if cursor.fetchone() is not None:
5046
            cursor.close()
5047
            cnx.close()
5048
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5049
                                   description='API.MICROGRID_USER_RELATION_EXISTS')
5050
        add_row = (" INSERT INTO tbl_microgrids_users (microgrid_id, user_id) "
5051
                   " VALUES (%s, %s) ")
5052
        cursor.execute(add_row, (id_, user_id,))
5053
        cnx.commit()
5054
        cursor.close()
5055
        cnx.close()
5056
        cursor_user.close()
5057
        cnx_user.close()
5058
5059
        resp.status = falcon.HTTP_201
5060
        resp.location = '/microgrids/' + str(id_) + '/users/' + str(user_id)
5061
5062
5063 View Code Duplication
class MicrogridUserItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5064
    def __init__(self):
5065
        """Initializes Class"""
5066
        pass
5067
5068
    @staticmethod
5069
    def on_options(req, resp, id_, uid):
5070
        resp.status = falcon.HTTP_200
5071
5072
    @staticmethod
5073
    @user_logger
5074
    def on_delete(req, resp, id_, uid):
5075
        # todo Verify if the user is bound when deleting it
5076
        admin_control(req)
5077
        if not id_.isdigit() or int(id_) <= 0:
5078
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5079
                                   description='API.INVALID_MICROGRID_ID')
5080
5081
        if not uid.isdigit() or int(uid) <= 0:
5082
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5083
                                   description='API.INVALID_USER_ID')
5084
5085
        cnx = mysql.connector.connect(**config.myems_system_db)
5086
        cursor = cnx.cursor()
5087
        cursor.execute(" SELECT name "
5088
                       " FROM tbl_microgrids "
5089
                       " WHERE id = %s ", (id_,))
5090
        if cursor.fetchone() is None:
5091
            cursor.close()
5092
            cnx.close()
5093
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5094
                                   description='API.MICROGRID_NOT_FOUND')
5095
5096
        cnx_user = mysql.connector.connect(**config.myems_user_db)
5097
        cursor_user = cnx_user.cursor()
5098
        cursor_user.execute(" SELECT name FROM tbl_users WHERE id = %s ", (uid,))
5099
        if cursor_user.fetchone() is None:
5100
            cursor_user.close()
5101
            cnx_user.close()
5102
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5103
                                   description='API.USER_NOT_FOUND')
5104
5105
        cursor.execute(" SELECT id "
5106
                       " FROM tbl_microgrids_users "
5107
                       " WHERE microgrid_id = %s AND user_id = %s ", (id_, uid))
5108
        if cursor.fetchone() is None:
5109
            cursor.close()
5110
            cnx.close()
5111
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5112
                                   description='API.MICROGRID_USER_RELATION_NOT_FOUND')
5113
5114
        cursor.execute(" DELETE FROM tbl_microgrids_users WHERE microgrid_id = %s AND user_id = %s ", (id_, uid))
5115
        cnx.commit()
5116
5117
        cursor.close()
5118
        cnx.close()
5119
        cursor_user.close()
5120
        cnx_user.close()
5121
5122
        resp.status = falcon.HTTP_204
5123
5124
5125
class MicrogridExport:
5126
    def __init__(self):
5127
        """"Initializes MicrogridExport"""
5128
        pass
5129
5130
    @staticmethod
5131
    def on_options(req, resp, id_):
5132
        resp.status = falcon.HTTP_200
5133
5134
    @staticmethod
5135
    def on_get(req, resp, id_):
5136
        access_control(req)
5137
        if not id_.isdigit() or int(id_) <= 0:
5138
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5139
                                   description='API.INVALID_MICROGRID_ID')
5140
5141
        cnx = mysql.connector.connect(**config.myems_system_db)
5142
        cursor = cnx.cursor()
5143
5144
        query = (" SELECT id, name, uuid "
5145
                 " FROM tbl_contacts ")
5146
        cursor.execute(query)
5147
        rows_contacts = cursor.fetchall()
5148
5149
        contact_dict = dict()
5150
        if rows_contacts is not None and len(rows_contacts) > 0:
5151
            for row in rows_contacts:
5152
                contact_dict[row[0]] = {"id": row[0],
5153
                                        "name": row[1],
5154
                                        "uuid": row[2]}
5155
5156
        query = (" SELECT id, name, uuid "
5157
                 " FROM tbl_cost_centers ")
5158
        cursor.execute(query)
5159
        rows_cost_centers = cursor.fetchall()
5160
5161
        cost_center_dict = dict()
5162
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
5163
            for row in rows_cost_centers:
5164
                cost_center_dict[row[0]] = {"id": row[0],
5165
                                            "name": row[1],
5166
                                            "uuid": row[2]}
5167
5168
        query = (" SELECT id, name, uuid, "
5169
                 "        address, postal_code, latitude, longitude, rated_capacity, rated_power, "
5170
                 "        contact_id, cost_center_id, serial_number, svg, is_cost_data_displayed, description "
5171
                 " FROM tbl_microgrids "
5172
                 " WHERE id = %s ")
5173
        cursor.execute(query, (id_,))
5174
        row = cursor.fetchone()
5175
        cursor.close()
5176
        cnx.close()
5177
5178 View Code Duplication
        if row is None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5179
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5180
                                   description='API.MICROGRID_NOT_FOUND')
5181
        else:
5182
            meta_result = {"id": row[0],
5183
                           "name": row[1],
5184
                           "uuid": row[2],
5185
                           "address": row[3],
5186
                           "postal_code": row[4],
5187
                           "latitude": row[5],
5188
                           "longitude": row[6],
5189
                           "rated_capacity": row[7],
5190
                           "rated_power": row[8],
5191
                           "contact": contact_dict.get(row[9], None),
5192
                           "cost_center": cost_center_dict.get(row[10], None),
5193
                           "serial_number": row[11],
5194
                           "svg": row[12],
5195
                           "is_cost_data_displayed": bool(row[13]),
5196
                           "description": row[14]}
5197
5198
        resp.text = json.dumps(meta_result)
5199
5200
5201
class MicrogridImport:
5202
    def __init__(self):
5203
        """"Initializes MicrogridImport"""
5204
        pass
5205
5206
    @staticmethod
5207
    def on_options(req, resp):
5208
        resp.status = falcon.HTTP_200
5209
5210
    @staticmethod
5211
    @user_logger
5212
    def on_post(req, resp):
5213
        """Handles POST requests"""
5214
        admin_control(req)
5215
        try:
5216
            raw_json = req.stream.read().decode('utf-8')
5217
        except Exception as ex:
5218
            raise falcon.HTTPError(status=falcon.HTTP_400,
5219
                                   title='API.BAD_REQUEST',
5220
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5221
5222
        new_values = json.loads(raw_json)
5223
5224
        if 'name' not in new_values.keys() or \
5225
                not isinstance(new_values['name'], str) or \
5226
                len(str.strip(new_values['name'])) == 0:
5227
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5228
                                   description='API.INVALID_MICROGRID_NAME')
5229
        name = str.strip(new_values['name'])
5230
5231
        if 'address' not in new_values.keys() or \
5232
                not isinstance(new_values['address'], str) or \
5233
                len(str.strip(new_values['address'])) == 0:
5234
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5235
                                   description='API.INVALID_ADDRESS_VALUE')
5236
        address = str.strip(new_values['address'])
5237
5238
        if 'postal_code' not in new_values.keys() or \
5239
                not isinstance(new_values['postal_code'], str) or \
5240
                len(str.strip(new_values['postal_code'])) == 0:
5241
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5242
                                   description='API.INVALID_POSTAL_CODE_VALUE')
5243
        postal_code = str.strip(new_values['postal_code'])
5244
5245
        if 'latitude' not in new_values.keys() or \
5246
                not (isinstance(new_values['latitude'], float) or
5247
                     isinstance(new_values['latitude'], int)) or \
5248
                new_values['latitude'] < -90.0 or \
5249
                new_values['latitude'] > 90.0:
5250
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5251
                                   description='API.INVALID_LATITUDE_VALUE')
5252
        latitude = new_values['latitude']
5253
5254
        if 'longitude' not in new_values.keys() or \
5255
                not (isinstance(new_values['longitude'], float) or
5256
                     isinstance(new_values['longitude'], int)) or \
5257
                new_values['longitude'] < -180.0 or \
5258
                new_values['longitude'] > 180.0:
5259
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5260
                                   description='API.INVALID_LONGITUDE_VALUE')
5261
        longitude = new_values['longitude']
5262
5263
        if 'rated_capacity' not in new_values.keys() or \
5264
                not (isinstance(new_values['rated_capacity'], float) or
5265
                     isinstance(new_values['rated_capacity'], int)) or \
5266
                new_values['rated_capacity'] <= 0.0:
5267
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5268
                                   description='API.INVALID_RATED_CAPACITY')
5269
        rated_capacity = new_values['rated_capacity']
5270
5271
        if 'rated_power' not in new_values.keys() or \
5272
                not (isinstance(new_values['rated_power'], float) or
5273
                     isinstance(new_values['rated_power'], int)) or \
5274
                new_values['rated_power'] <= 0.0:
5275
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5276
                                   description='API.INVALID_RATED_POWER')
5277
        rated_power = new_values['rated_power']
5278
5279
        if 'id' not in new_values['contact'].keys() or \
5280
                not isinstance(new_values['contact']['id'], int) or \
5281
                new_values['contact']['id'] <= 0:
5282
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5283
                                   description='API.INVALID_CONTACT_ID')
5284
        contact_id = new_values['contact']['id']
5285
5286
        if 'id' not in new_values['cost_center'].keys() or \
5287
                not isinstance(new_values['cost_center']['id'], int) or \
5288
                new_values['cost_center']['id'] <= 0:
5289
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5290
                                   description='API.INVALID_COST_CENTER_ID')
5291
        cost_center_id = new_values['cost_center']['id']
5292
5293
        if 'serial_number' not in new_values.keys() or \
5294
                not isinstance(new_values['serial_number'], str) or \
5295
                len(str.strip(new_values['serial_number'])) == 0:
5296
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5297
                                   description='API.INVALID_SERIAL_NUMBER')
5298
        serial_number = str.strip(new_values['serial_number'])
5299
5300
        if 'svg' not in new_values.keys() or \
5301
                not isinstance(new_values['svg'], str) or \
5302
                len(str.strip(new_values['svg'])) == 0:
5303
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5304
                                   description='API.INVALID_SVG')
5305
        svg = str.strip(new_values['svg'])
5306
5307
        if 'is_cost_data_displayed' not in new_values['data'].keys() or \
5308
                not isinstance(new_values['data']['is_cost_data_displayed'], bool):
5309
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5310
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED')
5311
        is_cost_data_displayed = new_values['data']['is_cost_data_displayed']
5312
5313
        if 'description' in new_values.keys() and \
5314
                new_values['description'] is not None and \
5315
                len(str(new_values['description'])) > 0:
5316
            description = str.strip(new_values['description'])
5317
        else:
5318
            description = None
5319
5320
        cnx = mysql.connector.connect(**config.myems_system_db)
5321
        cursor = cnx.cursor()
5322
5323
        cursor.execute(" SELECT name "
5324
                       " FROM tbl_microgrids "
5325
                       " WHERE name = %s ", (name,))
5326
        if cursor.fetchone() is not None:
5327
            cursor.close()
5328
            cnx.close()
5329
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5330
                                   description='API.MICROGRID_NAME_IS_ALREADY_IN_USE')
5331
5332
        cursor.execute(" SELECT name "
5333
                       " FROM tbl_contacts "
5334
                       " WHERE id = %s ",
5335
                       (new_values['contact']['id'],))
5336
        row = cursor.fetchone()
5337
        if row is None:
5338
            cursor.close()
5339
            cnx.close()
5340
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5341
                                   description='API.CONTACT_NOT_FOUND')
5342
5343
        cursor.execute(" SELECT name "
5344
                       " FROM tbl_cost_centers "
5345
                       " WHERE id = %s ",
5346
                       (new_values['cost_center']['id'],))
5347
        row = cursor.fetchone()
5348
        if row is None:
5349
            cursor.close()
5350
            cnx.close()
5351
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5352
                                   description='API.COST_CENTER_NOT_FOUND')
5353
5354
        add_values = (" INSERT INTO tbl_microgrids "
5355
                      "    (name, uuid, address, postal_code, latitude, longitude, rated_capacity, rated_power, "
5356
                      "     contact_id, cost_center_id, serial_number, svg, is_cost_data_displayed, description) "
5357
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
5358
        cursor.execute(add_values, (name,
5359
                                    str(uuid.uuid4()),
5360
                                    address,
5361
                                    postal_code,
5362
                                    latitude,
5363
                                    longitude,
5364
                                    rated_capacity,
5365
                                    rated_power,
5366
                                    contact_id,
5367
                                    cost_center_id,
5368
                                    serial_number,
5369
                                    svg,
5370
                                    is_cost_data_displayed,
5371
                                    description))
5372
        new_id = cursor.lastrowid
5373
        cnx.commit()
5374
        cursor.close()
5375
        cnx.close()
5376
5377
        resp.status = falcon.HTTP_201
5378
        resp.location = '/microgrids/' + str(new_id)
5379
5380
5381
class MicrogridClone:
5382
    def __init__(self):
5383
        """"Initializes MicrogridClone"""
5384
        pass
5385
5386
    @staticmethod
5387
    def on_options(req, resp, id_):
5388
        resp.status = falcon.HTTP_200
5389
5390
    @staticmethod
5391
    @user_logger
5392
    def on_post(req, resp, id_):
5393
        access_control(req)
5394
        if not id_.isdigit() or int(id_) <= 0:
5395
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5396
                                   description='API.INVALID_MICROGRID_ID')
5397
5398
        cnx = mysql.connector.connect(**config.myems_system_db)
5399
        cursor = cnx.cursor()
5400
5401
        query = (" SELECT id, name, uuid "
5402
                 " FROM tbl_contacts ")
5403
        cursor.execute(query)
5404
        rows_contacts = cursor.fetchall()
5405
5406
        contact_dict = dict()
5407
        if rows_contacts is not None and len(rows_contacts) > 0:
5408
            for row in rows_contacts:
5409
                contact_dict[row[0]] = {"id": row[0],
5410
                                        "name": row[1],
5411
                                        "uuid": row[2]}
5412
5413
        query = (" SELECT id, name, uuid "
5414
                 " FROM tbl_cost_centers ")
5415
        cursor.execute(query)
5416
        rows_cost_centers = cursor.fetchall()
5417
5418
        cost_center_dict = dict()
5419
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
5420
            for row in rows_cost_centers:
5421
                cost_center_dict[row[0]] = {"id": row[0],
5422
                                            "name": row[1],
5423
                                            "uuid": row[2]}
5424
5425
        query = (" SELECT id, name, uuid, "
5426
                 "        address, postal_code, latitude, longitude, capacity, "
5427
                 "        contact_id, cost_center_id, serial_number, svg, is_cost_data_displayed, description "
5428
                 " FROM tbl_microgrids "
5429
                 " WHERE id = %s ")
5430
        cursor.execute(query, (id_,))
5431
        row = cursor.fetchone()
5432
5433
        if row is None:
5434
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5435
                                   description='API.MICROGRID_NOT_FOUND')
5436
        else:
5437
            meta_result = {"id": row[0],
5438
                           "name": row[1],
5439
                           "uuid": row[2],
5440
                           "address": row[3],
5441
                           "postal_code": row[4],
5442
                           "latitude": row[5],
5443
                           "longitude": row[6],
5444
                           "capacity": row[7],
5445
                           "contact": contact_dict.get(row[8], None),
5446
                           "cost_center": cost_center_dict.get(row[9], None),
5447
                           "serial_number": row[10],
5448
                           "svg": row[11],
5449
                           "is_cost_data_displayed": row[12],
5450
                           "description": row[13]}
5451
            timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
5452
            if config.utc_offset[0] == '-':
5453
                timezone_offset = -timezone_offset
5454
            new_name = (str.strip(meta_result['name']) +
5455
                        (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds'))
5456
            add_values = (" INSERT INTO tbl_microgrids "
5457
                          "    (name, uuid, address, postal_code, latitude, longitude, capacity, "
5458
                          "     contact_id, cost_center_id, serial_number, svg, is_cost_data_displayed, description) "
5459
                          " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
5460
            cursor.execute(add_values, (new_name,
5461
                                        str(uuid.uuid4()),
5462
                                        meta_result['address'],
5463
                                        meta_result['postal_code'],
5464
                                        meta_result['latitude'],
5465
                                        meta_result['longitude'],
5466
                                        meta_result['capacity'],
5467
                                        meta_result['contact']['id'],
5468
                                        meta_result['cost_center']['id'],
5469
                                        meta_result['serial_number'],
5470
                                        meta_result['svg'],
5471
                                        meta_result['is_cost_data_displayed'],
5472
                                        meta_result['description']))
5473
            new_id = cursor.lastrowid
5474
            cnx.commit()
5475
            cursor.close()
5476
            cnx.close()
5477
5478
            resp.status = falcon.HTTP_201
5479
            resp.location = '/microgrids/' + str(new_id)
5480