Passed
Push — master ( 6bc2e1...0432bf )
by Guangyu
02:09 queued 11s
created

meterrealtime.Reporting.__init__()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 0
1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
import utilities
7
from decimal import *
8
9
10
class Reporting:
11
    @staticmethod
12
    def __init__():
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    ####################################################################################################################
20
    # PROCEDURES
21
    # Step 1: valid parameters
22
    # Step 2: query the meter and energy category
23
    # Step 3: query associated points
24
    # Step 4: query reporting period points trends
25
    # Step 5: query tariff data
26
    # Step 6: construct the report
27
    ####################################################################################################################
28
    @staticmethod
29
    def on_get(req, resp):
30
        print(req.params)
31
        meter_id = req.params.get('meterid')
32
33
        ################################################################################################################
34
        # Step 1: valid parameters
35
        ################################################################################################################
36
        if meter_id is None:
37
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
38
        else:
39
            meter_id = str.strip(meter_id)
40
            if not meter_id.isdigit() or int(meter_id) <= 0:
41
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID')
42
43
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
44
        if config.utc_offset[0] == '-':
45
            timezone_offset = -timezone_offset
46
47
        reporting_end_datetime_utc = datetime.utcnow()
48
        reporting_start_datetime_utc = reporting_end_datetime_utc - timedelta(minutes=60)
49
        ################################################################################################################
50
        # Step 2: query the meter and energy category
51
        ################################################################################################################
52
        cnx_system = mysql.connector.connect(**config.myems_system_db)
53
        cursor_system = cnx_system.cursor()
54
55
        cnx_historical = mysql.connector.connect(**config.myems_historical_db)
56
        cursor_historical = cnx_historical.cursor()
57
58
        cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, "
59
                              "        ec.name, ec.unit_of_measure "
60
                              " FROM tbl_meters m, tbl_energy_categories ec "
61
                              " WHERE m.id = %s AND m.energy_category_id = ec.id ", (meter_id,))
62
        row_meter = cursor_system.fetchone()
63
        if row_meter is None:
64
            if cursor_system:
65
                cursor_system.close()
66
            if cnx_system:
67
                cnx_system.disconnect()
68
69
            if cursor_historical:
70
                cursor_historical.close()
71
            if cnx_historical:
72
                cnx_historical.disconnect()
73
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND')
74
75
        meter = dict()
76
        meter['id'] = row_meter[0]
77
        meter['name'] = row_meter[1]
78
        meter['cost_center_id'] = row_meter[2]
79
        meter['energy_category_id'] = row_meter[3]
80
        meter['energy_category_name'] = row_meter[4]
81
        meter['unit_of_measure'] = row_meter[5]
82
83
        ################################################################################################################
84
        # Step 3: query associated points
85
        ################################################################################################################
86
        point_list = list()
87
        cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type  "
88
                              " FROM tbl_meters m, tbl_meters_points mp, tbl_points p "
89
                              " WHERE m.id = %s AND m.id = mp.meter_id AND mp.point_id = p.id "
90
                              " ORDER BY p.id ", (meter['id'],))
91
        rows_points = cursor_system.fetchall()
92
        if rows_points is not None and len(rows_points) > 0:
93
            for row in rows_points:
94
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
95
96
        ################################################################################################################
97
        # Step 7: query associated points data
98
        ################################################################################################################
99
        energy_value_data = dict()
100
        energy_value_data['name'] = None
101
        energy_value_data['timestamps'] = list()
102
        energy_value_data['values'] = list()
103
104
        parameters_data = dict()
105
        parameters_data['names'] = list()
106
        parameters_data['timestamps'] = list()
107
        parameters_data['values'] = list()
108
109
        for point in point_list:
110
            point_values = []
111
            point_timestamps = []
112
            if point['object_type'] == 'ANALOG_VALUE':
113
                query = (" SELECT utc_date_time, actual_value "
114
                         " FROM tbl_analog_value "
115
                         " WHERE point_id = %s "
116
                         "       AND utc_date_time BETWEEN %s AND %s "
117
                         " ORDER BY utc_date_time ")
118
                cursor_historical.execute(query, (point['id'],
119
                                                  reporting_start_datetime_utc,
120
                                                  reporting_end_datetime_utc))
121
                rows = cursor_historical.fetchall()
122
123
                if rows is not None and len(rows) > 0:
124
                    for row in rows:
125
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
126
                                                 timedelta(minutes=timezone_offset)
127
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
128
                        point_timestamps.append(current_datetime)
129
                        point_values.append(row[1])
130
131
            elif point['object_type'] == 'ENERGY_VALUE':
132
                energy_value_data['name'] = point['name']
133
                query = (" SELECT utc_date_time, actual_value "
134
                         " FROM tbl_energy_value "
135
                         " WHERE point_id = %s "
136
                         "       AND utc_date_time BETWEEN %s AND %s "
137
                         " ORDER BY utc_date_time ")
138
                cursor_historical.execute(query, (point['id'],
139
                                                  reporting_start_datetime_utc,
140
                                                  reporting_end_datetime_utc))
141
                rows = cursor_historical.fetchall()
142
143
                if rows is not None and len(rows) > 0:
144
145
                    for row in rows:
146
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
147
                                                 timedelta(minutes=timezone_offset)
148
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
149
                        energy_value_data['timestamps'].append(current_datetime)
150
                        energy_value_data['values'].append(row[1])
151
152
            elif point['object_type'] == 'DIGITAL_VALUE':
153
                query = (" SELECT utc_date_time, actual_value "
154
                         " FROM tbl_digital_value "
155
                         " WHERE point_id = %s "
156
                         "       AND utc_date_time BETWEEN %s AND %s ")
157
                cursor_historical.execute(query, (point['id'],
158
                                                  reporting_start_datetime_utc,
159
                                                  reporting_end_datetime_utc))
160
                rows = cursor_historical.fetchall()
161
162
                if rows is not None and len(rows) > 0:
163
                    for row in rows:
164
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
165
                                                 timedelta(minutes=timezone_offset)
166
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
167
                        point_timestamps.append(current_datetime)
168
                        point_values.append(row[1])
169
170
            parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
171
            parameters_data['timestamps'].append(point_timestamps)
172
            parameters_data['values'].append(point_values)
173
174
        ################################################################################################################
175
        # Step 6: construct the report
176
        ################################################################################################################
177
        if cursor_system:
178
            cursor_system.close()
179
        if cnx_system:
180
            cnx_system.disconnect()
181
182
        if cursor_historical:
183
            cursor_historical.close()
184
        if cnx_historical:
185
            cnx_historical.disconnect()
186
187
        result = {
188
            "meter": {
189
                "cost_center_id": meter['cost_center_id'],
190
                "energy_category_id": meter['energy_category_id'],
191
                "energy_category_name": meter['energy_category_name'],
192
                "unit_of_measure": meter['unit_of_measure'],
193
            },
194
            "energy_value": energy_value_data,
195
            "parameters": {
196
                "names": parameters_data['names'],
197
                "timestamps": parameters_data['timestamps'],
198
                "values": parameters_data['values']
199
            },
200
201
        }
202
203
        resp.body = json.dumps(result)
204