Passed
Push — master ( 844492...7c39ee )
by
unknown
09:45 queued 11s
created

core.microgrid.MicrogridCollection.on_get()   F

Complexity

Conditions 16

Size

Total Lines 107
Code Lines 68

Duplication

Lines 107
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 68
dl 107
loc 107
rs 2.4
c 0
b 0
f 0
cc 16
nop 2

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.MicrogridCollection.on_get() 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
    """
12
    Microgrid Collection Resource
13
14
    This class handles CRUD operations for microgrid collection.
15
    It provides endpoints for listing all microgrids and creating new ones.
16
    Microgrids represent localized energy systems that can operate independently
17
    or in conjunction with the main electrical grid, typically including
18
    distributed generation, energy storage, and load management capabilities.
19
    """
20
    def __init__(self):
21
        pass
22
23
    @staticmethod
24
    def on_options(req, resp):
25
        """
26
        Handle OPTIONS request for CORS preflight
27
28
        Args:
29
            req: Falcon request object
30
            resp: Falcon response object
31
        """
32
        _ = req
33
        resp.status = falcon.HTTP_200
34
35 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
36
    def on_get(req, resp):
37
        """
38
        Handle GET requests to retrieve all microgrids
39
40
        Returns a list of all microgrids with their complete information including:
41
        - Microgrid ID, name, and UUID
42
        - Associated contact and cost center information
43
        - Microgrid specifications and parameters
44
        - Related equipment and meter associations
45
        - SVG diagram information for visualization
46
47
        Args:
48
            req: Falcon request object
49
            resp: Falcon response object
50
        """
51
        access_control(req)
52
53
        search_query = req.get_param('q', default=None)
54
        if search_query is not None and len(search_query.strip()) > 0:
55
            search_query = search_query.strip()
56
        else:
57
            search_query = ''
58
59
        # Connect to database
60
        cnx = mysql.connector.connect(**config.myems_system_db)
61
        cursor = cnx.cursor()
62
63
        # Query to retrieve all contacts for reference
64
        query = (" SELECT id, name, uuid "
65
                 " FROM tbl_contacts ")
66
        cursor.execute(query)
67
        rows_contacts = cursor.fetchall()
68
69
        # Build contact dictionary for quick lookup by ID
70
        contact_dict = dict()
71
        if rows_contacts is not None and len(rows_contacts) > 0:
72
            for row in rows_contacts:
73
                contact_dict[row[0]] = {"id": row[0],
74
                                        "name": row[1],
75
                                        "uuid": row[2]}
76
77
        # Query to retrieve all cost centers for reference
78
        query = (" SELECT id, name, uuid "
79
                 " FROM tbl_cost_centers ")
80
        cursor.execute(query)
81
        rows_cost_centers = cursor.fetchall()
82
83
        # Build cost center dictionary for quick lookup by ID
84
        cost_center_dict = dict()
85
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
86
            for row in rows_cost_centers:
87
                cost_center_dict[row[0]] = {"id": row[0],
88
                                            "name": row[1],
89
                                            "uuid": row[2]}
90
91
        # Initialize SVG dictionary for diagram references
92
        svg_dict = dict()
93
94
        query = (" SELECT id, name, uuid "
95
                 " FROM tbl_svgs ")
96
        cursor.execute(query)
97
        rows_svgs = cursor.fetchall()
98
        if rows_svgs is not None and len(rows_svgs) > 0:
99
            for row in rows_svgs:
100
                svg_dict[row[0]] = {"id": row[0],
101
                                    "name": row[1],
102
                                    "uuid": row[2]}
103
104
        query = (" SELECT id, name, uuid, "
105
                 "        address, postal_code, latitude, longitude, rated_capacity, rated_power, "
106
                 "        contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, "
107
                 "        phase_of_lifecycle, description "
108
                 " FROM tbl_microgrids ")
109
        params = []
110
        if search_query:
111
            query += " WHERE name LIKE %s OR address LIKE %s OR description LIKE %s "
112
            params = [f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']
113
        query += " ORDER BY id "
114
        cursor.execute(query, params)
115
        rows_microgrids = cursor.fetchall()
116
117
        result = list()
118
        if rows_microgrids is not None and len(rows_microgrids) > 0:
119
            for row in rows_microgrids:
120
                meta_result = {"id": row[0],
121
                               "name": row[1],
122
                               "uuid": row[2],
123
                               "address": row[3],
124
                               "postal_code": row[4],
125
                               "latitude": row[5],
126
                               "longitude": row[6],
127
                               "rated_capacity": row[7],
128
                               "rated_power": row[8],
129
                               "contact": contact_dict.get(row[9], None),
130
                               "cost_center": cost_center_dict.get(row[10], None),
131
                               "serial_number": row[11],
132
                               "svg": svg_dict.get(row[12], None),
133
                               "is_cost_data_displayed": bool(row[13]),
134
                               "phase_of_lifecycle": row[14],
135
                               "description": row[15],
136
                               "qrcode": 'microgrid:' + row[2]}
137
                result.append(meta_result)
138
139
        cursor.close()
140
        cnx.close()
141
        resp.text = json.dumps(result)
142
143
    @staticmethod
144
    @user_logger
145
    def on_post(req, resp):
146
        """Handles POST requests"""
147
        admin_control(req)
148
        try:
149
            raw_json = req.stream.read().decode('utf-8')
150
        except Exception as ex:
151
            print(str(ex))
152
            raise falcon.HTTPError(status=falcon.HTTP_400,
153
                                   title='API.BAD_REQUEST',
154
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
155
156
        new_values = json.loads(raw_json)
157
158
        if 'name' not in new_values['data'].keys() or \
159
                not isinstance(new_values['data']['name'], str) or \
160
                len(str.strip(new_values['data']['name'])) == 0:
161
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
162
                                   description='API.INVALID_MICROGRID_NAME')
163
        name = str.strip(new_values['data']['name'])
164
165
        if 'address' not in new_values['data'].keys() or \
166
                not isinstance(new_values['data']['address'], str) or \
167
                len(str.strip(new_values['data']['address'])) == 0:
168
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
169
                                   description='API.INVALID_ADDRESS_VALUE')
170
        address = str.strip(new_values['data']['address'])
171
172
        if 'postal_code' not in new_values['data'].keys() or \
173
                not isinstance(new_values['data']['postal_code'], str) or \
174
                len(str.strip(new_values['data']['postal_code'])) == 0:
175
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
176
                                   description='API.INVALID_POSTAL_CODE_VALUE')
177
        postal_code = str.strip(new_values['data']['postal_code'])
178
179
        if 'latitude' not in new_values['data'].keys() or \
180
                not (isinstance(new_values['data']['latitude'], float) or
181
                     isinstance(new_values['data']['latitude'], int)) or \
182
                new_values['data']['latitude'] < -90.0 or \
183
                new_values['data']['latitude'] > 90.0:
184
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
185
                                   description='API.INVALID_LATITUDE_VALUE')
186
        latitude = new_values['data']['latitude']
187
188
        if 'longitude' not in new_values['data'].keys() or \
189
                not (isinstance(new_values['data']['longitude'], float) or
190
                     isinstance(new_values['data']['longitude'], int)) or \
191
                new_values['data']['longitude'] < -180.0 or \
192
                new_values['data']['longitude'] > 180.0:
193
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
194
                                   description='API.INVALID_LONGITUDE_VALUE')
195
        longitude = new_values['data']['longitude']
196
197
        if 'rated_capacity' not in new_values['data'].keys() or \
198
                not (isinstance(new_values['data']['rated_capacity'], float) or
199
                     isinstance(new_values['data']['rated_capacity'], int)) or \
200
                new_values['data']['rated_capacity'] <= 0.0:
201
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
202
                                   description='API.INVALID_RATED_CAPACITY')
203
        rated_capacity = new_values['data']['rated_capacity']
204
205
        if 'rated_power' not in new_values['data'].keys() or \
206
                not (isinstance(new_values['data']['rated_power'], float) or
207
                     isinstance(new_values['data']['rated_power'], int)) or \
208
                new_values['data']['rated_power'] <= 0.0:
209
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
210
                                   description='API.INVALID_RATED_POWER_VALUE')
211
        rated_power = new_values['data']['rated_power']
212
213
        if 'contact_id' not in new_values['data'].keys() or \
214
                not isinstance(new_values['data']['contact_id'], int) or \
215
                new_values['data']['contact_id'] <= 0:
216
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
217
                                   description='API.INVALID_CONTACT_ID')
218
        contact_id = new_values['data']['contact_id']
219
220
        if 'cost_center_id' not in new_values['data'].keys() or \
221
                not isinstance(new_values['data']['cost_center_id'], int) or \
222
                new_values['data']['cost_center_id'] <= 0:
223
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
224
                                   description='API.INVALID_COST_CENTER_ID')
225
        cost_center_id = new_values['data']['cost_center_id']
226
227
        if 'serial_number' not in new_values['data'].keys() or \
228
                not isinstance(new_values['data']['serial_number'], str) or \
229
                len(str.strip(new_values['data']['serial_number'])) == 0:
230
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
231
                                   description='API.INVALID_SERIAL_NUMBER')
232
        serial_number = str.strip(new_values['data']['serial_number'])
233
234
        if 'svg_id' not in new_values['data'].keys() or \
235
                not isinstance(new_values['data']['svg_id'], int) or \
236
                new_values['data']['svg_id'] <= 0:
237
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
238
                                   description='API.INVALID_SVG_ID')
239
        svg_id = new_values['data']['svg_id']
240
241
        if 'is_cost_data_displayed' not in new_values['data'].keys() or \
242
                not isinstance(new_values['data']['is_cost_data_displayed'], bool):
243
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
244
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED')
245
        is_cost_data_displayed = new_values['data']['is_cost_data_displayed']
246
247
        if 'phase_of_lifecycle' not in new_values['data'].keys() or \
248
                not isinstance(new_values['data']['phase_of_lifecycle'], str) or \
249
                len(str.strip(new_values['data']['phase_of_lifecycle'])) == 0:
250
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
251
                                   description='API.INVALID_PHASE_OF_LIFECYCLE')
252
        phase_of_lifecycle = str.strip(new_values['data']['phase_of_lifecycle'])
253
254
        if 'description' in new_values['data'].keys() and \
255
                new_values['data']['description'] is not None and \
256
                len(str(new_values['data']['description'])) > 0:
257
            description = str.strip(new_values['data']['description'])
258
        else:
259
            description = None
260
261
        cnx = mysql.connector.connect(**config.myems_system_db)
262
        cursor = cnx.cursor()
263
264
        cursor.execute(" SELECT name "
265
                       " FROM tbl_microgrids "
266
                       " WHERE name = %s ", (name,))
267
        if cursor.fetchone() is not None:
268
            cursor.close()
269
            cnx.close()
270
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
271
                                   description='API.MICROGRID_NAME_IS_ALREADY_IN_USE')
272
273
        cursor.execute(" SELECT name "
274
                       " FROM tbl_contacts "
275
                       " WHERE id = %s ",
276
                       (new_values['data']['contact_id'],))
277
        row = cursor.fetchone()
278
        if row is None:
279
            cursor.close()
280
            cnx.close()
281
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
282
                                   description='API.CONTACT_NOT_FOUND')
283
284
        cursor.execute(" SELECT name "
285
                       " FROM tbl_cost_centers "
286
                       " WHERE id = %s ",
287
                       (new_values['data']['cost_center_id'],))
288
        row = cursor.fetchone()
289
        if row is None:
290
            cursor.close()
291
            cnx.close()
292
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
293
                                   description='API.COST_CENTER_NOT_FOUND')
294
295
        cursor.execute(" SELECT name "
296
                       " FROM tbl_svgs "
297
                       " WHERE id = %s ",
298
                       (svg_id,))
299
        row = cursor.fetchone()
300
        if row is None:
301
            cursor.close()
302
            cnx.close()
303
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
304
                                   description='API.SVG_NOT_FOUND')
305
306
        add_values = (" INSERT INTO tbl_microgrids "
307
                      "    (name, uuid, address, postal_code, latitude, longitude, rated_capacity, rated_power, "
308
                      "     contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, "
309
                      "     phase_of_lifecycle, description) "
310
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
311
        cursor.execute(add_values, (name,
312
                                    str(uuid.uuid4()),
313
                                    address,
314
                                    postal_code,
315
                                    latitude,
316
                                    longitude,
317
                                    rated_capacity,
318
                                    rated_power,
319
                                    contact_id,
320
                                    cost_center_id,
321
                                    serial_number,
322
                                    svg_id,
323
                                    is_cost_data_displayed,
324
                                    phase_of_lifecycle,
325
                                    description))
326
        new_id = cursor.lastrowid
327
        cnx.commit()
328
        cursor.close()
329
        cnx.close()
330
331
        resp.status = falcon.HTTP_201
332
        resp.location = '/microgrids/' + str(new_id)
333
334
335
class MicrogridItem:
336
    def __init__(self):
337
        pass
338
339
    @staticmethod
340
    def on_options(req, resp, id_):
341
        _ = req
342
        resp.status = falcon.HTTP_200
343
        _ = id_
344
345 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
346
    def on_get(req, resp, id_):
347
        access_control(req)
348
        if not id_.isdigit() or int(id_) <= 0:
349
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
350
                                   description='API.INVALID_MICROGRID_ID')
351
352
        cnx = mysql.connector.connect(**config.myems_system_db)
353
        cursor = cnx.cursor()
354
355
        query = (" SELECT id, name, uuid "
356
                 " FROM tbl_contacts ")
357
        cursor.execute(query)
358
        rows_contacts = cursor.fetchall()
359
360
        contact_dict = dict()
361
        if rows_contacts is not None and len(rows_contacts) > 0:
362
            for row in rows_contacts:
363
                contact_dict[row[0]] = {"id": row[0],
364
                                        "name": row[1],
365
                                        "uuid": row[2]}
366
367
        query = (" SELECT id, name, uuid "
368
                 " FROM tbl_cost_centers ")
369
        cursor.execute(query)
370
        rows_cost_centers = cursor.fetchall()
371
372
        cost_center_dict = dict()
373
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
374
            for row in rows_cost_centers:
375
                cost_center_dict[row[0]] = {"id": row[0],
376
                                            "name": row[1],
377
                                            "uuid": row[2]}
378
        svg_dict = dict()
379
380
        query = (" SELECT id, name, uuid "
381
                 " FROM tbl_svgs ")
382
        cursor.execute(query)
383
        rows_svgs = cursor.fetchall()
384
        if rows_svgs is not None and len(rows_svgs) > 0:
385
            for row in rows_svgs:
386
                svg_dict[row[0]] = {"id": row[0],
387
                                    "name": row[1],
388
                                    "uuid": row[2]}
389
390
        query = (" SELECT id, name, uuid, "
391
                 "        address, postal_code, latitude, longitude, rated_capacity, rated_power, "
392
                 "        contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, "
393
                 "        phase_of_lifecycle, description "
394
                 " FROM tbl_microgrids "
395
                 " WHERE id = %s ")
396
        cursor.execute(query, (id_,))
397
        row = cursor.fetchone()
398
        cursor.close()
399
        cnx.close()
400
401
        if row is None:
402
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
403
                                   description='API.MICROGRID_NOT_FOUND')
404
        else:
405
            meta_result = {"id": row[0],
406
                           "name": row[1],
407
                           "uuid": row[2],
408
                           "address": row[3],
409
                           "postal_code": row[4],
410
                           "latitude": row[5],
411
                           "longitude": row[6],
412
                           "rated_capacity": row[7],
413
                           "rated_power": row[8],
414
                           "contact": contact_dict.get(row[9], None),
415
                           "cost_center": cost_center_dict.get(row[10], None),
416
                           "serial_number": row[11],
417
                           "svg": svg_dict.get(row[12], None),
418
                           "is_cost_data_displayed": bool(row[13]),
419
                           "phase_of_lifecycle": row[14],
420
                           "description": row[15],
421
                           "qrcode": 'microgrid:' + row[2]}
422
423
        resp.text = json.dumps(meta_result)
424
425 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
426
    @user_logger
427
    def on_delete(req, resp, id_):
428
        admin_control(req)
429
        if not id_.isdigit() or int(id_) <= 0:
430
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
431
                                   description='API.INVALID_MICROGRID_ID')
432
433
        cnx = mysql.connector.connect(**config.myems_system_db)
434
        cursor = cnx.cursor()
435
436
        cursor.execute(" SELECT name "
437
                       " FROM tbl_microgrids "
438
                       " WHERE id = %s ", (id_,))
439
        if cursor.fetchone() is None:
440
            cursor.close()
441
            cnx.close()
442
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
443
                                   description='API.MICROGRID_NOT_FOUND')
444
445
        # check relation with spaces
446
        cursor.execute(" SELECT id "
447
                       " FROM  tbl_spaces_microgrids "
448
                       " WHERE microgrid_id = %s ", (id_,))
449
        rows_spaces = cursor.fetchall()
450
        if rows_spaces is not None and len(rows_spaces) > 0:
451
            cursor.close()
452
            cnx.close()
453
            raise falcon.HTTPError(status=falcon.HTTP_400,
454
                                   title='API.BAD_REQUEST',
455
                                   description='API.THERE_IS_RELATION_WITH_SPACES')
456
457
        # check relation with power plants
458
        cursor.execute(" SELECT id "
459
                       " FROM tbl_virtual_power_plants_microgrids "
460
                       " WHERE microgrid_id = %s ",
461
                       (id_,))
462
        rows_power_plants = cursor.fetchall()
463
        if rows_power_plants is not None and len(rows_power_plants) > 0:
464
            cursor.close()
465
            cnx.close()
466
            raise falcon.HTTPError(status=falcon.HTTP_400,
467
                                   title='API.BAD_REQUEST',
468
                                   description='API.THERE_IS_RELATION_WITH_VIRTUAL_POWER_PLANTS')
469
470
        cursor.execute(" DELETE FROM tbl_microgrids_batteries WHERE microgrid_id = %s ", (id_,))
471
        cnx.commit()
472
        cursor.execute(" DELETE FROM tbl_microgrids_commands WHERE microgrid_id = %s ", (id_,))
473
        cnx.commit()
474
        cursor.execute(" DELETE FROM tbl_microgrids_power_conversion_systems WHERE microgrid_id = %s ", (id_,))
475
        cnx.commit()
476
        cursor.execute(" DELETE FROM tbl_microgrids_evchargers WHERE microgrid_id = %s ", (id_,))
477
        cnx.commit()
478
        cursor.execute(" DELETE FROM tbl_microgrids_generators WHERE microgrid_id = %s ", (id_,))
479
        cnx.commit()
480
        cursor.execute(" DELETE FROM tbl_microgrids_grids WHERE microgrid_id = %s ", (id_,))
481
        cnx.commit()
482
        cursor.execute(" DELETE FROM tbl_microgrids_heatpumps WHERE microgrid_id = %s ", (id_,))
483
        cnx.commit()
484
        cursor.execute(" DELETE FROM tbl_microgrids_loads WHERE microgrid_id = %s ", (id_,))
485
        cnx.commit()
486
        cursor.execute(" DELETE FROM tbl_microgrids_photovoltaics WHERE microgrid_id = %s ", (id_,))
487
        cnx.commit()
488
        cursor.execute(" DELETE FROM tbl_microgrids_sensors WHERE microgrid_id = %s ", (id_,))
489
        cnx.commit()
490
        cursor.execute(" DELETE FROM tbl_microgrids_users WHERE microgrid_id = %s ", (id_,))
491
        cnx.commit()
492
        cursor.execute(" DELETE FROM tbl_microgrids WHERE id = %s ", (id_,))
493
        cnx.commit()
494
495
        cursor.close()
496
        cnx.close()
497
498
        resp.status = falcon.HTTP_204
499
500
    @staticmethod
501
    @user_logger
502
    def on_put(req, resp, id_):
503
        """Handles PUT requests"""
504
        admin_control(req)
505
        try:
506
            raw_json = req.stream.read().decode('utf-8')
507
        except Exception as ex:
508
            print(str(ex))
509
            raise falcon.HTTPError(status=falcon.HTTP_400,
510
                                   title='API.BAD_REQUEST',
511
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
512
513
        if not id_.isdigit() or int(id_) <= 0:
514
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
515
                                   description='API.INVALID_MICROGRID_ID')
516
517
        new_values = json.loads(raw_json)
518
519
        if 'name' not in new_values['data'].keys() or \
520
                not isinstance(new_values['data']['name'], str) or \
521
                len(str.strip(new_values['data']['name'])) == 0:
522
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
523
                                   description='API.INVALID_MICROGRID_NAME')
524
        name = str.strip(new_values['data']['name'])
525
526
        if 'address' not in new_values['data'].keys() or \
527
                not isinstance(new_values['data']['address'], str) or \
528
                len(str.strip(new_values['data']['address'])) == 0:
529
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
530
                                   description='API.INVALID_ADDRESS_VALUE')
531
        address = str.strip(new_values['data']['address'])
532
533
        if 'postal_code' not in new_values['data'].keys() or \
534
                not isinstance(new_values['data']['postal_code'], str) or \
535
                len(str.strip(new_values['data']['postal_code'])) == 0:
536
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
537
                                   description='API.INVALID_POSTAL_CODE_VALUE')
538
        postal_code = str.strip(new_values['data']['postal_code'])
539
540
        if 'latitude' not in new_values['data'].keys() or \
541
                not (isinstance(new_values['data']['latitude'], float) or
542
                     isinstance(new_values['data']['latitude'], int)) or \
543
                new_values['data']['latitude'] < -90.0 or \
544
                new_values['data']['latitude'] > 90.0:
545
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
546
                                   description='API.INVALID_LATITUDE_VALUE')
547
        latitude = new_values['data']['latitude']
548
549
        if 'longitude' not in new_values['data'].keys() or \
550
                not (isinstance(new_values['data']['longitude'], float) or
551
                     isinstance(new_values['data']['longitude'], int)) or \
552
                new_values['data']['longitude'] < -180.0 or \
553
                new_values['data']['longitude'] > 180.0:
554
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
555
                                   description='API.INVALID_LONGITUDE_VALUE')
556
        longitude = new_values['data']['longitude']
557
558
        if 'rated_capacity' not in new_values['data'].keys() or \
559
                not (isinstance(new_values['data']['rated_capacity'], float) or
560
                     isinstance(new_values['data']['rated_capacity'], int)) or \
561
                new_values['data']['rated_capacity'] <= 0.0:
562
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
563
                                   description='API.INVALID_RATED_CAPACITY')
564
        rated_capacity = new_values['data']['rated_capacity']
565
566
        if 'rated_power' not in new_values['data'].keys() or \
567
                not (isinstance(new_values['data']['rated_power'], float) or
568
                     isinstance(new_values['data']['rated_power'], int)) or \
569
                new_values['data']['rated_power'] <= 0.0:
570
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
571
                                   description='API.INVALID_RATED_POWER_VALUE')
572
        rated_power = new_values['data']['rated_power']
573
574
        if 'contact_id' not in new_values['data'].keys() or \
575
                not isinstance(new_values['data']['contact_id'], int) or \
576
                new_values['data']['contact_id'] <= 0:
577
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
578
                                   description='API.INVALID_CONTACT_ID')
579
        contact_id = new_values['data']['contact_id']
580
581
        if 'cost_center_id' not in new_values['data'].keys() or \
582
                not isinstance(new_values['data']['cost_center_id'], int) or \
583
                new_values['data']['cost_center_id'] <= 0:
584
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
585
                                   description='API.INVALID_COST_CENTER_ID')
586
        cost_center_id = new_values['data']['cost_center_id']
587
588
        if 'serial_number' not in new_values['data'].keys() or \
589
                not isinstance(new_values['data']['serial_number'], str) or \
590
                len(str.strip(new_values['data']['serial_number'])) == 0:
591
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
592
                                   description='API.INVALID_SERIAL_NUMBER')
593
        serial_number = str.strip(new_values['data']['serial_number'])
594
595
        if 'svg_id' not in new_values['data'].keys() or \
596
                not isinstance(new_values['data']['svg_id'], int) or \
597
                new_values['data']['svg_id'] <= 0:
598
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
599
                                   description='API.INVALID_SVG_ID')
600
        svg_id = new_values['data']['svg_id']
601
602
        if 'is_cost_data_displayed' not in new_values['data'].keys() or \
603
                not isinstance(new_values['data']['is_cost_data_displayed'], bool):
604
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
605
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED')
606
        is_cost_data_displayed = new_values['data']['is_cost_data_displayed']
607
608
        if 'phase_of_lifecycle' not in new_values['data'].keys() or \
609
                not isinstance(new_values['data']['phase_of_lifecycle'], str) or \
610
                len(str.strip(new_values['data']['phase_of_lifecycle'])) == 0:
611
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
612
                                   description='API.INVALID_MICROGRID_PHASE_OF_LIFECYCLE')
613
        phase_of_lifecycle = str.strip(new_values['data']['phase_of_lifecycle'])
614
615
        if 'description' in new_values['data'].keys() and \
616
                new_values['data']['description'] is not None and \
617
                len(str(new_values['data']['description'])) > 0:
618
            description = str.strip(new_values['data']['description'])
619
        else:
620
            description = None
621
622
        cnx = mysql.connector.connect(**config.myems_system_db)
623
        cursor = cnx.cursor()
624
625
        cursor.execute(" SELECT name "
626
                       " FROM tbl_microgrids "
627
                       " WHERE id = %s ", (id_,))
628
        if cursor.fetchone() is None:
629
            cursor.close()
630
            cnx.close()
631
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
632
                                   description='API.MICROGRID_NOT_FOUND')
633
634
        cursor.execute(" SELECT name "
635
                       " FROM tbl_microgrids "
636
                       " WHERE name = %s AND id != %s ", (name, id_))
637
        if cursor.fetchone() is not None:
638
            cursor.close()
639
            cnx.close()
640
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
641
                                   description='API.MICROGRID_NAME_IS_ALREADY_IN_USE')
642
643
        cursor.execute(" SELECT name "
644
                       " FROM tbl_contacts "
645
                       " WHERE id = %s ",
646
                       (new_values['data']['contact_id'],))
647
        row = cursor.fetchone()
648
        if row is None:
649
            cursor.close()
650
            cnx.close()
651
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
652
                                   description='API.CONTACT_NOT_FOUND')
653
654
        cursor.execute(" SELECT name "
655
                       " FROM tbl_cost_centers "
656
                       " WHERE id = %s ",
657
                       (new_values['data']['cost_center_id'],))
658
        row = cursor.fetchone()
659
        if row is None:
660
            cursor.close()
661
            cnx.close()
662
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
663
                                   description='API.COST_CENTER_NOT_FOUND')
664
665
        cursor.execute(" SELECT name "
666
                       " FROM tbl_svgs "
667
                       " WHERE id = %s ",
668
                       (new_values['data']['svg_id'],))
669
        row = cursor.fetchone()
670
        if row is None:
671
            cursor.close()
672
            cnx.close()
673
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
674
                                   description='API.SVG_NOT_FOUND')
675
676
        update_row = (" UPDATE tbl_microgrids "
677
                      " SET name = %s, address = %s, postal_code = %s, latitude = %s, longitude = %s, "
678
                      "     rated_capacity = %s, rated_power = %s, "
679
                      "     contact_id = %s, cost_center_id = %s, "
680
                      "     serial_number = %s, svg_id = %s, is_cost_data_displayed = %s, phase_of_lifecycle = %s, "
681
                      "     description = %s "
682
                      " WHERE id = %s ")
683
        cursor.execute(update_row, (name,
684
                                    address,
685
                                    postal_code,
686
                                    latitude,
687
                                    longitude,
688
                                    rated_capacity,
689
                                    rated_power,
690
                                    contact_id,
691
                                    cost_center_id,
692
                                    serial_number,
693
                                    svg_id,
694
                                    is_cost_data_displayed,
695
                                    phase_of_lifecycle,
696
                                    description,
697
                                    id_))
698
        cnx.commit()
699
700
        cursor.close()
701
        cnx.close()
702
703
        resp.status = falcon.HTTP_200
704
705
706
class MicrogridBatteryCollection:
707
    def __init__(self):
708
        pass
709
710
    @staticmethod
711
    def on_options(req, resp, id_):
712
        _ = req
713
        resp.status = falcon.HTTP_200
714
        _ = id_
715
716 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
717
    def on_get(req, resp, id_):
718
        access_control(req)
719
        if not id_.isdigit() or int(id_) <= 0:
720
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
721
                                   description='API.INVALID_MICROGRID_ID')
722
723
        cnx = mysql.connector.connect(**config.myems_system_db)
724
        cursor = cnx.cursor()
725
726
        cursor.execute(" SELECT name "
727
                       " FROM tbl_microgrids "
728
                       " WHERE id = %s ", (id_,))
729
        if cursor.fetchone() is None:
730
            cursor.close()
731
            cnx.close()
732
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
733
                                   description='API.MICROGRID_NOT_FOUND')
734
735
        # query meter dict
736
        query = (" SELECT id, name, uuid "
737
                 " FROM tbl_meters ")
738
        cursor.execute(query)
739
        rows_meters = cursor.fetchall()
740
741
        meter_dict = dict()
742
        if rows_meters is not None and len(rows_meters) > 0:
743
            for row in rows_meters:
744
                meter_dict[row[0]] = {"id": row[0],
745
                                      "name": row[1],
746
                                      "uuid": row[2]}
747
        # query point dict
748
        query = (" SELECT id, name "
749
                 " FROM tbl_points ")
750
        cursor.execute(query)
751
        rows_points = cursor.fetchall()
752
753
        point_dict = dict()
754
        if rows_points is not None and len(rows_points) > 0:
755
            for row in rows_points:
756
                point_dict[row[0]] = {"id": row[0],
757
                                      "name": row[1]}
758
759
        query = (" SELECT id, name, uuid, "
760
                 "        battery_state_point_id, soc_point_id, power_point_id, "
761
                 "        charge_meter_id, discharge_meter_id, rated_capacity, rated_power, nominal_voltage "
762
                 " FROM tbl_microgrids_batteries "
763
                 " WHERE microgrid_id = %s "
764
                 " ORDER BY name ")
765
        cursor.execute(query, (id_,))
766
        rows = cursor.fetchall()
767
768
        result = list()
769
        if rows is not None and len(rows) > 0:
770
            for row in rows:
771
                meta_result = {"id": row[0],
772
                               "name": row[1],
773
                               "uuid": row[2],
774
                               "battery_state_point": point_dict.get(row[3]),
775
                               "soc_point": point_dict.get(row[4]),
776
                               "power_point": point_dict.get(row[5]),
777
                               "charge_meter": meter_dict.get(row[6]),
778
                               "discharge_meter": meter_dict.get(row[7]),
779
                               "rated_capacity": row[8],
780
                               "rated_power": row[9],
781
                               "nominal_voltage": row[10]}
782
                result.append(meta_result)
783
784
        resp.text = json.dumps(result)
785
786
    @staticmethod
787
    @user_logger
788
    def on_post(req, resp, id_):
789
        """Handles POST requests"""
790
        admin_control(req)
791
        try:
792
            raw_json = req.stream.read().decode('utf-8')
793
        except Exception as ex:
794
            print(str(ex))
795
            raise falcon.HTTPError(status=falcon.HTTP_400,
796
                                   title='API.BAD_REQUEST',
797
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
798
799
        if not id_.isdigit() or int(id_) <= 0:
800
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
801
                                   description='API.INVALID_MICROGRID_ID')
802
803
        cnx = mysql.connector.connect(**config.myems_system_db)
804
        cursor = cnx.cursor()
805
806
        cursor.execute(" SELECT name "
807
                       " FROM tbl_microgrids "
808
                       " WHERE id = %s ", (id_,))
809
        if cursor.fetchone() is None:
810
            cursor.close()
811
            cnx.close()
812
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
813
                                   description='API.MICROGRID_NOT_FOUND')
814
815
        new_values = json.loads(raw_json)
816
817
        if 'name' not in new_values['data'].keys() or \
818
                not isinstance(new_values['data']['name'], str) or \
819
                len(str.strip(new_values['data']['name'])) == 0:
820
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
821
                                   description='API.INVALID_MICROGRID_BATTERY_NAME')
822
        name = str.strip(new_values['data']['name'])
823
824
        if 'battery_state_point_id' not in new_values['data'].keys() or \
825
                not isinstance(new_values['data']['battery_state_point_id'], int) or \
826
                new_values['data']['battery_state_point_id'] <= 0:
827
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
828
                                   description='API.INVALID_BATTERY_STATE_POINT_ID')
829
        battery_state_point_id = new_values['data']['battery_state_point_id']
830
831
        if 'soc_point_id' not in new_values['data'].keys() or \
832
                not isinstance(new_values['data']['soc_point_id'], int) or \
833
                new_values['data']['soc_point_id'] <= 0:
834
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
835
                                   description='API.INVALID_SOC_POINT_ID')
836
        soc_point_id = new_values['data']['soc_point_id']
837
838
        if 'power_point_id' not in new_values['data'].keys() or \
839
                not isinstance(new_values['data']['power_point_id'], int) or \
840
                new_values['data']['power_point_id'] <= 0:
841
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
842
                                   description='API.INVALID_POWER_POINT_ID')
843
        power_point_id = new_values['data']['power_point_id']
844
845
        if 'charge_meter_id' not in new_values['data'].keys() or \
846
                not isinstance(new_values['data']['charge_meter_id'], int) or \
847
                new_values['data']['charge_meter_id'] <= 0:
848
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
849
                                   description='API.INVALID_CHARGE_METER_ID')
850
        charge_meter_id = new_values['data']['charge_meter_id']
851
852
        if 'discharge_meter_id' not in new_values['data'].keys() or \
853
                not isinstance(new_values['data']['discharge_meter_id'], int) or \
854
                new_values['data']['discharge_meter_id'] <= 0:
855
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
856
                                   description='API.INVALID_DISCHARGE_METER_ID')
857
        discharge_meter_id = new_values['data']['discharge_meter_id']
858
859
        if 'rated_capacity' not in new_values['data'].keys() or \
860
                not (isinstance(new_values['data']['rated_capacity'], float) or
861
                     isinstance(new_values['data']['rated_capacity'], int)):
862
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
863
                                   description='API.INVALID_RATED_CAPACITY')
864
        rated_capacity = float(new_values['data']['rated_capacity'])
865
866
        if 'rated_power' not in new_values['data'].keys() or \
867
                not (isinstance(new_values['data']['rated_power'], float) or
868
                     isinstance(new_values['data']['rated_power'], int)):
869
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
870
                                   description='API.INVALID_RATED_POWER')
871
        rated_power = float(new_values['data']['rated_power'])
872
873
        if 'nominal_voltage' not in new_values['data'].keys() or \
874
                not (isinstance(new_values['data']['nominal_voltage'], float) or
875
                     isinstance(new_values['data']['nominal_voltage'], int)):
876
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
877
                                   description='API.INVALID_NOMINAL_VOLTAGE')
878
        nominal_voltage = float(new_values['data']['nominal_voltage'])
879
880
        cnx = mysql.connector.connect(**config.myems_system_db)
881
        cursor = cnx.cursor()
882
883
        cursor.execute(" SELECT name "
884
                       " FROM tbl_microgrids_batteries "
885
                       " WHERE microgrid_id = %s AND name = %s ",
886
                       (id_, name,))
887
        if cursor.fetchone() is not None:
888
            cursor.close()
889
            cnx.close()
890
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
891
                                   description='API.MICROGRID_BATTERY_NAME_IS_ALREADY_IN_USE')
892
893
        cursor.execute(" SELECT name "
894
                       " FROM tbl_points "
895
                       " WHERE id = %s ",
896
                       (battery_state_point_id,))
897
        if cursor.fetchone() is None:
898
            cursor.close()
899
            cnx.close()
900
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
901
                                   description='API.BATTERY_STATE_POINT_NOT_FOUND')
902
903
        cursor.execute(" SELECT name "
904
                       " FROM tbl_points "
905
                       " WHERE id = %s ",
906
                       (soc_point_id,))
907
        if cursor.fetchone() is None:
908
            cursor.close()
909
            cnx.close()
910
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
911
                                   description='API.SOC_POINT_NOT_FOUND')
912
913
        cursor.execute(" SELECT name "
914
                       " FROM tbl_points "
915
                       " WHERE id = %s ",
916
                       (power_point_id,))
917
        if cursor.fetchone() is None:
918
            cursor.close()
919
            cnx.close()
920
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
921
                                   description='API.POWER_POINT_NOT_FOUND')
922
923
        cursor.execute(" SELECT name "
924
                       " FROM tbl_meters "
925
                       " WHERE id = %s ",
926
                       (charge_meter_id,))
927
        if cursor.fetchone() is None:
928
            cursor.close()
929
            cnx.close()
930
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
931
                                   description='API.CHARGE_METER_NOT_FOUND')
932
933
        cursor.execute(" SELECT name "
934
                       " FROM tbl_meters "
935
                       " WHERE id = %s ",
936
                       (discharge_meter_id,))
937
        if cursor.fetchone() is None:
938
            cursor.close()
939
            cnx.close()
940
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
941
                                   description='API.DISCHARGE_METER_NOT_FOUND')
942
943
        add_values = (" INSERT INTO tbl_microgrids_batteries "
944
                      "    (name, uuid, microgrid_id, "
945
                      "     battery_state_point_id, soc_point_id, power_point_id, "
946
                      "     charge_meter_id, discharge_meter_id, rated_capacity, rated_power, nominal_voltage) "
947
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
948
        cursor.execute(add_values, (name,
949
                                    str(uuid.uuid4()),
950
                                    id_,
951
                                    battery_state_point_id,
952
                                    soc_point_id,
953
                                    power_point_id,
954
                                    charge_meter_id,
955
                                    discharge_meter_id,
956
                                    rated_capacity,
957
                                    rated_power,
958
                                    nominal_voltage))
959
        new_id = cursor.lastrowid
960
        cnx.commit()
961
        cursor.close()
962
        cnx.close()
963
964
        resp.status = falcon.HTTP_201
965
        resp.location = '/microgrids/' + str(id_) + '/batteries/' + str(new_id)
966
967
968
class MicrogridBatteryItem:
969
    def __init__(self):
970
        pass
971
972
    @staticmethod
973
    def on_options(req, resp, id_, bid):
974
        _ = req
975
        resp.status = falcon.HTTP_200
976
        _ = id_
977
978 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
979
    def on_get(req, resp, id_, bid):
980
        access_control(req)
981
        if not id_.isdigit() or int(id_) <= 0:
982
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
983
                                   description='API.INVALID_MICROGRID_ID')
984
        if not bid.isdigit() or int(bid) <= 0:
985
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
986
                                   description='API.INVALID_MICROGRID_BATTERY_ID')
987
988
        cnx = mysql.connector.connect(**config.myems_system_db)
989
        cursor = cnx.cursor()
990
991
        cursor.execute(" SELECT name "
992
                       " FROM tbl_microgrids "
993
                       " WHERE id = %s ", (id_,))
994
        if cursor.fetchone() is None:
995
            cursor.close()
996
            cnx.close()
997
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
998
                                   description='API.MICROGRID_NOT_FOUND')
999
1000
        # query microgrid dict
1001
        query = (" SELECT id, name, uuid "
1002
                 " FROM tbl_microgrids ")
1003
        cursor.execute(query)
1004
        rows_microgrids = cursor.fetchall()
1005
1006
        microgrid_dict = dict()
1007
        if rows_microgrids is not None and len(rows_microgrids) > 0:
1008
            for row in rows_microgrids:
1009
                microgrid_dict[row[0]] = {"id": row[0],
1010
                                          "name": row[1],
1011
                                          "uuid": row[2]}
1012
        # query meter dict
1013
        query = (" SELECT id, name, uuid "
1014
                 " FROM tbl_meters ")
1015
        cursor.execute(query)
1016
        rows_meters = cursor.fetchall()
1017
1018
        meter_dict = dict()
1019
        if rows_meters is not None and len(rows_meters) > 0:
1020
            for row in rows_meters:
1021
                meter_dict[row[0]] = {"id": row[0],
1022
                                      "name": row[1],
1023
                                      "uuid": row[2]}
1024
        # query point dict
1025
        query = (" SELECT id, name "
1026
                 " FROM tbl_points ")
1027
        cursor.execute(query)
1028
        rows_points = cursor.fetchall()
1029
1030
        point_dict = dict()
1031
        if rows_points is not None and len(rows_points) > 0:
1032
            for row in rows_points:
1033
                point_dict[row[0]] = {"id": row[0],
1034
                                      "name": row[1]}
1035
1036
        query = (" SELECT id, name, uuid, microgrid_id, "
1037
                 "       battery_state_point_id, soc_point_id, power_point_id, "
1038
                 "       charge_meter_id, discharge_meter_id, rated_capacity, rated_power, nominal_voltage "
1039
                 " FROM tbl_microgrids_batteries "
1040
                 " WHERE id = %s ")
1041
        cursor.execute(query, (bid,))
1042
        row = cursor.fetchone()
1043
        cursor.close()
1044
        cnx.close()
1045
1046
        if row is None:
1047
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1048
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
1049
        else:
1050
            meta_result = {"id": row[0],
1051
                           "name": row[1],
1052
                           "uuid": row[2],
1053
                           "microgrid": microgrid_dict.get(row[3]),
1054
                           "battery_state_point": point_dict.get(row[4]),
1055
                           "soc_point": point_dict.get(row[5]),
1056
                           "power_point": point_dict.get(row[6]),
1057
                           "charge_meter": meter_dict.get(row[7]),
1058
                           "discharge_meter": meter_dict.get(row[8]),
1059
                           "rated_capacity": row[9],
1060
                           "rated_power": row[10],
1061
                           "nominal_voltage": row[11]}
1062
1063
        resp.text = json.dumps(meta_result)
1064
1065
    @staticmethod
1066
    @user_logger
1067
    def on_delete(req, resp, id_, bid):
1068
        admin_control(req)
1069
        if not id_.isdigit() or int(id_) <= 0:
1070
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1071
                                   description='API.INVALID_MICROGRID_ID')
1072
        if not bid.isdigit() or int(bid) <= 0:
1073
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1074
                                   description='API.INVALID_MICROGRID_BATTERY_ID')
1075
1076
        cnx = mysql.connector.connect(**config.myems_system_db)
1077
        cursor = cnx.cursor()
1078
1079
        cursor.execute(" SELECT name "
1080
                       " FROM tbl_microgrids "
1081
                       " WHERE id = %s ", (id_,))
1082
        if cursor.fetchone() is None:
1083
            cursor.close()
1084
            cnx.close()
1085
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1086
                                   description='API.MICROGRID_NOT_FOUND')
1087
1088
        cursor.execute(" SELECT name "
1089
                       " FROM tbl_microgrids_batteries "
1090
                       " WHERE id = %s ", (bid,))
1091
        if cursor.fetchone() is None:
1092
            cursor.close()
1093
            cnx.close()
1094
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1095
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
1096
1097
        cursor.execute(" DELETE FROM tbl_microgrids_batteries "
1098
                       " WHERE id = %s ", (bid,))
1099
        cnx.commit()
1100
1101
        cursor.close()
1102
        cnx.close()
1103
1104
        resp.status = falcon.HTTP_204
1105
1106
    @staticmethod
1107
    @user_logger
1108
    def on_put(req, resp, id_, bid):
1109
        """Handles PUT requests"""
1110
        admin_control(req)
1111
        try:
1112
            raw_json = req.stream.read().decode('utf-8')
1113
        except Exception as ex:
1114
            print(str(ex))
1115
            raise falcon.HTTPError(status=falcon.HTTP_400,
1116
                                   title='API.BAD_REQUEST',
1117
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1118
        if not id_.isdigit() or int(id_) <= 0:
1119
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1120
                                   description='API.INVALID_MICROGRID_ID')
1121
        if not bid.isdigit() or int(bid) <= 0:
1122
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1123
                                   description='API.INVALID_MICROGRID_BATTERY_ID')
1124
1125
        new_values = json.loads(raw_json)
1126
1127
        if 'name' not in new_values['data'].keys() or \
1128
                not isinstance(new_values['data']['name'], str) or \
1129
                len(str.strip(new_values['data']['name'])) == 0:
1130
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1131
                                   description='API.INVALID_MICROGRID_BATTERY_NAME')
1132
        name = str.strip(new_values['data']['name'])
1133
1134
        if 'battery_state_point_id' not in new_values['data'].keys() or \
1135
                not isinstance(new_values['data']['battery_state_point_id'], int) or \
1136
                new_values['data']['battery_state_point_id'] <= 0:
1137
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1138
                                   description='API.INVALID_BATTERY_STATE_POINT_ID')
1139
        battery_state_point_id = new_values['data']['battery_state_point_id']
1140
1141
        if 'soc_point_id' not in new_values['data'].keys() or \
1142
                not isinstance(new_values['data']['soc_point_id'], int) or \
1143
                new_values['data']['soc_point_id'] <= 0:
1144
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1145
                                   description='API.INVALID_SOC_POINT_ID')
1146
        soc_point_id = new_values['data']['soc_point_id']
1147
1148
        if 'power_point_id' not in new_values['data'].keys() or \
1149
                not isinstance(new_values['data']['power_point_id'], int) or \
1150
                new_values['data']['power_point_id'] <= 0:
1151
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1152
                                   description='API.INVALID_POWER_POINT_ID')
1153
        power_point_id = new_values['data']['power_point_id']
1154
1155
        if 'charge_meter_id' not in new_values['data'].keys() or \
1156
                not isinstance(new_values['data']['charge_meter_id'], int) or \
1157
                new_values['data']['charge_meter_id'] <= 0:
1158
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1159
                                   description='API.INVALID_CHARGE_METER_ID')
1160
        charge_meter_id = new_values['data']['charge_meter_id']
1161
1162
        if 'discharge_meter_id' not in new_values['data'].keys() or \
1163
                not isinstance(new_values['data']['discharge_meter_id'], int) or \
1164
                new_values['data']['discharge_meter_id'] <= 0:
1165
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1166
                                   description='API.INVALID_DISCHARGE_METER_ID')
1167
        discharge_meter_id = new_values['data']['discharge_meter_id']
1168
1169
        if 'rated_capacity' not in new_values['data'].keys() or \
1170
                not (isinstance(new_values['data']['rated_capacity'], float) or
1171
                     isinstance(new_values['data']['rated_capacity'], int)):
1172
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1173
                                   description='API.INVALID_RATED_CAPACITY')
1174
        rated_capacity = float(new_values['data']['rated_capacity'])
1175
1176
        if 'rated_power' not in new_values['data'].keys() or \
1177
                not (isinstance(new_values['data']['rated_power'], float) or
1178
                     isinstance(new_values['data']['rated_power'], int)):
1179
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1180
                                   description='API.INVALID_RATED_POWER')
1181
        rated_power = float(new_values['data']['rated_power'])
1182
1183
        if 'nominal_voltage' not in new_values['data'].keys() or \
1184
                not (isinstance(new_values['data']['nominal_voltage'], float) or
1185
                     isinstance(new_values['data']['nominal_voltage'], int)):
1186
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1187
                                   description='API.INVALID_NOMINAL_VOLTAGE')
1188
        nominal_voltage = float(new_values['data']['nominal_voltage'])
1189
1190
        cnx = mysql.connector.connect(**config.myems_system_db)
1191
        cursor = cnx.cursor()
1192
1193
        cursor.execute(" SELECT name "
1194
                       " FROM tbl_microgrids "
1195
                       " WHERE id = %s ",
1196
                       (id_,))
1197
        if cursor.fetchone() is None:
1198
            cursor.close()
1199
            cnx.close()
1200
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1201
                                   description='API.MICROGRID_NOT_FOUND')
1202
1203
        cursor.execute(" SELECT name "
1204
                       " FROM tbl_microgrids_batteries "
1205
                       " WHERE id = %s ", (bid,))
1206
        if cursor.fetchone() is None:
1207
            cursor.close()
1208
            cnx.close()
1209
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1210
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
1211
1212
        cursor.execute(" SELECT name "
1213
                       " FROM tbl_microgrids_batteries "
1214
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
1215
                       (id_, name, bid))
1216
        if cursor.fetchone() is not None:
1217
            cursor.close()
1218
            cnx.close()
1219
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1220
                                   description='API.MICROGRID_BATTERY_NAME_IS_ALREADY_IN_USE')
1221
1222
        cursor.execute(" SELECT name "
1223
                       " FROM tbl_points "
1224
                       " WHERE id = %s ",
1225
                       (battery_state_point_id,))
1226
        if cursor.fetchone() is None:
1227
            cursor.close()
1228
            cnx.close()
1229
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1230
                                   description='API.BATTERY_STATE_POINT_NOT_FOUND')
1231
1232
        cursor.execute(" SELECT name "
1233
                       " FROM tbl_points "
1234
                       " WHERE id = %s ",
1235
                       (soc_point_id,))
1236
        if cursor.fetchone() is None:
1237
            cursor.close()
1238
            cnx.close()
1239
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1240
                                   description='API.SOC_POINT_NOT_FOUND')
1241
1242
        cursor.execute(" SELECT name "
1243
                       " FROM tbl_points "
1244
                       " WHERE id = %s ",
1245
                       (power_point_id,))
1246
        if cursor.fetchone() is None:
1247
            cursor.close()
1248
            cnx.close()
1249
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1250
                                   description='API.POWER_POINT_NOT_FOUND')
1251
1252
        cursor.execute(" SELECT name "
1253
                       " FROM tbl_meters "
1254
                       " WHERE id = %s ",
1255
                       (charge_meter_id,))
1256
        if cursor.fetchone() is None:
1257
            cursor.close()
1258
            cnx.close()
1259
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1260
                                   description='API.CHARGE_METER_NOT_FOUND')
1261
1262
        cursor.execute(" SELECT name "
1263
                       " FROM tbl_meters "
1264
                       " WHERE id = %s ",
1265
                       (discharge_meter_id,))
1266
        if cursor.fetchone() is None:
1267
            cursor.close()
1268
            cnx.close()
1269
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1270
                                   description='API.DISCHARGE_METER_NOT_FOUND')
1271
1272
        update_row = (" UPDATE tbl_microgrids_batteries "
1273
                      " SET name = %s, microgrid_id = %s, "
1274
                      "     battery_state_point_id = %s, soc_point_id = %s, power_point_id = %s, "
1275
                      "     charge_meter_id = %s, discharge_meter_id = %s, rated_capacity = %s, rated_power = %s,"
1276
                      "     nominal_voltage = %s "
1277
                      " WHERE id = %s ")
1278
        cursor.execute(update_row, (name,
1279
                                    id_,
1280
                                    battery_state_point_id,
1281
                                    soc_point_id,
1282
                                    power_point_id,
1283
                                    charge_meter_id,
1284
                                    discharge_meter_id,
1285
                                    rated_capacity,
1286
                                    rated_power,
1287
                                    nominal_voltage,
1288
                                    bid))
1289
        cnx.commit()
1290
1291
        cursor.close()
1292
        cnx.close()
1293
1294
        resp.status = falcon.HTTP_200
1295
1296
1297
class MicrogridCommandCollection:
1298
    def __init__(self):
1299
        pass
1300
1301
    @staticmethod
1302
    def on_options(req, resp, id_):
1303
        _ = req
1304
        resp.status = falcon.HTTP_200
1305
        _ = id_
1306
1307
    @staticmethod
1308
    def on_get(req, resp, id_):
1309
        access_control(req)
1310
        if not id_.isdigit() or int(id_) <= 0:
1311
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1312
                                   description='API.INVALID_MICROGRID_ID')
1313
1314
        cnx = mysql.connector.connect(**config.myems_system_db)
1315
        cursor = cnx.cursor()
1316
1317
        cursor.execute(" SELECT name "
1318
                       " FROM tbl_microgrids "
1319
                       " WHERE id = %s ", (id_,))
1320
        if cursor.fetchone() is None:
1321
            cursor.close()
1322
            cnx.close()
1323
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1324
                                   description='API.MICROGRID_NOT_FOUND')
1325
1326
        query = (" SELECT c.id, c.name, c.uuid "
1327
                 " FROM tbl_microgrids m, tbl_microgrids_commands mc, tbl_commands c "
1328
                 " WHERE mc.microgrid_id = m.id AND c.id = mc.command_id AND m.id = %s "
1329
                 " ORDER BY c.id ")
1330
        cursor.execute(query, (id_,))
1331
        rows = cursor.fetchall()
1332
1333
        result = list()
1334
        if rows is not None and len(rows) > 0:
1335
            for row in rows:
1336
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1337
                result.append(meta_result)
1338
1339
        resp.text = json.dumps(result)
1340
1341
1342 View Code Duplication
class MicrogridEVChargerCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1343
    def __init__(self):
1344
        pass
1345
1346
    @staticmethod
1347
    def on_options(req, resp, id_):
1348
        _ = req
1349
        resp.status = falcon.HTTP_200
1350
        _ = id_
1351
1352
    @staticmethod
1353
    def on_get(req, resp, id_):
1354
        access_control(req)
1355
        if not id_.isdigit() or int(id_) <= 0:
1356
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1357
                                   description='API.INVALID_MICROGRID_ID')
1358
1359
        cnx = mysql.connector.connect(**config.myems_system_db)
1360
        cursor = cnx.cursor()
1361
1362
        cursor.execute(" SELECT name "
1363
                       " FROM tbl_microgrids "
1364
                       " WHERE id = %s ", (id_,))
1365
        if cursor.fetchone() is None:
1366
            cursor.close()
1367
            cnx.close()
1368
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1369
                                   description='API.MICROGRID_NOT_FOUND')
1370
1371
        # query meter dict
1372
        query = (" SELECT id, name, uuid "
1373
                 " FROM tbl_meters ")
1374
        cursor.execute(query)
1375
        rows_meters = cursor.fetchall()
1376
1377
        meter_dict = dict()
1378
        if rows_meters is not None and len(rows_meters) > 0:
1379
            for row in rows_meters:
1380
                meter_dict[row[0]] = {"id": row[0],
1381
                                      "name": row[1],
1382
                                      "uuid": row[2]}
1383
        # query point dict
1384
        query = (" SELECT id, name "
1385
                 " FROM tbl_points ")
1386
        cursor.execute(query)
1387
        rows_points = cursor.fetchall()
1388
1389
        point_dict = dict()
1390
        if rows_points is not None and len(rows_points) > 0:
1391
            for row in rows_points:
1392
                point_dict[row[0]] = {"id": row[0],
1393
                                      "name": row[1]}
1394
1395
        query = (" SELECT id, name, uuid, "
1396
                 "       power_point_id, meter_id, rated_output_power "
1397
                 " FROM tbl_microgrids_evchargers "
1398
                 " WHERE microgrid_id = %s "
1399
                 " ORDER BY name ")
1400
        cursor.execute(query, (id_,))
1401
        rows = cursor.fetchall()
1402
1403
        result = list()
1404
        if rows is not None and len(rows) > 0:
1405
            for row in rows:
1406
                meta_result = {"id": row[0],
1407
                               "name": row[1],
1408
                               "uuid": row[2],
1409
                               "power_point": point_dict.get(row[3]),
1410
                               "meter": meter_dict.get(row[4]),
1411
                               "rated_output_power": row[5]}
1412
                result.append(meta_result)
1413
1414
        resp.text = json.dumps(result)
1415
1416
    @staticmethod
1417
    @user_logger
1418
    def on_post(req, resp, id_):
1419
        """Handles POST requests"""
1420
        admin_control(req)
1421
        try:
1422
            raw_json = req.stream.read().decode('utf-8')
1423
        except Exception as ex:
1424
            print(str(ex))
1425
            raise falcon.HTTPError(status=falcon.HTTP_400,
1426
                                   title='API.BAD_REQUEST',
1427
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1428
1429
        if not id_.isdigit() or int(id_) <= 0:
1430
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1431
                                   description='API.INVALID_MICROGRID_ID')
1432
1433
        cnx = mysql.connector.connect(**config.myems_system_db)
1434
        cursor = cnx.cursor()
1435
1436
        cursor.execute(" SELECT name "
1437
                       " FROM tbl_microgrids "
1438
                       " WHERE id = %s ", (id_,))
1439
        if cursor.fetchone() is None:
1440
            cursor.close()
1441
            cnx.close()
1442
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1443
                                   description='API.MICROGRID_NOT_FOUND')
1444
1445
        new_values = json.loads(raw_json)
1446
1447
        if 'name' not in new_values['data'].keys() or \
1448
                not isinstance(new_values['data']['name'], str) or \
1449
                len(str.strip(new_values['data']['name'])) == 0:
1450
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1451
                                   description='API.INVALID_MICROGRID_EVCHARGER_NAME')
1452
        name = str.strip(new_values['data']['name'])
1453
1454
        if 'power_point_id' not in new_values['data'].keys() or \
1455
                not isinstance(new_values['data']['power_point_id'], int) or \
1456
                new_values['data']['power_point_id'] <= 0:
1457
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1458
                                   description='API.INVALID_POWER_POINT_ID')
1459
        power_point_id = new_values['data']['power_point_id']
1460
1461
        if 'meter_id' not in new_values['data'].keys() or \
1462
                not isinstance(new_values['data']['meter_id'], int) or \
1463
                new_values['data']['meter_id'] <= 0:
1464
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1465
                                   description='API.INVALID_METER_ID')
1466
        meter_id = new_values['data']['meter_id']
1467
1468
        if 'rated_output_power' not in new_values['data'].keys() or \
1469
                not (isinstance(new_values['data']['rated_output_power'], float) or
1470
                     isinstance(new_values['data']['rated_output_power'], int)):
1471
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1472
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1473
        rated_output_power = float(new_values['data']['rated_output_power'])
1474
1475
        cnx = mysql.connector.connect(**config.myems_system_db)
1476
        cursor = cnx.cursor()
1477
1478
        cursor.execute(" SELECT name "
1479
                       " FROM tbl_microgrids "
1480
                       " WHERE id = %s ",
1481
                       (id_,))
1482
        if cursor.fetchone() is None:
1483
            cursor.close()
1484
            cnx.close()
1485
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1486
                                   description='API.MICROGRID_NOT_FOUND')
1487
1488
        cursor.execute(" SELECT name "
1489
                       " FROM tbl_microgrids_evchargers "
1490
                       " WHERE microgrid_id = %s AND name = %s ",
1491
                       (id_, name,))
1492
        if cursor.fetchone() is not None:
1493
            cursor.close()
1494
            cnx.close()
1495
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1496
                                   description='API.MICROGRID_EVCHARGER_NAME_IS_ALREADY_IN_USE')
1497
1498
        cursor.execute(" SELECT name "
1499
                       " FROM tbl_points "
1500
                       " WHERE id = %s ",
1501
                       (power_point_id,))
1502
        if cursor.fetchone() is None:
1503
            cursor.close()
1504
            cnx.close()
1505
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1506
                                   description='API.POWER_POINT_NOT_FOUND')
1507
1508
        cursor.execute(" SELECT name "
1509
                       " FROM tbl_meters "
1510
                       " WHERE id = %s ",
1511
                       (meter_id,))
1512
        if cursor.fetchone() is None:
1513
            cursor.close()
1514
            cnx.close()
1515
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1516
                                   description='API.METER_NOT_FOUND')
1517
1518
        add_values = (" INSERT INTO tbl_microgrids_evchargers "
1519
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power) "
1520
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
1521
        cursor.execute(add_values, (name,
1522
                                    str(uuid.uuid4()),
1523
                                    id_,
1524
                                    power_point_id,
1525
                                    meter_id,
1526
                                    rated_output_power))
1527
        new_id = cursor.lastrowid
1528
        cnx.commit()
1529
        cursor.close()
1530
        cnx.close()
1531
1532
        resp.status = falcon.HTTP_201
1533
        resp.location = '/microgrids/' + id_ + '/evchargers/' + str(new_id)
1534
1535
1536 View Code Duplication
class MicrogridEVChargerItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1537
    def __init__(self):
1538
        pass
1539
1540
    @staticmethod
1541
    def on_options(req, resp, id_, eid):
1542
        _ = req
1543
        resp.status = falcon.HTTP_200
1544
        _ = id_
1545
1546
    @staticmethod
1547
    def on_get(req, resp, id_, eid):
1548
        access_control(req)
1549
        if not id_.isdigit() or int(id_) <= 0:
1550
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1551
                                   description='API.INVALID_MICROGRID_ID')
1552
        if not eid.isdigit() or int(eid) <= 0:
1553
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1554
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1555
1556
        cnx = mysql.connector.connect(**config.myems_system_db)
1557
        cursor = cnx.cursor()
1558
1559
        cursor.execute(" SELECT name "
1560
                       " FROM tbl_microgrids "
1561
                       " WHERE id = %s ", (id_,))
1562
        if cursor.fetchone() is None:
1563
            cursor.close()
1564
            cnx.close()
1565
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1566
                                   description='API.MICROGRID_NOT_FOUND')
1567
1568
        # query microgrid dict
1569
        query = (" SELECT id, name, uuid "
1570
                 " FROM tbl_microgrids ")
1571
        cursor.execute(query)
1572
        rows_microgrids = cursor.fetchall()
1573
1574
        microgrid_dict = dict()
1575
        if rows_microgrids is not None and len(rows_microgrids) > 0:
1576
            for row in rows_microgrids:
1577
                microgrid_dict[row[0]] = {"id": row[0],
1578
                                          "name": row[1],
1579
                                          "uuid": row[2]}
1580
        # query meter dict
1581
        query = (" SELECT id, name, uuid "
1582
                 " FROM tbl_meters ")
1583
        cursor.execute(query)
1584
        rows_meters = cursor.fetchall()
1585
1586
        meter_dict = dict()
1587
        if rows_meters is not None and len(rows_meters) > 0:
1588
            for row in rows_meters:
1589
                meter_dict[row[0]] = {"id": row[0],
1590
                                      "name": row[1],
1591
                                      "uuid": row[2]}
1592
        # query point dict
1593
        query = (" SELECT id, name "
1594
                 " FROM tbl_points ")
1595
        cursor.execute(query)
1596
        rows_points = cursor.fetchall()
1597
1598
        point_dict = dict()
1599
        if rows_points is not None and len(rows_points) > 0:
1600
            for row in rows_points:
1601
                point_dict[row[0]] = {"id": row[0],
1602
                                      "name": row[1]}
1603
1604
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power "
1605
                 " FROM tbl_microgrids_evchargers "
1606
                 " WHERE id = %s ")
1607
        cursor.execute(query, (eid,))
1608
        row = cursor.fetchone()
1609
        cursor.close()
1610
        cnx.close()
1611
1612
        if row is None:
1613
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1614
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1615
        else:
1616
            meta_result = {"id": row[0],
1617
                           "name": row[1],
1618
                           "uuid": row[2],
1619
                           "microgrid": microgrid_dict.get(row[3]),
1620
                           "power_point": point_dict.get(row[4]),
1621
                           "meter": meter_dict.get(row[5]),
1622
                           "rated_output_power": row[6]}
1623
1624
        resp.text = json.dumps(meta_result)
1625
1626
    @staticmethod
1627
    @user_logger
1628
    def on_delete(req, resp, id_, eid):
1629
        admin_control(req)
1630
        if not id_.isdigit() or int(id_) <= 0:
1631
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1632
                                   description='API.INVALID_MICROGRID_ID')
1633
        if not eid.isdigit() or int(eid) <= 0:
1634
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1635
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1636
        cnx = mysql.connector.connect(**config.myems_system_db)
1637
        cursor = cnx.cursor()
1638
1639
        cursor.execute(" SELECT name "
1640
                       " FROM tbl_microgrids "
1641
                       " WHERE id = %s ", (id_,))
1642
        if cursor.fetchone() is None:
1643
            cursor.close()
1644
            cnx.close()
1645
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1646
                                   description='API.MICROGRID_NOT_FOUND')
1647
1648
        cursor.execute(" SELECT name "
1649
                       " FROM tbl_microgrids_evchargers "
1650
                       " WHERE id = %s ", (eid,))
1651
        if cursor.fetchone() is None:
1652
            cursor.close()
1653
            cnx.close()
1654
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1655
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1656
1657
        cursor.execute(" DELETE FROM tbl_microgrids_evchargers "
1658
                       " WHERE id = %s ", (eid,))
1659
        cnx.commit()
1660
1661
        cursor.close()
1662
        cnx.close()
1663
1664
        resp.status = falcon.HTTP_204
1665
1666
    @staticmethod
1667
    @user_logger
1668
    def on_put(req, resp, id_, eid):
1669
        """Handles PUT requests"""
1670
        admin_control(req)
1671
        try:
1672
            raw_json = req.stream.read().decode('utf-8')
1673
        except Exception as ex:
1674
            print(str(ex))
1675
            raise falcon.HTTPError(status=falcon.HTTP_400,
1676
                                   title='API.BAD_REQUEST',
1677
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1678
        if not id_.isdigit() or int(id_) <= 0:
1679
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1680
                                   description='API.INVALID_MICROGRID_ID')
1681
        if not eid.isdigit() or int(eid) <= 0:
1682
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1683
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1684
1685
        new_values = json.loads(raw_json)
1686
1687
        if 'name' not in new_values['data'].keys() or \
1688
                not isinstance(new_values['data']['name'], str) or \
1689
                len(str.strip(new_values['data']['name'])) == 0:
1690
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1691
                                   description='API.INVALID_MICROGRID_EVCHARGER_NAME')
1692
        name = str.strip(new_values['data']['name'])
1693
1694
        if 'power_point_id' not in new_values['data'].keys() or \
1695
                not isinstance(new_values['data']['power_point_id'], int) or \
1696
                new_values['data']['power_point_id'] <= 0:
1697
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1698
                                   description='API.INVALID_POWER_POINT_ID')
1699
        power_point_id = new_values['data']['power_point_id']
1700
1701
        if 'meter_id' not in new_values['data'].keys() or \
1702
                not isinstance(new_values['data']['meter_id'], int) or \
1703
                new_values['data']['meter_id'] <= 0:
1704
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1705
                                   description='API.INVALID_METER_ID')
1706
        meter_id = new_values['data']['meter_id']
1707
1708
        if 'rated_output_power' not in new_values['data'].keys() or \
1709
                not (isinstance(new_values['data']['rated_output_power'], float) or
1710
                     isinstance(new_values['data']['rated_output_power'], int)):
1711
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1712
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1713
        rated_output_power = float(new_values['data']['rated_output_power'])
1714
1715
        cnx = mysql.connector.connect(**config.myems_system_db)
1716
        cursor = cnx.cursor()
1717
1718
        cursor.execute(" SELECT name "
1719
                       " FROM tbl_microgrids "
1720
                       " WHERE id = %s ", (id_,))
1721
        if cursor.fetchone() is None:
1722
            cursor.close()
1723
            cnx.close()
1724
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1725
                                   description='API.MICROGRID_NOT_FOUND')
1726
1727
        cursor.execute(" SELECT name "
1728
                       " FROM tbl_microgrids_evchargers "
1729
                       " WHERE id = %s ", (eid,))
1730
        if cursor.fetchone() is None:
1731
            cursor.close()
1732
            cnx.close()
1733
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1734
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1735
1736
        cursor.execute(" SELECT name "
1737
                       " FROM tbl_microgrids_evchargers "
1738
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
1739
                       (id_, name, eid))
1740
        if cursor.fetchone() is not None:
1741
            cursor.close()
1742
            cnx.close()
1743
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1744
                                   description='API.MICROGRID_EVCHARGER_NAME_IS_ALREADY_IN_USE')
1745
1746
        cursor.execute(" SELECT name "
1747
                       " FROM tbl_points "
1748
                       " WHERE id = %s ",
1749
                       (power_point_id,))
1750
        if cursor.fetchone() is None:
1751
            cursor.close()
1752
            cnx.close()
1753
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1754
                                   description='API.POWER_POINT_NOT_FOUND')
1755
1756
        cursor.execute(" SELECT name "
1757
                       " FROM tbl_meters "
1758
                       " WHERE id = %s ",
1759
                       (meter_id,))
1760
        if cursor.fetchone() is None:
1761
            cursor.close()
1762
            cnx.close()
1763
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1764
                                   description='API.METER_NOT_FOUND')
1765
1766
        update_row = (" UPDATE tbl_microgrids_evchargers "
1767
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_output_power = %s "
1768
                      " WHERE id = %s ")
1769
        cursor.execute(update_row, (name,
1770
                                    id_,
1771
                                    power_point_id,
1772
                                    meter_id,
1773
                                    rated_output_power,
1774
                                    eid))
1775
        cnx.commit()
1776
1777
        cursor.close()
1778
        cnx.close()
1779
1780
        resp.status = falcon.HTTP_200
1781
1782
1783 View Code Duplication
class MicrogridGeneratorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1784
    def __init__(self):
1785
        pass
1786
1787
    @staticmethod
1788
    def on_options(req, resp, id_):
1789
        _ = req
1790
        resp.status = falcon.HTTP_200
1791
        _ = id_
1792
1793
    @staticmethod
1794
    def on_get(req, resp, id_):
1795
        access_control(req)
1796
        if not id_.isdigit() or int(id_) <= 0:
1797
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1798
                                   description='API.INVALID_MICROGRID_ID')
1799
1800
        cnx = mysql.connector.connect(**config.myems_system_db)
1801
        cursor = cnx.cursor()
1802
1803
        cursor.execute(" SELECT name "
1804
                       " FROM tbl_microgrids "
1805
                       " WHERE id = %s ", (id_,))
1806
        if cursor.fetchone() is None:
1807
            cursor.close()
1808
            cnx.close()
1809
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1810
                                   description='API.MICROGRID_NOT_FOUND')
1811
1812
        # query meter dict
1813
        query = (" SELECT id, name, uuid "
1814
                 " FROM tbl_meters ")
1815
        cursor.execute(query)
1816
        rows_meters = cursor.fetchall()
1817
1818
        meter_dict = dict()
1819
        if rows_meters is not None and len(rows_meters) > 0:
1820
            for row in rows_meters:
1821
                meter_dict[row[0]] = {"id": row[0],
1822
                                      "name": row[1],
1823
                                      "uuid": row[2]}
1824
        # query point dict
1825
        query = (" SELECT id, name "
1826
                 " FROM tbl_points ")
1827
        cursor.execute(query)
1828
        rows_points = cursor.fetchall()
1829
1830
        point_dict = dict()
1831
        if rows_points is not None and len(rows_points) > 0:
1832
            for row in rows_points:
1833
                point_dict[row[0]] = {"id": row[0],
1834
                                      "name": row[1]}
1835
1836
        query = (" SELECT id, name, uuid, "
1837
                 "        power_point_id, meter_id, rated_output_power "
1838
                 " FROM tbl_microgrids_generators "
1839
                 " WHERE microgrid_id = %s "
1840
                 " ORDER BY name ")
1841
        cursor.execute(query, (id_,))
1842
        rows = cursor.fetchall()
1843
1844
        result = list()
1845
        if rows is not None and len(rows) > 0:
1846
            for row in rows:
1847
                meta_result = {"id": row[0],
1848
                               "name": row[1],
1849
                               "uuid": row[2],
1850
                               "power_point": point_dict.get(row[3]),
1851
                               "meter": meter_dict.get(row[4]),
1852
                               "rated_output_power": row[5]}
1853
                result.append(meta_result)
1854
1855
        resp.text = json.dumps(result)
1856
1857
    @staticmethod
1858
    @user_logger
1859
    def on_post(req, resp, id_):
1860
        """Handles POST requests"""
1861
        admin_control(req)
1862
        try:
1863
            raw_json = req.stream.read().decode('utf-8')
1864
        except Exception as ex:
1865
            print(str(ex))
1866
            raise falcon.HTTPError(status=falcon.HTTP_400,
1867
                                   title='API.BAD_REQUEST',
1868
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1869
        if not id_.isdigit() or int(id_) <= 0:
1870
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1871
                                   description='API.INVALID_MICROGRID_ID')
1872
1873
        cnx = mysql.connector.connect(**config.myems_system_db)
1874
        cursor = cnx.cursor()
1875
1876
        cursor.execute(" SELECT name "
1877
                       " FROM tbl_microgrids "
1878
                       " WHERE id = %s ", (id_,))
1879
        if cursor.fetchone() is None:
1880
            cursor.close()
1881
            cnx.close()
1882
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1883
                                   description='API.MICROGRID_NOT_FOUND')
1884
1885
        new_values = json.loads(raw_json)
1886
1887
        if 'name' not in new_values['data'].keys() or \
1888
                not isinstance(new_values['data']['name'], str) or \
1889
                len(str.strip(new_values['data']['name'])) == 0:
1890
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1891
                                   description='API.INVALID_MICROGRID_GENERATOR_NAME')
1892
        name = str.strip(new_values['data']['name'])
1893
1894
        if 'power_point_id' not in new_values['data'].keys() or \
1895
                not isinstance(new_values['data']['power_point_id'], int) or \
1896
                new_values['data']['power_point_id'] <= 0:
1897
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1898
                                   description='API.INVALID_POWER_POINT_ID')
1899
        power_point_id = new_values['data']['power_point_id']
1900
1901
        if 'meter_id' not in new_values['data'].keys() or \
1902
                not isinstance(new_values['data']['meter_id'], int) or \
1903
                new_values['data']['meter_id'] <= 0:
1904
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1905
                                   description='API.INVALID_METER_ID')
1906
        meter_id = new_values['data']['meter_id']
1907
1908
        if 'rated_output_power' not in new_values['data'].keys() or \
1909
                not (isinstance(new_values['data']['rated_output_power'], float) or
1910
                     isinstance(new_values['data']['rated_output_power'], int)):
1911
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1912
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1913
        rated_output_power = float(new_values['data']['rated_output_power'])
1914
1915
        cnx = mysql.connector.connect(**config.myems_system_db)
1916
        cursor = cnx.cursor()
1917
1918
        cursor.execute(" SELECT name "
1919
                       " FROM tbl_microgrids "
1920
                       " WHERE id = %s ",
1921
                       (id_,))
1922
        if cursor.fetchone() is None:
1923
            cursor.close()
1924
            cnx.close()
1925
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1926
                                   description='API.MICROGRID_NOT_FOUND')
1927
1928
        cursor.execute(" SELECT name "
1929
                       " FROM tbl_microgrids_generators "
1930
                       " WHERE microgrid_id = %s AND name = %s ",
1931
                       (id_, name,))
1932
        if cursor.fetchone() is not None:
1933
            cursor.close()
1934
            cnx.close()
1935
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1936
                                   description='API.MICROGRID_GENERATOR_NAME_IS_ALREADY_IN_USE')
1937
1938
        cursor.execute(" SELECT name "
1939
                       " FROM tbl_points "
1940
                       " WHERE id = %s ",
1941
                       (power_point_id,))
1942
        if cursor.fetchone() is None:
1943
            cursor.close()
1944
            cnx.close()
1945
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1946
                                   description='API.POWER_POINT_NOT_FOUND')
1947
1948
        cursor.execute(" SELECT name "
1949
                       " FROM tbl_meters "
1950
                       " WHERE id = %s ",
1951
                       (meter_id,))
1952
        if cursor.fetchone() is None:
1953
            cursor.close()
1954
            cnx.close()
1955
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1956
                                   description='API.METER_NOT_FOUND')
1957
1958
        add_values = (" INSERT INTO tbl_microgrids_generators "
1959
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power) "
1960
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
1961
        cursor.execute(add_values, (name,
1962
                                    str(uuid.uuid4()),
1963
                                    id_,
1964
                                    power_point_id,
1965
                                    meter_id,
1966
                                    rated_output_power))
1967
        new_id = cursor.lastrowid
1968
        cnx.commit()
1969
        cursor.close()
1970
        cnx.close()
1971
1972
        resp.status = falcon.HTTP_201
1973
        resp.location = '/microgrids/' + str(id_) + '/generators/' + str(new_id)
1974
1975
1976 View Code Duplication
class MicrogridGeneratorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1977
    def __init__(self):
1978
        pass
1979
1980
    @staticmethod
1981
    def on_options(req, resp, id_, gid):
1982
        _ = req
1983
        resp.status = falcon.HTTP_200
1984
        _ = id_
1985
1986
    @staticmethod
1987
    def on_get(req, resp, id_, gid):
1988
        access_control(req)
1989
        if not id_.isdigit() or int(id_) <= 0:
1990
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1991
                                   description='API.INVALID_MICROGRID_ID')
1992
        if not gid.isdigit() or int(gid) <= 0:
1993
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1994
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
1995
1996
        cnx = mysql.connector.connect(**config.myems_system_db)
1997
        cursor = cnx.cursor()
1998
1999
        cursor.execute(" SELECT name "
2000
                       " FROM tbl_microgrids "
2001
                       " WHERE id = %s ", (id_,))
2002
        if cursor.fetchone() is None:
2003
            cursor.close()
2004
            cnx.close()
2005
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2006
                                   description='API.MICROGRID_NOT_FOUND')
2007
2008
        # query microgrid dict
2009
        query = (" SELECT id, name, uuid "
2010
                 " FROM tbl_microgrids ")
2011
        cursor.execute(query)
2012
        rows_microgrids = cursor.fetchall()
2013
2014
        microgrid_dict = dict()
2015
        if rows_microgrids is not None and len(rows_microgrids) > 0:
2016
            for row in rows_microgrids:
2017
                microgrid_dict[row[0]] = {"id": row[0],
2018
                                          "name": row[1],
2019
                                          "uuid": row[2]}
2020
        # query meter dict
2021
        query = (" SELECT id, name, uuid "
2022
                 " FROM tbl_meters ")
2023
        cursor.execute(query)
2024
        rows_meters = cursor.fetchall()
2025
2026
        meter_dict = dict()
2027
        if rows_meters is not None and len(rows_meters) > 0:
2028
            for row in rows_meters:
2029
                meter_dict[row[0]] = {"id": row[0],
2030
                                      "name": row[1],
2031
                                      "uuid": row[2]}
2032
        # query point dict
2033
        query = (" SELECT id, name "
2034
                 " FROM tbl_points ")
2035
        cursor.execute(query)
2036
        rows_points = cursor.fetchall()
2037
2038
        point_dict = dict()
2039
        if rows_points is not None and len(rows_points) > 0:
2040
            for row in rows_points:
2041
                point_dict[row[0]] = {"id": row[0],
2042
                                      "name": row[1]}
2043
2044
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power "
2045
                 " FROM tbl_microgrids_generators "
2046
                 " WHERE id = %s ")
2047
        cursor.execute(query, (gid,))
2048
        row = cursor.fetchone()
2049
        cursor.close()
2050
        cnx.close()
2051
2052
        if row is None:
2053
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2054
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2055
        else:
2056
            meta_result = {"id": row[0],
2057
                           "name": row[1],
2058
                           "uuid": row[2],
2059
                           "microgrid": microgrid_dict.get(row[3]),
2060
                           "power_point": point_dict.get(row[4]),
2061
                           "meter": meter_dict.get(row[5]),
2062
                           "rated_output_power": row[6]}
2063
2064
        resp.text = json.dumps(meta_result)
2065
2066
    @staticmethod
2067
    @user_logger
2068
    def on_delete(req, resp, id_, gid):
2069
        admin_control(req)
2070
        if not id_.isdigit() or int(id_) <= 0:
2071
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2072
                                   description='API.INVALID_MICROGRID_ID')
2073
        if not gid.isdigit() or int(gid) <= 0:
2074
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2075
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
2076
2077
        cnx = mysql.connector.connect(**config.myems_system_db)
2078
        cursor = cnx.cursor()
2079
2080
        cursor.execute(" SELECT name "
2081
                       " FROM tbl_microgrids "
2082
                       " WHERE id = %s ", (id_,))
2083
        if cursor.fetchone() is None:
2084
            cursor.close()
2085
            cnx.close()
2086
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2087
                                   description='API.MICROGRID_NOT_FOUND')
2088
2089
        cursor.execute(" SELECT name "
2090
                       " FROM tbl_microgrids_generators "
2091
                       " WHERE id = %s ", (gid,))
2092
        if cursor.fetchone() is None:
2093
            cursor.close()
2094
            cnx.close()
2095
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2096
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2097
2098
        cursor.execute(" DELETE FROM tbl_microgrids_generators "
2099
                       " WHERE id = %s ", (gid,))
2100
        cnx.commit()
2101
2102
        cursor.close()
2103
        cnx.close()
2104
2105
        resp.status = falcon.HTTP_204
2106
2107
    @staticmethod
2108
    @user_logger
2109
    def on_put(req, resp, id_, gid):
2110
        """Handles PUT requests"""
2111
        admin_control(req)
2112
        try:
2113
            raw_json = req.stream.read().decode('utf-8')
2114
        except Exception as ex:
2115
            print(str(ex))
2116
            raise falcon.HTTPError(status=falcon.HTTP_400,
2117
                                   title='API.BAD_REQUEST',
2118
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2119
        if not id_.isdigit() or int(id_) <= 0:
2120
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2121
                                   description='API.INVALID_MICROGRID_ID')
2122
        if not gid.isdigit() or int(gid) <= 0:
2123
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2124
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
2125
2126
        new_values = json.loads(raw_json)
2127
2128
        if 'name' not in new_values['data'].keys() or \
2129
                not isinstance(new_values['data']['name'], str) or \
2130
                len(str.strip(new_values['data']['name'])) == 0:
2131
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2132
                                   description='API.INVALID_MICROGRID_GENERATOR_NAME')
2133
        name = str.strip(new_values['data']['name'])
2134
2135
        if 'power_point_id' not in new_values['data'].keys() or \
2136
                not isinstance(new_values['data']['power_point_id'], int) or \
2137
                new_values['data']['power_point_id'] <= 0:
2138
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2139
                                   description='API.INVALID_POWER_POINT_ID')
2140
        power_point_id = new_values['data']['power_point_id']
2141
2142
        if 'meter_id' not in new_values['data'].keys() or \
2143
                not isinstance(new_values['data']['meter_id'], int) or \
2144
                new_values['data']['meter_id'] <= 0:
2145
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2146
                                   description='API.INVALID_METER_ID')
2147
        meter_id = new_values['data']['meter_id']
2148
2149
        if 'rated_output_power' not in new_values['data'].keys() or \
2150
                not (isinstance(new_values['data']['rated_output_power'], float) or
2151
                     isinstance(new_values['data']['rated_output_power'], int)):
2152
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2153
                                   description='API.INVALID_RATED_OUTPUT_POWER')
2154
        rated_output_power = float(new_values['data']['rated_output_power'])
2155
2156
        cnx = mysql.connector.connect(**config.myems_system_db)
2157
        cursor = cnx.cursor()
2158
2159
        cursor.execute(" SELECT name "
2160
                       " FROM tbl_microgrids "
2161
                       " WHERE id = %s ", (id_,))
2162
        if cursor.fetchone() is None:
2163
            cursor.close()
2164
            cnx.close()
2165
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2166
                                   description='API.MICROGRID_NOT_FOUND')
2167
2168
        cursor.execute(" SELECT name "
2169
                       " FROM tbl_microgrids_generators "
2170
                       " WHERE id = %s ", (gid,))
2171
        if cursor.fetchone() is None:
2172
            cursor.close()
2173
            cnx.close()
2174
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2175
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2176
2177
        cursor.execute(" SELECT name "
2178
                       " FROM tbl_microgrids_generators "
2179
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
2180
                       (id_, name, gid))
2181
        if cursor.fetchone() is not None:
2182
            cursor.close()
2183
            cnx.close()
2184
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2185
                                   description='API.MICROGRID_GENERATOR_NAME_IS_ALREADY_IN_USE')
2186
2187
        cursor.execute(" SELECT name "
2188
                       " FROM tbl_points "
2189
                       " WHERE id = %s ",
2190
                       (power_point_id,))
2191
        if cursor.fetchone() is None:
2192
            cursor.close()
2193
            cnx.close()
2194
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2195
                                   description='API.POWER_POINT_NOT_FOUND')
2196
2197
        cursor.execute(" SELECT name "
2198
                       " FROM tbl_meters "
2199
                       " WHERE id = %s ",
2200
                       (meter_id,))
2201
        if cursor.fetchone() is None:
2202
            cursor.close()
2203
            cnx.close()
2204
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2205
                                   description='API.METER_NOT_FOUND')
2206
2207
        update_row = (" UPDATE tbl_microgrids_generators "
2208
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_output_power = %s "
2209
                      " WHERE id = %s ")
2210
        cursor.execute(update_row, (name,
2211
                                    id_,
2212
                                    power_point_id,
2213
                                    meter_id,
2214
                                    rated_output_power,
2215
                                    gid))
2216
        cnx.commit()
2217
2218
        cursor.close()
2219
        cnx.close()
2220
2221
        resp.status = falcon.HTTP_200
2222
2223
2224 View Code Duplication
class MicrogridGridCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2225
    def __init__(self):
2226
        pass
2227
2228
    @staticmethod
2229
    def on_options(req, resp, id_):
2230
        _ = req
2231
        resp.status = falcon.HTTP_200
2232
        _ = id_
2233
2234
    @staticmethod
2235
    def on_get(req, resp, id_):
2236
        access_control(req)
2237
        if not id_.isdigit() or int(id_) <= 0:
2238
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2239
                                   description='API.INVALID_MICROGRID_ID')
2240
2241
        cnx = mysql.connector.connect(**config.myems_system_db)
2242
        cursor = cnx.cursor()
2243
2244
        cursor.execute(" SELECT name "
2245
                       " FROM tbl_microgrids "
2246
                       " WHERE id = %s ", (id_,))
2247
        if cursor.fetchone() is None:
2248
            cursor.close()
2249
            cnx.close()
2250
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2251
                                   description='API.MICROGRID_NOT_FOUND')
2252
2253
        # query meter dict
2254
        query = (" SELECT id, name, uuid "
2255
                 " FROM tbl_meters ")
2256
        cursor.execute(query)
2257
        rows_meters = cursor.fetchall()
2258
2259
        meter_dict = dict()
2260
        if rows_meters is not None and len(rows_meters) > 0:
2261
            for row in rows_meters:
2262
                meter_dict[row[0]] = {"id": row[0],
2263
                                      "name": row[1],
2264
                                      "uuid": row[2]}
2265
        # query point dict
2266
        query = (" SELECT id, name "
2267
                 " FROM tbl_points ")
2268
        cursor.execute(query)
2269
        rows_points = cursor.fetchall()
2270
2271
        point_dict = dict()
2272
        if rows_points is not None and len(rows_points) > 0:
2273
            for row in rows_points:
2274
                point_dict[row[0]] = {"id": row[0],
2275
                                      "name": row[1]}
2276
2277
        query = (" SELECT id, name, uuid, "
2278
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2279
                 " FROM tbl_microgrids_grids "
2280
                 " WHERE microgrid_id = %s "
2281
                 " ORDER BY name ")
2282
        cursor.execute(query, (id_,))
2283
        rows = cursor.fetchall()
2284
2285
        result = list()
2286
        if rows is not None and len(rows) > 0:
2287
            for row in rows:
2288
                meta_result = {"id": row[0],
2289
                               "name": row[1],
2290
                               "uuid": row[2],
2291
                               "power_point": point_dict.get(row[3]),
2292
                               "buy_meter": meter_dict.get(row[4]),
2293
                               "sell_meter": meter_dict.get(row[5]),
2294
                               "capacity": row[6]}
2295
                result.append(meta_result)
2296
2297
        resp.text = json.dumps(result)
2298
2299
    @staticmethod
2300
    @user_logger
2301
    def on_post(req, resp, id_):
2302
        """Handles POST requests"""
2303
        admin_control(req)
2304
        try:
2305
            raw_json = req.stream.read().decode('utf-8')
2306
        except Exception as ex:
2307
            print(str(ex))
2308
            raise falcon.HTTPError(status=falcon.HTTP_400,
2309
                                   title='API.BAD_REQUEST',
2310
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2311
        if not id_.isdigit() or int(id_) <= 0:
2312
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2313
                                   description='API.INVALID_MICROGRID_ID')
2314
2315
        cnx = mysql.connector.connect(**config.myems_system_db)
2316
        cursor = cnx.cursor()
2317
2318
        cursor.execute(" SELECT name "
2319
                       " FROM tbl_microgrids "
2320
                       " WHERE id = %s ", (id_,))
2321
        if cursor.fetchone() is None:
2322
            cursor.close()
2323
            cnx.close()
2324
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2325
                                   description='API.MICROGRID_NOT_FOUND')
2326
2327
        new_values = json.loads(raw_json)
2328
2329
        if 'name' not in new_values['data'].keys() or \
2330
                not isinstance(new_values['data']['name'], str) or \
2331
                len(str.strip(new_values['data']['name'])) == 0:
2332
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2333
                                   description='API.INVALID_MICROGRID_GRID_NAME')
2334
        name = str.strip(new_values['data']['name'])
2335
2336
        if 'power_point_id' not in new_values['data'].keys() or \
2337
                not isinstance(new_values['data']['power_point_id'], int) or \
2338
                new_values['data']['power_point_id'] <= 0:
2339
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2340
                                   description='API.INVALID_POWER_POINT_ID')
2341
        power_point_id = new_values['data']['power_point_id']
2342
2343
        if 'buy_meter_id' not in new_values['data'].keys() or \
2344
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2345
                new_values['data']['buy_meter_id'] <= 0:
2346
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2347
                                   description='API.INVALID_BUY_METER_ID')
2348
        buy_meter_id = new_values['data']['buy_meter_id']
2349
2350
        if 'sell_meter_id' not in new_values['data'].keys() or \
2351
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2352
                new_values['data']['sell_meter_id'] <= 0:
2353
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2354
                                   description='API.INVALID_SELL_METER_ID')
2355
        sell_meter_id = new_values['data']['sell_meter_id']
2356
2357
        if 'capacity' not in new_values['data'].keys() or \
2358
                not (isinstance(new_values['data']['capacity'], float) or
2359
                     isinstance(new_values['data']['capacity'], int)):
2360
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2361
                                   description='API.INVALID_CAPACITY')
2362
        capacity = float(new_values['data']['capacity'])
2363
2364
        cnx = mysql.connector.connect(**config.myems_system_db)
2365
        cursor = cnx.cursor()
2366
2367
        cursor.execute(" SELECT name "
2368
                       " FROM tbl_microgrids "
2369
                       " WHERE id = %s ",
2370
                       (id_,))
2371
        if cursor.fetchone() is None:
2372
            cursor.close()
2373
            cnx.close()
2374
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2375
                                   description='API.MICROGRID_NOT_FOUND')
2376
2377
        cursor.execute(" SELECT name "
2378
                       " FROM tbl_microgrids_grids "
2379
                       " WHERE microgrid_id = %s AND name = %s ",
2380
                       (id_, name,))
2381
        if cursor.fetchone() is not None:
2382
            cursor.close()
2383
            cnx.close()
2384
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2385
                                   description='API.MICROGRID_GRID_NAME_IS_ALREADY_IN_USE')
2386
2387
        cursor.execute(" SELECT name "
2388
                       " FROM tbl_points "
2389
                       " WHERE id = %s ",
2390
                       (power_point_id,))
2391
        if cursor.fetchone() is None:
2392
            cursor.close()
2393
            cnx.close()
2394
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2395
                                   description='API.POWER_POINT_NOT_FOUND')
2396
2397
        cursor.execute(" SELECT name "
2398
                       " FROM tbl_meters "
2399
                       " WHERE id = %s ",
2400
                       (buy_meter_id,))
2401
        if cursor.fetchone() is None:
2402
            cursor.close()
2403
            cnx.close()
2404
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2405
                                   description='API.BUY_METER_NOT_FOUND')
2406
2407
        cursor.execute(" SELECT name "
2408
                       " FROM tbl_meters "
2409
                       " WHERE id = %s ",
2410
                       (sell_meter_id,))
2411
        if cursor.fetchone() is None:
2412
            cursor.close()
2413
            cnx.close()
2414
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2415
                                   description='API.SELL_METER_NOT_FOUND')
2416
2417
        add_values = (" INSERT INTO tbl_microgrids_grids "
2418
                      "    (name, uuid, microgrid_id, power_point_id, buy_meter_id, sell_meter_id, capacity) "
2419
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2420
        cursor.execute(add_values, (name,
2421
                                    str(uuid.uuid4()),
2422
                                    id_,
2423
                                    power_point_id,
2424
                                    buy_meter_id,
2425
                                    sell_meter_id,
2426
                                    capacity))
2427
        new_id = cursor.lastrowid
2428
        cnx.commit()
2429
        cursor.close()
2430
        cnx.close()
2431
2432
        resp.status = falcon.HTTP_201
2433
        resp.location = '/microgrids/' + str(id_) + '/grids/' + str(new_id)
2434
2435
2436 View Code Duplication
class MicrogridGridItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2437
    def __init__(self):
2438
        pass
2439
2440
    @staticmethod
2441
    def on_options(req, resp, id_, gid):
2442
        _ = req
2443
        resp.status = falcon.HTTP_200
2444
        _ = id_
2445
2446
    @staticmethod
2447
    def on_get(req, resp, id_, gid):
2448
        access_control(req)
2449
        if not id_.isdigit() or int(id_) <= 0:
2450
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2451
                                   description='API.INVALID_MICROGRID_ID')
2452
        if not gid.isdigit() or int(gid) <= 0:
2453
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2454
                                   description='API.INVALID_MICROGRID_GRID_ID')
2455
2456
        cnx = mysql.connector.connect(**config.myems_system_db)
2457
        cursor = cnx.cursor()
2458
2459
        cursor.execute(" SELECT name "
2460
                       " FROM tbl_microgrids "
2461
                       " WHERE id = %s ", (id_,))
2462
        if cursor.fetchone() is None:
2463
            cursor.close()
2464
            cnx.close()
2465
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2466
                                   description='API.MICROGRID_NOT_FOUND')
2467
2468
        # query microgrid dict
2469
        query = (" SELECT id, name, uuid "
2470
                 " FROM tbl_microgrids ")
2471
        cursor.execute(query)
2472
        rows_microgrids = cursor.fetchall()
2473
2474
        microgrid_dict = dict()
2475
        if rows_microgrids is not None and len(rows_microgrids) > 0:
2476
            for row in rows_microgrids:
2477
                microgrid_dict[row[0]] = {"id": row[0],
2478
                                          "name": row[1],
2479
                                          "uuid": row[2]}
2480
        # query meter dict
2481
        query = (" SELECT id, name, uuid "
2482
                 " FROM tbl_meters ")
2483
        cursor.execute(query)
2484
        rows_meters = cursor.fetchall()
2485
2486
        meter_dict = dict()
2487
        if rows_meters is not None and len(rows_meters) > 0:
2488
            for row in rows_meters:
2489
                meter_dict[row[0]] = {"id": row[0],
2490
                                      "name": row[1],
2491
                                      "uuid": row[2]}
2492
        # query point dict
2493
        query = (" SELECT id, name "
2494
                 " FROM tbl_points ")
2495
        cursor.execute(query)
2496
        rows_points = cursor.fetchall()
2497
2498
        point_dict = dict()
2499
        if rows_points is not None and len(rows_points) > 0:
2500
            for row in rows_points:
2501
                point_dict[row[0]] = {"id": row[0],
2502
                                      "name": row[1]}
2503
2504
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, buy_meter_id, sell_meter_id, capacity "
2505
                 " FROM tbl_microgrids_grids "
2506
                 " WHERE id = %s ")
2507
        cursor.execute(query, (gid,))
2508
        row = cursor.fetchone()
2509
        cursor.close()
2510
        cnx.close()
2511
2512
        if row is None:
2513
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2514
                                   description='API.MICROGRID_GRID_NOT_FOUND')
2515
        else:
2516
            meta_result = {"id": row[0],
2517
                           "name": row[1],
2518
                           "uuid": row[2],
2519
                           "microgrid": microgrid_dict.get(row[3]),
2520
                           "power_point": point_dict.get(row[4]),
2521
                           "buy_meter": meter_dict.get(row[5]),
2522
                           "sell_meter": meter_dict.get(row[6]),
2523
                           "capacity": row[7]}
2524
2525
        resp.text = json.dumps(meta_result)
2526
2527
    @staticmethod
2528
    @user_logger
2529
    def on_delete(req, resp, id_, gid):
2530
        admin_control(req)
2531
        if not id_.isdigit() or int(id_) <= 0:
2532
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2533
                                   description='API.INVALID_MICROGRID_ID')
2534
        if not gid.isdigit() or int(gid) <= 0:
2535
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2536
                                   description='API.INVALID_MICROGRID_GRID_ID')
2537
2538
        cnx = mysql.connector.connect(**config.myems_system_db)
2539
        cursor = cnx.cursor()
2540
2541
        cursor.execute(" SELECT name "
2542
                       " FROM tbl_microgrids "
2543
                       " WHERE id = %s ", (id_,))
2544
        if cursor.fetchone() is None:
2545
            cursor.close()
2546
            cnx.close()
2547
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2548
                                   description='API.MICROGRID_NOT_FOUND')
2549
2550
        cursor.execute(" SELECT name "
2551
                       " FROM tbl_microgrids_grids "
2552
                       " WHERE id = %s ", (gid,))
2553
        if cursor.fetchone() is None:
2554
            cursor.close()
2555
            cnx.close()
2556
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2557
                                   description='API.MICROGRID_GRID_NOT_FOUND')
2558
2559
        cursor.execute(" DELETE FROM tbl_microgrids_grids "
2560
                       " WHERE id = %s ", (gid,))
2561
        cnx.commit()
2562
2563
        cursor.close()
2564
        cnx.close()
2565
2566
        resp.status = falcon.HTTP_204
2567
2568
    @staticmethod
2569
    @user_logger
2570
    def on_put(req, resp, id_, gid):
2571
        """Handles PUT requests"""
2572
        admin_control(req)
2573
        try:
2574
            raw_json = req.stream.read().decode('utf-8')
2575
        except Exception as ex:
2576
            print(str(ex))
2577
            raise falcon.HTTPError(status=falcon.HTTP_400,
2578
                                   title='API.BAD_REQUEST',
2579
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2580
        if not id_.isdigit() or int(id_) <= 0:
2581
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2582
                                   description='API.INVALID_MICROGRID_ID')
2583
2584
        if not gid.isdigit() or int(gid) <= 0:
2585
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2586
                                   description='API.INVALID_MICROGRID_GRID_ID')
2587
2588
        new_values = json.loads(raw_json)
2589
2590
        if 'name' not in new_values['data'].keys() or \
2591
                not isinstance(new_values['data']['name'], str) or \
2592
                len(str.strip(new_values['data']['name'])) == 0:
2593
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2594
                                   description='API.INVALID_MICROGRID_GRID_NAME')
2595
        name = str.strip(new_values['data']['name'])
2596
2597
        if 'power_point_id' not in new_values['data'].keys() or \
2598
                not isinstance(new_values['data']['power_point_id'], int) or \
2599
                new_values['data']['power_point_id'] <= 0:
2600
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2601
                                   description='API.INVALID_POWER_POINT_ID')
2602
        power_point_id = new_values['data']['power_point_id']
2603
2604
        if 'buy_meter_id' not in new_values['data'].keys() or \
2605
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2606
                new_values['data']['buy_meter_id'] <= 0:
2607
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2608
                                   description='API.INVALID_BUY_METER_ID')
2609
        buy_meter_id = new_values['data']['buy_meter_id']
2610
2611
        if 'sell_meter_id' not in new_values['data'].keys() or \
2612
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2613
                new_values['data']['sell_meter_id'] <= 0:
2614
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2615
                                   description='API.INVALID_METER_ID')
2616
        sell_meter_id = new_values['data']['sell_meter_id']
2617
2618
        if 'capacity' not in new_values['data'].keys() or \
2619
                not (isinstance(new_values['data']['capacity'], float) or
2620
                     isinstance(new_values['data']['capacity'], int)):
2621
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2622
                                   description='API.INVALID_CAPACITY')
2623
        capacity = float(new_values['data']['capacity'])
2624
2625
        cnx = mysql.connector.connect(**config.myems_system_db)
2626
        cursor = cnx.cursor()
2627
2628
        cursor.execute(" SELECT name "
2629
                       " FROM tbl_microgrids "
2630
                       " WHERE id = %s ", (id_,))
2631
        if cursor.fetchone() is None:
2632
            cursor.close()
2633
            cnx.close()
2634
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2635
                                   description='API.MICROGRID_NOT_FOUND')
2636
2637
        cursor.execute(" SELECT name "
2638
                       " FROM tbl_microgrids_grids "
2639
                       " WHERE id = %s ", (gid,))
2640
        if cursor.fetchone() is None:
2641
            cursor.close()
2642
            cnx.close()
2643
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2644
                                   description='API.MICROGRID_GRID_NOT_FOUND')
2645
2646
        cursor.execute(" SELECT name "
2647
                       " FROM tbl_microgrids_grids "
2648
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
2649
                       (id_, name, gid))
2650
        if cursor.fetchone() is not None:
2651
            cursor.close()
2652
            cnx.close()
2653
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2654
                                   description='API.MICROGRID_GRID_NAME_IS_ALREADY_IN_USE')
2655
2656
        cursor.execute(" SELECT name "
2657
                       " FROM tbl_points "
2658
                       " WHERE id = %s ",
2659
                       (power_point_id,))
2660
        if cursor.fetchone() is None:
2661
            cursor.close()
2662
            cnx.close()
2663
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2664
                                   description='API.POWER_POINT_NOT_FOUND')
2665
2666
        cursor.execute(" SELECT name "
2667
                       " FROM tbl_meters "
2668
                       " WHERE id = %s ",
2669
                       (buy_meter_id,))
2670
        if cursor.fetchone() is None:
2671
            cursor.close()
2672
            cnx.close()
2673
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2674
                                   description='API.BUY_METER_NOT_FOUND')
2675
2676
        cursor.execute(" SELECT name "
2677
                       " FROM tbl_meters "
2678
                       " WHERE id = %s ",
2679
                       (sell_meter_id,))
2680
        if cursor.fetchone() is None:
2681
            cursor.close()
2682
            cnx.close()
2683
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2684
                                   description='API.SELL_METER_NOT_FOUND')
2685
2686
        update_row = (" UPDATE tbl_microgrids_grids "
2687
                      " SET name = %s, microgrid_id = %s, "
2688
                      "     power_point_id = %s, buy_meter_id = %s, sell_meter_id = %s, capacity = %s "
2689
                      " WHERE id = %s ")
2690
        cursor.execute(update_row, (name,
2691
                                    id_,
2692
                                    power_point_id,
2693
                                    buy_meter_id,
2694
                                    sell_meter_id,
2695
                                    capacity,
2696
                                    gid))
2697
        cnx.commit()
2698
2699
        cursor.close()
2700
        cnx.close()
2701
2702
        resp.status = falcon.HTTP_200
2703
2704
2705
class MicrogridHeatpumpCollection:
2706
    def __init__(self):
2707
        pass
2708
2709
    @staticmethod
2710
    def on_options(req, resp, id_):
2711
        _ = req
2712
        resp.status = falcon.HTTP_200
2713
        _ = id_
2714
2715
    @staticmethod
2716
    def on_get(req, resp, id_):
2717
        access_control(req)
2718
        if not id_.isdigit() or int(id_) <= 0:
2719
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2720
                                   description='API.INVALID_MICROGRID_ID')
2721
2722
        cnx = mysql.connector.connect(**config.myems_system_db)
2723
        cursor = cnx.cursor()
2724
2725
        cursor.execute(" SELECT name "
2726
                       " FROM tbl_microgrids "
2727
                       " WHERE id = %s ", (id_,))
2728
        if cursor.fetchone() is None:
2729
            cursor.close()
2730
            cnx.close()
2731
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2732
                                   description='API.MICROGRID_NOT_FOUND')
2733
2734
        # query meter dict
2735
        query = (" SELECT id, name, uuid "
2736
                 " FROM tbl_meters ")
2737
        cursor.execute(query)
2738
        rows_meters = cursor.fetchall()
2739
2740
        meter_dict = dict()
2741
        if rows_meters is not None and len(rows_meters) > 0:
2742
            for row in rows_meters:
2743
                meter_dict[row[0]] = {"id": row[0],
2744
                                      "name": row[1],
2745
                                      "uuid": row[2]}
2746
        # query point dict
2747
        query = (" SELECT id, name "
2748
                 " FROM tbl_points ")
2749
        cursor.execute(query)
2750
        rows_points = cursor.fetchall()
2751
2752
        point_dict = dict()
2753
        if rows_points is not None and len(rows_points) > 0:
2754
            for row in rows_points:
2755
                point_dict[row[0]] = {"id": row[0],
2756
                                      "name": row[1]}
2757
2758
        query = (" SELECT id, name, uuid, "
2759
                 "        power_point_id, electricity_meter_id, heat_meter_id, cooling_meter_id, rated_input_power "
2760
                 " FROM tbl_microgrids_heatpumps "
2761
                 " WHERE microgrid_id = %s "
2762
                 " ORDER BY name ")
2763
        cursor.execute(query, (id_,))
2764
        rows = cursor.fetchall()
2765
2766
        result = list()
2767
        if rows is not None and len(rows) > 0:
2768
            for row in rows:
2769
                meta_result = {"id": row[0],
2770
                               "name": row[1],
2771
                               "uuid": row[2],
2772
                               "power_point": point_dict.get(row[3], None),
2773
                               "electricity_meter": meter_dict.get(row[4], None),
2774
                               "heat_meter": meter_dict.get(row[5], None),
2775
                               "cooling_meter": meter_dict.get(row[6], None),
2776
                               "rated_input_power": row[7]}
2777
                result.append(meta_result)
2778
2779
        resp.text = json.dumps(result)
2780
2781
    @staticmethod
2782
    @user_logger
2783
    def on_post(req, resp, id_):
2784
        """Handles POST requests"""
2785
        admin_control(req)
2786
        try:
2787
            raw_json = req.stream.read().decode('utf-8')
2788
        except Exception as ex:
2789
            print(str(ex))
2790
            raise falcon.HTTPError(status=falcon.HTTP_400,
2791
                                   title='API.BAD_REQUEST',
2792
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2793
        if not id_.isdigit() or int(id_) <= 0:
2794
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2795
                                   description='API.INVALID_MICROGRID_ID')
2796
2797
        cnx = mysql.connector.connect(**config.myems_system_db)
2798
        cursor = cnx.cursor()
2799
2800
        cursor.execute(" SELECT name "
2801
                       " FROM tbl_microgrids "
2802
                       " WHERE id = %s ", (id_,))
2803
        if cursor.fetchone() is None:
2804
            cursor.close()
2805
            cnx.close()
2806
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2807
                                   description='API.MICROGRID_NOT_FOUND')
2808
2809
        new_values = json.loads(raw_json)
2810
2811
        if 'name' not in new_values['data'].keys() or \
2812
                not isinstance(new_values['data']['name'], str) or \
2813
                len(str.strip(new_values['data']['name'])) == 0:
2814
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2815
                                   description='API.INVALID_MICROGRID_HEATPUMP_NAME')
2816
        name = str.strip(new_values['data']['name'])
2817
2818
        if 'power_point_id' not in new_values['data'].keys() or \
2819
                not isinstance(new_values['data']['power_point_id'], int) or \
2820
                new_values['data']['power_point_id'] <= 0:
2821
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2822
                                   description='API.INVALID_POWER_POINT_ID')
2823
        power_point_id = new_values['data']['power_point_id']
2824
2825
        if 'electricity_meter_id' not in new_values['data'].keys() or \
2826
                not isinstance(new_values['data']['electricity_meter_id'], int) or \
2827
                new_values['data']['electricity_meter_id'] <= 0:
2828
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2829
                                   description='API.INVALID_ELECTRICITY_METER_ID')
2830
        electricity_meter_id = new_values['data']['electricity_meter_id']
2831
2832
        if 'heat_meter_id' not in new_values['data'].keys() or \
2833
                not isinstance(new_values['data']['heat_meter_id'], int) or \
2834
                new_values['data']['heat_meter_id'] <= 0:
2835
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2836
                                   description='API.INVALID_SELL_METER_ID')
2837
        heat_meter_id = new_values['data']['heat_meter_id']
2838
2839
        if 'cooling_meter_id' not in new_values['data'].keys() or \
2840
                not isinstance(new_values['data']['cooling_meter_id'], int) or \
2841
                new_values['data']['cooling_meter_id'] <= 0:
2842
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2843
                                   description='API.INVALID_COOLING_METER_ID')
2844
        cooling_meter_id = new_values['data']['cooling_meter_id']
2845
2846
        if 'rated_input_power' not in new_values['data'].keys() or \
2847
                not (isinstance(new_values['data']['rated_input_power'], float) or
2848
                     isinstance(new_values['data']['rated_input_power'], int)):
2849
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2850
                                   description='API.INVALID_RATED_INPUT_POWER')
2851
        rated_input_power = float(new_values['data']['rated_input_power'])
2852
2853
        cnx = mysql.connector.connect(**config.myems_system_db)
2854
        cursor = cnx.cursor()
2855
2856
        cursor.execute(" SELECT name "
2857
                       " FROM tbl_microgrids "
2858
                       " WHERE id = %s ",
2859
                       (id_,))
2860
        if cursor.fetchone() is None:
2861
            cursor.close()
2862
            cnx.close()
2863
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2864
                                   description='API.MICROGRID_NOT_FOUND')
2865
2866
        cursor.execute(" SELECT name "
2867
                       " FROM tbl_microgrids_heatpumps "
2868
                       " WHERE microgrid_id = %s AND name = %s ",
2869
                       (id_, name,))
2870
        if cursor.fetchone() is not None:
2871
            cursor.close()
2872
            cnx.close()
2873
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2874
                                   description='API.MICROGRID_HEATPUMP_NAME_IS_ALREADY_IN_USE')
2875
2876
        cursor.execute(" SELECT name "
2877
                       " FROM tbl_points "
2878
                       " WHERE id = %s ",
2879
                       (power_point_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.POWER_POINT_NOT_FOUND')
2885
2886
        cursor.execute(" SELECT name "
2887
                       " FROM tbl_meters "
2888
                       " WHERE id = %s ",
2889
                       (electricity_meter_id,))
2890
        if cursor.fetchone() is None:
2891
            cursor.close()
2892
            cnx.close()
2893
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2894
                                   description='API.ELECTRICITY_METER_NOT_FOUND')
2895
2896
        cursor.execute(" SELECT name "
2897
                       " FROM tbl_meters "
2898
                       " WHERE id = %s ",
2899
                       (heat_meter_id,))
2900
        if cursor.fetchone() is None:
2901
            cursor.close()
2902
            cnx.close()
2903
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2904
                                   description='API.HEAT_METER_NOT_FOUND')
2905
2906
        cursor.execute(" SELECT name "
2907
                       " FROM tbl_meters "
2908
                       " WHERE id = %s ",
2909
                       (cooling_meter_id,))
2910
        if cursor.fetchone() is None:
2911
            cursor.close()
2912
            cnx.close()
2913
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2914
                                   description='API.COOLING_METER_NOT_FOUND')
2915
2916
        add_values = (" INSERT INTO tbl_microgrids_heatpumps "
2917
                      "    (name, uuid, microgrid_id, "
2918
                      "     power_point_id, electricity_meter_id, heat_meter_id, cooling_meter_id, rated_input_power) "
2919
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ")
2920
        cursor.execute(add_values, (name,
2921
                                    str(uuid.uuid4()),
2922
                                    id_,
2923
                                    power_point_id,
2924
                                    electricity_meter_id,
2925
                                    heat_meter_id,
2926
                                    cooling_meter_id,
2927
                                    rated_input_power))
2928
        new_id = cursor.lastrowid
2929
        cnx.commit()
2930
        cursor.close()
2931
        cnx.close()
2932
2933
        resp.status = falcon.HTTP_201
2934
        resp.location = '/microgrids/' + str(id_) + '/heatpumps/' + str(new_id)
2935
2936
2937
class MicrogridHeatpumpItem:
2938
    def __init__(self):
2939
        pass
2940
2941
    @staticmethod
2942
    def on_options(req, resp, id_, hid):
2943
        _ = req
2944
        resp.status = falcon.HTTP_200
2945
        _ = id_
2946
2947
    @staticmethod
2948
    def on_get(req, resp, id_, hid):
2949
        access_control(req)
2950
        if not id_.isdigit() or int(id_) <= 0:
2951
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2952
                                   description='API.INVALID_MICROGRID_ID')
2953
        if not hid.isdigit() or int(hid) <= 0:
2954
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2955
                                   description='API.INVALID_MICROGRID_HEATPUMP_ID')
2956
2957
        cnx = mysql.connector.connect(**config.myems_system_db)
2958
        cursor = cnx.cursor()
2959
2960
        cursor.execute(" SELECT name "
2961
                       " FROM tbl_microgrids "
2962
                       " WHERE id = %s ", (id_,))
2963
        if cursor.fetchone() is None:
2964
            cursor.close()
2965
            cnx.close()
2966
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2967
                                   description='API.MICROGRID_NOT_FOUND')
2968
2969
        # query microgrid dict
2970
        query = (" SELECT id, name, uuid "
2971
                 " FROM tbl_microgrids ")
2972
        cursor.execute(query)
2973
        rows_microgrids = cursor.fetchall()
2974
2975
        microgrid_dict = dict()
2976
        if rows_microgrids is not None and len(rows_microgrids) > 0:
2977
            for row in rows_microgrids:
2978
                microgrid_dict[row[0]] = {"id": row[0],
2979
                                          "name": row[1],
2980
                                          "uuid": row[2]}
2981
        # query meter dict
2982
        query = (" SELECT id, name, uuid "
2983
                 " FROM tbl_meters ")
2984
        cursor.execute(query)
2985
        rows_meters = cursor.fetchall()
2986
2987
        meter_dict = dict()
2988
        if rows_meters is not None and len(rows_meters) > 0:
2989
            for row in rows_meters:
2990
                meter_dict[row[0]] = {"id": row[0],
2991
                                      "name": row[1],
2992
                                      "uuid": row[2]}
2993
        # query point dict
2994
        query = (" SELECT id, name "
2995
                 " FROM tbl_points ")
2996
        cursor.execute(query)
2997
        rows_points = cursor.fetchall()
2998
2999
        point_dict = dict()
3000
        if rows_points is not None and len(rows_points) > 0:
3001
            for row in rows_points:
3002
                point_dict[row[0]] = {"id": row[0],
3003
                                      "name": row[1]}
3004
3005
        query = (" SELECT id, name, uuid, microgrid_id, "
3006
                 "        power_point_id, electricity_meter_id, heat_meter_id, cooling_meter_id, rated_input_power "
3007
                 " FROM tbl_microgrids_heatpumps "
3008
                 " WHERE id = %s ")
3009
        cursor.execute(query, (hid,))
3010
        row = cursor.fetchone()
3011
        cursor.close()
3012
        cnx.close()
3013
3014
        if row is None:
3015
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3016
                                   description='API.MICROGRID_HEATPUMP_NOT_FOUND')
3017
        else:
3018
            meta_result = {"id": row[0],
3019
                           "name": row[1],
3020
                           "uuid": row[2],
3021
                           "microgrid": microgrid_dict.get(row[3], None),
3022
                           "power_point": point_dict.get(row[4], None),
3023
                           "electricity_meter": meter_dict.get(row[5], None),
3024
                           "heat_meter": meter_dict.get(row[6], None),
3025
                           "cooling_meter": meter_dict.get(row[7], None),
3026
                           "rated_input_power": row[8]}
3027
3028
        resp.text = json.dumps(meta_result)
3029
3030
    @staticmethod
3031
    @user_logger
3032
    def on_delete(req, resp, id_, hid):
3033
        admin_control(req)
3034
        if not id_.isdigit() or int(id_) <= 0:
3035
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3036
                                   description='API.INVALID_MICROGRID_ID')
3037
        if not hid.isdigit() or int(hid) <= 0:
3038
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3039
                                   description='API.INVALID_MICROGRID_HEATPUMP_ID')
3040
3041
        cnx = mysql.connector.connect(**config.myems_system_db)
3042
        cursor = cnx.cursor()
3043
3044
        cursor.execute(" SELECT name "
3045
                       " FROM tbl_microgrids "
3046
                       " WHERE id = %s ", (id_,))
3047
        if cursor.fetchone() is None:
3048
            cursor.close()
3049
            cnx.close()
3050
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3051
                                   description='API.MICROGRID_NOT_FOUND')
3052
3053
        cursor.execute(" SELECT name "
3054
                       " FROM tbl_microgrids_heatpumps "
3055
                       " WHERE id = %s ", (hid,))
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_HEATPUMP_NOT_FOUND')
3061
3062
        cursor.execute(" DELETE FROM tbl_microgrids_heatpumps "
3063
                       " WHERE id = %s ", (hid,))
3064
        cnx.commit()
3065
3066
        cursor.close()
3067
        cnx.close()
3068
3069
        resp.status = falcon.HTTP_204
3070
3071
    @staticmethod
3072
    @user_logger
3073
    def on_put(req, resp, id_, hid):
3074
        """Handles PUT requests"""
3075
        admin_control(req)
3076
        try:
3077
            raw_json = req.stream.read().decode('utf-8')
3078
        except Exception as ex:
3079
            print(str(ex))
3080
            raise falcon.HTTPError(status=falcon.HTTP_400,
3081
                                   title='API.BAD_REQUEST',
3082
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3083
        if not id_.isdigit() or int(id_) <= 0:
3084
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3085
                                   description='API.INVALID_MICROGRID_ID')
3086
        if not hid.isdigit() or int(hid) <= 0:
3087
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3088
                                   description='API.INVALID_MICROGRID_HEATPUMP_ID')
3089
3090
        new_values = json.loads(raw_json)
3091
3092
        if 'name' not in new_values['data'].keys() or \
3093
                not isinstance(new_values['data']['name'], str) or \
3094
                len(str.strip(new_values['data']['name'])) == 0:
3095
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3096
                                   description='API.INVALID_MICROGRID_HEATPUMP_NAME')
3097
        name = str.strip(new_values['data']['name'])
3098
3099
        if 'power_point_id' not in new_values['data'].keys() or \
3100
                not isinstance(new_values['data']['power_point_id'], int) or \
3101
                new_values['data']['power_point_id'] <= 0:
3102
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3103
                                   description='API.INVALID_POWER_POINT_ID')
3104
        power_point_id = new_values['data']['power_point_id']
3105
3106
        if 'electricity_meter_id' not in new_values['data'].keys() or \
3107
                not isinstance(new_values['data']['electricity_meter_id'], int) or \
3108
                new_values['data']['electricity_meter_id'] <= 0:
3109
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3110
                                   description='API.INVALID_ELECTRICITY_METER_ID')
3111
        electricity_meter_id = new_values['data']['electricity_meter_id']
3112
3113
        if 'heat_meter_id' not in new_values['data'].keys() or \
3114
                not isinstance(new_values['data']['heat_meter_id'], int) or \
3115
                new_values['data']['heat_meter_id'] <= 0:
3116
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3117
                                   description='API.INVALID_HEAT_METER_ID')
3118
        heat_meter_id = new_values['data']['heat_meter_id']
3119
3120
        if 'cooling_meter_id' not in new_values['data'].keys() or \
3121
                not isinstance(new_values['data']['cooling_meter_id'], int) or \
3122
                new_values['data']['cooling_meter_id'] <= 0:
3123
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3124
                                   description='API.INVALID_COOLING_METER_ID')
3125
        cooling_meter_id = new_values['data']['cooling_meter_id']
3126
3127
        if 'rated_input_power' not in new_values['data'].keys() or \
3128
                not (isinstance(new_values['data']['rated_input_power'], float) or
3129
                     isinstance(new_values['data']['rated_input_power'], int)):
3130
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3131
                                   description='API.INVALID_RATED_INPUT_POWER')
3132
        rated_input_power = float(new_values['data']['rated_input_power'])
3133
3134
        cnx = mysql.connector.connect(**config.myems_system_db)
3135
        cursor = cnx.cursor()
3136
3137
        cursor.execute(" SELECT name "
3138
                       " FROM tbl_microgrids "
3139
                       " WHERE id = %s ", (id_,))
3140
        if cursor.fetchone() is None:
3141
            cursor.close()
3142
            cnx.close()
3143
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3144
                                   description='API.MICROGRID_NOT_FOUND')
3145
3146
        cursor.execute(" SELECT name "
3147
                       " FROM tbl_microgrids_heatpumps "
3148
                       " WHERE id = %s ", (hid,))
3149
        if cursor.fetchone() is None:
3150
            cursor.close()
3151
            cnx.close()
3152
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3153
                                   description='API.MICROGRID_HEATPUMP_NOT_FOUND')
3154
3155
        cursor.execute(" SELECT name "
3156
                       " FROM tbl_microgrids_heatpumps "
3157
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
3158
                       (id_, name, hid))
3159
        if cursor.fetchone() is not None:
3160
            cursor.close()
3161
            cnx.close()
3162
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3163
                                   description='API.MICROGRID_HEATPUMP_NAME_IS_ALREADY_IN_USE')
3164
3165
        cursor.execute(" SELECT name "
3166
                       " FROM tbl_points "
3167
                       " WHERE id = %s ",
3168
                       (power_point_id,))
3169
        if cursor.fetchone() is None:
3170
            cursor.close()
3171
            cnx.close()
3172
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3173
                                   description='API.POWER_POINT_NOT_FOUND')
3174
3175
        cursor.execute(" SELECT name "
3176
                       " FROM tbl_meters "
3177
                       " WHERE id = %s ",
3178
                       (electricity_meter_id,))
3179
        if cursor.fetchone() is None:
3180
            cursor.close()
3181
            cnx.close()
3182
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3183
                                   description='API.ELECTRICITY_METER_NOT_FOUND')
3184
3185
        cursor.execute(" SELECT name "
3186
                       " FROM tbl_meters "
3187
                       " WHERE id = %s ",
3188
                       (heat_meter_id,))
3189
        if cursor.fetchone() is None:
3190
            cursor.close()
3191
            cnx.close()
3192
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3193
                                   description='API.HEAT_METER_NOT_FOUND')
3194
3195
        cursor.execute(" SELECT name "
3196
                       " FROM tbl_meters "
3197
                       " WHERE id = %s ",
3198
                       (cooling_meter_id,))
3199
        if cursor.fetchone() is None:
3200
            cursor.close()
3201
            cnx.close()
3202
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3203
                                   description='API.COOLING_METER_NOT_FOUND')
3204
3205
        update_row = (" UPDATE tbl_microgrids_heatpumps "
3206
                      " SET name = %s, microgrid_id = %s, "
3207
                      "     power_point_id = %s, electricity_meter_id = %s, heat_meter_id = %s, cooling_meter_id = %s, "
3208
                      "     rated_input_power = %s "
3209
                      " WHERE id = %s ")
3210
        cursor.execute(update_row, (name,
3211
                                    id_,
3212
                                    power_point_id,
3213
                                    electricity_meter_id,
3214
                                    heat_meter_id,
3215
                                    heat_meter_id,
3216
                                    rated_input_power,
3217
                                    hid))
3218
        cnx.commit()
3219
3220
        cursor.close()
3221
        cnx.close()
3222
3223
        resp.status = falcon.HTTP_200
3224
3225
3226 View Code Duplication
class MicrogridLoadCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3227
    def __init__(self):
3228
        pass
3229
3230
    @staticmethod
3231
    def on_options(req, resp, id_):
3232
        _ = req
3233
        resp.status = falcon.HTTP_200
3234
        _ = id_
3235
3236
    @staticmethod
3237
    def on_get(req, resp, id_):
3238
        access_control(req)
3239
        if not id_.isdigit() or int(id_) <= 0:
3240
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3241
                                   description='API.INVALID_MICROGRID_ID')
3242
3243
        cnx = mysql.connector.connect(**config.myems_system_db)
3244
        cursor = cnx.cursor()
3245
3246
        cursor.execute(" SELECT name "
3247
                       " FROM tbl_microgrids "
3248
                       " WHERE id = %s ", (id_,))
3249
        if cursor.fetchone() is None:
3250
            cursor.close()
3251
            cnx.close()
3252
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3253
                                   description='API.MICROGRID_NOT_FOUND')
3254
3255
        # query meter dict
3256
        query = (" SELECT id, name, uuid "
3257
                 " FROM tbl_meters ")
3258
        cursor.execute(query)
3259
        rows_meters = cursor.fetchall()
3260
3261
        meter_dict = dict()
3262
        if rows_meters is not None and len(rows_meters) > 0:
3263
            for row in rows_meters:
3264
                meter_dict[row[0]] = {"id": row[0],
3265
                                      "name": row[1],
3266
                                      "uuid": row[2]}
3267
        # query point dict
3268
        query = (" SELECT id, name "
3269
                 " FROM tbl_points ")
3270
        cursor.execute(query)
3271
        rows_points = cursor.fetchall()
3272
3273
        point_dict = dict()
3274
        if rows_points is not None and len(rows_points) > 0:
3275
            for row in rows_points:
3276
                point_dict[row[0]] = {"id": row[0],
3277
                                      "name": row[1]}
3278
3279
        query = (" SELECT id, name, uuid, "
3280
                 "        power_point_id, meter_id, rated_input_power "
3281
                 " FROM tbl_microgrids_loads "
3282
                 " WHERE microgrid_id = %s "
3283
                 " ORDER BY name ")
3284
        cursor.execute(query, (id_,))
3285
        rows = cursor.fetchall()
3286
3287
        result = list()
3288
        if rows is not None and len(rows) > 0:
3289
            for row in rows:
3290
                meta_result = {"id": row[0],
3291
                               "name": row[1],
3292
                               "uuid": row[2],
3293
                               "power_point": point_dict.get(row[3], None),
3294
                               "meter": meter_dict.get(row[4], None),
3295
                               "rated_input_power": row[5]}
3296
                result.append(meta_result)
3297
3298
        resp.text = json.dumps(result)
3299
3300
    @staticmethod
3301
    @user_logger
3302
    def on_post(req, resp, id_):
3303
        """Handles POST requests"""
3304
        admin_control(req)
3305
        try:
3306
            raw_json = req.stream.read().decode('utf-8')
3307
        except Exception as ex:
3308
            print(str(ex))
3309
            raise falcon.HTTPError(status=falcon.HTTP_400,
3310
                                   title='API.BAD_REQUEST',
3311
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3312
        if not id_.isdigit() or int(id_) <= 0:
3313
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3314
                                   description='API.INVALID_MICROGRID_ID')
3315
3316
        cnx = mysql.connector.connect(**config.myems_system_db)
3317
        cursor = cnx.cursor()
3318
3319
        cursor.execute(" SELECT name "
3320
                       " FROM tbl_microgrids "
3321
                       " WHERE id = %s ", (id_,))
3322
        if cursor.fetchone() is None:
3323
            cursor.close()
3324
            cnx.close()
3325
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3326
                                   description='API.MICROGRID_NOT_FOUND')
3327
3328
        new_values = json.loads(raw_json)
3329
3330
        if 'name' not in new_values['data'].keys() or \
3331
                not isinstance(new_values['data']['name'], str) or \
3332
                len(str.strip(new_values['data']['name'])) == 0:
3333
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3334
                                   description='API.INVALID_MICROGRID_LOAD_NAME')
3335
        name = str.strip(new_values['data']['name'])
3336
3337
        if 'power_point_id' not in new_values['data'].keys() or \
3338
                not isinstance(new_values['data']['power_point_id'], int) or \
3339
                new_values['data']['power_point_id'] <= 0:
3340
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3341
                                   description='API.INVALID_POWER_POINT_ID')
3342
        power_point_id = new_values['data']['power_point_id']
3343
3344
        if 'meter_id' not in new_values['data'].keys() or \
3345
                not isinstance(new_values['data']['meter_id'], int) or \
3346
                new_values['data']['meter_id'] <= 0:
3347
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3348
                                   description='API.INVALID_METER_ID')
3349
        meter_id = new_values['data']['meter_id']
3350
3351
        if 'rated_input_power' not in new_values['data'].keys() or \
3352
                not (isinstance(new_values['data']['rated_input_power'], float) or
3353
                     isinstance(new_values['data']['rated_input_power'], int)):
3354
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3355
                                   description='API.INVALID_RATED_INPUT_POWER')
3356
        rated_input_power = float(new_values['data']['rated_input_power'])
3357
3358
        cnx = mysql.connector.connect(**config.myems_system_db)
3359
        cursor = cnx.cursor()
3360
3361
        cursor.execute(" SELECT name "
3362
                       " FROM tbl_microgrids "
3363
                       " WHERE id = %s ",
3364
                       (id_,))
3365
        if cursor.fetchone() is None:
3366
            cursor.close()
3367
            cnx.close()
3368
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3369
                                   description='API.MICROGRID_NOT_FOUND')
3370
3371
        cursor.execute(" SELECT name "
3372
                       " FROM tbl_microgrids_loads "
3373
                       " WHERE microgrid_id = %s AND name = %s ",
3374
                       (id_, name,))
3375
        if cursor.fetchone() is not None:
3376
            cursor.close()
3377
            cnx.close()
3378
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3379
                                   description='API.MICROGRID_LOAD_NAME_IS_ALREADY_IN_USE')
3380
3381
        cursor.execute(" SELECT name "
3382
                       " FROM tbl_points "
3383
                       " WHERE id = %s ",
3384
                       (power_point_id,))
3385
        if cursor.fetchone() is None:
3386
            cursor.close()
3387
            cnx.close()
3388
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3389
                                   description='API.POWER_POINT_NOT_FOUND')
3390
3391
        cursor.execute(" SELECT name "
3392
                       " FROM tbl_meters "
3393
                       " WHERE id = %s ",
3394
                       (meter_id,))
3395
        if cursor.fetchone() is None:
3396
            cursor.close()
3397
            cnx.close()
3398
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3399
                                   description='API.METER_NOT_FOUND')
3400
3401
        add_values = (" INSERT INTO tbl_microgrids_loads "
3402
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_input_power) "
3403
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3404
        cursor.execute(add_values, (name,
3405
                                    str(uuid.uuid4()),
3406
                                    id_,
3407
                                    power_point_id,
3408
                                    meter_id,
3409
                                    rated_input_power))
3410
        new_id = cursor.lastrowid
3411
        cnx.commit()
3412
        cursor.close()
3413
        cnx.close()
3414
3415
        resp.status = falcon.HTTP_201
3416
        resp.location = '/microgrids/' + str(id_) + '/loads/' + str(new_id)
3417
3418
3419
class MicrogridLoadItem:
3420
    def __init__(self):
3421
        pass
3422
3423
    @staticmethod
3424
    def on_options(req, resp, id_, lid):
3425
        _ = req
3426
        resp.status = falcon.HTTP_200
3427
        _ = id_
3428
3429
    @staticmethod
3430
    def on_get(req, resp, id_, lid):
3431
        access_control(req)
3432
        if not id_.isdigit() or int(id_) <= 0:
3433
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3434
                                   description='API.INVALID_MICROGRID_ID')
3435
        if not lid.isdigit() or int(lid) <= 0:
3436
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3437
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3438
3439
        cnx = mysql.connector.connect(**config.myems_system_db)
3440
        cursor = cnx.cursor()
3441
3442
        cursor.execute(" SELECT name "
3443
                       " FROM tbl_microgrids "
3444
                       " WHERE id = %s ", (id_,))
3445
        if cursor.fetchone() is None:
3446
            cursor.close()
3447
            cnx.close()
3448
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3449
                                   description='API.MICROGRID_NOT_FOUND')
3450
3451
        # query microgrid dict
3452
        query = (" SELECT id, name, uuid "
3453
                 " FROM tbl_microgrids ")
3454
        cursor.execute(query)
3455
        rows_microgrids = cursor.fetchall()
3456
3457
        microgrid_dict = dict()
3458
        if rows_microgrids is not None and len(rows_microgrids) > 0:
3459
            for row in rows_microgrids:
3460
                microgrid_dict[row[0]] = {"id": row[0],
3461
                                          "name": row[1],
3462
                                          "uuid": row[2]}
3463
        # query meter dict
3464
        query = (" SELECT id, name, uuid "
3465
                 " FROM tbl_meters ")
3466
        cursor.execute(query)
3467
        rows_meters = cursor.fetchall()
3468
3469
        meter_dict = dict()
3470
        if rows_meters is not None and len(rows_meters) > 0:
3471
            for row in rows_meters:
3472
                meter_dict[row[0]] = {"id": row[0],
3473
                                      "name": row[1],
3474
                                      "uuid": row[2]}
3475
        # query point dict
3476
        query = (" SELECT id, name "
3477
                 " FROM tbl_points ")
3478
        cursor.execute(query)
3479
        rows_points = cursor.fetchall()
3480
3481
        point_dict = dict()
3482
        if rows_points is not None and len(rows_points) > 0:
3483
            for row in rows_points:
3484
                point_dict[row[0]] = {"id": row[0],
3485
                                      "name": row[1]}
3486
3487
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_input_power "
3488
                 " FROM tbl_microgrids_loads "
3489
                 " WHERE id = %s ")
3490
        cursor.execute(query, (lid,))
3491
        row = cursor.fetchone()
3492
        cursor.close()
3493
        cnx.close()
3494
3495
        if row is None:
3496
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3497
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3498
        else:
3499
            meta_result = {"id": row[0],
3500
                           "name": row[1],
3501
                           "uuid": row[2],
3502
                           "microgrid": microgrid_dict.get(row[3], None),
3503
                           "power_point": point_dict.get(row[4], None),
3504
                           "meter": meter_dict.get(row[5], None),
3505
                           "rated_input_power": row[6]}
3506
3507
        resp.text = json.dumps(meta_result)
3508
3509
    @staticmethod
3510
    @user_logger
3511
    def on_delete(req, resp, id_, lid):
3512
        admin_control(req)
3513
        if not id_.isdigit() or int(id_) <= 0:
3514
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3515
                                   description='API.INVALID_MICROGRID_ID')
3516
        if not lid.isdigit() or int(lid) <= 0:
3517
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3518
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3519
3520
        cnx = mysql.connector.connect(**config.myems_system_db)
3521
        cursor = cnx.cursor()
3522
3523
        cursor.execute(" SELECT name "
3524
                       " FROM tbl_microgrids "
3525
                       " WHERE id = %s ", (id_,))
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_NOT_FOUND')
3531
3532
        cursor.execute(" SELECT name "
3533
                       " FROM tbl_microgrids_loads "
3534
                       " WHERE id = %s ", (lid,))
3535
        if cursor.fetchone() is None:
3536
            cursor.close()
3537
            cnx.close()
3538
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3539
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3540
3541
        cursor.execute(" DELETE FROM tbl_microgrids_loads "
3542
                       " WHERE id = %s ", (lid,))
3543
        cnx.commit()
3544
3545
        cursor.close()
3546
        cnx.close()
3547
3548
        resp.status = falcon.HTTP_204
3549
3550
    @staticmethod
3551
    @user_logger
3552
    def on_put(req, resp, id_, lid):
3553
        """Handles PUT requests"""
3554
        admin_control(req)
3555
        try:
3556
            raw_json = req.stream.read().decode('utf-8')
3557
        except Exception as ex:
3558
            print(str(ex))
3559
            raise falcon.HTTPError(status=falcon.HTTP_400,
3560
                                   title='API.BAD_REQUEST',
3561
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3562
        if not id_.isdigit() or int(id_) <= 0:
3563
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3564
                                   description='API.INVALID_MICROGRID_ID')
3565
        if not lid.isdigit() or int(lid) <= 0:
3566
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3567
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3568
3569
        new_values = json.loads(raw_json)
3570
3571
        if 'name' not in new_values['data'].keys() or \
3572
                not isinstance(new_values['data']['name'], str) or \
3573
                len(str.strip(new_values['data']['name'])) == 0:
3574
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3575
                                   description='API.INVALID_MICROGRID_LOAD_NAME')
3576
        name = str.strip(new_values['data']['name'])
3577
3578
        if 'power_point_id' not in new_values['data'].keys() or \
3579
                not isinstance(new_values['data']['power_point_id'], int) or \
3580
                new_values['data']['power_point_id'] <= 0:
3581
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3582
                                   description='API.INVALID_POWER_POINT_ID')
3583
        power_point_id = new_values['data']['power_point_id']
3584
3585
        if 'meter_id' not in new_values['data'].keys() or \
3586
                not isinstance(new_values['data']['meter_id'], int) or \
3587
                new_values['data']['meter_id'] <= 0:
3588
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3589
                                   description='API.INVALID_METER_ID')
3590
        meter_id = new_values['data']['meter_id']
3591
3592
        if 'rated_input_power' not in new_values['data'].keys() or \
3593
                not (isinstance(new_values['data']['rated_input_power'], float) or
3594
                     isinstance(new_values['data']['rated_input_power'], int)):
3595
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3596
                                   description='API.INVALID_RATED_INPUT_POWER')
3597
        rated_input_power = float(new_values['data']['rated_input_power'])
3598
3599
        cnx = mysql.connector.connect(**config.myems_system_db)
3600
        cursor = cnx.cursor()
3601
3602
        cursor.execute(" SELECT name "
3603
                       " FROM tbl_microgrids "
3604
                       " WHERE id = %s ", (id_,))
3605
        if cursor.fetchone() is None:
3606
            cursor.close()
3607
            cnx.close()
3608
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3609
                                   description='API.MICROGRID_NOT_FOUND')
3610
3611
        cursor.execute(" SELECT name "
3612
                       " FROM tbl_microgrids_loads "
3613
                       " WHERE id = %s ", (lid,))
3614
        if cursor.fetchone() is None:
3615
            cursor.close()
3616
            cnx.close()
3617
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3618
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3619
3620
        cursor.execute(" SELECT name "
3621
                       " FROM tbl_microgrids_loads "
3622
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
3623
                       (id_, name, lid))
3624
        if cursor.fetchone() is not None:
3625
            cursor.close()
3626
            cnx.close()
3627
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3628
                                   description='API.MICROGRID_LOAD_NAME_IS_ALREADY_IN_USE')
3629
3630
        cursor.execute(" SELECT name "
3631
                       " FROM tbl_points "
3632
                       " WHERE id = %s ",
3633
                       (power_point_id,))
3634
        if cursor.fetchone() is None:
3635
            cursor.close()
3636
            cnx.close()
3637
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3638
                                   description='API.POWER_POINT_NOT_FOUND')
3639
3640
        cursor.execute(" SELECT name "
3641
                       " FROM tbl_meters "
3642
                       " WHERE id = %s ",
3643
                       (meter_id,))
3644
        if cursor.fetchone() is None:
3645
            cursor.close()
3646
            cnx.close()
3647
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3648
                                   description='API.METER_NOT_FOUND')
3649
3650
        update_row = (" UPDATE tbl_microgrids_loads "
3651
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_input_power = %s "
3652
                      " WHERE id = %s ")
3653
        cursor.execute(update_row, (name,
3654
                                    id_,
3655
                                    power_point_id,
3656
                                    meter_id,
3657
                                    rated_input_power,
3658
                                    lid))
3659
        cnx.commit()
3660
3661
        cursor.close()
3662
        cnx.close()
3663
3664
        resp.status = falcon.HTTP_200
3665
3666
3667 View Code Duplication
class MicrogridPhotovoltaicCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3668
    def __init__(self):
3669
        pass
3670
3671
    @staticmethod
3672
    def on_options(req, resp, id_):
3673
        _ = req
3674
        resp.status = falcon.HTTP_200
3675
        _ = id_
3676
3677
    @staticmethod
3678
    def on_get(req, resp, id_):
3679
        access_control(req)
3680
        if not id_.isdigit() or int(id_) <= 0:
3681
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3682
                                   description='API.INVALID_MICROGRID_ID')
3683
3684
        cnx = mysql.connector.connect(**config.myems_system_db)
3685
        cursor = cnx.cursor()
3686
3687
        cursor.execute(" SELECT name "
3688
                       " FROM tbl_microgrids "
3689
                       " WHERE id = %s ", (id_,))
3690
        if cursor.fetchone() is None:
3691
            cursor.close()
3692
            cnx.close()
3693
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3694
                                   description='API.MICROGRID_NOT_FOUND')
3695
3696
        # query meter dict
3697
        query = (" SELECT id, name, uuid "
3698
                 " FROM tbl_meters ")
3699
        cursor.execute(query)
3700
        rows_meters = cursor.fetchall()
3701
3702
        meter_dict = dict()
3703
        if rows_meters is not None and len(rows_meters) > 0:
3704
            for row in rows_meters:
3705
                meter_dict[row[0]] = {"id": row[0],
3706
                                      "name": row[1],
3707
                                      "uuid": row[2]}
3708
        # query point dict
3709
        query = (" SELECT id, name "
3710
                 " FROM tbl_points ")
3711
        cursor.execute(query)
3712
        rows_points = cursor.fetchall()
3713
3714
        point_dict = dict()
3715
        if rows_points is not None and len(rows_points) > 0:
3716
            for row in rows_points:
3717
                point_dict[row[0]] = {"id": row[0],
3718
                                      "name": row[1]}
3719
3720
        query = (" SELECT id, name, uuid, "
3721
                 "        power_point_id, meter_id, rated_power "
3722
                 " FROM tbl_microgrids_photovoltaics "
3723
                 " WHERE microgrid_id = %s "
3724
                 " ORDER BY name ")
3725
        cursor.execute(query, (id_,))
3726
        rows = cursor.fetchall()
3727
3728
        result = list()
3729
        if rows is not None and len(rows) > 0:
3730
            for row in rows:
3731
                meta_result = {"id": row[0],
3732
                               "name": row[1],
3733
                               "uuid": row[2],
3734
                               "power_point": point_dict.get(row[3], None),
3735
                               "meter": meter_dict.get(row[4], None),
3736
                               "rated_power": row[5],
3737
                               }
3738
                result.append(meta_result)
3739
3740
        resp.text = json.dumps(result)
3741
3742
    @staticmethod
3743
    @user_logger
3744
    def on_post(req, resp, id_):
3745
        """Handles POST requests"""
3746
        admin_control(req)
3747
        try:
3748
            raw_json = req.stream.read().decode('utf-8')
3749
        except Exception as ex:
3750
            print(str(ex))
3751
            raise falcon.HTTPError(status=falcon.HTTP_400,
3752
                                   title='API.BAD_REQUEST',
3753
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3754
        if not id_.isdigit() or int(id_) <= 0:
3755
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3756
                                   description='API.INVALID_MICROGRID_ID')
3757
3758
        cnx = mysql.connector.connect(**config.myems_system_db)
3759
        cursor = cnx.cursor()
3760
3761
        cursor.execute(" SELECT name "
3762
                       " FROM tbl_microgrids "
3763
                       " WHERE id = %s ", (id_,))
3764
        if cursor.fetchone() is None:
3765
            cursor.close()
3766
            cnx.close()
3767
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3768
                                   description='API.MICROGRID_NOT_FOUND')
3769
3770
        new_values = json.loads(raw_json)
3771
3772
        if 'name' not in new_values['data'].keys() or \
3773
                not isinstance(new_values['data']['name'], str) or \
3774
                len(str.strip(new_values['data']['name'])) == 0:
3775
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3776
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_NAME')
3777
        name = str.strip(new_values['data']['name'])
3778
3779
        if 'power_point_id' not in new_values['data'].keys() or \
3780
                not isinstance(new_values['data']['power_point_id'], int) or \
3781
                new_values['data']['power_point_id'] <= 0:
3782
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3783
                                   description='API.INVALID_POWER_POINT_ID')
3784
        power_point_id = new_values['data']['power_point_id']
3785
3786
        if 'meter_id' not in new_values['data'].keys() or \
3787
                not isinstance(new_values['data']['meter_id'], int) or \
3788
                new_values['data']['meter_id'] <= 0:
3789
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3790
                                   description='API.INVALID_METER_ID')
3791
        meter_id = new_values['data']['meter_id']
3792
3793
        if 'rated_power' not in new_values['data'].keys() or \
3794
                not (isinstance(new_values['data']['rated_power'], float) or
3795
                     isinstance(new_values['data']['rated_power'], int)):
3796
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3797
                                   description='API.INVALID_RATED_POWER')
3798
        rated_power = float(new_values['data']['rated_power'])
3799
3800
        cnx = mysql.connector.connect(**config.myems_system_db)
3801
        cursor = cnx.cursor()
3802
3803
        cursor.execute(" SELECT name "
3804
                       " FROM tbl_microgrids "
3805
                       " WHERE id = %s ",
3806
                       (id_,))
3807
        if cursor.fetchone() is None:
3808
            cursor.close()
3809
            cnx.close()
3810
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3811
                                   description='API.MICROGRID_NOT_FOUND')
3812
3813
        cursor.execute(" SELECT name "
3814
                       " FROM tbl_microgrids_photovoltaics "
3815
                       " WHERE microgrid_id = %s AND name = %s ",
3816
                       (id_, name,))
3817
        if cursor.fetchone() is not None:
3818
            cursor.close()
3819
            cnx.close()
3820
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3821
                                   description='API.MICROGRID_PHOTOVOLTAIC_NAME_IS_ALREADY_IN_USE')
3822
3823
        cursor.execute(" SELECT name "
3824
                       " FROM tbl_points "
3825
                       " WHERE id = %s ",
3826
                       (power_point_id,))
3827
        if cursor.fetchone() is None:
3828
            cursor.close()
3829
            cnx.close()
3830
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3831
                                   description='API.POWER_POINT_NOT_FOUND')
3832
3833
        cursor.execute(" SELECT name "
3834
                       " FROM tbl_meters "
3835
                       " WHERE id = %s ",
3836
                       (meter_id,))
3837
        if cursor.fetchone() is None:
3838
            cursor.close()
3839
            cnx.close()
3840
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3841
                                   description='API.METER_NOT_FOUND')
3842
3843
        add_values = (" INSERT INTO tbl_microgrids_photovoltaics "
3844
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_power) "
3845
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3846
        cursor.execute(add_values, (name,
3847
                                    str(uuid.uuid4()),
3848
                                    id_,
3849
                                    power_point_id,
3850
                                    meter_id,
3851
                                    rated_power))
3852
        new_id = cursor.lastrowid
3853
        cnx.commit()
3854
        cursor.close()
3855
        cnx.close()
3856
3857
        resp.status = falcon.HTTP_201
3858
        resp.location = '/microgrids' + str(id_) + '/photovoltaics/' + str(new_id)
3859
3860
3861
class MicrogridPhotovoltaicItem:
3862
    def __init__(self):
3863
        pass
3864
3865
    @staticmethod
3866
    def on_options(req, resp, id_, pid):
3867
        _ = req
3868
        resp.status = falcon.HTTP_200
3869
        _ = id_
3870
3871
    @staticmethod
3872
    def on_get(req, resp, id_, pid):
3873
        access_control(req)
3874
        if not id_.isdigit() or int(id_) <= 0:
3875
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3876
                                   description='API.INVALID_MICROGRID_ID')
3877
        if not pid.isdigit() or int(pid) <= 0:
3878
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3879
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
3880
3881
        cnx = mysql.connector.connect(**config.myems_system_db)
3882
        cursor = cnx.cursor()
3883
3884
        cursor.execute(" SELECT name "
3885
                       " FROM tbl_microgrids "
3886
                       " WHERE id = %s ", (id_,))
3887
        if cursor.fetchone() is None:
3888
            cursor.close()
3889
            cnx.close()
3890
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3891
                                   description='API.MICROGRID_NOT_FOUND')
3892
3893
        # query microgrid dict
3894
        query = (" SELECT id, name, uuid "
3895
                 " FROM tbl_microgrids ")
3896
        cursor.execute(query)
3897
        rows_microgrids = cursor.fetchall()
3898
3899
        microgrid_dict = dict()
3900
        if rows_microgrids is not None and len(rows_microgrids) > 0:
3901
            for row in rows_microgrids:
3902
                microgrid_dict[row[0]] = {"id": row[0],
3903
                                          "name": row[1],
3904
                                          "uuid": row[2]}
3905
        # query meter dict
3906
        query = (" SELECT id, name, uuid "
3907
                 " FROM tbl_meters ")
3908
        cursor.execute(query)
3909
        rows_meters = cursor.fetchall()
3910
3911
        meter_dict = dict()
3912
        if rows_meters is not None and len(rows_meters) > 0:
3913
            for row in rows_meters:
3914
                meter_dict[row[0]] = {"id": row[0],
3915
                                      "name": row[1],
3916
                                      "uuid": row[2]}
3917
        # query point dict
3918
        query = (" SELECT id, name "
3919
                 " FROM tbl_points ")
3920
        cursor.execute(query)
3921
        rows_points = cursor.fetchall()
3922
3923
        point_dict = dict()
3924
        if rows_points is not None and len(rows_points) > 0:
3925
            for row in rows_points:
3926
                point_dict[row[0]] = {"id": row[0],
3927
                                      "name": row[1]}
3928
3929
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_power "
3930
                 " FROM tbl_microgrids_photovoltaics "
3931
                 " WHERE id = %s ")
3932
        cursor.execute(query, (pid,))
3933
        row = cursor.fetchone()
3934
        cursor.close()
3935
        cnx.close()
3936
3937
        if row is None:
3938
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3939
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
3940
        else:
3941
            meta_result = {"id": row[0],
3942
                           "name": row[1],
3943
                           "uuid": row[2],
3944
                           "microgrid": microgrid_dict.get(row[3], None),
3945
                           "power_point": point_dict.get(row[4], None),
3946
                           "meter": meter_dict.get(row[5], None),
3947
                           "rated_power": row[6]}
3948
3949
        resp.text = json.dumps(meta_result)
3950
3951
    @staticmethod
3952
    @user_logger
3953
    def on_delete(req, resp, id_, pid):
3954
        admin_control(req)
3955
        if not id_.isdigit() or int(id_) <= 0:
3956
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3957
                                   description='API.INVALID_MICROGRID_ID')
3958
        if not pid.isdigit() or int(pid) <= 0:
3959
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3960
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
3961
3962
        cnx = mysql.connector.connect(**config.myems_system_db)
3963
        cursor = cnx.cursor()
3964
3965
        cursor.execute(" SELECT name "
3966
                       " FROM tbl_microgrids "
3967
                       " WHERE id = %s ", (id_,))
3968
        if cursor.fetchone() is None:
3969
            cursor.close()
3970
            cnx.close()
3971
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3972
                                   description='API.MICROGRID_NOT_FOUND')
3973
3974
        cursor.execute(" SELECT name "
3975
                       " FROM tbl_microgrids_photovoltaics "
3976
                       " WHERE id = %s ", (pid,))
3977
        if cursor.fetchone() is None:
3978
            cursor.close()
3979
            cnx.close()
3980
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3981
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
3982
3983
        cursor.execute(" DELETE FROM tbl_microgrids_photovoltaics "
3984
                       " WHERE id = %s ", (pid,))
3985
        cnx.commit()
3986
3987
        cursor.close()
3988
        cnx.close()
3989
3990
        resp.status = falcon.HTTP_204
3991
3992
    @staticmethod
3993
    @user_logger
3994
    def on_put(req, resp, id_, pid):
3995
        """Handles PUT requests"""
3996
        admin_control(req)
3997
        try:
3998
            raw_json = req.stream.read().decode('utf-8')
3999
        except Exception as ex:
4000
            print(str(ex))
4001
            raise falcon.HTTPError(status=falcon.HTTP_400,
4002
                                   title='API.BAD_REQUEST',
4003
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4004
        if not id_.isdigit() or int(id_) <= 0:
4005
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4006
                                   description='API.INVALID_MICROGRID_ID')
4007
        if not pid.isdigit() or int(pid) <= 0:
4008
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4009
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
4010
4011
        new_values = json.loads(raw_json)
4012
4013
        if 'name' not in new_values['data'].keys() or \
4014
                not isinstance(new_values['data']['name'], str) or \
4015
                len(str.strip(new_values['data']['name'])) == 0:
4016
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4017
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_NAME')
4018
        name = str.strip(new_values['data']['name'])
4019
4020
        if 'power_point_id' not in new_values['data'].keys() or \
4021
                not isinstance(new_values['data']['power_point_id'], int) or \
4022
                new_values['data']['power_point_id'] <= 0:
4023
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4024
                                   description='API.INVALID_POWER_POINT_ID')
4025
        power_point_id = new_values['data']['power_point_id']
4026
4027
        if 'meter_id' not in new_values['data'].keys() or \
4028
                not isinstance(new_values['data']['meter_id'], int) or \
4029
                new_values['data']['meter_id'] <= 0:
4030
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4031
                                   description='API.INVALID_METER_ID')
4032
        meter_id = new_values['data']['meter_id']
4033
4034
        if 'rated_power' not in new_values['data'].keys() or \
4035
                not (isinstance(new_values['data']['rated_power'], float) or
4036
                     isinstance(new_values['data']['rated_power'], int)):
4037
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4038
                                   description='API.INVALID_RATED_POWER')
4039
        rated_power = float(new_values['data']['rated_power'])
4040
4041
        cnx = mysql.connector.connect(**config.myems_system_db)
4042
        cursor = cnx.cursor()
4043
4044
        cursor.execute(" SELECT name "
4045
                       " FROM tbl_microgrids "
4046
                       " WHERE id = %s ", (id_,))
4047
        if cursor.fetchone() is None:
4048
            cursor.close()
4049
            cnx.close()
4050
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4051
                                   description='API.MICROGRID_NOT_FOUND')
4052
4053
        cursor.execute(" SELECT name "
4054
                       " FROM tbl_microgrids_photovoltaics "
4055
                       " WHERE id = %s ", (pid,))
4056
        if cursor.fetchone() is None:
4057
            cursor.close()
4058
            cnx.close()
4059
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4060
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
4061
4062
        cursor.execute(" SELECT name "
4063
                       " FROM tbl_microgrids_photovoltaics "
4064
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
4065
                       (id_, name, pid))
4066
        if cursor.fetchone() is not None:
4067
            cursor.close()
4068
            cnx.close()
4069
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4070
                                   description='API.MICROGRID_PHOTOVOLTAIC_NAME_IS_ALREADY_IN_USE')
4071
4072
        cursor.execute(" SELECT name "
4073
                       " FROM tbl_points "
4074
                       " WHERE id = %s ",
4075
                       (power_point_id,))
4076
        if cursor.fetchone() is None:
4077
            cursor.close()
4078
            cnx.close()
4079
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4080
                                   description='API.POWER_POINT_NOT_FOUND')
4081
4082
        cursor.execute(" SELECT name "
4083
                       " FROM tbl_meters "
4084
                       " WHERE id = %s ",
4085
                       (meter_id,))
4086
        if cursor.fetchone() is None:
4087
            cursor.close()
4088
            cnx.close()
4089
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4090
                                   description='API.METER_NOT_FOUND')
4091
4092
        update_row = (" UPDATE tbl_microgrids_photovoltaics "
4093
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_power = %s "
4094
                      " WHERE id = %s ")
4095
        cursor.execute(update_row, (name,
4096
                                    id_,
4097
                                    power_point_id,
4098
                                    meter_id,
4099
                                    rated_power,
4100
                                    pid))
4101
        cnx.commit()
4102
4103
        cursor.close()
4104
        cnx.close()
4105
4106
        resp.status = falcon.HTTP_200
4107
4108
4109
class MicrogridPowerconversionsystemCollection:
4110
    def __init__(self):
4111
        pass
4112
4113
    @staticmethod
4114
    def on_options(req, resp, id_):
4115
        _ = req
4116
        resp.status = falcon.HTTP_200
4117
        _ = id_
4118
4119
    @staticmethod
4120
    def on_get(req, resp, id_):
4121
        access_control(req)
4122
        if not id_.isdigit() or int(id_) <= 0:
4123
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4124
                                   description='API.INVALID_MICROGRID_ID')
4125
4126
        cnx = mysql.connector.connect(**config.myems_system_db)
4127
        cursor = cnx.cursor()
4128
4129
        cursor.execute(" SELECT name "
4130
                       " FROM tbl_microgrids "
4131
                       " WHERE id = %s ", (id_,))
4132
        if cursor.fetchone() is None:
4133
            cursor.close()
4134
            cnx.close()
4135
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4136
                                   description='API.MICROGRID_NOT_FOUND')
4137
4138
        # query point dict
4139
        query = (" SELECT id, name "
4140
                 " FROM tbl_points ")
4141
        cursor.execute(query)
4142
        rows_points = cursor.fetchall()
4143
4144
        point_dict = dict()
4145
        if rows_points is not None and len(rows_points) > 0:
4146
            for row in rows_points:
4147
                point_dict[row[0]] = {"id": row[0],
4148
                                      "name": row[1]}
4149
        # query command dict
4150
        query = (" SELECT id, name "
4151
                 " FROM tbl_commands ")
4152
        cursor.execute(query)
4153
        rows_commands = cursor.fetchall()
4154
4155
        command_dict = dict()
4156
        if rows_commands is not None and len(rows_commands) > 0:
4157
            for row in rows_commands:
4158
                command_dict[row[0]] = {"id": row[0],
4159
                                        "name": row[1]}
4160
4161
        query = (" SELECT id, name, uuid, run_state_point_id, rated_output_power, "
4162
                 "        today_charge_energy_point_id, today_discharge_energy_point_id, "
4163
                 "        total_charge_energy_point_id, total_discharge_energy_point_id "
4164
                 " FROM tbl_microgrids_power_conversion_systems "
4165
                 " WHERE microgrid_id = %s "
4166
                 " ORDER BY name ")
4167
        cursor.execute(query, (id_,))
4168
        rows = cursor.fetchall()
4169
4170
        result = list()
4171
        if rows is not None and len(rows) > 0:
4172
            for row in rows:
4173
                meta_result = {"id": row[0],
4174
                               "name": row[1],
4175
                               "uuid": row[2],
4176
                               "run_state_point": point_dict.get(row[3]),
4177
                               "rated_output_power": row[4],
4178
                               "today_charge_energy_point": point_dict.get(row[5]),
4179
                               "today_discharge_energy_point": point_dict.get(row[6]),
4180
                               "total_charge_energy_point": point_dict.get(row[7]),
4181
                               "total_discharge_energy_point": point_dict.get(row[8])}
4182
                result.append(meta_result)
4183
4184
        resp.text = json.dumps(result)
4185
4186
    @staticmethod
4187
    @user_logger
4188
    def on_post(req, resp, id_):
4189
        """Handles POST requests"""
4190
        admin_control(req)
4191
        try:
4192
            raw_json = req.stream.read().decode('utf-8')
4193
        except Exception as ex:
4194
            print(str(ex))
4195
            raise falcon.HTTPError(status=falcon.HTTP_400,
4196
                                   title='API.BAD_REQUEST',
4197
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4198
        if not id_.isdigit() or int(id_) <= 0:
4199
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4200
                                   description='API.INVALID_MICROGRID_ID')
4201
4202
        cnx = mysql.connector.connect(**config.myems_system_db)
4203
        cursor = cnx.cursor()
4204
4205
        cursor.execute(" SELECT name "
4206
                       " FROM tbl_microgrids "
4207
                       " WHERE id = %s ", (id_,))
4208
        if cursor.fetchone() is None:
4209
            cursor.close()
4210
            cnx.close()
4211
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4212
                                   description='API.MICROGRID_NOT_FOUND')
4213
4214
        new_values = json.loads(raw_json)
4215
4216
        if 'name' not in new_values['data'].keys() or \
4217
                not isinstance(new_values['data']['name'], str) or \
4218
                len(str.strip(new_values['data']['name'])) == 0:
4219
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4220
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_NAME')
4221
        name = str.strip(new_values['data']['name'])
4222
4223
        if 'run_state_point_id' not in new_values['data'].keys() or \
4224
                not isinstance(new_values['data']['run_state_point_id'], int) or \
4225
                new_values['data']['run_state_point_id'] <= 0:
4226
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4227
                                   description='API.INVALID_RUN_STATE_POINT_ID')
4228
        run_state_point_id = new_values['data']['run_state_point_id']
4229
4230
        if 'rated_output_power' not in new_values['data'].keys() or \
4231
                not (isinstance(new_values['data']['rated_output_power'], float) or
4232
                     isinstance(new_values['data']['rated_output_power'], int)):
4233
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4234
                                   description='API.INVALID_RATED_OUTPUT_POWER')
4235
        rated_output_power = float(new_values['data']['rated_output_power'])
4236
4237
        if 'today_charge_energy_point_id' not in new_values['data'].keys() or \
4238
                not isinstance(new_values['data']['today_charge_energy_point_id'], int) or \
4239
                new_values['data']['today_charge_energy_point_id'] <= 0:
4240
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4241
                                   description='API.INVALID_TODAY_CHARGE_ENERGY_POINT_ID')
4242
        today_charge_energy_point_id = new_values['data']['today_charge_energy_point_id']
4243
4244
        if 'today_discharge_energy_point_id' not in new_values['data'].keys() or \
4245
                not isinstance(new_values['data']['today_discharge_energy_point_id'], int) or \
4246
                new_values['data']['today_discharge_energy_point_id'] <= 0:
4247
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4248
                                   description='API.INVALID_TODAY_DISCHARGE_ENERGY_POINT_ID')
4249
        today_discharge_energy_point_id = new_values['data']['today_discharge_energy_point_id']
4250
4251
        if 'total_charge_energy_point_id' not in new_values['data'].keys() or \
4252
                not isinstance(new_values['data']['total_charge_energy_point_id'], int) or \
4253
                new_values['data']['total_charge_energy_point_id'] <= 0:
4254
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4255
                                   description='API.INVALID_TOTAL_CHARGE_POINT_ID')
4256
        total_charge_energy_point_id = new_values['data']['total_charge_energy_point_id']
4257
4258
        if 'total_discharge_energy_point_id' not in new_values['data'].keys() or \
4259
                not isinstance(new_values['data']['total_discharge_energy_point_id'], int) or \
4260
                new_values['data']['total_discharge_energy_point_id'] <= 0:
4261
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4262
                                   description='API.INVALID_TOTAL_DISCHARGE_POINT_ID')
4263
        total_discharge_energy_point_id = new_values['data']['total_discharge_energy_point_id']
4264
4265
        cnx = mysql.connector.connect(**config.myems_system_db)
4266
        cursor = cnx.cursor()
4267
4268
        cursor.execute(" SELECT name "
4269
                       " FROM tbl_microgrids "
4270
                       " WHERE id = %s ",
4271
                       (id_,))
4272
        if cursor.fetchone() is None:
4273
            cursor.close()
4274
            cnx.close()
4275
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4276
                                   description='API.MICROGRID_NOT_FOUND')
4277
4278
        cursor.execute(" SELECT name "
4279
                       " FROM tbl_microgrids_power_conversion_systems "
4280
                       " WHERE microgrid_id = %s AND name = %s ",
4281
                       (id_, name,))
4282
        if cursor.fetchone() is not None:
4283
            cursor.close()
4284
            cnx.close()
4285
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4286
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NAME_IS_ALREADY_IN_USE')
4287
4288
        add_values = (" INSERT INTO tbl_microgrids_power_conversion_systems "
4289
                      "     (name, uuid, microgrid_id, run_state_point_id, rated_output_power, "
4290
                      "      today_charge_energy_point_id, today_discharge_energy_point_id, "
4291
                      "      total_charge_energy_point_id, total_discharge_energy_point_id) "
4292
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ")
4293
        cursor.execute(add_values, (name,
4294
                                    str(uuid.uuid4()),
4295
                                    id_,
4296
                                    run_state_point_id,
4297
                                    rated_output_power,
4298
                                    today_charge_energy_point_id,
4299
                                    today_discharge_energy_point_id,
4300
                                    total_charge_energy_point_id,
4301
                                    total_discharge_energy_point_id
4302
                                    ))
4303
        new_id = cursor.lastrowid
4304
        cnx.commit()
4305
        cursor.close()
4306
        cnx.close()
4307
4308
        resp.status = falcon.HTTP_201
4309
        resp.location = '/microgridpowerconversionsystems/' + str(new_id)
4310
4311
4312
class MicrogridPowerconversionsystemItem:
4313
    def __init__(self):
4314
        pass
4315
4316
    @staticmethod
4317
    def on_options(req, resp, id_, pid):
4318
        _ = req
4319
        resp.status = falcon.HTTP_200
4320
        _ = id_
4321
4322
    @staticmethod
4323
    def on_get(req, resp, id_, pid):
4324
        access_control(req)
4325
        if not id_.isdigit() or int(id_) <= 0:
4326
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4327
                                   description='API.INVALID_MICROGRID_ID')
4328
        if not pid.isdigit() or int(pid) <= 0:
4329
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4330
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_ID')
4331
4332
        cnx = mysql.connector.connect(**config.myems_system_db)
4333
        cursor = cnx.cursor()
4334
4335
        cursor.execute(" SELECT name "
4336
                       " FROM tbl_microgrids "
4337
                       " WHERE id = %s ", (id_,))
4338
        if cursor.fetchone() is None:
4339
            cursor.close()
4340
            cnx.close()
4341
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4342
                                   description='API.MICROGRID_NOT_FOUND')
4343
4344
        # query microgrid dict
4345
        query = (" SELECT id, name, uuid "
4346
                 " FROM tbl_microgrids ")
4347
        cursor.execute(query)
4348
        rows_microgrids = cursor.fetchall()
4349
4350
        microgrid_dict = dict()
4351
        if rows_microgrids is not None and len(rows_microgrids) > 0:
4352
            for row in rows_microgrids:
4353
                microgrid_dict[row[0]] = {"id": row[0],
4354
                                          "name": row[1],
4355
                                          "uuid": row[2]}
4356
        # query meter dict
4357
        query = (" SELECT id, name, uuid "
4358
                 " FROM tbl_meters ")
4359
        cursor.execute(query)
4360
        rows_meters = cursor.fetchall()
4361
4362
        meter_dict = dict()
4363
        if rows_meters is not None and len(rows_meters) > 0:
4364
            for row in rows_meters:
4365
                meter_dict[row[0]] = {"id": row[0],
4366
                                      "name": row[1],
4367
                                      "uuid": row[2]}
4368
        # query point dict
4369
        query = (" SELECT id, name "
4370
                 " FROM tbl_points ")
4371
        cursor.execute(query)
4372
        rows_points = cursor.fetchall()
4373
4374
        point_dict = dict()
4375
        if rows_points is not None and len(rows_points) > 0:
4376
            for row in rows_points:
4377
                point_dict[row[0]] = {"id": row[0],
4378
                                      "name": row[1]}
4379
4380
        # query command dict
4381
        query = (" SELECT id, name "
4382
                 " FROM tbl_commands ")
4383
        cursor.execute(query)
4384
        rows_commands = cursor.fetchall()
4385
4386
        command_dict = dict()
4387
        if rows_commands is not None and len(rows_commands) > 0:
4388
            for row in rows_commands:
4389
                command_dict[row[0]] = {"id": row[0],
4390
                                        "name": row[1]}
4391
4392
        query = (" SELECT id, name, uuid, microgrid_id, run_state_point_id, rated_output_power, "
4393
                 "        today_charge_energy_point_id, today_discharge_energy_point_id, "
4394
                 "        total_charge_energy_point_id, total_discharge_energy_point_id "
4395
                 " FROM tbl_microgrids_power_conversion_systems "
4396
                 " WHERE id = %s ")
4397
        cursor.execute(query, (pid,))
4398
        row = cursor.fetchone()
4399
        cursor.close()
4400
        cnx.close()
4401
4402
        if row is None:
4403
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4404
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
4405
        else:
4406
            meta_result = {"id": row[0],
4407
                           "name": row[1],
4408
                           "uuid": row[2],
4409
                           "microgrid": microgrid_dict.get(row[3]),
4410
                           "run_state_point": point_dict.get(row[4]),
4411
                           "rated_output_power": row[5],
4412
                           "today_charge_energy_point": point_dict.get(row[6]),
4413
                           "today_discharge_energy_point": point_dict.get(row[7]),
4414
                           "total_charge_energy_point": point_dict.get(row[8]),
4415
                           "total_discharge_energy_point": point_dict.get(row[9])}
4416
4417
        resp.text = json.dumps(meta_result)
4418
4419
    @staticmethod
4420
    @user_logger
4421
    def on_delete(req, resp, id_, pid):
4422
        admin_control(req)
4423
        if not id_.isdigit() or int(id_) <= 0:
4424
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4425
                                   description='API.INVALID_MICROGRID_ID')
4426
        if not pid.isdigit() or int(pid) <= 0:
4427
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4428
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_ID')
4429
4430
        cnx = mysql.connector.connect(**config.myems_system_db)
4431
        cursor = cnx.cursor()
4432
4433
        cursor.execute(" SELECT name "
4434
                       " FROM tbl_microgrids "
4435
                       " WHERE id = %s ", (id_,))
4436
        if cursor.fetchone() is None:
4437
            cursor.close()
4438
            cnx.close()
4439
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4440
                                   description='API.MICROGRID_NOT_FOUND')
4441
4442
        cursor.execute(" SELECT name "
4443
                       " FROM tbl_microgrids_power_conversion_systems "
4444
                       " WHERE id = %s ", (pid,))
4445
        if cursor.fetchone() is None:
4446
            cursor.close()
4447
            cnx.close()
4448
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4449
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
4450
4451
        cursor.execute(" DELETE FROM tbl_microgrids_power_conversion_systems "
4452
                       " WHERE id = %s ", (pid,))
4453
        cnx.commit()
4454
4455
        cursor.close()
4456
        cnx.close()
4457
4458
        resp.status = falcon.HTTP_204
4459
4460
    @staticmethod
4461
    @user_logger
4462
    def on_put(req, resp, id_, pid):
4463
        """Handles PUT requests"""
4464
        admin_control(req)
4465
        try:
4466
            raw_json = req.stream.read().decode('utf-8')
4467
        except Exception as ex:
4468
            print(str(ex))
4469
            raise falcon.HTTPError(status=falcon.HTTP_400,
4470
                                   title='API.BAD_REQUEST',
4471
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4472
        if not id_.isdigit() or int(id_) <= 0:
4473
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4474
                                   description='API.INVALID_MICROGRID_ID')
4475
        if not pid.isdigit() or int(pid) <= 0:
4476
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4477
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_ID')
4478
4479
        new_values = json.loads(raw_json)
4480
4481
        if 'name' not in new_values['data'].keys() or \
4482
                not isinstance(new_values['data']['name'], str) or \
4483
                len(str.strip(new_values['data']['name'])) == 0:
4484
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4485
                                   description='API.INVALID_MICROGRID_POWER_CONVERSION_SYSTEM_NAME')
4486
        name = str.strip(new_values['data']['name'])
4487
4488
        if 'run_state_point_id' not in new_values['data'].keys() or \
4489
                not isinstance(new_values['data']['run_state_point_id'], int) or \
4490
                new_values['data']['run_state_point_id'] <= 0:
4491
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4492
                                   description='API.INVALID_RUN_STATE_POINT_ID')
4493
        run_state_point_id = new_values['data']['run_state_point_id']
4494
4495
        if 'rated_output_power' not in new_values['data'].keys() or \
4496
                not (isinstance(new_values['data']['rated_output_power'], float) or
4497
                     isinstance(new_values['data']['rated_output_power'], int)):
4498
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4499
                                   description='API.INVALID_RATED_OUTPUT_POWER')
4500
        rated_output_power = float(new_values['data']['rated_output_power'])
4501
4502
        if 'today_charge_energy_point_id' not in new_values['data'].keys() or \
4503
                not isinstance(new_values['data']['today_charge_energy_point_id'], int) or \
4504
                new_values['data']['today_charge_energy_point_id'] <= 0:
4505
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4506
                                   description='API.INVALID_TODAY_CHARGE_ENERGY_POINT_ID')
4507
        today_charge_energy_point_id = new_values['data']['today_charge_energy_point_id']
4508
4509
        if 'today_discharge_energy_point_id' not in new_values['data'].keys() or \
4510
                not isinstance(new_values['data']['today_discharge_energy_point_id'], int) or \
4511
                new_values['data']['today_discharge_energy_point_id'] <= 0:
4512
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4513
                                   description='API.INVALID_TODAY_DISCHARGE_ENERGY_POINT_ID')
4514
        today_discharge_energy_point_id = new_values['data']['today_discharge_energy_point_id']
4515
4516
        if 'total_charge_energy_point_id' not in new_values['data'].keys() or \
4517
                not isinstance(new_values['data']['total_charge_energy_point_id'], int) or \
4518
                new_values['data']['total_charge_energy_point_id'] <= 0:
4519
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4520
                                   description='API.INVALID_TOTAL_CHARGE_POINT_ID')
4521
        total_charge_energy_point_id = new_values['data']['total_charge_energy_point_id']
4522
4523
        if 'total_discharge_energy_point_id' not in new_values['data'].keys() or \
4524
                not isinstance(new_values['data']['total_discharge_energy_point_id'], int) or \
4525
                new_values['data']['total_discharge_energy_point_id'] <= 0:
4526
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4527
                                   description='API.INVALID_TOTAL_DISCHARGE_POINT_ID')
4528
        total_discharge_energy_point_id = new_values['data']['total_discharge_energy_point_id']
4529
4530
        cnx = mysql.connector.connect(**config.myems_system_db)
4531
        cursor = cnx.cursor()
4532
4533
        cursor.execute(" SELECT name "
4534
                       " FROM tbl_microgrids "
4535
                       " WHERE id = %s ", (id_,))
4536
        if cursor.fetchone() is None:
4537
            cursor.close()
4538
            cnx.close()
4539
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4540
                                   description='API.MICROGRID_NOT_FOUND')
4541
4542
        cursor.execute(" SELECT name "
4543
                       " FROM tbl_microgrids_power_conversion_systems "
4544
                       " WHERE id = %s ", (pid,))
4545
        if cursor.fetchone() is None:
4546
            cursor.close()
4547
            cnx.close()
4548
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4549
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
4550
4551
        cursor.execute(" SELECT name "
4552
                       " FROM tbl_microgrids_power_conversion_systems "
4553
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
4554
                       (id_, name, pid))
4555
        if cursor.fetchone() is not None:
4556
            cursor.close()
4557
            cnx.close()
4558
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4559
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NAME_IS_ALREADY_IN_USE')
4560
4561
        update_row = (" UPDATE tbl_microgrids_power_conversion_systems "
4562
                      " SET name = %s, microgrid_id = %s, run_state_point_id = %s, rated_output_power = %s, "
4563
                      "     today_charge_energy_point_id = %s, today_discharge_energy_point_id = %s, "
4564
                      "     total_charge_energy_point_id = %s, total_discharge_energy_point_id = %s "
4565
                      " WHERE id = %s ")
4566
        cursor.execute(update_row, (name,
4567
                                    id_,
4568
                                    run_state_point_id,
4569
                                    rated_output_power,
4570
                                    today_charge_energy_point_id,
4571
                                    today_discharge_energy_point_id,
4572
                                    total_charge_energy_point_id,
4573
                                    total_discharge_energy_point_id,
4574
                                    pid))
4575
        cnx.commit()
4576
4577
        cursor.close()
4578
        cnx.close()
4579
4580
        resp.status = falcon.HTTP_200
4581
4582
4583 View Code Duplication
class MicrogridScheduleCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4584
    def __init__(self):
4585
        pass
4586
4587
    @staticmethod
4588
    def on_options(req, resp, id_):
4589
        _ = req
4590
        resp.status = falcon.HTTP_200
4591
        _ = id_
4592
4593
    @staticmethod
4594
    def on_get(req, resp, id_):
4595
        access_control(req)
4596
        if not id_.isdigit() or int(id_) <= 0:
4597
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4598
                                   description='API.INVALID_MICROGRID_ID')
4599
4600
        cnx = mysql.connector.connect(**config.myems_system_db)
4601
        cursor = cnx.cursor()
4602
4603
        cursor.execute(" SELECT name "
4604
                       " FROM tbl_microgrids "
4605
                       " WHERE id = %s ", (id_,))
4606
        if cursor.fetchone() is None:
4607
            cursor.close()
4608
            cnx.close()
4609
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4610
                                   description='API.MICROGRID_NOT_FOUND')
4611
4612
        query = (" SELECT id, start_time_of_day, end_time_of_day, peak_type, power "
4613
                 " FROM tbl_microgrids_schedules "
4614
                 " WHERE microgrid_id = %s "
4615
                 " ORDER BY start_time_of_day ")
4616
        cursor.execute(query, (id_,))
4617
        rows = cursor.fetchall()
4618
4619
        result = list()
4620
        if rows is not None and len(rows) > 0:
4621
            for row in rows:
4622
                meta_result = {"id": row[0],
4623
                               "start_time_of_day": str(row[1]),
4624
                               "end_time_of_day": str(row[2]),
4625
                               "peak_type": row[3],
4626
                               "power": row[4],
4627
                               }
4628
                result.append(meta_result)
4629
4630
        resp.text = json.dumps(result)
4631
4632
    @staticmethod
4633
    @user_logger
4634
    def on_post(req, resp, id_):
4635
        """Handles POST requests"""
4636
        admin_control(req)
4637
        try:
4638
            raw_json = req.stream.read().decode('utf-8')
4639
        except Exception as ex:
4640
            print(str(ex))
4641
            raise falcon.HTTPError(status=falcon.HTTP_400,
4642
                                   title='API.BAD_REQUEST',
4643
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4644
        if not id_.isdigit() or int(id_) <= 0:
4645
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4646
                                   description='API.INVALID_MICROGRID_ID')
4647
4648
        cnx = mysql.connector.connect(**config.myems_system_db)
4649
        cursor = cnx.cursor()
4650
4651
        cursor.execute(" SELECT name "
4652
                       " FROM tbl_microgrids "
4653
                       " WHERE id = %s ", (id_,))
4654
        if cursor.fetchone() is None:
4655
            cursor.close()
4656
            cnx.close()
4657
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4658
                                   description='API.MICROGRID_NOT_FOUND')
4659
4660
        new_values = json.loads(raw_json)
4661
4662
        cnx = mysql.connector.connect(**config.myems_system_db)
4663
        cursor = cnx.cursor()
4664
4665
        cursor.execute(" SELECT name "
4666
                       " FROM tbl_microgrids "
4667
                       " WHERE id = %s ",
4668
                       (id_,))
4669
        if cursor.fetchone() is None:
4670
            cursor.close()
4671
            cnx.close()
4672
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4673
                                   description='API.MICROGRID_NOT_FOUND')
4674
4675
        add_schedule = (" INSERT INTO tbl_microgrids_schedules "
4676
                        "     (microgrid_id, start_time_of_day, end_time_of_day, peak_type, power) "
4677
                        " VALUES (%s, %s, %s, %s, %s) ")
4678
        cursor.execute(add_schedule, (id_,
4679
                                      new_values['data']['start_time_of_day'],
4680
                                      new_values['data']['end_time_of_day'],
4681
                                      new_values['data']['peak_type'],
4682
                                      new_values['data']['power']))
4683
        new_id = cursor.lastrowid
4684
        cnx.commit()
4685
        cursor.close()
4686
        cnx.close()
4687
        resp.status = falcon.HTTP_201
4688
        resp.location = '/energystoragecontainerschedules/' + str(new_id)
4689
4690
4691 View Code Duplication
class MicrogridScheduleItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4692
    def __init__(self):
4693
        pass
4694
4695
    @staticmethod
4696
    def on_options(req, resp, id_, sid):
4697
        _ = req
4698
        resp.status = falcon.HTTP_200
4699
        _ = id_
4700
4701
    @staticmethod
4702
    def on_get(req, resp, id_, sid):
4703
        access_control(req)
4704
        if not id_.isdigit() or int(id_) <= 0:
4705
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4706
                                   description='API.INVALID_MICROGRID_ID')
4707
        if not sid.isdigit() or int(sid) <= 0:
4708
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4709
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4710
4711
        cnx = mysql.connector.connect(**config.myems_system_db)
4712
        cursor = cnx.cursor()
4713
4714
        cursor.execute(" SELECT name "
4715
                       " FROM tbl_microgrids "
4716
                       " WHERE id = %s ", (id_,))
4717
        if cursor.fetchone() is None:
4718
            cursor.close()
4719
            cnx.close()
4720
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4721
                                   description='API.MICROGRID_NOT_FOUND')
4722
4723
        query = (" SELECT id, name, uuid "
4724
                 " FROM tbl_microgrids ")
4725
        cursor.execute(query)
4726
        rows_energystoragecontainers = cursor.fetchall()
4727
4728
        microgrid_dict = dict()
4729
        if rows_energystoragecontainers is not None and len(rows_energystoragecontainers) > 0:
4730
            for row in rows_energystoragecontainers:
4731
                microgrid_dict[row[0]] = {"id": row[0],
4732
                                          "name": row[1],
4733
                                          "uuid": row[2]}
4734
4735
        query = (" SELECT id, start_time_of_day, end_time_of_day, peak_type, power "
4736
                 " FROM tbl_microgrids_schedules "
4737
                 " WHERE id = %s ")
4738
        cursor.execute(query, (sid,))
4739
        row = cursor.fetchone()
4740
        cursor.close()
4741
        cnx.close()
4742
4743
        if row is None:
4744
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4745
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4746
        else:
4747
            meta_result = {"id": row[0],
4748
                           "start_time_of_day": str(row[1]),
4749
                           "end_time_of_day": str(row[2]),
4750
                           "peak_type": row[3],
4751
                           "power": row[4]}
4752
4753
        resp.text = json.dumps(meta_result)
4754
4755
    @staticmethod
4756
    @user_logger
4757
    def on_delete(req, resp, id_, sid):
4758
        admin_control(req)
4759
        if not id_.isdigit() or int(id_) <= 0:
4760
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4761
                                   description='API.INVALID_MICROGRID_ID')
4762
        if not sid.isdigit() or int(sid) <= 0:
4763
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4764
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4765
4766
        cnx = mysql.connector.connect(**config.myems_system_db)
4767
        cursor = cnx.cursor()
4768
4769
        cursor.execute(" SELECT name "
4770
                       " FROM tbl_microgrids "
4771
                       " WHERE id = %s ", (id_,))
4772
        if cursor.fetchone() is None:
4773
            cursor.close()
4774
            cnx.close()
4775
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4776
                                   description='API.MICROGRID_NOT_FOUND')
4777
4778
        cursor.execute(" SELECT id "
4779
                       " FROM tbl_microgrids_schedules "
4780
                       " WHERE id = %s ", (sid,))
4781
        if cursor.fetchone() is None:
4782
            cursor.close()
4783
            cnx.close()
4784
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4785
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4786
4787
        cursor.execute(" DELETE FROM tbl_microgrids_schedules "
4788
                       " WHERE id = %s ", (sid,))
4789
        cnx.commit()
4790
4791
        cursor.close()
4792
        cnx.close()
4793
4794
        resp.status = falcon.HTTP_204
4795
4796
    @staticmethod
4797
    @user_logger
4798
    def on_put(req, resp, id_, sid):
4799
        """Handles PUT requests"""
4800
        admin_control(req)
4801
        try:
4802
            raw_json = req.stream.read().decode('utf-8')
4803
        except Exception as ex:
4804
            print(str(ex))
4805
            raise falcon.HTTPError(status=falcon.HTTP_400,
4806
                                   title='API.BAD_REQUEST',
4807
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4808
        if not id_.isdigit() or int(id_) <= 0:
4809
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4810
                                   description='API.INVALID_MICROGRID_ID')
4811
        if not sid.isdigit() or int(sid) <= 0:
4812
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4813
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4814
4815
        new_values = json.loads(raw_json)
4816
4817
        if 'start_time_of_day' not in new_values['data'].keys() or \
4818
                not isinstance(new_values['data']['start_time_of_day'], str) or \
4819
                len(str.strip(new_values['data']['start_time_of_day'])) == 0:
4820
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4821
                                   description='API.INVALID_START_TIME_OF_DAY')
4822
        start_time_of_day = str.strip(new_values['data']['start_time_of_day'])
4823
4824
        if 'end_time_of_day' not in new_values['data'].keys() or \
4825
                not isinstance(new_values['data']['end_time_of_day'], str) or \
4826
                len(str.strip(new_values['data']['end_time_of_day'])) == 0:
4827
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4828
                                   description='API.INVALID_END_TIME_OF_DAY')
4829
        end_time_of_day = str.strip(new_values['data']['end_time_of_day'])
4830
4831
        if 'peak_type' not in new_values['data'].keys() or \
4832
                not isinstance(new_values['data']['peak_type'], str) or \
4833
                len(str.strip(new_values['data']['peak_type'])) == 0:
4834
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4835
                                   description='API.INVALID_PEAK_TYPE')
4836
        peak_type = str.strip(new_values['data']['peak_type'])
4837
4838
        if 'power' not in new_values['data'].keys() or \
4839
                not (isinstance(new_values['data']['power'], float) or
4840
                     isinstance(new_values['data']['power'], int)):
4841
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4842
                                   description='API.INVALID_POWER')
4843
        power = float(new_values['data']['power'])
4844
4845
        cnx = mysql.connector.connect(**config.myems_system_db)
4846
        cursor = cnx.cursor()
4847
4848
        cursor.execute(" SELECT name "
4849
                       " FROM tbl_microgrids "
4850
                       " WHERE id = %s ", (id_,))
4851
        if cursor.fetchone() is None:
4852
            cursor.close()
4853
            cnx.close()
4854
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4855
                                   description='API.MICROGRID_NOT_FOUND')
4856
4857
        cursor.execute(" SELECT id "
4858
                       " FROM tbl_microgrids_schedules "
4859
                       " WHERE id = %s ", (sid,))
4860
        if cursor.fetchone() is None:
4861
            cursor.close()
4862
            cnx.close()
4863
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4864
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4865
4866
        update_row = (" UPDATE tbl_microgrids_schedules "
4867
                      " SET start_time_of_day = %s, end_time_of_day = %s, peak_type = %s, power = %s "
4868
                      " WHERE id = %s ")
4869
        cursor.execute(update_row, (start_time_of_day,
4870
                                    end_time_of_day,
4871
                                    peak_type,
4872
                                    power,
4873
                                    sid))
4874
        cnx.commit()
4875
4876
        cursor.close()
4877
        cnx.close()
4878
4879
        resp.status = falcon.HTTP_200
4880
4881
4882 View Code Duplication
class MicrogridSensorCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4883
    def __init__(self):
4884
        pass
4885
4886
    @staticmethod
4887
    def on_options(req, resp, id_):
4888
        _ = req
4889
        resp.status = falcon.HTTP_200
4890
        _ = id_
4891
4892
    @staticmethod
4893
    def on_get(req, resp, id_):
4894
        access_control(req)
4895
        if not id_.isdigit() or int(id_) <= 0:
4896
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4897
                                   description='API.INVALID_MICROGRID_ID')
4898
4899
        cnx = mysql.connector.connect(**config.myems_system_db)
4900
        cursor = cnx.cursor()
4901
4902
        cursor.execute(" SELECT name "
4903
                       " FROM tbl_microgrids "
4904
                       " WHERE id = %s ", (id_,))
4905
        if cursor.fetchone() is None:
4906
            cursor.close()
4907
            cnx.close()
4908
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4909
                                   description='API.MICROGRID_NOT_FOUND')
4910
4911
        query = (" SELECT s.id, s.name, s.uuid "
4912
                 " FROM tbl_microgrids m, tbl_microgrids_sensors ms, tbl_sensors s "
4913
                 " WHERE ms.microgrid_id = m.id AND s.id = ms.sensor_id AND m.id = %s "
4914
                 " ORDER BY s.id ")
4915
        cursor.execute(query, (id_,))
4916
        rows = cursor.fetchall()
4917
4918
        result = list()
4919
        if rows is not None and len(rows) > 0:
4920
            for row in rows:
4921
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
4922
                result.append(meta_result)
4923
4924
        resp.text = json.dumps(result)
4925
4926
    @staticmethod
4927
    @user_logger
4928
    def on_post(req, resp, id_):
4929
        """Handles POST requests"""
4930
        admin_control(req)
4931
        try:
4932
            raw_json = req.stream.read().decode('utf-8')
4933
        except Exception as ex:
4934
            print(str(ex))
4935
            raise falcon.HTTPError(status=falcon.HTTP_400,
4936
                                   title='API.BAD_REQUEST',
4937
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4938
4939
        if not id_.isdigit() or int(id_) <= 0:
4940
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4941
                                   description='API.INVALID_MICROGRID_ID')
4942
4943
        new_values = json.loads(raw_json)
4944
4945
        if 'sensor_id' not in new_values['data'].keys() or \
4946
                not isinstance(new_values['data']['sensor_id'], int) or \
4947
                new_values['data']['sensor_id'] <= 0:
4948
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4949
                                   description='API.INVALID_SENSOR_ID')
4950
        sensor_id = new_values['data']['sensor_id']
4951
4952
        cnx = mysql.connector.connect(**config.myems_system_db)
4953
        cursor = cnx.cursor()
4954
4955
        cursor.execute(" SELECT name "
4956
                       " from tbl_microgrids "
4957
                       " WHERE id = %s ", (id_,))
4958
        if cursor.fetchone() is None:
4959
            cursor.close()
4960
            cnx.close()
4961
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4962
                                   description='API.MICROGRID_NOT_FOUND')
4963
4964
        cursor.execute(" SELECT name "
4965
                       " FROM tbl_sensors "
4966
                       " WHERE id = %s ", (sensor_id,))
4967
        if cursor.fetchone() is None:
4968
            cursor.close()
4969
            cnx.close()
4970
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4971
                                   description='API.SENSOR_NOT_FOUND')
4972
4973
        query = (" SELECT id "
4974
                 " FROM tbl_microgrids_sensors "
4975
                 " WHERE microgrid_id = %s AND sensor_id = %s")
4976
        cursor.execute(query, (id_, sensor_id,))
4977
        if cursor.fetchone() is not None:
4978
            cursor.close()
4979
            cnx.close()
4980
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4981
                                   description='API.MICROGRID_SENSOR_RELATION_EXISTS')
4982
4983
        add_row = (" INSERT INTO tbl_microgrids_sensors (microgrid_id, sensor_id) "
4984
                   " VALUES (%s, %s) ")
4985
        cursor.execute(add_row, (id_, sensor_id,))
4986
        cnx.commit()
4987
        cursor.close()
4988
        cnx.close()
4989
4990
        resp.status = falcon.HTTP_201
4991
        resp.location = '/microgrids/' + str(id_) + '/sensors/' + str(sensor_id)
4992
4993
4994 View Code Duplication
class MicrogridSensorItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4995
    def __init__(self):
4996
        pass
4997
4998
    @staticmethod
4999
    def on_options(req, resp, id_, sid):
5000
        _ = req
5001
        resp.status = falcon.HTTP_200
5002
        _ = id_
5003
5004
    @staticmethod
5005
    @user_logger
5006
    def on_delete(req, resp, id_, sid):
5007
        admin_control(req)
5008
        if not id_.isdigit() or int(id_) <= 0:
5009
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5010
                                   description='API.INVALID_MICROGRID_ID')
5011
5012
        if not sid.isdigit() or int(sid) <= 0:
5013
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5014
                                   description='API.INVALID_SENSOR_ID')
5015
5016
        cnx = mysql.connector.connect(**config.myems_system_db)
5017
        cursor = cnx.cursor()
5018
5019
        cursor.execute(" SELECT name "
5020
                       " FROM tbl_microgrids "
5021
                       " WHERE id = %s ", (id_,))
5022
        if cursor.fetchone() is None:
5023
            cursor.close()
5024
            cnx.close()
5025
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5026
                                   description='API.MICROGRID_NOT_FOUND')
5027
5028
        cursor.execute(" SELECT name "
5029
                       " FROM tbl_sensors "
5030
                       " WHERE id = %s ", (sid,))
5031
        if cursor.fetchone() is None:
5032
            cursor.close()
5033
            cnx.close()
5034
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5035
                                   description='API.SENSOR_NOT_FOUND')
5036
5037
        cursor.execute(" SELECT id "
5038
                       " FROM tbl_microgrids_sensors "
5039
                       " WHERE microgrid_id = %s AND sensor_id = %s ", (id_, sid))
5040
        if cursor.fetchone() is None:
5041
            cursor.close()
5042
            cnx.close()
5043
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5044
                                   description='API.MICROGRID_SENSOR_RELATION_NOT_FOUND')
5045
5046
        cursor.execute(" DELETE FROM tbl_microgrids_sensors "
5047
                       " WHERE microgrid_id = %s AND sensor_id = %s ", (id_, sid))
5048
        cnx.commit()
5049
5050
        cursor.close()
5051
        cnx.close()
5052
5053
        resp.status = falcon.HTTP_204
5054
5055
5056 View Code Duplication
class MicrogridUserCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5057
    def __init__(self):
5058
        pass
5059
5060
    @staticmethod
5061
    def on_options(req, resp, id_):
5062
        _ = req
5063
        resp.status = falcon.HTTP_200
5064
        _ = id_
5065
5066
    @staticmethod
5067
    def on_get(req, resp, id_):
5068
        access_control(req)
5069
        if not id_.isdigit() or int(id_) <= 0:
5070
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5071
                                   description='API.INVALID_MICROGRID_ID')
5072
5073
        cnx = mysql.connector.connect(**config.myems_system_db)
5074
        cursor = cnx.cursor()
5075
        cursor.execute(" SELECT name "
5076
                       " FROM tbl_microgrids "
5077
                       " WHERE id = %s ", (id_,))
5078
        if cursor.fetchone() is None:
5079
            cursor.close()
5080
            cnx.close()
5081
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5082
                                   description='API.MICROGRID_NOT_FOUND')
5083
5084
        query = (" SELECT u.id, u.name, u.uuid "
5085
                 " FROM tbl_microgrids m, tbl_microgrids_users mu, "
5086
                 + config.myems_user_db['database'] + ".tbl_users u "
5087
                 " WHERE mu.microgrid_id = m.id AND u.id = mu.user_id AND m.id = %s "
5088
                 " ORDER BY u.id ")
5089
        cursor.execute(query, (id_,))
5090
        rows = cursor.fetchall()
5091
        result = list()
5092
        if rows is not None and len(rows) > 0:
5093
            for row in rows:
5094
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
5095
                result.append(meta_result)
5096
5097
        cursor.close()
5098
        cnx.close()
5099
        resp.text = json.dumps(result)
5100
5101
    @staticmethod
5102
    @user_logger
5103
    def on_post(req, resp, id_):
5104
        """Handles POST requests"""
5105
        admin_control(req)
5106
        try:
5107
            raw_json = req.stream.read().decode('utf-8')
5108
        except Exception as ex:
5109
            print(str(ex))
5110
            raise falcon.HTTPError(status=falcon.HTTP_400,
5111
                                   title='API.BAD_REQUEST',
5112
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5113
5114
        if not id_.isdigit() or int(id_) <= 0:
5115
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5116
                                   description='API.INVALID_MICROGRID_ID')
5117
5118
        new_values = json.loads(raw_json)
5119
        if 'user_id' not in new_values['data'].keys() or \
5120
                not isinstance(new_values['data']['user_id'], int) or \
5121
                new_values['data']['user_id'] <= 0:
5122
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5123
                                   description='API.INVALID_USER_ID')
5124
        user_id = new_values['data']['user_id']
5125
        cnx = mysql.connector.connect(**config.myems_system_db)
5126
        cursor = cnx.cursor()
5127
        cursor.execute(" SELECT name "
5128
                       " from tbl_microgrids "
5129
                       " WHERE id = %s ", (id_,))
5130
        if cursor.fetchone() is None:
5131
            cursor.close()
5132
            cnx.close()
5133
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5134
                                   description='API.MICROGRID_NOT_FOUND')
5135
5136
        cnx_user = mysql.connector.connect(**config.myems_user_db)
5137
        cursor_user = cnx_user.cursor()
5138
        cursor_user.execute(" SELECT name"
5139
                            " FROM tbl_users "
5140
                            " WHERE id = %s ", (user_id,))
5141
        if cursor_user.fetchone() is None:
5142
            cursor_user.close()
5143
            cnx_user.close()
5144
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5145
                                   description='API.USER_NOT_FOUND')
5146
        query = (" SELECT id "
5147
                 " FROM tbl_microgrids_users "
5148
                 " WHERE microgrid_id = %s AND user_id = %s")
5149
        cursor.execute(query, (id_, user_id,))
5150
        if cursor.fetchone() is not None:
5151
            cursor.close()
5152
            cnx.close()
5153
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5154
                                   description='API.MICROGRID_USER_RELATION_EXISTS')
5155
        add_row = (" INSERT INTO tbl_microgrids_users (microgrid_id, user_id) "
5156
                   " VALUES (%s, %s) ")
5157
        cursor.execute(add_row, (id_, user_id,))
5158
        cnx.commit()
5159
        cursor.close()
5160
        cnx.close()
5161
        cursor_user.close()
5162
        cnx_user.close()
5163
5164
        resp.status = falcon.HTTP_201
5165
        resp.location = '/microgrids/' + str(id_) + '/users/' + str(user_id)
5166
5167
5168 View Code Duplication
class MicrogridUserItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5169
    def __init__(self):
5170
        pass
5171
5172
    @staticmethod
5173
    def on_options(req, resp, id_, uid):
5174
        _ = req
5175
        resp.status = falcon.HTTP_200
5176
        _ = id_
5177
5178
    @staticmethod
5179
    @user_logger
5180
    def on_delete(req, resp, id_, uid):
5181
        # todo Verify if the user is bound when deleting it
5182
        admin_control(req)
5183
        if not id_.isdigit() or int(id_) <= 0:
5184
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5185
                                   description='API.INVALID_MICROGRID_ID')
5186
5187
        if not uid.isdigit() or int(uid) <= 0:
5188
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5189
                                   description='API.INVALID_USER_ID')
5190
5191
        cnx = mysql.connector.connect(**config.myems_system_db)
5192
        cursor = cnx.cursor()
5193
        cursor.execute(" SELECT name "
5194
                       " FROM tbl_microgrids "
5195
                       " WHERE id = %s ", (id_,))
5196
        if cursor.fetchone() is None:
5197
            cursor.close()
5198
            cnx.close()
5199
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5200
                                   description='API.MICROGRID_NOT_FOUND')
5201
5202
        cnx_user = mysql.connector.connect(**config.myems_user_db)
5203
        cursor_user = cnx_user.cursor()
5204
        cursor_user.execute(" SELECT name FROM tbl_users WHERE id = %s ", (uid,))
5205
        if cursor_user.fetchone() is None:
5206
            cursor_user.close()
5207
            cnx_user.close()
5208
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5209
                                   description='API.USER_NOT_FOUND')
5210
5211
        cursor.execute(" SELECT id "
5212
                       " FROM tbl_microgrids_users "
5213
                       " WHERE microgrid_id = %s AND user_id = %s ", (id_, uid))
5214
        if cursor.fetchone() is None:
5215
            cursor.close()
5216
            cnx.close()
5217
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5218
                                   description='API.MICROGRID_USER_RELATION_NOT_FOUND')
5219
5220
        cursor.execute(" DELETE FROM tbl_microgrids_users WHERE microgrid_id = %s AND user_id = %s ", (id_, uid))
5221
        cnx.commit()
5222
5223
        cursor.close()
5224
        cnx.close()
5225
        cursor_user.close()
5226
        cnx_user.close()
5227
5228
        resp.status = falcon.HTTP_204
5229
5230
5231
class MicrogridExport:
5232
    def __init__(self):
5233
        pass
5234
5235
    @staticmethod
5236
    def on_options(req, resp, id_):
5237
        _ = req
5238
        resp.status = falcon.HTTP_200
5239
        _ = id_
5240
5241
    @staticmethod
5242
    def on_get(req, resp, id_):
5243
        access_control(req)
5244
        if not id_.isdigit() or int(id_) <= 0:
5245
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5246
                                   description='API.INVALID_MICROGRID_ID')
5247
5248
        cnx = mysql.connector.connect(**config.myems_system_db)
5249
        cursor = cnx.cursor()
5250
5251
        query = (" SELECT id, name, uuid "
5252
                 " FROM tbl_contacts ")
5253
        cursor.execute(query)
5254
        rows_contacts = cursor.fetchall()
5255
5256
        contact_dict = dict()
5257
        if rows_contacts is not None and len(rows_contacts) > 0:
5258
            for row in rows_contacts:
5259
                contact_dict[row[0]] = {"id": row[0],
5260
                                        "name": row[1],
5261
                                        "uuid": row[2]}
5262
5263
        query = (" SELECT id, name, uuid "
5264
                 " FROM tbl_cost_centers ")
5265
        cursor.execute(query)
5266
        rows_cost_centers = cursor.fetchall()
5267
5268
        cost_center_dict = dict()
5269
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
5270
            for row in rows_cost_centers:
5271
                cost_center_dict[row[0]] = {"id": row[0],
5272
                                            "name": row[1],
5273
                                            "uuid": row[2]}
5274
5275
        query = (" SELECT id, name, uuid, "
5276
                 "        address, postal_code, latitude, longitude, rated_capacity, rated_power, "
5277
                 "        contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, phase_of_lifecycle, description "
5278
                 " FROM tbl_microgrids "
5279
                 " WHERE id = %s ")
5280
        cursor.execute(query, (id_,))
5281
        row = cursor.fetchone()
5282
        cursor.close()
5283
        cnx.close()
5284
5285
        if row is None:
5286
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5287
                                   description='API.MICROGRID_NOT_FOUND')
5288
        else:
5289
            meta_result = {"id": row[0],
5290
                           "name": row[1],
5291
                           "uuid": row[2],
5292
                           "address": row[3],
5293
                           "postal_code": row[4],
5294
                           "latitude": row[5],
5295
                           "longitude": row[6],
5296
                           "rated_capacity": row[7],
5297
                           "rated_power": row[8],
5298
                           "contact": contact_dict.get(row[9], None),
5299
                           "cost_center": cost_center_dict.get(row[10], None),
5300
                           "serial_number": row[11],
5301
                           "svg_id": row[12],
5302
                           "is_cost_data_displayed": bool(row[13]),
5303
                           "phase_of_lifecycle": row[14],
5304
                           "description": row[15]}
5305
5306
        resp.text = json.dumps(meta_result)
5307
5308
5309
class MicrogridImport:
5310
    def __init__(self):
5311
        pass
5312
5313
    @staticmethod
5314
    def on_options(req, resp):
5315
        _ = req
5316
        resp.status = falcon.HTTP_200
5317
5318
    @staticmethod
5319
    @user_logger
5320
    def on_post(req, resp):
5321
        """Handles POST requests"""
5322
        admin_control(req)
5323
        try:
5324
            raw_json = req.stream.read().decode('utf-8')
5325
        except Exception as ex:
5326
            print(str(ex))
5327
            raise falcon.HTTPError(status=falcon.HTTP_400,
5328
                                   title='API.BAD_REQUEST',
5329
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5330
5331
        new_values = json.loads(raw_json)
5332
5333
        if 'name' not in new_values.keys() or \
5334
                not isinstance(new_values['name'], str) or \
5335
                len(str.strip(new_values['name'])) == 0:
5336
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5337
                                   description='API.INVALID_MICROGRID_NAME')
5338
        name = str.strip(new_values['name'])
5339
5340
        if 'address' not in new_values.keys() or \
5341
                not isinstance(new_values['address'], str) or \
5342
                len(str.strip(new_values['address'])) == 0:
5343
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5344
                                   description='API.INVALID_ADDRESS_VALUE')
5345
        address = str.strip(new_values['address'])
5346
5347
        if 'postal_code' not in new_values.keys() or \
5348
                not isinstance(new_values['postal_code'], str) or \
5349
                len(str.strip(new_values['postal_code'])) == 0:
5350
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5351
                                   description='API.INVALID_POSTAL_CODE_VALUE')
5352
        postal_code = str.strip(new_values['postal_code'])
5353
5354
        if 'latitude' not in new_values.keys() or \
5355
                not (isinstance(new_values['latitude'], float) or
5356
                     isinstance(new_values['latitude'], int)) or \
5357
                new_values['latitude'] < -90.0 or \
5358
                new_values['latitude'] > 90.0:
5359
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5360
                                   description='API.INVALID_LATITUDE_VALUE')
5361
        latitude = new_values['latitude']
5362
5363
        if 'longitude' not in new_values.keys() or \
5364
                not (isinstance(new_values['longitude'], float) or
5365
                     isinstance(new_values['longitude'], int)) or \
5366
                new_values['longitude'] < -180.0 or \
5367
                new_values['longitude'] > 180.0:
5368
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5369
                                   description='API.INVALID_LONGITUDE_VALUE')
5370
        longitude = new_values['longitude']
5371
5372
        if 'rated_capacity' not in new_values.keys() or \
5373
                not (isinstance(new_values['rated_capacity'], float) or
5374
                     isinstance(new_values['rated_capacity'], int)) or \
5375
                new_values['rated_capacity'] <= 0.0:
5376
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5377
                                   description='API.INVALID_RATED_CAPACITY')
5378
        rated_capacity = new_values['rated_capacity']
5379
5380
        if 'rated_power' not in new_values.keys() or \
5381
                not (isinstance(new_values['rated_power'], float) or
5382
                     isinstance(new_values['rated_power'], int)) or \
5383
                new_values['rated_power'] <= 0.0:
5384
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5385
                                   description='API.INVALID_RATED_POWER')
5386
        rated_power = new_values['rated_power']
5387
5388
        if 'id' not in new_values['contact'].keys() or \
5389
                not isinstance(new_values['contact']['id'], int) or \
5390
                new_values['contact']['id'] <= 0:
5391
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5392
                                   description='API.INVALID_CONTACT_ID')
5393
        contact_id = new_values['contact']['id']
5394
5395
        if 'id' not in new_values['cost_center'].keys() or \
5396
                not isinstance(new_values['cost_center']['id'], int) or \
5397
                new_values['cost_center']['id'] <= 0:
5398
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5399
                                   description='API.INVALID_COST_CENTER_ID')
5400
        cost_center_id = new_values['cost_center']['id']
5401
5402
        if 'serial_number' not in new_values.keys() or \
5403
                not isinstance(new_values['serial_number'], str) or \
5404
                len(str.strip(new_values['serial_number'])) == 0:
5405
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5406
                                   description='API.INVALID_SERIAL_NUMBER')
5407
        serial_number = str.strip(new_values['serial_number'])
5408
5409
        if 'svg_id' not in new_values.keys() or \
5410
                not isinstance(new_values['svg_id'], int) or \
5411
                new_values['svg_id'] <= 0:
5412
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5413
                                   description='API.INVALID_SVG_ID')
5414
        svg_id = new_values['svg_id']
5415
5416
        if 'is_cost_data_displayed' not in new_values.keys() or \
5417
                not isinstance(new_values['is_cost_data_displayed'], bool):
5418
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5419
                                   description='API.INVALID_IS_COST_DATA_DISPLAYED')
5420
        is_cost_data_displayed = new_values['is_cost_data_displayed']
5421
5422
        if 'phase_of_lifecycle' not in new_values.keys() or \
5423
                not isinstance(new_values['phase_of_lifecycle'], str) or \
5424
                len(str.strip(new_values['phase_of_lifecycle'])) == 0:
5425
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5426
                                   description='API.INVALID_PHASE_OF_LIFECYCLE')
5427
        phase_of_lifecycle = str.strip(new_values['phase_of_lifecycle'])
5428
5429
        if 'description' in new_values.keys() and \
5430
                new_values['description'] is not None and \
5431
                len(str(new_values['description'])) > 0:
5432
            description = str.strip(new_values['description'])
5433
        else:
5434
            description = None
5435
5436
        cnx = mysql.connector.connect(**config.myems_system_db)
5437
        cursor = cnx.cursor()
5438
5439
        original_name = name
5440
        while True:
5441
            cursor.execute(" SELECT name "
5442
                           " FROM tbl_microgrids "
5443
                           " WHERE name = %s ", (name,))
5444
            if cursor.fetchone() is None:
5445
                break
5446
            timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
5447
            if config.utc_offset[0] == '-':
5448
                timezone_offset = -timezone_offset
5449
            name = (str.strip(original_name) +
5450
                    (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds'))
5451
5452
        cursor.execute(" SELECT name "
5453
                       " FROM tbl_contacts "
5454
                       " WHERE id = %s ",
5455
                       (new_values['contact']['id'],))
5456
        row = cursor.fetchone()
5457
        if row is None:
5458
            cursor.close()
5459
            cnx.close()
5460
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5461
                                   description='API.CONTACT_NOT_FOUND')
5462
5463
        cursor.execute(" SELECT name "
5464
                       " FROM tbl_cost_centers "
5465
                       " WHERE id = %s ",
5466
                       (new_values['cost_center']['id'],))
5467
        row = cursor.fetchone()
5468
        if row is None:
5469
            cursor.close()
5470
            cnx.close()
5471
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5472
                                   description='API.COST_CENTER_NOT_FOUND')
5473
5474
        cursor.execute(" SELECT name "
5475
                       " FROM tbl_svgs "
5476
                       " WHERE id = %s ",
5477
                       (svg_id,))
5478
        row = cursor.fetchone()
5479
        if row is None:
5480
            cursor.close()
5481
            cnx.close()
5482
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5483
                                   description='API.SVG_NOT_FOUND')
5484
5485
        add_values = (" INSERT INTO tbl_microgrids "
5486
                      "    (name, uuid, address, postal_code, latitude, longitude, rated_capacity, rated_power, "
5487
                      "     contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, phase_of_lifecycle, description) "
5488
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
5489
        cursor.execute(add_values, (name,
5490
                                    str(uuid.uuid4()),
5491
                                    address,
5492
                                    postal_code,
5493
                                    latitude,
5494
                                    longitude,
5495
                                    rated_capacity,
5496
                                    rated_power,
5497
                                    contact_id,
5498
                                    cost_center_id,
5499
                                    serial_number,
5500
                                    svg_id,
5501
                                    is_cost_data_displayed,
5502
                                    phase_of_lifecycle,
5503
                                    description))
5504
        new_id = cursor.lastrowid
5505
        cnx.commit()
5506
        cursor.close()
5507
        cnx.close()
5508
5509
        resp.status = falcon.HTTP_201
5510
        resp.location = '/microgrids/' + str(new_id)
5511
5512
5513
class MicrogridClone:
5514
    def __init__(self):
5515
        pass
5516
5517
    @staticmethod
5518
    def on_options(req, resp, id_):
5519
        _ = req
5520
        resp.status = falcon.HTTP_200
5521
        _ = id_
5522
5523
    @staticmethod
5524
    @user_logger
5525
    def on_post(req, resp, id_):
5526
        admin_control(req)
5527
        if not id_.isdigit() or int(id_) <= 0:
5528
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5529
                                   description='API.INVALID_MICROGRID_ID')
5530
5531
        cnx = mysql.connector.connect(**config.myems_system_db)
5532
        cursor = cnx.cursor()
5533
5534
        query = (" SELECT id, name, uuid "
5535
                 " FROM tbl_contacts ")
5536
        cursor.execute(query)
5537
        rows_contacts = cursor.fetchall()
5538
5539
        contact_dict = dict()
5540
        if rows_contacts is not None and len(rows_contacts) > 0:
5541
            for row in rows_contacts:
5542
                contact_dict[row[0]] = {"id": row[0],
5543
                                        "name": row[1],
5544
                                        "uuid": row[2]}
5545
5546
        query = (" SELECT id, name, uuid "
5547
                 " FROM tbl_cost_centers ")
5548
        cursor.execute(query)
5549
        rows_cost_centers = cursor.fetchall()
5550
5551
        cost_center_dict = dict()
5552
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
5553
            for row in rows_cost_centers:
5554
                cost_center_dict[row[0]] = {"id": row[0],
5555
                                            "name": row[1],
5556
                                            "uuid": row[2]}
5557
5558
        query = (" SELECT id, name, uuid, "
5559
                    "        address, postal_code, latitude, longitude, rated_capacity, rated_power, "
5560
                    "        contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, phase_of_lifecycle, description "
5561
                    " FROM tbl_microgrids "
5562
                    " WHERE id = %s ")
5563
        cursor.execute(query, (id_,))
5564
        row = cursor.fetchone()
5565
5566
        if row is None:
5567
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5568
                                   description='API.MICROGRID_NOT_FOUND')
5569
        else:
5570
            meta_result = {"id": row[0],
5571
                           "name": row[1],
5572
                           "uuid": row[2],
5573
                           "address": row[3],
5574
                           "postal_code": row[4],
5575
                           "latitude": row[5],
5576
                           "longitude": row[6],
5577
                           "rated_capacity": row[7],
5578
                           "rated_power": row[8],
5579
                           "contact": contact_dict.get(row[9], None),
5580
                           "cost_center": cost_center_dict.get(row[10], None),
5581
                           "serial_number": row[11],
5582
                           "svg_id": row[12],
5583
                           "is_cost_data_displayed": row[13],
5584
                           "phase_of_lifecycle": row[14],
5585
                           "description": row[15]}
5586
            timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
5587
            if config.utc_offset[0] == '-':
5588
                timezone_offset = -timezone_offset
5589
            new_name = (str.strip(meta_result['name']) +
5590
                        (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds'))
5591
            add_values = (" INSERT INTO tbl_microgrids "
5592
                          "    (name, uuid, address, postal_code, latitude, longitude, rated_capacity, rated_power, "
5593
                          "     contact_id, cost_center_id, serial_number, svg_id, is_cost_data_displayed, phase_of_lifecycle, description) "
5594
                          " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
5595
            cursor.execute(add_values, (new_name,
5596
                                        str(uuid.uuid4()),
5597
                                        meta_result['address'],
5598
                                        meta_result['postal_code'],
5599
                                        meta_result['latitude'],
5600
                                        meta_result['longitude'],
5601
                                        meta_result['rated_capacity'],
5602
                                        meta_result['rated_power'],
5603
                                        meta_result['contact']['id'],
5604
                                        meta_result['cost_center']['id'],
5605
                                        meta_result['serial_number'],
5606
                                        meta_result['svg_id'],
5607
                                        meta_result['is_cost_data_displayed'],
5608
                                        meta_result['phase_of_lifecycle'],
5609
                                        meta_result['description']))
5610
            new_id = cursor.lastrowid
5611
            cnx.commit()
5612
            cursor.close()
5613
            cnx.close()
5614
5615
            resp.status = falcon.HTTP_201
5616
            resp.location = '/microgrids/' + str(new_id)
5617
5618 View Code Duplication
class MicrogridDataSourceCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5619
    def __init__(self):
5620
        pass
5621
5622
    @staticmethod
5623
    def on_options(req, resp, id_):
5624
        _ = req
5625
        _ = id_
5626
        resp.status = falcon.HTTP_200
5627
5628
    @staticmethod
5629
    def on_get(req, resp, id_):
5630
        if 'API-KEY' not in req.headers or \
5631
                not isinstance(req.headers['API-KEY'], str) or \
5632
                len(str.strip(req.headers['API-KEY'])) == 0:
5633
            access_control(req)
5634
        else:
5635
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
5636
5637
        if not id_.isdigit() or int(id_) <= 0:
5638
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5639
                                   description='API.INVALID_MICROGRID_ID')
5640
5641
        cnx = mysql.connector.connect(**config.myems_system_db)
5642
        cursor = cnx.cursor()
5643
5644
        cursor.execute(" SELECT name FROM tbl_microgrids WHERE id = %s ", (id_,))
5645
        if cursor.fetchone() is None:
5646
            cursor.close()
5647
            cnx.close()
5648
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5649
                                   description='API.MICROGRID_NOT_FOUND')
5650
5651
        query = (" SELECT ds.id, ds.name, ds.uuid "
5652
                 " FROM tbl_microgrids mg, tbl_microgrids_data_sources mgds, tbl_data_sources ds "
5653
                 " WHERE mgds.microgrid_id = mg.id AND ds.id = mgds.data_source_id AND mg.id = %s "
5654
                 " ORDER BY ds.id ")
5655
        cursor.execute(query, (id_,))
5656
        rows = cursor.fetchall()
5657
5658
        result = list()
5659
        if rows is not None and len(rows) > 0:
5660
            for row in rows:
5661
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
5662
                result.append(meta_result)
5663
5664
        cursor.close()
5665
        cnx.close()
5666
5667
        resp.text = json.dumps(result)
5668
5669
    @staticmethod
5670
    @user_logger
5671
    def on_post(req, resp, id_):
5672
        admin_control(req)
5673
        try:
5674
            raw_json = req.stream.read().decode('utf-8')
5675
        except Exception as ex:
5676
            raise falcon.HTTPError(status=falcon.HTTP_400,
5677
                                   title='API.BAD_REQUEST',
5678
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5679
5680
        if not id_.isdigit() or int(id_) <= 0:
5681
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5682
                                   description='API.INVALID_MICROGRID_ID')
5683
5684
        new_values = json.loads(raw_json)
5685
5686
        if 'data_source_id' not in new_values['data'].keys() or \
5687
                not isinstance(new_values['data']['data_source_id'], int) or \
5688
                new_values['data']['data_source_id'] <= 0:
5689
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5690
                                   description='API.INVALID_DATA_SOURCE_ID')
5691
5692
        data_source_id = new_values['data']['data_source_id']
5693
5694
        cnx = mysql.connector.connect(**config.myems_system_db)
5695
        cursor = cnx.cursor()
5696
5697
        cursor.execute(" SELECT name FROM tbl_microgrids WHERE id = %s ", (id_,))
5698
        if cursor.fetchone() is None:
5699
            cursor.close()
5700
            cnx.close()
5701
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5702
                                   description='API.MICROGRID_NOT_FOUND')
5703
5704
        cursor.execute(" SELECT name FROM tbl_data_sources WHERE id = %s ", (data_source_id,))
5705
        if cursor.fetchone() is None:
5706
            cursor.close()
5707
            cnx.close()
5708
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5709
                                   description='API.DATA_SOURCE_NOT_FOUND')
5710
5711
        cursor.execute(" SELECT id "
5712
                       " FROM tbl_microgrids_data_sources "
5713
                       " WHERE microgrid_id = %s AND data_source_id = %s", (id_, data_source_id))
5714
        if cursor.fetchone() is not None:
5715
            cursor.close()
5716
            cnx.close()
5717
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5718
                                   description='API.MICROGRID_DATA_SOURCE_RELATION_EXISTS')
5719
5720
        cursor.execute(" INSERT INTO tbl_microgrids_data_sources (microgrid_id, data_source_id) "
5721
                       " VALUES (%s, %s) ", (id_, data_source_id))
5722
        cnx.commit()
5723
        cursor.close()
5724
        cnx.close()
5725
5726
        resp.status = falcon.HTTP_201
5727
        resp.location = '/microgrids/' + str(id_) + '/datasources/' + str(data_source_id)
5728
5729 View Code Duplication
class MicrogridDataSourceItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5730
    def __init__(self):
5731
        pass
5732
5733
    @staticmethod
5734
    def on_options(req, resp, id_, dsid):
5735
        _ = req
5736
        _ = id_
5737
        _ = dsid
5738
        resp.status = falcon.HTTP_200
5739
5740
    @staticmethod
5741
    @user_logger
5742
    def on_delete(req, resp, id_, dsid):
5743
        admin_control(req)
5744
5745
        if not id_.isdigit() or int(id_) <= 0:
5746
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5747
                                   description='API.INVALID_MICROGRID_ID')
5748
5749
        if not dsid.isdigit() or int(dsid) <= 0:
5750
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5751
                                   description='API.INVALID_DATA_SOURCE_ID')
5752
5753
        cnx = mysql.connector.connect(**config.myems_system_db)
5754
        cursor = cnx.cursor()
5755
5756
        cursor.execute(" SELECT name FROM tbl_microgrids WHERE id = %s ", (id_,))
5757
        if cursor.fetchone() is None:
5758
            cursor.close()
5759
            cnx.close()
5760
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5761
                                   description='API.MICROGRID_NOT_FOUND')
5762
5763
        cursor.execute(" SELECT name FROM tbl_data_sources WHERE id = %s ", (dsid,))
5764
        if cursor.fetchone() is None:
5765
            cursor.close()
5766
            cnx.close()
5767
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5768
                                   description='API.DATA_SOURCE_NOT_FOUND')
5769
5770
        cursor.execute(" SELECT id "
5771
                       " FROM tbl_microgrids_data_sources "
5772
                       " WHERE microgrid_id = %s AND data_source_id = %s ", (id_, dsid))
5773
        if cursor.fetchone() is None:
5774
            cursor.close()
5775
            cnx.close()
5776
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5777
                                   description='API.MICROGRID_DATA_SOURCE_RELATION_NOT_FOUND')
5778
5779
        cursor.execute(" DELETE FROM tbl_microgrids_data_sources "
5780
                       " WHERE microgrid_id = %s AND data_source_id = %s ", (id_, dsid))
5781
        cnx.commit()
5782
        cursor.close()
5783
        cnx.close()
5784
5785
        resp.status = falcon.HTTP_204
5786
5787 View Code Duplication
class MicrogridDataSourcePointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5788
    def __init__(self):
5789
        pass
5790
5791
    @staticmethod
5792
    def on_options(req, resp, id_):
5793
        _ = req
5794
        resp.status = falcon.HTTP_200
5795
        _ = id_
5796
5797
    @staticmethod
5798
    def on_get(req, resp, id_):
5799
        if 'API-KEY' not in req.headers or \
5800
                not isinstance(req.headers['API-KEY'], str) or \
5801
                len(str.strip(req.headers['API-KEY'])) == 0:
5802
            access_control(req)
5803
        else:
5804
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
5805
        if not id_.isdigit() or int(id_) <= 0:
5806
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5807
                                   description='API.INVALID_MICROGRID_ID')
5808
5809
        cnx = mysql.connector.connect(**config.myems_system_db)
5810
        cursor = cnx.cursor()
5811
5812
        query = (" SELECT p.id, p.name "
5813
                 " FROM tbl_points p, tbl_microgrids_data_sources mds, tbl_data_sources ds "
5814
                 " WHERE mds.microgrid_id = %s "
5815
                 "       AND mds.data_source_id = ds.id "
5816
                 "       AND p.data_source_id = ds.id "
5817
                 " ORDER BY p.id ")
5818
        cursor.execute(query, (id_,))
5819
        rows = cursor.fetchall()
5820
5821
        result = list()
5822
        if rows is not None and len(rows) > 0:
5823
            for row in rows:
5824
                meta_result = {"id": row[0], "name": row[1]}
5825
                result.append(meta_result)
5826
5827
        cursor.close()
5828
        cnx.close()
5829
5830
        resp.text = json.dumps(result)
5831
5832 View Code Duplication
class MicrogridBatteryPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5833
    def __init__(self):
5834
        pass
5835
5836
    @staticmethod
5837
    def on_options(req, resp, id_, bid):
5838
        _ = req
5839
        resp.status = falcon.HTTP_200
5840
        _ = id_
5841
        _ = bid
5842
5843
    @staticmethod
5844
    def on_get(req, resp, id_, bid):
5845
        if 'API-KEY' not in req.headers or \
5846
                not isinstance(req.headers['API-KEY'], str) or \
5847
                len(str.strip(req.headers['API-KEY'])) == 0:
5848
            access_control(req)
5849
        else:
5850
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
5851
        if not id_.isdigit() or int(id_) <= 0:
5852
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5853
                                   description='API.INVALID_MICROGRID_ID')
5854
        if not bid.isdigit() or int(bid) <= 0:
5855
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5856
                                   description='API.INVALID_BATTERY_ID')
5857
5858
        cnx = mysql.connector.connect(**config.myems_system_db)
5859
        cursor = cnx.cursor()
5860
5861
        cursor.execute(" SELECT name "
5862
                       " FROM tbl_microgrids_batteries "
5863
                       " WHERE microgrid_id = %s AND id = %s ", (id_, bid,))
5864
        if cursor.fetchone() is None:
5865
            cursor.close()
5866
            cnx.close()
5867
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5868
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
5869
5870
        query = (" SELECT p.id, p.name, "
5871
                 "        ds.id, ds.name, ds.uuid, "
5872
                 "        p.address "
5873
                 " FROM tbl_points p, tbl_microgrids_bmses_points mp, tbl_data_sources ds "
5874
                 " WHERE mp.bms_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
5875
                 " ORDER BY p.name ")
5876
        cursor.execute(query, (bid,))
5877
        rows = cursor.fetchall()
5878
5879
        result = list()
5880
        if rows is not None and len(rows) > 0:
5881
            for row in rows:
5882
                meta_result = {"id": row[0], "name": row[1],
5883
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
5884
                               "address": row[5]}
5885
                result.append(meta_result)
5886
5887
        resp.text = json.dumps(result)
5888
5889
    @staticmethod
5890
    @user_logger
5891
    def on_post(req, resp, id_, bid):
5892
        admin_control(req)
5893
        try:
5894
            raw_json = req.stream.read().decode('utf-8')
5895
        except Exception as ex:
5896
            print(str(ex))
5897
            raise falcon.HTTPError(status=falcon.HTTP_400,
5898
                                   title='API.BAD_REQUEST',
5899
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5900
5901
        if not id_.isdigit() or int(id_) <= 0:
5902
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5903
                                   description='API.INVALID_MICROGRID_ID')
5904
        if not bid.isdigit() or int(bid) <= 0:
5905
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5906
                                   description='API.INVALID_BATTERY_ID')
5907
5908
        new_values = json.loads(raw_json)
5909
        cnx = mysql.connector.connect(**config.myems_system_db)
5910
        cursor = cnx.cursor()
5911
5912
        cursor.execute(" SELECT name "
5913
                       " FROM tbl_microgrids_batteries "
5914
                       " WHERE microgrid_id = %s AND id = %s ", (id_, bid,))
5915
        if cursor.fetchone() is None:
5916
            cursor.close()
5917
            cnx.close()
5918
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5919
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
5920
5921
        cursor.execute(" SELECT name, object_type "
5922
                       " FROM tbl_points "
5923
                       " WHERE id = %s ", (new_values['data']['point_id'],))
5924
        row = cursor.fetchone()
5925
        if row is None:
5926
            cursor.close()
5927
            cnx.close()
5928
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5929
                                   description='API.POINT_NOT_FOUND')
5930
5931
        query = (" SELECT id "
5932
                 " FROM tbl_microgrids_bmses_points "
5933
                 " WHERE bms_id = %s AND point_id = %s")
5934
        cursor.execute(query, (bid, new_values['data']['point_id'],))
5935
        if cursor.fetchone() is not None:
5936
            cursor.close()
5937
            cnx.close()
5938
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5939
                                   description='API.BATTERY_POINT_RELATION_EXISTS')
5940
5941
        add_row = (" INSERT INTO tbl_microgrids_bmses_points (bms_id, point_id) "
5942
                   " VALUES (%s, %s) ")
5943
        cursor.execute(add_row, (bid, new_values['data']['point_id'],))
5944
        cnx.commit()
5945
        cursor.close()
5946
        cnx.close()
5947
5948
        resp.status = falcon.HTTP_201
5949
        resp.location = '/microgrids/' + str(id_) + '/batteries/' + str(bid) + '/points/' + \
5950
                        str(new_values['data']['point_id'])
5951
5952
5953 View Code Duplication
class MicrogridBatteryPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5954
    def __init__(self):
5955
        pass
5956
5957
    @staticmethod
5958
    def on_options(req, resp, id_, bid, pid):
5959
        _ = req
5960
        resp.status = falcon.HTTP_200
5961
        _ = id_
5962
        _ = bid
5963
        _ = pid
5964
5965
    @staticmethod
5966
    @user_logger
5967
    def on_delete(req, resp, id_, bid, pid):
5968
        admin_control(req)
5969
        if not id_.isdigit() or int(id_) <= 0:
5970
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5971
                                   description='API.INVALID_MICROGRID_ID')
5972
        if not bid.isdigit() or int(bid) <= 0:
5973
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5974
                                   description='API.INVALID_BATTERY_ID')
5975
        if not pid.isdigit() or int(pid) <= 0:
5976
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5977
                                   description='API.INVALID_POINT_ID')
5978
5979
        cnx = mysql.connector.connect(**config.myems_system_db)
5980
        cursor = cnx.cursor()
5981
5982
        cursor.execute(" SELECT name "
5983
                       " FROM tbl_microgrids_batteries "
5984
                       " WHERE microgrid_id = %s AND id = %s ", (id_, bid,))
5985
        if cursor.fetchone() is None:
5986
            cursor.close()
5987
            cnx.close()
5988
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5989
                                   description='API.MICROGRID_BATTERY_NOT_FOUND')
5990
5991
        cursor.execute(" SELECT name "
5992
                       " FROM tbl_points "
5993
                       " WHERE id = %s ", (pid,))
5994
        if cursor.fetchone() is None:
5995
            cursor.close()
5996
            cnx.close()
5997
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5998
                                   description='API.POINT_NOT_FOUND')
5999
6000
        cursor.execute(" SELECT id "
6001
                       " FROM tbl_microgrids_bmses_points "
6002
                       " WHERE bms_id = %s AND point_id = %s ", (bid, pid))
6003
        if cursor.fetchone() is None:
6004
            cursor.close()
6005
            cnx.close()
6006
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6007
                                   description='API.BATTERY_POINT_RELATION_NOT_FOUND')
6008
6009
        cursor.execute(" DELETE FROM tbl_microgrids_bmses_points "
6010
                       " WHERE bms_id = %s AND point_id = %s ", (bid, pid))
6011
        cnx.commit()
6012
6013
        cursor.close()
6014
        cnx.close()
6015
6016
        resp.status = falcon.HTTP_204
6017
6018 View Code Duplication
class MicrogridEVChargerPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6019
    def __init__(self):
6020
        pass
6021
6022
    @staticmethod
6023
    def on_options(req, resp, id_, eid):
6024
        _ = req
6025
        resp.status = falcon.HTTP_200
6026
        _ = id_
6027
        _ = eid
6028
6029
    @staticmethod
6030
    def on_get(req, resp, id_, eid):
6031
        if 'API-KEY' not in req.headers or \
6032
                not isinstance(req.headers['API-KEY'], str) or \
6033
                len(str.strip(req.headers['API-KEY'])) == 0:
6034
            access_control(req)
6035
        else:
6036
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
6037
        if not id_.isdigit() or int(id_) <= 0:
6038
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6039
                                   description='API.INVALID_MICROGRID_ID')
6040
        if not eid.isdigit() or int(eid) <= 0:
6041
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6042
                                   description='API.INVALID_EVCHARGER_ID')
6043
6044
        cnx = mysql.connector.connect(**config.myems_system_db)
6045
        cursor = cnx.cursor()
6046
6047
        cursor.execute(" SELECT name "
6048
                       " FROM tbl_microgrids_evchargers "
6049
                       " WHERE microgrid_id = %s AND id = %s ", (id_, eid,))
6050
        if cursor.fetchone() is None:
6051
            cursor.close()
6052
            cnx.close()
6053
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6054
                                   description='API.MICROGRID_EV_CHARGER_NOT_FOUND')
6055
6056
        query = (" SELECT p.id, p.name, "
6057
                 "        ds.id, ds.name, ds.uuid, "
6058
                 "        p.address "
6059
                 " FROM tbl_points p, tbl_microgrids_evchargers_points mp, tbl_data_sources ds "
6060
                 " WHERE mp.evcharger_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
6061
                 " ORDER BY p.name ")
6062
        cursor.execute(query, (eid,))
6063
        rows = cursor.fetchall()
6064
6065
        result = list()
6066
        if rows is not None and len(rows) > 0:
6067
            for row in rows:
6068
                meta_result = {"id": row[0], "name": row[1],
6069
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
6070
                               "address": row[5]}
6071
                result.append(meta_result)
6072
6073
        resp.text = json.dumps(result)
6074
6075
    @staticmethod
6076
    @user_logger
6077
    def on_post(req, resp, id_, eid):
6078
        admin_control(req)
6079
        try:
6080
            raw_json = req.stream.read().decode('utf-8')
6081
        except Exception as ex:
6082
            print(str(ex))
6083
            raise falcon.HTTPError(status=falcon.HTTP_400,
6084
                                   title='API.BAD_REQUEST',
6085
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
6086
6087
        if not id_.isdigit() or int(id_) <= 0:
6088
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6089
                                   description='API.INVALID_MICROGRID_ID')
6090
        if not eid.isdigit() or int(eid) <= 0:
6091
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6092
                                   description='API.INVALID_EVCHARGER_ID')
6093
6094
        new_values = json.loads(raw_json)
6095
        cnx = mysql.connector.connect(**config.myems_system_db)
6096
        cursor = cnx.cursor()
6097
6098
        cursor.execute(" SELECT name "
6099
                       " FROM tbl_microgrids_evchargers "
6100
                       " WHERE microgrid_id = %s AND id = %s ", (id_, eid,))
6101
        if cursor.fetchone() is None:
6102
            cursor.close()
6103
            cnx.close()
6104
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6105
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
6106
6107
        cursor.execute(" SELECT name, object_type "
6108
                       " FROM tbl_points "
6109
                       " WHERE id = %s ", (new_values['data']['point_id'],))
6110
        row = cursor.fetchone()
6111
        if row is None:
6112
            cursor.close()
6113
            cnx.close()
6114
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6115
                                   description='API.POINT_NOT_FOUND')
6116
6117
        query = (" SELECT id "
6118
                 " FROM tbl_microgrids_evchargers_points "
6119
                 " WHERE evcharger_id = %s AND point_id = %s")
6120
        cursor.execute(query, (eid, new_values['data']['point_id'],))
6121
        if cursor.fetchone() is not None:
6122
            cursor.close()
6123
            cnx.close()
6124
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
6125
                                   description='API.EVCHARGER_POINT_RELATION_EXISTS')
6126
6127
        add_row = (" INSERT INTO tbl_microgrids_evchargers_points (evcharger_id, point_id) "
6128
                   " VALUES (%s, %s) ")
6129
        cursor.execute(add_row, (eid, new_values['data']['point_id'],))
6130
        cnx.commit()
6131
        cursor.close()
6132
        cnx.close()
6133
6134
        resp.status = falcon.HTTP_201
6135
        resp.location = '/microgrids/' + str(id_) + '/evchargers/' + str(eid) + '/points/' + \
6136
                        str(new_values['data']['point_id'])
6137
6138
6139 View Code Duplication
class MicrogridEVChargerPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6140
    def __init__(self):
6141
        pass
6142
6143
    @staticmethod
6144
    def on_options(req, resp, id_, eid, pid):
6145
        _ = req
6146
        resp.status = falcon.HTTP_200
6147
        _ = id_
6148
        _ = eid
6149
        _ = pid
6150
6151
    @staticmethod
6152
    @user_logger
6153
    def on_delete(req, resp, id_, eid, pid):
6154
        admin_control(req)
6155
        if not id_.isdigit() or int(id_) <= 0:
6156
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6157
                                   description='API.INVALID_MICROGRID_ID')
6158
        if not eid.isdigit() or int(eid) <= 0:
6159
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6160
                                   description='API.INVALID_EVCHARGER_ID')
6161
        if not pid.isdigit() or int(pid) <= 0:
6162
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6163
                                   description='API.INVALID_POINT_ID')
6164
6165
        cnx = mysql.connector.connect(**config.myems_system_db)
6166
        cursor = cnx.cursor()
6167
6168
        cursor.execute(" SELECT name "
6169
                       " FROM tbl_microgrids_evchargers "
6170
                       " WHERE microgrid_id = %s AND id = %s ", (id_, eid,))
6171
        if cursor.fetchone() is None:
6172
            cursor.close()
6173
            cnx.close()
6174
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6175
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
6176
6177
        cursor.execute(" SELECT name "
6178
                       " FROM tbl_points "
6179
                       " WHERE id = %s ", (pid,))
6180
        if cursor.fetchone() is None:
6181
            cursor.close()
6182
            cnx.close()
6183
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6184
                                   description='API.POINT_NOT_FOUND')
6185
6186
        cursor.execute(" SELECT id "
6187
                       " FROM tbl_microgrids_evchargers_points "
6188
                       " WHERE evcharger_id = %s AND point_id = %s ", (eid, pid))
6189
        if cursor.fetchone() is None:
6190
            cursor.close()
6191
            cnx.close()
6192
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6193
                                   description='API.EVCHARGER_POINT_RELATION_NOT_FOUND')
6194
6195
        cursor.execute(" DELETE FROM tbl_microgrids_evchargers_points "
6196
                       " WHERE evcharger_id = %s AND point_id = %s ", (eid, pid))
6197
        cnx.commit()
6198
6199
        cursor.close()
6200
        cnx.close()
6201
6202
        resp.status = falcon.HTTP_204
6203
6204 View Code Duplication
class MicrogridGeneratorPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6205
    def __init__(self):
6206
        pass
6207
6208
    @staticmethod
6209
    def on_options(req, resp, id_, gid):
6210
        _ = req
6211
        resp.status = falcon.HTTP_200
6212
        _ = id_
6213
        _ = gid
6214
6215
    @staticmethod
6216
    def on_get(req, resp, id_, gid):
6217
        if 'API-KEY' not in req.headers or \
6218
                not isinstance(req.headers['API-KEY'], str) or \
6219
                len(str.strip(req.headers['API-KEY'])) == 0:
6220
            access_control(req)
6221
        else:
6222
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
6223
        if not id_.isdigit() or int(id_) <= 0:
6224
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6225
                                   description='API.INVALID_MICROGRID_ID')
6226
        if not gid.isdigit() or int(gid) <= 0:
6227
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6228
                                   description='API.INVALID_GENERATOR_ID')
6229
6230
        cnx = mysql.connector.connect(**config.myems_system_db)
6231
        cursor = cnx.cursor()
6232
6233
        cursor.execute(" SELECT name "
6234
                       " FROM tbl_microgrids_generators "
6235
                       " WHERE microgrid_id = %s AND id = %s ", (id_, gid,))
6236
        if cursor.fetchone() is None:
6237
            cursor.close()
6238
            cnx.close()
6239
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6240
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
6241
6242
        query = (" SELECT p.id, p.name, "
6243
                 "        ds.id, ds.name, ds.uuid, "
6244
                 "        p.address "
6245
                 " FROM tbl_points p, tbl_microgrids_generators_points mp, tbl_data_sources ds "
6246
                 " WHERE mp.generator_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
6247
                 " ORDER BY p.name ")
6248
        cursor.execute(query, (gid,))
6249
        rows = cursor.fetchall()
6250
6251
        result = list()
6252
        if rows is not None and len(rows) > 0:
6253
            for row in rows:
6254
                meta_result = {"id": row[0], "name": row[1],
6255
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
6256
                               "address": row[5]}
6257
                result.append(meta_result)
6258
6259
        resp.text = json.dumps(result)
6260
6261
    @staticmethod
6262
    @user_logger
6263
    def on_post(req, resp, id_, gid):
6264
        admin_control(req)
6265
        try:
6266
            raw_json = req.stream.read().decode('utf-8')
6267
        except Exception as ex:
6268
            print(str(ex))
6269
            raise falcon.HTTPError(status=falcon.HTTP_400,
6270
                                   title='API.BAD_REQUEST',
6271
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
6272
6273
        if not id_.isdigit() or int(id_) <= 0:
6274
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6275
                                   description='API.INVALID_MICROGRID_ID')
6276
        if not gid.isdigit() or int(gid) <= 0:
6277
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6278
                                   description='API.INVALID_GENERATOR_ID')
6279
6280
        new_values = json.loads(raw_json)
6281
        cnx = mysql.connector.connect(**config.myems_system_db)
6282
        cursor = cnx.cursor()
6283
6284
        cursor.execute(" SELECT name "
6285
                       " FROM tbl_microgrids_generators "
6286
                       " WHERE microgrid_id = %s AND id = %s ", (id_, gid,))
6287
        if cursor.fetchone() is None:
6288
            cursor.close()
6289
            cnx.close()
6290
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6291
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
6292
6293
        cursor.execute(" SELECT name, object_type "
6294
                       " FROM tbl_points "
6295
                       " WHERE id = %s ", (new_values['data']['point_id'],))
6296
        row = cursor.fetchone()
6297
        if row is None:
6298
            cursor.close()
6299
            cnx.close()
6300
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6301
                                   description='API.POINT_NOT_FOUND')
6302
6303
        query = (" SELECT id "
6304
                 " FROM tbl_microgrids_generators_points "
6305
                 " WHERE generator_id = %s AND point_id = %s")
6306
        cursor.execute(query, (gid, new_values['data']['point_id'],))
6307
        if cursor.fetchone() is not None:
6308
            cursor.close()
6309
            cnx.close()
6310
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
6311
                                   description='API.GENERATOR_POINT_RELATION_EXISTS')
6312
6313
        add_row = (" INSERT INTO tbl_microgrids_generators_points (generator_id, point_id) "
6314
                   " VALUES (%s, %s) ")
6315
        cursor.execute(add_row, (gid, new_values['data']['point_id'],))
6316
        cnx.commit()
6317
        cursor.close()
6318
        cnx.close()
6319
6320
        resp.status = falcon.HTTP_201
6321
        resp.location = '/microgrids/' + str(id_) + '/generators/' + str(gid) + '/points/' + \
6322
                        str(new_values['data']['point_id'])
6323
6324
6325 View Code Duplication
class MicrogridGeneratorPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6326
    def __init__(self):
6327
        pass
6328
6329
    @staticmethod
6330
    def on_options(req, resp, id_, gid, pid):
6331
        _ = req
6332
        resp.status = falcon.HTTP_200
6333
        _ = id_
6334
        _ = gid
6335
        _ = pid
6336
6337
    @staticmethod
6338
    @user_logger
6339
    def on_delete(req, resp, id_, gid, pid):
6340
        admin_control(req)
6341
        if not id_.isdigit() or int(id_) <= 0:
6342
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6343
                                   description='API.INVALID_MICROGRID_ID')
6344
        if not gid.isdigit() or int(gid) <= 0:
6345
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6346
                                   description='API.INVALID_GENERATOR_ID')
6347
        if not pid.isdigit() or int(pid) <= 0:
6348
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6349
                                   description='API.INVALID_POINT_ID')
6350
6351
        cnx = mysql.connector.connect(**config.myems_system_db)
6352
        cursor = cnx.cursor()
6353
6354
        cursor.execute(" SELECT name "
6355
                       " FROM tbl_microgrids_generators "
6356
                       " WHERE microgrid_id = %s AND id = %s ", (id_, gid,))
6357
        if cursor.fetchone() is None:
6358
            cursor.close()
6359
            cnx.close()
6360
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6361
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
6362
6363
        cursor.execute(" SELECT name "
6364
                       " FROM tbl_points "
6365
                       " WHERE id = %s ", (pid,))
6366
        if cursor.fetchone() is None:
6367
            cursor.close()
6368
            cnx.close()
6369
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6370
                                   description='API.POINT_NOT_FOUND')
6371
6372
        cursor.execute(" SELECT id "
6373
                       " FROM tbl_microgrids_generators_points "
6374
                       " WHERE generator_id = %s AND point_id = %s ", (gid, pid))
6375
        if cursor.fetchone() is None:
6376
            cursor.close()
6377
            cnx.close()
6378
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6379
                                   description='API.GENERATOR_POINT_RELATION_NOT_FOUND')
6380
6381
        cursor.execute(" DELETE FROM tbl_microgrids_generators_points "
6382
                       " WHERE generator_id = %s AND point_id = %s ", (gid, pid))
6383
        cnx.commit()
6384
6385
        cursor.close()
6386
        cnx.close()
6387
6388
        resp.status = falcon.HTTP_204
6389
6390 View Code Duplication
class MicrogridGridPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6391
    def __init__(self):
6392
        pass
6393
6394
    @staticmethod
6395
    def on_options(req, resp, id_, gid):
6396
        _ = req
6397
        resp.status = falcon.HTTP_200
6398
        _ = id_
6399
        _ = gid
6400
6401
    @staticmethod
6402
    def on_get(req, resp, id_, gid):
6403
        if 'API-KEY' not in req.headers or \
6404
                not isinstance(req.headers['API-KEY'], str) or \
6405
                len(str.strip(req.headers['API-KEY'])) == 0:
6406
            access_control(req)
6407
        else:
6408
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
6409
        if not id_.isdigit() or int(id_) <= 0:
6410
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6411
                                   description='API.INVALID_MICROGRID_ID')
6412
        if not gid.isdigit() or int(gid) <= 0:
6413
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6414
                                   description='API.INVALID_GRID_ID')
6415
6416
        cnx = mysql.connector.connect(**config.myems_system_db)
6417
        cursor = cnx.cursor()
6418
6419
        cursor.execute(" SELECT name "
6420
                       " FROM tbl_microgrids_grids "
6421
                       " WHERE microgrid_id = %s AND id = %s ", (id_, gid,))
6422
        if cursor.fetchone() is None:
6423
            cursor.close()
6424
            cnx.close()
6425
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6426
                                   description='API.MICROGRID_GRID_NOT_FOUND')
6427
6428
        query = (" SELECT p.id, p.name, "
6429
                 "        ds.id, ds.name, ds.uuid, "
6430
                 "        p.address "
6431
                 " FROM tbl_points p, tbl_microgrids_grids_points mp, tbl_data_sources ds "
6432
                 " WHERE mp.grid_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
6433
                 " ORDER BY p.name ")
6434
        cursor.execute(query, (gid,))
6435
        rows = cursor.fetchall()
6436
6437
        result = list()
6438
        if rows is not None and len(rows) > 0:
6439
            for row in rows:
6440
                meta_result = {"id": row[0], "name": row[1],
6441
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
6442
                               "address": row[5]}
6443
                result.append(meta_result)
6444
6445
        resp.text = json.dumps(result)
6446
6447
    @staticmethod
6448
    @user_logger
6449
    def on_post(req, resp, id_, gid):
6450
        admin_control(req)
6451
        try:
6452
            raw_json = req.stream.read().decode('utf-8')
6453
        except Exception as ex:
6454
            print(str(ex))
6455
            raise falcon.HTTPError(status=falcon.HTTP_400,
6456
                                   title='API.BAD_REQUEST',
6457
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
6458
6459
        if not id_.isdigit() or int(id_) <= 0:
6460
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6461
                                   description='API.INVALID_MICROGRID_ID')
6462
        if not gid.isdigit() or int(gid) <= 0:
6463
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6464
                                   description='API.INVALID_GRID_ID')
6465
6466
        new_values = json.loads(raw_json)
6467
        cnx = mysql.connector.connect(**config.myems_system_db)
6468
        cursor = cnx.cursor()
6469
6470
        cursor.execute(" SELECT name "
6471
                       " FROM tbl_microgrids_grids "
6472
                       " WHERE microgrid_id = %s AND id = %s ", (id_, gid,))
6473
        if cursor.fetchone() is None:
6474
            cursor.close()
6475
            cnx.close()
6476
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6477
                                   description='API.MICROGRID_GRID_NOT_FOUND')
6478
6479
        cursor.execute(" SELECT name, object_type "
6480
                       " FROM tbl_points "
6481
                       " WHERE id = %s ", (new_values['data']['point_id'],))
6482
        row = cursor.fetchone()
6483
        if row is None:
6484
            cursor.close()
6485
            cnx.close()
6486
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6487
                                   description='API.POINT_NOT_FOUND')
6488
6489
        query = (" SELECT id "
6490
                 " FROM tbl_microgrids_grids_points "
6491
                 " WHERE grid_id = %s AND point_id = %s")
6492
        cursor.execute(query, (gid, new_values['data']['point_id'],))
6493
        if cursor.fetchone() is not None:
6494
            cursor.close()
6495
            cnx.close()
6496
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
6497
                                   description='API.GRID_POINT_RELATION_EXISTS')
6498
6499
        add_row = (" INSERT INTO tbl_microgrids_grids_points (grid_id, point_id) "
6500
                   " VALUES (%s, %s) ")
6501
        cursor.execute(add_row, (gid, new_values['data']['point_id'],))
6502
        cnx.commit()
6503
        cursor.close()
6504
        cnx.close()
6505
6506
        resp.status = falcon.HTTP_201
6507
        resp.location = '/microgrids/' + str(id_) + '/grids/' + str(gid) + '/points/' + \
6508
                        str(new_values['data']['point_id'])
6509
6510
6511 View Code Duplication
class MicrogridGridPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6512
    def __init__(self):
6513
        pass
6514
6515
    @staticmethod
6516
    def on_options(req, resp, id_, gid, pid):
6517
        _ = req
6518
        resp.status = falcon.HTTP_200
6519
        _ = id_
6520
        _ = gid
6521
        _ = pid
6522
6523
    @staticmethod
6524
    @user_logger
6525
    def on_delete(req, resp, id_, gid, pid):
6526
        admin_control(req)
6527
        if not id_.isdigit() or int(id_) <= 0:
6528
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6529
                                   description='API.INVALID_MICROGRID_ID')
6530
        if not gid.isdigit() or int(gid) <= 0:
6531
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6532
                                   description='API.INVALID_GRID_ID')
6533
        if not pid.isdigit() or int(pid) <= 0:
6534
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6535
                                   description='API.INVALID_POINT_ID')
6536
6537
        cnx = mysql.connector.connect(**config.myems_system_db)
6538
        cursor = cnx.cursor()
6539
6540
        cursor.execute(" SELECT name "
6541
                       " FROM tbl_microgrids_grids "
6542
                       " WHERE microgrid_id = %s AND id = %s ", (id_, gid,))
6543
        if cursor.fetchone() is None:
6544
            cursor.close()
6545
            cnx.close()
6546
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6547
                                   description='API.MICROGRID_GRID_NOT_FOUND')
6548
6549
        cursor.execute(" SELECT name "
6550
                       " FROM tbl_points "
6551
                       " WHERE id = %s ", (pid,))
6552
        if cursor.fetchone() is None:
6553
            cursor.close()
6554
            cnx.close()
6555
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6556
                                   description='API.POINT_NOT_FOUND')
6557
6558
        cursor.execute(" SELECT id "
6559
                       " FROM tbl_microgrids_grids_points "
6560
                       " WHERE grid_id = %s AND point_id = %s ", (gid, pid))
6561
        if cursor.fetchone() is None:
6562
            cursor.close()
6563
            cnx.close()
6564
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6565
                                   description='API.GRID_POINT_RELATION_NOT_FOUND')
6566
6567
        cursor.execute(" DELETE FROM tbl_microgrids_grids_points "
6568
                       " WHERE grid_id = %s AND point_id = %s ", (gid, pid))
6569
        cnx.commit()
6570
6571
        cursor.close()
6572
        cnx.close()
6573
6574
        resp.status = falcon.HTTP_204
6575
6576 View Code Duplication
class MicrogridHeatPumpPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6577
    def __init__(self):
6578
        pass
6579
6580
    @staticmethod
6581
    def on_options(req, resp, id_, hid):
6582
        _ = req
6583
        resp.status = falcon.HTTP_200
6584
        _ = id_
6585
        _ = hid
6586
6587
    @staticmethod
6588
    def on_get(req, resp, id_, hid):
6589
        if 'API-KEY' not in req.headers or \
6590
                not isinstance(req.headers['API-KEY'], str) or \
6591
                len(str.strip(req.headers['API-KEY'])) == 0:
6592
            access_control(req)
6593
        else:
6594
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
6595
        if not id_.isdigit() or int(id_) <= 0:
6596
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6597
                                   description='API.INVALID_MICROGRID_ID')
6598
        if not hid.isdigit() or int(hid) <= 0:
6599
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6600
                                   description='API.INVALID_HEATPUMP_ID')
6601
6602
        cnx = mysql.connector.connect(**config.myems_system_db)
6603
        cursor = cnx.cursor()
6604
6605
        cursor.execute(" SELECT name "
6606
                       " FROM tbl_microgrids_heatpumps "
6607
                       " WHERE microgrid_id = %s AND id = %s ", (id_, hid,))
6608
        if cursor.fetchone() is None:
6609
            cursor.close()
6610
            cnx.close()
6611
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6612
                                   description='API.MICROGRID_HEATPUMP_NOT_FOUND')
6613
6614
        query = (" SELECT p.id, p.name, "
6615
                 "        ds.id, ds.name, ds.uuid, "
6616
                 "        p.address "
6617
                 " FROM tbl_points p, tbl_microgrids_heatpumps_points mp, tbl_data_sources ds "
6618
                 " WHERE mp.heatpump_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
6619
                 " ORDER BY p.name ")
6620
        cursor.execute(query, (hid,))
6621
        rows = cursor.fetchall()
6622
6623
        result = list()
6624
        if rows is not None and len(rows) > 0:
6625
            for row in rows:
6626
                meta_result = {"id": row[0], "name": row[1],
6627
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
6628
                               "address": row[5]}
6629
                result.append(meta_result)
6630
6631
        resp.text = json.dumps(result)
6632
6633
    @staticmethod
6634
    @user_logger
6635
    def on_post(req, resp, id_, hid):
6636
        admin_control(req)
6637
        try:
6638
            raw_json = req.stream.read().decode('utf-8')
6639
        except Exception as ex:
6640
            print(str(ex))
6641
            raise falcon.HTTPError(status=falcon.HTTP_400,
6642
                                   title='API.BAD_REQUEST',
6643
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
6644
6645
        if not id_.isdigit() or int(id_) <= 0:
6646
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6647
                                   description='API.INVALID_MICROGRID_ID')
6648
        if not hid.isdigit() or int(hid) <= 0:
6649
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6650
                                   description='API.INVALID_HEATPUMP_ID')
6651
6652
        new_values = json.loads(raw_json)
6653
        cnx = mysql.connector.connect(**config.myems_system_db)
6654
        cursor = cnx.cursor()
6655
6656
        cursor.execute(" SELECT name "
6657
                       " FROM tbl_microgrids_heatpumps "
6658
                       " WHERE microgrid_id = %s AND id = %s ", (id_, hid,))
6659
        if cursor.fetchone() is None:
6660
            cursor.close()
6661
            cnx.close()
6662
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6663
                                   description='API.MICROGRID_HEATPUMP_NOT_FOUND')
6664
6665
        cursor.execute(" SELECT name, object_type "
6666
                       " FROM tbl_points "
6667
                       " WHERE id = %s ", (new_values['data']['point_id'],))
6668
        row = cursor.fetchone()
6669
        if row is None:
6670
            cursor.close()
6671
            cnx.close()
6672
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6673
                                   description='API.POINT_NOT_FOUND')
6674
6675
        query = (" SELECT id "
6676
                 " FROM tbl_microgrids_heatpumps_points "
6677
                 " WHERE heatpump_id = %s AND point_id = %s")
6678
        cursor.execute(query, (hid, new_values['data']['point_id'],))
6679
        if cursor.fetchone() is not None:
6680
            cursor.close()
6681
            cnx.close()
6682
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
6683
                                   description='API.HEATPUMP_POINT_RELATION_EXISTS')
6684
6685
        add_row = (" INSERT INTO tbl_microgrids_heatpumps_points (heatpump_id, point_id) "
6686
                   " VALUES (%s, %s) ")
6687
        cursor.execute(add_row, (hid, new_values['data']['point_id'],))
6688
        cnx.commit()
6689
        cursor.close()
6690
        cnx.close()
6691
6692
        resp.status = falcon.HTTP_201
6693
        resp.location = '/microgrids/' + str(id_) + '/heatpumps/' + str(hid) + '/points/' + \
6694
                        str(new_values['data']['point_id'])
6695
6696
6697 View Code Duplication
class MicrogridHeatPumpPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6698
    def __init__(self):
6699
        pass
6700
6701
    @staticmethod
6702
    def on_options(req, resp, id_, hid, pid):
6703
        _ = req
6704
        resp.status = falcon.HTTP_200
6705
        _ = id_
6706
        _ = hid
6707
        _ = pid
6708
6709
    @staticmethod
6710
    @user_logger
6711
    def on_delete(req, resp, id_, hid, pid):
6712
        admin_control(req)
6713
        if not id_.isdigit() or int(id_) <= 0:
6714
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6715
                                   description='API.INVALID_MICROGRID_ID')
6716
        if not hid.isdigit() or int(hid) <= 0:
6717
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6718
                                   description='API.INVALID_HEATPUMP_ID')
6719
        if not pid.isdigit() or int(pid) <= 0:
6720
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6721
                                   description='API.INVALID_POINT_ID')
6722
6723
        cnx = mysql.connector.connect(**config.myems_system_db)
6724
        cursor = cnx.cursor()
6725
6726
        cursor.execute(" SELECT name "
6727
                       " FROM tbl_microgrids_heatpumps "
6728
                       " WHERE microgrid_id = %s AND id = %s ", (id_, hid,))
6729
        if cursor.fetchone() is None:
6730
            cursor.close()
6731
            cnx.close()
6732
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6733
                                   description='API.MICROGRID_HEATPUMP_NOT_FOUND')
6734
6735
        cursor.execute(" SELECT name "
6736
                       " FROM tbl_points "
6737
                       " WHERE id = %s ", (pid,))
6738
        if cursor.fetchone() is None:
6739
            cursor.close()
6740
            cnx.close()
6741
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6742
                                   description='API.POINT_NOT_FOUND')
6743
6744
        cursor.execute(" SELECT id "
6745
                       " FROM tbl_microgrids_heatpumps_points "
6746
                       " WHERE heatpump_id = %s AND point_id = %s ", (hid, pid))
6747
        if cursor.fetchone() is None:
6748
            cursor.close()
6749
            cnx.close()
6750
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6751
                                   description='API.HEATPUMP_POINT_RELATION_NOT_FOUND')
6752
6753
        cursor.execute(" DELETE FROM tbl_microgrids_heatpumps_points "
6754
                       " WHERE heatpump_id = %s AND point_id = %s ", (hid, pid))
6755
        cnx.commit()
6756
6757
        cursor.close()
6758
        cnx.close()
6759
6760
        resp.status = falcon.HTTP_204
6761
6762 View Code Duplication
class MicrogridLoadPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6763
    def __init__(self):
6764
        pass
6765
6766
    @staticmethod
6767
    def on_options(req, resp, id_, lid):
6768
        _ = req
6769
        resp.status = falcon.HTTP_200
6770
        _ = id_
6771
        _ = lid
6772
6773
    @staticmethod
6774
    def on_get(req, resp, id_, lid):
6775
        if 'API-KEY' not in req.headers or \
6776
                not isinstance(req.headers['API-KEY'], str) or \
6777
                len(str.strip(req.headers['API-KEY'])) == 0:
6778
            access_control(req)
6779
        else:
6780
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
6781
        if not id_.isdigit() or int(id_) <= 0:
6782
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6783
                                   description='API.INVALID_MICROGRID_ID')
6784
        if not lid.isdigit() or int(lid) <= 0:
6785
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6786
                                   description='API.INVALID_LOAD_ID')
6787
6788
        cnx = mysql.connector.connect(**config.myems_system_db)
6789
        cursor = cnx.cursor()
6790
6791
        cursor.execute(" SELECT name "
6792
                       " FROM tbl_microgrids_loads "
6793
                       " WHERE microgrid_id = %s AND id = %s ", (id_, lid,))
6794
        if cursor.fetchone() is None:
6795
            cursor.close()
6796
            cnx.close()
6797
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6798
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
6799
6800
        query = (" SELECT p.id, p.name, "
6801
                 "        ds.id, ds.name, ds.uuid, "
6802
                 "        p.address "
6803
                 " FROM tbl_points p, tbl_microgrids_loads_points mp, tbl_data_sources ds "
6804
                 " WHERE mp.load_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
6805
                 " ORDER BY p.name ")
6806
        cursor.execute(query, (lid,))
6807
        rows = cursor.fetchall()
6808
6809
        result = list()
6810
        if rows is not None and len(rows) > 0:
6811
            for row in rows:
6812
                meta_result = {"id": row[0], "name": row[1],
6813
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
6814
                               "address": row[5]}
6815
                result.append(meta_result)
6816
6817
        resp.text = json.dumps(result)
6818
6819
    @staticmethod
6820
    @user_logger
6821
    def on_post(req, resp, id_, lid):
6822
        admin_control(req)
6823
        try:
6824
            raw_json = req.stream.read().decode('utf-8')
6825
        except Exception as ex:
6826
            print(str(ex))
6827
            raise falcon.HTTPError(status=falcon.HTTP_400,
6828
                                   title='API.BAD_REQUEST',
6829
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
6830
6831
        if not id_.isdigit() or int(id_) <= 0:
6832
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6833
                                   description='API.INVALID_MICROGRID_ID')
6834
        if not lid.isdigit() or int(lid) <= 0:
6835
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6836
                                   description='API.INVALID_LOAD_ID')
6837
6838
        new_values = json.loads(raw_json)
6839
        cnx = mysql.connector.connect(**config.myems_system_db)
6840
        cursor = cnx.cursor()
6841
6842
        cursor.execute(" SELECT name "
6843
                       " FROM tbl_microgrids_loads "
6844
                       " WHERE microgrid_id = %s AND id = %s ", (id_, lid,))
6845
        if cursor.fetchone() is None:
6846
            cursor.close()
6847
            cnx.close()
6848
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6849
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
6850
6851
        cursor.execute(" SELECT name, object_type "
6852
                       " FROM tbl_points "
6853
                       " WHERE id = %s ", (new_values['data']['point_id'],))
6854
        row = cursor.fetchone()
6855
        if row is None:
6856
            cursor.close()
6857
            cnx.close()
6858
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6859
                                   description='API.POINT_NOT_FOUND')
6860
6861
        query = (" SELECT id "
6862
                 " FROM tbl_microgrids_loads_points "
6863
                 " WHERE load_id = %s AND point_id = %s")
6864
        cursor.execute(query, (lid, new_values['data']['point_id'],))
6865
        if cursor.fetchone() is not None:
6866
            cursor.close()
6867
            cnx.close()
6868
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
6869
                                   description='API.LOAD_POINT_RELATION_EXISTS')
6870
6871
        add_row = (" INSERT INTO tbl_microgrids_loads_points (load_id, point_id) "
6872
                   " VALUES (%s, %s) ")
6873
        cursor.execute(add_row, (lid, new_values['data']['point_id'],))
6874
        cnx.commit()
6875
        cursor.close()
6876
        cnx.close()
6877
6878
        resp.status = falcon.HTTP_201
6879
        resp.location = '/microgrids/' + str(id_) + '/loads/' + str(lid) + '/points/' + \
6880
                        str(new_values['data']['point_id'])
6881
6882
6883 View Code Duplication
class MicrogridLoadPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6884
    def __init__(self):
6885
        pass
6886
6887
    @staticmethod
6888
    def on_options(req, resp, id_, lid, pid):
6889
        _ = req
6890
        resp.status = falcon.HTTP_200
6891
        _ = id_
6892
        _ = lid
6893
        _ = pid
6894
6895
    @staticmethod
6896
    @user_logger
6897
    def on_delete(req, resp, id_, lid, pid):
6898
        admin_control(req)
6899
        if not id_.isdigit() or int(id_) <= 0:
6900
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6901
                                   description='API.INVALID_MICROGRID_ID')
6902
        if not lid.isdigit() or int(lid) <= 0:
6903
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6904
                                   description='API.INVALID_LOAD_ID')
6905
        if not pid.isdigit() or int(pid) <= 0:
6906
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6907
                                   description='API.INVALID_POINT_ID')
6908
6909
        cnx = mysql.connector.connect(**config.myems_system_db)
6910
        cursor = cnx.cursor()
6911
6912
        cursor.execute(" SELECT name "
6913
                       " FROM tbl_microgrids_loads "
6914
                       " WHERE microgrid_id = %s AND id = %s ", (id_, lid,))
6915
        if cursor.fetchone() is None:
6916
            cursor.close()
6917
            cnx.close()
6918
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6919
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
6920
6921
        cursor.execute(" SELECT name "
6922
                       " FROM tbl_points "
6923
                       " WHERE id = %s ", (pid,))
6924
        if cursor.fetchone() is None:
6925
            cursor.close()
6926
            cnx.close()
6927
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6928
                                   description='API.POINT_NOT_FOUND')
6929
6930
        cursor.execute(" SELECT id "
6931
                       " FROM tbl_microgrids_loads_points "
6932
                       " WHERE load_id = %s AND point_id = %s ", (lid, pid))
6933
        if cursor.fetchone() is None:
6934
            cursor.close()
6935
            cnx.close()
6936
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6937
                                   description='API.LOAD_POINT_RELATION_NOT_FOUND')
6938
6939
        cursor.execute(" DELETE FROM tbl_microgrids_loads_points "
6940
                       " WHERE load_id = %s AND point_id = %s ", (lid, pid))
6941
        cnx.commit()
6942
6943
        cursor.close()
6944
        cnx.close()
6945
6946
        resp.status = falcon.HTTP_204
6947
6948 View Code Duplication
class MicrogridPhotovoltaicPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6949
    def __init__(self):
6950
        pass
6951
6952
    @staticmethod
6953
    def on_options(req, resp, id_, pvid):
6954
        _ = req
6955
        resp.status = falcon.HTTP_200
6956
        _ = id_
6957
        _ = pvid
6958
6959
    @staticmethod
6960
    def on_get(req, resp, id_, pvid):
6961
        if 'API-KEY' not in req.headers or \
6962
                not isinstance(req.headers['API-KEY'], str) or \
6963
                len(str.strip(req.headers['API-KEY'])) == 0:
6964
            access_control(req)
6965
        else:
6966
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
6967
        if not id_.isdigit() or int(id_) <= 0:
6968
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6969
                                   description='API.INVALID_MICROGRID_ID')
6970
        if not pvid.isdigit() or int(pvid) <= 0:
6971
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
6972
                                   description='API.INVALID_PHOTOVOLTAIC_ID')
6973
6974
        cnx = mysql.connector.connect(**config.myems_system_db)
6975
        cursor = cnx.cursor()
6976
6977
        cursor.execute(" SELECT name "
6978
                       " FROM tbl_microgrids_photovoltaics "
6979
                       " WHERE microgrid_id = %s AND id = %s ", (id_, pvid,))
6980
        if cursor.fetchone() is None:
6981
            cursor.close()
6982
            cnx.close()
6983
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
6984
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
6985
6986
        query = (" SELECT p.id, p.name, "
6987
                 "        ds.id, ds.name, ds.uuid, "
6988
                 "        p.address "
6989
                 " FROM tbl_points p, tbl_microgrids_pvs_points mp, tbl_data_sources ds "
6990
                 " WHERE mp.pv_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
6991
                 " ORDER BY p.name ")
6992
        cursor.execute(query, (pvid,))
6993
        rows = cursor.fetchall()
6994
6995
        result = list()
6996
        if rows is not None and len(rows) > 0:
6997
            for row in rows:
6998
                meta_result = {"id": row[0], "name": row[1],
6999
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
7000
                               "address": row[5]}
7001
                result.append(meta_result)
7002
7003
        resp.text = json.dumps(result)
7004
7005
    @staticmethod
7006
    @user_logger
7007
    def on_post(req, resp, id_, pvid):
7008
        admin_control(req)
7009
        try:
7010
            raw_json = req.stream.read().decode('utf-8')
7011
        except Exception as ex:
7012
            print(str(ex))
7013
            raise falcon.HTTPError(status=falcon.HTTP_400,
7014
                                   title='API.BAD_REQUEST',
7015
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
7016
7017
        if not id_.isdigit() or int(id_) <= 0:
7018
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7019
                                   description='API.INVALID_MICROGRID_ID')
7020
        if not pvid.isdigit() or int(pvid) <= 0:
7021
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7022
                                   description='API.INVALID_PHOTOVOLTAIC_ID')
7023
7024
        new_values = json.loads(raw_json)
7025
        cnx = mysql.connector.connect(**config.myems_system_db)
7026
        cursor = cnx.cursor()
7027
7028
        cursor.execute(" SELECT name "
7029
                       " FROM tbl_microgrids_photovoltaics "
7030
                       " WHERE microgrid_id = %s AND id = %s ", (id_, pvid,))
7031
        if cursor.fetchone() is None:
7032
            cursor.close()
7033
            cnx.close()
7034
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7035
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
7036
7037
        cursor.execute(" SELECT name, object_type "
7038
                       " FROM tbl_points "
7039
                       " WHERE id = %s ", (new_values['data']['point_id'],))
7040
        row = cursor.fetchone()
7041
        if row is None:
7042
            cursor.close()
7043
            cnx.close()
7044
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7045
                                   description='API.POINT_NOT_FOUND')
7046
7047
        query = (" SELECT id "
7048
                 " FROM tbl_microgrids_pvs_points "
7049
                 " WHERE pv_id = %s AND point_id = %s")
7050
        cursor.execute(query, (pvid, new_values['data']['point_id'],))
7051
        if cursor.fetchone() is not None:
7052
            cursor.close()
7053
            cnx.close()
7054
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
7055
                                   description='API.PHOTOVOLTAIC_POINT_RELATION_EXISTS')
7056
7057
        add_row = (" INSERT INTO tbl_microgrids_pvs_points (pv_id, point_id) "
7058
                   " VALUES (%s, %s) ")
7059
        cursor.execute(add_row, (pvid, new_values['data']['point_id'],))
7060
        cnx.commit()
7061
        cursor.close()
7062
        cnx.close()
7063
7064
        resp.status = falcon.HTTP_201
7065
        resp.location = '/microgrids/' + str(id_) + '/photovoltaics/' + str(pvid) + '/points/' + \
7066
                        str(new_values['data']['point_id'])
7067
7068
7069 View Code Duplication
class MicrogridPhotovoltaicPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
7070
    def __init__(self):
7071
        pass
7072
7073
    @staticmethod
7074
    def on_options(req, resp, id_, pvid, pid):
7075
        _ = req
7076
        resp.status = falcon.HTTP_200
7077
        _ = id_
7078
        _ = pvid
7079
        _ = pid
7080
7081
    @staticmethod
7082
    @user_logger
7083
    def on_delete(req, resp, id_, pvid, pid):
7084
        admin_control(req)
7085
        if not id_.isdigit() or int(id_) <= 0:
7086
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7087
                                   description='API.INVALID_MICROGRID_ID')
7088
        if not pvid.isdigit() or int(pvid) <= 0:
7089
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7090
                                   description='API.INVALID_PHOTOVOLTAIC_ID')
7091
        if not pid.isdigit() or int(pid) <= 0:
7092
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7093
                                   description='API.INVALID_POINT_ID')
7094
7095
        cnx = mysql.connector.connect(**config.myems_system_db)
7096
        cursor = cnx.cursor()
7097
7098
        cursor.execute(" SELECT name "
7099
                       " FROM tbl_microgrids_photovoltaics "
7100
                       " WHERE microgrid_id = %s AND id = %s ", (id_, pvid,))
7101
        if cursor.fetchone() is None:
7102
            cursor.close()
7103
            cnx.close()
7104
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7105
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
7106
7107
        cursor.execute(" SELECT name "
7108
                       " FROM tbl_points "
7109
                       " WHERE id = %s ", (pid,))
7110
        if cursor.fetchone() is None:
7111
            cursor.close()
7112
            cnx.close()
7113
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7114
                                   description='API.POINT_NOT_FOUND')
7115
7116
        cursor.execute(" SELECT id "
7117
                       " FROM tbl_microgrids_pvs_points "
7118
                       " WHERE pv_id = %s AND point_id = %s ", (pvid, pid))
7119
        if cursor.fetchone() is None:
7120
            cursor.close()
7121
            cnx.close()
7122
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7123
                                   description='API.PHOTOVOLTAIC_POINT_RELATION_NOT_FOUND')
7124
7125
        cursor.execute(" DELETE FROM tbl_microgrids_pvs_points "
7126
                       " WHERE pv_id = %s AND point_id = %s ", (pvid, pid))
7127
        cnx.commit()
7128
7129
        cursor.close()
7130
        cnx.close()
7131
7132
        resp.status = falcon.HTTP_204
7133
7134 View Code Duplication
class MicrogridPowerConversionSystemPointCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
7135
    def __init__(self):
7136
        pass
7137
7138
    @staticmethod
7139
    def on_options(req, resp, id_, pcsid):
7140
        _ = req
7141
        resp.status = falcon.HTTP_200
7142
        _ = id_
7143
        _ = pcsid
7144
7145
    @staticmethod
7146
    def on_get(req, resp, id_, pcsid):
7147
        if 'API-KEY' not in req.headers or \
7148
                not isinstance(req.headers['API-KEY'], str) or \
7149
                len(str.strip(req.headers['API-KEY'])) == 0:
7150
            access_control(req)
7151
        else:
7152
            api_key_control(req)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable api_key_control does not seem to be defined.
Loading history...
7153
        if not id_.isdigit() or int(id_) <= 0:
7154
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7155
                                   description='API.INVALID_MICROGRID_ID')
7156
        if not pcsid.isdigit() or int(pcsid) <= 0:
7157
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7158
                                   description='API.INVALID_POWER_CONVERSION_SYSTEM_ID')
7159
7160
        cnx = mysql.connector.connect(**config.myems_system_db)
7161
        cursor = cnx.cursor()
7162
7163
        cursor.execute(" SELECT name "
7164
                       " FROM tbl_microgrids_power_conversion_systems "
7165
                       " WHERE microgrid_id = %s AND id = %s ", (id_, pcsid,))
7166
        if cursor.fetchone() is None:
7167
            cursor.close()
7168
            cnx.close()
7169
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7170
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
7171
7172
        query = (" SELECT p.id, p.name, "
7173
                 "        ds.id, ds.name, ds.uuid, "
7174
                 "        p.address "
7175
                 " FROM tbl_points p, tbl_microgrids_pcses_points mp, tbl_data_sources ds "
7176
                 " WHERE mp.pcs_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
7177
                 " ORDER BY p.name ")
7178
        cursor.execute(query, (pcsid,))
7179
        rows = cursor.fetchall()
7180
7181
        result = list()
7182
        if rows is not None and len(rows) > 0:
7183
            for row in rows:
7184
                meta_result = {"id": row[0], "name": row[1],
7185
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
7186
                               "address": row[5]}
7187
                result.append(meta_result)
7188
7189
        resp.text = json.dumps(result)
7190
7191
    @staticmethod
7192
    @user_logger
7193
    def on_post(req, resp, id_, pcsid):
7194
        admin_control(req)
7195
        try:
7196
            raw_json = req.stream.read().decode('utf-8')
7197
        except Exception as ex:
7198
            print(str(ex))
7199
            raise falcon.HTTPError(status=falcon.HTTP_400,
7200
                                   title='API.BAD_REQUEST',
7201
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
7202
7203
        if not id_.isdigit() or int(id_) <= 0:
7204
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7205
                                   description='API.INVALID_MICROGRID_ID')
7206
        if not pcsid.isdigit() or int(pcsid) <= 0:
7207
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7208
                                   description='API.INVALID_POWER_CONVERSION_SYSTEM_ID')
7209
7210
        new_values = json.loads(raw_json)
7211
        cnx = mysql.connector.connect(**config.myems_system_db)
7212
        cursor = cnx.cursor()
7213
7214
        cursor.execute(" SELECT name "
7215
                       " FROM tbl_microgrids_power_conversion_systems "
7216
                       " WHERE microgrid_id = %s AND id = %s ", (id_, pcsid,))
7217
        if cursor.fetchone() is None:
7218
            cursor.close()
7219
            cnx.close()
7220
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7221
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
7222
7223
        cursor.execute(" SELECT name, object_type "
7224
                       " FROM tbl_points "
7225
                       " WHERE id = %s ", (new_values['data']['point_id'],))
7226
        row = cursor.fetchone()
7227
        if row is None:
7228
            cursor.close()
7229
            cnx.close()
7230
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7231
                                   description='API.POINT_NOT_FOUND')
7232
7233
        query = (" SELECT id "
7234
                 " FROM tbl_microgrids_pcses_points "
7235
                 " WHERE pcs_id = %s AND point_id = %s")
7236
        cursor.execute(query, (pcsid, new_values['data']['point_id'],))
7237
        if cursor.fetchone() is not None:
7238
            cursor.close()
7239
            cnx.close()
7240
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
7241
                                   description='API.POWER_CONVERSION_SYSTEM_POINT_RELATION_EXISTS')
7242
7243
        add_row = (" INSERT INTO tbl_microgrids_pcses_points (pcs_id, point_id) "
7244
                   " VALUES (%s, %s) ")
7245
        cursor.execute(add_row, (pcsid, new_values['data']['point_id'],))
7246
        cnx.commit()
7247
        cursor.close()
7248
        cnx.close()
7249
7250
        resp.status = falcon.HTTP_201
7251
        resp.location = '/microgrids/' + str(id_) + '/powerconversionsystems/' + str(pcsid) + '/points/' + \
7252
                        str(new_values['data']['point_id'])
7253
7254
7255 View Code Duplication
class MicrogridPowerConversionSystemPointItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
7256
    def __init__(self):
7257
        pass
7258
7259
    @staticmethod
7260
    def on_options(req, resp, id_, pcsid, pid):
7261
        _ = req
7262
        resp.status = falcon.HTTP_200
7263
        _ = id_
7264
        _ = pcsid
7265
        _ = pid
7266
7267
    @staticmethod
7268
    @user_logger
7269
    def on_delete(req, resp, id_, pcsid, pid):
7270
        admin_control(req)
7271
        if not id_.isdigit() or int(id_) <= 0:
7272
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7273
                                   description='API.INVALID_MICROGRID_ID')
7274
        if not pcsid.isdigit() or int(pcsid) <= 0:
7275
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7276
                                   description='API.INVALID_POWER_CONVERSION_SYSTEM_ID')
7277
        if not pid.isdigit() or int(pid) <= 0:
7278
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
7279
                                   description='API.INVALID_POINT_ID')
7280
7281
        cnx = mysql.connector.connect(**config.myems_system_db)
7282
        cursor = cnx.cursor()
7283
7284
        cursor.execute(" SELECT name "
7285
                       " FROM tbl_microgrids_power_conversion_systems "
7286
                       " WHERE microgrid_id = %s AND id = %s ", (id_, pcsid,))
7287
        if cursor.fetchone() is None:
7288
            cursor.close()
7289
            cnx.close()
7290
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7291
                                   description='API.MICROGRID_POWER_CONVERSION_SYSTEM_NOT_FOUND')
7292
7293
        cursor.execute(" SELECT name "
7294
                       " FROM tbl_points "
7295
                       " WHERE id = %s ", (pid,))
7296
        if cursor.fetchone() is None:
7297
            cursor.close()
7298
            cnx.close()
7299
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7300
                                   description='API.POINT_NOT_FOUND')
7301
7302
        cursor.execute(" SELECT id "
7303
                       " FROM tbl_microgrids_pcses_points "
7304
                       " WHERE pcs_id = %s AND point_id = %s ", (pcsid, pid))
7305
        if cursor.fetchone() is None:
7306
            cursor.close()
7307
            cnx.close()
7308
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
7309
                                   description='API.POWER_CONVERSION_SYSTEM_POINT_RELATION_NOT_FOUND')
7310
7311
        cursor.execute(" DELETE FROM tbl_microgrids_pcses_points "
7312
                       " WHERE pcs_id = %s AND point_id = %s ", (pcsid, pid))
7313
        cnx.commit()
7314
7315
        cursor.close()
7316
        cnx.close()
7317
7318
        resp.status = falcon.HTTP_204
7319