Code Duplication    Length = 113-117 lines in 28 locations

myems-api/core/combinedequipment.py 2 locations

@@ 600-716 (lines=117) @@
597
        resp.location = '/combinedequipments/' + str(new_id)
598
599
600
class CombinedEquipmentEquipmentCollection:
601
    def __init__(self):
602
        """Initializes CombinedEquipmentEquipmentCollection"""
603
        pass
604
605
    @staticmethod
606
    def on_options(req, resp, id_):
607
        _=req
608
        resp.status = falcon.HTTP_200
609
        _=id_
610
    @staticmethod
611
    def on_get(req, resp, id_):
612
        if 'API-KEY' not in req.headers or \
613
                not isinstance(req.headers['API-KEY'], str) or \
614
                len(str.strip(req.headers['API-KEY'])) == 0:
615
            access_control(req)
616
        else:
617
            api_key_control(req)
618
        if not id_.isdigit() or int(id_) <= 0:
619
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
620
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
621
622
        cnx = mysql.connector.connect(**config.myems_system_db)
623
        cursor = cnx.cursor()
624
625
        cursor.execute(" SELECT name "
626
                       " FROM tbl_combined_equipments "
627
                       " WHERE id = %s ", (id_,))
628
        if cursor.fetchone() is None:
629
            cursor.close()
630
            cnx.close()
631
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
632
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
633
634
        query = (" SELECT e.id, e.name, e.uuid "
635
                 " FROM tbl_combined_equipments c, tbl_combined_equipments_equipments ce, tbl_equipments e "
636
                 " WHERE ce.combined_equipment_id = c.id AND e.id = ce.equipment_id AND c.id = %s "
637
                 " ORDER BY e.id ")
638
        cursor.execute(query, (id_,))
639
        rows = cursor.fetchall()
640
        cursor.close()
641
        cnx.close()
642
643
        result = list()
644
        if rows is not None and len(rows) > 0:
645
            for row in rows:
646
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
647
                result.append(meta_result)
648
649
        resp.text = json.dumps(result)
650
651
    @staticmethod
652
    @user_logger
653
    def on_post(req, resp, id_):
654
        """Handles POST requests"""
655
        admin_control(req)
656
        try:
657
            raw_json = req.stream.read().decode('utf-8')
658
        except Exception as ex:
659
            print(ex)
660
            raise falcon.HTTPError(status=falcon.HTTP_400,
661
                                   title='API.BAD_REQUEST',
662
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
663
664
        if not id_.isdigit() or int(id_) <= 0:
665
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
666
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
667
668
        new_values = json.loads(raw_json)
669
670
        if 'equipment_id' not in new_values['data'].keys() or \
671
                not isinstance(new_values['data']['equipment_id'], int) or \
672
                new_values['data']['equipment_id'] <= 0:
673
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
674
                                   description='API.INVALID_EQUIPMENT_ID')
675
        equipment_id = new_values['data']['equipment_id']
676
677
        cnx = mysql.connector.connect(**config.myems_system_db)
678
        cursor = cnx.cursor()
679
680
        cursor.execute(" SELECT name "
681
                       " from tbl_combined_equipments "
682
                       " WHERE id = %s ", (id_,))
683
        if cursor.fetchone() is None:
684
            cursor.close()
685
            cnx.close()
686
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
687
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
688
689
        cursor.execute(" SELECT name "
690
                       " FROM tbl_equipments "
691
                       " WHERE id = %s ", (equipment_id,))
692
        if cursor.fetchone() is None:
693
            cursor.close()
694
            cnx.close()
695
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
696
                                   description='API.EQUIPMENT_NOT_FOUND')
697
698
        query = (" SELECT id "
699
                 " FROM tbl_combined_equipments_equipments "
700
                 " WHERE combined_equipment_id = %s AND equipment_id = %s")
701
        cursor.execute(query, (id_, equipment_id,))
702
        if cursor.fetchone() is not None:
703
            cursor.close()
704
            cnx.close()
705
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
706
                                   description='API.COMBINED_EQUIPMENT_EQUIPMENT_RELATION_EXISTS')
707
708
        add_row = (" INSERT INTO tbl_combined_equipments_equipments (combined_equipment_id, equipment_id) "
709
                   " VALUES (%s, %s) ")
710
        cursor.execute(add_row, (id_, equipment_id,))
711
        cnx.commit()
712
        cursor.close()
713
        cnx.close()
714
715
        resp.status = falcon.HTTP_201
716
        resp.location = '/combinedequipments/' + str(id_) + '/equipments/' + str(equipment_id)
717
718
719
class CombinedEquipmentEquipmentItem:
@@ 2118-2232 (lines=115) @@
2115
        resp.status = falcon.HTTP_204
2116
2117
2118
class CombinedEquipmentCommandCollection:
2119
    def __init__(self):
2120
        """Initializes Class"""
2121
        pass
2122
2123
    @staticmethod
2124
    def on_options(req, resp, id_):
2125
        _=req
2126
        resp.status = falcon.HTTP_200
2127
        _=id_
2128
    @staticmethod
2129
    def on_get(req, resp, id_):
2130
        if 'API-KEY' not in req.headers or \
2131
                not isinstance(req.headers['API-KEY'], str) or \
2132
                len(str.strip(req.headers['API-KEY'])) == 0:
2133
            access_control(req)
2134
        else:
2135
            api_key_control(req)
2136
        if not id_.isdigit() or int(id_) <= 0:
2137
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2138
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
2139
2140
        cnx = mysql.connector.connect(**config.myems_system_db)
2141
        cursor = cnx.cursor()
2142
2143
        cursor.execute(" SELECT name "
2144
                       " FROM tbl_combined_equipments "
2145
                       " WHERE id = %s ", (id_,))
2146
        if cursor.fetchone() is None:
2147
            cursor.close()
2148
            cnx.close()
2149
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2150
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
2151
2152
        query = (" SELECT c.id, c.name, c.uuid "
2153
                 " FROM tbl_combined_equipments ce, tbl_combined_equipments_commands cec, tbl_commands c "
2154
                 " WHERE cec.combined_equipment_id = ce.id AND c.id = cec.command_id AND ce.id = %s "
2155
                 " ORDER BY c.id ")
2156
        cursor.execute(query, (id_,))
2157
        rows = cursor.fetchall()
2158
2159
        result = list()
2160
        if rows is not None and len(rows) > 0:
2161
            for row in rows:
2162
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2163
                result.append(meta_result)
2164
2165
        resp.text = json.dumps(result)
2166
2167
    @staticmethod
2168
    @user_logger
2169
    def on_post(req, resp, id_):
2170
        """Handles POST requests"""
2171
        admin_control(req)
2172
        try:
2173
            raw_json = req.stream.read().decode('utf-8')
2174
        except Exception as ex:
2175
            print(ex)
2176
            raise falcon.HTTPError(status=falcon.HTTP_400,
2177
                                   title='API.BAD_REQUEST',
2178
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2179
2180
        if not id_.isdigit() or int(id_) <= 0:
2181
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2182
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
2183
2184
        new_values = json.loads(raw_json)
2185
2186
        if 'command_id' not in new_values['data'].keys() or \
2187
                not isinstance(new_values['data']['command_id'], int) or \
2188
                new_values['data']['command_id'] <= 0:
2189
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2190
                                   description='API.INVALID_COMMAND_ID')
2191
        command_id = new_values['data']['command_id']
2192
2193
        cnx = mysql.connector.connect(**config.myems_system_db)
2194
        cursor = cnx.cursor()
2195
2196
        cursor.execute(" SELECT name "
2197
                       " from tbl_combined_equipments "
2198
                       " WHERE id = %s ", (id_,))
2199
        if cursor.fetchone() is None:
2200
            cursor.close()
2201
            cnx.close()
2202
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2203
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
2204
2205
        cursor.execute(" SELECT name "
2206
                       " FROM tbl_commands "
2207
                       " WHERE id = %s ", (command_id,))
2208
        if cursor.fetchone() is None:
2209
            cursor.close()
2210
            cnx.close()
2211
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2212
                                   description='API.COMMAND_NOT_FOUND')
2213
2214
        query = (" SELECT id " 
2215
                 " FROM tbl_combined_equipments_commands "
2216
                 " WHERE combined_equipment_id = %s AND command_id = %s")
2217
        cursor.execute(query, (id_, command_id,))
2218
        if cursor.fetchone() is not None:
2219
            cursor.close()
2220
            cnx.close()
2221
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2222
                                   description='API.COMBINED_EQUIPMENT_COMMAND_RELATION_EXISTS')
2223
2224
        add_row = (" INSERT INTO tbl_combined_equipments_commands (combined_equipment_id, command_id) "
2225
                   " VALUES (%s, %s) ")
2226
        cursor.execute(add_row, (id_, command_id,))
2227
        cnx.commit()
2228
        cursor.close()
2229
        cnx.close()
2230
2231
        resp.status = falcon.HTTP_201
2232
        resp.location = '/combinedequipments/' + str(id_) + '/commands/' + str(command_id)
2233
2234
2235
class CombinedEquipmentCommandItem:

myems-api/core/equipment.py 1 location

@@ 1914-2028 (lines=115) @@
1911
        resp.status = falcon.HTTP_204
1912
1913
1914
class EquipmentCommandCollection:
1915
    def __init__(self):
1916
        """Initializes Class"""
1917
        pass
1918
1919
    @staticmethod
1920
    def on_options(req, resp, id_):
1921
        resp.status = falcon.HTTP_200
1922
1923
    @staticmethod
1924
    def on_get(req, resp, id_):
1925
        if 'API-KEY' not in req.headers or \
1926
                not isinstance(req.headers['API-KEY'], str) or \
1927
                len(str.strip(req.headers['API-KEY'])) == 0:
1928
            access_control(req)
1929
        else:
1930
            api_key_control(req)
1931
        if not id_.isdigit() or int(id_) <= 0:
1932
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1933
                                   description='API.INVALID_EQUIPMENT_ID')
1934
1935
        cnx = mysql.connector.connect(**config.myems_system_db)
1936
        cursor = cnx.cursor()
1937
1938
        cursor.execute(" SELECT name "
1939
                       " FROM tbl_equipments "
1940
                       " WHERE id = %s ", (id_,))
1941
        if cursor.fetchone() is None:
1942
            cursor.close()
1943
            cnx.close()
1944
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1945
                                   description='API.EQUIPMENT_NOT_FOUND')
1946
1947
        query = (" SELECT c.id, c.name, c.uuid "
1948
                 " FROM tbl_equipments e, tbl_equipments_commands ec, tbl_commands c "
1949
                 " WHERE ec.equipment_id = e.id AND c.id = ec.command_id AND e.id = %s "
1950
                 " ORDER BY c.id ")
1951
        cursor.execute(query, (id_,))
1952
        rows = cursor.fetchall()
1953
1954
        result = list()
1955
        if rows is not None and len(rows) > 0:
1956
            for row in rows:
1957
                meta_result = {"id": row[0],
1958
                               "name": row[1],
1959
                               "uuid": row[2]}
1960
                result.append(meta_result)
1961
1962
        resp.text = json.dumps(result)
1963
1964
    @staticmethod
1965
    @user_logger
1966
    def on_post(req, resp, id_):
1967
        """Handles POST requests"""
1968
        admin_control(req)
1969
        try:
1970
            raw_json = req.stream.read().decode('utf-8')
1971
        except Exception as ex:
1972
            raise falcon.HTTPError(status=falcon.HTTP_400,
1973
                                   title='API.BAD_REQUEST',
1974
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1975
1976
        if not id_.isdigit() or int(id_) <= 0:
1977
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1978
                                   description='API.INVALID_EQUIPMENT_ID')
1979
1980
        new_values = json.loads(raw_json)
1981
1982
        if 'command_id' not in new_values['data'].keys() or \
1983
                not isinstance(new_values['data']['command_id'], int) or \
1984
                new_values['data']['command_id'] <= 0:
1985
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1986
                                   description='API.INVALID_COMMAND_ID')
1987
        command_id = new_values['data']['command_id']
1988
1989
        cnx = mysql.connector.connect(**config.myems_system_db)
1990
        cursor = cnx.cursor()
1991
1992
        cursor.execute(" SELECT name "
1993
                       " from tbl_equipments "
1994
                       " WHERE id = %s ", (id_,))
1995
        if cursor.fetchone() is None:
1996
            cursor.close()
1997
            cnx.close()
1998
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1999
                                   description='API.EQUIPMENT_NOT_FOUND')
2000
2001
        cursor.execute(" SELECT name "
2002
                       " FROM tbl_commands "
2003
                       " WHERE id = %s ", (command_id,))
2004
        if cursor.fetchone() is None:
2005
            cursor.close()
2006
            cnx.close()
2007
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2008
                                   description='API.COMMAND_NOT_FOUND')
2009
2010
        query = (" SELECT id " 
2011
                 " FROM tbl_equipments_commands "
2012
                 " WHERE equipment_id = %s AND command_id = %s")
2013
        cursor.execute(query, (id_, command_id,))
2014
        if cursor.fetchone() is not None:
2015
            cursor.close()
2016
            cnx.close()
2017
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2018
                                   description='API.EQUIPMENT_COMMAND_RELATION_EXISTS')
2019
2020
        add_row = (" INSERT INTO tbl_equipments_commands (equipment_id, command_id) "
2021
                   " VALUES (%s, %s) ")
2022
        cursor.execute(add_row, (id_, command_id,))
2023
        cnx.commit()
2024
        cursor.close()
2025
        cnx.close()
2026
2027
        resp.status = falcon.HTTP_201
2028
        resp.location = '/equipments/' + str(id_) + '/commands/' + str(command_id)
2029
2030
2031
class EquipmentCommandItem:

myems-api/core/tenant.py 3 locations

@@ 1792-1906 (lines=115) @@
1789
        resp.status = falcon.HTTP_204
1790
1791
1792
class TenantCommandCollection:
1793
    def __init__(self):
1794
        """Initializes Class"""
1795
        pass
1796
1797
    @staticmethod
1798
    def on_options(req, resp, id_):
1799
        resp.status = falcon.HTTP_200
1800
1801
    @staticmethod
1802
    def on_get(req, resp, id_):
1803
        if 'API-KEY' not in req.headers or \
1804
                not isinstance(req.headers['API-KEY'], str) or \
1805
                len(str.strip(req.headers['API-KEY'])) == 0:
1806
            access_control(req)
1807
        else:
1808
            api_key_control(req)
1809
        if not id_.isdigit() or int(id_) <= 0:
1810
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1811
                                   description='API.INVALID_TENANT_ID')
1812
1813
        cnx = mysql.connector.connect(**config.myems_system_db)
1814
        cursor = cnx.cursor()
1815
1816
        cursor.execute(" SELECT name "
1817
                       " FROM tbl_tenants "
1818
                       " WHERE id = %s ", (id_,))
1819
        if cursor.fetchone() is None:
1820
            cursor.close()
1821
            cnx.close()
1822
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1823
                                   description='API.TENANT_NOT_FOUND')
1824
1825
        query = (" SELECT c.id, c.name, c.uuid "
1826
                 " FROM tbl_tenants t, tbl_tenants_commands tc, tbl_commands c "
1827
                 " WHERE tc.tenant_id = t.id AND c.id = tc.command_id AND t.id = %s "
1828
                 " ORDER BY c.id ")
1829
        cursor.execute(query, (id_,))
1830
        rows = cursor.fetchall()
1831
1832
        result = list()
1833
        if rows is not None and len(rows) > 0:
1834
            for row in rows:
1835
                meta_result = {"id": row[0],
1836
                               "name": row[1],
1837
                               "uuid": row[2]}
1838
                result.append(meta_result)
1839
1840
        resp.text = json.dumps(result)
1841
1842
    @staticmethod
1843
    @user_logger
1844
    def on_post(req, resp, id_):
1845
        """Handles POST requests"""
1846
        admin_control(req)
1847
        try:
1848
            raw_json = req.stream.read().decode('utf-8')
1849
        except Exception as ex:
1850
            raise falcon.HTTPError(status=falcon.HTTP_400,
1851
                                   title='API.BAD_REQUEST',
1852
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1853
1854
        if not id_.isdigit() or int(id_) <= 0:
1855
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1856
                                   description='API.INVALID_TENANT_ID')
1857
1858
        new_values = json.loads(raw_json)
1859
1860
        if 'command_id' not in new_values['data'].keys() or \
1861
                not isinstance(new_values['data']['command_id'], int) or \
1862
                new_values['data']['command_id'] <= 0:
1863
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1864
                                   description='API.INVALID_COMMAND_ID')
1865
        command_id = new_values['data']['command_id']
1866
1867
        cnx = mysql.connector.connect(**config.myems_system_db)
1868
        cursor = cnx.cursor()
1869
1870
        cursor.execute(" SELECT name "
1871
                       " from tbl_tenants "
1872
                       " WHERE id = %s ", (id_,))
1873
        if cursor.fetchone() is None:
1874
            cursor.close()
1875
            cnx.close()
1876
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1877
                                   description='API.TENANT_NOT_FOUND')
1878
1879
        cursor.execute(" SELECT name "
1880
                       " FROM tbl_commands "
1881
                       " WHERE id = %s ", (command_id,))
1882
        if cursor.fetchone() is None:
1883
            cursor.close()
1884
            cnx.close()
1885
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1886
                                   description='API.COMMAND_NOT_FOUND')
1887
1888
        query = (" SELECT id " 
1889
                 " FROM tbl_tenants_commands "
1890
                 " WHERE tenant_id = %s AND command_id = %s")
1891
        cursor.execute(query, (id_, command_id,))
1892
        if cursor.fetchone() is not None:
1893
            cursor.close()
1894
            cnx.close()
1895
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1896
                                   description='API.TENANT_COMMAND_RELATION_EXISTS')
1897
1898
        add_row = (" INSERT INTO tbl_tenants_commands (tenant_id, command_id) "
1899
                   " VALUES (%s, %s) ")
1900
        cursor.execute(add_row, (id_, command_id,))
1901
        cnx.commit()
1902
        cursor.close()
1903
        cnx.close()
1904
1905
        resp.status = falcon.HTTP_201
1906
        resp.location = '/tenants/' + str(id_) + '/commands/' + str(command_id)
1907
1908
1909
class TenantCommandItem:
@@ 1614-1728 (lines=115) @@
1611
        resp.status = falcon.HTTP_204
1612
1613
1614
class TenantWorkingCalendarCollection:
1615
    def __init__(self):
1616
        """Initializes TenantWorkingCalendarCollection Class"""
1617
        pass
1618
1619
    @staticmethod
1620
    def on_options(req, resp, id_):
1621
        resp.status = falcon.HTTP_200
1622
1623
    @staticmethod
1624
    def on_get(req, resp, id_):
1625
        if 'API-KEY' not in req.headers or \
1626
                not isinstance(req.headers['API-KEY'], str) or \
1627
                len(str.strip(req.headers['API-KEY'])) == 0:
1628
            access_control(req)
1629
        else:
1630
            api_key_control(req)
1631
        if not id_.isdigit() or int(id_) <= 0:
1632
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1633
                                   description='API.INVALID_TENANT_ID')
1634
1635
        cnx = mysql.connector.connect(**config.myems_system_db)
1636
        cursor = cnx.cursor()
1637
1638
        cursor.execute(" SELECT name "
1639
                       " FROM tbl_tenants "
1640
                       " WHERE id = %s ", (id_,))
1641
        if cursor.fetchone() is None:
1642
            cursor.close()
1643
            cnx.close()
1644
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1645
                                   description='API.TENANT_NOT_FOUND')
1646
1647
        query = (" SELECT wc.id, wc.name, wc.description "
1648
                 " FROM tbl_tenants t, tbl_tenants_working_calendars twc, tbl_working_calendars wc "
1649
                 " WHERE twc.tenant_id = t.id AND wc.id = twc.working_calendar_id AND t.id = %s "
1650
                 " ORDER BY wc.id ")
1651
        cursor.execute(query, (id_,))
1652
        rows = cursor.fetchall()
1653
1654
        result = list()
1655
        if rows is not None and len(rows) > 0:
1656
            for row in rows:
1657
                meta_result = {"id": row[0],
1658
                               "name": row[1],
1659
                               "description": row[2]}
1660
                result.append(meta_result)
1661
1662
        resp.text = json.dumps(result)
1663
1664
    @staticmethod
1665
    @user_logger
1666
    def on_post(req, resp, id_):
1667
        """Handles POST requests"""
1668
        admin_control(req)
1669
        try:
1670
            raw_json = req.stream.read().decode('utf-8')
1671
        except Exception as ex:
1672
            raise falcon.HTTPError(status=falcon.HTTP_400,
1673
                                   title='API.BAD_REQUEST',
1674
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1675
1676
        if not id_.isdigit() or int(id_) <= 0:
1677
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1678
                                   description='API.INVALID_TENANT_ID')
1679
1680
        new_values = json.loads(raw_json)
1681
1682
        if 'working_calendar_id' not in new_values['data'].keys() or \
1683
                not isinstance(new_values['data']['working_calendar_id'], int) or \
1684
                new_values['data']['working_calendar_id'] <= 0:
1685
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1686
                                   description='API.INVALID_WORKING_CALENDAR_ID')
1687
        working_calendar_id = new_values['data']['working_calendar_id']
1688
1689
        cnx = mysql.connector.connect(**config.myems_system_db)
1690
        cursor = cnx.cursor()
1691
1692
        cursor.execute(" SELECT name "
1693
                       " from tbl_tenants "
1694
                       " WHERE id = %s ", (id_,))
1695
        if cursor.fetchone() is None:
1696
            cursor.close()
1697
            cnx.close()
1698
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1699
                                   description='API.TENANT_NOT_FOUND')
1700
1701
        cursor.execute(" SELECT name "
1702
                       " FROM tbl_working_calendars "
1703
                       " WHERE id = %s ", (working_calendar_id,))
1704
        if cursor.fetchone() is None:
1705
            cursor.close()
1706
            cnx.close()
1707
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1708
                                   description='API.WORKING_CALENDAR_NOT_FOUND')
1709
1710
        query = (" SELECT id " 
1711
                 " FROM tbl_tenants_working_calendars "
1712
                 " WHERE tenant_id = %s AND working_calendar_id = %s")
1713
        cursor.execute(query, (id_, working_calendar_id,))
1714
        if cursor.fetchone() is not None:
1715
            cursor.close()
1716
            cnx.close()
1717
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1718
                                   description='API.TENANT_WORKING_CALENDAR_RELATION_EXISTS')
1719
1720
        add_row = (" INSERT INTO tbl_tenants_working_calendars (tenant_id, working_calendar_id) "
1721
                   " VALUES (%s, %s) ")
1722
        cursor.execute(add_row, (id_, working_calendar_id,))
1723
        cnx.commit()
1724
        cursor.close()
1725
        cnx.close()
1726
1727
        resp.status = falcon.HTTP_201
1728
        resp.location = '/tenants/' + str(id_) + '/workingcalendars/' + str(working_calendar_id)
1729
1730
1731
class TenantWorkingCalendarItem:
@@ 1246-1360 (lines=115) @@
1243
        resp.status = falcon.HTTP_204
1244
1245
1246
class TenantSensorCollection:
1247
    def __init__(self):
1248
        """Initializes Class"""
1249
        pass
1250
1251
    @staticmethod
1252
    def on_options(req, resp, id_):
1253
        resp.status = falcon.HTTP_200
1254
1255
    @staticmethod
1256
    def on_get(req, resp, id_):
1257
        if 'API-KEY' not in req.headers or \
1258
                not isinstance(req.headers['API-KEY'], str) or \
1259
                len(str.strip(req.headers['API-KEY'])) == 0:
1260
            access_control(req)
1261
        else:
1262
            api_key_control(req)
1263
        if not id_.isdigit() or int(id_) <= 0:
1264
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1265
                                   description='API.INVALID_TENANT_ID')
1266
1267
        cnx = mysql.connector.connect(**config.myems_system_db)
1268
        cursor = cnx.cursor()
1269
1270
        cursor.execute(" SELECT name "
1271
                       " FROM tbl_tenants "
1272
                       " WHERE id = %s ", (id_,))
1273
        if cursor.fetchone() is None:
1274
            cursor.close()
1275
            cnx.close()
1276
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1277
                                   description='API.TENANT_NOT_FOUND')
1278
1279
        query = (" SELECT s.id, s.name, s.uuid "
1280
                 " FROM tbl_tenants t, tbl_tenants_sensors ts, tbl_sensors s "
1281
                 " WHERE ts.tenant_id = t.id AND s.id = ts.sensor_id AND t.id = %s "
1282
                 " ORDER BY s.id ")
1283
        cursor.execute(query, (id_,))
1284
        rows = cursor.fetchall()
1285
1286
        result = list()
1287
        if rows is not None and len(rows) > 0:
1288
            for row in rows:
1289
                meta_result = {"id": row[0],
1290
                               "name": row[1],
1291
                               "uuid": row[2]}
1292
                result.append(meta_result)
1293
1294
        resp.text = json.dumps(result)
1295
1296
    @staticmethod
1297
    @user_logger
1298
    def on_post(req, resp, id_):
1299
        """Handles POST requests"""
1300
        admin_control(req)
1301
        try:
1302
            raw_json = req.stream.read().decode('utf-8')
1303
        except Exception as ex:
1304
            raise falcon.HTTPError(status=falcon.HTTP_400,
1305
                                   title='API.BAD_REQUEST',
1306
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1307
1308
        if not id_.isdigit() or int(id_) <= 0:
1309
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1310
                                   description='API.INVALID_TENANT_ID')
1311
1312
        new_values = json.loads(raw_json)
1313
1314
        if 'sensor_id' not in new_values['data'].keys() or \
1315
                not isinstance(new_values['data']['sensor_id'], int) or \
1316
                new_values['data']['sensor_id'] <= 0:
1317
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1318
                                   description='API.INVALID_SENSOR_ID')
1319
        sensor_id = new_values['data']['sensor_id']
1320
1321
        cnx = mysql.connector.connect(**config.myems_system_db)
1322
        cursor = cnx.cursor()
1323
1324
        cursor.execute(" SELECT name "
1325
                       " from tbl_tenants "
1326
                       " WHERE id = %s ", (id_,))
1327
        if cursor.fetchone() is None:
1328
            cursor.close()
1329
            cnx.close()
1330
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1331
                                   description='API.TENANT_NOT_FOUND')
1332
1333
        cursor.execute(" SELECT name "
1334
                       " FROM tbl_sensors "
1335
                       " WHERE id = %s ", (sensor_id,))
1336
        if cursor.fetchone() is None:
1337
            cursor.close()
1338
            cnx.close()
1339
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1340
                                   description='API.SENSOR_NOT_FOUND')
1341
1342
        query = (" SELECT id " 
1343
                 " FROM tbl_tenants_sensors "
1344
                 " WHERE tenant_id = %s AND sensor_id = %s")
1345
        cursor.execute(query, (id_, sensor_id,))
1346
        if cursor.fetchone() is not None:
1347
            cursor.close()
1348
            cnx.close()
1349
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1350
                                   description='API.TENANT_SENSOR_RELATION_EXISTS')
1351
1352
        add_row = (" INSERT INTO tbl_tenants_sensors (tenant_id, sensor_id) "
1353
                   " VALUES (%s, %s) ")
1354
        cursor.execute(add_row, (id_, sensor_id,))
1355
        cnx.commit()
1356
        cursor.close()
1357
        cnx.close()
1358
1359
        resp.status = falcon.HTTP_201
1360
        resp.location = '/tenants/' + str(id_) + '/sensors/' + str(sensor_id)
1361
1362
1363
class TenantSensorItem:

myems-api/core/space.py 12 locations

@@ 5479-5591 (lines=113) @@
5476
        resp.status = falcon.HTTP_204
5477
5478
5479
class DistributionSystemCollection:
5480
    def __init__(self):
5481
        """Initializes Class"""
5482
        pass
5483
5484
    @staticmethod
5485
    def on_options(req, resp, id_):
5486
        resp.status = falcon.HTTP_200
5487
5488
    @staticmethod
5489
    def on_get(req, resp, id_):
5490
        if 'API-KEY' not in req.headers or \
5491
                not isinstance(req.headers['API-KEY'], str) or \
5492
                len(str.strip(req.headers['API-KEY'])) == 0:
5493
            access_control(req)
5494
        else:
5495
            api_key_control(req)
5496
        if not id_.isdigit() or int(id_) <= 0:
5497
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5498
                                   description='API.INVALID_SPACE_ID')
5499
5500
        cnx = mysql.connector.connect(**config.myems_system_db)
5501
        cursor = cnx.cursor()
5502
5503
        cursor.execute(" SELECT name "
5504
                       " FROM tbl_spaces "
5505
                       " WHERE id = %s ", (id_,))
5506
        if cursor.fetchone() is None:
5507
            cursor.close()
5508
            cnx.close()
5509
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5510
                                   description='API.SPACE_NOT_FOUND')
5511
5512
        query = (" SELECT d.id, d.name, d.uuid "
5513
                 " FROM tbl_spaces s, tbl_spaces_distribution_systems sd, tbl_distribution_systems d "
5514
                 " WHERE sd.space_id = s.id AND d.id = sd.distribution_system_id AND s.id = %s "
5515
                 " ORDER BY d.id ")
5516
        cursor.execute(query, (id_,))
5517
        rows = cursor.fetchall()
5518
5519
        result = list()
5520
        if rows is not None and len(rows) > 0:
5521
            for row in rows:
5522
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
5523
                result.append(meta_result)
5524
5525
        resp.text = json.dumps(result)
5526
5527
    @staticmethod
5528
    @user_logger
5529
    def on_post(req, resp, id_):
5530
        """Handles POST requests"""
5531
        admin_control(req)
5532
        try:
5533
            raw_json = req.stream.read().decode('utf-8')
5534
        except Exception as ex:
5535
            raise falcon.HTTPError(status=falcon.HTTP_400,
5536
                                   title='API.BAD_REQUEST',
5537
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5538
5539
        if not id_.isdigit() or int(id_) <= 0:
5540
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5541
                                   description='API.INVALID_SPACE_ID')
5542
5543
        new_values = json.loads(raw_json)
5544
5545
        if 'distribution_system_id' not in new_values['data'].keys() or \
5546
                not isinstance(new_values['data']['distribution_system_id'], int) or \
5547
                new_values['data']['distribution_system_id'] <= 0:
5548
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5549
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
5550
        distribution_system_id = new_values['data']['distribution_system_id']
5551
5552
        cnx = mysql.connector.connect(**config.myems_system_db)
5553
        cursor = cnx.cursor()
5554
5555
        cursor.execute(" SELECT name "
5556
                       " from tbl_spaces "
5557
                       " WHERE id = %s ", (id_,))
5558
        if cursor.fetchone() is None:
5559
            cursor.close()
5560
            cnx.close()
5561
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5562
                                   description='API.SPACE_NOT_FOUND')
5563
5564
        cursor.execute(" SELECT name "
5565
                       " FROM tbl_distribution_systems "
5566
                       " WHERE id = %s ", (distribution_system_id,))
5567
        if cursor.fetchone() is None:
5568
            cursor.close()
5569
            cnx.close()
5570
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5571
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
5572
5573
        query = (" SELECT id " 
5574
                 " FROM tbl_spaces_distribution_systems "
5575
                 " WHERE space_id = %s AND distribution_system_id = %s")
5576
        cursor.execute(query, (id_, distribution_system_id,))
5577
        if cursor.fetchone() is not None:
5578
            cursor.close()
5579
            cnx.close()
5580
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5581
                                   description='API.SPACE_DISTRIBUTION_SYSTEM_RELATION_EXISTS')
5582
5583
        add_row = (" INSERT INTO tbl_spaces_distribution_systems (space_id, distribution_system_id) "
5584
                   " VALUES (%s, %s) ")
5585
        cursor.execute(add_row, (id_, distribution_system_id,))
5586
        cnx.commit()
5587
        cursor.close()
5588
        cnx.close()
5589
5590
        resp.status = falcon.HTTP_201
5591
        resp.location = '/spaces/' + str(id_) + '/distributionsystems/' + str(distribution_system_id)
5592
5593
5594
class DistributionSystemItem:
@@ 5303-5415 (lines=113) @@
5300
            resp.location = '/spaces/' + str(new_id)
5301
5302
5303
class SpaceEnergyFlowDiagramCollection:
5304
    def __init__(self):
5305
        """Initializes Class"""
5306
        pass
5307
5308
    @staticmethod
5309
    def on_options(req, resp, id_):
5310
        resp.status = falcon.HTTP_200
5311
5312
    @staticmethod
5313
    def on_get(req, resp, id_):
5314
        if 'API-KEY' not in req.headers or \
5315
                not isinstance(req.headers['API-KEY'], str) or \
5316
                len(str.strip(req.headers['API-KEY'])) == 0:
5317
            access_control(req)
5318
        else:
5319
            api_key_control(req)
5320
        if not id_.isdigit() or int(id_) <= 0:
5321
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5322
                                   description='API.INVALID_SPACE_ID')
5323
5324
        cnx = mysql.connector.connect(**config.myems_system_db)
5325
        cursor = cnx.cursor()
5326
5327
        cursor.execute(" SELECT name "
5328
                       " FROM tbl_spaces "
5329
                       " WHERE id = %s ", (id_,))
5330
        if cursor.fetchone() is None:
5331
            cursor.close()
5332
            cnx.close()
5333
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5334
                                   description='API.SPACE_NOT_FOUND')
5335
5336
        query = (" SELECT e.id, e.name, e.uuid "
5337
                 " FROM tbl_spaces s, tbl_spaces_energy_flow_diagrams se, tbl_energy_flow_diagrams e "
5338
                 " WHERE se.space_id = s.id AND e.id = se.energy_flow_diagram_id AND s.id = %s "
5339
                 " ORDER BY e.id ")
5340
        cursor.execute(query, (id_,))
5341
        rows = cursor.fetchall()
5342
5343
        result = list()
5344
        if rows is not None and len(rows) > 0:
5345
            for row in rows:
5346
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
5347
                result.append(meta_result)
5348
5349
        resp.text = json.dumps(result)
5350
5351
    @staticmethod
5352
    @user_logger
5353
    def on_post(req, resp, id_):
5354
        """Handles POST requests"""
5355
        admin_control(req)
5356
        try:
5357
            raw_json = req.stream.read().decode('utf-8')
5358
        except Exception as ex:
5359
            raise falcon.HTTPError(status=falcon.HTTP_400,
5360
                                   title='API.BAD_REQUEST',
5361
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5362
5363
        if not id_.isdigit() or int(id_) <= 0:
5364
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5365
                                   description='API.INVALID_SPACE_ID')
5366
5367
        new_values = json.loads(raw_json)
5368
5369
        if 'energy_flow_diagram_id' not in new_values['data'].keys() or \
5370
                not isinstance(new_values['data']['energy_flow_diagram_id'], int) or \
5371
                new_values['data']['energy_flow_diagram_id'] <= 0:
5372
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5373
                                   description='API.INVALID_ENERGY_FLOW_DIAGRAM_ID')
5374
        energy_flow_diagram_id = new_values['data']['energy_flow_diagram_id']
5375
5376
        cnx = mysql.connector.connect(**config.myems_system_db)
5377
        cursor = cnx.cursor()
5378
5379
        cursor.execute(" SELECT name "
5380
                       " from tbl_spaces "
5381
                       " WHERE id = %s ", (id_,))
5382
        if cursor.fetchone() is None:
5383
            cursor.close()
5384
            cnx.close()
5385
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5386
                                   description='API.SPACE_NOT_FOUND')
5387
5388
        cursor.execute(" SELECT name "
5389
                       " FROM tbl_energy_flow_diagrams "
5390
                       " WHERE id = %s ", (energy_flow_diagram_id,))
5391
        if cursor.fetchone() is None:
5392
            cursor.close()
5393
            cnx.close()
5394
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5395
                                   description='API.ENERGY_FLOW_DIAGRAM_NOT_FOUND')
5396
5397
        query = (" SELECT id " 
5398
                 " FROM tbl_spaces_energy_flow_diagrams "
5399
                 " WHERE space_id = %s AND energy_flow_diagram_id = %s")
5400
        cursor.execute(query, (id_, energy_flow_diagram_id,))
5401
        if cursor.fetchone() is not None:
5402
            cursor.close()
5403
            cnx.close()
5404
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5405
                                   description='API.SPACE_ENERGY_FLOW_DIAGRAM_RELATION_EXISTS')
5406
5407
        add_row = (" INSERT INTO tbl_spaces_energy_flow_diagrams (space_id, energy_flow_diagram_id) "
5408
                   " VALUES (%s, %s) ")
5409
        cursor.execute(add_row, (id_, energy_flow_diagram_id,))
5410
        cnx.commit()
5411
        cursor.close()
5412
        cnx.close()
5413
5414
        resp.status = falcon.HTTP_201
5415
        resp.location = '/spaces/' + str(id_) + '/energyflowdiagrams/' + str(energy_flow_diagram_id)
5416
5417
5418
class SpaceEnergyFlowDiagramItem:
@@ 3574-3686 (lines=113) @@
3571
        resp.status = falcon.HTTP_204
3572
3573
3574
class SpaceCommandCollection:
3575
    def __init__(self):
3576
        """Initializes Class"""
3577
        pass
3578
3579
    @staticmethod
3580
    def on_options(req, resp, id_):
3581
        resp.status = falcon.HTTP_200
3582
3583
    @staticmethod
3584
    def on_get(req, resp, id_):
3585
        if 'API-KEY' not in req.headers or \
3586
                not isinstance(req.headers['API-KEY'], str) or \
3587
                len(str.strip(req.headers['API-KEY'])) == 0:
3588
            access_control(req)
3589
        else:
3590
            api_key_control(req)
3591
        if not id_.isdigit() or int(id_) <= 0:
3592
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3593
                                   description='API.INVALID_SPACE_ID')
3594
3595
        cnx = mysql.connector.connect(**config.myems_system_db)
3596
        cursor = cnx.cursor()
3597
3598
        cursor.execute(" SELECT name "
3599
                       " FROM tbl_spaces "
3600
                       " WHERE id = %s ", (id_,))
3601
        if cursor.fetchone() is None:
3602
            cursor.close()
3603
            cnx.close()
3604
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3605
                                   description='API.SPACE_NOT_FOUND')
3606
3607
        query = (" SELECT c.id, c.name, c.uuid "
3608
                 " FROM tbl_spaces s, tbl_spaces_commands sc, tbl_commands c "
3609
                 " WHERE sc.space_id = s.id AND c.id = sc.command_id AND s.id = %s "
3610
                 " ORDER BY c.id ")
3611
        cursor.execute(query, (id_,))
3612
        rows = cursor.fetchall()
3613
3614
        result = list()
3615
        if rows is not None and len(rows) > 0:
3616
            for row in rows:
3617
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
3618
                result.append(meta_result)
3619
3620
        resp.text = json.dumps(result)
3621
3622
    @staticmethod
3623
    @user_logger
3624
    def on_post(req, resp, id_):
3625
        """Handles POST requests"""
3626
        admin_control(req)
3627
        try:
3628
            raw_json = req.stream.read().decode('utf-8')
3629
        except Exception as ex:
3630
            raise falcon.HTTPError(status=falcon.HTTP_400,
3631
                                   title='API.BAD_REQUEST',
3632
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3633
3634
        if not id_.isdigit() or int(id_) <= 0:
3635
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3636
                                   description='API.INVALID_SPACE_ID')
3637
3638
        new_values = json.loads(raw_json)
3639
3640
        if 'command_id' not in new_values['data'].keys() or \
3641
                not isinstance(new_values['data']['command_id'], int) or \
3642
                new_values['data']['command_id'] <= 0:
3643
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3644
                                   description='API.INVALID_COMMAND_ID')
3645
        command_id = new_values['data']['command_id']
3646
3647
        cnx = mysql.connector.connect(**config.myems_system_db)
3648
        cursor = cnx.cursor()
3649
3650
        cursor.execute(" SELECT name "
3651
                       " from tbl_spaces "
3652
                       " WHERE id = %s ", (id_,))
3653
        if cursor.fetchone() is None:
3654
            cursor.close()
3655
            cnx.close()
3656
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3657
                                   description='API.SPACE_NOT_FOUND')
3658
3659
        cursor.execute(" SELECT name "
3660
                       " FROM tbl_commands "
3661
                       " WHERE id = %s ", (command_id,))
3662
        if cursor.fetchone() is None:
3663
            cursor.close()
3664
            cnx.close()
3665
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3666
                                   description='API.COMMAND_NOT_FOUND')
3667
3668
        query = (" SELECT id " 
3669
                 " FROM tbl_spaces_commands "
3670
                 " WHERE space_id = %s AND command_id = %s")
3671
        cursor.execute(query, (id_, command_id,))
3672
        if cursor.fetchone() is not None:
3673
            cursor.close()
3674
            cnx.close()
3675
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3676
                                   description='API.SPACE_COMMAND_RELATION_EXISTS')
3677
3678
        add_row = (" INSERT INTO tbl_spaces_commands (space_id, command_id) "
3679
                   " VALUES (%s, %s) ")
3680
        cursor.execute(add_row, (id_, command_id,))
3681
        cnx.commit()
3682
        cursor.close()
3683
        cnx.close()
3684
3685
        resp.status = falcon.HTTP_201
3686
        resp.location = '/spaces/' + str(id_) + '/commands/' + str(command_id)
3687
3688
3689
class SpaceCommandItem:
@@ 3398-3510 (lines=113) @@
3395
        resp.text = json.dumps(result)
3396
3397
3398
class SpaceWorkingCalendarCollection:
3399
    def __init__(self):
3400
        """Initializes SpaceWorkingCalendarCollection Class"""
3401
        pass
3402
3403
    @staticmethod
3404
    def on_options(req, resp, id_):
3405
        resp.status = falcon.HTTP_200
3406
3407
    @staticmethod
3408
    def on_get(req, resp, id_):
3409
        if 'API-KEY' not in req.headers or \
3410
                not isinstance(req.headers['API-KEY'], str) or \
3411
                len(str.strip(req.headers['API-KEY'])) == 0:
3412
            access_control(req)
3413
        else:
3414
            api_key_control(req)
3415
        if not id_.isdigit() or int(id_) <= 0:
3416
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3417
                                   description='API.INVALID_SPACE_ID')
3418
3419
        cnx = mysql.connector.connect(**config.myems_system_db)
3420
        cursor = cnx.cursor()
3421
3422
        cursor.execute(" SELECT name "
3423
                       " FROM tbl_spaces "
3424
                       " WHERE id = %s ", (id_,))
3425
        if cursor.fetchone() is None:
3426
            cursor.close()
3427
            cnx.close()
3428
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3429
                                   description='API.SPACE_NOT_FOUND')
3430
3431
        query = (" SELECT wc.id, wc.name, wc.description "
3432
                 " FROM tbl_spaces s, tbl_spaces_working_calendars swc, tbl_working_calendars wc "
3433
                 " WHERE swc.space_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
3434
                 " ORDER BY wc.id ")
3435
        cursor.execute(query, (id_,))
3436
        rows = cursor.fetchall()
3437
3438
        result = list()
3439
        if rows is not None and len(rows) > 0:
3440
            for row in rows:
3441
                meta_result = {"id": row[0], "name": row[1], "description": row[2]}
3442
                result.append(meta_result)
3443
3444
        resp.text = json.dumps(result)
3445
3446
    @staticmethod
3447
    @user_logger
3448
    def on_post(req, resp, id_):
3449
        """Handles POST requests"""
3450
        admin_control(req)
3451
        try:
3452
            raw_json = req.stream.read().decode('utf-8')
3453
        except Exception as ex:
3454
            raise falcon.HTTPError(status=falcon.HTTP_400,
3455
                                   title='API.BAD_REQUEST',
3456
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3457
3458
        if not id_.isdigit() or int(id_) <= 0:
3459
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3460
                                   description='API.INVALID_SPACE_ID')
3461
3462
        new_values = json.loads(raw_json)
3463
3464
        if 'working_calendar_id' not in new_values['data'].keys() or \
3465
                not isinstance(new_values['data']['working_calendar_id'], int) or \
3466
                new_values['data']['working_calendar_id'] <= 0:
3467
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3468
                                   description='API.INVALID_WORKING_CALENDAR_ID')
3469
        working_calendar_id = new_values['data']['working_calendar_id']
3470
3471
        cnx = mysql.connector.connect(**config.myems_system_db)
3472
        cursor = cnx.cursor()
3473
3474
        cursor.execute(" SELECT name "
3475
                       " from tbl_spaces "
3476
                       " WHERE id = %s ", (id_,))
3477
        if cursor.fetchone() is None:
3478
            cursor.close()
3479
            cnx.close()
3480
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3481
                                   description='API.SPACE_NOT_FOUND')
3482
3483
        cursor.execute(" SELECT name "
3484
                       " FROM tbl_working_calendars "
3485
                       " WHERE id = %s ", (working_calendar_id,))
3486
        if cursor.fetchone() is None:
3487
            cursor.close()
3488
            cnx.close()
3489
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3490
                                   description='API.WORKING_CALENDAR_NOT_FOUND')
3491
3492
        query = (" SELECT id " 
3493
                 " FROM tbl_spaces_working_calendars "
3494
                 " WHERE space_id = %s AND working_calendar_id = %s")
3495
        cursor.execute(query, (id_, working_calendar_id,))
3496
        if cursor.fetchone() is not None:
3497
            cursor.close()
3498
            cnx.close()
3499
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3500
                                   description='API.SPACE_WORKING_CALENDAR_RELATION_EXISTS')
3501
3502
        add_row = (" INSERT INTO tbl_spaces_working_calendars (space_id, working_calendar_id) "
3503
                   " VALUES (%s, %s) ")
3504
        cursor.execute(add_row, (id_, working_calendar_id,))
3505
        cnx.commit()
3506
        cursor.close()
3507
        cnx.close()
3508
3509
        resp.status = falcon.HTTP_201
3510
        resp.location = '/spaces/' + str(id_) + '/workingcalendars/' + str(working_calendar_id)
3511
3512
3513
class SpaceWorkingCalendarItem:
@@ 2849-2961 (lines=113) @@
2846
        resp.status = falcon.HTTP_204
2847
2848
2849
class SpaceTenantCollection:
2850
    def __init__(self):
2851
        """Initializes Class"""
2852
        pass
2853
2854
    @staticmethod
2855
    def on_options(req, resp, id_):
2856
        resp.status = falcon.HTTP_200
2857
2858
    @staticmethod
2859
    def on_get(req, resp, id_):
2860
        if 'API-KEY' not in req.headers or \
2861
                not isinstance(req.headers['API-KEY'], str) or \
2862
                len(str.strip(req.headers['API-KEY'])) == 0:
2863
            access_control(req)
2864
        else:
2865
            api_key_control(req)
2866
        if not id_.isdigit() or int(id_) <= 0:
2867
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2868
                                   description='API.INVALID_SPACE_ID')
2869
2870
        cnx = mysql.connector.connect(**config.myems_system_db)
2871
        cursor = cnx.cursor()
2872
2873
        cursor.execute(" SELECT name "
2874
                       " FROM tbl_spaces "
2875
                       " WHERE id = %s ", (id_,))
2876
        if cursor.fetchone() is None:
2877
            cursor.close()
2878
            cnx.close()
2879
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2880
                                   description='API.SPACE_NOT_FOUND')
2881
2882
        query = (" SELECT t.id, t.name, t.uuid "
2883
                 " FROM tbl_spaces s, tbl_spaces_tenants st, tbl_tenants t "
2884
                 " WHERE st.space_id = s.id AND t.id = st.tenant_id AND s.id = %s "
2885
                 " ORDER BY t.id ")
2886
        cursor.execute(query, (id_,))
2887
        rows = cursor.fetchall()
2888
2889
        result = list()
2890
        if rows is not None and len(rows) > 0:
2891
            for row in rows:
2892
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2893
                result.append(meta_result)
2894
2895
        resp.text = json.dumps(result)
2896
2897
    @staticmethod
2898
    @user_logger
2899
    def on_post(req, resp, id_):
2900
        """Handles POST requests"""
2901
        admin_control(req)
2902
        try:
2903
            raw_json = req.stream.read().decode('utf-8')
2904
        except Exception as ex:
2905
            raise falcon.HTTPError(status=falcon.HTTP_400,
2906
                                   title='API.BAD_REQUEST',
2907
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2908
2909
        if not id_.isdigit() or int(id_) <= 0:
2910
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2911
                                   description='API.INVALID_SPACE_ID')
2912
2913
        new_values = json.loads(raw_json)
2914
2915
        if 'tenant_id' not in new_values['data'].keys() or \
2916
                not isinstance(new_values['data']['tenant_id'], int) or \
2917
                new_values['data']['tenant_id'] <= 0:
2918
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2919
                                   description='API.INVALID_TENANT_ID')
2920
        tenant_id = new_values['data']['tenant_id']
2921
2922
        cnx = mysql.connector.connect(**config.myems_system_db)
2923
        cursor = cnx.cursor()
2924
2925
        cursor.execute(" SELECT name "
2926
                       " from tbl_spaces "
2927
                       " WHERE id = %s ", (id_,))
2928
        if cursor.fetchone() is None:
2929
            cursor.close()
2930
            cnx.close()
2931
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2932
                                   description='API.SPACE_NOT_FOUND')
2933
2934
        cursor.execute(" SELECT name "
2935
                       " FROM tbl_tenants "
2936
                       " WHERE id = %s ", (tenant_id,))
2937
        if cursor.fetchone() is None:
2938
            cursor.close()
2939
            cnx.close()
2940
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2941
                                   description='API.TENANT_NOT_FOUND')
2942
2943
        query = (" SELECT id " 
2944
                 " FROM tbl_spaces_tenants "
2945
                 " WHERE space_id = %s AND tenant_id = %s")
2946
        cursor.execute(query, (id_, tenant_id,))
2947
        if cursor.fetchone() is not None:
2948
            cursor.close()
2949
            cnx.close()
2950
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2951
                                   description='API.SPACE_TENANT_RELATION_EXISTS')
2952
2953
        add_row = (" INSERT INTO tbl_spaces_tenants (space_id, tenant_id) "
2954
                   " VALUES (%s, %s) ")
2955
        cursor.execute(add_row, (id_, tenant_id,))
2956
        cnx.commit()
2957
        cursor.close()
2958
        cnx.close()
2959
2960
        resp.status = falcon.HTTP_201
2961
        resp.location = '/spaces/' + str(id_) + '/tenants/' + str(tenant_id)
2962
2963
2964
class SpaceTenantItem:
@@ 2674-2786 (lines=113) @@
2671
        resp.status = falcon.HTTP_204
2672
2673
2674
class SpaceStoreCollection:
2675
    def __init__(self):
2676
        """Initializes Class"""
2677
        pass
2678
2679
    @staticmethod
2680
    def on_options(req, resp, id_):
2681
        resp.status = falcon.HTTP_200
2682
2683
    @staticmethod
2684
    def on_get(req, resp, id_):
2685
        if 'API-KEY' not in req.headers or \
2686
                not isinstance(req.headers['API-KEY'], str) or \
2687
                len(str.strip(req.headers['API-KEY'])) == 0:
2688
            access_control(req)
2689
        else:
2690
            api_key_control(req)
2691
        if not id_.isdigit() or int(id_) <= 0:
2692
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2693
                                   description='API.INVALID_SPACE_ID')
2694
2695
        cnx = mysql.connector.connect(**config.myems_system_db)
2696
        cursor = cnx.cursor()
2697
2698
        cursor.execute(" SELECT name "
2699
                       " FROM tbl_spaces "
2700
                       " WHERE id = %s ", (id_,))
2701
        if cursor.fetchone() is None:
2702
            cursor.close()
2703
            cnx.close()
2704
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2705
                                   description='API.SPACE_NOT_FOUND')
2706
2707
        query = (" SELECT t.id, t.name, t.uuid "
2708
                 " FROM tbl_spaces s, tbl_spaces_stores st, tbl_stores t "
2709
                 " WHERE st.space_id = s.id AND t.id = st.store_id AND s.id = %s "
2710
                 " ORDER BY t.id ")
2711
        cursor.execute(query, (id_,))
2712
        rows = cursor.fetchall()
2713
2714
        result = list()
2715
        if rows is not None and len(rows) > 0:
2716
            for row in rows:
2717
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2718
                result.append(meta_result)
2719
2720
        resp.text = json.dumps(result)
2721
2722
    @staticmethod
2723
    @user_logger
2724
    def on_post(req, resp, id_):
2725
        """Handles POST requests"""
2726
        admin_control(req)
2727
        try:
2728
            raw_json = req.stream.read().decode('utf-8')
2729
        except Exception as ex:
2730
            raise falcon.HTTPError(status=falcon.HTTP_400,
2731
                                   title='API.BAD_REQUEST',
2732
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2733
2734
        if not id_.isdigit() or int(id_) <= 0:
2735
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2736
                                   description='API.INVALID_SPACE_ID')
2737
2738
        new_values = json.loads(raw_json)
2739
2740
        if 'store_id' not in new_values['data'].keys() or \
2741
                not isinstance(new_values['data']['store_id'], int) or \
2742
                new_values['data']['store_id'] <= 0:
2743
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2744
                                   description='API.INVALID_STORE_ID')
2745
        store_id = new_values['data']['store_id']
2746
2747
        cnx = mysql.connector.connect(**config.myems_system_db)
2748
        cursor = cnx.cursor()
2749
2750
        cursor.execute(" SELECT name "
2751
                       " from tbl_spaces "
2752
                       " WHERE id = %s ", (id_,))
2753
        if cursor.fetchone() is None:
2754
            cursor.close()
2755
            cnx.close()
2756
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2757
                                   description='API.SPACE_NOT_FOUND')
2758
2759
        cursor.execute(" SELECT name "
2760
                       " FROM tbl_stores "
2761
                       " WHERE id = %s ", (store_id,))
2762
        if cursor.fetchone() is None:
2763
            cursor.close()
2764
            cnx.close()
2765
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2766
                                   description='API.STORE_NOT_FOUND')
2767
2768
        query = (" SELECT id " 
2769
                 " FROM tbl_spaces_stores "
2770
                 " WHERE space_id = %s AND store_id = %s")
2771
        cursor.execute(query, (id_, store_id,))
2772
        if cursor.fetchone() is not None:
2773
            cursor.close()
2774
            cnx.close()
2775
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2776
                                   description='API.SPACE_STORE_RELATION_EXISTS')
2777
2778
        add_row = (" INSERT INTO tbl_spaces_stores (space_id, store_id) "
2779
                   " VALUES (%s, %s) ")
2780
        cursor.execute(add_row, (id_, store_id,))
2781
        cnx.commit()
2782
        cursor.close()
2783
        cnx.close()
2784
2785
        resp.status = falcon.HTTP_201
2786
        resp.location = '/spaces/' + str(id_) + '/stores/' + str(store_id)
2787
2788
2789
class SpaceStoreItem:
@@ 2499-2611 (lines=113) @@
2496
        resp.status = falcon.HTTP_204
2497
2498
2499
class SpaceShopfloorCollection:
2500
    def __init__(self):
2501
        """Initializes Class"""
2502
        pass
2503
2504
    @staticmethod
2505
    def on_options(req, resp, id_):
2506
        resp.status = falcon.HTTP_200
2507
2508
    @staticmethod
2509
    def on_get(req, resp, id_):
2510
        if 'API-KEY' not in req.headers or \
2511
                not isinstance(req.headers['API-KEY'], str) or \
2512
                len(str.strip(req.headers['API-KEY'])) == 0:
2513
            access_control(req)
2514
        else:
2515
            api_key_control(req)
2516
        if not id_.isdigit() or int(id_) <= 0:
2517
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2518
                                   description='API.INVALID_SPACE_ID')
2519
2520
        cnx = mysql.connector.connect(**config.myems_system_db)
2521
        cursor = cnx.cursor()
2522
2523
        cursor.execute(" SELECT name "
2524
                       " FROM tbl_spaces "
2525
                       " WHERE id = %s ", (id_,))
2526
        if cursor.fetchone() is None:
2527
            cursor.close()
2528
            cnx.close()
2529
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2530
                                   description='API.SPACE_NOT_FOUND')
2531
2532
        query = (" SELECT sf.id, sf.name, sf.uuid "
2533
                 " FROM tbl_spaces sp, tbl_spaces_shopfloors ss, tbl_shopfloors sf "
2534
                 " WHERE ss.space_id = sp.id AND sf.id = ss.shopfloor_id AND sp.id = %s "
2535
                 " ORDER BY sf.id ")
2536
        cursor.execute(query, (id_,))
2537
        rows = cursor.fetchall()
2538
2539
        result = list()
2540
        if rows is not None and len(rows) > 0:
2541
            for row in rows:
2542
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2543
                result.append(meta_result)
2544
2545
        resp.text = json.dumps(result)
2546
2547
    @staticmethod
2548
    @user_logger
2549
    def on_post(req, resp, id_):
2550
        """Handles POST requests"""
2551
        admin_control(req)
2552
        try:
2553
            raw_json = req.stream.read().decode('utf-8')
2554
        except Exception as ex:
2555
            raise falcon.HTTPError(status=falcon.HTTP_400,
2556
                                   title='API.BAD_REQUEST',
2557
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2558
2559
        if not id_.isdigit() or int(id_) <= 0:
2560
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2561
                                   description='API.INVALID_SPACE_ID')
2562
2563
        new_values = json.loads(raw_json)
2564
2565
        if 'shopfloor_id' not in new_values['data'].keys() or \
2566
                not isinstance(new_values['data']['shopfloor_id'], int) or \
2567
                new_values['data']['shopfloor_id'] <= 0:
2568
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2569
                                   description='API.INVALID_SHOPFLOOR_ID')
2570
        shopfloor_id = new_values['data']['shopfloor_id']
2571
2572
        cnx = mysql.connector.connect(**config.myems_system_db)
2573
        cursor = cnx.cursor()
2574
2575
        cursor.execute(" SELECT name "
2576
                       " from tbl_spaces "
2577
                       " WHERE id = %s ", (id_,))
2578
        if cursor.fetchone() is None:
2579
            cursor.close()
2580
            cnx.close()
2581
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2582
                                   description='API.SPACE_NOT_FOUND')
2583
2584
        cursor.execute(" SELECT name "
2585
                       " FROM tbl_shopfloors "
2586
                       " WHERE id = %s ", (shopfloor_id,))
2587
        if cursor.fetchone() is None:
2588
            cursor.close()
2589
            cnx.close()
2590
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2591
                                   description='API.SHOPFLOOR_NOT_FOUND')
2592
2593
        query = (" SELECT id " 
2594
                 " FROM tbl_spaces_shopfloors "
2595
                 " WHERE space_id = %s AND shopfloor_id = %s")
2596
        cursor.execute(query, (id_, shopfloor_id,))
2597
        if cursor.fetchone() is not None:
2598
            cursor.close()
2599
            cnx.close()
2600
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2601
                                   description='API.SPACE_SHOPFLOOR_RELATION_EXISTS')
2602
2603
        add_row = (" INSERT INTO tbl_spaces_shopfloors (space_id, shopfloor_id) "
2604
                   " VALUES (%s, %s) ")
2605
        cursor.execute(add_row, (id_, shopfloor_id,))
2606
        cnx.commit()
2607
        cursor.close()
2608
        cnx.close()
2609
2610
        resp.status = falcon.HTTP_201
2611
        resp.location = '/spaces/' + str(id_) + '/shopfloors/' + str(shopfloor_id)
2612
2613
2614
class SpaceShopfloorItem:
@@ 2324-2436 (lines=113) @@
2321
        resp.status = falcon.HTTP_204
2322
2323
2324
class SpaceSensorCollection:
2325
    def __init__(self):
2326
        """Initializes Class"""
2327
        pass
2328
2329
    @staticmethod
2330
    def on_options(req, resp, id_):
2331
        resp.status = falcon.HTTP_200
2332
2333
    @staticmethod
2334
    def on_get(req, resp, id_):
2335
        if 'API-KEY' not in req.headers or \
2336
                not isinstance(req.headers['API-KEY'], str) or \
2337
                len(str.strip(req.headers['API-KEY'])) == 0:
2338
            access_control(req)
2339
        else:
2340
            api_key_control(req)
2341
        if not id_.isdigit() or int(id_) <= 0:
2342
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2343
                                   description='API.INVALID_SPACE_ID')
2344
2345
        cnx = mysql.connector.connect(**config.myems_system_db)
2346
        cursor = cnx.cursor()
2347
2348
        cursor.execute(" SELECT name "
2349
                       " FROM tbl_spaces "
2350
                       " WHERE id = %s ", (id_,))
2351
        if cursor.fetchone() is None:
2352
            cursor.close()
2353
            cnx.close()
2354
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2355
                                   description='API.SPACE_NOT_FOUND')
2356
2357
        query = (" SELECT se.id, se.name, se.uuid "
2358
                 " FROM tbl_spaces sp, tbl_spaces_sensors ss, tbl_sensors se "
2359
                 " WHERE ss.space_id = sp.id AND se.id = ss.sensor_id AND sp.id = %s "
2360
                 " ORDER BY se.id ")
2361
        cursor.execute(query, (id_,))
2362
        rows = cursor.fetchall()
2363
2364
        result = list()
2365
        if rows is not None and len(rows) > 0:
2366
            for row in rows:
2367
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2368
                result.append(meta_result)
2369
2370
        resp.text = json.dumps(result)
2371
2372
    @staticmethod
2373
    @user_logger
2374
    def on_post(req, resp, id_):
2375
        """Handles POST requests"""
2376
        admin_control(req)
2377
        try:
2378
            raw_json = req.stream.read().decode('utf-8')
2379
        except Exception as ex:
2380
            raise falcon.HTTPError(status=falcon.HTTP_400,
2381
                                   title='API.BAD_REQUEST',
2382
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2383
2384
        if not id_.isdigit() or int(id_) <= 0:
2385
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2386
                                   description='API.INVALID_SPACE_ID')
2387
2388
        new_values = json.loads(raw_json)
2389
2390
        if 'sensor_id' not in new_values['data'].keys() or \
2391
                not isinstance(new_values['data']['sensor_id'], int) or \
2392
                new_values['data']['sensor_id'] <= 0:
2393
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2394
                                   description='API.INVALID_SENSOR_ID')
2395
        sensor_id = new_values['data']['sensor_id']
2396
2397
        cnx = mysql.connector.connect(**config.myems_system_db)
2398
        cursor = cnx.cursor()
2399
2400
        cursor.execute(" SELECT name "
2401
                       " from tbl_spaces "
2402
                       " WHERE id = %s ", (id_,))
2403
        if cursor.fetchone() is None:
2404
            cursor.close()
2405
            cnx.close()
2406
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2407
                                   description='API.SPACE_NOT_FOUND')
2408
2409
        cursor.execute(" SELECT name "
2410
                       " FROM tbl_sensors "
2411
                       " WHERE id = %s ", (sensor_id,))
2412
        if cursor.fetchone() is None:
2413
            cursor.close()
2414
            cnx.close()
2415
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2416
                                   description='API.SENSOR_NOT_FOUND')
2417
2418
        query = (" SELECT id " 
2419
                 " FROM tbl_spaces_sensors "
2420
                 " WHERE space_id = %s AND sensor_id = %s")
2421
        cursor.execute(query, (id_, sensor_id,))
2422
        if cursor.fetchone() is not None:
2423
            cursor.close()
2424
            cnx.close()
2425
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2426
                                   description='API.SPACE_SENSOR_RELATION_EXISTS')
2427
2428
        add_row = (" INSERT INTO tbl_spaces_sensors (space_id, sensor_id) "
2429
                   " VALUES (%s, %s) ")
2430
        cursor.execute(add_row, (id_, sensor_id,))
2431
        cnx.commit()
2432
        cursor.close()
2433
        cnx.close()
2434
2435
        resp.status = falcon.HTTP_201
2436
        resp.location = '/spaces/' + str(id_) + '/sensors/' + str(sensor_id)
2437
2438
2439
class SpaceSensorItem:
@@ 1960-2072 (lines=113) @@
1957
        resp.status = falcon.HTTP_204
1958
1959
1960
class SpacePhotovoltaicPowerStationCollection:
1961
    def __init__(self):
1962
        """Initializes Class"""
1963
        pass
1964
1965
    @staticmethod
1966
    def on_options(req, resp, id_):
1967
        resp.status = falcon.HTTP_200
1968
1969
    @staticmethod
1970
    def on_get(req, resp, id_):
1971
        if 'API-KEY' not in req.headers or \
1972
                not isinstance(req.headers['API-KEY'], str) or \
1973
                len(str.strip(req.headers['API-KEY'])) == 0:
1974
            access_control(req)
1975
        else:
1976
            api_key_control(req)
1977
        if not id_.isdigit() or int(id_) <= 0:
1978
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1979
                                   description='API.INVALID_SPACE_ID')
1980
1981
        cnx = mysql.connector.connect(**config.myems_system_db)
1982
        cursor = cnx.cursor()
1983
1984
        cursor.execute(" SELECT name "
1985
                       " FROM tbl_spaces "
1986
                       " WHERE id = %s ", (id_,))
1987
        if cursor.fetchone() is None:
1988
            cursor.close()
1989
            cnx.close()
1990
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1991
                                   description='API.SPACE_NOT_FOUND')
1992
1993
        query = (" SELECT e.id, e.name, e.uuid, e.phase_of_lifecycle "
1994
                 " FROM tbl_spaces s, tbl_spaces_photovoltaic_power_stations se, tbl_photovoltaic_power_stations e "
1995
                 " WHERE se.space_id = s.id AND e.id = se.photovoltaic_power_station_id AND s.id = %s "
1996
                 " ORDER BY e.phase_of_lifecycle, e.id ")
1997
        cursor.execute(query, (id_,))
1998
        rows = cursor.fetchall()
1999
2000
        result = list()
2001
        if rows is not None and len(rows) > 0:
2002
            for row in rows:
2003
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
2004
                result.append(meta_result)
2005
2006
        resp.text = json.dumps(result)
2007
2008
    @staticmethod
2009
    @user_logger
2010
    def on_post(req, resp, id_):
2011
        """Handles POST requests"""
2012
        admin_control(req)
2013
        try:
2014
            raw_json = req.stream.read().decode('utf-8')
2015
        except Exception as ex:
2016
            raise falcon.HTTPError(status=falcon.HTTP_400,
2017
                                   title='API.BAD_REQUEST',
2018
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2019
2020
        if not id_.isdigit() or int(id_) <= 0:
2021
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2022
                                   description='API.INVALID_SPACE_ID')
2023
2024
        new_values = json.loads(raw_json)
2025
2026
        if 'photovoltaic_power_station_id' not in new_values['data'].keys() or \
2027
                not isinstance(new_values['data']['photovoltaic_power_station_id'], int) or \
2028
                new_values['data']['photovoltaic_power_station_id'] <= 0:
2029
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2030
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
2031
        photovoltaic_power_station_id = new_values['data']['photovoltaic_power_station_id']
2032
2033
        cnx = mysql.connector.connect(**config.myems_system_db)
2034
        cursor = cnx.cursor()
2035
2036
        cursor.execute(" SELECT name "
2037
                       " from tbl_spaces "
2038
                       " WHERE id = %s ", (id_,))
2039
        if cursor.fetchone() is None:
2040
            cursor.close()
2041
            cnx.close()
2042
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2043
                                   description='API.SPACE_NOT_FOUND')
2044
2045
        cursor.execute(" SELECT name "
2046
                       " FROM tbl_photovoltaic_power_stations "
2047
                       " WHERE id = %s ", (photovoltaic_power_station_id,))
2048
        if cursor.fetchone() is None:
2049
            cursor.close()
2050
            cnx.close()
2051
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2052
                                   description='API.PHOTOVOLTAIC_POWER_STATION_NOT_FOUND')
2053
2054
        query = (" SELECT id " 
2055
                 " FROM tbl_spaces_photovoltaic_power_stations "
2056
                 " WHERE space_id = %s AND photovoltaic_power_station_id = %s")
2057
        cursor.execute(query, (id_, photovoltaic_power_station_id,))
2058
        if cursor.fetchone() is not None:
2059
            cursor.close()
2060
            cnx.close()
2061
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2062
                                   description='API.SPACE_PHOTOVOLTAIC_POWER_STATION_RELATION_EXISTS')
2063
2064
        add_row = (" INSERT INTO tbl_spaces_photovoltaic_power_stations (space_id, photovoltaic_power_station_id) "
2065
                   " VALUES (%s, %s) ")
2066
        cursor.execute(add_row, (id_, photovoltaic_power_station_id,))
2067
        cnx.commit()
2068
        cursor.close()
2069
        cnx.close()
2070
2071
        resp.status = falcon.HTTP_201
2072
        resp.location = '/spaces/' + str(id_) + '/photovoltaicpowerstations/' + str(photovoltaic_power_station_id)
2073
2074
2075
class SpacePhotovoltaicPowerStationItem:
@@ 1595-1707 (lines=113) @@
1592
        resp.status = falcon.HTTP_204
1593
1594
1595
class SpaceMicrogridCollection:
1596
    def __init__(self):
1597
        """Initializes Class"""
1598
        pass
1599
1600
    @staticmethod
1601
    def on_options(req, resp, id_):
1602
        resp.status = falcon.HTTP_200
1603
1604
    @staticmethod
1605
    def on_get(req, resp, id_):
1606
        if 'API-KEY' not in req.headers or \
1607
                not isinstance(req.headers['API-KEY'], str) or \
1608
                len(str.strip(req.headers['API-KEY'])) == 0:
1609
            access_control(req)
1610
        else:
1611
            api_key_control(req)
1612
        if not id_.isdigit() or int(id_) <= 0:
1613
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1614
                                   description='API.INVALID_SPACE_ID')
1615
1616
        cnx = mysql.connector.connect(**config.myems_system_db)
1617
        cursor = cnx.cursor()
1618
1619
        cursor.execute(" SELECT name "
1620
                       " FROM tbl_spaces "
1621
                       " WHERE id = %s ", (id_,))
1622
        if cursor.fetchone() is None:
1623
            cursor.close()
1624
            cnx.close()
1625
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1626
                                   description='API.SPACE_NOT_FOUND')
1627
1628
        query = (" SELECT e.id, e.name, e.uuid, e.phase_of_lifecycle "
1629
                 " FROM tbl_spaces s, tbl_spaces_microgrids se, tbl_microgrids e "
1630
                 " WHERE se.space_id = s.id AND e.id = se.microgrid_id AND s.id = %s "
1631
                 " ORDER BY e.phase_of_lifecycle, e.id ")
1632
        cursor.execute(query, (id_,))
1633
        rows = cursor.fetchall()
1634
1635
        result = list()
1636
        if rows is not None and len(rows) > 0:
1637
            for row in rows:
1638
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1639
                result.append(meta_result)
1640
1641
        resp.text = json.dumps(result)
1642
1643
    @staticmethod
1644
    @user_logger
1645
    def on_post(req, resp, id_):
1646
        """Handles POST requests"""
1647
        admin_control(req)
1648
        try:
1649
            raw_json = req.stream.read().decode('utf-8')
1650
        except Exception as ex:
1651
            raise falcon.HTTPError(status=falcon.HTTP_400,
1652
                                   title='API.BAD_REQUEST',
1653
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1654
1655
        if not id_.isdigit() or int(id_) <= 0:
1656
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1657
                                   description='API.INVALID_SPACE_ID')
1658
1659
        new_values = json.loads(raw_json)
1660
1661
        if 'microgrid_id' not in new_values['data'].keys() or \
1662
                not isinstance(new_values['data']['microgrid_id'], int) or \
1663
                new_values['data']['microgrid_id'] <= 0:
1664
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1665
                                   description='API.INVALID_MICROGRID_ID')
1666
        microgrid_id = new_values['data']['microgrid_id']
1667
1668
        cnx = mysql.connector.connect(**config.myems_system_db)
1669
        cursor = cnx.cursor()
1670
1671
        cursor.execute(" SELECT name "
1672
                       " from tbl_spaces "
1673
                       " WHERE id = %s ", (id_,))
1674
        if cursor.fetchone() is None:
1675
            cursor.close()
1676
            cnx.close()
1677
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1678
                                   description='API.SPACE_NOT_FOUND')
1679
1680
        cursor.execute(" SELECT name "
1681
                       " FROM tbl_microgrids "
1682
                       " WHERE id = %s ", (microgrid_id,))
1683
        if cursor.fetchone() is None:
1684
            cursor.close()
1685
            cnx.close()
1686
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1687
                                   description='API.MICROGRID_NOT_FOUND')
1688
1689
        query = (" SELECT id " 
1690
                 " FROM tbl_spaces_microgrids "
1691
                 " WHERE space_id = %s AND microgrid_id = %s")
1692
        cursor.execute(query, (id_, microgrid_id,))
1693
        if cursor.fetchone() is not None:
1694
            cursor.close()
1695
            cnx.close()
1696
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1697
                                   description='API.SPACE_MICROGRID_RELATION_EXISTS')
1698
1699
        add_row = (" INSERT INTO tbl_spaces_microgrids (space_id, microgrid_id) "
1700
                   " VALUES (%s, %s) ")
1701
        cursor.execute(add_row, (id_, microgrid_id,))
1702
        cnx.commit()
1703
        cursor.close()
1704
        cnx.close()
1705
1706
        resp.status = falcon.HTTP_201
1707
        resp.location = '/spaces/' + str(id_) + '/microgrids/' + str(microgrid_id)
1708
1709
1710
class SpaceMicrogridItem:
@@ 1230-1342 (lines=113) @@
1227
        resp.status = falcon.HTTP_204
1228
1229
1230
class SpaceEquipmentCollection:
1231
    def __init__(self):
1232
        """Initializes Class"""
1233
        pass
1234
1235
    @staticmethod
1236
    def on_options(req, resp, id_):
1237
        resp.status = falcon.HTTP_200
1238
1239
    @staticmethod
1240
    def on_get(req, resp, id_):
1241
        if 'API-KEY' not in req.headers or \
1242
                not isinstance(req.headers['API-KEY'], str) or \
1243
                len(str.strip(req.headers['API-KEY'])) == 0:
1244
            access_control(req)
1245
        else:
1246
            api_key_control(req)
1247
        if not id_.isdigit() or int(id_) <= 0:
1248
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1249
                                   description='API.INVALID_SPACE_ID')
1250
1251
        cnx = mysql.connector.connect(**config.myems_system_db)
1252
        cursor = cnx.cursor()
1253
1254
        cursor.execute(" SELECT name "
1255
                       " FROM tbl_spaces "
1256
                       " WHERE id = %s ", (id_,))
1257
        if cursor.fetchone() is None:
1258
            cursor.close()
1259
            cnx.close()
1260
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1261
                                   description='API.SPACE_NOT_FOUND')
1262
1263
        query = (" SELECT e.id, e.name, e.uuid "
1264
                 " FROM tbl_spaces s, tbl_spaces_equipments se, tbl_equipments e "
1265
                 " WHERE se.space_id = s.id AND e.id = se.equipment_id AND s.id = %s "
1266
                 " ORDER BY e.id ")
1267
        cursor.execute(query, (id_,))
1268
        rows = cursor.fetchall()
1269
1270
        result = list()
1271
        if rows is not None and len(rows) > 0:
1272
            for row in rows:
1273
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1274
                result.append(meta_result)
1275
1276
        resp.text = json.dumps(result)
1277
1278
    @staticmethod
1279
    @user_logger
1280
    def on_post(req, resp, id_):
1281
        """Handles POST requests"""
1282
        admin_control(req)
1283
        try:
1284
            raw_json = req.stream.read().decode('utf-8')
1285
        except Exception as ex:
1286
            raise falcon.HTTPError(status=falcon.HTTP_400,
1287
                                   title='API.BAD_REQUEST',
1288
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1289
1290
        if not id_.isdigit() or int(id_) <= 0:
1291
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1292
                                   description='API.INVALID_SPACE_ID')
1293
1294
        new_values = json.loads(raw_json)
1295
1296
        if 'equipment_id' not in new_values['data'].keys() or \
1297
                not isinstance(new_values['data']['equipment_id'], int) or \
1298
                new_values['data']['equipment_id'] <= 0:
1299
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1300
                                   description='API.INVALID_EQUIPMENT_ID')
1301
        equipment_id = new_values['data']['equipment_id']
1302
1303
        cnx = mysql.connector.connect(**config.myems_system_db)
1304
        cursor = cnx.cursor()
1305
1306
        cursor.execute(" SELECT name "
1307
                       " from tbl_spaces "
1308
                       " WHERE id = %s ", (id_,))
1309
        if cursor.fetchone() is None:
1310
            cursor.close()
1311
            cnx.close()
1312
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1313
                                   description='API.SPACE_NOT_FOUND')
1314
1315
        cursor.execute(" SELECT name "
1316
                       " FROM tbl_equipments "
1317
                       " WHERE id = %s ", (equipment_id,))
1318
        if cursor.fetchone() is None:
1319
            cursor.close()
1320
            cnx.close()
1321
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1322
                                   description='API.EQUIPMENT_NOT_FOUND')
1323
1324
        query = (" SELECT id " 
1325
                 " FROM tbl_spaces_equipments "
1326
                 " WHERE space_id = %s AND equipment_id = %s")
1327
        cursor.execute(query, (id_, equipment_id,))
1328
        if cursor.fetchone() is not None:
1329
            cursor.close()
1330
            cnx.close()
1331
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1332
                                   description='API.SPACE_EQUIPMENT_RELATION_EXISTS')
1333
1334
        add_row = (" INSERT INTO tbl_spaces_equipments (space_id, equipment_id) "
1335
                   " VALUES (%s, %s) ")
1336
        cursor.execute(add_row, (id_, equipment_id,))
1337
        cnx.commit()
1338
        cursor.close()
1339
        cnx.close()
1340
1341
        resp.status = falcon.HTTP_201
1342
        resp.location = '/spaces/' + str(id_) + '/equipments/' + str(equipment_id)
1343
1344
1345
class SpaceEquipmentItem:
@@ 839-951 (lines=113) @@
836
        resp.text = json.dumps(result)
837
838
839
class SpaceCombinedEquipmentCollection:
840
    def __init__(self):
841
        """Initializes Class"""
842
        pass
843
844
    @staticmethod
845
    def on_options(req, resp, id_):
846
        resp.status = falcon.HTTP_200
847
848
    @staticmethod
849
    def on_get(req, resp, id_):
850
        if 'API-KEY' not in req.headers or \
851
                not isinstance(req.headers['API-KEY'], str) or \
852
                len(str.strip(req.headers['API-KEY'])) == 0:
853
            access_control(req)
854
        else:
855
            api_key_control(req)
856
        if not id_.isdigit() or int(id_) <= 0:
857
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
858
                                   description='API.INVALID_SPACE_ID')
859
860
        cnx = mysql.connector.connect(**config.myems_system_db)
861
        cursor = cnx.cursor()
862
863
        cursor.execute(" SELECT name "
864
                       " FROM tbl_spaces "
865
                       " WHERE id = %s ", (id_,))
866
        if cursor.fetchone() is None:
867
            cursor.close()
868
            cnx.close()
869
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
870
                                   description='API.SPACE_NOT_FOUND')
871
872
        query = (" SELECT e.id, e.name, e.uuid "
873
                 " FROM tbl_spaces s, tbl_spaces_combined_equipments se, tbl_combined_equipments e "
874
                 " WHERE se.space_id = s.id AND e.id = se.combined_equipment_id AND s.id = %s "
875
                 " ORDER BY e.id ")
876
        cursor.execute(query, (id_,))
877
        rows = cursor.fetchall()
878
879
        result = list()
880
        if rows is not None and len(rows) > 0:
881
            for row in rows:
882
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
883
                result.append(meta_result)
884
885
        resp.text = json.dumps(result)
886
887
    @staticmethod
888
    @user_logger
889
    def on_post(req, resp, id_):
890
        """Handles POST requests"""
891
        admin_control(req)
892
        try:
893
            raw_json = req.stream.read().decode('utf-8')
894
        except Exception as ex:
895
            raise falcon.HTTPError(status=falcon.HTTP_400,
896
                                   title='API.BAD_REQUEST',
897
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
898
899
        if not id_.isdigit() or int(id_) <= 0:
900
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
901
                                   description='API.INVALID_SPACE_ID')
902
903
        new_values = json.loads(raw_json)
904
905
        if 'combined_equipment_id' not in new_values['data'].keys() or \
906
                not isinstance(new_values['data']['combined_equipment_id'], int) or \
907
                new_values['data']['combined_equipment_id'] <= 0:
908
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
909
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
910
        combined_equipment_id = new_values['data']['combined_equipment_id']
911
912
        cnx = mysql.connector.connect(**config.myems_system_db)
913
        cursor = cnx.cursor()
914
915
        cursor.execute(" SELECT name "
916
                       " from tbl_spaces "
917
                       " WHERE id = %s ", (id_,))
918
        if cursor.fetchone() is None:
919
            cursor.close()
920
            cnx.close()
921
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
922
                                   description='API.SPACE_NOT_FOUND')
923
924
        cursor.execute(" SELECT name "
925
                       " FROM tbl_combined_equipments "
926
                       " WHERE id = %s ", (combined_equipment_id,))
927
        if cursor.fetchone() is None:
928
            cursor.close()
929
            cnx.close()
930
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
931
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
932
933
        query = (" SELECT id " 
934
                 " FROM tbl_spaces_combined_equipments "
935
                 " WHERE space_id = %s AND combined_equipment_id = %s")
936
        cursor.execute(query, (id_, combined_equipment_id,))
937
        if cursor.fetchone() is not None:
938
            cursor.close()
939
            cnx.close()
940
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
941
                                   description='API.SPACE_COMBINED_EQUIPMENT_RELATION_EXISTS')
942
943
        add_row = (" INSERT INTO tbl_spaces_combined_equipments (space_id, combined_equipment_id) "
944
                   " VALUES (%s, %s) ")
945
        cursor.execute(add_row, (id_, combined_equipment_id,))
946
        cnx.commit()
947
        cursor.close()
948
        cnx.close()
949
950
        resp.status = falcon.HTTP_201
951
        resp.location = '/spaces/' + str(id_) + '/combinedequipments/' + str(combined_equipment_id)
952
953
954
class SpaceCombinedEquipmentItem:

myems-api/core/shopfloor.py 4 locations

@@ 1739-1851 (lines=113) @@
1736
        resp.status = falcon.HTTP_204
1737
1738
1739
class ShopfloorCommandCollection:
1740
    def __init__(self):
1741
        """Initializes Class"""
1742
        pass
1743
1744
    @staticmethod
1745
    def on_options(req, resp, id_):
1746
        resp.status = falcon.HTTP_200
1747
1748
    @staticmethod
1749
    def on_get(req, resp, id_):
1750
        if 'API-KEY' not in req.headers or \
1751
                not isinstance(req.headers['API-KEY'], str) or \
1752
                len(str.strip(req.headers['API-KEY'])) == 0:
1753
            access_control(req)
1754
        else:
1755
            api_key_control(req)
1756
        if not id_.isdigit() or int(id_) <= 0:
1757
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1758
                                   description='API.INVALID_STORE_ID')
1759
1760
        cnx = mysql.connector.connect(**config.myems_system_db)
1761
        cursor = cnx.cursor()
1762
1763
        cursor.execute(" SELECT name "
1764
                       " FROM tbl_shopfloors "
1765
                       " WHERE id = %s ", (id_,))
1766
        if cursor.fetchone() is None:
1767
            cursor.close()
1768
            cnx.close()
1769
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1770
                                   description='API.SHOPFLOOR_NOT_FOUND')
1771
1772
        query = (" SELECT c.id, c.name, c.uuid "
1773
                 " FROM tbl_shopfloors s, tbl_shopfloors_commands sc, tbl_commands c "
1774
                 " WHERE sc.shopfloor_id = s.id AND c.id = sc.command_id AND s.id = %s "
1775
                 " ORDER BY c.id ")
1776
        cursor.execute(query, (id_,))
1777
        rows = cursor.fetchall()
1778
1779
        result = list()
1780
        if rows is not None and len(rows) > 0:
1781
            for row in rows:
1782
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1783
                result.append(meta_result)
1784
1785
        resp.text = json.dumps(result)
1786
1787
    @staticmethod
1788
    @user_logger
1789
    def on_post(req, resp, id_):
1790
        """Handles POST requests"""
1791
        admin_control(req)
1792
        try:
1793
            raw_json = req.stream.read().decode('utf-8')
1794
        except Exception as ex:
1795
            raise falcon.HTTPError(status=falcon.HTTP_400,
1796
                                   title='API.BAD_REQUEST',
1797
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1798
1799
        if not id_.isdigit() or int(id_) <= 0:
1800
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1801
                                   description='API.INVALID_SHOPFLOOR_ID')
1802
1803
        new_values = json.loads(raw_json)
1804
1805
        if 'command_id' not in new_values['data'].keys() or \
1806
                not isinstance(new_values['data']['command_id'], int) or \
1807
                new_values['data']['command_id'] <= 0:
1808
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1809
                                   description='API.INVALID_COMMAND_ID')
1810
        command_id = new_values['data']['command_id']
1811
1812
        cnx = mysql.connector.connect(**config.myems_system_db)
1813
        cursor = cnx.cursor()
1814
1815
        cursor.execute(" SELECT name "
1816
                       " from tbl_shopfloors "
1817
                       " WHERE id = %s ", (id_,))
1818
        if cursor.fetchone() is None:
1819
            cursor.close()
1820
            cnx.close()
1821
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1822
                                   description='API.SHOPFLOOR_NOT_FOUND')
1823
1824
        cursor.execute(" SELECT name "
1825
                       " FROM tbl_commands "
1826
                       " WHERE id = %s ", (command_id,))
1827
        if cursor.fetchone() is None:
1828
            cursor.close()
1829
            cnx.close()
1830
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1831
                                   description='API.COMMAND_NOT_FOUND')
1832
1833
        query = (" SELECT id " 
1834
                 " FROM tbl_shopfloors_commands "
1835
                 " WHERE shopfloor_id = %s AND command_id = %s")
1836
        cursor.execute(query, (id_, command_id,))
1837
        if cursor.fetchone() is not None:
1838
            cursor.close()
1839
            cnx.close()
1840
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1841
                                   description='API.SHOPFLOOR_COMMAND_RELATION_EXISTS')
1842
1843
        add_row = (" INSERT INTO tbl_shopfloors_commands (shopfloor_id, command_id) "
1844
                   " VALUES (%s, %s) ")
1845
        cursor.execute(add_row, (id_, command_id,))
1846
        cnx.commit()
1847
        cursor.close()
1848
        cnx.close()
1849
1850
        resp.status = falcon.HTTP_201
1851
        resp.location = '/shopfloors/' + str(id_) + '/commands/' + str(command_id)
1852
1853
1854
class ShopfloorCommandItem:
@@ 1563-1675 (lines=113) @@
1560
        resp.status = falcon.HTTP_204
1561
1562
1563
class ShopfloorWorkingCalendarCollection:
1564
    def __init__(self):
1565
        """Initializes ShopfloorWorkingCalendarCollection Class"""
1566
        pass
1567
1568
    @staticmethod
1569
    def on_options(req, resp, id_):
1570
        resp.status = falcon.HTTP_200
1571
1572
    @staticmethod
1573
    def on_get(req, resp, id_):
1574
        if 'API-KEY' not in req.headers or \
1575
                not isinstance(req.headers['API-KEY'], str) or \
1576
                len(str.strip(req.headers['API-KEY'])) == 0:
1577
            access_control(req)
1578
        else:
1579
            api_key_control(req)
1580
        if not id_.isdigit() or int(id_) <= 0:
1581
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1582
                                   description='API.INVALID_SHOPFLOOR_ID')
1583
1584
        cnx = mysql.connector.connect(**config.myems_system_db)
1585
        cursor = cnx.cursor()
1586
1587
        cursor.execute(" SELECT name "
1588
                       " FROM tbl_shopfloors "
1589
                       " WHERE id = %s ", (id_,))
1590
        if cursor.fetchone() is None:
1591
            cursor.close()
1592
            cnx.close()
1593
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1594
                                   description='API.SHOPFLOOR_NOT_FOUND')
1595
1596
        query = (" SELECT wc.id, wc.name, wc.description "
1597
                 " FROM tbl_shopfloors s, tbl_shopfloors_working_calendars swc, tbl_working_calendars wc "
1598
                 " WHERE swc.shopfloor_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
1599
                 " ORDER BY wc.id ")
1600
        cursor.execute(query, (id_,))
1601
        rows = cursor.fetchall()
1602
1603
        result = list()
1604
        if rows is not None and len(rows) > 0:
1605
            for row in rows:
1606
                meta_result = {"id": row[0], "name": row[1], "description": row[2]}
1607
                result.append(meta_result)
1608
1609
        resp.text = json.dumps(result)
1610
1611
    @staticmethod
1612
    @user_logger
1613
    def on_post(req, resp, id_):
1614
        """Handles POST requests"""
1615
        admin_control(req)
1616
        try:
1617
            raw_json = req.stream.read().decode('utf-8')
1618
        except Exception as ex:
1619
            raise falcon.HTTPError(status=falcon.HTTP_400,
1620
                                   title='API.BAD_REQUEST',
1621
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1622
1623
        if not id_.isdigit() or int(id_) <= 0:
1624
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1625
                                   description='API.INVALID_SHOPFLOOR_ID')
1626
1627
        new_values = json.loads(raw_json)
1628
1629
        if 'working_calendar_id' not in new_values['data'].keys() or \
1630
                not isinstance(new_values['data']['working_calendar_id'], int) or \
1631
                new_values['data']['working_calendar_id'] <= 0:
1632
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1633
                                   description='API.INVALID_WORKING_CALENDAR_ID')
1634
        working_calendar_id = new_values['data']['working_calendar_id']
1635
1636
        cnx = mysql.connector.connect(**config.myems_system_db)
1637
        cursor = cnx.cursor()
1638
1639
        cursor.execute(" SELECT name "
1640
                       " from tbl_shopfloors "
1641
                       " WHERE id = %s ", (id_,))
1642
        if cursor.fetchone() is None:
1643
            cursor.close()
1644
            cnx.close()
1645
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1646
                                   description='API.SHOPFLOOR_NOT_FOUND')
1647
1648
        cursor.execute(" SELECT name "
1649
                       " FROM tbl_working_calendars "
1650
                       " WHERE id = %s ", (working_calendar_id,))
1651
        if cursor.fetchone() is None:
1652
            cursor.close()
1653
            cnx.close()
1654
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1655
                                   description='API.WORKING_CALENDAR_NOT_FOUND')
1656
1657
        query = (" SELECT id " 
1658
                 " FROM tbl_shopfloors_working_calendars "
1659
                 " WHERE shopfloor_id = %s AND working_calendar_id = %s")
1660
        cursor.execute(query, (id_, working_calendar_id,))
1661
        if cursor.fetchone() is not None:
1662
            cursor.close()
1663
            cnx.close()
1664
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1665
                                   description='API.SHOPFLOOR_WORKING_CALENDAR_RELATION_EXISTS')
1666
1667
        add_row = (" INSERT INTO tbl_shopfloors_working_calendars (shopfloor_id, working_calendar_id) "
1668
                   " VALUES (%s, %s) ")
1669
        cursor.execute(add_row, (id_, working_calendar_id,))
1670
        cnx.commit()
1671
        cursor.close()
1672
        cnx.close()
1673
1674
        resp.status = falcon.HTTP_201
1675
        resp.location = '/shopfloors/' + str(id_) + '/workingcalendars/' + str(working_calendar_id)
1676
1677
1678
class ShopfloorWorkingCalendarItem:
@@ 1199-1311 (lines=113) @@
1196
        resp.status = falcon.HTTP_204
1197
1198
1199
class ShopfloorSensorCollection:
1200
    def __init__(self):
1201
        """Initializes ShopfloorSensorCollection"""
1202
        pass
1203
1204
    @staticmethod
1205
    def on_options(req, resp, id_):
1206
        resp.status = falcon.HTTP_200
1207
1208
    @staticmethod
1209
    def on_get(req, resp, id_):
1210
        if 'API-KEY' not in req.headers or \
1211
                not isinstance(req.headers['API-KEY'], str) or \
1212
                len(str.strip(req.headers['API-KEY'])) == 0:
1213
            access_control(req)
1214
        else:
1215
            api_key_control(req)
1216
        if not id_.isdigit() or int(id_) <= 0:
1217
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1218
                                   description='API.INVALID_SHOPFLOOR_ID')
1219
1220
        cnx = mysql.connector.connect(**config.myems_system_db)
1221
        cursor = cnx.cursor()
1222
1223
        cursor.execute(" SELECT name "
1224
                       " FROM tbl_shopfloors "
1225
                       " WHERE id = %s ", (id_,))
1226
        if cursor.fetchone() is None:
1227
            cursor.close()
1228
            cnx.close()
1229
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1230
                                   description='API.SHOPFLOOR_NOT_FOUND')
1231
1232
        query = (" SELECT se.id, se.name, se.uuid "
1233
                 " FROM tbl_shopfloors sp, tbl_shopfloors_sensors ss, tbl_sensors se "
1234
                 " WHERE ss.shopfloor_id = sp.id AND se.id = ss.sensor_id AND sp.id = %s "
1235
                 " ORDER BY se.id ")
1236
        cursor.execute(query, (id_,))
1237
        rows = cursor.fetchall()
1238
1239
        result = list()
1240
        if rows is not None and len(rows) > 0:
1241
            for row in rows:
1242
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1243
                result.append(meta_result)
1244
1245
        resp.text = json.dumps(result)
1246
1247
    @staticmethod
1248
    @user_logger
1249
    def on_post(req, resp, id_):
1250
        """Handles POST requests"""
1251
        admin_control(req)
1252
        try:
1253
            raw_json = req.stream.read().decode('utf-8')
1254
        except Exception as ex:
1255
            raise falcon.HTTPError(status=falcon.HTTP_400,
1256
                                   title='API.BAD_REQUEST',
1257
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1258
1259
        if not id_.isdigit() or int(id_) <= 0:
1260
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1261
                                   description='API.INVALID_SHOPFLOOR_ID')
1262
1263
        new_values = json.loads(raw_json)
1264
1265
        if 'sensor_id' not in new_values['data'].keys() or \
1266
                not isinstance(new_values['data']['sensor_id'], int) or \
1267
                new_values['data']['sensor_id'] <= 0:
1268
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1269
                                   description='API.INVALID_SENSOR_ID')
1270
        sensor_id = new_values['data']['sensor_id']
1271
1272
        cnx = mysql.connector.connect(**config.myems_system_db)
1273
        cursor = cnx.cursor()
1274
1275
        cursor.execute(" SELECT name "
1276
                       " from tbl_shopfloors "
1277
                       " WHERE id = %s ", (id_,))
1278
        if cursor.fetchone() is None:
1279
            cursor.close()
1280
            cnx.close()
1281
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1282
                                   description='API.SHOPFLOOR_NOT_FOUND')
1283
1284
        cursor.execute(" SELECT name "
1285
                       " FROM tbl_sensors "
1286
                       " WHERE id = %s ", (sensor_id,))
1287
        if cursor.fetchone() is None:
1288
            cursor.close()
1289
            cnx.close()
1290
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1291
                                   description='API.SENSOR_NOT_FOUND')
1292
1293
        query = (" SELECT id " 
1294
                 " FROM tbl_shopfloors_sensors "
1295
                 " WHERE shopfloor_id = %s AND sensor_id = %s")
1296
        cursor.execute(query, (id_, sensor_id,))
1297
        if cursor.fetchone() is not None:
1298
            cursor.close()
1299
            cnx.close()
1300
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1301
                                   description='API.SHOPFLOOR_SENSOR_RELATION_EXISTS')
1302
1303
        add_row = (" INSERT INTO tbl_shopfloors_sensors (shopfloor_id, sensor_id) "
1304
                   " VALUES (%s, %s) ")
1305
        cursor.execute(add_row, (id_, sensor_id,))
1306
        cnx.commit()
1307
        cursor.close()
1308
        cnx.close()
1309
1310
        resp.status = falcon.HTTP_201
1311
        resp.location = '/shopfloors/' + str(id_) + '/sensors/' + str(sensor_id)
1312
1313
1314
class ShopfloorSensorItem:
@@ 458-570 (lines=113) @@
455
        resp.status = falcon.HTTP_200
456
457
458
class ShopfloorEquipmentCollection:
459
    def __init__(self):
460
        """Initializes ShopfloorEquipmentCollection"""
461
        pass
462
463
    @staticmethod
464
    def on_options(req, resp, id_):
465
        resp.status = falcon.HTTP_200
466
467
    @staticmethod
468
    def on_get(req, resp, id_):
469
        if 'API-KEY' not in req.headers or \
470
                not isinstance(req.headers['API-KEY'], str) or \
471
                len(str.strip(req.headers['API-KEY'])) == 0:
472
            access_control(req)
473
        else:
474
            api_key_control(req)
475
        if not id_.isdigit() or int(id_) <= 0:
476
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
477
                                   description='API.INVALID_SHOPFLOOR_ID')
478
479
        cnx = mysql.connector.connect(**config.myems_system_db)
480
        cursor = cnx.cursor()
481
482
        cursor.execute(" SELECT name "
483
                       " FROM tbl_shopfloors "
484
                       " WHERE id = %s ", (id_,))
485
        if cursor.fetchone() is None:
486
            cursor.close()
487
            cnx.close()
488
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
489
                                   description='API.SHOPFLOOR_NOT_FOUND')
490
491
        query = (" SELECT e.id, e.name, e.uuid "
492
                 " FROM tbl_shopfloors s, tbl_shopfloors_equipments se, tbl_equipments e "
493
                 " WHERE se.shopfloor_id = s.id AND e.id = se.equipment_id AND s.id = %s "
494
                 " ORDER BY e.id ")
495
        cursor.execute(query, (id_,))
496
        rows = cursor.fetchall()
497
498
        result = list()
499
        if rows is not None and len(rows) > 0:
500
            for row in rows:
501
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
502
                result.append(meta_result)
503
504
        resp.text = json.dumps(result)
505
506
    @staticmethod
507
    @user_logger
508
    def on_post(req, resp, id_):
509
        """Handles POST requests"""
510
        admin_control(req)
511
        try:
512
            raw_json = req.stream.read().decode('utf-8')
513
        except Exception as ex:
514
            raise falcon.HTTPError(status=falcon.HTTP_400,
515
                                   title='API.BAD_REQUEST',
516
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
517
518
        if not id_.isdigit() or int(id_) <= 0:
519
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
520
                                   description='API.INVALID_SHOPFLOOR_ID')
521
522
        new_values = json.loads(raw_json)
523
524
        if 'equipment_id' not in new_values['data'].keys() or \
525
                not isinstance(new_values['data']['equipment_id'], int) or \
526
                new_values['data']['equipment_id'] <= 0:
527
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
528
                                   description='API.INVALID_EQUIPMENT_ID')
529
        equipment_id = new_values['data']['equipment_id']
530
531
        cnx = mysql.connector.connect(**config.myems_system_db)
532
        cursor = cnx.cursor()
533
534
        cursor.execute(" SELECT name "
535
                       " from tbl_shopfloors "
536
                       " WHERE id = %s ", (id_,))
537
        if cursor.fetchone() is None:
538
            cursor.close()
539
            cnx.close()
540
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
541
                                   description='API.SHOPFLOOR_NOT_FOUND')
542
543
        cursor.execute(" SELECT name "
544
                       " FROM tbl_equipments "
545
                       " WHERE id = %s ", (equipment_id,))
546
        if cursor.fetchone() is None:
547
            cursor.close()
548
            cnx.close()
549
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
550
                                   description='API.EQUIPMENT_NOT_FOUND')
551
552
        query = (" SELECT id " 
553
                 " FROM tbl_shopfloors_equipments "
554
                 " WHERE shopfloor_id = %s AND equipment_id = %s")
555
        cursor.execute(query, (id_, equipment_id,))
556
        if cursor.fetchone() is not None:
557
            cursor.close()
558
            cnx.close()
559
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
560
                                   description='API.SHOPFLOOR_EQUIPMENT_RELATION_EXISTS')
561
562
        add_row = (" INSERT INTO tbl_shopfloors_equipments (shopfloor_id, equipment_id) "
563
                   " VALUES (%s, %s) ")
564
        cursor.execute(add_row, (id_, equipment_id,))
565
        cnx.commit()
566
        cursor.close()
567
        cnx.close()
568
569
        resp.status = falcon.HTTP_201
570
        resp.location = '/shopfloors/' + str(id_) + '/equipments/' + str(equipment_id)
571
572
573
class ShopfloorEquipmentItem:

myems-api/core/store.py 3 locations

@@ 1682-1794 (lines=113) @@
1679
        resp.status = falcon.HTTP_204
1680
1681
1682
class StoreCommandCollection:
1683
    def __init__(self):
1684
        """Initializes Class"""
1685
        pass
1686
1687
    @staticmethod
1688
    def on_options(req, resp, id_):
1689
        resp.status = falcon.HTTP_200
1690
1691
    @staticmethod
1692
    def on_get(req, resp, id_):
1693
        if 'API-KEY' not in req.headers or \
1694
                not isinstance(req.headers['API-KEY'], str) or \
1695
                len(str.strip(req.headers['API-KEY'])) == 0:
1696
            access_control(req)
1697
        else:
1698
            api_key_control(req)
1699
        if not id_.isdigit() or int(id_) <= 0:
1700
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1701
                                   description='API.INVALID_STORE_ID')
1702
1703
        cnx = mysql.connector.connect(**config.myems_system_db)
1704
        cursor = cnx.cursor()
1705
1706
        cursor.execute(" SELECT name "
1707
                       " FROM tbl_stores "
1708
                       " WHERE id = %s ", (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.STORE_NOT_FOUND')
1714
1715
        query = (" SELECT c.id, c.name, c.uuid "
1716
                 " FROM tbl_stores s, tbl_stores_commands sc, tbl_commands c "
1717
                 " WHERE sc.store_id = s.id AND c.id = sc.command_id AND s.id = %s "
1718
                 " ORDER BY c.id ")
1719
        cursor.execute(query, (id_,))
1720
        rows = cursor.fetchall()
1721
1722
        result = list()
1723
        if rows is not None and len(rows) > 0:
1724
            for row in rows:
1725
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1726
                result.append(meta_result)
1727
1728
        resp.text = json.dumps(result)
1729
1730
    @staticmethod
1731
    @user_logger
1732
    def on_post(req, resp, id_):
1733
        """Handles POST requests"""
1734
        admin_control(req)
1735
        try:
1736
            raw_json = req.stream.read().decode('utf-8')
1737
        except Exception as ex:
1738
            raise falcon.HTTPError(status=falcon.HTTP_400,
1739
                                   title='API.BAD_REQUEST',
1740
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1741
1742
        if not id_.isdigit() or int(id_) <= 0:
1743
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1744
                                   description='API.INVALID_STORE_ID')
1745
1746
        new_values = json.loads(raw_json)
1747
1748
        if 'command_id' not in new_values['data'].keys() or \
1749
                not isinstance(new_values['data']['command_id'], int) or \
1750
                new_values['data']['command_id'] <= 0:
1751
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1752
                                   description='API.INVALID_COMMAND_ID')
1753
        command_id = new_values['data']['command_id']
1754
1755
        cnx = mysql.connector.connect(**config.myems_system_db)
1756
        cursor = cnx.cursor()
1757
1758
        cursor.execute(" SELECT name "
1759
                       " from tbl_stores "
1760
                       " WHERE id = %s ", (id_,))
1761
        if cursor.fetchone() is None:
1762
            cursor.close()
1763
            cnx.close()
1764
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1765
                                   description='API.STORE_NOT_FOUND')
1766
1767
        cursor.execute(" SELECT name "
1768
                       " FROM tbl_commands "
1769
                       " WHERE id = %s ", (command_id,))
1770
        if cursor.fetchone() is None:
1771
            cursor.close()
1772
            cnx.close()
1773
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1774
                                   description='API.COMMAND_NOT_FOUND')
1775
1776
        query = (" SELECT id " 
1777
                 " FROM tbl_stores_commands "
1778
                 " WHERE store_id = %s AND command_id = %s")
1779
        cursor.execute(query, (id_, command_id,))
1780
        if cursor.fetchone() is not None:
1781
            cursor.close()
1782
            cnx.close()
1783
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1784
                                   description='API.STORE_COMMAND_RELATION_EXISTS')
1785
1786
        add_row = (" INSERT INTO tbl_stores_commands (store_id, command_id) "
1787
                   " VALUES (%s, %s) ")
1788
        cursor.execute(add_row, (id_, command_id,))
1789
        cnx.commit()
1790
        cursor.close()
1791
        cnx.close()
1792
1793
        resp.status = falcon.HTTP_201
1794
        resp.location = '/stores/' + str(id_) + '/commands/' + str(command_id)
1795
1796
1797
class StoreCommandItem:
@@ 1506-1618 (lines=113) @@
1503
        resp.status = falcon.HTTP_204
1504
1505
1506
class StoreWorkingCalendarCollection:
1507
    def __init__(self):
1508
        """Initializes StoreWorkingCalendarCollection Class"""
1509
        pass
1510
1511
    @staticmethod
1512
    def on_options(req, resp, id_):
1513
        resp.status = falcon.HTTP_200
1514
1515
    @staticmethod
1516
    def on_get(req, resp, id_):
1517
        if 'API-KEY' not in req.headers or \
1518
                not isinstance(req.headers['API-KEY'], str) or \
1519
                len(str.strip(req.headers['API-KEY'])) == 0:
1520
            access_control(req)
1521
        else:
1522
            api_key_control(req)
1523
        if not id_.isdigit() or int(id_) <= 0:
1524
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1525
                                   description='API.INVALID_STORE_ID')
1526
1527
        cnx = mysql.connector.connect(**config.myems_system_db)
1528
        cursor = cnx.cursor()
1529
1530
        cursor.execute(" SELECT name "
1531
                       " FROM tbl_stores "
1532
                       " WHERE id = %s ", (id_,))
1533
        if cursor.fetchone() is None:
1534
            cursor.close()
1535
            cnx.close()
1536
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1537
                                   description='API.STORE_NOT_FOUND')
1538
1539
        query = (" SELECT wc.id, wc.name, wc.description "
1540
                 " FROM tbl_stores s, tbl_stores_working_calendars swc, tbl_working_calendars wc "
1541
                 " WHERE swc.store_id = s.id AND wc.id = swc.working_calendar_id AND s.id = %s "
1542
                 " ORDER BY wc.id ")
1543
        cursor.execute(query, (id_,))
1544
        rows = cursor.fetchall()
1545
1546
        result = list()
1547
        if rows is not None and len(rows) > 0:
1548
            for row in rows:
1549
                meta_result = {"id": row[0], "name": row[1], "description": row[2]}
1550
                result.append(meta_result)
1551
1552
        resp.text = json.dumps(result)
1553
1554
    @staticmethod
1555
    @user_logger
1556
    def on_post(req, resp, id_):
1557
        """Handles POST requests"""
1558
        admin_control(req)
1559
        try:
1560
            raw_json = req.stream.read().decode('utf-8')
1561
        except Exception as ex:
1562
            raise falcon.HTTPError(status=falcon.HTTP_400,
1563
                                   title='API.BAD_REQUEST',
1564
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1565
1566
        if not id_.isdigit() or int(id_) <= 0:
1567
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1568
                                   description='API.INVALID_STORE_ID')
1569
1570
        new_values = json.loads(raw_json)
1571
1572
        if 'working_calendar_id' not in new_values['data'].keys() or \
1573
                not isinstance(new_values['data']['working_calendar_id'], int) or \
1574
                new_values['data']['working_calendar_id'] <= 0:
1575
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1576
                                   description='API.INVALID_WORKING_CALENDAR_ID')
1577
        working_calendar_id = new_values['data']['working_calendar_id']
1578
1579
        cnx = mysql.connector.connect(**config.myems_system_db)
1580
        cursor = cnx.cursor()
1581
1582
        cursor.execute(" SELECT name "
1583
                       " from tbl_stores "
1584
                       " WHERE id = %s ", (id_,))
1585
        if cursor.fetchone() is None:
1586
            cursor.close()
1587
            cnx.close()
1588
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1589
                                   description='API.STORE_NOT_FOUND')
1590
1591
        cursor.execute(" SELECT name "
1592
                       " FROM tbl_working_calendars "
1593
                       " WHERE id = %s ", (working_calendar_id,))
1594
        if cursor.fetchone() is None:
1595
            cursor.close()
1596
            cnx.close()
1597
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1598
                                   description='API.WORKING_CALENDAR_NOT_FOUND')
1599
1600
        query = (" SELECT id " 
1601
                 " FROM tbl_stores_working_calendars "
1602
                 " WHERE store_id = %s AND working_calendar_id = %s")
1603
        cursor.execute(query, (id_, working_calendar_id,))
1604
        if cursor.fetchone() is not None:
1605
            cursor.close()
1606
            cnx.close()
1607
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1608
                                   description='API.STORE_WORKING_CALENDAR_RELATION_EXISTS')
1609
1610
        add_row = (" INSERT INTO tbl_stores_working_calendars (store_id, working_calendar_id) "
1611
                   " VALUES (%s, %s) ")
1612
        cursor.execute(add_row, (id_, working_calendar_id,))
1613
        cnx.commit()
1614
        cursor.close()
1615
        cnx.close()
1616
1617
        resp.status = falcon.HTTP_201
1618
        resp.location = '/stores/' + str(id_) + '/workingcalendars/' + str(working_calendar_id)
1619
1620
1621
class StoreWorkingCalendarItem:
@@ 1142-1254 (lines=113) @@
1139
        resp.status = falcon.HTTP_204
1140
1141
1142
class StoreSensorCollection:
1143
    def __init__(self):
1144
        """Initializes Class"""
1145
        pass
1146
1147
    @staticmethod
1148
    def on_options(req, resp, id_):
1149
        resp.status = falcon.HTTP_200
1150
1151
    @staticmethod
1152
    def on_get(req, resp, id_):
1153
        if 'API-KEY' not in req.headers or \
1154
                not isinstance(req.headers['API-KEY'], str) or \
1155
                len(str.strip(req.headers['API-KEY'])) == 0:
1156
            access_control(req)
1157
        else:
1158
            api_key_control(req)
1159
        if not id_.isdigit() or int(id_) <= 0:
1160
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1161
                                   description='API.INVALID_STORE_ID')
1162
1163
        cnx = mysql.connector.connect(**config.myems_system_db)
1164
        cursor = cnx.cursor()
1165
1166
        cursor.execute(" SELECT name "
1167
                       " FROM tbl_stores "
1168
                       " WHERE id = %s ", (id_,))
1169
        if cursor.fetchone() is None:
1170
            cursor.close()
1171
            cnx.close()
1172
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1173
                                   description='API.STORE_NOT_FOUND')
1174
1175
        query = (" SELECT s.id, s.name, s.uuid "
1176
                 " FROM tbl_stores t, tbl_stores_sensors ts, tbl_sensors s "
1177
                 " WHERE ts.store_id = t.id AND s.id = ts.sensor_id AND t.id = %s "
1178
                 " ORDER BY s.id ")
1179
        cursor.execute(query, (id_,))
1180
        rows = cursor.fetchall()
1181
1182
        result = list()
1183
        if rows is not None and len(rows) > 0:
1184
            for row in rows:
1185
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1186
                result.append(meta_result)
1187
1188
        resp.text = json.dumps(result)
1189
1190
    @staticmethod
1191
    @user_logger
1192
    def on_post(req, resp, id_):
1193
        """Handles POST requests"""
1194
        admin_control(req)
1195
        try:
1196
            raw_json = req.stream.read().decode('utf-8')
1197
        except Exception as ex:
1198
            raise falcon.HTTPError(status=falcon.HTTP_400,
1199
                                   title='API.BAD_REQUEST',
1200
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1201
1202
        if not id_.isdigit() or int(id_) <= 0:
1203
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1204
                                   description='API.INVALID_STORE_ID')
1205
1206
        new_values = json.loads(raw_json)
1207
1208
        if 'sensor_id' not in new_values['data'].keys() or \
1209
                not isinstance(new_values['data']['sensor_id'], int) or \
1210
                new_values['data']['sensor_id'] <= 0:
1211
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1212
                                   description='API.INVALID_SENSOR_ID')
1213
        sensor_id = new_values['data']['sensor_id']
1214
1215
        cnx = mysql.connector.connect(**config.myems_system_db)
1216
        cursor = cnx.cursor()
1217
1218
        cursor.execute(" SELECT name "
1219
                       " from tbl_stores "
1220
                       " WHERE id = %s ", (id_,))
1221
        if cursor.fetchone() is None:
1222
            cursor.close()
1223
            cnx.close()
1224
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1225
                                   description='API.STORE_NOT_FOUND')
1226
1227
        cursor.execute(" SELECT name "
1228
                       " FROM tbl_sensors "
1229
                       " WHERE id = %s ", (sensor_id,))
1230
        if cursor.fetchone() is None:
1231
            cursor.close()
1232
            cnx.close()
1233
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1234
                                   description='API.SENSOR_NOT_FOUND')
1235
1236
        query = (" SELECT id " 
1237
                 " FROM tbl_stores_sensors "
1238
                 " WHERE store_id = %s AND sensor_id = %s")
1239
        cursor.execute(query, (id_, sensor_id,))
1240
        if cursor.fetchone() is not None:
1241
            cursor.close()
1242
            cnx.close()
1243
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1244
                                   description='API.STORE_SENSOR_RELATION_EXISTS')
1245
1246
        add_row = (" INSERT INTO tbl_stores_sensors (store_id, sensor_id) "
1247
                   " VALUES (%s, %s) ")
1248
        cursor.execute(add_row, (id_, sensor_id,))
1249
        cnx.commit()
1250
        cursor.close()
1251
        cnx.close()
1252
1253
        resp.status = falcon.HTTP_201
1254
        resp.location = '/stores/' + str(id_) + '/sensors/' + str(sensor_id)
1255
1256
1257
class StoreSensorItem:

myems-api/core/energystoragecontainer.py 1 location

@@ 1221-1333 (lines=113) @@
1218
        resp.status = falcon.HTTP_204
1219
1220
1221
class EnergyStorageContainerCommandCollection:
1222
    def __init__(self):
1223
        """Initializes Class"""
1224
        pass
1225
1226
    @staticmethod
1227
    def on_options(req, resp, id_):
1228
        resp.status = falcon.HTTP_200
1229
1230
    @staticmethod
1231
    def on_get(req, resp, id_):
1232
        if 'API-KEY' not in req.headers or \
1233
                not isinstance(req.headers['API-KEY'], str) or \
1234
                len(str.strip(req.headers['API-KEY'])) == 0:
1235
            access_control(req)
1236
        else:
1237
            api_key_control(req)
1238
        if not id_.isdigit() or int(id_) <= 0:
1239
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1240
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1241
1242
        cnx = mysql.connector.connect(**config.myems_system_db)
1243
        cursor = cnx.cursor()
1244
1245
        cursor.execute(" SELECT name "
1246
                       " FROM tbl_energy_storage_containers "
1247
                       " WHERE id = %s ", (id_,))
1248
        if cursor.fetchone() is None:
1249
            cursor.close()
1250
            cnx.close()
1251
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1252
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
1253
1254
        query = (" SELECT c.id, c.name, c.uuid "
1255
                 " FROM tbl_energy_storage_containers ce, tbl_energy_storage_containers_commands cec, tbl_commands c "
1256
                 " WHERE cec.energy_storage_container_id = ce.id AND c.id = cec.command_id AND ce.id = %s "
1257
                 " ORDER BY c.id ")
1258
        cursor.execute(query, (id_,))
1259
        rows = cursor.fetchall()
1260
1261
        result = list()
1262
        if rows is not None and len(rows) > 0:
1263
            for row in rows:
1264
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1265
                result.append(meta_result)
1266
1267
        resp.text = json.dumps(result)
1268
1269
    @staticmethod
1270
    @user_logger
1271
    def on_post(req, resp, id_):
1272
        """Handles POST requests"""
1273
        admin_control(req)
1274
        try:
1275
            raw_json = req.stream.read().decode('utf-8')
1276
        except Exception as ex:
1277
            raise falcon.HTTPError(status=falcon.HTTP_400,
1278
                                   title='API.BAD_REQUEST',
1279
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1280
1281
        if not id_.isdigit() or int(id_) <= 0:
1282
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1283
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1284
1285
        new_values = json.loads(raw_json)
1286
1287
        if 'command_id' not in new_values['data'].keys() or \
1288
                not isinstance(new_values['data']['command_id'], int) or \
1289
                new_values['data']['command_id'] <= 0:
1290
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1291
                                   description='API.INVALID_COMMAND_ID')
1292
        command_id = new_values['data']['command_id']
1293
1294
        cnx = mysql.connector.connect(**config.myems_system_db)
1295
        cursor = cnx.cursor()
1296
1297
        cursor.execute(" SELECT name "
1298
                       " from tbl_energy_storage_containers "
1299
                       " WHERE id = %s ", (id_,))
1300
        if cursor.fetchone() is None:
1301
            cursor.close()
1302
            cnx.close()
1303
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1304
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
1305
1306
        cursor.execute(" SELECT name "
1307
                       " FROM tbl_commands "
1308
                       " WHERE id = %s ", (command_id,))
1309
        if cursor.fetchone() is None:
1310
            cursor.close()
1311
            cnx.close()
1312
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1313
                                   description='API.COMMAND_NOT_FOUND')
1314
1315
        query = (" SELECT id " 
1316
                 " FROM tbl_energy_storage_containers_commands "
1317
                 " WHERE energy_storage_container_id = %s AND command_id = %s")
1318
        cursor.execute(query, (id_, command_id,))
1319
        if cursor.fetchone() is not None:
1320
            cursor.close()
1321
            cnx.close()
1322
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1323
                                   description='API.ENERGY_STORAGE_CONTAINER_COMMAND_RELATION_EXISTS')
1324
1325
        add_row = (" INSERT INTO tbl_energy_storage_containers_commands (energy_storage_container_id, command_id) "
1326
                   " VALUES (%s, %s) ")
1327
        cursor.execute(add_row, (id_, command_id,))
1328
        cnx.commit()
1329
        cursor.close()
1330
        cnx.close()
1331
1332
        resp.status = falcon.HTTP_201
1333
        resp.location = '/combinedequipments/' + str(id_) + '/commands/' + str(command_id)
1334
1335
1336
class EnergyStorageContainerCommandItem:

myems-api/core/meter.py 1 location

@@ 1142-1254 (lines=113) @@
1139
        resp.status = falcon.HTTP_204
1140
1141
1142
class MeterCommandCollection:
1143
    def __init__(self):
1144
        """Initializes Class"""
1145
        pass
1146
1147
    @staticmethod
1148
    def on_options(req, resp, id_):
1149
        resp.status = falcon.HTTP_200
1150
1151
    @staticmethod
1152
    def on_get(req, resp, id_):
1153
        if 'API-KEY' not in req.headers or \
1154
                not isinstance(req.headers['API-KEY'], str) or \
1155
                len(str.strip(req.headers['API-KEY'])) == 0:
1156
            access_control(req)
1157
        else:
1158
            api_key_control(req)
1159
        if not id_.isdigit() or int(id_) <= 0:
1160
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1161
                                   description='API.INVALID_METER_ID')
1162
1163
        cnx = mysql.connector.connect(**config.myems_system_db)
1164
        cursor = cnx.cursor()
1165
1166
        cursor.execute(" SELECT name "
1167
                       " FROM tbl_meters "
1168
                       " WHERE id = %s ", (id_,))
1169
        if cursor.fetchone() is None:
1170
            cursor.close()
1171
            cnx.close()
1172
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1173
                                   description='API.METER_NOT_FOUND')
1174
1175
        query = (" SELECT c.id, c.name, c.uuid "
1176
                 " FROM tbl_meters m, tbl_meters_commands mc, tbl_commands c "
1177
                 " WHERE mc.meter_id = m.id AND c.id = mc.command_id AND m.id = %s "
1178
                 " ORDER BY c.id ")
1179
        cursor.execute(query, (id_,))
1180
        rows = cursor.fetchall()
1181
1182
        result = list()
1183
        if rows is not None and len(rows) > 0:
1184
            for row in rows:
1185
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
1186
                result.append(meta_result)
1187
1188
        resp.text = json.dumps(result)
1189
1190
    @staticmethod
1191
    @user_logger
1192
    def on_post(req, resp, id_):
1193
        """Handles POST requests"""
1194
        admin_control(req)
1195
        try:
1196
            raw_json = req.stream.read().decode('utf-8')
1197
        except Exception as ex:
1198
            raise falcon.HTTPError(status=falcon.HTTP_400,
1199
                                   title='API.BAD_REQUEST',
1200
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1201
1202
        if not id_.isdigit() or int(id_) <= 0:
1203
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1204
                                   description='API.INVALID_METER_ID')
1205
1206
        new_values = json.loads(raw_json)
1207
1208
        if 'command_id' not in new_values['data'].keys() or \
1209
                not isinstance(new_values['data']['command_id'], int) or \
1210
                new_values['data']['command_id'] <= 0:
1211
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1212
                                   description='API.INVALID_COMMAND_ID')
1213
        command_id = new_values['data']['command_id']
1214
1215
        cnx = mysql.connector.connect(**config.myems_system_db)
1216
        cursor = cnx.cursor()
1217
1218
        cursor.execute(" SELECT name "
1219
                       " from tbl_meters "
1220
                       " WHERE id = %s ", (id_,))
1221
        if cursor.fetchone() is None:
1222
            cursor.close()
1223
            cnx.close()
1224
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1225
                                   description='API.METER_NOT_FOUND')
1226
1227
        cursor.execute(" SELECT name "
1228
                       " FROM tbl_commands "
1229
                       " WHERE id = %s ", (command_id,))
1230
        if cursor.fetchone() is None:
1231
            cursor.close()
1232
            cnx.close()
1233
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1234
                                   description='API.COMMAND_NOT_FOUND')
1235
1236
        query = (" SELECT id " 
1237
                 " FROM tbl_meters_commands "
1238
                 " WHERE meter_id = %s AND command_id = %s")
1239
        cursor.execute(query, (id_, command_id,))
1240
        if cursor.fetchone() is not None:
1241
            cursor.close()
1242
            cnx.close()
1243
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1244
                                   description='API.METER_COMMAND_RELATION_EXISTS')
1245
1246
        add_row = (" INSERT INTO tbl_meters_commands (meter_id, command_id) "
1247
                   " VALUES (%s, %s) ")
1248
        cursor.execute(add_row, (id_, command_id,))
1249
        cnx.commit()
1250
        cursor.close()
1251
        cnx.close()
1252
1253
        resp.status = falcon.HTTP_201
1254
        resp.location = '/meters/' + str(id_) + '/commands/' + str(command_id)
1255
1256
1257
class MeterCommandItem:

myems-api/core/virtualpowerplant.py 1 location

@@ 435-547 (lines=113) @@
432
        resp.status = falcon.HTTP_200
433
434
435
class VirtualPowerPlantMicrogridCollection:
436
    def __init__(self):
437
        """Initializes Class"""
438
        pass
439
440
    @staticmethod
441
    def on_options(req, resp, id_):
442
        resp.status = falcon.HTTP_200
443
444
    @staticmethod
445
    def on_get(req, resp, id_):
446
        if 'API-KEY' not in req.headers or \
447
                not isinstance(req.headers['API-KEY'], str) or \
448
                len(str.strip(req.headers['API-KEY'])) == 0:
449
            access_control(req)
450
        else:
451
            api_key_control(req)
452
        if not id_.isdigit() or int(id_) <= 0:
453
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
454
                                   description='API.INVALID_VIRTUAL_POWER_PLANT_ID')
455
456
        cnx = mysql.connector.connect(**config.myems_system_db)
457
        cursor = cnx.cursor()
458
459
        cursor.execute(" SELECT name "
460
                       " FROM tbl_virtual_power_plants "
461
                       " WHERE id = %s ", (id_,))
462
        if cursor.fetchone() is None:
463
            cursor.close()
464
            cnx.close()
465
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
466
                                   description='API.VIRTUAL_POWER_PLANT_NOT_FOUND')
467
468
        query = (" SELECT m.id, m.name, m.uuid "
469
                 " FROM tbl_virtual_power_plants_microgrids vppm, tbl_microgrids m "
470
                 " WHERE m.id = vppm.microgrid_id AND vppm.virtual_power_plant_id = %s "
471
                 " ORDER BY m.id ")
472
        cursor.execute(query, (id_,))
473
        rows = cursor.fetchall()
474
475
        result = list()
476
        if rows is not None and len(rows) > 0:
477
            for row in rows:
478
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2]}
479
                result.append(meta_result)
480
481
        resp.text = json.dumps(result)
482
483
    @staticmethod
484
    @user_logger
485
    def on_post(req, resp, id_):
486
        """Handles POST requests"""
487
        admin_control(req)
488
        try:
489
            raw_json = req.stream.read().decode('utf-8')
490
        except Exception as ex:
491
            raise falcon.HTTPError(status=falcon.HTTP_400,
492
                                   title='API.BAD_REQUEST',
493
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
494
495
        if not id_.isdigit() or int(id_) <= 0:
496
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
497
                                   description='API.INVALID_VIRTUAL_POWER_PLANT_ID')
498
499
        new_values = json.loads(raw_json)
500
501
        if 'microgrid_id' not in new_values['data'].keys() or \
502
                not isinstance(new_values['data']['microgrid_id'], int) or \
503
                new_values['data']['microgrid_id'] <= 0:
504
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
505
                                   description='API.INVALID_MICROGRID_ID')
506
        microgrid_id = new_values['data']['microgrid_id']
507
508
        cnx = mysql.connector.connect(**config.myems_system_db)
509
        cursor = cnx.cursor()
510
511
        cursor.execute(" SELECT name "
512
                       " from tbl_virtual_power_plants "
513
                       " WHERE id = %s ", (id_,))
514
        if cursor.fetchone() is None:
515
            cursor.close()
516
            cnx.close()
517
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
518
                                   description='API.VIRTUAL_POWER_PLANT_NOT_FOUND')
519
520
        cursor.execute(" SELECT name "
521
                       " FROM tbl_microgrids "
522
                       " WHERE id = %s ", (microgrid_id,))
523
        if cursor.fetchone() is None:
524
            cursor.close()
525
            cnx.close()
526
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
527
                                   description='API.MICROGRID_NOT_FOUND')
528
529
        query = (" SELECT id " 
530
                 " FROM tbl_virtual_power_plants_microgrids "
531
                 " WHERE virtual_power_plant_id = %s AND microgrid_id = %s")
532
        cursor.execute(query, (id_, microgrid_id,))
533
        if cursor.fetchone() is not None:
534
            cursor.close()
535
            cnx.close()
536
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
537
                                   description='API.VIRTUAL_POWER_PLANT_MICROGRID_RELATION_EXISTS')
538
539
        add_row = (" INSERT INTO tbl_virtual_power_plants_microgrids (virtual_power_plant_id, microgrid_id) "
540
                   " VALUES (%s, %s) ")
541
        cursor.execute(add_row, (id_, microgrid_id,))
542
        cnx.commit()
543
        cursor.close()
544
        cnx.close()
545
546
        resp.status = falcon.HTTP_201
547
        resp.location = '/virtualpowerplants/' + str(id_) + '/microgrids/' + str(microgrid_id)
548
549
550
class VirtualPowerPlantMicrogridItem: