Passed
Push — master ( a3b41e...4d6f13 )
by
unknown
09:13
created

EnergyStorageContainerCollection.on_get()   D

Complexity

Conditions 13

Size

Total Lines 78
Code Lines 51

Duplication

Lines 12
Ratio 15.38 %

Importance

Changes 0
Metric Value
eloc 51
dl 12
loc 78
rs 4.2
c 0
b 0
f 0
cc 13
nop 2

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

Complexity

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

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

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