Code Duplication    Length = 125-128 lines in 16 locations

myems-api/core/tenant.py 4 locations

@@ 1423-1550 (lines=128) @@
1420
        resp.status = falcon.HTTP_204
1421
1422
1423
class TenantVirtualMeterCollection:
1424
    def __init__(self):
1425
        """Initializes Class"""
1426
        pass
1427
1428
    @staticmethod
1429
    def on_options(req, resp, id_):
1430
        resp.status = falcon.HTTP_200
1431
1432
    @staticmethod
1433
    def on_get(req, resp, id_):
1434
        if 'API-KEY' not in req.headers or \
1435
                not isinstance(req.headers['API-KEY'], str) or \
1436
                len(str.strip(req.headers['API-KEY'])) == 0:
1437
            access_control(req)
1438
        else:
1439
            api_key_control(req)
1440
        if not id_.isdigit() or int(id_) <= 0:
1441
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1442
                                   description='API.INVALID_TENANT_ID')
1443
1444
        cnx = mysql.connector.connect(**config.myems_system_db)
1445
        cursor = cnx.cursor()
1446
1447
        cursor.execute(" SELECT name "
1448
                       " FROM tbl_tenants "
1449
                       " WHERE id = %s ", (id_,))
1450
        if cursor.fetchone() is None:
1451
            cursor.close()
1452
            cnx.close()
1453
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1454
                                   description='API.TENANT_NOT_FOUND')
1455
1456
        query = (" SELECT id, name, uuid "
1457
                 " FROM tbl_energy_categories ")
1458
        cursor.execute(query)
1459
        rows_energy_categories = cursor.fetchall()
1460
1461
        energy_category_dict = dict()
1462
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1463
            for row in rows_energy_categories:
1464
                energy_category_dict[row[0]] = {"id": row[0],
1465
                                                "name": row[1],
1466
                                                "uuid": row[2]}
1467
1468
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1469
                 " FROM tbl_tenants t, tbl_tenants_virtual_meters tm, tbl_virtual_meters m "
1470
                 " WHERE tm.tenant_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s "
1471
                 " ORDER BY m.id ")
1472
        cursor.execute(query, (id_,))
1473
        rows = cursor.fetchall()
1474
1475
        result = list()
1476
        if rows is not None and len(rows) > 0:
1477
            for row in rows:
1478
                meta_result = {"id": row[0],
1479
                               "name": row[1],
1480
                               "uuid": row[2],
1481
                               "energy_category": energy_category_dict.get(row[3], None)}
1482
                result.append(meta_result)
1483
1484
        resp.text = json.dumps(result)
1485
1486
    @staticmethod
1487
    @user_logger
1488
    def on_post(req, resp, id_):
1489
        """Handles POST requests"""
1490
        admin_control(req)
1491
        try:
1492
            raw_json = req.stream.read().decode('utf-8')
1493
        except Exception as ex:
1494
            raise falcon.HTTPError(status=falcon.HTTP_400,
1495
                                   title='API.BAD_REQUEST',
1496
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1497
1498
        if not id_.isdigit() or int(id_) <= 0:
1499
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1500
                                   description='API.INVALID_TENANT_ID')
1501
1502
        new_values = json.loads(raw_json)
1503
1504
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1505
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1506
                new_values['data']['virtual_meter_id'] <= 0:
1507
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1508
                                   description='API.INVALID_VIRTUAL_METER_ID')
1509
        virtual_meter_id = new_values['data']['virtual_meter_id']
1510
1511
        cnx = mysql.connector.connect(**config.myems_system_db)
1512
        cursor = cnx.cursor()
1513
1514
        cursor.execute(" SELECT name "
1515
                       " from tbl_tenants "
1516
                       " WHERE id = %s ", (id_,))
1517
        if cursor.fetchone() is None:
1518
            cursor.close()
1519
            cnx.close()
1520
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1521
                                   description='API.TENANT_NOT_FOUND')
1522
1523
        cursor.execute(" SELECT name "
1524
                       " FROM tbl_virtual_meters "
1525
                       " WHERE id = %s ", (virtual_meter_id,))
1526
        if cursor.fetchone() is None:
1527
            cursor.close()
1528
            cnx.close()
1529
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1530
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1531
1532
        query = (" SELECT id " 
1533
                 " FROM tbl_tenants_virtual_meters "
1534
                 " WHERE tenant_id = %s AND virtual_meter_id = %s")
1535
        cursor.execute(query, (id_, virtual_meter_id,))
1536
        if cursor.fetchone() is not None:
1537
            cursor.close()
1538
            cnx.close()
1539
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1540
                                   description='API.TENANT_VIRTUAL_METER_RELATION_EXISTS')
1541
1542
        add_row = (" INSERT INTO tbl_tenants_virtual_meters (tenant_id, virtual_meter_id) "
1543
                   " VALUES (%s, %s) ")
1544
        cursor.execute(add_row, (id_, virtual_meter_id,))
1545
        cnx.commit()
1546
        cursor.close()
1547
        cnx.close()
1548
1549
        resp.status = falcon.HTTP_201
1550
        resp.location = '/tenants/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1551
1552
1553
class TenantVirtualMeterItem:
@@ 865-992 (lines=128) @@
862
        resp.status = falcon.HTTP_204
863
864
865
class TenantOfflineMeterCollection:
866
    def __init__(self):
867
        """Initializes Class"""
868
        pass
869
870
    @staticmethod
871
    def on_options(req, resp, id_):
872
        resp.status = falcon.HTTP_200
873
874
    @staticmethod
875
    def on_get(req, resp, id_):
876
        if 'API-KEY' not in req.headers or \
877
                not isinstance(req.headers['API-KEY'], str) or \
878
                len(str.strip(req.headers['API-KEY'])) == 0:
879
            access_control(req)
880
        else:
881
            api_key_control(req)
882
        if not id_.isdigit() or int(id_) <= 0:
883
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
884
                                   description='API.INVALID_TENANT_ID')
885
886
        cnx = mysql.connector.connect(**config.myems_system_db)
887
        cursor = cnx.cursor()
888
889
        cursor.execute(" SELECT name "
890
                       " FROM tbl_tenants "
891
                       " WHERE id = %s ", (id_,))
892
        if cursor.fetchone() is None:
893
            cursor.close()
894
            cnx.close()
895
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
896
                                   description='API.TENANT_NOT_FOUND')
897
898
        query = (" SELECT id, name, uuid "
899
                 " FROM tbl_energy_categories ")
900
        cursor.execute(query)
901
        rows_energy_categories = cursor.fetchall()
902
903
        energy_category_dict = dict()
904
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
905
            for row in rows_energy_categories:
906
                energy_category_dict[row[0]] = {"id": row[0],
907
                                                "name": row[1],
908
                                                "uuid": row[2]}
909
910
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
911
                 " FROM tbl_tenants s, tbl_tenants_offline_meters sm, tbl_offline_meters m "
912
                 " WHERE sm.tenant_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
913
                 " ORDER BY m.id ")
914
        cursor.execute(query, (id_,))
915
        rows = cursor.fetchall()
916
917
        result = list()
918
        if rows is not None and len(rows) > 0:
919
            for row in rows:
920
                meta_result = {"id": row[0],
921
                               "name": row[1],
922
                               "uuid": row[2],
923
                               "energy_category": energy_category_dict.get(row[3], None)}
924
                result.append(meta_result)
925
926
        resp.text = json.dumps(result)
927
928
    @staticmethod
929
    @user_logger
930
    def on_post(req, resp, id_):
931
        """Handles POST requests"""
932
        admin_control(req)
933
        try:
934
            raw_json = req.stream.read().decode('utf-8')
935
        except Exception as ex:
936
            raise falcon.HTTPError(status=falcon.HTTP_400,
937
                                   title='API.BAD_REQUEST',
938
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
939
940
        if not id_.isdigit() or int(id_) <= 0:
941
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
942
                                   description='API.INVALID_TENANT_ID')
943
944
        new_values = json.loads(raw_json)
945
946
        if 'offline_meter_id' not in new_values['data'].keys() or \
947
                not isinstance(new_values['data']['offline_meter_id'], int) or \
948
                new_values['data']['offline_meter_id'] <= 0:
949
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
950
                                   description='API.INVALID_OFFLINE_METER_ID')
951
        offline_meter_id = new_values['data']['offline_meter_id']
952
953
        cnx = mysql.connector.connect(**config.myems_system_db)
954
        cursor = cnx.cursor()
955
956
        cursor.execute(" SELECT name "
957
                       " from tbl_tenants "
958
                       " WHERE id = %s ", (id_,))
959
        if cursor.fetchone() is None:
960
            cursor.close()
961
            cnx.close()
962
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
963
                                   description='API.TENANT_NOT_FOUND')
964
965
        cursor.execute(" SELECT name "
966
                       " FROM tbl_offline_meters "
967
                       " WHERE id = %s ", (offline_meter_id,))
968
        if cursor.fetchone() is None:
969
            cursor.close()
970
            cnx.close()
971
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
972
                                   description='API.OFFLINE_METER_NOT_FOUND')
973
974
        query = (" SELECT id " 
975
                 " FROM tbl_tenants_offline_meters "
976
                 " WHERE tenant_id = %s AND offline_meter_id = %s")
977
        cursor.execute(query, (id_, offline_meter_id,))
978
        if cursor.fetchone() is not None:
979
            cursor.close()
980
            cnx.close()
981
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
982
                                   description='API.TENANT_OFFLINE_METER_RELATION_EXISTS')
983
984
        add_row = (" INSERT INTO tbl_tenants_offline_meters (tenant_id, offline_meter_id) "
985
                   " VALUES (%s, %s) ")
986
        cursor.execute(add_row, (id_, offline_meter_id,))
987
        cnx.commit()
988
        cursor.close()
989
        cnx.close()
990
991
        resp.status = falcon.HTTP_201
992
        resp.location = '/tenants/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
993
994
995
class TenantOfflineMeterItem:
@@ 675-802 (lines=128) @@
672
        resp.status = falcon.HTTP_200
673
674
675
class TenantMeterCollection:
676
    def __init__(self):
677
        """Initializes Class"""
678
        pass
679
680
    @staticmethod
681
    def on_options(req, resp, id_):
682
        resp.status = falcon.HTTP_200
683
684
    @staticmethod
685
    def on_get(req, resp, id_):
686
        if 'API-KEY' not in req.headers or \
687
                not isinstance(req.headers['API-KEY'], str) or \
688
                len(str.strip(req.headers['API-KEY'])) == 0:
689
            access_control(req)
690
        else:
691
            api_key_control(req)
692
        if not id_.isdigit() or int(id_) <= 0:
693
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
694
                                   description='API.INVALID_TENANT_ID')
695
696
        cnx = mysql.connector.connect(**config.myems_system_db)
697
        cursor = cnx.cursor()
698
699
        cursor.execute(" SELECT name "
700
                       " FROM tbl_tenants "
701
                       " WHERE id = %s ", (id_,))
702
        if cursor.fetchone() is None:
703
            cursor.close()
704
            cnx.close()
705
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
706
                                   description='API.TENANT_NOT_FOUND')
707
708
        query = (" SELECT id, name, uuid "
709
                 " FROM tbl_energy_categories ")
710
        cursor.execute(query)
711
        rows_energy_categories = cursor.fetchall()
712
713
        energy_category_dict = dict()
714
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
715
            for row in rows_energy_categories:
716
                energy_category_dict[row[0]] = {"id": row[0],
717
                                                "name": row[1],
718
                                                "uuid": row[2]}
719
720
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
721
                 " FROM tbl_tenants t, tbl_tenants_meters tm, tbl_meters m "
722
                 " WHERE tm.tenant_id = t.id AND m.id = tm.meter_id AND t.id = %s "
723
                 " ORDER BY m.id ")
724
        cursor.execute(query, (id_,))
725
        rows = cursor.fetchall()
726
727
        result = list()
728
        if rows is not None and len(rows) > 0:
729
            for row in rows:
730
                meta_result = {"id": row[0],
731
                               "name": row[1],
732
                               "uuid": row[2],
733
                               "energy_category": energy_category_dict.get(row[3], None)}
734
                result.append(meta_result)
735
736
        resp.text = json.dumps(result)
737
738
    @staticmethod
739
    @user_logger
740
    def on_post(req, resp, id_):
741
        """Handles POST requests"""
742
        admin_control(req)
743
        try:
744
            raw_json = req.stream.read().decode('utf-8')
745
        except Exception as ex:
746
            raise falcon.HTTPError(status=falcon.HTTP_400,
747
                                   title='API.BAD_REQUEST',
748
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
749
750
        if not id_.isdigit() or int(id_) <= 0:
751
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
752
                                   description='API.INVALID_TENANT_ID')
753
754
        new_values = json.loads(raw_json)
755
756
        if 'meter_id' not in new_values['data'].keys() or \
757
                not isinstance(new_values['data']['meter_id'], int) or \
758
                new_values['data']['meter_id'] <= 0:
759
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
760
                                   description='API.INVALID_METER_ID')
761
        meter_id = new_values['data']['meter_id']
762
763
        cnx = mysql.connector.connect(**config.myems_system_db)
764
        cursor = cnx.cursor()
765
766
        cursor.execute(" SELECT name "
767
                       " from tbl_tenants "
768
                       " WHERE id = %s ", (id_,))
769
        if cursor.fetchone() is None:
770
            cursor.close()
771
            cnx.close()
772
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
773
                                   description='API.TENANT_NOT_FOUND')
774
775
        cursor.execute(" SELECT name "
776
                       " FROM tbl_meters "
777
                       " WHERE id = %s ", (meter_id,))
778
        if cursor.fetchone() is None:
779
            cursor.close()
780
            cnx.close()
781
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
782
                                   description='API.METER_NOT_FOUND')
783
784
        query = (" SELECT id " 
785
                 " FROM tbl_tenants_meters "
786
                 " WHERE tenant_id = %s AND meter_id = %s")
787
        cursor.execute(query, (id_, meter_id,))
788
        if cursor.fetchone() is not None:
789
            cursor.close()
790
            cnx.close()
791
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
792
                                   description='API.TENANT_METER_RELATION_EXISTS')
793
794
        add_row = (" INSERT INTO tbl_tenants_meters (tenant_id, meter_id) "
795
                   " VALUES (%s, %s) ")
796
        cursor.execute(add_row, (id_, meter_id,))
797
        cnx.commit()
798
        cursor.close()
799
        cnx.close()
800
801
        resp.status = falcon.HTTP_201
802
        resp.location = '/tenants/' + str(id_) + '/meters/' + str(meter_id)
803
804
805
class TenantMeterItem:
@@ 1056-1182 (lines=127) @@
1053
        resp.status = falcon.HTTP_204
1054
1055
1056
class TenantPointCollection:
1057
    def __init__(self):
1058
        """Initializes Class"""
1059
        pass
1060
1061
    @staticmethod
1062
    def on_options(req, resp, id_):
1063
        resp.status = falcon.HTTP_200
1064
1065
    @staticmethod
1066
    def on_get(req, resp, id_):
1067
        if 'API-KEY' not in req.headers or \
1068
                not isinstance(req.headers['API-KEY'], str) or \
1069
                len(str.strip(req.headers['API-KEY'])) == 0:
1070
            access_control(req)
1071
        else:
1072
            api_key_control(req)
1073
        if not id_.isdigit() or int(id_) <= 0:
1074
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1075
                                   description='API.INVALID_TENANT_ID')
1076
1077
        cnx = mysql.connector.connect(**config.myems_system_db)
1078
        cursor = cnx.cursor()
1079
1080
        cursor.execute(" SELECT name "
1081
                       " FROM tbl_tenants "
1082
                       " WHERE id = %s ", (id_,))
1083
        if cursor.fetchone() is None:
1084
            cursor.close()
1085
            cnx.close()
1086
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1087
                                   description='API.TENANT_NOT_FOUND')
1088
1089
        query = (" SELECT id, name, uuid "
1090
                 " FROM tbl_data_sources ")
1091
        cursor.execute(query)
1092
        rows_data_sources = cursor.fetchall()
1093
1094
        data_source_dict = dict()
1095
        if rows_data_sources is not None and len(rows_data_sources) > 0:
1096
            for row in rows_data_sources:
1097
                data_source_dict[row[0]] = {"id": row[0],
1098
                                            "name": row[1],
1099
                                            "uuid": row[2]}
1100
1101
        query = (" SELECT p.id, p.name, p.data_source_id "
1102
                 " FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p "
1103
                 " WHERE tp.tenant_id = t.id AND p.id = tp.point_id AND t.id = %s "
1104
                 " ORDER BY p.id ")
1105
        cursor.execute(query, (id_,))
1106
        rows = cursor.fetchall()
1107
1108
        result = list()
1109
        if rows is not None and len(rows) > 0:
1110
            for row in rows:
1111
                meta_result = {"id": row[0],
1112
                               "name": row[1],
1113
                               "data_source": data_source_dict.get(row[2], None)}
1114
                result.append(meta_result)
1115
1116
        resp.text = json.dumps(result)
1117
1118
    @staticmethod
1119
    @user_logger
1120
    def on_post(req, resp, id_):
1121
        """Handles POST requests"""
1122
        admin_control(req)
1123
        try:
1124
            raw_json = req.stream.read().decode('utf-8')
1125
        except Exception as ex:
1126
            raise falcon.HTTPError(status=falcon.HTTP_400,
1127
                                   title='API.BAD_REQUEST',
1128
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1129
1130
        if not id_.isdigit() or int(id_) <= 0:
1131
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1132
                                   description='API.INVALID_TENANT_ID')
1133
1134
        new_values = json.loads(raw_json)
1135
1136
        if 'point_id' not in new_values['data'].keys() or \
1137
                not isinstance(new_values['data']['point_id'], int) or \
1138
                new_values['data']['point_id'] <= 0:
1139
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1140
                                   description='API.INVALID_POINT_ID')
1141
        point_id = new_values['data']['point_id']
1142
1143
        cnx = mysql.connector.connect(**config.myems_system_db)
1144
        cursor = cnx.cursor()
1145
1146
        cursor.execute(" SELECT name "
1147
                       " from tbl_tenants "
1148
                       " WHERE id = %s ", (id_,))
1149
        if cursor.fetchone() is None:
1150
            cursor.close()
1151
            cnx.close()
1152
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1153
                                   description='API.TENANT_NOT_FOUND')
1154
1155
        cursor.execute(" SELECT name "
1156
                       " FROM tbl_points "
1157
                       " WHERE id = %s ", (point_id,))
1158
        if cursor.fetchone() is None:
1159
            cursor.close()
1160
            cnx.close()
1161
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1162
                                   description='API.POINT_NOT_FOUND')
1163
1164
        query = (" SELECT id " 
1165
                 " FROM tbl_tenants_points "
1166
                 " WHERE tenant_id = %s AND point_id = %s")
1167
        cursor.execute(query, (id_, point_id,))
1168
        if cursor.fetchone() is not None:
1169
            cursor.close()
1170
            cnx.close()
1171
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1172
                                   description='API.TENANT_POINT_RELATION_EXISTS')
1173
1174
        add_row = (" INSERT INTO tbl_tenants_points (tenant_id, point_id) "
1175
                   " VALUES (%s, %s) ")
1176
        cursor.execute(add_row, (id_, point_id,))
1177
        cnx.commit()
1178
        cursor.close()
1179
        cnx.close()
1180
1181
        resp.status = falcon.HTTP_201
1182
        resp.location = '/tenants/' + str(id_) + '/points/' + str(point_id)
1183
1184
1185
class TenantPointItem:

myems-api/core/shopfloor.py 4 locations

@@ 1374-1499 (lines=126) @@
1371
        resp.status = falcon.HTTP_204
1372
1373
1374
class ShopfloorVirtualMeterCollection:
1375
    def __init__(self):
1376
        """Initializes ShopfloorVirtualMeterCollection"""
1377
        pass
1378
1379
    @staticmethod
1380
    def on_options(req, resp, id_):
1381
        resp.status = falcon.HTTP_200
1382
1383
    @staticmethod
1384
    def on_get(req, resp, id_):
1385
        if 'API-KEY' not in req.headers or \
1386
                not isinstance(req.headers['API-KEY'], str) or \
1387
                len(str.strip(req.headers['API-KEY'])) == 0:
1388
            access_control(req)
1389
        else:
1390
            api_key_control(req)
1391
        if not id_.isdigit() or int(id_) <= 0:
1392
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1393
                                   description='API.INVALID_SHOPFLOOR_ID')
1394
1395
        cnx = mysql.connector.connect(**config.myems_system_db)
1396
        cursor = cnx.cursor()
1397
1398
        cursor.execute(" SELECT name "
1399
                       " FROM tbl_shopfloors "
1400
                       " WHERE id = %s ", (id_,))
1401
        if cursor.fetchone() is None:
1402
            cursor.close()
1403
            cnx.close()
1404
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1405
                                   description='API.SHOPFLOOR_NOT_FOUND')
1406
1407
        query = (" SELECT id, name, uuid "
1408
                 " FROM tbl_energy_categories ")
1409
        cursor.execute(query)
1410
        rows_energy_categories = cursor.fetchall()
1411
1412
        energy_category_dict = dict()
1413
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1414
            for row in rows_energy_categories:
1415
                energy_category_dict[row[0]] = {"id": row[0],
1416
                                                "name": row[1],
1417
                                                "uuid": row[2]}
1418
1419
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1420
                 " FROM tbl_shopfloors s, tbl_shopfloors_virtual_meters sm, tbl_virtual_meters m "
1421
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
1422
                 " ORDER BY m.id ")
1423
        cursor.execute(query, (id_,))
1424
        rows = cursor.fetchall()
1425
1426
        result = list()
1427
        if rows is not None and len(rows) > 0:
1428
            for row in rows:
1429
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1430
                               "energy_category": energy_category_dict.get(row[3], None)}
1431
                result.append(meta_result)
1432
1433
        resp.text = json.dumps(result)
1434
1435
    @staticmethod
1436
    @user_logger
1437
    def on_post(req, resp, id_):
1438
        """Handles POST requests"""
1439
        admin_control(req)
1440
        try:
1441
            raw_json = req.stream.read().decode('utf-8')
1442
        except Exception as ex:
1443
            raise falcon.HTTPError(status=falcon.HTTP_400,
1444
                                   title='API.BAD_REQUEST',
1445
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1446
1447
        if not id_.isdigit() or int(id_) <= 0:
1448
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1449
                                   description='API.INVALID_SHOPFLOOR_ID')
1450
1451
        new_values = json.loads(raw_json)
1452
1453
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1454
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1455
                new_values['data']['virtual_meter_id'] <= 0:
1456
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1457
                                   description='API.INVALID_VIRTUAL_METER_ID')
1458
        virtual_meter_id = new_values['data']['virtual_meter_id']
1459
1460
        cnx = mysql.connector.connect(**config.myems_system_db)
1461
        cursor = cnx.cursor()
1462
1463
        cursor.execute(" SELECT name "
1464
                       " from tbl_shopfloors "
1465
                       " WHERE id = %s ", (id_,))
1466
        if cursor.fetchone() is None:
1467
            cursor.close()
1468
            cnx.close()
1469
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1470
                                   description='API.SHOPFLOOR_NOT_FOUND')
1471
1472
        cursor.execute(" SELECT name "
1473
                       " FROM tbl_virtual_meters "
1474
                       " WHERE id = %s ", (virtual_meter_id,))
1475
        if cursor.fetchone() is None:
1476
            cursor.close()
1477
            cnx.close()
1478
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1479
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1480
1481
        query = (" SELECT id " 
1482
                 " FROM tbl_shopfloors_virtual_meters "
1483
                 " WHERE shopfloor_id = %s AND virtual_meter_id = %s")
1484
        cursor.execute(query, (id_, virtual_meter_id,))
1485
        if cursor.fetchone() is not None:
1486
            cursor.close()
1487
            cnx.close()
1488
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1489
                                   description='API.SHOPFLOOR_VIRTUAL_METER_RELATION_EXISTS')
1490
1491
        add_row = (" INSERT INTO tbl_shopfloors_virtual_meters (shopfloor_id, virtual_meter_id) "
1492
                   " VALUES (%s, %s) ")
1493
        cursor.execute(add_row, (id_, virtual_meter_id,))
1494
        cnx.commit()
1495
        cursor.close()
1496
        cnx.close()
1497
1498
        resp.status = falcon.HTTP_201
1499
        resp.location = '/shopfloors/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1500
1501
1502
class ShopfloorVirtualMeterItem:
@@ 822-947 (lines=126) @@
819
        resp.status = falcon.HTTP_204
820
821
822
class ShopfloorOfflineMeterCollection:
823
    def __init__(self):
824
        """Initializes ShopfloorOfflineMeterCollection"""
825
        pass
826
827
    @staticmethod
828
    def on_options(req, resp, id_):
829
        resp.status = falcon.HTTP_200
830
831
    @staticmethod
832
    def on_get(req, resp, id_):
833
        if 'API-KEY' not in req.headers or \
834
                not isinstance(req.headers['API-KEY'], str) or \
835
                len(str.strip(req.headers['API-KEY'])) == 0:
836
            access_control(req)
837
        else:
838
            api_key_control(req)
839
        if not id_.isdigit() or int(id_) <= 0:
840
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
841
                                   description='API.INVALID_SHOPFLOOR_ID')
842
843
        cnx = mysql.connector.connect(**config.myems_system_db)
844
        cursor = cnx.cursor()
845
846
        cursor.execute(" SELECT name "
847
                       " FROM tbl_shopfloors "
848
                       " WHERE id = %s ", (id_,))
849
        if cursor.fetchone() is None:
850
            cursor.close()
851
            cnx.close()
852
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
853
                                   description='API.SHOPFLOOR_NOT_FOUND')
854
855
        query = (" SELECT id, name, uuid "
856
                 " FROM tbl_energy_categories ")
857
        cursor.execute(query)
858
        rows_energy_categories = cursor.fetchall()
859
860
        energy_category_dict = dict()
861
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
862
            for row in rows_energy_categories:
863
                energy_category_dict[row[0]] = {"id": row[0],
864
                                                "name": row[1],
865
                                                "uuid": row[2]}
866
867
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
868
                 " FROM tbl_shopfloors s, tbl_shopfloors_offline_meters sm, tbl_offline_meters m "
869
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
870
                 " ORDER BY m.id ")
871
        cursor.execute(query, (id_,))
872
        rows = cursor.fetchall()
873
874
        result = list()
875
        if rows is not None and len(rows) > 0:
876
            for row in rows:
877
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
878
                               "energy_category": energy_category_dict.get(row[3], None)}
879
                result.append(meta_result)
880
881
        resp.text = json.dumps(result)
882
883
    @staticmethod
884
    @user_logger
885
    def on_post(req, resp, id_):
886
        """Handles POST requests"""
887
        admin_control(req)
888
        try:
889
            raw_json = req.stream.read().decode('utf-8')
890
        except Exception as ex:
891
            raise falcon.HTTPError(status=falcon.HTTP_400,
892
                                   title='API.BAD_REQUEST',
893
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
894
895
        if not id_.isdigit() or int(id_) <= 0:
896
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
897
                                   description='API.INVALID_SHOPFLOOR_ID')
898
899
        new_values = json.loads(raw_json)
900
901
        if 'offline_meter_id' not in new_values['data'].keys() or \
902
                not isinstance(new_values['data']['offline_meter_id'], int) or \
903
                new_values['data']['offline_meter_id'] <= 0:
904
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
905
                                   description='API.INVALID_OFFLINE_METER_ID')
906
        offline_meter_id = new_values['data']['offline_meter_id']
907
908
        cnx = mysql.connector.connect(**config.myems_system_db)
909
        cursor = cnx.cursor()
910
911
        cursor.execute(" SELECT name "
912
                       " from tbl_shopfloors "
913
                       " WHERE id = %s ", (id_,))
914
        if cursor.fetchone() is None:
915
            cursor.close()
916
            cnx.close()
917
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
918
                                   description='API.SHOPFLOOR_NOT_FOUND')
919
920
        cursor.execute(" SELECT name "
921
                       " FROM tbl_offline_meters "
922
                       " WHERE id = %s ", (offline_meter_id,))
923
        if cursor.fetchone() is None:
924
            cursor.close()
925
            cnx.close()
926
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
927
                                   description='API.OFFLINE_METER_NOT_FOUND')
928
929
        query = (" SELECT id " 
930
                 " FROM tbl_shopfloors_offline_meters "
931
                 " WHERE shopfloor_id = %s AND offline_meter_id = %s")
932
        cursor.execute(query, (id_, offline_meter_id,))
933
        if cursor.fetchone() is not None:
934
            cursor.close()
935
            cnx.close()
936
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
937
                                   description='API.SHOPFLOOR_OFFLINE_METER_RELATION_EXISTS')
938
939
        add_row = (" INSERT INTO tbl_shopfloors_offline_meters (shopfloor_id, offline_meter_id) "
940
                   " VALUES (%s, %s) ")
941
        cursor.execute(add_row, (id_, offline_meter_id,))
942
        cnx.commit()
943
        cursor.close()
944
        cnx.close()
945
946
        resp.status = falcon.HTTP_201
947
        resp.location = '/shopfloors/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
948
949
950
class ShopfloorOfflineMeterItem:
@@ 634-759 (lines=126) @@
631
        resp.status = falcon.HTTP_204
632
633
634
class ShopfloorMeterCollection:
635
    def __init__(self):
636
        """Initializes ShopfloorMeterCollection"""
637
        pass
638
639
    @staticmethod
640
    def on_options(req, resp, id_):
641
        resp.status = falcon.HTTP_200
642
643
    @staticmethod
644
    def on_get(req, resp, id_):
645
        if 'API-KEY' not in req.headers or \
646
                not isinstance(req.headers['API-KEY'], str) or \
647
                len(str.strip(req.headers['API-KEY'])) == 0:
648
            access_control(req)
649
        else:
650
            api_key_control(req)
651
        if not id_.isdigit() or int(id_) <= 0:
652
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
653
                                   description='API.INVALID_SHOPFLOOR_ID')
654
655
        cnx = mysql.connector.connect(**config.myems_system_db)
656
        cursor = cnx.cursor()
657
658
        cursor.execute(" SELECT name "
659
                       " FROM tbl_shopfloors "
660
                       " WHERE id = %s ", (id_,))
661
        if cursor.fetchone() is None:
662
            cursor.close()
663
            cnx.close()
664
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
665
                                   description='API.SHOPFLOOR_NOT_FOUND')
666
667
        query = (" SELECT id, name, uuid "
668
                 " FROM tbl_energy_categories ")
669
        cursor.execute(query)
670
        rows_energy_categories = cursor.fetchall()
671
672
        energy_category_dict = dict()
673
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
674
            for row in rows_energy_categories:
675
                energy_category_dict[row[0]] = {"id": row[0],
676
                                                "name": row[1],
677
                                                "uuid": row[2]}
678
679
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
680
                 " FROM tbl_shopfloors s, tbl_shopfloors_meters sm, tbl_meters m "
681
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.meter_id AND s.id = %s "
682
                 " ORDER BY m.id ")
683
        cursor.execute(query, (id_,))
684
        rows = cursor.fetchall()
685
686
        result = list()
687
        if rows is not None and len(rows) > 0:
688
            for row in rows:
689
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
690
                               "energy_category": energy_category_dict.get(row[3], None)}
691
                result.append(meta_result)
692
693
        resp.text = json.dumps(result)
694
695
    @staticmethod
696
    @user_logger
697
    def on_post(req, resp, id_):
698
        """Handles POST requests"""
699
        admin_control(req)
700
        try:
701
            raw_json = req.stream.read().decode('utf-8')
702
        except Exception as ex:
703
            raise falcon.HTTPError(status=falcon.HTTP_400,
704
                                   title='API.BAD_REQUEST',
705
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
706
707
        if not id_.isdigit() or int(id_) <= 0:
708
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
709
                                   description='API.INVALID_SHOPFLOOR_ID')
710
711
        new_values = json.loads(raw_json)
712
713
        if 'meter_id' not in new_values['data'].keys() or \
714
                not isinstance(new_values['data']['meter_id'], int) or \
715
                new_values['data']['meter_id'] <= 0:
716
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
717
                                   description='API.INVALID_METER_ID')
718
        meter_id = new_values['data']['meter_id']
719
720
        cnx = mysql.connector.connect(**config.myems_system_db)
721
        cursor = cnx.cursor()
722
723
        cursor.execute(" SELECT name "
724
                       " from tbl_shopfloors "
725
                       " WHERE id = %s ", (id_,))
726
        if cursor.fetchone() is None:
727
            cursor.close()
728
            cnx.close()
729
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
730
                                   description='API.SHOPFLOOR_NOT_FOUND')
731
732
        cursor.execute(" SELECT name "
733
                       " FROM tbl_meters "
734
                       " WHERE id = %s ", (meter_id,))
735
        if cursor.fetchone() is None:
736
            cursor.close()
737
            cnx.close()
738
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
739
                                   description='API.METER_NOT_FOUND')
740
741
        query = (" SELECT id " 
742
                 " FROM tbl_shopfloors_meters "
743
                 " WHERE shopfloor_id = %s AND meter_id = %s")
744
        cursor.execute(query, (id_, meter_id,))
745
        if cursor.fetchone() is not None:
746
            cursor.close()
747
            cnx.close()
748
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
749
                                   description='API.SHOPFLOOR_METER_RELATION_EXISTS')
750
751
        add_row = (" INSERT INTO tbl_shopfloors_meters (shopfloor_id, meter_id) "
752
                   " VALUES (%s, %s) ")
753
        cursor.execute(add_row, (id_, meter_id,))
754
        cnx.commit()
755
        cursor.close()
756
        cnx.close()
757
758
        resp.status = falcon.HTTP_201
759
        resp.location = '/shopfloors/' + str(id_) + '/meters/' + str(meter_id)
760
761
762
class ShopfloorMeterItem:
@@ 1011-1135 (lines=125) @@
1008
        resp.status = falcon.HTTP_204
1009
1010
1011
class ShopfloorPointCollection:
1012
    def __init__(self):
1013
        """Initializes ShopfloorPointCollection"""
1014
        pass
1015
1016
    @staticmethod
1017
    def on_options(req, resp, id_):
1018
        resp.status = falcon.HTTP_200
1019
1020
    @staticmethod
1021
    def on_get(req, resp, id_):
1022
        if 'API-KEY' not in req.headers or \
1023
                not isinstance(req.headers['API-KEY'], str) or \
1024
                len(str.strip(req.headers['API-KEY'])) == 0:
1025
            access_control(req)
1026
        else:
1027
            api_key_control(req)
1028
        if not id_.isdigit() or int(id_) <= 0:
1029
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1030
                                   description='API.INVALID_SHOPFLOOR_ID')
1031
1032
        cnx = mysql.connector.connect(**config.myems_system_db)
1033
        cursor = cnx.cursor()
1034
1035
        cursor.execute(" SELECT name "
1036
                       " FROM tbl_shopfloors "
1037
                       " WHERE id = %s ", (id_,))
1038
        if cursor.fetchone() is None:
1039
            cursor.close()
1040
            cnx.close()
1041
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1042
                                   description='API.SHOPFLOOR_NOT_FOUND')
1043
1044
        query = (" SELECT id, name, uuid "
1045
                 " FROM tbl_data_sources ")
1046
        cursor.execute(query)
1047
        rows_data_sources = cursor.fetchall()
1048
1049
        data_source_dict = dict()
1050
        if rows_data_sources is not None and len(rows_data_sources) > 0:
1051
            for row in rows_data_sources:
1052
                data_source_dict[row[0]] = {"id": row[0],
1053
                                            "name": row[1],
1054
                                            "uuid": row[2]}
1055
1056
        query = (" SELECT p.id, p.name, p.data_source_id "
1057
                 " FROM tbl_shopfloors s, tbl_shopfloors_points sp, tbl_points p "
1058
                 " WHERE sp.shopfloor_id = s.id AND p.id = sp.point_id AND s.id = %s "
1059
                 " ORDER BY p.id ")
1060
        cursor.execute(query, (id_,))
1061
        rows = cursor.fetchall()
1062
1063
        result = list()
1064
        if rows is not None and len(rows) > 0:
1065
            for row in rows:
1066
                meta_result = {"id": row[0], "name": row[1], "data_source": data_source_dict.get(row[2], None)}
1067
                result.append(meta_result)
1068
1069
        resp.text = json.dumps(result)
1070
1071
    @staticmethod
1072
    @user_logger
1073
    def on_post(req, resp, id_):
1074
        """Handles POST requests"""
1075
        admin_control(req)
1076
        try:
1077
            raw_json = req.stream.read().decode('utf-8')
1078
        except Exception as ex:
1079
            raise falcon.HTTPError(status=falcon.HTTP_400,
1080
                                   title='API.BAD_REQUEST',
1081
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1082
1083
        if not id_.isdigit() or int(id_) <= 0:
1084
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1085
                                   description='API.INVALID_SHOPFLOOR_ID')
1086
1087
        new_values = json.loads(raw_json)
1088
1089
        if 'point_id' not in new_values['data'].keys() or \
1090
                not isinstance(new_values['data']['point_id'], int) or \
1091
                new_values['data']['point_id'] <= 0:
1092
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1093
                                   description='API.INVALID_POINT_ID')
1094
        point_id = new_values['data']['point_id']
1095
1096
        cnx = mysql.connector.connect(**config.myems_system_db)
1097
        cursor = cnx.cursor()
1098
1099
        cursor.execute(" SELECT name "
1100
                       " from tbl_shopfloors "
1101
                       " WHERE id = %s ", (id_,))
1102
        if cursor.fetchone() is None:
1103
            cursor.close()
1104
            cnx.close()
1105
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1106
                                   description='API.SHOPFLOOR_NOT_FOUND')
1107
1108
        cursor.execute(" SELECT name "
1109
                       " FROM tbl_points "
1110
                       " WHERE id = %s ", (point_id,))
1111
        if cursor.fetchone() is None:
1112
            cursor.close()
1113
            cnx.close()
1114
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1115
                                   description='API.POINT_NOT_FOUND')
1116
1117
        query = (" SELECT id " 
1118
                 " FROM tbl_shopfloors_points "
1119
                 " WHERE shopfloor_id = %s AND point_id = %s")
1120
        cursor.execute(query, (id_, point_id,))
1121
        if cursor.fetchone() is not None:
1122
            cursor.close()
1123
            cnx.close()
1124
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1125
                                   description='API.SHOPFLOOR_POINT_RELATION_EXISTS')
1126
1127
        add_row = (" INSERT INTO tbl_shopfloors_points (shopfloor_id, point_id) "
1128
                   " VALUES (%s, %s) ")
1129
        cursor.execute(add_row, (id_, point_id,))
1130
        cnx.commit()
1131
        cursor.close()
1132
        cnx.close()
1133
1134
        resp.status = falcon.HTTP_201
1135
        resp.location = '/shopfloors/' + str(id_) + '/points/' + str(point_id)
1136
1137
1138
class ShopfloorPointItem:

myems-api/core/store.py 4 locations

@@ 1317-1442 (lines=126) @@
1314
        resp.status = falcon.HTTP_204
1315
1316
1317
class StoreVirtualMeterCollection:
1318
    def __init__(self):
1319
        """Initializes Class"""
1320
        pass
1321
1322
    @staticmethod
1323
    def on_options(req, resp, id_):
1324
        resp.status = falcon.HTTP_200
1325
1326
    @staticmethod
1327
    def on_get(req, resp, id_):
1328
        if 'API-KEY' not in req.headers or \
1329
                not isinstance(req.headers['API-KEY'], str) or \
1330
                len(str.strip(req.headers['API-KEY'])) == 0:
1331
            access_control(req)
1332
        else:
1333
            api_key_control(req)
1334
        if not id_.isdigit() or int(id_) <= 0:
1335
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1336
                                   description='API.INVALID_STORE_ID')
1337
1338
        cnx = mysql.connector.connect(**config.myems_system_db)
1339
        cursor = cnx.cursor()
1340
1341
        cursor.execute(" SELECT name "
1342
                       " FROM tbl_stores "
1343
                       " WHERE id = %s ", (id_,))
1344
        if cursor.fetchone() is None:
1345
            cursor.close()
1346
            cnx.close()
1347
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1348
                                   description='API.STORE_NOT_FOUND')
1349
1350
        query = (" SELECT id, name, uuid "
1351
                 " FROM tbl_energy_categories ")
1352
        cursor.execute(query)
1353
        rows_energy_categories = cursor.fetchall()
1354
1355
        energy_category_dict = dict()
1356
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1357
            for row in rows_energy_categories:
1358
                energy_category_dict[row[0]] = {"id": row[0],
1359
                                                "name": row[1],
1360
                                                "uuid": row[2]}
1361
1362
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1363
                 " FROM tbl_stores t, tbl_stores_virtual_meters tm, tbl_virtual_meters m "
1364
                 " WHERE tm.store_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s "
1365
                 " ORDER BY m.id ")
1366
        cursor.execute(query, (id_,))
1367
        rows = cursor.fetchall()
1368
1369
        result = list()
1370
        if rows is not None and len(rows) > 0:
1371
            for row in rows:
1372
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1373
                               "energy_category": energy_category_dict.get(row[3], None)}
1374
                result.append(meta_result)
1375
1376
        resp.text = json.dumps(result)
1377
1378
    @staticmethod
1379
    @user_logger
1380
    def on_post(req, resp, id_):
1381
        """Handles POST requests"""
1382
        admin_control(req)
1383
        try:
1384
            raw_json = req.stream.read().decode('utf-8')
1385
        except Exception as ex:
1386
            raise falcon.HTTPError(status=falcon.HTTP_400,
1387
                                   title='API.BAD_REQUEST',
1388
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1389
1390
        if not id_.isdigit() or int(id_) <= 0:
1391
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1392
                                   description='API.INVALID_STORE_ID')
1393
1394
        new_values = json.loads(raw_json)
1395
1396
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1397
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1398
                new_values['data']['virtual_meter_id'] <= 0:
1399
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1400
                                   description='API.INVALID_VIRTUAL_METER_ID')
1401
        virtual_meter_id = new_values['data']['virtual_meter_id']
1402
1403
        cnx = mysql.connector.connect(**config.myems_system_db)
1404
        cursor = cnx.cursor()
1405
1406
        cursor.execute(" SELECT name "
1407
                       " from tbl_stores "
1408
                       " WHERE id = %s ", (id_,))
1409
        if cursor.fetchone() is None:
1410
            cursor.close()
1411
            cnx.close()
1412
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1413
                                   description='API.STORE_NOT_FOUND')
1414
1415
        cursor.execute(" SELECT name "
1416
                       " FROM tbl_virtual_meters "
1417
                       " WHERE id = %s ", (virtual_meter_id,))
1418
        if cursor.fetchone() is None:
1419
            cursor.close()
1420
            cnx.close()
1421
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1422
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1423
1424
        query = (" SELECT id " 
1425
                 " FROM tbl_stores_virtual_meters "
1426
                 " WHERE store_id = %s AND virtual_meter_id = %s")
1427
        cursor.execute(query, (id_, virtual_meter_id,))
1428
        if cursor.fetchone() is not None:
1429
            cursor.close()
1430
            cnx.close()
1431
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1432
                                   description='API.STORE_VIRTUAL_METER_RELATION_EXISTS')
1433
1434
        add_row = (" INSERT INTO tbl_stores_virtual_meters (store_id, virtual_meter_id) "
1435
                   " VALUES (%s, %s) ")
1436
        cursor.execute(add_row, (id_, virtual_meter_id,))
1437
        cnx.commit()
1438
        cursor.close()
1439
        cnx.close()
1440
1441
        resp.status = falcon.HTTP_201
1442
        resp.location = '/stores/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1443
1444
1445
class StoreVirtualMeterItem:
@@ 765-890 (lines=126) @@
762
        resp.status = falcon.HTTP_204
763
764
765
class StoreOfflineMeterCollection:
766
    def __init__(self):
767
        """Initializes Class"""
768
        pass
769
770
    @staticmethod
771
    def on_options(req, resp, id_):
772
        resp.status = falcon.HTTP_200
773
774
    @staticmethod
775
    def on_get(req, resp, id_):
776
        if 'API-KEY' not in req.headers or \
777
                not isinstance(req.headers['API-KEY'], str) or \
778
                len(str.strip(req.headers['API-KEY'])) == 0:
779
            access_control(req)
780
        else:
781
            api_key_control(req)
782
        if not id_.isdigit() or int(id_) <= 0:
783
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
784
                                   description='API.INVALID_STORE_ID')
785
786
        cnx = mysql.connector.connect(**config.myems_system_db)
787
        cursor = cnx.cursor()
788
789
        cursor.execute(" SELECT name "
790
                       " FROM tbl_stores "
791
                       " WHERE id = %s ", (id_,))
792
        if cursor.fetchone() is None:
793
            cursor.close()
794
            cnx.close()
795
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
796
                                   description='API.STORE_NOT_FOUND')
797
798
        query = (" SELECT id, name, uuid "
799
                 " FROM tbl_energy_categories ")
800
        cursor.execute(query)
801
        rows_energy_categories = cursor.fetchall()
802
803
        energy_category_dict = dict()
804
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
805
            for row in rows_energy_categories:
806
                energy_category_dict[row[0]] = {"id": row[0],
807
                                                "name": row[1],
808
                                                "uuid": row[2]}
809
810
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
811
                 " FROM tbl_stores s, tbl_stores_offline_meters sm, tbl_offline_meters m "
812
                 " WHERE sm.store_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
813
                 " ORDER BY m.id ")
814
        cursor.execute(query, (id_,))
815
        rows = cursor.fetchall()
816
817
        result = list()
818
        if rows is not None and len(rows) > 0:
819
            for row in rows:
820
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
821
                               "energy_category": energy_category_dict.get(row[3], None)}
822
                result.append(meta_result)
823
824
        resp.text = json.dumps(result)
825
826
    @staticmethod
827
    @user_logger
828
    def on_post(req, resp, id_):
829
        """Handles POST requests"""
830
        admin_control(req)
831
        try:
832
            raw_json = req.stream.read().decode('utf-8')
833
        except Exception as ex:
834
            raise falcon.HTTPError(status=falcon.HTTP_400,
835
                                   title='API.BAD_REQUEST',
836
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
837
838
        if not id_.isdigit() or int(id_) <= 0:
839
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
840
                                   description='API.INVALID_STORE_ID')
841
842
        new_values = json.loads(raw_json)
843
844
        if 'offline_meter_id' not in new_values['data'].keys() or \
845
                not isinstance(new_values['data']['offline_meter_id'], int) or \
846
                new_values['data']['offline_meter_id'] <= 0:
847
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
848
                                   description='API.INVALID_OFFLINE_METER_ID')
849
        offline_meter_id = new_values['data']['offline_meter_id']
850
851
        cnx = mysql.connector.connect(**config.myems_system_db)
852
        cursor = cnx.cursor()
853
854
        cursor.execute(" SELECT name "
855
                       " from tbl_stores "
856
                       " WHERE id = %s ", (id_,))
857
        if cursor.fetchone() is None:
858
            cursor.close()
859
            cnx.close()
860
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
861
                                   description='API.STORE_NOT_FOUND')
862
863
        cursor.execute(" SELECT name "
864
                       " FROM tbl_offline_meters "
865
                       " WHERE id = %s ", (offline_meter_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.OFFLINE_METER_NOT_FOUND')
871
872
        query = (" SELECT id " 
873
                 " FROM tbl_stores_offline_meters "
874
                 " WHERE store_id = %s AND offline_meter_id = %s")
875
        cursor.execute(query, (id_, offline_meter_id,))
876
        if cursor.fetchone() is not None:
877
            cursor.close()
878
            cnx.close()
879
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
880
                                   description='API.STORE_OFFLINE_METER_RELATION_EXISTS')
881
882
        add_row = (" INSERT INTO tbl_stores_offline_meters (store_id, offline_meter_id) "
883
                   " VALUES (%s, %s) ")
884
        cursor.execute(add_row, (id_, offline_meter_id,))
885
        cnx.commit()
886
        cursor.close()
887
        cnx.close()
888
889
        resp.status = falcon.HTTP_201
890
        resp.location = '/stores/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
891
892
893
class StoreOfflineMeterItem:
@@ 577-702 (lines=126) @@
574
        resp.status = falcon.HTTP_200
575
576
577
class StoreMeterCollection:
578
    def __init__(self):
579
        """"Initializes StoreMeterCollection"""
580
        pass
581
582
    @staticmethod
583
    def on_options(req, resp, id_):
584
        resp.status = falcon.HTTP_200
585
586
    @staticmethod
587
    def on_get(req, resp, id_):
588
        if 'API-KEY' not in req.headers or \
589
                not isinstance(req.headers['API-KEY'], str) or \
590
                len(str.strip(req.headers['API-KEY'])) == 0:
591
            access_control(req)
592
        else:
593
            api_key_control(req)
594
        if not id_.isdigit() or int(id_) <= 0:
595
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
596
                                   description='API.INVALID_STORE_ID')
597
598
        cnx = mysql.connector.connect(**config.myems_system_db)
599
        cursor = cnx.cursor()
600
601
        cursor.execute(" SELECT name "
602
                       " FROM tbl_stores "
603
                       " WHERE id = %s ", (id_,))
604
        if cursor.fetchone() is None:
605
            cursor.close()
606
            cnx.close()
607
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
608
                                   description='API.STORE_NOT_FOUND')
609
610
        query = (" SELECT id, name, uuid "
611
                 " FROM tbl_energy_categories ")
612
        cursor.execute(query)
613
        rows_energy_categories = cursor.fetchall()
614
615
        energy_category_dict = dict()
616
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
617
            for row in rows_energy_categories:
618
                energy_category_dict[row[0]] = {"id": row[0],
619
                                                "name": row[1],
620
                                                "uuid": row[2]}
621
622
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
623
                 " FROM tbl_stores t, tbl_stores_meters tm, tbl_meters m "
624
                 " WHERE tm.store_id = t.id AND m.id = tm.meter_id AND t.id = %s "
625
                 " ORDER BY m.id ")
626
        cursor.execute(query, (id_,))
627
        rows = cursor.fetchall()
628
629
        result = list()
630
        if rows is not None and len(rows) > 0:
631
            for row in rows:
632
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
633
                               "energy_category": energy_category_dict.get(row[3], None)}
634
                result.append(meta_result)
635
636
        resp.text = json.dumps(result)
637
638
    @staticmethod
639
    @user_logger
640
    def on_post(req, resp, id_):
641
        """Handles POST requests"""
642
        admin_control(req)
643
        try:
644
            raw_json = req.stream.read().decode('utf-8')
645
        except Exception as ex:
646
            raise falcon.HTTPError(status=falcon.HTTP_400,
647
                                   title='API.BAD_REQUEST',
648
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
649
650
        if not id_.isdigit() or int(id_) <= 0:
651
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
652
                                   description='API.INVALID_STORE_ID')
653
654
        new_values = json.loads(raw_json)
655
656
        if 'meter_id' not in new_values['data'].keys() or \
657
                not isinstance(new_values['data']['meter_id'], int) or \
658
                new_values['data']['meter_id'] <= 0:
659
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
660
                                   description='API.INVALID_METER_ID')
661
        meter_id = new_values['data']['meter_id']
662
663
        cnx = mysql.connector.connect(**config.myems_system_db)
664
        cursor = cnx.cursor()
665
666
        cursor.execute(" SELECT name "
667
                       " from tbl_stores "
668
                       " WHERE id = %s ", (id_,))
669
        if cursor.fetchone() is None:
670
            cursor.close()
671
            cnx.close()
672
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
673
                                   description='API.STORE_NOT_FOUND')
674
675
        cursor.execute(" SELECT name "
676
                       " FROM tbl_meters "
677
                       " WHERE id = %s ", (meter_id,))
678
        if cursor.fetchone() is None:
679
            cursor.close()
680
            cnx.close()
681
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
682
                                   description='API.METER_NOT_FOUND')
683
684
        query = (" SELECT id " 
685
                 " FROM tbl_stores_meters "
686
                 " WHERE store_id = %s AND meter_id = %s")
687
        cursor.execute(query, (id_, meter_id,))
688
        if cursor.fetchone() is not None:
689
            cursor.close()
690
            cnx.close()
691
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
692
                                   description='API.STORE_METER_RELATION_EXISTS')
693
694
        add_row = (" INSERT INTO tbl_stores_meters (store_id, meter_id) "
695
                   " VALUES (%s, %s) ")
696
        cursor.execute(add_row, (id_, meter_id,))
697
        cnx.commit()
698
        cursor.close()
699
        cnx.close()
700
701
        resp.status = falcon.HTTP_201
702
        resp.location = '/stores/' + str(id_) + '/meters/' + str(meter_id)
703
704
705
class StoreMeterItem:
@@ 954-1078 (lines=125) @@
951
        resp.status = falcon.HTTP_204
952
953
954
class StorePointCollection:
955
    def __init__(self):
956
        """Initializes Class"""
957
        pass
958
959
    @staticmethod
960
    def on_options(req, resp, id_):
961
        resp.status = falcon.HTTP_200
962
963
    @staticmethod
964
    def on_get(req, resp, id_):
965
        if 'API-KEY' not in req.headers or \
966
                not isinstance(req.headers['API-KEY'], str) or \
967
                len(str.strip(req.headers['API-KEY'])) == 0:
968
            access_control(req)
969
        else:
970
            api_key_control(req)
971
        if not id_.isdigit() or int(id_) <= 0:
972
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
973
                                   description='API.INVALID_STORE_ID')
974
975
        cnx = mysql.connector.connect(**config.myems_system_db)
976
        cursor = cnx.cursor()
977
978
        cursor.execute(" SELECT name "
979
                       " FROM tbl_stores "
980
                       " WHERE id = %s ", (id_,))
981
        if cursor.fetchone() is None:
982
            cursor.close()
983
            cnx.close()
984
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
985
                                   description='API.STORE_NOT_FOUND')
986
987
        query = (" SELECT id, name, uuid "
988
                 " FROM tbl_data_sources ")
989
        cursor.execute(query)
990
        rows_data_sources = cursor.fetchall()
991
992
        data_source_dict = dict()
993
        if rows_data_sources is not None and len(rows_data_sources) > 0:
994
            for row in rows_data_sources:
995
                data_source_dict[row[0]] = {"id": row[0],
996
                                            "name": row[1],
997
                                            "uuid": row[2]}
998
999
        query = (" SELECT p.id, p.name, p.data_source_id "
1000
                 " FROM tbl_stores t, tbl_stores_points tp, tbl_points p "
1001
                 " WHERE tp.store_id = t.id AND p.id = tp.point_id AND t.id = %s "
1002
                 " ORDER BY p.id ")
1003
        cursor.execute(query, (id_,))
1004
        rows = cursor.fetchall()
1005
1006
        result = list()
1007
        if rows is not None and len(rows) > 0:
1008
            for row in rows:
1009
                meta_result = {"id": row[0], "name": row[1], "data_source": data_source_dict.get(row[2], None)}
1010
                result.append(meta_result)
1011
1012
        resp.text = json.dumps(result)
1013
1014
    @staticmethod
1015
    @user_logger
1016
    def on_post(req, resp, id_):
1017
        """Handles POST requests"""
1018
        admin_control(req)
1019
        try:
1020
            raw_json = req.stream.read().decode('utf-8')
1021
        except Exception as ex:
1022
            raise falcon.HTTPError(status=falcon.HTTP_400,
1023
                                   title='API.BAD_REQUEST',
1024
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1025
1026
        if not id_.isdigit() or int(id_) <= 0:
1027
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1028
                                   description='API.INVALID_STORE_ID')
1029
1030
        new_values = json.loads(raw_json)
1031
1032
        if 'point_id' not in new_values['data'].keys() or \
1033
                not isinstance(new_values['data']['point_id'], int) or \
1034
                new_values['data']['point_id'] <= 0:
1035
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1036
                                   description='API.INVALID_POINT_ID')
1037
        point_id = new_values['data']['point_id']
1038
1039
        cnx = mysql.connector.connect(**config.myems_system_db)
1040
        cursor = cnx.cursor()
1041
1042
        cursor.execute(" SELECT name "
1043
                       " from tbl_stores "
1044
                       " WHERE id = %s ", (id_,))
1045
        if cursor.fetchone() is None:
1046
            cursor.close()
1047
            cnx.close()
1048
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1049
                                   description='API.STORE_NOT_FOUND')
1050
1051
        cursor.execute(" SELECT name "
1052
                       " FROM tbl_points "
1053
                       " WHERE id = %s ", (point_id,))
1054
        if cursor.fetchone() is None:
1055
            cursor.close()
1056
            cnx.close()
1057
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1058
                                   description='API.POINT_NOT_FOUND')
1059
1060
        query = (" SELECT id " 
1061
                 " FROM tbl_stores_points "
1062
                 " WHERE store_id = %s AND point_id = %s")
1063
        cursor.execute(query, (id_, point_id,))
1064
        if cursor.fetchone() is not None:
1065
            cursor.close()
1066
            cnx.close()
1067
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1068
                                   description='API.STORE_POINT_RELATION_EXISTS')
1069
1070
        add_row = (" INSERT INTO tbl_stores_points (store_id, point_id) "
1071
                   " VALUES (%s, %s) ")
1072
        cursor.execute(add_row, (id_, point_id,))
1073
        cnx.commit()
1074
        cursor.close()
1075
        cnx.close()
1076
1077
        resp.status = falcon.HTTP_201
1078
        resp.location = '/stores/' + str(id_) + '/points/' + str(point_id)
1079
1080
1081
class StorePointItem:

myems-api/core/space.py 4 locations

@@ 3024-3149 (lines=126) @@
3021
        resp.status = falcon.HTTP_204
3022
3023
3024
class SpaceVirtualMeterCollection:
3025
    def __init__(self):
3026
        """Initializes Class"""
3027
        pass
3028
3029
    @staticmethod
3030
    def on_options(req, resp, id_):
3031
        resp.status = falcon.HTTP_200
3032
3033
    @staticmethod
3034
    def on_get(req, resp, id_):
3035
        if 'API-KEY' not in req.headers or \
3036
                not isinstance(req.headers['API-KEY'], str) or \
3037
                len(str.strip(req.headers['API-KEY'])) == 0:
3038
            access_control(req)
3039
        else:
3040
            api_key_control(req)
3041
        if not id_.isdigit() or int(id_) <= 0:
3042
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3043
                                   description='API.INVALID_SPACE_ID')
3044
3045
        cnx = mysql.connector.connect(**config.myems_system_db)
3046
        cursor = cnx.cursor()
3047
3048
        cursor.execute(" SELECT name "
3049
                       " FROM tbl_spaces "
3050
                       " WHERE id = %s ", (id_,))
3051
        if cursor.fetchone() is None:
3052
            cursor.close()
3053
            cnx.close()
3054
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3055
                                   description='API.SPACE_NOT_FOUND')
3056
3057
        query = (" SELECT id, name, uuid "
3058
                 " FROM tbl_energy_categories ")
3059
        cursor.execute(query)
3060
        rows_energy_categories = cursor.fetchall()
3061
3062
        energy_category_dict = dict()
3063
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
3064
            for row in rows_energy_categories:
3065
                energy_category_dict[row[0]] = {"id": row[0],
3066
                                                "name": row[1],
3067
                                                "uuid": row[2]}
3068
3069
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
3070
                 " FROM tbl_spaces s, tbl_spaces_virtual_meters sm, tbl_virtual_meters m "
3071
                 " WHERE sm.space_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
3072
                 " ORDER BY m.id ")
3073
        cursor.execute(query, (id_,))
3074
        rows = cursor.fetchall()
3075
3076
        result = list()
3077
        if rows is not None and len(rows) > 0:
3078
            for row in rows:
3079
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
3080
                               "energy_category": energy_category_dict.get(row[3], None)}
3081
                result.append(meta_result)
3082
3083
        resp.text = json.dumps(result)
3084
3085
    @staticmethod
3086
    @user_logger
3087
    def on_post(req, resp, id_):
3088
        """Handles POST requests"""
3089
        admin_control(req)
3090
        try:
3091
            raw_json = req.stream.read().decode('utf-8')
3092
        except Exception as ex:
3093
            raise falcon.HTTPError(status=falcon.HTTP_400,
3094
                                   title='API.BAD_REQUEST',
3095
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3096
3097
        if not id_.isdigit() or int(id_) <= 0:
3098
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3099
                                   description='API.INVALID_SPACE_ID')
3100
3101
        new_values = json.loads(raw_json)
3102
3103
        if 'virtual_meter_id' not in new_values['data'].keys() or \
3104
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
3105
                new_values['data']['virtual_meter_id'] <= 0:
3106
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3107
                                   description='API.INVALID_VIRTUAL_METER_ID')
3108
        virtual_meter_id = new_values['data']['virtual_meter_id']
3109
3110
        cnx = mysql.connector.connect(**config.myems_system_db)
3111
        cursor = cnx.cursor()
3112
3113
        cursor.execute(" SELECT name "
3114
                       " from tbl_spaces "
3115
                       " WHERE id = %s ", (id_,))
3116
        if cursor.fetchone() is None:
3117
            cursor.close()
3118
            cnx.close()
3119
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3120
                                   description='API.SPACE_NOT_FOUND')
3121
3122
        cursor.execute(" SELECT name "
3123
                       " FROM tbl_virtual_meters "
3124
                       " WHERE id = %s ", (virtual_meter_id,))
3125
        if cursor.fetchone() is None:
3126
            cursor.close()
3127
            cnx.close()
3128
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3129
                                   description='API.VIRTUAL_METER_NOT_FOUND')
3130
3131
        query = (" SELECT id " 
3132
                 " FROM tbl_spaces_virtual_meters "
3133
                 " WHERE space_id = %s AND virtual_meter_id = %s")
3134
        cursor.execute(query, (id_, virtual_meter_id,))
3135
        if cursor.fetchone() is not None:
3136
            cursor.close()
3137
            cnx.close()
3138
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3139
                                   description='API.SPACE_VIRTUAL_METER_RELATION_EXISTS')
3140
3141
        add_row = (" INSERT INTO tbl_spaces_virtual_meters (space_id, virtual_meter_id) "
3142
                   " VALUES (%s, %s) ")
3143
        cursor.execute(add_row, (id_, virtual_meter_id,))
3144
        cnx.commit()
3145
        cursor.close()
3146
        cnx.close()
3147
3148
        resp.status = falcon.HTTP_201
3149
        resp.location = '/spaces/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
3150
3151
3152
class SpaceVirtualMeterItem:
@@ 1771-1896 (lines=126) @@
1768
        resp.status = falcon.HTTP_204
1769
1770
1771
class SpaceOfflineMeterCollection:
1772
    def __init__(self):
1773
        """Initializes Class"""
1774
        pass
1775
1776
    @staticmethod
1777
    def on_options(req, resp, id_):
1778
        resp.status = falcon.HTTP_200
1779
1780
    @staticmethod
1781
    def on_get(req, resp, id_):
1782
        if 'API-KEY' not in req.headers or \
1783
                not isinstance(req.headers['API-KEY'], str) or \
1784
                len(str.strip(req.headers['API-KEY'])) == 0:
1785
            access_control(req)
1786
        else:
1787
            api_key_control(req)
1788
        if not id_.isdigit() or int(id_) <= 0:
1789
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1790
                                   description='API.INVALID_SPACE_ID')
1791
1792
        cnx = mysql.connector.connect(**config.myems_system_db)
1793
        cursor = cnx.cursor()
1794
1795
        cursor.execute(" SELECT name "
1796
                       " FROM tbl_spaces "
1797
                       " WHERE id = %s ", (id_,))
1798
        if cursor.fetchone() is None:
1799
            cursor.close()
1800
            cnx.close()
1801
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1802
                                   description='API.SPACE_NOT_FOUND')
1803
1804
        query = (" SELECT id, name, uuid "
1805
                 " FROM tbl_energy_categories ")
1806
        cursor.execute(query)
1807
        rows_energy_categories = cursor.fetchall()
1808
1809
        energy_category_dict = dict()
1810
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1811
            for row in rows_energy_categories:
1812
                energy_category_dict[row[0]] = {"id": row[0],
1813
                                                "name": row[1],
1814
                                                "uuid": row[2]}
1815
1816
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1817
                 " FROM tbl_spaces s, tbl_spaces_offline_meters sm, tbl_offline_meters m "
1818
                 " WHERE sm.space_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
1819
                 " ORDER BY m.id ")
1820
        cursor.execute(query, (id_,))
1821
        rows = cursor.fetchall()
1822
1823
        result = list()
1824
        if rows is not None and len(rows) > 0:
1825
            for row in rows:
1826
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1827
                               "energy_category": energy_category_dict.get(row[3], None)}
1828
                result.append(meta_result)
1829
1830
        resp.text = json.dumps(result)
1831
1832
    @staticmethod
1833
    @user_logger
1834
    def on_post(req, resp, id_):
1835
        """Handles POST requests"""
1836
        admin_control(req)
1837
        try:
1838
            raw_json = req.stream.read().decode('utf-8')
1839
        except Exception as ex:
1840
            raise falcon.HTTPError(status=falcon.HTTP_400,
1841
                                   title='API.BAD_REQUEST',
1842
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1843
1844
        if not id_.isdigit() or int(id_) <= 0:
1845
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1846
                                   description='API.INVALID_SPACE_ID')
1847
1848
        new_values = json.loads(raw_json)
1849
1850
        if 'offline_meter_id' not in new_values['data'].keys() or \
1851
                not isinstance(new_values['data']['offline_meter_id'], int) or \
1852
                new_values['data']['offline_meter_id'] <= 0:
1853
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1854
                                   description='API.INVALID_OFFLINE_METER_ID')
1855
        offline_meter_id = new_values['data']['offline_meter_id']
1856
1857
        cnx = mysql.connector.connect(**config.myems_system_db)
1858
        cursor = cnx.cursor()
1859
1860
        cursor.execute(" SELECT name "
1861
                       " from tbl_spaces "
1862
                       " WHERE id = %s ", (id_,))
1863
        if cursor.fetchone() is None:
1864
            cursor.close()
1865
            cnx.close()
1866
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1867
                                   description='API.SPACE_NOT_FOUND')
1868
1869
        cursor.execute(" SELECT name "
1870
                       " FROM tbl_offline_meters "
1871
                       " WHERE id = %s ", (offline_meter_id,))
1872
        if cursor.fetchone() is None:
1873
            cursor.close()
1874
            cnx.close()
1875
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1876
                                   description='API.OFFLINE_METER_NOT_FOUND')
1877
1878
        query = (" SELECT id " 
1879
                 " FROM tbl_spaces_offline_meters "
1880
                 " WHERE space_id = %s AND offline_meter_id = %s")
1881
        cursor.execute(query, (id_, offline_meter_id,))
1882
        if cursor.fetchone() is not None:
1883
            cursor.close()
1884
            cnx.close()
1885
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1886
                                   description='API.SPACE_OFFLINE_METER_RELATION_EXISTS')
1887
1888
        add_row = (" INSERT INTO tbl_spaces_offline_meters (space_id, offline_meter_id) "
1889
                   " VALUES (%s, %s) ")
1890
        cursor.execute(add_row, (id_, offline_meter_id,))
1891
        cnx.commit()
1892
        cursor.close()
1893
        cnx.close()
1894
1895
        resp.status = falcon.HTTP_201
1896
        resp.location = '/spaces/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
1897
1898
1899
class SpaceOfflineMeterItem:
@@ 1405-1530 (lines=126) @@
1402
        resp.status = falcon.HTTP_204
1403
1404
1405
class SpaceMeterCollection:
1406
    def __init__(self):
1407
        """Initializes Class"""
1408
        pass
1409
1410
    @staticmethod
1411
    def on_options(req, resp, id_):
1412
        resp.status = falcon.HTTP_200
1413
1414
    @staticmethod
1415
    def on_get(req, resp, id_):
1416
        if 'API-KEY' not in req.headers or \
1417
                not isinstance(req.headers['API-KEY'], str) or \
1418
                len(str.strip(req.headers['API-KEY'])) == 0:
1419
            access_control(req)
1420
        else:
1421
            api_key_control(req)
1422
        if not id_.isdigit() or int(id_) <= 0:
1423
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1424
                                   description='API.INVALID_SPACE_ID')
1425
1426
        cnx = mysql.connector.connect(**config.myems_system_db)
1427
        cursor = cnx.cursor()
1428
1429
        cursor.execute(" SELECT name "
1430
                       " FROM tbl_spaces "
1431
                       " WHERE id = %s ", (id_,))
1432
        if cursor.fetchone() is None:
1433
            cursor.close()
1434
            cnx.close()
1435
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1436
                                   description='API.SPACE_NOT_FOUND')
1437
1438
        query = (" SELECT id, name, uuid "
1439
                 " FROM tbl_energy_categories ")
1440
        cursor.execute(query)
1441
        rows_energy_categories = cursor.fetchall()
1442
1443
        energy_category_dict = dict()
1444
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1445
            for row in rows_energy_categories:
1446
                energy_category_dict[row[0]] = {"id": row[0],
1447
                                                "name": row[1],
1448
                                                "uuid": row[2]}
1449
1450
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1451
                 " FROM tbl_spaces s, tbl_spaces_meters sm, tbl_meters m "
1452
                 " WHERE sm.space_id = s.id AND m.id = sm.meter_id AND s.id = %s "
1453
                 " ORDER BY m.id ")
1454
        cursor.execute(query, (id_,))
1455
        rows = cursor.fetchall()
1456
1457
        result = list()
1458
        if rows is not None and len(rows) > 0:
1459
            for row in rows:
1460
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2],
1461
                               "energy_category": energy_category_dict.get(row[3], None)}
1462
                result.append(meta_result)
1463
1464
        resp.text = json.dumps(result)
1465
1466
    @staticmethod
1467
    @user_logger
1468
    def on_post(req, resp, id_):
1469
        """Handles POST requests"""
1470
        admin_control(req)
1471
        try:
1472
            raw_json = req.stream.read().decode('utf-8')
1473
        except Exception as ex:
1474
            raise falcon.HTTPError(status=falcon.HTTP_400,
1475
                                   title='API.BAD_REQUEST',
1476
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1477
1478
        if not id_.isdigit() or int(id_) <= 0:
1479
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1480
                                   description='API.INVALID_SPACE_ID')
1481
1482
        new_values = json.loads(raw_json)
1483
1484
        if 'meter_id' not in new_values['data'].keys() or \
1485
                not isinstance(new_values['data']['meter_id'], int) or \
1486
                new_values['data']['meter_id'] <= 0:
1487
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1488
                                   description='API.INVALID_METER_ID')
1489
        meter_id = new_values['data']['meter_id']
1490
1491
        cnx = mysql.connector.connect(**config.myems_system_db)
1492
        cursor = cnx.cursor()
1493
1494
        cursor.execute(" SELECT name "
1495
                       " from tbl_spaces "
1496
                       " WHERE id = %s ", (id_,))
1497
        if cursor.fetchone() is None:
1498
            cursor.close()
1499
            cnx.close()
1500
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1501
                                   description='API.SPACE_NOT_FOUND')
1502
1503
        cursor.execute(" SELECT name "
1504
                       " FROM tbl_meters "
1505
                       " WHERE id = %s ", (meter_id,))
1506
        if cursor.fetchone() is None:
1507
            cursor.close()
1508
            cnx.close()
1509
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1510
                                   description='API.METER_NOT_FOUND')
1511
1512
        query = (" SELECT id " 
1513
                 " FROM tbl_spaces_meters "
1514
                 " WHERE space_id = %s AND meter_id = %s")
1515
        cursor.execute(query, (id_, meter_id,))
1516
        if cursor.fetchone() is not None:
1517
            cursor.close()
1518
            cnx.close()
1519
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1520
                                   description='API.SPACE_METER_RELATION_EXISTS')
1521
1522
        add_row = (" INSERT INTO tbl_spaces_meters (space_id, meter_id) "
1523
                   " VALUES (%s, %s) ")
1524
        cursor.execute(add_row, (id_, meter_id,))
1525
        cnx.commit()
1526
        cursor.close()
1527
        cnx.close()
1528
1529
        resp.status = falcon.HTTP_201
1530
        resp.location = '/spaces/' + str(id_) + '/meters/' + str(meter_id)
1531
1532
1533
class SpaceMeterItem:
@@ 2136-2260 (lines=125) @@
2133
        resp.status = falcon.HTTP_204
2134
2135
2136
class SpacePointCollection:
2137
    def __init__(self):
2138
        """Initializes Class"""
2139
        pass
2140
2141
    @staticmethod
2142
    def on_options(req, resp, id_):
2143
        resp.status = falcon.HTTP_200
2144
2145
    @staticmethod
2146
    def on_get(req, resp, id_):
2147
        if 'API-KEY' not in req.headers or \
2148
                not isinstance(req.headers['API-KEY'], str) or \
2149
                len(str.strip(req.headers['API-KEY'])) == 0:
2150
            access_control(req)
2151
        else:
2152
            api_key_control(req)
2153
        if not id_.isdigit() or int(id_) <= 0:
2154
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2155
                                   description='API.INVALID_SPACE_ID')
2156
2157
        cnx = mysql.connector.connect(**config.myems_system_db)
2158
        cursor = cnx.cursor()
2159
2160
        cursor.execute(" SELECT name "
2161
                       " FROM tbl_spaces "
2162
                       " WHERE id = %s ", (id_,))
2163
        if cursor.fetchone() is None:
2164
            cursor.close()
2165
            cnx.close()
2166
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2167
                                   description='API.SPACE_NOT_FOUND')
2168
2169
        query = (" SELECT id, name, uuid "
2170
                 " FROM tbl_data_sources ")
2171
        cursor.execute(query)
2172
        rows_data_sources = cursor.fetchall()
2173
2174
        data_source_dict = dict()
2175
        if rows_data_sources is not None and len(rows_data_sources) > 0:
2176
            for row in rows_data_sources:
2177
                data_source_dict[row[0]] = {"id": row[0],
2178
                                            "name": row[1],
2179
                                            "uuid": row[2]}
2180
2181
        query = (" SELECT p.id, p.name, p.data_source_id "
2182
                 " FROM tbl_spaces s, tbl_spaces_points sp, tbl_points p "
2183
                 " WHERE sp.space_id = s.id AND p.id = sp.point_id AND s.id = %s "
2184
                 " ORDER BY p.id ")
2185
        cursor.execute(query, (id_,))
2186
        rows = cursor.fetchall()
2187
2188
        result = list()
2189
        if rows is not None and len(rows) > 0:
2190
            for row in rows:
2191
                meta_result = {"id": row[0], "name": row[1], "data_source": data_source_dict.get(row[2], None)}
2192
                result.append(meta_result)
2193
2194
        resp.text = json.dumps(result)
2195
2196
    @staticmethod
2197
    @user_logger
2198
    def on_post(req, resp, id_):
2199
        """Handles POST requests"""
2200
        admin_control(req)
2201
        try:
2202
            raw_json = req.stream.read().decode('utf-8')
2203
        except Exception as ex:
2204
            raise falcon.HTTPError(status=falcon.HTTP_400,
2205
                                   title='API.BAD_REQUEST',
2206
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2207
2208
        if not id_.isdigit() or int(id_) <= 0:
2209
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2210
                                   description='API.INVALID_SPACE_ID')
2211
2212
        new_values = json.loads(raw_json)
2213
2214
        if 'point_id' not in new_values['data'].keys() or \
2215
                not isinstance(new_values['data']['point_id'], int) or \
2216
                new_values['data']['point_id'] <= 0:
2217
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2218
                                   description='API.INVALID_POINT_ID')
2219
        point_id = new_values['data']['point_id']
2220
2221
        cnx = mysql.connector.connect(**config.myems_system_db)
2222
        cursor = cnx.cursor()
2223
2224
        cursor.execute(" SELECT name "
2225
                       " from tbl_spaces "
2226
                       " WHERE id = %s ", (id_,))
2227
        if cursor.fetchone() is None:
2228
            cursor.close()
2229
            cnx.close()
2230
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2231
                                   description='API.SPACE_NOT_FOUND')
2232
2233
        cursor.execute(" SELECT name "
2234
                       " FROM tbl_points "
2235
                       " WHERE id = %s ", (point_id,))
2236
        if cursor.fetchone() is None:
2237
            cursor.close()
2238
            cnx.close()
2239
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2240
                                   description='API.POINT_NOT_FOUND')
2241
2242
        query = (" SELECT id " 
2243
                 " FROM tbl_spaces_points "
2244
                 " WHERE space_id = %s AND point_id = %s")
2245
        cursor.execute(query, (id_, point_id,))
2246
        if cursor.fetchone() is not None:
2247
            cursor.close()
2248
            cnx.close()
2249
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2250
                                   description='API.SPACE_POINT_RELATION_EXISTS')
2251
2252
        add_row = (" INSERT INTO tbl_spaces_points (space_id, point_id) "
2253
                   " VALUES (%s, %s) ")
2254
        cursor.execute(add_row, (id_, point_id,))
2255
        cnx.commit()
2256
        cursor.close()
2257
        cnx.close()
2258
2259
        resp.status = falcon.HTTP_201
2260
        resp.location = '/spaces/' + str(id_) + '/points/' + str(point_id)
2261
2262
2263
class SpacePointItem: