Passed
Push — master ( 49640a...288f92 )
by
unknown
11:30 queued 17s
created

EnergyStorageContainerBatteryItem.on_delete()   B

Complexity

Conditions 7

Size

Total Lines 40
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

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