Code Duplication    Length = 246-249 lines in 3 locations

myems-api/core/microgrid.py 2 locations

@@ 1936-2182 (lines=247) @@
1933
        resp.location = '/microgrids/' + str(id_) + '/generators/' + str(new_id)
1934
1935
1936
class MicrogridGeneratorItem:
1937
    def __init__(self):
1938
        """Initializes MicrogridGeneratorItem"""
1939
        pass
1940
1941
    @staticmethod
1942
    def on_options(req, resp, id_, gid):
1943
        _ = req
1944
        resp.status = falcon.HTTP_200
1945
        _ = id_
1946
1947
    @staticmethod
1948
    def on_get(req, resp, id_, gid):
1949
        access_control(req)
1950
        if not id_.isdigit() or int(id_) <= 0:
1951
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1952
                                   description='API.INVALID_MICROGRID_ID')
1953
        if not gid.isdigit() or int(gid) <= 0:
1954
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1955
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
1956
1957
        cnx = mysql.connector.connect(**config.myems_system_db)
1958
        cursor = cnx.cursor()
1959
1960
        cursor.execute(" SELECT name "
1961
                       " FROM tbl_microgrids "
1962
                       " WHERE id = %s ", (id_,))
1963
        if cursor.fetchone() is None:
1964
            cursor.close()
1965
            cnx.close()
1966
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1967
                                   description='API.MICROGRID_NOT_FOUND')
1968
1969
        # query microgrid dict
1970
        query = (" SELECT id, name, uuid "
1971
                 " FROM tbl_microgrids ")
1972
        cursor.execute(query)
1973
        rows_microgrids = cursor.fetchall()
1974
1975
        microgrid_dict = dict()
1976
        if rows_microgrids is not None and len(rows_microgrids) > 0:
1977
            for row in rows_microgrids:
1978
                microgrid_dict[row[0]] = {"id": row[0],
1979
                                          "name": row[1],
1980
                                          "uuid": row[2]}
1981
        # query meter dict
1982
        query = (" SELECT id, name, uuid "
1983
                 " FROM tbl_meters ")
1984
        cursor.execute(query)
1985
        rows_meters = cursor.fetchall()
1986
1987
        meter_dict = dict()
1988
        if rows_meters is not None and len(rows_meters) > 0:
1989
            for row in rows_meters:
1990
                meter_dict[row[0]] = {"id": row[0],
1991
                                      "name": row[1],
1992
                                      "uuid": row[2]}
1993
        # query point dict
1994
        query = (" SELECT id, name "
1995
                 " FROM tbl_points ")
1996
        cursor.execute(query)
1997
        rows_points = cursor.fetchall()
1998
1999
        point_dict = dict()
2000
        if rows_points is not None and len(rows_points) > 0:
2001
            for row in rows_points:
2002
                point_dict[row[0]] = {"id": row[0],
2003
                                      "name": row[1]}
2004
2005
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power "
2006
                 " FROM tbl_microgrids_generators "
2007
                 " WHERE id = %s ")
2008
        cursor.execute(query, (gid,))
2009
        row = cursor.fetchone()
2010
        cursor.close()
2011
        cnx.close()
2012
2013
        if row is None:
2014
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2015
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2016
        else:
2017
            meta_result = {"id": row[0],
2018
                           "name": row[1],
2019
                           "uuid": row[2],
2020
                           "microgrid": microgrid_dict.get(row[3]),
2021
                           "power_point": point_dict.get(row[4]),
2022
                           "meter": meter_dict.get(row[5]),
2023
                           "rated_output_power": row[6]}
2024
2025
        resp.text = json.dumps(meta_result)
2026
2027
    @staticmethod
2028
    @user_logger
2029
    def on_delete(req, resp, id_, gid):
2030
        admin_control(req)
2031
        if not id_.isdigit() or int(id_) <= 0:
2032
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2033
                                   description='API.INVALID_MICROGRID_ID')
2034
        if not gid.isdigit() or int(gid) <= 0:
2035
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2036
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
2037
2038
        cnx = mysql.connector.connect(**config.myems_system_db)
2039
        cursor = cnx.cursor()
2040
2041
        cursor.execute(" SELECT name "
2042
                       " FROM tbl_microgrids "
2043
                       " WHERE id = %s ", (id_,))
2044
        if cursor.fetchone() is None:
2045
            cursor.close()
2046
            cnx.close()
2047
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2048
                                   description='API.MICROGRID_NOT_FOUND')
2049
2050
        cursor.execute(" SELECT name "
2051
                       " FROM tbl_microgrids_generators "
2052
                       " WHERE id = %s ", (gid,))
2053
        if cursor.fetchone() is None:
2054
            cursor.close()
2055
            cnx.close()
2056
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2057
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2058
2059
        cursor.execute(" DELETE FROM tbl_microgrids_generators "
2060
                       " WHERE id = %s ", (gid,))
2061
        cnx.commit()
2062
2063
        cursor.close()
2064
        cnx.close()
2065
2066
        resp.status = falcon.HTTP_204
2067
2068
    @staticmethod
2069
    @user_logger
2070
    def on_put(req, resp, id_, gid):
2071
        """Handles PUT requests"""
2072
        admin_control(req)
2073
        try:
2074
            raw_json = req.stream.read().decode('utf-8')
2075
        except Exception as ex:
2076
            print(str(ex))
2077
            raise falcon.HTTPError(status=falcon.HTTP_400,
2078
                                   title='API.BAD_REQUEST',
2079
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2080
        if not id_.isdigit() or int(id_) <= 0:
2081
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2082
                                   description='API.INVALID_MICROGRID_ID')
2083
        if not gid.isdigit() or int(gid) <= 0:
2084
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2085
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
2086
2087
        new_values = json.loads(raw_json)
2088
2089
        if 'name' not in new_values['data'].keys() or \
2090
                not isinstance(new_values['data']['name'], str) or \
2091
                len(str.strip(new_values['data']['name'])) == 0:
2092
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2093
                                   description='API.INVALID_MICROGRID_GENERATOR_NAME')
2094
        name = str.strip(new_values['data']['name'])
2095
2096
        if 'power_point_id' not in new_values['data'].keys() or \
2097
                not isinstance(new_values['data']['power_point_id'], int) or \
2098
                new_values['data']['power_point_id'] <= 0:
2099
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2100
                                   description='API.INVALID_POWER_POINT_ID')
2101
        power_point_id = new_values['data']['power_point_id']
2102
2103
        if 'meter_id' not in new_values['data'].keys() or \
2104
                not isinstance(new_values['data']['meter_id'], int) or \
2105
                new_values['data']['meter_id'] <= 0:
2106
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2107
                                   description='API.INVALID_METER_ID')
2108
        meter_id = new_values['data']['meter_id']
2109
2110
        if 'rated_output_power' not in new_values['data'].keys() or \
2111
                not (isinstance(new_values['data']['rated_output_power'], float) or
2112
                     isinstance(new_values['data']['rated_output_power'], int)):
2113
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2114
                                   description='API.INVALID_RATED_OUTPUT_POWER')
2115
        rated_output_power = float(new_values['data']['rated_output_power'])
2116
2117
        cnx = mysql.connector.connect(**config.myems_system_db)
2118
        cursor = cnx.cursor()
2119
2120
        cursor.execute(" SELECT name "
2121
                       " FROM tbl_microgrids "
2122
                       " WHERE id = %s ", (id_,))
2123
        if cursor.fetchone() is None:
2124
            cursor.close()
2125
            cnx.close()
2126
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2127
                                   description='API.MICROGRID_NOT_FOUND')
2128
2129
        cursor.execute(" SELECT name "
2130
                       " FROM tbl_microgrids_generators "
2131
                       " WHERE id = %s ", (gid,))
2132
        if cursor.fetchone() is None:
2133
            cursor.close()
2134
            cnx.close()
2135
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2136
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2137
2138
        cursor.execute(" SELECT name "
2139
                       " FROM tbl_microgrids_generators "
2140
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
2141
                       (id_, name, gid))
2142
        if cursor.fetchone() is not None:
2143
            cursor.close()
2144
            cnx.close()
2145
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2146
                                   description='API.MICROGRID_GENERATOR_NAME_IS_ALREADY_IN_USE')
2147
2148
        cursor.execute(" SELECT name "
2149
                       " FROM tbl_points "
2150
                       " WHERE id = %s ",
2151
                       (power_point_id,))
2152
        if cursor.fetchone() is None:
2153
            cursor.close()
2154
            cnx.close()
2155
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2156
                                   description='API.POWER_POINT_NOT_FOUND')
2157
2158
        cursor.execute(" SELECT name "
2159
                       " FROM tbl_meters "
2160
                       " WHERE id = %s ",
2161
                       (meter_id,))
2162
        if cursor.fetchone() is None:
2163
            cursor.close()
2164
            cnx.close()
2165
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2166
                                   description='API.METER_NOT_FOUND')
2167
2168
        update_row = (" UPDATE tbl_microgrids_generators "
2169
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_output_power = %s "
2170
                      " WHERE id = %s ")
2171
        cursor.execute(update_row, (name,
2172
                                    id_,
2173
                                    power_point_id,
2174
                                    meter_id,
2175
                                    rated_output_power,
2176
                                    gid))
2177
        cnx.commit()
2178
2179
        cursor.close()
2180
        cnx.close()
2181
2182
        resp.status = falcon.HTTP_200
2183
2184
2185
class MicrogridGridCollection:
@@ 1494-1739 (lines=246) @@
1491
        resp.location = '/microgrids/' + id_ + '/evchargers/' + str(new_id)
1492
1493
1494
class MicrogridEVChargerItem:
1495
    def __init__(self):
1496
        """Initializes MicrogridEVChargerItem"""
1497
        pass
1498
1499
    @staticmethod
1500
    def on_options(req, resp, id_, eid):
1501
        _ = req
1502
        resp.status = falcon.HTTP_200
1503
        _ = id_
1504
1505
    @staticmethod
1506
    def on_get(req, resp, id_, eid):
1507
        access_control(req)
1508
        if not id_.isdigit() or int(id_) <= 0:
1509
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1510
                                   description='API.INVALID_MICROGRID_ID')
1511
        if not eid.isdigit() or int(eid) <= 0:
1512
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1513
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1514
1515
        cnx = mysql.connector.connect(**config.myems_system_db)
1516
        cursor = cnx.cursor()
1517
1518
        cursor.execute(" SELECT name "
1519
                       " FROM tbl_microgrids "
1520
                       " WHERE id = %s ", (id_,))
1521
        if cursor.fetchone() is None:
1522
            cursor.close()
1523
            cnx.close()
1524
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1525
                                   description='API.MICROGRID_NOT_FOUND')
1526
1527
        # query microgrid dict
1528
        query = (" SELECT id, name, uuid "
1529
                 " FROM tbl_microgrids ")
1530
        cursor.execute(query)
1531
        rows_microgrids = cursor.fetchall()
1532
1533
        microgrid_dict = dict()
1534
        if rows_microgrids is not None and len(rows_microgrids) > 0:
1535
            for row in rows_microgrids:
1536
                microgrid_dict[row[0]] = {"id": row[0],
1537
                                          "name": row[1],
1538
                                          "uuid": row[2]}
1539
        # query meter dict
1540
        query = (" SELECT id, name, uuid "
1541
                 " FROM tbl_meters ")
1542
        cursor.execute(query)
1543
        rows_meters = cursor.fetchall()
1544
1545
        meter_dict = dict()
1546
        if rows_meters is not None and len(rows_meters) > 0:
1547
            for row in rows_meters:
1548
                meter_dict[row[0]] = {"id": row[0],
1549
                                      "name": row[1],
1550
                                      "uuid": row[2]}
1551
        # query point dict
1552
        query = (" SELECT id, name "
1553
                 " FROM tbl_points ")
1554
        cursor.execute(query)
1555
        rows_points = cursor.fetchall()
1556
1557
        point_dict = dict()
1558
        if rows_points is not None and len(rows_points) > 0:
1559
            for row in rows_points:
1560
                point_dict[row[0]] = {"id": row[0],
1561
                                      "name": row[1]}
1562
1563
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power "
1564
                 " FROM tbl_microgrids_evchargers "
1565
                 " WHERE id = %s ")
1566
        cursor.execute(query, (eid,))
1567
        row = cursor.fetchone()
1568
        cursor.close()
1569
        cnx.close()
1570
1571
        if row is None:
1572
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1573
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1574
        else:
1575
            meta_result = {"id": row[0],
1576
                           "name": row[1],
1577
                           "uuid": row[2],
1578
                           "microgrid": microgrid_dict.get(row[3]),
1579
                           "power_point": point_dict.get(row[4]),
1580
                           "meter": meter_dict.get(row[5]),
1581
                           "rated_output_power": row[6]}
1582
1583
        resp.text = json.dumps(meta_result)
1584
1585
    @staticmethod
1586
    @user_logger
1587
    def on_delete(req, resp, id_, eid):
1588
        admin_control(req)
1589
        if not id_.isdigit() or int(id_) <= 0:
1590
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1591
                                   description='API.INVALID_MICROGRID_ID')
1592
        if not eid.isdigit() or int(eid) <= 0:
1593
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1594
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1595
        cnx = mysql.connector.connect(**config.myems_system_db)
1596
        cursor = cnx.cursor()
1597
1598
        cursor.execute(" SELECT name "
1599
                       " FROM tbl_microgrids "
1600
                       " WHERE id = %s ", (id_,))
1601
        if cursor.fetchone() is None:
1602
            cursor.close()
1603
            cnx.close()
1604
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1605
                                   description='API.MICROGRID_NOT_FOUND')
1606
1607
        cursor.execute(" SELECT name "
1608
                       " FROM tbl_microgrids_evchargers "
1609
                       " WHERE id = %s ", (eid,))
1610
        if cursor.fetchone() is None:
1611
            cursor.close()
1612
            cnx.close()
1613
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1614
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1615
1616
        cursor.execute(" DELETE FROM tbl_microgrids_evchargers "
1617
                       " WHERE id = %s ", (eid,))
1618
        cnx.commit()
1619
1620
        cursor.close()
1621
        cnx.close()
1622
1623
        resp.status = falcon.HTTP_204
1624
1625
    @staticmethod
1626
    @user_logger
1627
    def on_put(req, resp, id_, eid):
1628
        """Handles PUT requests"""
1629
        admin_control(req)
1630
        try:
1631
            raw_json = req.stream.read().decode('utf-8')
1632
        except Exception as ex:
1633
            print(str(ex))
1634
            raise falcon.HTTPError(status=falcon.HTTP_400,
1635
                                   title='API.BAD_REQUEST',
1636
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1637
        if not id_.isdigit() or int(id_) <= 0:
1638
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1639
                                   description='API.INVALID_MICROGRID_ID')
1640
        if not eid.isdigit() or int(eid) <= 0:
1641
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1642
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1643
1644
        new_values = json.loads(raw_json)
1645
1646
        if 'name' not in new_values['data'].keys() or \
1647
                not isinstance(new_values['data']['name'], str) or \
1648
                len(str.strip(new_values['data']['name'])) == 0:
1649
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1650
                                   description='API.INVALID_MICROGRID_EVCHARGER_NAME')
1651
        name = str.strip(new_values['data']['name'])
1652
1653
        if 'power_point_id' not in new_values['data'].keys() or \
1654
                not isinstance(new_values['data']['power_point_id'], int) or \
1655
                new_values['data']['power_point_id'] <= 0:
1656
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1657
                                   description='API.INVALID_POWER_POINT_ID')
1658
        power_point_id = new_values['data']['power_point_id']
1659
1660
        if 'meter_id' not in new_values['data'].keys() or \
1661
                not isinstance(new_values['data']['meter_id'], int) or \
1662
                new_values['data']['meter_id'] <= 0:
1663
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1664
                                   description='API.INVALID_METER_ID')
1665
        meter_id = new_values['data']['meter_id']
1666
1667
        if 'rated_output_power' not in new_values['data'].keys() or \
1668
                not (isinstance(new_values['data']['rated_output_power'], float) or
1669
                     isinstance(new_values['data']['rated_output_power'], int)):
1670
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1671
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1672
        rated_output_power = float(new_values['data']['rated_output_power'])
1673
1674
        cnx = mysql.connector.connect(**config.myems_system_db)
1675
        cursor = cnx.cursor()
1676
1677
        cursor.execute(" SELECT name "
1678
                       " FROM tbl_microgrids "
1679
                       " WHERE id = %s ", (id_,))
1680
        if cursor.fetchone() is None:
1681
            cursor.close()
1682
            cnx.close()
1683
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1684
                                   description='API.MICROGRID_NOT_FOUND')
1685
1686
        cursor.execute(" SELECT name "
1687
                       " FROM tbl_microgrids_evchargers "
1688
                       " WHERE id = %s ", (eid,))
1689
        if cursor.fetchone() is None:
1690
            cursor.close()
1691
            cnx.close()
1692
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1693
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1694
1695
        cursor.execute(" SELECT name "
1696
                       " FROM tbl_microgrids_evchargers "
1697
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
1698
                       (id_, name, eid))
1699
        if cursor.fetchone() is not None:
1700
            cursor.close()
1701
            cnx.close()
1702
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1703
                                   description='API.MICROGRID_EVCHARGER_NAME_IS_ALREADY_IN_USE')
1704
1705
        cursor.execute(" SELECT name "
1706
                       " FROM tbl_points "
1707
                       " WHERE id = %s ",
1708
                       (power_point_id,))
1709
        if cursor.fetchone() is None:
1710
            cursor.close()
1711
            cnx.close()
1712
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1713
                                   description='API.POWER_POINT_NOT_FOUND')
1714
1715
        cursor.execute(" SELECT name "
1716
                       " FROM tbl_meters "
1717
                       " WHERE id = %s ",
1718
                       (meter_id,))
1719
        if cursor.fetchone() is None:
1720
            cursor.close()
1721
            cnx.close()
1722
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1723
                                   description='API.METER_NOT_FOUND')
1724
1725
        update_row = (" UPDATE tbl_microgrids_evchargers "
1726
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_output_power = %s "
1727
                      " WHERE id = %s ")
1728
        cursor.execute(update_row, (name,
1729
                                    id_,
1730
                                    power_point_id,
1731
                                    meter_id,
1732
                                    rated_output_power,
1733
                                    eid))
1734
        cnx.commit()
1735
1736
        cursor.close()
1737
        cnx.close()
1738
1739
        resp.status = falcon.HTTP_200
1740
1741
1742
class MicrogridGeneratorCollection:

myems-api/core/energystoragecontainer.py 1 location

@@ 4026-4274 (lines=249) @@
4023
        resp.location = '/energystoragecontainers/' + str(id_) + '/loads/' + str(new_id)
4024
4025
4026
class EnergyStorageContainerLoadItem:
4027
    def __init__(self):
4028
        """Initializes Class"""
4029
        pass
4030
4031
    @staticmethod
4032
    def on_options(req, resp, id_, lid):
4033
        _ = req
4034
        resp.status = falcon.HTTP_200
4035
        _ = id_
4036
4037
    @staticmethod
4038
    def on_get(req, resp, id_, lid):
4039
        access_control(req)
4040
        if not id_.isdigit() or int(id_) <= 0:
4041
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4042
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4043
        if not lid.isdigit() or int(lid) <= 0:
4044
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4045
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_ID')
4046
4047
        cnx = mysql.connector.connect(**config.myems_system_db)
4048
        cursor = cnx.cursor()
4049
4050
        cursor.execute(" SELECT name "
4051
                       " FROM tbl_energy_storage_containers "
4052
                       " WHERE id = %s ", (id_,))
4053
        if cursor.fetchone() is None:
4054
            cursor.close()
4055
            cnx.close()
4056
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4057
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
4058
4059
        query = (" SELECT id, name, uuid "
4060
                 " FROM tbl_energy_storage_containers ")
4061
        cursor.execute(query)
4062
        rows_energystoragecontainers = cursor.fetchall()
4063
4064
        energy_storage_container_dict = dict()
4065
        if rows_energystoragecontainers is not None and len(rows_energystoragecontainers) > 0:
4066
            for row in rows_energystoragecontainers:
4067
                energy_storage_container_dict[row[0]] = {"id": row[0],
4068
                                                         "name": row[1],
4069
                                                         "uuid": row[2]}
4070
        # query meter dict
4071
        query = (" SELECT id, name, uuid "
4072
                 " FROM tbl_meters ")
4073
        cursor.execute(query)
4074
        rows_meters = cursor.fetchall()
4075
4076
        meter_dict = dict()
4077
        if rows_meters is not None and len(rows_meters) > 0:
4078
            for row in rows_meters:
4079
                meter_dict[row[0]] = {"id": row[0],
4080
                                      "name": row[1],
4081
                                      "uuid": row[2]}
4082
        # query point dict
4083
        query = (" SELECT id, name "
4084
                 " FROM tbl_points ")
4085
        cursor.execute(query)
4086
        rows_points = cursor.fetchall()
4087
4088
        point_dict = dict()
4089
        if rows_points is not None and len(rows_points) > 0:
4090
            for row in rows_points:
4091
                point_dict[row[0]] = {"id": row[0],
4092
                                      "name": row[1]}
4093
4094
        query = (" SELECT id, name, uuid, "
4095
                 "        energy_storage_container_id, power_point_id, meter_id, rated_input_power "
4096
                 " FROM tbl_energy_storage_containers_loads "
4097
                 " WHERE id = %s ")
4098
        cursor.execute(query, (lid,))
4099
        row = cursor.fetchone()
4100
        cursor.close()
4101
        cnx.close()
4102
4103
        if row is None:
4104
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4105
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
4106
        else:
4107
            meta_result = {"id": row[0],
4108
                           "name": row[1],
4109
                           "uuid": row[2],
4110
                           "energy_storage_container": energy_storage_container_dict.get(row[3]),
4111
                           "power_point": point_dict.get(row[4]),
4112
                           "meter": meter_dict.get(row[5]),
4113
                           "rated_input_power": row[6]
4114
                           }
4115
4116
        resp.text = json.dumps(meta_result)
4117
4118
    @staticmethod
4119
    @user_logger
4120
    def on_delete(req, resp, id_, lid):
4121
        admin_control(req)
4122
        if not id_.isdigit() or int(id_) <= 0:
4123
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4124
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4125
        if not lid.isdigit() or int(lid) <= 0:
4126
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4127
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_ID')
4128
4129
        cnx = mysql.connector.connect(**config.myems_system_db)
4130
        cursor = cnx.cursor()
4131
4132
        cursor.execute(" SELECT name "
4133
                       " FROM tbl_energy_storage_containers "
4134
                       " WHERE id = %s ", (id_,))
4135
        if cursor.fetchone() is None:
4136
            cursor.close()
4137
            cnx.close()
4138
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4139
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
4140
4141
        cursor.execute(" SELECT name "
4142
                       " FROM tbl_energy_storage_containers_loads "
4143
                       " WHERE id = %s ", (lid,))
4144
        if cursor.fetchone() is None:
4145
            cursor.close()
4146
            cnx.close()
4147
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4148
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
4149
4150
        cursor.execute(" DELETE FROM tbl_energy_storage_containers_loads "
4151
                       " WHERE id = %s ", (lid,))
4152
        cnx.commit()
4153
4154
        cursor.close()
4155
        cnx.close()
4156
4157
        resp.status = falcon.HTTP_204
4158
4159
    @staticmethod
4160
    @user_logger
4161
    def on_put(req, resp, id_, lid):
4162
        """Handles PUT requests"""
4163
        admin_control(req)
4164
        try:
4165
            raw_json = req.stream.read().decode('utf-8')
4166
        except Exception as ex:
4167
            print(str(ex))
4168
            raise falcon.HTTPError(status=falcon.HTTP_400,
4169
                                   title='API.BAD_REQUEST',
4170
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4171
        if not id_.isdigit() or int(id_) <= 0:
4172
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4173
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4174
        if not lid.isdigit() or int(lid) <= 0:
4175
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4176
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_ID')
4177
4178
        new_values = json.loads(raw_json)
4179
4180
        if 'name' not in new_values['data'].keys() or \
4181
                not isinstance(new_values['data']['name'], str) or \
4182
                len(str.strip(new_values['data']['name'])) == 0:
4183
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4184
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_NAME')
4185
        name = str.strip(new_values['data']['name'])
4186
4187
        if 'power_point_id' not in new_values['data'].keys() or \
4188
                not isinstance(new_values['data']['power_point_id'], int) or \
4189
                new_values['data']['power_point_id'] <= 0:
4190
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4191
                                   description='API.INVALID_POWER_POINT_ID')
4192
        power_point_id = new_values['data']['power_point_id']
4193
4194
        if 'meter_id' not in new_values['data'].keys() or \
4195
                not isinstance(new_values['data']['meter_id'], int) or \
4196
                new_values['data']['meter_id'] <= 0:
4197
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4198
                                   description='API.INVALID_METER_ID')
4199
        meter_id = new_values['data']['meter_id']
4200
4201
        if 'rated_input_power' not in new_values['data'].keys() or \
4202
                not (isinstance(new_values['data']['rated_input_power'], float) or
4203
                     isinstance(new_values['data']['rated_input_power'], int)):
4204
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4205
                                   description='API.INVALID_RATED_INPUT_POWER')
4206
        rated_input_power = Decimal(new_values['data']['rated_input_power'])
4207
4208
        cnx = mysql.connector.connect(**config.myems_system_db)
4209
        cursor = cnx.cursor()
4210
4211
        cursor.execute(" SELECT name "
4212
                       " FROM tbl_energy_storage_containers "
4213
                       " WHERE id = %s ", (id_,))
4214
        if cursor.fetchone() is None:
4215
            cursor.close()
4216
            cnx.close()
4217
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4218
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
4219
4220
        cursor.execute(" SELECT name "
4221
                       " FROM tbl_energy_storage_containers_loads "
4222
                       " WHERE id = %s ", (lid,))
4223
        if cursor.fetchone() is None:
4224
            cursor.close()
4225
            cnx.close()
4226
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4227
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
4228
4229
        cursor.execute(" SELECT name "
4230
                       " FROM tbl_energy_storage_containers_loads "
4231
                       " WHERE energy_storage_container_id = %s AND name = %s AND id != %s ",
4232
                       (id_, name, lid))
4233
        if cursor.fetchone() is not None:
4234
            cursor.close()
4235
            cnx.close()
4236
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4237
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NAME_IS_ALREADY_IN_USE')
4238
4239
        cursor.execute(" SELECT name "
4240
                       " FROM tbl_points "
4241
                       " WHERE id = %s ",
4242
                       (power_point_id,))
4243
        if cursor.fetchone() is None:
4244
            cursor.close()
4245
            cnx.close()
4246
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4247
                                   description='API.POWER_POINT_NOT_FOUND')
4248
4249
        cursor.execute(" SELECT name "
4250
                       " FROM tbl_meters "
4251
                       " WHERE id = %s ",
4252
                       (meter_id,))
4253
        if cursor.fetchone() is None:
4254
            cursor.close()
4255
            cnx.close()
4256
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4257
                                   description='API.METER_NOT_FOUND')
4258
4259
        update_row = (" UPDATE tbl_energy_storage_containers_loads "
4260
                      " SET name = %s, energy_storage_container_id = %s, power_point_id = %s, "
4261
                      "     meter_id = %s, rated_input_power = %s "
4262
                      " WHERE id = %s ")
4263
        cursor.execute(update_row, (name,
4264
                                    id_,
4265
                                    power_point_id,
4266
                                    meter_id,
4267
                                    rated_input_power,
4268
                                    lid))
4269
        cnx.commit()
4270
4271
        cursor.close()
4272
        cnx.close()
4273
4274
        resp.status = falcon.HTTP_200
4275
4276
4277
class EnergyStorageContainerLoadPointCollection: