EnergyStorageContainerCommandCollection.on_post()   C
last analyzed

Complexity

Conditions 10

Size

Total Lines 65
Code Lines 50

Duplication

Lines 65
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 50
dl 65
loc 65
rs 5.8362
c 0
b 0
f 0
cc 10
nop 3

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