Code Duplication    Length = 135-139 lines in 6 locations

myems-api/core/combinedequipment.py 3 locations

@@ 1713-1851 (lines=139) @@
1710
        resp.status = falcon.HTTP_204
1711
1712
1713
class CombinedEquipmentOfflineMeterCollection:
1714
    def __init__(self):
1715
        """"Initializes CombinedEquipmentOfflineMeterCollection"""
1716
        pass
1717
1718
    @staticmethod
1719
    def on_options(req, resp, id_):
1720
        _=req
1721
        resp.status = falcon.HTTP_200
1722
        _=id_
1723
    @staticmethod
1724
    def on_get(req, resp, id_):
1725
        if 'API-KEY' not in req.headers or \
1726
                not isinstance(req.headers['API-KEY'], str) or \
1727
                len(str.strip(req.headers['API-KEY'])) == 0:
1728
            access_control(req)
1729
        else:
1730
            api_key_control(req)
1731
        if not id_.isdigit() or int(id_) <= 0:
1732
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1733
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
1734
1735
        cnx = mysql.connector.connect(**config.myems_system_db)
1736
        cursor = cnx.cursor()
1737
1738
        cursor.execute(" SELECT name "
1739
                       " FROM tbl_combined_equipments "
1740
                       " WHERE id = %s ", (id_,))
1741
        if cursor.fetchone() is None:
1742
            cursor.close()
1743
            cnx.close()
1744
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1745
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
1746
1747
        query = (" SELECT id, name, uuid "
1748
                 " FROM tbl_energy_categories ")
1749
        cursor.execute(query)
1750
        rows_energy_categories = cursor.fetchall()
1751
1752
        energy_category_dict = dict()
1753
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1754
            for row in rows_energy_categories:
1755
                energy_category_dict[row[0]] = {"id": row[0],
1756
                                                "name": row[1],
1757
                                                "uuid": row[2]}
1758
1759
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id, em.is_output "
1760
                 " FROM tbl_combined_equipments e, tbl_combined_equipments_offline_meters em, tbl_offline_meters m "
1761
                 " WHERE em.combined_equipment_id = e.id AND m.id = em.offline_meter_id AND e.id = %s "
1762
                 " ORDER BY m.id ")
1763
        cursor.execute(query, (id_,))
1764
        rows = cursor.fetchall()
1765
1766
        result = list()
1767
        if rows is not None and len(rows) > 0:
1768
            for row in rows:
1769
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1770
                               "energy_category": energy_category_dict.get(row[3], None),
1771
                               "is_output": bool(row[4])}
1772
                result.append(meta_result)
1773
1774
        cursor.close()
1775
        cnx.close()
1776
1777
        resp.text = json.dumps(result)
1778
1779
    @staticmethod
1780
    @user_logger
1781
    def on_post(req, resp, id_):
1782
        """Handles POST requests"""
1783
        admin_control(req)
1784
        try:
1785
            raw_json = req.stream.read().decode('utf-8')
1786
        except Exception as ex:
1787
            print(ex)
1788
            raise falcon.HTTPError(status=falcon.HTTP_400,
1789
                                   title='API.BAD_REQUEST',
1790
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1791
1792
        if not id_.isdigit() or int(id_) <= 0:
1793
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1794
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
1795
1796
        new_values = json.loads(raw_json)
1797
1798
        if 'offline_meter_id' not in new_values['data'].keys() or \
1799
                not isinstance(new_values['data']['offline_meter_id'], int) or \
1800
                new_values['data']['offline_meter_id'] <= 0:
1801
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1802
                                   description='API.INVALID_OFFLINE_METER_ID')
1803
        offline_meter_id = new_values['data']['offline_meter_id']
1804
1805
        if 'is_output' not in new_values['data'].keys() or \
1806
                not isinstance(new_values['data']['is_output'], bool):
1807
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1808
                                   description='API.INVALID_IS_OUTPUT_VALUE')
1809
        is_output = new_values['data']['is_output']
1810
1811
        cnx = mysql.connector.connect(**config.myems_system_db)
1812
        cursor = cnx.cursor()
1813
1814
        cursor.execute(" SELECT name "
1815
                       " from tbl_combined_equipments "
1816
                       " WHERE id = %s ", (id_,))
1817
        if cursor.fetchone() is None:
1818
            cursor.close()
1819
            cnx.close()
1820
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1821
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
1822
1823
        cursor.execute(" SELECT name "
1824
                       " FROM tbl_offline_meters "
1825
                       " WHERE id = %s ", (offline_meter_id,))
1826
        if cursor.fetchone() is None:
1827
            cursor.close()
1828
            cnx.close()
1829
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1830
                                   description='API.OFFLINE_METER_NOT_FOUND')
1831
1832
        query = (" SELECT id "
1833
                 " FROM tbl_combined_equipments_offline_meters "
1834
                 " WHERE combined_equipment_id = %s AND offline_meter_id = %s")
1835
        cursor.execute(query, (id_, offline_meter_id,))
1836
        if cursor.fetchone() is not None:
1837
            cursor.close()
1838
            cnx.close()
1839
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1840
                                   description='API.COMBINED_EQUIPMENT_OFFLINE_METER_RELATION_EXISTS')
1841
1842
        add_row = (" INSERT INTO tbl_combined_equipments_offline_meters "
1843
                   " (combined_equipment_id, offline_meter_id, is_output ) "
1844
                   " VALUES (%s, %s, %s) ")
1845
        cursor.execute(add_row, (id_, offline_meter_id, is_output))
1846
        cnx.commit()
1847
        cursor.close()
1848
        cnx.close()
1849
1850
        resp.status = falcon.HTTP_201
1851
        resp.location = '/combinedequipments/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
1852
1853
1854
class CombinedEquipmentOfflineMeterItem:
@@ 1916-2053 (lines=138) @@
1913
        resp.status = falcon.HTTP_204
1914
1915
1916
class CombinedEquipmentVirtualMeterCollection:
1917
    def __init__(self):
1918
        """"Initializes CombinedEquipmentVirtualMeterCollection"""
1919
        pass
1920
1921
    @staticmethod
1922
    def on_options(req, resp, id_):
1923
        _=req
1924
        resp.status = falcon.HTTP_200
1925
        _=id_
1926
    @staticmethod
1927
    def on_get(req, resp, id_):
1928
        if 'API-KEY' not in req.headers or \
1929
                not isinstance(req.headers['API-KEY'], str) or \
1930
                len(str.strip(req.headers['API-KEY'])) == 0:
1931
            access_control(req)
1932
        else:
1933
            api_key_control(req)
1934
        if not id_.isdigit() or int(id_) <= 0:
1935
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1936
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
1937
1938
        cnx = mysql.connector.connect(**config.myems_system_db)
1939
        cursor = cnx.cursor()
1940
1941
        cursor.execute(" SELECT name "
1942
                       " FROM tbl_combined_equipments "
1943
                       " WHERE id = %s ", (id_,))
1944
        if cursor.fetchone() is None:
1945
            cursor.close()
1946
            cnx.close()
1947
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1948
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
1949
1950
        query = (" SELECT id, name, uuid "
1951
                 " FROM tbl_energy_categories ")
1952
        cursor.execute(query)
1953
        rows_energy_categories = cursor.fetchall()
1954
1955
        energy_category_dict = dict()
1956
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1957
            for row in rows_energy_categories:
1958
                energy_category_dict[row[0]] = {"id": row[0],
1959
                                                "name": row[1],
1960
                                                "uuid": row[2]}
1961
1962
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id, em.is_output "
1963
                 " FROM tbl_combined_equipments e, tbl_combined_equipments_virtual_meters em, tbl_virtual_meters m "
1964
                 " WHERE em.combined_equipment_id = e.id AND m.id = em.virtual_meter_id AND e.id = %s "
1965
                 " ORDER BY m.id ")
1966
        cursor.execute(query, (id_,))
1967
        rows = cursor.fetchall()
1968
1969
        result = list()
1970
        if rows is not None and len(rows) > 0:
1971
            for row in rows:
1972
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1973
                               "energy_category": energy_category_dict.get(row[3], None),
1974
                               "is_output": bool(row[4])}
1975
                result.append(meta_result)
1976
1977
        cursor.close()
1978
        cnx.close()
1979
        resp.text = json.dumps(result)
1980
1981
    @staticmethod
1982
    @user_logger
1983
    def on_post(req, resp, id_):
1984
        """Handles POST requests"""
1985
        admin_control(req)
1986
        try:
1987
            raw_json = req.stream.read().decode('utf-8')
1988
        except Exception as ex:
1989
            print(ex)
1990
            raise falcon.HTTPError(status=falcon.HTTP_400,
1991
                                   title='API.BAD_REQUEST',
1992
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1993
1994
        if not id_.isdigit() or int(id_) <= 0:
1995
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1996
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
1997
1998
        new_values = json.loads(raw_json)
1999
2000
        if 'virtual_meter_id' not in new_values['data'].keys() or \
2001
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
2002
                new_values['data']['virtual_meter_id'] <= 0:
2003
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2004
                                   description='API.INVALID_VIRTUAL_METER_ID')
2005
        virtual_meter_id = new_values['data']['virtual_meter_id']
2006
2007
        if 'is_output' not in new_values['data'].keys() or \
2008
                not isinstance(new_values['data']['is_output'], bool):
2009
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2010
                                   description='API.INVALID_IS_OUTPUT_VALUE')
2011
        is_output = new_values['data']['is_output']
2012
2013
        cnx = mysql.connector.connect(**config.myems_system_db)
2014
        cursor = cnx.cursor()
2015
2016
        cursor.execute(" SELECT name "
2017
                       " from tbl_combined_equipments "
2018
                       " WHERE id = %s ", (id_,))
2019
        if cursor.fetchone() is None:
2020
            cursor.close()
2021
            cnx.close()
2022
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2023
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
2024
2025
        cursor.execute(" SELECT name "
2026
                       " FROM tbl_virtual_meters "
2027
                       " WHERE id = %s ", (virtual_meter_id,))
2028
        if cursor.fetchone() is None:
2029
            cursor.close()
2030
            cnx.close()
2031
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2032
                                   description='API.VIRTUAL_METER_NOT_FOUND')
2033
2034
        query = (" SELECT id "
2035
                 " FROM tbl_combined_equipments_virtual_meters "
2036
                 " WHERE combined_equipment_id = %s AND virtual_meter_id = %s")
2037
        cursor.execute(query, (id_, virtual_meter_id,))
2038
        if cursor.fetchone() is not None:
2039
            cursor.close()
2040
            cnx.close()
2041
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2042
                                   description='API.COMBINED_EQUIPMENT_VIRTUAL_METER_RELATION_EXISTS')
2043
2044
        add_row = (" INSERT INTO tbl_combined_equipments_virtual_meters "
2045
                   " (combined_equipment_id, virtual_meter_id, is_output ) "
2046
                   " VALUES (%s, %s, %s) ")
2047
        cursor.execute(add_row, (id_, virtual_meter_id, is_output))
2048
        cnx.commit()
2049
        cursor.close()
2050
        cnx.close()
2051
2052
        resp.status = falcon.HTTP_201
2053
        resp.location = '/combinedequipments/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
2054
2055
2056
class CombinedEquipmentVirtualMeterItem:
@@ 1511-1648 (lines=138) @@
1508
        resp.status = falcon.HTTP_200
1509
1510
1511
class CombinedEquipmentMeterCollection:
1512
    def __init__(self):
1513
        """"Initializes CombinedEquipmentMeterCollection"""
1514
        pass
1515
1516
    @staticmethod
1517
    def on_options(req, resp, id_):
1518
        _=req
1519
        resp.status = falcon.HTTP_200
1520
        _=id_
1521
    @staticmethod
1522
    def on_get(req, resp, id_):
1523
        if 'API-KEY' not in req.headers or \
1524
                not isinstance(req.headers['API-KEY'], str) or \
1525
                len(str.strip(req.headers['API-KEY'])) == 0:
1526
            access_control(req)
1527
        else:
1528
            api_key_control(req)
1529
        if not id_.isdigit() or int(id_) <= 0:
1530
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1531
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
1532
1533
        cnx = mysql.connector.connect(**config.myems_system_db)
1534
        cursor = cnx.cursor()
1535
1536
        cursor.execute(" SELECT name "
1537
                       " FROM tbl_combined_equipments "
1538
                       " WHERE id = %s ", (id_,))
1539
        if cursor.fetchone() is None:
1540
            cursor.close()
1541
            cnx.close()
1542
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1543
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
1544
1545
        query = (" SELECT id, name, uuid "
1546
                 " FROM tbl_energy_categories ")
1547
        cursor.execute(query)
1548
        rows_energy_categories = cursor.fetchall()
1549
1550
        energy_category_dict = dict()
1551
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1552
            for row in rows_energy_categories:
1553
                energy_category_dict[row[0]] = {"id": row[0],
1554
                                                "name": row[1],
1555
                                                "uuid": row[2]}
1556
1557
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id, em.is_output "
1558
                 " FROM tbl_combined_equipments e, tbl_combined_equipments_meters em, tbl_meters m "
1559
                 " WHERE em.combined_equipment_id = e.id AND m.id = em.meter_id AND e.id = %s "
1560
                 " ORDER BY m.id ")
1561
        cursor.execute(query, (id_,))
1562
        rows = cursor.fetchall()
1563
1564
        result = list()
1565
        if rows is not None and len(rows) > 0:
1566
            for row in rows:
1567
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1568
                               "energy_category": energy_category_dict.get(row[3], None),
1569
                               "is_output": bool(row[4])}
1570
                result.append(meta_result)
1571
1572
        cursor.close()
1573
        cnx.close()
1574
1575
        resp.text = json.dumps(result)
1576
1577
    @staticmethod
1578
    @user_logger
1579
    def on_post(req, resp, id_):
1580
        """Handles POST requests"""
1581
        admin_control(req)
1582
        try:
1583
            raw_json = req.stream.read().decode('utf-8')
1584
        except Exception as ex:
1585
            print(ex)
1586
            raise falcon.HTTPError(status=falcon.HTTP_400,
1587
                                   title='API.BAD_REQUEST',
1588
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1589
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_COMBINED_EQUIPMENT_ID')
1593
1594
        new_values = json.loads(raw_json)
1595
1596
        if 'meter_id' not in new_values['data'].keys() or \
1597
                not isinstance(new_values['data']['meter_id'], int) or \
1598
                new_values['data']['meter_id'] <= 0:
1599
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1600
                                   description='API.INVALID_METER_ID')
1601
        meter_id = new_values['data']['meter_id']
1602
1603
        if 'is_output' not in new_values['data'].keys() or \
1604
                not isinstance(new_values['data']['is_output'], bool):
1605
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1606
                                   description='API.INVALID_IS_OUTPUT_VALUE')
1607
        is_output = new_values['data']['is_output']
1608
1609
        cnx = mysql.connector.connect(**config.myems_system_db)
1610
        cursor = cnx.cursor()
1611
1612
        cursor.execute(" SELECT name "
1613
                       " from tbl_combined_equipments "
1614
                       " WHERE id = %s ", (id_,))
1615
        if cursor.fetchone() is None:
1616
            cursor.close()
1617
            cnx.close()
1618
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1619
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
1620
1621
        cursor.execute(" SELECT name "
1622
                       " FROM tbl_meters "
1623
                       " WHERE id = %s ", (meter_id,))
1624
        if cursor.fetchone() is None:
1625
            cursor.close()
1626
            cnx.close()
1627
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1628
                                   description='API.METER_NOT_FOUND')
1629
1630
        query = (" SELECT id "
1631
                 " FROM tbl_combined_equipments_meters "
1632
                 " WHERE combined_equipment_id = %s AND meter_id = %s")
1633
        cursor.execute(query, (id_, meter_id,))
1634
        if cursor.fetchone() is not None:
1635
            cursor.close()
1636
            cnx.close()
1637
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1638
                                   description='API.COMBINED_EQUIPMENT_METER_RELATION_EXISTS')
1639
1640
        add_row = (" INSERT INTO tbl_combined_equipments_meters (combined_equipment_id, meter_id, is_output ) "
1641
                   " VALUES (%s, %s, %s) ")
1642
        cursor.execute(add_row, (id_, meter_id, is_output))
1643
        cnx.commit()
1644
        cursor.close()
1645
        cnx.close()
1646
1647
        resp.status = falcon.HTTP_201
1648
        resp.location = '/combinedequipments/' + str(id_) + '/meters/' + str(meter_id)
1649
1650
1651
class CombinedEquipmentMeterItem:

myems-api/core/equipment.py 3 locations

@@ 1716-1850 (lines=135) @@
1713
        resp.status = falcon.HTTP_204
1714
1715
1716
class EquipmentVirtualMeterCollection:
1717
    def __init__(self):
1718
        """Initializes EquipmentVirtualMeterCollection"""
1719
        pass
1720
1721
    @staticmethod
1722
    def on_options(req, resp, id_):
1723
        resp.status = falcon.HTTP_200
1724
1725
    @staticmethod
1726
    def on_get(req, resp, id_):
1727
        if 'API-KEY' not in req.headers or \
1728
                not isinstance(req.headers['API-KEY'], str) or \
1729
                len(str.strip(req.headers['API-KEY'])) == 0:
1730
            access_control(req)
1731
        else:
1732
            api_key_control(req)
1733
        if not id_.isdigit() or int(id_) <= 0:
1734
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1735
                                   description='API.INVALID_EQUIPMENT_ID')
1736
1737
        cnx = mysql.connector.connect(**config.myems_system_db)
1738
        cursor = cnx.cursor()
1739
1740
        cursor.execute(" SELECT name "
1741
                       " FROM tbl_equipments "
1742
                       " WHERE id = %s ", (id_,))
1743
        if cursor.fetchone() is None:
1744
            cursor.close()
1745
            cnx.close()
1746
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1747
                                   description='API.EQUIPMENT_NOT_FOUND')
1748
1749
        query = (" SELECT id, name, uuid "
1750
                 " FROM tbl_energy_categories ")
1751
        cursor.execute(query)
1752
        rows_energy_categories = cursor.fetchall()
1753
1754
        energy_category_dict = dict()
1755
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1756
            for row in rows_energy_categories:
1757
                energy_category_dict[row[0]] = {"id": row[0],
1758
                                                "name": row[1],
1759
                                                "uuid": row[2]}
1760
1761
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id, em.is_output "
1762
                 " FROM tbl_equipments e, tbl_equipments_virtual_meters em, tbl_virtual_meters m "
1763
                 " WHERE em.equipment_id = e.id AND m.id = em.virtual_meter_id AND e.id = %s "
1764
                 " ORDER BY m.id ")
1765
        cursor.execute(query, (id_,))
1766
        rows = cursor.fetchall()
1767
1768
        result = list()
1769
        if rows is not None and len(rows) > 0:
1770
            for row in rows:
1771
                meta_result = {"id": row[0],
1772
                               "name": row[1],
1773
                               "uuid": row[2],
1774
                               "energy_category": energy_category_dict.get(row[3], None),
1775
                               "is_output": bool(row[4])}
1776
                result.append(meta_result)
1777
1778
        resp.text = json.dumps(result)
1779
1780
    @staticmethod
1781
    @user_logger
1782
    def on_post(req, resp, id_):
1783
        """Handles POST requests"""
1784
        admin_control(req)
1785
        try:
1786
            raw_json = req.stream.read().decode('utf-8')
1787
        except Exception as ex:
1788
            raise falcon.HTTPError(status=falcon.HTTP_400,
1789
                                   title='API.BAD_REQUEST',
1790
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1791
1792
        if not id_.isdigit() or int(id_) <= 0:
1793
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1794
                                   description='API.INVALID_EQUIPMENT_ID')
1795
1796
        new_values = json.loads(raw_json)
1797
1798
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1799
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1800
                new_values['data']['virtual_meter_id'] <= 0:
1801
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1802
                                   description='API.INVALID_VIRTUAL_METER_ID')
1803
        virtual_meter_id = new_values['data']['virtual_meter_id']
1804
1805
        if 'is_output' not in new_values['data'].keys() or \
1806
                not isinstance(new_values['data']['is_output'], bool):
1807
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1808
                                   description='API.INVALID_IS_OUTPUT_VALUE')
1809
        is_output = new_values['data']['is_output']
1810
1811
        cnx = mysql.connector.connect(**config.myems_system_db)
1812
        cursor = cnx.cursor()
1813
1814
        cursor.execute(" SELECT name "
1815
                       " from tbl_equipments "
1816
                       " WHERE id = %s ", (id_,))
1817
        if cursor.fetchone() is None:
1818
            cursor.close()
1819
            cnx.close()
1820
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1821
                                   description='API.EQUIPMENT_NOT_FOUND')
1822
1823
        cursor.execute(" SELECT name "
1824
                       " FROM tbl_virtual_meters "
1825
                       " WHERE id = %s ", (virtual_meter_id,))
1826
        if cursor.fetchone() is None:
1827
            cursor.close()
1828
            cnx.close()
1829
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1830
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1831
1832
        query = (" SELECT id " 
1833
                 " FROM tbl_equipments_virtual_meters "
1834
                 " WHERE equipment_id = %s AND virtual_meter_id = %s")
1835
        cursor.execute(query, (id_, virtual_meter_id,))
1836
        if cursor.fetchone() is not None:
1837
            cursor.close()
1838
            cnx.close()
1839
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1840
                                   description='API.EQUIPMENT_VIRTUAL_METER_RELATION_EXISTS')
1841
1842
        add_row = (" INSERT INTO tbl_equipments_virtual_meters (equipment_id, virtual_meter_id, is_output ) "
1843
                   " VALUES (%s, %s, %s) ")
1844
        cursor.execute(add_row, (id_, virtual_meter_id, is_output))
1845
        cnx.commit()
1846
        cursor.close()
1847
        cnx.close()
1848
1849
        resp.status = falcon.HTTP_201
1850
        resp.location = '/equipments/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1851
1852
1853
class EquipmentVirtualMeterItem:
@@ 1518-1652 (lines=135) @@
1515
        resp.status = falcon.HTTP_204
1516
1517
1518
class EquipmentOfflineMeterCollection:
1519
    def __init__(self):
1520
        """Initializes EquipmentOfflineMeterCollection"""
1521
        pass
1522
1523
    @staticmethod
1524
    def on_options(req, resp, id_):
1525
        resp.status = falcon.HTTP_200
1526
1527
    @staticmethod
1528
    def on_get(req, resp, id_):
1529
        if 'API-KEY' not in req.headers or \
1530
                not isinstance(req.headers['API-KEY'], str) or \
1531
                len(str.strip(req.headers['API-KEY'])) == 0:
1532
            access_control(req)
1533
        else:
1534
            api_key_control(req)
1535
        if not id_.isdigit() or int(id_) <= 0:
1536
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1537
                                   description='API.INVALID_EQUIPMENT_ID')
1538
1539
        cnx = mysql.connector.connect(**config.myems_system_db)
1540
        cursor = cnx.cursor()
1541
1542
        cursor.execute(" SELECT name "
1543
                       " FROM tbl_equipments "
1544
                       " WHERE id = %s ", (id_,))
1545
        if cursor.fetchone() is None:
1546
            cursor.close()
1547
            cnx.close()
1548
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1549
                                   description='API.EQUIPMENT_NOT_FOUND')
1550
1551
        query = (" SELECT id, name, uuid "
1552
                 " FROM tbl_energy_categories ")
1553
        cursor.execute(query)
1554
        rows_energy_categories = cursor.fetchall()
1555
1556
        energy_category_dict = dict()
1557
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1558
            for row in rows_energy_categories:
1559
                energy_category_dict[row[0]] = {"id": row[0],
1560
                                                "name": row[1],
1561
                                                "uuid": row[2]}
1562
1563
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id, em.is_output "
1564
                 " FROM tbl_equipments e, tbl_equipments_offline_meters em, tbl_offline_meters m "
1565
                 " WHERE em.equipment_id = e.id AND m.id = em.offline_meter_id AND e.id = %s "
1566
                 " ORDER BY m.id ")
1567
        cursor.execute(query, (id_,))
1568
        rows = cursor.fetchall()
1569
1570
        result = list()
1571
        if rows is not None and len(rows) > 0:
1572
            for row in rows:
1573
                meta_result = {"id": row[0],
1574
                               "name": row[1],
1575
                               "uuid": row[2],
1576
                               "energy_category": energy_category_dict.get(row[3], None),
1577
                               "is_output": bool(row[4])}
1578
                result.append(meta_result)
1579
1580
        resp.text = json.dumps(result)
1581
1582
    @staticmethod
1583
    @user_logger
1584
    def on_post(req, resp, id_):
1585
        """Handles POST requests"""
1586
        admin_control(req)
1587
        try:
1588
            raw_json = req.stream.read().decode('utf-8')
1589
        except Exception as ex:
1590
            raise falcon.HTTPError(status=falcon.HTTP_400,
1591
                                   title='API.BAD_REQUEST',
1592
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1593
1594
        if not id_.isdigit() or int(id_) <= 0:
1595
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1596
                                   description='API.INVALID_EQUIPMENT_ID')
1597
1598
        new_values = json.loads(raw_json)
1599
1600
        if 'offline_meter_id' not in new_values['data'].keys() or \
1601
                not isinstance(new_values['data']['offline_meter_id'], int) or \
1602
                new_values['data']['offline_meter_id'] <= 0:
1603
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1604
                                   description='API.INVALID_OFFLINE_METER_ID')
1605
        offline_meter_id = new_values['data']['offline_meter_id']
1606
1607
        if 'is_output' not in new_values['data'].keys() or \
1608
                not isinstance(new_values['data']['is_output'], bool):
1609
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1610
                                   description='API.INVALID_IS_OUTPUT_VALUE')
1611
        is_output = new_values['data']['is_output']
1612
1613
        cnx = mysql.connector.connect(**config.myems_system_db)
1614
        cursor = cnx.cursor()
1615
1616
        cursor.execute(" SELECT name "
1617
                       " from tbl_equipments "
1618
                       " WHERE id = %s ", (id_,))
1619
        if cursor.fetchone() is None:
1620
            cursor.close()
1621
            cnx.close()
1622
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1623
                                   description='API.EQUIPMENT_NOT_FOUND')
1624
1625
        cursor.execute(" SELECT name "
1626
                       " FROM tbl_offline_meters "
1627
                       " WHERE id = %s ", (offline_meter_id,))
1628
        if cursor.fetchone() is None:
1629
            cursor.close()
1630
            cnx.close()
1631
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1632
                                   description='API.OFFLINE_METER_NOT_FOUND')
1633
1634
        query = (" SELECT id " 
1635
                 " FROM tbl_equipments_offline_meters "
1636
                 " WHERE equipment_id = %s AND offline_meter_id = %s")
1637
        cursor.execute(query, (id_, offline_meter_id,))
1638
        if cursor.fetchone() is not None:
1639
            cursor.close()
1640
            cnx.close()
1641
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1642
                                   description='API.EQUIPMENT_OFFLINE_METER_RELATION_EXISTS')
1643
1644
        add_row = (" INSERT INTO tbl_equipments_offline_meters (equipment_id, offline_meter_id, is_output ) "
1645
                   " VALUES (%s, %s, %s) ")
1646
        cursor.execute(add_row, (id_, offline_meter_id, is_output))
1647
        cnx.commit()
1648
        cursor.close()
1649
        cnx.close()
1650
1651
        resp.status = falcon.HTTP_201
1652
        resp.location = '/equipments/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
1653
1654
1655
class EquipmentOfflineMeterItem:
@@ 1321-1455 (lines=135) @@
1318
        resp.status = falcon.HTTP_200
1319
1320
1321
class EquipmentMeterCollection:
1322
    def __init__(self):
1323
        """Initializes EquipmentMeterCollection"""
1324
        pass
1325
1326
    @staticmethod
1327
    def on_options(req, resp, id_):
1328
        resp.status = falcon.HTTP_200
1329
1330
    @staticmethod
1331
    def on_get(req, resp, id_):
1332
        if 'API-KEY' not in req.headers or \
1333
                not isinstance(req.headers['API-KEY'], str) or \
1334
                len(str.strip(req.headers['API-KEY'])) == 0:
1335
            access_control(req)
1336
        else:
1337
            api_key_control(req)
1338
        if not id_.isdigit() or int(id_) <= 0:
1339
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1340
                                   description='API.INVALID_EQUIPMENT_ID')
1341
1342
        cnx = mysql.connector.connect(**config.myems_system_db)
1343
        cursor = cnx.cursor()
1344
1345
        cursor.execute(" SELECT name "
1346
                       " FROM tbl_equipments "
1347
                       " WHERE id = %s ", (id_,))
1348
        if cursor.fetchone() is None:
1349
            cursor.close()
1350
            cnx.close()
1351
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1352
                                   description='API.EQUIPMENT_NOT_FOUND')
1353
1354
        query = (" SELECT id, name, uuid "
1355
                 " FROM tbl_energy_categories ")
1356
        cursor.execute(query)
1357
        rows_energy_categories = cursor.fetchall()
1358
1359
        energy_category_dict = dict()
1360
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1361
            for row in rows_energy_categories:
1362
                energy_category_dict[row[0]] = {"id": row[0],
1363
                                                "name": row[1],
1364
                                                "uuid": row[2]}
1365
1366
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id, em.is_output "
1367
                 " FROM tbl_equipments e, tbl_equipments_meters em, tbl_meters m "
1368
                 " WHERE em.equipment_id = e.id AND m.id = em.meter_id AND e.id = %s "
1369
                 " ORDER BY m.id ")
1370
        cursor.execute(query, (id_,))
1371
        rows = cursor.fetchall()
1372
1373
        result = list()
1374
        if rows is not None and len(rows) > 0:
1375
            for row in rows:
1376
                meta_result = {"id": row[0],
1377
                               "name": row[1],
1378
                               "uuid": row[2],
1379
                               "energy_category": energy_category_dict.get(row[3], None),
1380
                               "is_output": bool(row[4])}
1381
                result.append(meta_result)
1382
1383
        resp.text = json.dumps(result)
1384
1385
    @staticmethod
1386
    @user_logger
1387
    def on_post(req, resp, id_):
1388
        """Handles POST requests"""
1389
        admin_control(req)
1390
        try:
1391
            raw_json = req.stream.read().decode('utf-8')
1392
        except Exception as ex:
1393
            raise falcon.HTTPError(status=falcon.HTTP_400,
1394
                                   title='API.BAD_REQUEST',
1395
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1396
1397
        if not id_.isdigit() or int(id_) <= 0:
1398
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1399
                                   description='API.INVALID_EQUIPMENT_ID')
1400
1401
        new_values = json.loads(raw_json)
1402
1403
        if 'meter_id' not in new_values['data'].keys() or \
1404
                not isinstance(new_values['data']['meter_id'], int) or \
1405
                new_values['data']['meter_id'] <= 0:
1406
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1407
                                   description='API.INVALID_METER_ID')
1408
        meter_id = new_values['data']['meter_id']
1409
1410
        if 'is_output' not in new_values['data'].keys() or \
1411
                not isinstance(new_values['data']['is_output'], bool):
1412
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1413
                                   description='API.INVALID_IS_OUTPUT_VALUE')
1414
        is_output = new_values['data']['is_output']
1415
1416
        cnx = mysql.connector.connect(**config.myems_system_db)
1417
        cursor = cnx.cursor()
1418
1419
        cursor.execute(" SELECT name "
1420
                       " from tbl_equipments "
1421
                       " WHERE id = %s ", (id_,))
1422
        if cursor.fetchone() is None:
1423
            cursor.close()
1424
            cnx.close()
1425
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1426
                                   description='API.EQUIPMENT_NOT_FOUND')
1427
1428
        cursor.execute(" SELECT name "
1429
                       " FROM tbl_meters "
1430
                       " WHERE id = %s ", (meter_id,))
1431
        if cursor.fetchone() is None:
1432
            cursor.close()
1433
            cnx.close()
1434
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1435
                                   description='API.METER_NOT_FOUND')
1436
1437
        query = (" SELECT id " 
1438
                 " FROM tbl_equipments_meters "
1439
                 " WHERE equipment_id = %s AND meter_id = %s")
1440
        cursor.execute(query, (id_, meter_id,))
1441
        if cursor.fetchone() is not None:
1442
            cursor.close()
1443
            cnx.close()
1444
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1445
                                   description='API.EQUIPMENT_METER_RELATION_EXISTS')
1446
1447
        add_row = (" INSERT INTO tbl_equipments_meters (equipment_id, meter_id, is_output ) "
1448
                   " VALUES (%s, %s, %s) ")
1449
        cursor.execute(add_row, (id_, meter_id, is_output))
1450
        cnx.commit()
1451
        cursor.close()
1452
        cnx.close()
1453
1454
        resp.status = falcon.HTTP_201
1455
        resp.location = '/equipments/' + str(id_) + '/meters/' + str(meter_id)
1456
1457
1458
class EquipmentMeterItem: