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

reports.energystoragepowerstationdetailsload   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 205
Duplicated Lines 95.61 %

Importance

Changes 0
Metric Value
wmc 41
eloc 127
dl 196
loc 205
rs 9.1199
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Reporting.on_options() 3 3 1
F Reporting.on_get() 176 176 39
A Reporting.__init__() 3 3 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like reports.energystoragepowerstationdetailsload 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
from datetime import datetime, timedelta
2
import falcon
3
import mysql.connector
4
import simplejson as json
5
from core.useractivity import access_control, api_key_control
6
import config
7
8
9 View Code Duplication
class Reporting:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
10
    def __init__(self):
11
        """Initializes Class"""
12
        pass
13
14
    @staticmethod
15
    def on_options(req, resp, id_):
16
        resp.status = falcon.HTTP_200
17
18
    ####################################################################################################################
19
    # PROCEDURES
20
    # Step 1: valid parameters
21
    # Step 2: query the energy storage power station
22
    # Step 3: query associated containers
23
    # Step 4: query analog points latest values
24
    # Step 5: query energy points latest values
25
    # Step 6: query digital points latest values
26
    # Step 7: query the points of loads
27
    # Step 8: construct the report
28
    ####################################################################################################################
29
    @staticmethod
30
    def on_get(req, resp, id_):
31
        if 'API-KEY' not in req.headers or \
32
                not isinstance(req.headers['API-KEY'], str) or \
33
                len(str.strip(req.headers['API-KEY'])) == 0:
34
            access_control(req)
35
        else:
36
            api_key_control(req)
37
38
        ################################################################################################################
39
        # Step 1: valid parameters
40
        ################################################################################################################
41
        if not id_.isdigit() or int(id_) <= 0:
42
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
43
                                   description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')
44
        energy_storage_power_station_id = id_
45
        ################################################################################################################
46
        # Step 2: query the energy storage power station
47
        ################################################################################################################
48
        cnx_system = mysql.connector.connect(**config.myems_system_db)
49
        cursor_system = cnx_system.cursor()
50
51
        cnx_historical = mysql.connector.connect(**config.myems_historical_db)
52
        cursor_historical = cnx_historical.cursor()
53
54
        if energy_storage_power_station_id is not None:
55
            query = (" SELECT id, name, uuid "
56
                     " FROM tbl_energy_storage_power_stations "
57
                     " WHERE id = %s ")
58
            cursor_system.execute(query, (energy_storage_power_station_id,))
59
            row = cursor_system.fetchone()
60
61
        if row is None:
0 ignored issues
show
introduced by
The variable row does not seem to be defined in case energy_storage_power_station_id is not None on line 54 is False. Are you sure this can never be the case?
Loading history...
62
            cursor_system.close()
63
            cnx_system.close()
64
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
65
                                   description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
66
        else:
67
            energy_storage_power_station_id = row[0]
68
            meta_result = {"id": row[0],
69
                           "name": row[1],
70
                           "uuid": row[2]}
71
        # query all points
72
        query = (" SELECT id, name, units, description "
73
                 " FROM tbl_points ")
74
        cursor_system.execute(query)
75
        rows = cursor_system.fetchall()
76
77
        points_dict = dict()
78
        if rows is not None and len(rows) > 0:
79
            for row in rows:
80
                points_dict[row[0]] = [row[1], row[2], row[3]]
81
        ################################################################################################################
82
        # Step 3: query associated containers
83
        ################################################################################################################
84
        container_list = list()
85
        cursor_system.execute(" SELECT c.id, c.name, c.uuid "
86
                              " FROM tbl_energy_storage_power_stations_containers espsc, "
87
                              "      tbl_energy_storage_containers c "
88
                              " WHERE espsc.energy_storage_power_station_id = %s "
89
                              "      AND espsc.energy_storage_container_id = c.id ",
90
                              (energy_storage_power_station_id,))
91
        rows_containers = cursor_system.fetchall()
92
        if rows_containers is not None and len(rows_containers) > 0:
93
            for row_container in rows_containers:
94
                container_list.append({"id": row_container[0],
95
                                       "name": row_container[1],
96
                                       "uuid": row_container[2]})
97
        print('container_list:' + str(container_list))
98
99
        ################################################################################################################
100
        # Step 4: query analog points latest values
101
        ################################################################################################################
102
        latest_value_dict = dict()
103
        query = (" SELECT point_id, actual_value "
104
                 " FROM tbl_analog_value_latest "
105
                 " WHERE utc_date_time > %s ")
106
        cursor_historical.execute(query, (datetime.utcnow() - timedelta(minutes=60),))
107
        rows = cursor_historical.fetchall()
108
        if rows is not None and len(rows) > 0:
109
            for row in rows:
110
                latest_value_dict[row[0]] = [points_dict[row[0]][0],
111
                                             points_dict[row[0]][1],
112
                                             points_dict[row[0]][2],
113
                                             row[1]]
114
115
        ################################################################################################################
116
        # Step 5: query energy points latest values
117
        ################################################################################################################
118
        query = (" SELECT point_id, actual_value "
119
                 " FROM tbl_energy_value_latest "
120
                 " WHERE utc_date_time > %s ")
121
        cursor_historical.execute(query, (datetime.utcnow() - timedelta(minutes=60),))
122
        rows = cursor_historical.fetchall()
123
        if rows is not None and len(rows) > 0:
124
            for row in rows:
125
                latest_value_dict[row[0]] = [points_dict[row[0]][0],
126
                                             points_dict[row[0]][1],
127
                                             points_dict[row[0]][2],
128
                                             row[1]]
129
130
        ################################################################################################################
131
        # Step 6: query digital points latest values
132
        ################################################################################################################
133
        query = (" SELECT point_id, actual_value "
134
                 " FROM tbl_digital_value_latest "
135
                 " WHERE utc_date_time > %s ")
136
        cursor_historical.execute(query, (datetime.utcnow() - timedelta(minutes=60),))
137
        rows = cursor_historical.fetchall()
138
        if rows is not None and len(rows) > 0:
139
            for row in rows:
140
                latest_value_dict[row[0]] = [points_dict[row[0]][0],
141
                                             points_dict[row[0]][1],
142
                                             points_dict[row[0]][2],
143
                                             row[1]]
144
145
        ################################################################################################################
146
        # Step 7: query the points of loads
147
        ################################################################################################################
148
        # query all points with units
149
        query = (" SELECT id, units "
150
                 " FROM tbl_points ")
151
        cursor_system.execute(query)
152
        rows = cursor_system.fetchall()
153
154
        units_dict = dict()
155
        if rows is not None and len(rows) > 0:
156
            for row in rows:
157
                units_dict[row[0]] = row[1]
158
159
        # query load parameters
160
        load_list = list()
161
        for container in container_list:
162
            cursor_system.execute(" SELECT id, name, uuid "
163
                                  " FROM tbl_energy_storage_containers_loads "
164
                                  " WHERE energy_storage_container_id = %s "
165
                                  " ORDER BY id ",
166
                                  (container['id'],))
167
            rows_loads = cursor_system.fetchall()
168
            if rows_loads is not None and len(rows_loads) > 0:
169
                for row in rows_loads:
170
                    current_bms = dict()
171
                    current_bms['id'] = row[0]
172
                    current_bms['name'] = row[1]
173
                    current_bms['uuid'] = row[2]
174
                    current_bms['points'] = list()
175
                    load_list.append(current_bms)
176
177
            for index, load in enumerate(load_list):
178
                cursor_system.execute(" SELECT p.id "
179
                                      " FROM tbl_energy_storage_containers_loads_points bp, tbl_points p "
180
                                      " WHERE bp.load_id = %s AND bp.point_id = p.id "
181
                                      " ORDER BY bp.id ",
182
                                      (load['id'],))
183
                rows_points = cursor_system.fetchall()
184
                if rows_points is not None and len(rows_points) > 0:
185
                    point_list = list()
186
                    for row in rows_points:
187
                        point = latest_value_dict.get(row[0], None)
188
                        if point is not None:
189
                            point_list.append(point)
190
                    load_list[index]['points'] = point_list
191
192
        if cursor_system:
193
            cursor_system.close()
194
        if cnx_system:
195
            cnx_system.close()
196
197
        if cursor_historical:
198
            cursor_historical.close()
199
        if cnx_historical:
200
            cnx_historical.close()
201
        ################################################################################################################
202
        # Step 8: construct the report
203
        ################################################################################################################
204
        resp.text = json.dumps(load_list)
205