Code Duplication    Length = 208-211 lines in 2 locations

myems-api/core/microgrid.py 1 location

@@ 2148-2355 (lines=208) @@
2145
        resp.status = falcon.HTTP_200
2146
2147
2148
class MicrogridGridCollection:
2149
    def __init__(self):
2150
        """Initializes MicrogridGridCollection"""
2151
        pass
2152
2153
    @staticmethod
2154
    def on_options(req, resp, id_):
2155
        resp.status = falcon.HTTP_200
2156
2157
    @staticmethod
2158
    def on_get(req, resp, id_):
2159
        access_control(req)
2160
        if not id_.isdigit() or int(id_) <= 0:
2161
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2162
                                   description='API.INVALID_MICROGRID_ID')
2163
2164
        cnx = mysql.connector.connect(**config.myems_system_db)
2165
        cursor = cnx.cursor()
2166
2167
        cursor.execute(" SELECT name "
2168
                       " FROM tbl_microgrids "
2169
                       " WHERE id = %s ", (id_,))
2170
        if cursor.fetchone() is None:
2171
            cursor.close()
2172
            cnx.close()
2173
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2174
                                   description='API.MICROGRID_NOT_FOUND')
2175
2176
        # query meter dict
2177
        query = (" SELECT id, name, uuid "
2178
                 " FROM tbl_meters ")
2179
        cursor.execute(query)
2180
        rows_meters = cursor.fetchall()
2181
2182
        meter_dict = dict()
2183
        if rows_meters is not None and len(rows_meters) > 0:
2184
            for row in rows_meters:
2185
                meter_dict[row[0]] = {"id": row[0],
2186
                                      "name": row[1],
2187
                                      "uuid": row[2]}
2188
        # query point dict
2189
        query = (" SELECT id, name "
2190
                 " FROM tbl_points ")
2191
        cursor.execute(query)
2192
        rows_points = cursor.fetchall()
2193
2194
        point_dict = dict()
2195
        if rows_points is not None and len(rows_points) > 0:
2196
            for row in rows_points:
2197
                point_dict[row[0]] = {"id": row[0],
2198
                                      "name": row[1]}
2199
2200
        query = (" SELECT id, name, uuid, "
2201
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2202
                 " FROM tbl_microgrids_grids "
2203
                 " WHERE microgrid_id = %s "
2204
                 " ORDER BY name ")
2205
        cursor.execute(query, (id_,))
2206
        rows = cursor.fetchall()
2207
2208
        result = list()
2209
        if rows is not None and len(rows) > 0:
2210
            for row in rows:
2211
                meta_result = {"id": row[0],
2212
                               "name": row[1],
2213
                               "uuid": row[2],
2214
                               "power_point": point_dict.get(row[3]),
2215
                               "buy_meter": meter_dict.get(row[4]),
2216
                               "sell_meter": meter_dict.get(row[5]),
2217
                               "capacity": row[6]}
2218
                result.append(meta_result)
2219
2220
        resp.text = json.dumps(result)
2221
2222
    @staticmethod
2223
    @user_logger
2224
    def on_post(req, resp, id_):
2225
        """Handles POST requests"""
2226
        admin_control(req)
2227
        try:
2228
            raw_json = req.stream.read().decode('utf-8')
2229
        except Exception as ex:
2230
            raise falcon.HTTPError(status=falcon.HTTP_400,
2231
                                   title='API.BAD_REQUEST',
2232
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2233
        if not id_.isdigit() or int(id_) <= 0:
2234
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2235
                                   description='API.INVALID_MICROGRID_ID')
2236
2237
        cnx = mysql.connector.connect(**config.myems_system_db)
2238
        cursor = cnx.cursor()
2239
2240
        cursor.execute(" SELECT name "
2241
                       " FROM tbl_microgrids "
2242
                       " WHERE id = %s ", (id_,))
2243
        if cursor.fetchone() is None:
2244
            cursor.close()
2245
            cnx.close()
2246
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2247
                                   description='API.MICROGRID_NOT_FOUND')
2248
2249
        new_values = json.loads(raw_json)
2250
2251
        if 'name' not in new_values['data'].keys() or \
2252
                not isinstance(new_values['data']['name'], str) or \
2253
                len(str.strip(new_values['data']['name'])) == 0:
2254
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2255
                                   description='API.INVALID_MICROGRID_GRID_NAME')
2256
        name = str.strip(new_values['data']['name'])
2257
2258
        if 'power_point_id' not in new_values['data'].keys() or \
2259
                not isinstance(new_values['data']['power_point_id'], int) or \
2260
                new_values['data']['power_point_id'] <= 0:
2261
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2262
                                   description='API.INVALID_POWER_POINT_ID')
2263
        power_point_id = new_values['data']['power_point_id']
2264
2265
        if 'buy_meter_id' not in new_values['data'].keys() or \
2266
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2267
                new_values['data']['buy_meter_id'] <= 0:
2268
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2269
                                   description='API.INVALID_BUY_METER_ID')
2270
        buy_meter_id = new_values['data']['buy_meter_id']
2271
2272
        if 'sell_meter_id' not in new_values['data'].keys() or \
2273
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2274
                new_values['data']['sell_meter_id'] <= 0:
2275
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2276
                                   description='API.INVALID_SELL_METER_ID')
2277
        sell_meter_id = new_values['data']['sell_meter_id']
2278
2279
        if 'capacity' not in new_values['data'].keys() or \
2280
                not (isinstance(new_values['data']['capacity'], float) or
2281
                     isinstance(new_values['data']['capacity'], int)):
2282
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2283
                                   description='API.INVALID_CAPACITY')
2284
        capacity = float(new_values['data']['capacity'])
2285
2286
        cnx = mysql.connector.connect(**config.myems_system_db)
2287
        cursor = cnx.cursor()
2288
2289
        cursor.execute(" SELECT name "
2290
                       " FROM tbl_microgrids "
2291
                       " WHERE id = %s ",
2292
                       (id_,))
2293
        if cursor.fetchone() is None:
2294
            cursor.close()
2295
            cnx.close()
2296
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2297
                                   description='API.MICROGRID_NOT_FOUND')
2298
2299
        cursor.execute(" SELECT name "
2300
                       " FROM tbl_microgrids_grids "
2301
                       " WHERE microgrid_id = %s AND name = %s ",
2302
                       (id_, name,))
2303
        if cursor.fetchone() is not None:
2304
            cursor.close()
2305
            cnx.close()
2306
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2307
                                   description='API.MICROGRID_GRID_NAME_IS_ALREADY_IN_USE')
2308
2309
        cursor.execute(" SELECT name "
2310
                       " FROM tbl_points "
2311
                       " WHERE id = %s ",
2312
                       (power_point_id,))
2313
        if cursor.fetchone() is None:
2314
            cursor.close()
2315
            cnx.close()
2316
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2317
                                   description='API.POWER_POINT_NOT_FOUND')
2318
2319
        cursor.execute(" SELECT name "
2320
                       " FROM tbl_meters "
2321
                       " WHERE id = %s ",
2322
                       (buy_meter_id,))
2323
        if cursor.fetchone() is None:
2324
            cursor.close()
2325
            cnx.close()
2326
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2327
                                   description='API.BUY_METER_NOT_FOUND')
2328
2329
        cursor.execute(" SELECT name "
2330
                       " FROM tbl_meters "
2331
                       " WHERE id = %s ",
2332
                       (sell_meter_id,))
2333
        if cursor.fetchone() is None:
2334
            cursor.close()
2335
            cnx.close()
2336
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2337
                                   description='API.SELL_METER_NOT_FOUND')
2338
2339
        add_values = (" INSERT INTO tbl_microgrids_grids "
2340
                      "    (name, uuid, microgrid_id, power_point_id, buy_meter_id, sell_meter_id, capacity) "
2341
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2342
        cursor.execute(add_values, (name,
2343
                                    str(uuid.uuid4()),
2344
                                    id_,
2345
                                    power_point_id,
2346
                                    buy_meter_id,
2347
                                    sell_meter_id,
2348
                                    capacity))
2349
        new_id = cursor.lastrowid
2350
        cnx.commit()
2351
        cursor.close()
2352
        cnx.close()
2353
2354
        resp.status = falcon.HTTP_201
2355
        resp.location = '/microgrids/' + str(id_) + '/grids/' + str(new_id)
2356
2357
2358
class MicrogridGridItem:

myems-api/core/energystoragecontainer.py 1 location

@@ 2622-2832 (lines=211) @@
2619
        resp.status = falcon.HTTP_204
2620
2621
2622
class EnergyStorageContainerGridCollection:
2623
    def __init__(self):
2624
        """Initializes Class"""
2625
        pass
2626
2627
    @staticmethod
2628
    def on_options(req, resp, id_):
2629
        resp.status = falcon.HTTP_200
2630
2631
    @staticmethod
2632
    def on_get(req, resp, id_):
2633
        access_control(req)
2634
        if not id_.isdigit() or int(id_) <= 0:
2635
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2636
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2637
2638
        cnx = mysql.connector.connect(**config.myems_system_db)
2639
        cursor = cnx.cursor()
2640
2641
        cursor.execute(" SELECT name "
2642
                       " FROM tbl_energy_storage_containers "
2643
                       " WHERE id = %s ", (id_,))
2644
        if cursor.fetchone() is None:
2645
            cursor.close()
2646
            cnx.close()
2647
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2648
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2649
2650
        # query meter dict
2651
        query = (" SELECT id, name, uuid "
2652
                 " FROM tbl_meters ")
2653
        cursor.execute(query)
2654
        rows_meters = cursor.fetchall()
2655
2656
        meter_dict = dict()
2657
        if rows_meters is not None and len(rows_meters) > 0:
2658
            for row in rows_meters:
2659
                meter_dict[row[0]] = {"id": row[0],
2660
                                      "name": row[1],
2661
                                      "uuid": row[2]}
2662
        # query point dict
2663
        query = (" SELECT id, name "
2664
                 " FROM tbl_points ")
2665
        cursor.execute(query)
2666
        rows_points = cursor.fetchall()
2667
2668
        point_dict = dict()
2669
        if rows_points is not None and len(rows_points) > 0:
2670
            for row in rows_points:
2671
                point_dict[row[0]] = {"id": row[0],
2672
                                      "name": row[1]}
2673
2674
        query = (" SELECT id, name, uuid, "
2675
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2676
                 " FROM tbl_energy_storage_containers_grids "
2677
                 " WHERE energy_storage_container_id = %s "
2678
                 " ORDER BY name ")
2679
        cursor.execute(query, (id_,))
2680
        rows = cursor.fetchall()
2681
2682
        result = list()
2683
        if rows is not None and len(rows) > 0:
2684
            for row in rows:
2685
                meta_result = {"id": row[0],
2686
                               "name": row[1],
2687
                               "uuid": row[2],
2688
                               "power_point": point_dict.get(row[3]),
2689
                               "buy_meter": meter_dict.get(row[4]),
2690
                               "sell_meter": meter_dict.get(row[5]),
2691
                               "capacity": row[6]
2692
                               }
2693
                result.append(meta_result)
2694
2695
        resp.text = json.dumps(result)
2696
2697
    @staticmethod
2698
    @user_logger
2699
    def on_post(req, resp, id_):
2700
        """Handles POST requests"""
2701
        admin_control(req)
2702
        try:
2703
            raw_json = req.stream.read().decode('utf-8')
2704
        except Exception as ex:
2705
            raise falcon.HTTPError(status=falcon.HTTP_400,
2706
                                   title='API.BAD_REQUEST',
2707
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2708
        if not id_.isdigit() or int(id_) <= 0:
2709
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2710
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2711
2712
        cnx = mysql.connector.connect(**config.myems_system_db)
2713
        cursor = cnx.cursor()
2714
2715
        cursor.execute(" SELECT name "
2716
                       " FROM tbl_energy_storage_containers "
2717
                       " WHERE id = %s ", (id_,))
2718
        if cursor.fetchone() is None:
2719
            cursor.close()
2720
            cnx.close()
2721
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2722
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2723
2724
        new_values = json.loads(raw_json)
2725
2726
        if 'name' not in new_values['data'].keys() or \
2727
                not isinstance(new_values['data']['name'], str) or \
2728
                len(str.strip(new_values['data']['name'])) == 0:
2729
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2730
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_GRID_NAME')
2731
        name = str.strip(new_values['data']['name'])
2732
2733
        if 'power_point_id' not in new_values['data'].keys() or \
2734
                not isinstance(new_values['data']['power_point_id'], int) or \
2735
                new_values['data']['power_point_id'] <= 0:
2736
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2737
                                   description='API.INVALID_POWER_POINT_ID')
2738
        power_point_id = new_values['data']['power_point_id']
2739
2740
        if 'buy_meter_id' not in new_values['data'].keys() or \
2741
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2742
                new_values['data']['buy_meter_id'] <= 0:
2743
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2744
                                   description='API.INVALID_BUY_METER_ID')
2745
        buy_meter_id = new_values['data']['buy_meter_id']
2746
2747
        if 'sell_meter_id' not in new_values['data'].keys() or \
2748
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2749
                new_values['data']['sell_meter_id'] <= 0:
2750
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2751
                                   description='API.INVALID_SELL_METER_ID')
2752
        sell_meter_id = new_values['data']['sell_meter_id']
2753
2754
        if 'capacity' not in new_values['data'].keys() or \
2755
                not (isinstance(new_values['data']['capacity'], float) or
2756
                     isinstance(new_values['data']['capacity'], int)):
2757
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2758
                                   description='API.INVALID_CAPACITY')
2759
        capacity = Decimal(new_values['data']['capacity'])
2760
2761
        cnx = mysql.connector.connect(**config.myems_system_db)
2762
        cursor = cnx.cursor()
2763
2764
        cursor.execute(" SELECT name "
2765
                       " FROM tbl_energy_storage_containers "
2766
                       " WHERE id = %s ",
2767
                       (id_,))
2768
        if cursor.fetchone() is None:
2769
            cursor.close()
2770
            cnx.close()
2771
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2772
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2773
2774
        cursor.execute(" SELECT name "
2775
                       " FROM tbl_energy_storage_containers_grids "
2776
                       " WHERE energy_storage_container_id = %s AND name = %s ",
2777
                       (id_, name,))
2778
        if cursor.fetchone() is not None:
2779
            cursor.close()
2780
            cnx.close()
2781
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2782
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NAME_IS_ALREADY_IN_USE')
2783
2784
        cursor.execute(" SELECT name "
2785
                       " FROM tbl_points "
2786
                       " WHERE id = %s ",
2787
                       (power_point_id,))
2788
        if cursor.fetchone() is None:
2789
            cursor.close()
2790
            cnx.close()
2791
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2792
                                   description='API.POWER_POINT_NOT_FOUND')
2793
2794
        cursor.execute(" SELECT name "
2795
                       " FROM tbl_meters "
2796
                       " WHERE id = %s ",
2797
                       (buy_meter_id,))
2798
        if cursor.fetchone() is None:
2799
            cursor.close()
2800
            cnx.close()
2801
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2802
                                   description='API.BUY_METER_NOT_FOUND')
2803
2804
        cursor.execute(" SELECT name "
2805
                       " FROM tbl_meters "
2806
                       " WHERE id = %s ",
2807
                       (sell_meter_id,))
2808
        if cursor.fetchone() is None:
2809
            cursor.close()
2810
            cnx.close()
2811
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2812
                                   description='API.SELL_METER_NOT_FOUND')
2813
2814
        add_values = (" INSERT INTO tbl_energy_storage_containers_grids "
2815
                      "    (name, uuid, energy_storage_container_id, power_point_id, "
2816
                      "     buy_meter_id, sell_meter_id, capacity) "
2817
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2818
        cursor.execute(add_values, (name,
2819
                                    str(uuid.uuid4()),
2820
                                    id_,
2821
                                    power_point_id,
2822
                                    buy_meter_id,
2823
                                    sell_meter_id,
2824
                                    capacity
2825
                                    ))
2826
        new_id = cursor.lastrowid
2827
        cnx.commit()
2828
        cursor.close()
2829
        cnx.close()
2830
2831
        resp.status = falcon.HTTP_201
2832
        resp.location = '/energystoragecontainers/' + str(id_) + '/grids/' + str(new_id)
2833
2834
2835
class EnergyStorageContainerGridItem: