PhotovoltaicPowerStationCollection.on_post()   F
last analyzed

Complexity

Conditions 51

Size

Total Lines 187
Code Lines 153

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 153
dl 0
loc 187
rs 0
c 0
b 0
f 0
cc 51
nop 2

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

Complexity

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

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

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