Code Duplication    Length = 117-118 lines in 16 locations

space.py 4 locations

@@ 2311-2428 (lines=118) @@
2308
        resp.status = falcon.HTTP_204
2309
2310
2311
class SpaceVirtualMeterCollection:
2312
    @staticmethod
2313
    def __init__():
2314
        pass
2315
2316
    @staticmethod
2317
    def on_options(req, resp, id_):
2318
        resp.status = falcon.HTTP_200
2319
2320
    @staticmethod
2321
    def on_get(req, resp, id_):
2322
        if not id_.isdigit() or int(id_) <= 0:
2323
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2324
                                   description='API.INVALID_SPACE_ID')
2325
2326
        cnx = mysql.connector.connect(**config.myems_system_db)
2327
        cursor = cnx.cursor(dictionary=True)
2328
2329
        cursor.execute(" SELECT name "
2330
                       " FROM tbl_spaces "
2331
                       " WHERE id = %s ", (id_,))
2332
        if cursor.fetchone() is None:
2333
            cursor.close()
2334
            cnx.disconnect()
2335
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2336
                                   description='API.SPACE_NOT_FOUND')
2337
2338
        query = (" SELECT id, name, uuid "
2339
                 " FROM tbl_energy_categories ")
2340
        cursor.execute(query)
2341
        rows_energy_categories = cursor.fetchall()
2342
2343
        energy_category_dict = dict()
2344
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
2345
            for row in rows_energy_categories:
2346
                energy_category_dict[row['id']] = {"id": row['id'],
2347
                                                   "name": row['name'],
2348
                                                   "uuid": row['uuid']}
2349
2350
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
2351
                 " FROM tbl_spaces s, tbl_spaces_virtual_meters sm, tbl_virtual_meters m "
2352
                 " WHERE sm.space_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
2353
                 " ORDER BY m.id ")
2354
        cursor.execute(query, (id_,))
2355
        rows = cursor.fetchall()
2356
2357
        result = list()
2358
        if rows is not None and len(rows) > 0:
2359
            for row in rows:
2360
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
2361
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
2362
                               "energy_category": energy_category}
2363
                result.append(meta_result)
2364
2365
        resp.body = json.dumps(result)
2366
2367
    @staticmethod
2368
    def on_post(req, resp, id_):
2369
        """Handles POST requests"""
2370
        try:
2371
            raw_json = req.stream.read().decode('utf-8')
2372
        except Exception as ex:
2373
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
2374
2375
        if not id_.isdigit() or int(id_) <= 0:
2376
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2377
                                   description='API.INVALID_SPACE_ID')
2378
2379
        new_values = json.loads(raw_json, encoding='utf-8')
2380
2381
        if 'virtual_meter_id' not in new_values['data'].keys() or \
2382
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
2383
                new_values['data']['virtual_meter_id'] <= 0:
2384
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
2385
                                   description='API.INVALID_VIRTUAL_METER_ID')
2386
        virtual_meter_id = new_values['data']['virtual_meter_id']
2387
2388
        cnx = mysql.connector.connect(**config.myems_system_db)
2389
        cursor = cnx.cursor()
2390
2391
        cursor.execute(" SELECT name "
2392
                       " from tbl_spaces "
2393
                       " WHERE id = %s ", (id_,))
2394
        if cursor.fetchone() is None:
2395
            cursor.close()
2396
            cnx.disconnect()
2397
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2398
                                   description='API.SPACE_NOT_FOUND')
2399
2400
        cursor.execute(" SELECT name "
2401
                       " FROM tbl_virtual_meters "
2402
                       " WHERE id = %s ", (virtual_meter_id,))
2403
        if cursor.fetchone() is None:
2404
            cursor.close()
2405
            cnx.disconnect()
2406
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
2407
                                   description='API.VIRTUAL_METER_NOT_FOUND')
2408
2409
        query = (" SELECT id " 
2410
                 " FROM tbl_spaces_virtual_meters "
2411
                 " WHERE space_id = %s AND virtual_meter_id = %s")
2412
        cursor.execute(query, (id_, virtual_meter_id,))
2413
        if cursor.fetchone() is not None:
2414
            cursor.close()
2415
            cnx.disconnect()
2416
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
2417
                                   description='API.SPACE_VIRTUAL_METER_RELATION_EXISTED')
2418
2419
        add_row = (" INSERT INTO tbl_spaces_virtual_meters (space_id, virtual_meter_id) "
2420
                   " VALUES (%s, %s) ")
2421
        cursor.execute(add_row, (id_, virtual_meter_id,))
2422
        new_id = cursor.lastrowid
2423
        cnx.commit()
2424
        cursor.close()
2425
        cnx.disconnect()
2426
2427
        resp.status = falcon.HTTP_201
2428
        resp.location = '/spaces/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
2429
2430
2431
class SpaceVirtualMeterItem:
@@ 1298-1415 (lines=118) @@
1295
        resp.status = falcon.HTTP_204
1296
1297
1298
class SpaceOfflineMeterCollection:
1299
    @staticmethod
1300
    def __init__():
1301
        pass
1302
1303
    @staticmethod
1304
    def on_options(req, resp, id_):
1305
        resp.status = falcon.HTTP_200
1306
1307
    @staticmethod
1308
    def on_get(req, resp, id_):
1309
        if not id_.isdigit() or int(id_) <= 0:
1310
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1311
                                   description='API.INVALID_SPACE_ID')
1312
1313
        cnx = mysql.connector.connect(**config.myems_system_db)
1314
        cursor = cnx.cursor(dictionary=True)
1315
1316
        cursor.execute(" SELECT name "
1317
                       " FROM tbl_spaces "
1318
                       " WHERE id = %s ", (id_,))
1319
        if cursor.fetchone() is None:
1320
            cursor.close()
1321
            cnx.disconnect()
1322
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1323
                                   description='API.SPACE_NOT_FOUND')
1324
1325
        query = (" SELECT id, name, uuid "
1326
                 " FROM tbl_energy_categories ")
1327
        cursor.execute(query)
1328
        rows_energy_categories = cursor.fetchall()
1329
1330
        energy_category_dict = dict()
1331
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1332
            for row in rows_energy_categories:
1333
                energy_category_dict[row['id']] = {"id": row['id'],
1334
                                                   "name": row['name'],
1335
                                                   "uuid": row['uuid']}
1336
1337
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1338
                 " FROM tbl_spaces s, tbl_spaces_offline_meters sm, tbl_offline_meters m "
1339
                 " WHERE sm.space_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
1340
                 " ORDER BY m.id ")
1341
        cursor.execute(query, (id_,))
1342
        rows = cursor.fetchall()
1343
1344
        result = list()
1345
        if rows is not None and len(rows) > 0:
1346
            for row in rows:
1347
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1348
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1349
                               "energy_category": energy_category}
1350
                result.append(meta_result)
1351
1352
        resp.body = json.dumps(result)
1353
1354
    @staticmethod
1355
    def on_post(req, resp, id_):
1356
        """Handles POST requests"""
1357
        try:
1358
            raw_json = req.stream.read().decode('utf-8')
1359
        except Exception as ex:
1360
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1361
1362
        if not id_.isdigit() or int(id_) <= 0:
1363
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1364
                                   description='API.INVALID_SPACE_ID')
1365
1366
        new_values = json.loads(raw_json, encoding='utf-8')
1367
1368
        if 'offline_meter_id' not in new_values['data'].keys() or \
1369
                not isinstance(new_values['data']['offline_meter_id'], int) or \
1370
                new_values['data']['offline_meter_id'] <= 0:
1371
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1372
                                   description='API.INVALID_OFFLINE_METER_ID')
1373
        offline_meter_id = new_values['data']['offline_meter_id']
1374
1375
        cnx = mysql.connector.connect(**config.myems_system_db)
1376
        cursor = cnx.cursor()
1377
1378
        cursor.execute(" SELECT name "
1379
                       " from tbl_spaces "
1380
                       " WHERE id = %s ", (id_,))
1381
        if cursor.fetchone() is None:
1382
            cursor.close()
1383
            cnx.disconnect()
1384
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1385
                                   description='API.SPACE_NOT_FOUND')
1386
1387
        cursor.execute(" SELECT name "
1388
                       " FROM tbl_offline_meters "
1389
                       " WHERE id = %s ", (offline_meter_id,))
1390
        if cursor.fetchone() is None:
1391
            cursor.close()
1392
            cnx.disconnect()
1393
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1394
                                   description='API.OFFLINE_METER_NOT_FOUND')
1395
1396
        query = (" SELECT id " 
1397
                 " FROM tbl_spaces_offline_meters "
1398
                 " WHERE space_id = %s AND offline_meter_id = %s")
1399
        cursor.execute(query, (id_, offline_meter_id,))
1400
        if cursor.fetchone() is not None:
1401
            cursor.close()
1402
            cnx.disconnect()
1403
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1404
                                   description='API.SPACE_OFFLINE_METER_RELATION_EXISTED')
1405
1406
        add_row = (" INSERT INTO tbl_spaces_offline_meters (space_id, offline_meter_id) "
1407
                   " VALUES (%s, %s) ")
1408
        cursor.execute(add_row, (id_, offline_meter_id,))
1409
        new_id = cursor.lastrowid
1410
        cnx.commit()
1411
        cursor.close()
1412
        cnx.disconnect()
1413
1414
        resp.status = falcon.HTTP_201
1415
        resp.location = '/spaces/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
1416
1417
1418
class SpaceOfflineMeterItem:
@@ 1120-1237 (lines=118) @@
1117
        resp.status = falcon.HTTP_204
1118
1119
1120
class SpaceMeterCollection:
1121
    @staticmethod
1122
    def __init__():
1123
        pass
1124
1125
    @staticmethod
1126
    def on_options(req, resp, id_):
1127
        resp.status = falcon.HTTP_200
1128
1129
    @staticmethod
1130
    def on_get(req, resp, id_):
1131
        if not id_.isdigit() or int(id_) <= 0:
1132
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1133
                                   description='API.INVALID_SPACE_ID')
1134
1135
        cnx = mysql.connector.connect(**config.myems_system_db)
1136
        cursor = cnx.cursor(dictionary=True)
1137
1138
        cursor.execute(" SELECT name "
1139
                       " FROM tbl_spaces "
1140
                       " WHERE id = %s ", (id_,))
1141
        if cursor.fetchone() is None:
1142
            cursor.close()
1143
            cnx.disconnect()
1144
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1145
                                   description='API.SPACE_NOT_FOUND')
1146
1147
        query = (" SELECT id, name, uuid "
1148
                 " FROM tbl_energy_categories ")
1149
        cursor.execute(query)
1150
        rows_energy_categories = cursor.fetchall()
1151
1152
        energy_category_dict = dict()
1153
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1154
            for row in rows_energy_categories:
1155
                energy_category_dict[row['id']] = {"id": row['id'],
1156
                                                   "name": row['name'],
1157
                                                   "uuid": row['uuid']}
1158
1159
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1160
                 " FROM tbl_spaces s, tbl_spaces_meters sm, tbl_meters m "
1161
                 " WHERE sm.space_id = s.id AND m.id = sm.meter_id AND s.id = %s "
1162
                 " ORDER BY m.id ")
1163
        cursor.execute(query, (id_,))
1164
        rows = cursor.fetchall()
1165
1166
        result = list()
1167
        if rows is not None and len(rows) > 0:
1168
            for row in rows:
1169
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1170
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1171
                               "energy_category": energy_category}
1172
                result.append(meta_result)
1173
1174
        resp.body = json.dumps(result)
1175
1176
    @staticmethod
1177
    def on_post(req, resp, id_):
1178
        """Handles POST requests"""
1179
        try:
1180
            raw_json = req.stream.read().decode('utf-8')
1181
        except Exception as ex:
1182
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1183
1184
        if not id_.isdigit() or int(id_) <= 0:
1185
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1186
                                   description='API.INVALID_SPACE_ID')
1187
1188
        new_values = json.loads(raw_json, encoding='utf-8')
1189
1190
        if 'meter_id' not in new_values['data'].keys() or \
1191
                not isinstance(new_values['data']['meter_id'], int) or \
1192
                new_values['data']['meter_id'] <= 0:
1193
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1194
                                   description='API.INVALID_METER_ID')
1195
        meter_id = new_values['data']['meter_id']
1196
1197
        cnx = mysql.connector.connect(**config.myems_system_db)
1198
        cursor = cnx.cursor()
1199
1200
        cursor.execute(" SELECT name "
1201
                       " from tbl_spaces "
1202
                       " WHERE id = %s ", (id_,))
1203
        if cursor.fetchone() is None:
1204
            cursor.close()
1205
            cnx.disconnect()
1206
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1207
                                   description='API.SPACE_NOT_FOUND')
1208
1209
        cursor.execute(" SELECT name "
1210
                       " FROM tbl_meters "
1211
                       " WHERE id = %s ", (meter_id,))
1212
        if cursor.fetchone() is None:
1213
            cursor.close()
1214
            cnx.disconnect()
1215
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1216
                                   description='API.METER_NOT_FOUND')
1217
1218
        query = (" SELECT id " 
1219
                 " FROM tbl_spaces_meters "
1220
                 " WHERE space_id = %s AND meter_id = %s")
1221
        cursor.execute(query, (id_, meter_id,))
1222
        if cursor.fetchone() is not None:
1223
            cursor.close()
1224
            cnx.disconnect()
1225
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1226
                                   description='API.SPACE_METER_RELATION_EXISTED')
1227
1228
        add_row = (" INSERT INTO tbl_spaces_meters (space_id, meter_id) "
1229
                   " VALUES (%s, %s) ")
1230
        cursor.execute(add_row, (id_, meter_id,))
1231
        new_id = cursor.lastrowid
1232
        cnx.commit()
1233
        cursor.close()
1234
        cnx.disconnect()
1235
1236
        resp.status = falcon.HTTP_201
1237
        resp.location = '/spaces/' + str(id_) + '/meters/' + str(meter_id)
1238
1239
1240
class SpaceMeterItem:
@@ 1477-1593 (lines=117) @@
1474
        resp.status = falcon.HTTP_204
1475
1476
1477
class SpacePointCollection:
1478
    @staticmethod
1479
    def __init__():
1480
        pass
1481
1482
    @staticmethod
1483
    def on_options(req, resp, id_):
1484
        resp.status = falcon.HTTP_200
1485
1486
    @staticmethod
1487
    def on_get(req, resp, id_):
1488
        if not id_.isdigit() or int(id_) <= 0:
1489
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1490
                                   description='API.INVALID_SPACE_ID')
1491
1492
        cnx = mysql.connector.connect(**config.myems_system_db)
1493
        cursor = cnx.cursor(dictionary=True)
1494
1495
        cursor.execute(" SELECT name "
1496
                       " FROM tbl_spaces "
1497
                       " WHERE id = %s ", (id_,))
1498
        if cursor.fetchone() is None:
1499
            cursor.close()
1500
            cnx.disconnect()
1501
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1502
                                   description='API.SPACE_NOT_FOUND')
1503
1504
        query = (" SELECT id, name, uuid "
1505
                 " FROM tbl_data_sources ")
1506
        cursor.execute(query)
1507
        rows_data_sources = cursor.fetchall()
1508
1509
        data_source_dict = dict()
1510
        if rows_data_sources is not None and len(rows_data_sources) > 0:
1511
            for row in rows_data_sources:
1512
                data_source_dict[row['id']] = {"id": row['id'],
1513
                                               "name": row['name'],
1514
                                               "uuid": row['uuid']}
1515
1516
        query = (" SELECT p.id, p.name, p.data_source_id "
1517
                 " FROM tbl_spaces s, tbl_spaces_points sp, tbl_points p "
1518
                 " WHERE sp.space_id = s.id AND p.id = sp.point_id AND s.id = %s "
1519
                 " ORDER BY p.id ")
1520
        cursor.execute(query, (id_,))
1521
        rows = cursor.fetchall()
1522
1523
        result = list()
1524
        if rows is not None and len(rows) > 0:
1525
            for row in rows:
1526
                data_source = data_source_dict.get(row['data_source_id'], None)
1527
                meta_result = {"id": row['id'], "name": row['name'], "data_source": data_source}
1528
                result.append(meta_result)
1529
1530
        resp.body = json.dumps(result)
1531
1532
    @staticmethod
1533
    def on_post(req, resp, id_):
1534
        """Handles POST requests"""
1535
        try:
1536
            raw_json = req.stream.read().decode('utf-8')
1537
        except Exception as ex:
1538
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1539
1540
        if not id_.isdigit() or int(id_) <= 0:
1541
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1542
                                   description='API.INVALID_SPACE_ID')
1543
1544
        new_values = json.loads(raw_json, encoding='utf-8')
1545
1546
        if 'point_id' not in new_values['data'].keys() or \
1547
                not isinstance(new_values['data']['point_id'], int) or \
1548
                new_values['data']['point_id'] <= 0:
1549
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1550
                                   description='API.INVALID_POINT_ID')
1551
        point_id = new_values['data']['point_id']
1552
1553
        cnx = mysql.connector.connect(**config.myems_system_db)
1554
        cursor = cnx.cursor()
1555
1556
        cursor.execute(" SELECT name "
1557
                       " from tbl_spaces "
1558
                       " WHERE id = %s ", (id_,))
1559
        if cursor.fetchone() is None:
1560
            cursor.close()
1561
            cnx.disconnect()
1562
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1563
                                   description='API.SPACE_NOT_FOUND')
1564
1565
        cursor.execute(" SELECT name "
1566
                       " FROM tbl_points "
1567
                       " WHERE id = %s ", (point_id,))
1568
        if cursor.fetchone() is None:
1569
            cursor.close()
1570
            cnx.disconnect()
1571
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1572
                                   description='API.POINT_NOT_FOUND')
1573
1574
        query = (" SELECT id " 
1575
                 " FROM tbl_spaces_points "
1576
                 " WHERE space_id = %s AND point_id = %s")
1577
        cursor.execute(query, (id_, point_id,))
1578
        if cursor.fetchone() is not None:
1579
            cursor.close()
1580
            cnx.disconnect()
1581
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1582
                                   description='API.SPACE_POINT_RELATION_EXISTED')
1583
1584
        add_row = (" INSERT INTO tbl_spaces_points (space_id, point_id) "
1585
                   " VALUES (%s, %s) ")
1586
        cursor.execute(add_row, (id_, point_id,))
1587
        new_id = cursor.lastrowid
1588
        cnx.commit()
1589
        cursor.close()
1590
        cnx.disconnect()
1591
1592
        resp.status = falcon.HTTP_201
1593
        resp.location = '/spaces/' + str(id_) + '/points/' + str(point_id)
1594
1595
1596
class SpacePointItem:

tenant.py 4 locations

@@ 1386-1503 (lines=118) @@
1383
        resp.status = falcon.HTTP_204
1384
1385
1386
class TenantVirtualMeterCollection:
1387
    @staticmethod
1388
    def __init__():
1389
        pass
1390
1391
    @staticmethod
1392
    def on_options(req, resp, id_):
1393
        resp.status = falcon.HTTP_200
1394
1395
    @staticmethod
1396
    def on_get(req, resp, id_):
1397
        if not id_.isdigit() or int(id_) <= 0:
1398
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1399
                                   description='API.INVALID_TENANT_ID')
1400
1401
        cnx = mysql.connector.connect(**config.myems_system_db)
1402
        cursor = cnx.cursor(dictionary=True)
1403
1404
        cursor.execute(" SELECT name "
1405
                       " FROM tbl_tenants "
1406
                       " WHERE id = %s ", (id_,))
1407
        if cursor.fetchone() is None:
1408
            cursor.close()
1409
            cnx.disconnect()
1410
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1411
                                   description='API.TENANT_NOT_FOUND')
1412
1413
        query = (" SELECT id, name, uuid "
1414
                 " FROM tbl_energy_categories ")
1415
        cursor.execute(query)
1416
        rows_energy_categories = cursor.fetchall()
1417
1418
        energy_category_dict = dict()
1419
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1420
            for row in rows_energy_categories:
1421
                energy_category_dict[row['id']] = {"id": row['id'],
1422
                                                   "name": row['name'],
1423
                                                   "uuid": row['uuid']}
1424
1425
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1426
                 " FROM tbl_tenants t, tbl_tenants_virtual_meters tm, tbl_virtual_meters m "
1427
                 " WHERE tm.tenant_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s "
1428
                 " ORDER BY m.id ")
1429
        cursor.execute(query, (id_,))
1430
        rows = cursor.fetchall()
1431
1432
        result = list()
1433
        if rows is not None and len(rows) > 0:
1434
            for row in rows:
1435
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1436
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1437
                               "energy_category": energy_category}
1438
                result.append(meta_result)
1439
1440
        resp.body = json.dumps(result)
1441
1442
    @staticmethod
1443
    def on_post(req, resp, id_):
1444
        """Handles POST requests"""
1445
        try:
1446
            raw_json = req.stream.read().decode('utf-8')
1447
        except Exception as ex:
1448
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1449
1450
        if not id_.isdigit() or int(id_) <= 0:
1451
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1452
                                   description='API.INVALID_TENANT_ID')
1453
1454
        new_values = json.loads(raw_json, encoding='utf-8')
1455
1456
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1457
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1458
                new_values['data']['virtual_meter_id'] <= 0:
1459
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1460
                                   description='API.INVALID_VIRTUAL_METER_ID')
1461
        virtual_meter_id = new_values['data']['virtual_meter_id']
1462
1463
        cnx = mysql.connector.connect(**config.myems_system_db)
1464
        cursor = cnx.cursor()
1465
1466
        cursor.execute(" SELECT name "
1467
                       " from tbl_tenants "
1468
                       " WHERE id = %s ", (id_,))
1469
        if cursor.fetchone() is None:
1470
            cursor.close()
1471
            cnx.disconnect()
1472
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1473
                                   description='API.TENANT_NOT_FOUND')
1474
1475
        cursor.execute(" SELECT name "
1476
                       " FROM tbl_virtual_meters "
1477
                       " WHERE id = %s ", (virtual_meter_id,))
1478
        if cursor.fetchone() is None:
1479
            cursor.close()
1480
            cnx.disconnect()
1481
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1482
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1483
1484
        query = (" SELECT id " 
1485
                 " FROM tbl_tenants_virtual_meters "
1486
                 " WHERE tenant_id = %s AND virtual_meter_id = %s")
1487
        cursor.execute(query, (id_, virtual_meter_id,))
1488
        if cursor.fetchone() is not None:
1489
            cursor.close()
1490
            cnx.disconnect()
1491
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1492
                                   description='API.TENANT_VIRTUAL_METER_RELATION_EXISTED')
1493
1494
        add_row = (" INSERT INTO tbl_tenants_virtual_meters (tenant_id, virtual_meter_id) "
1495
                   " VALUES (%s, %s) ")
1496
        cursor.execute(add_row, (id_, virtual_meter_id,))
1497
        new_id = cursor.lastrowid
1498
        cnx.commit()
1499
        cursor.close()
1500
        cnx.disconnect()
1501
1502
        resp.status = falcon.HTTP_201
1503
        resp.location = '/tenants/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1504
1505
1506
class TenantVirtualMeterItem:
@@ 865-982 (lines=118) @@
862
        resp.status = falcon.HTTP_204
863
864
865
class TenantOfflineMeterCollection:
866
    @staticmethod
867
    def __init__():
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 not id_.isdigit() or int(id_) <= 0:
877
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
878
                                   description='API.INVALID_TENANT_ID')
879
880
        cnx = mysql.connector.connect(**config.myems_system_db)
881
        cursor = cnx.cursor(dictionary=True)
882
883
        cursor.execute(" SELECT name "
884
                       " FROM tbl_tenants "
885
                       " WHERE id = %s ", (id_,))
886
        if cursor.fetchone() is None:
887
            cursor.close()
888
            cnx.disconnect()
889
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
890
                                   description='API.TENANT_NOT_FOUND')
891
892
        query = (" SELECT id, name, uuid "
893
                 " FROM tbl_energy_categories ")
894
        cursor.execute(query)
895
        rows_energy_categories = cursor.fetchall()
896
897
        energy_category_dict = dict()
898
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
899
            for row in rows_energy_categories:
900
                energy_category_dict[row['id']] = {"id": row['id'],
901
                                                   "name": row['name'],
902
                                                   "uuid": row['uuid']}
903
904
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
905
                 " FROM tbl_tenants s, tbl_tenants_offline_meters sm, tbl_offline_meters m "
906
                 " WHERE sm.tenant_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
907
                 " ORDER BY m.id ")
908
        cursor.execute(query, (id_,))
909
        rows = cursor.fetchall()
910
911
        result = list()
912
        if rows is not None and len(rows) > 0:
913
            for row in rows:
914
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
915
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
916
                               "energy_category": energy_category}
917
                result.append(meta_result)
918
919
        resp.body = json.dumps(result)
920
921
    @staticmethod
922
    def on_post(req, resp, id_):
923
        """Handles POST requests"""
924
        try:
925
            raw_json = req.stream.read().decode('utf-8')
926
        except Exception as ex:
927
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
928
929
        if not id_.isdigit() or int(id_) <= 0:
930
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
931
                                   description='API.INVALID_TENANT_ID')
932
933
        new_values = json.loads(raw_json, encoding='utf-8')
934
935
        if 'offline_meter_id' not in new_values['data'].keys() or \
936
                not isinstance(new_values['data']['offline_meter_id'], int) or \
937
                new_values['data']['offline_meter_id'] <= 0:
938
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
939
                                   description='API.INVALID_OFFLINE_METER_ID')
940
        offline_meter_id = new_values['data']['offline_meter_id']
941
942
        cnx = mysql.connector.connect(**config.myems_system_db)
943
        cursor = cnx.cursor()
944
945
        cursor.execute(" SELECT name "
946
                       " from tbl_tenants "
947
                       " WHERE id = %s ", (id_,))
948
        if cursor.fetchone() is None:
949
            cursor.close()
950
            cnx.disconnect()
951
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
952
                                   description='API.TENANT_NOT_FOUND')
953
954
        cursor.execute(" SELECT name "
955
                       " FROM tbl_offline_meters "
956
                       " WHERE id = %s ", (offline_meter_id,))
957
        if cursor.fetchone() is None:
958
            cursor.close()
959
            cnx.disconnect()
960
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
961
                                   description='API.OFFLINE_METER_NOT_FOUND')
962
963
        query = (" SELECT id " 
964
                 " FROM tbl_tenants_offline_meters "
965
                 " WHERE tenant_id = %s AND offline_meter_id = %s")
966
        cursor.execute(query, (id_, offline_meter_id,))
967
        if cursor.fetchone() is not None:
968
            cursor.close()
969
            cnx.disconnect()
970
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
971
                                   description='API.TENANT_OFFLINE_METER_RELATION_EXISTED')
972
973
        add_row = (" INSERT INTO tbl_tenants_offline_meters (tenant_id, offline_meter_id) "
974
                   " VALUES (%s, %s) ")
975
        cursor.execute(add_row, (id_, offline_meter_id,))
976
        new_id = cursor.lastrowid
977
        cnx.commit()
978
        cursor.close()
979
        cnx.disconnect()
980
981
        resp.status = falcon.HTTP_201
982
        resp.location = '/tenants/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
983
984
985
class TenantOfflineMeterItem:
@@ 687-804 (lines=118) @@
684
        resp.status = falcon.HTTP_200
685
686
687
class TenantMeterCollection:
688
    @staticmethod
689
    def __init__():
690
        pass
691
692
    @staticmethod
693
    def on_options(req, resp, id_):
694
        resp.status = falcon.HTTP_200
695
696
    @staticmethod
697
    def on_get(req, resp, id_):
698
        if not id_.isdigit() or int(id_) <= 0:
699
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
700
                                   description='API.INVALID_TENANT_ID')
701
702
        cnx = mysql.connector.connect(**config.myems_system_db)
703
        cursor = cnx.cursor(dictionary=True)
704
705
        cursor.execute(" SELECT name "
706
                       " FROM tbl_tenants "
707
                       " WHERE id = %s ", (id_,))
708
        if cursor.fetchone() is None:
709
            cursor.close()
710
            cnx.disconnect()
711
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
712
                                   description='API.TENANT_NOT_FOUND')
713
714
        query = (" SELECT id, name, uuid "
715
                 " FROM tbl_energy_categories ")
716
        cursor.execute(query)
717
        rows_energy_categories = cursor.fetchall()
718
719
        energy_category_dict = dict()
720
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
721
            for row in rows_energy_categories:
722
                energy_category_dict[row['id']] = {"id": row['id'],
723
                                                   "name": row['name'],
724
                                                   "uuid": row['uuid']}
725
726
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
727
                 " FROM tbl_tenants t, tbl_tenants_meters tm, tbl_meters m "
728
                 " WHERE tm.tenant_id = t.id AND m.id = tm.meter_id AND t.id = %s "
729
                 " ORDER BY m.id ")
730
        cursor.execute(query, (id_,))
731
        rows = cursor.fetchall()
732
733
        result = list()
734
        if rows is not None and len(rows) > 0:
735
            for row in rows:
736
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
737
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
738
                               "energy_category": energy_category}
739
                result.append(meta_result)
740
741
        resp.body = json.dumps(result)
742
743
    @staticmethod
744
    def on_post(req, resp, id_):
745
        """Handles POST requests"""
746
        try:
747
            raw_json = req.stream.read().decode('utf-8')
748
        except Exception as ex:
749
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
750
751
        if not id_.isdigit() or int(id_) <= 0:
752
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
753
                                   description='API.INVALID_TENANT_ID')
754
755
        new_values = json.loads(raw_json, encoding='utf-8')
756
757
        if 'meter_id' not in new_values['data'].keys() or \
758
                not isinstance(new_values['data']['meter_id'], int) or \
759
                new_values['data']['meter_id'] <= 0:
760
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
761
                                   description='API.INVALID_METER_ID')
762
        meter_id = new_values['data']['meter_id']
763
764
        cnx = mysql.connector.connect(**config.myems_system_db)
765
        cursor = cnx.cursor()
766
767
        cursor.execute(" SELECT name "
768
                       " from tbl_tenants "
769
                       " WHERE id = %s ", (id_,))
770
        if cursor.fetchone() is None:
771
            cursor.close()
772
            cnx.disconnect()
773
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
774
                                   description='API.TENANT_NOT_FOUND')
775
776
        cursor.execute(" SELECT name "
777
                       " FROM tbl_meters "
778
                       " WHERE id = %s ", (meter_id,))
779
        if cursor.fetchone() is None:
780
            cursor.close()
781
            cnx.disconnect()
782
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
783
                                   description='API.METER_NOT_FOUND')
784
785
        query = (" SELECT id " 
786
                 " FROM tbl_tenants_meters "
787
                 " WHERE tenant_id = %s AND meter_id = %s")
788
        cursor.execute(query, (id_, meter_id,))
789
        if cursor.fetchone() is not None:
790
            cursor.close()
791
            cnx.disconnect()
792
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
793
                                   description='API.TENANT_METER_RELATION_EXISTED')
794
795
        add_row = (" INSERT INTO tbl_tenants_meters (tenant_id, meter_id) "
796
                   " VALUES (%s, %s) ")
797
        cursor.execute(add_row, (id_, meter_id,))
798
        new_id = cursor.lastrowid
799
        cnx.commit()
800
        cursor.close()
801
        cnx.disconnect()
802
803
        resp.status = falcon.HTTP_201
804
        resp.location = '/tenants/' + str(id_) + '/meters/' + str(meter_id)
805
806
807
class TenantMeterItem:
@@ 1044-1160 (lines=117) @@
1041
        resp.status = falcon.HTTP_204
1042
1043
1044
class TenantPointCollection:
1045
    @staticmethod
1046
    def __init__():
1047
        pass
1048
1049
    @staticmethod
1050
    def on_options(req, resp, id_):
1051
        resp.status = falcon.HTTP_200
1052
1053
    @staticmethod
1054
    def on_get(req, resp, id_):
1055
        if not id_.isdigit() or int(id_) <= 0:
1056
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1057
                                   description='API.INVALID_TENANT_ID')
1058
1059
        cnx = mysql.connector.connect(**config.myems_system_db)
1060
        cursor = cnx.cursor(dictionary=True)
1061
1062
        cursor.execute(" SELECT name "
1063
                       " FROM tbl_tenants "
1064
                       " WHERE id = %s ", (id_,))
1065
        if cursor.fetchone() is None:
1066
            cursor.close()
1067
            cnx.disconnect()
1068
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1069
                                   description='API.TENANT_NOT_FOUND')
1070
1071
        query = (" SELECT id, name, uuid "
1072
                 " FROM tbl_data_sources ")
1073
        cursor.execute(query)
1074
        rows_data_sources = cursor.fetchall()
1075
1076
        data_source_dict = dict()
1077
        if rows_data_sources is not None and len(rows_data_sources) > 0:
1078
            for row in rows_data_sources:
1079
                data_source_dict[row['id']] = {"id": row['id'],
1080
                                               "name": row['name'],
1081
                                               "uuid": row['uuid']}
1082
1083
        query = (" SELECT p.id, p.name, p.data_source_id "
1084
                 " FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p "
1085
                 " WHERE tp.tenant_id = t.id AND p.id = tp.point_id AND t.id = %s "
1086
                 " ORDER BY p.id ")
1087
        cursor.execute(query, (id_,))
1088
        rows = cursor.fetchall()
1089
1090
        result = list()
1091
        if rows is not None and len(rows) > 0:
1092
            for row in rows:
1093
                data_source = data_source_dict.get(row['data_source_id'], None)
1094
                meta_result = {"id": row['id'], "name": row['name'], "data_source": data_source}
1095
                result.append(meta_result)
1096
1097
        resp.body = json.dumps(result)
1098
1099
    @staticmethod
1100
    def on_post(req, resp, id_):
1101
        """Handles POST requests"""
1102
        try:
1103
            raw_json = req.stream.read().decode('utf-8')
1104
        except Exception as ex:
1105
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1106
1107
        if not id_.isdigit() or int(id_) <= 0:
1108
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1109
                                   description='API.INVALID_TENANT_ID')
1110
1111
        new_values = json.loads(raw_json, encoding='utf-8')
1112
1113
        if 'point_id' not in new_values['data'].keys() or \
1114
                not isinstance(new_values['data']['point_id'], int) or \
1115
                new_values['data']['point_id'] <= 0:
1116
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1117
                                   description='API.INVALID_POINT_ID')
1118
        point_id = new_values['data']['point_id']
1119
1120
        cnx = mysql.connector.connect(**config.myems_system_db)
1121
        cursor = cnx.cursor()
1122
1123
        cursor.execute(" SELECT name "
1124
                       " from tbl_tenants "
1125
                       " WHERE id = %s ", (id_,))
1126
        if cursor.fetchone() is None:
1127
            cursor.close()
1128
            cnx.disconnect()
1129
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1130
                                   description='API.TENANT_NOT_FOUND')
1131
1132
        cursor.execute(" SELECT name "
1133
                       " FROM tbl_points "
1134
                       " WHERE id = %s ", (point_id,))
1135
        if cursor.fetchone() is None:
1136
            cursor.close()
1137
            cnx.disconnect()
1138
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1139
                                   description='API.POINT_NOT_FOUND')
1140
1141
        query = (" SELECT id " 
1142
                 " FROM tbl_tenants_points "
1143
                 " WHERE tenant_id = %s AND point_id = %s")
1144
        cursor.execute(query, (id_, point_id,))
1145
        if cursor.fetchone() is not None:
1146
            cursor.close()
1147
            cnx.disconnect()
1148
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1149
                                   description='API.TENANT_POINT_RELATION_EXISTED')
1150
1151
        add_row = (" INSERT INTO tbl_tenants_points (tenant_id, point_id) "
1152
                   " VALUES (%s, %s) ")
1153
        cursor.execute(add_row, (id_, point_id,))
1154
        new_id = cursor.lastrowid
1155
        cnx.commit()
1156
        cursor.close()
1157
        cnx.disconnect()
1158
1159
        resp.status = falcon.HTTP_201
1160
        resp.location = '/tenants/' + str(id_) + '/points/' + str(point_id)
1161
1162
1163
class TenantPointItem:

shopfloor.py 4 locations

@@ 1378-1495 (lines=118) @@
1375
        resp.status = falcon.HTTP_204
1376
1377
1378
class ShopfloorVirtualMeterCollection:
1379
    @staticmethod
1380
    def __init__():
1381
        pass
1382
1383
    @staticmethod
1384
    def on_options(req, resp, id_):
1385
        resp.status = falcon.HTTP_200
1386
1387
    @staticmethod
1388
    def on_get(req, resp, id_):
1389
        if not id_.isdigit() or int(id_) <= 0:
1390
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1391
                                   description='API.INVALID_SHOPFLOOR_ID')
1392
1393
        cnx = mysql.connector.connect(**config.myems_system_db)
1394
        cursor = cnx.cursor(dictionary=True)
1395
1396
        cursor.execute(" SELECT name "
1397
                       " FROM tbl_shopfloors "
1398
                       " WHERE id = %s ", (id_,))
1399
        if cursor.fetchone() is None:
1400
            cursor.close()
1401
            cnx.disconnect()
1402
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1403
                                   description='API.SHOPFLOOR_NOT_FOUND')
1404
1405
        query = (" SELECT id, name, uuid "
1406
                 " FROM tbl_energy_categories ")
1407
        cursor.execute(query)
1408
        rows_energy_categories = cursor.fetchall()
1409
1410
        energy_category_dict = dict()
1411
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1412
            for row in rows_energy_categories:
1413
                energy_category_dict[row['id']] = {"id": row['id'],
1414
                                                   "name": row['name'],
1415
                                                   "uuid": row['uuid']}
1416
1417
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1418
                 " FROM tbl_shopfloors s, tbl_shopfloors_virtual_meters sm, tbl_virtual_meters m "
1419
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.virtual_meter_id AND s.id = %s "
1420
                 " ORDER BY m.id ")
1421
        cursor.execute(query, (id_,))
1422
        rows = cursor.fetchall()
1423
1424
        result = list()
1425
        if rows is not None and len(rows) > 0:
1426
            for row in rows:
1427
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1428
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1429
                               "energy_category": energy_category}
1430
                result.append(meta_result)
1431
1432
        resp.body = json.dumps(result)
1433
1434
    @staticmethod
1435
    def on_post(req, resp, id_):
1436
        """Handles POST requests"""
1437
        try:
1438
            raw_json = req.stream.read().decode('utf-8')
1439
        except Exception as ex:
1440
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1441
1442
        if not id_.isdigit() or int(id_) <= 0:
1443
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1444
                                   description='API.INVALID_SHOPFLOOR_ID')
1445
1446
        new_values = json.loads(raw_json, encoding='utf-8')
1447
1448
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1449
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1450
                new_values['data']['virtual_meter_id'] <= 0:
1451
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1452
                                   description='API.INVALID_VIRTUAL_METER_ID')
1453
        virtual_meter_id = new_values['data']['virtual_meter_id']
1454
1455
        cnx = mysql.connector.connect(**config.myems_system_db)
1456
        cursor = cnx.cursor()
1457
1458
        cursor.execute(" SELECT name "
1459
                       " from tbl_shopfloors "
1460
                       " WHERE id = %s ", (id_,))
1461
        if cursor.fetchone() is None:
1462
            cursor.close()
1463
            cnx.disconnect()
1464
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1465
                                   description='API.SHOPFLOOR_NOT_FOUND')
1466
1467
        cursor.execute(" SELECT name "
1468
                       " FROM tbl_virtual_meters "
1469
                       " WHERE id = %s ", (virtual_meter_id,))
1470
        if cursor.fetchone() is None:
1471
            cursor.close()
1472
            cnx.disconnect()
1473
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1474
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1475
1476
        query = (" SELECT id " 
1477
                 " FROM tbl_shopfloors_virtual_meters "
1478
                 " WHERE shopfloor_id = %s AND virtual_meter_id = %s")
1479
        cursor.execute(query, (id_, virtual_meter_id,))
1480
        if cursor.fetchone() is not None:
1481
            cursor.close()
1482
            cnx.disconnect()
1483
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1484
                                   description='API.SHOPFLOOR_VIRTUAL_METER_RELATION_EXISTED')
1485
1486
        add_row = (" INSERT INTO tbl_shopfloors_virtual_meters (shopfloor_id, virtual_meter_id) "
1487
                   " VALUES (%s, %s) ")
1488
        cursor.execute(add_row, (id_, virtual_meter_id,))
1489
        new_id = cursor.lastrowid
1490
        cnx.commit()
1491
        cursor.close()
1492
        cnx.disconnect()
1493
1494
        resp.status = falcon.HTTP_201
1495
        resp.location = '/shopfloors/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1496
1497
1498
class ShopfloorVirtualMeterItem:
@@ 857-974 (lines=118) @@
854
        resp.status = falcon.HTTP_204
855
856
857
class ShopfloorOfflineMeterCollection:
858
    @staticmethod
859
    def __init__():
860
        pass
861
862
    @staticmethod
863
    def on_options(req, resp, id_):
864
        resp.status = falcon.HTTP_200
865
866
    @staticmethod
867
    def on_get(req, resp, id_):
868
        if not id_.isdigit() or int(id_) <= 0:
869
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
870
                                   description='API.INVALID_SHOPFLOOR_ID')
871
872
        cnx = mysql.connector.connect(**config.myems_system_db)
873
        cursor = cnx.cursor(dictionary=True)
874
875
        cursor.execute(" SELECT name "
876
                       " FROM tbl_shopfloors "
877
                       " WHERE id = %s ", (id_,))
878
        if cursor.fetchone() is None:
879
            cursor.close()
880
            cnx.disconnect()
881
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
882
                                   description='API.SHOPFLOOR_NOT_FOUND')
883
884
        query = (" SELECT id, name, uuid "
885
                 " FROM tbl_energy_categories ")
886
        cursor.execute(query)
887
        rows_energy_categories = cursor.fetchall()
888
889
        energy_category_dict = dict()
890
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
891
            for row in rows_energy_categories:
892
                energy_category_dict[row['id']] = {"id": row['id'],
893
                                                   "name": row['name'],
894
                                                   "uuid": row['uuid']}
895
896
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
897
                 " FROM tbl_shopfloors s, tbl_shopfloors_offline_meters sm, tbl_offline_meters m "
898
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
899
                 " ORDER BY m.id ")
900
        cursor.execute(query, (id_,))
901
        rows = cursor.fetchall()
902
903
        result = list()
904
        if rows is not None and len(rows) > 0:
905
            for row in rows:
906
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
907
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
908
                               "energy_category": energy_category}
909
                result.append(meta_result)
910
911
        resp.body = json.dumps(result)
912
913
    @staticmethod
914
    def on_post(req, resp, id_):
915
        """Handles POST requests"""
916
        try:
917
            raw_json = req.stream.read().decode('utf-8')
918
        except Exception as ex:
919
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
920
921
        if not id_.isdigit() or int(id_) <= 0:
922
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
923
                                   description='API.INVALID_SHOPFLOOR_ID')
924
925
        new_values = json.loads(raw_json, encoding='utf-8')
926
927
        if 'offline_meter_id' not in new_values['data'].keys() or \
928
                not isinstance(new_values['data']['offline_meter_id'], int) or \
929
                new_values['data']['offline_meter_id'] <= 0:
930
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
931
                                   description='API.INVALID_OFFLINE_METER_ID')
932
        offline_meter_id = new_values['data']['offline_meter_id']
933
934
        cnx = mysql.connector.connect(**config.myems_system_db)
935
        cursor = cnx.cursor()
936
937
        cursor.execute(" SELECT name "
938
                       " from tbl_shopfloors "
939
                       " WHERE id = %s ", (id_,))
940
        if cursor.fetchone() is None:
941
            cursor.close()
942
            cnx.disconnect()
943
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
944
                                   description='API.SHOPFLOOR_NOT_FOUND')
945
946
        cursor.execute(" SELECT name "
947
                       " FROM tbl_offline_meters "
948
                       " WHERE id = %s ", (offline_meter_id,))
949
        if cursor.fetchone() is None:
950
            cursor.close()
951
            cnx.disconnect()
952
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
953
                                   description='API.OFFLINE_METER_NOT_FOUND')
954
955
        query = (" SELECT id " 
956
                 " FROM tbl_shopfloors_offline_meters "
957
                 " WHERE shopfloor_id = %s AND offline_meter_id = %s")
958
        cursor.execute(query, (id_, offline_meter_id,))
959
        if cursor.fetchone() is not None:
960
            cursor.close()
961
            cnx.disconnect()
962
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
963
                                   description='API.SHOPFLOOR_OFFLINE_METER_RELATION_EXISTED')
964
965
        add_row = (" INSERT INTO tbl_shopfloors_offline_meters (shopfloor_id, offline_meter_id) "
966
                   " VALUES (%s, %s) ")
967
        cursor.execute(add_row, (id_, offline_meter_id,))
968
        new_id = cursor.lastrowid
969
        cnx.commit()
970
        cursor.close()
971
        cnx.disconnect()
972
973
        resp.status = falcon.HTTP_201
974
        resp.location = '/shopfloors/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
975
976
977
class ShopfloorOfflineMeterItem:
@@ 679-796 (lines=118) @@
676
        resp.status = falcon.HTTP_204
677
678
679
class ShopfloorMeterCollection:
680
    @staticmethod
681
    def __init__():
682
        pass
683
684
    @staticmethod
685
    def on_options(req, resp, id_):
686
        resp.status = falcon.HTTP_200
687
688
    @staticmethod
689
    def on_get(req, resp, id_):
690
        if not id_.isdigit() or int(id_) <= 0:
691
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
692
                                   description='API.INVALID_SHOPFLOOR_ID')
693
694
        cnx = mysql.connector.connect(**config.myems_system_db)
695
        cursor = cnx.cursor(dictionary=True)
696
697
        cursor.execute(" SELECT name "
698
                       " FROM tbl_shopfloors "
699
                       " WHERE id = %s ", (id_,))
700
        if cursor.fetchone() is None:
701
            cursor.close()
702
            cnx.disconnect()
703
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
704
                                   description='API.SHOPFLOOR_NOT_FOUND')
705
706
        query = (" SELECT id, name, uuid "
707
                 " FROM tbl_energy_categories ")
708
        cursor.execute(query)
709
        rows_energy_categories = cursor.fetchall()
710
711
        energy_category_dict = dict()
712
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
713
            for row in rows_energy_categories:
714
                energy_category_dict[row['id']] = {"id": row['id'],
715
                                                   "name": row['name'],
716
                                                   "uuid": row['uuid']}
717
718
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
719
                 " FROM tbl_shopfloors s, tbl_shopfloors_meters sm, tbl_meters m "
720
                 " WHERE sm.shopfloor_id = s.id AND m.id = sm.meter_id AND s.id = %s "
721
                 " ORDER BY m.id ")
722
        cursor.execute(query, (id_,))
723
        rows = cursor.fetchall()
724
725
        result = list()
726
        if rows is not None and len(rows) > 0:
727
            for row in rows:
728
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
729
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
730
                               "energy_category": energy_category}
731
                result.append(meta_result)
732
733
        resp.body = json.dumps(result)
734
735
    @staticmethod
736
    def on_post(req, resp, id_):
737
        """Handles POST requests"""
738
        try:
739
            raw_json = req.stream.read().decode('utf-8')
740
        except Exception as ex:
741
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
742
743
        if not id_.isdigit() or int(id_) <= 0:
744
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
745
                                   description='API.INVALID_SHOPFLOOR_ID')
746
747
        new_values = json.loads(raw_json, encoding='utf-8')
748
749
        if 'meter_id' not in new_values['data'].keys() or \
750
                not isinstance(new_values['data']['meter_id'], int) or \
751
                new_values['data']['meter_id'] <= 0:
752
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
753
                                   description='API.INVALID_METER_ID')
754
        meter_id = new_values['data']['meter_id']
755
756
        cnx = mysql.connector.connect(**config.myems_system_db)
757
        cursor = cnx.cursor()
758
759
        cursor.execute(" SELECT name "
760
                       " from tbl_shopfloors "
761
                       " WHERE id = %s ", (id_,))
762
        if cursor.fetchone() is None:
763
            cursor.close()
764
            cnx.disconnect()
765
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
766
                                   description='API.SHOPFLOOR_NOT_FOUND')
767
768
        cursor.execute(" SELECT name "
769
                       " FROM tbl_meters "
770
                       " WHERE id = %s ", (meter_id,))
771
        if cursor.fetchone() is None:
772
            cursor.close()
773
            cnx.disconnect()
774
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
775
                                   description='API.METER_NOT_FOUND')
776
777
        query = (" SELECT id " 
778
                 " FROM tbl_shopfloors_meters "
779
                 " WHERE shopfloor_id = %s AND meter_id = %s")
780
        cursor.execute(query, (id_, meter_id,))
781
        if cursor.fetchone() is not None:
782
            cursor.close()
783
            cnx.disconnect()
784
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
785
                                   description='API.SHOPFLOOR_METER_RELATION_EXISTED')
786
787
        add_row = (" INSERT INTO tbl_shopfloors_meters (shopfloor_id, meter_id) "
788
                   " VALUES (%s, %s) ")
789
        cursor.execute(add_row, (id_, meter_id,))
790
        new_id = cursor.lastrowid
791
        cnx.commit()
792
        cursor.close()
793
        cnx.disconnect()
794
795
        resp.status = falcon.HTTP_201
796
        resp.location = '/shopfloors/' + str(id_) + '/meters/' + str(meter_id)
797
798
799
class ShopfloorMeterItem:
@@ 1036-1152 (lines=117) @@
1033
        resp.status = falcon.HTTP_204
1034
1035
1036
class ShopfloorPointCollection:
1037
    @staticmethod
1038
    def __init__():
1039
        pass
1040
1041
    @staticmethod
1042
    def on_options(req, resp, id_):
1043
        resp.status = falcon.HTTP_200
1044
1045
    @staticmethod
1046
    def on_get(req, resp, id_):
1047
        if not id_.isdigit() or int(id_) <= 0:
1048
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1049
                                   description='API.INVALID_SHOPFLOOR_ID')
1050
1051
        cnx = mysql.connector.connect(**config.myems_system_db)
1052
        cursor = cnx.cursor(dictionary=True)
1053
1054
        cursor.execute(" SELECT name "
1055
                       " FROM tbl_shopfloors "
1056
                       " WHERE id = %s ", (id_,))
1057
        if cursor.fetchone() is None:
1058
            cursor.close()
1059
            cnx.disconnect()
1060
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1061
                                   description='API.SHOPFLOOR_NOT_FOUND')
1062
1063
        query = (" SELECT id, name, uuid "
1064
                 " FROM tbl_data_sources ")
1065
        cursor.execute(query)
1066
        rows_data_sources = cursor.fetchall()
1067
1068
        data_source_dict = dict()
1069
        if rows_data_sources is not None and len(rows_data_sources) > 0:
1070
            for row in rows_data_sources:
1071
                data_source_dict[row['id']] = {"id": row['id'],
1072
                                               "name": row['name'],
1073
                                               "uuid": row['uuid']}
1074
1075
        query = (" SELECT p.id, p.name, p.data_source_id "
1076
                 " FROM tbl_shopfloors s, tbl_shopfloors_points sp, tbl_points p "
1077
                 " WHERE sp.shopfloor_id = s.id AND p.id = sp.point_id AND s.id = %s "
1078
                 " ORDER BY p.id ")
1079
        cursor.execute(query, (id_,))
1080
        rows = cursor.fetchall()
1081
1082
        result = list()
1083
        if rows is not None and len(rows) > 0:
1084
            for row in rows:
1085
                data_source = data_source_dict.get(row['data_source_id'], None)
1086
                meta_result = {"id": row['id'], "name": row['name'], "data_source": data_source}
1087
                result.append(meta_result)
1088
1089
        resp.body = json.dumps(result)
1090
1091
    @staticmethod
1092
    def on_post(req, resp, id_):
1093
        """Handles POST requests"""
1094
        try:
1095
            raw_json = req.stream.read().decode('utf-8')
1096
        except Exception as ex:
1097
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1098
1099
        if not id_.isdigit() or int(id_) <= 0:
1100
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1101
                                   description='API.INVALID_SHOPFLOOR_ID')
1102
1103
        new_values = json.loads(raw_json, encoding='utf-8')
1104
1105
        if 'point_id' not in new_values['data'].keys() or \
1106
                not isinstance(new_values['data']['point_id'], int) or \
1107
                new_values['data']['point_id'] <= 0:
1108
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1109
                                   description='API.INVALID_POINT_ID')
1110
        point_id = new_values['data']['point_id']
1111
1112
        cnx = mysql.connector.connect(**config.myems_system_db)
1113
        cursor = cnx.cursor()
1114
1115
        cursor.execute(" SELECT name "
1116
                       " from tbl_shopfloors "
1117
                       " WHERE id = %s ", (id_,))
1118
        if cursor.fetchone() is None:
1119
            cursor.close()
1120
            cnx.disconnect()
1121
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1122
                                   description='API.SHOPFLOOR_NOT_FOUND')
1123
1124
        cursor.execute(" SELECT name "
1125
                       " FROM tbl_points "
1126
                       " WHERE id = %s ", (point_id,))
1127
        if cursor.fetchone() is None:
1128
            cursor.close()
1129
            cnx.disconnect()
1130
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1131
                                   description='API.POINT_NOT_FOUND')
1132
1133
        query = (" SELECT id " 
1134
                 " FROM tbl_shopfloors_points "
1135
                 " WHERE shopfloor_id = %s AND point_id = %s")
1136
        cursor.execute(query, (id_, point_id,))
1137
        if cursor.fetchone() is not None:
1138
            cursor.close()
1139
            cnx.disconnect()
1140
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1141
                                   description='API.SHOPFLOOR_POINT_RELATION_EXISTED')
1142
1143
        add_row = (" INSERT INTO tbl_shopfloors_points (shopfloor_id, point_id) "
1144
                   " VALUES (%s, %s) ")
1145
        cursor.execute(add_row, (id_, point_id,))
1146
        new_id = cursor.lastrowid
1147
        cnx.commit()
1148
        cursor.close()
1149
        cnx.disconnect()
1150
1151
        resp.status = falcon.HTTP_201
1152
        resp.location = '/shopfloors/' + str(id_) + '/points/' + str(point_id)
1153
1154
1155
class ShopfloorPointItem:

store.py 4 locations

@@ 1289-1406 (lines=118) @@
1286
        resp.status = falcon.HTTP_204
1287
1288
1289
class StoreVirtualMeterCollection:
1290
    @staticmethod
1291
    def __init__():
1292
        pass
1293
1294
    @staticmethod
1295
    def on_options(req, resp, id_):
1296
        resp.status = falcon.HTTP_200
1297
1298
    @staticmethod
1299
    def on_get(req, resp, id_):
1300
        if not id_.isdigit() or int(id_) <= 0:
1301
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1302
                                   description='API.INVALID_STORE_ID')
1303
1304
        cnx = mysql.connector.connect(**config.myems_system_db)
1305
        cursor = cnx.cursor(dictionary=True)
1306
1307
        cursor.execute(" SELECT name "
1308
                       " FROM tbl_stores "
1309
                       " WHERE id = %s ", (id_,))
1310
        if cursor.fetchone() is None:
1311
            cursor.close()
1312
            cnx.disconnect()
1313
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1314
                                   description='API.STORE_NOT_FOUND')
1315
1316
        query = (" SELECT id, name, uuid "
1317
                 " FROM tbl_energy_categories ")
1318
        cursor.execute(query)
1319
        rows_energy_categories = cursor.fetchall()
1320
1321
        energy_category_dict = dict()
1322
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
1323
            for row in rows_energy_categories:
1324
                energy_category_dict[row['id']] = {"id": row['id'],
1325
                                                   "name": row['name'],
1326
                                                   "uuid": row['uuid']}
1327
1328
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
1329
                 " FROM tbl_stores t, tbl_stores_virtual_meters tm, tbl_virtual_meters m "
1330
                 " WHERE tm.store_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s "
1331
                 " ORDER BY m.id ")
1332
        cursor.execute(query, (id_,))
1333
        rows = cursor.fetchall()
1334
1335
        result = list()
1336
        if rows is not None and len(rows) > 0:
1337
            for row in rows:
1338
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
1339
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
1340
                               "energy_category": energy_category}
1341
                result.append(meta_result)
1342
1343
        resp.body = json.dumps(result)
1344
1345
    @staticmethod
1346
    def on_post(req, resp, id_):
1347
        """Handles POST requests"""
1348
        try:
1349
            raw_json = req.stream.read().decode('utf-8')
1350
        except Exception as ex:
1351
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1352
1353
        if not id_.isdigit() or int(id_) <= 0:
1354
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1355
                                   description='API.INVALID_STORE_ID')
1356
1357
        new_values = json.loads(raw_json, encoding='utf-8')
1358
1359
        if 'virtual_meter_id' not in new_values['data'].keys() or \
1360
                not isinstance(new_values['data']['virtual_meter_id'], int) or \
1361
                new_values['data']['virtual_meter_id'] <= 0:
1362
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1363
                                   description='API.INVALID_VIRTUAL_METER_ID')
1364
        virtual_meter_id = new_values['data']['virtual_meter_id']
1365
1366
        cnx = mysql.connector.connect(**config.myems_system_db)
1367
        cursor = cnx.cursor()
1368
1369
        cursor.execute(" SELECT name "
1370
                       " from tbl_stores "
1371
                       " WHERE id = %s ", (id_,))
1372
        if cursor.fetchone() is None:
1373
            cursor.close()
1374
            cnx.disconnect()
1375
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1376
                                   description='API.STORE_NOT_FOUND')
1377
1378
        cursor.execute(" SELECT name "
1379
                       " FROM tbl_virtual_meters "
1380
                       " WHERE id = %s ", (virtual_meter_id,))
1381
        if cursor.fetchone() is None:
1382
            cursor.close()
1383
            cnx.disconnect()
1384
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1385
                                   description='API.VIRTUAL_METER_NOT_FOUND')
1386
1387
        query = (" SELECT id " 
1388
                 " FROM tbl_stores_virtual_meters "
1389
                 " WHERE store_id = %s AND virtual_meter_id = %s")
1390
        cursor.execute(query, (id_, virtual_meter_id,))
1391
        if cursor.fetchone() is not None:
1392
            cursor.close()
1393
            cnx.disconnect()
1394
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1395
                                   description='API.STORE_VIRTUAL_METER_RELATION_EXISTED')
1396
1397
        add_row = (" INSERT INTO tbl_stores_virtual_meters (store_id, virtual_meter_id) "
1398
                   " VALUES (%s, %s) ")
1399
        cursor.execute(add_row, (id_, virtual_meter_id,))
1400
        new_id = cursor.lastrowid
1401
        cnx.commit()
1402
        cursor.close()
1403
        cnx.disconnect()
1404
1405
        resp.status = falcon.HTTP_201
1406
        resp.location = '/stores/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id)
1407
1408
1409
class StoreVirtualMeterItem:
@@ 768-885 (lines=118) @@
765
        resp.status = falcon.HTTP_204
766
767
768
class StoreOfflineMeterCollection:
769
    @staticmethod
770
    def __init__():
771
        pass
772
773
    @staticmethod
774
    def on_options(req, resp, id_):
775
        resp.status = falcon.HTTP_200
776
777
    @staticmethod
778
    def on_get(req, resp, id_):
779
        if not id_.isdigit() or int(id_) <= 0:
780
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
781
                                   description='API.INVALID_STORE_ID')
782
783
        cnx = mysql.connector.connect(**config.myems_system_db)
784
        cursor = cnx.cursor(dictionary=True)
785
786
        cursor.execute(" SELECT name "
787
                       " FROM tbl_stores "
788
                       " WHERE id = %s ", (id_,))
789
        if cursor.fetchone() is None:
790
            cursor.close()
791
            cnx.disconnect()
792
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
793
                                   description='API.STORE_NOT_FOUND')
794
795
        query = (" SELECT id, name, uuid "
796
                 " FROM tbl_energy_categories ")
797
        cursor.execute(query)
798
        rows_energy_categories = cursor.fetchall()
799
800
        energy_category_dict = dict()
801
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
802
            for row in rows_energy_categories:
803
                energy_category_dict[row['id']] = {"id": row['id'],
804
                                                   "name": row['name'],
805
                                                   "uuid": row['uuid']}
806
807
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
808
                 " FROM tbl_stores s, tbl_stores_offline_meters sm, tbl_offline_meters m "
809
                 " WHERE sm.store_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s "
810
                 " ORDER BY m.id ")
811
        cursor.execute(query, (id_,))
812
        rows = cursor.fetchall()
813
814
        result = list()
815
        if rows is not None and len(rows) > 0:
816
            for row in rows:
817
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
818
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
819
                               "energy_category": energy_category}
820
                result.append(meta_result)
821
822
        resp.body = json.dumps(result)
823
824
    @staticmethod
825
    def on_post(req, resp, id_):
826
        """Handles POST requests"""
827
        try:
828
            raw_json = req.stream.read().decode('utf-8')
829
        except Exception as ex:
830
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
831
832
        if not id_.isdigit() or int(id_) <= 0:
833
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
834
                                   description='API.INVALID_STORE_ID')
835
836
        new_values = json.loads(raw_json, encoding='utf-8')
837
838
        if 'offline_meter_id' not in new_values['data'].keys() or \
839
                not isinstance(new_values['data']['offline_meter_id'], int) or \
840
                new_values['data']['offline_meter_id'] <= 0:
841
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
842
                                   description='API.INVALID_OFFLINE_METER_ID')
843
        offline_meter_id = new_values['data']['offline_meter_id']
844
845
        cnx = mysql.connector.connect(**config.myems_system_db)
846
        cursor = cnx.cursor()
847
848
        cursor.execute(" SELECT name "
849
                       " from tbl_stores "
850
                       " WHERE id = %s ", (id_,))
851
        if cursor.fetchone() is None:
852
            cursor.close()
853
            cnx.disconnect()
854
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
855
                                   description='API.STORE_NOT_FOUND')
856
857
        cursor.execute(" SELECT name "
858
                       " FROM tbl_offline_meters "
859
                       " WHERE id = %s ", (offline_meter_id,))
860
        if cursor.fetchone() is None:
861
            cursor.close()
862
            cnx.disconnect()
863
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
864
                                   description='API.OFFLINE_METER_NOT_FOUND')
865
866
        query = (" SELECT id " 
867
                 " FROM tbl_stores_offline_meters "
868
                 " WHERE store_id = %s AND offline_meter_id = %s")
869
        cursor.execute(query, (id_, offline_meter_id,))
870
        if cursor.fetchone() is not None:
871
            cursor.close()
872
            cnx.disconnect()
873
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
874
                                   description='API.STORE_OFFLINE_METER_RELATION_EXISTED')
875
876
        add_row = (" INSERT INTO tbl_stores_offline_meters (store_id, offline_meter_id) "
877
                   " VALUES (%s, %s) ")
878
        cursor.execute(add_row, (id_, offline_meter_id,))
879
        new_id = cursor.lastrowid
880
        cnx.commit()
881
        cursor.close()
882
        cnx.disconnect()
883
884
        resp.status = falcon.HTTP_201
885
        resp.location = '/stores/' + str(id_) + '/offlinemeters/' + str(offline_meter_id)
886
887
888
class StoreOfflineMeterItem:
@@ 590-707 (lines=118) @@
587
        resp.status = falcon.HTTP_200
588
589
590
class StoreMeterCollection:
591
    @staticmethod
592
    def __init__():
593
        pass
594
595
    @staticmethod
596
    def on_options(req, resp, id_):
597
        resp.status = falcon.HTTP_200
598
599
    @staticmethod
600
    def on_get(req, resp, id_):
601
        if not id_.isdigit() or int(id_) <= 0:
602
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
603
                                   description='API.INVALID_STORE_ID')
604
605
        cnx = mysql.connector.connect(**config.myems_system_db)
606
        cursor = cnx.cursor(dictionary=True)
607
608
        cursor.execute(" SELECT name "
609
                       " FROM tbl_stores "
610
                       " WHERE id = %s ", (id_,))
611
        if cursor.fetchone() is None:
612
            cursor.close()
613
            cnx.disconnect()
614
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
615
                                   description='API.STORE_NOT_FOUND')
616
617
        query = (" SELECT id, name, uuid "
618
                 " FROM tbl_energy_categories ")
619
        cursor.execute(query)
620
        rows_energy_categories = cursor.fetchall()
621
622
        energy_category_dict = dict()
623
        if rows_energy_categories is not None and len(rows_energy_categories) > 0:
624
            for row in rows_energy_categories:
625
                energy_category_dict[row['id']] = {"id": row['id'],
626
                                                   "name": row['name'],
627
                                                   "uuid": row['uuid']}
628
629
        query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id "
630
                 " FROM tbl_stores t, tbl_stores_meters tm, tbl_meters m "
631
                 " WHERE tm.store_id = t.id AND m.id = tm.meter_id AND t.id = %s "
632
                 " ORDER BY m.id ")
633
        cursor.execute(query, (id_,))
634
        rows = cursor.fetchall()
635
636
        result = list()
637
        if rows is not None and len(rows) > 0:
638
            for row in rows:
639
                energy_category = energy_category_dict.get(row['energy_category_id'], None)
640
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
641
                               "energy_category": energy_category}
642
                result.append(meta_result)
643
644
        resp.body = json.dumps(result)
645
646
    @staticmethod
647
    def on_post(req, resp, id_):
648
        """Handles POST requests"""
649
        try:
650
            raw_json = req.stream.read().decode('utf-8')
651
        except Exception as ex:
652
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
653
654
        if not id_.isdigit() or int(id_) <= 0:
655
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
656
                                   description='API.INVALID_STORE_ID')
657
658
        new_values = json.loads(raw_json, encoding='utf-8')
659
660
        if 'meter_id' not in new_values['data'].keys() or \
661
                not isinstance(new_values['data']['meter_id'], int) or \
662
                new_values['data']['meter_id'] <= 0:
663
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
664
                                   description='API.INVALID_METER_ID')
665
        meter_id = new_values['data']['meter_id']
666
667
        cnx = mysql.connector.connect(**config.myems_system_db)
668
        cursor = cnx.cursor()
669
670
        cursor.execute(" SELECT name "
671
                       " from tbl_stores "
672
                       " WHERE id = %s ", (id_,))
673
        if cursor.fetchone() is None:
674
            cursor.close()
675
            cnx.disconnect()
676
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
677
                                   description='API.STORE_NOT_FOUND')
678
679
        cursor.execute(" SELECT name "
680
                       " FROM tbl_meters "
681
                       " WHERE id = %s ", (meter_id,))
682
        if cursor.fetchone() is None:
683
            cursor.close()
684
            cnx.disconnect()
685
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
686
                                   description='API.METER_NOT_FOUND')
687
688
        query = (" SELECT id " 
689
                 " FROM tbl_stores_meters "
690
                 " WHERE store_id = %s AND meter_id = %s")
691
        cursor.execute(query, (id_, meter_id,))
692
        if cursor.fetchone() is not None:
693
            cursor.close()
694
            cnx.disconnect()
695
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
696
                                   description='API.STORE_METER_RELATION_EXISTED')
697
698
        add_row = (" INSERT INTO tbl_stores_meters (store_id, meter_id) "
699
                   " VALUES (%s, %s) ")
700
        cursor.execute(add_row, (id_, meter_id,))
701
        new_id = cursor.lastrowid
702
        cnx.commit()
703
        cursor.close()
704
        cnx.disconnect()
705
706
        resp.status = falcon.HTTP_201
707
        resp.location = '/stores/' + str(id_) + '/meters/' + str(meter_id)
708
709
710
class StoreMeterItem:
@@ 947-1063 (lines=117) @@
944
        resp.status = falcon.HTTP_204
945
946
947
class StorePointCollection:
948
    @staticmethod
949
    def __init__():
950
        pass
951
952
    @staticmethod
953
    def on_options(req, resp, id_):
954
        resp.status = falcon.HTTP_200
955
956
    @staticmethod
957
    def on_get(req, resp, id_):
958
        if not id_.isdigit() or int(id_) <= 0:
959
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
960
                                   description='API.INVALID_STORE_ID')
961
962
        cnx = mysql.connector.connect(**config.myems_system_db)
963
        cursor = cnx.cursor(dictionary=True)
964
965
        cursor.execute(" SELECT name "
966
                       " FROM tbl_stores "
967
                       " WHERE id = %s ", (id_,))
968
        if cursor.fetchone() is None:
969
            cursor.close()
970
            cnx.disconnect()
971
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
972
                                   description='API.STORE_NOT_FOUND')
973
974
        query = (" SELECT id, name, uuid "
975
                 " FROM tbl_data_sources ")
976
        cursor.execute(query)
977
        rows_data_sources = cursor.fetchall()
978
979
        data_source_dict = dict()
980
        if rows_data_sources is not None and len(rows_data_sources) > 0:
981
            for row in rows_data_sources:
982
                data_source_dict[row['id']] = {"id": row['id'],
983
                                               "name": row['name'],
984
                                               "uuid": row['uuid']}
985
986
        query = (" SELECT p.id, p.name, p.data_source_id "
987
                 " FROM tbl_stores t, tbl_stores_points tp, tbl_points p "
988
                 " WHERE tp.store_id = t.id AND p.id = tp.point_id AND t.id = %s "
989
                 " ORDER BY p.id ")
990
        cursor.execute(query, (id_,))
991
        rows = cursor.fetchall()
992
993
        result = list()
994
        if rows is not None and len(rows) > 0:
995
            for row in rows:
996
                data_source = data_source_dict.get(row['data_source_id'], None)
997
                meta_result = {"id": row['id'], "name": row['name'], "data_source": data_source}
998
                result.append(meta_result)
999
1000
        resp.body = json.dumps(result)
1001
1002
    @staticmethod
1003
    def on_post(req, resp, id_):
1004
        """Handles POST requests"""
1005
        try:
1006
            raw_json = req.stream.read().decode('utf-8')
1007
        except Exception as ex:
1008
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
1009
1010
        if not id_.isdigit() or int(id_) <= 0:
1011
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1012
                                   description='API.INVALID_STORE_ID')
1013
1014
        new_values = json.loads(raw_json, encoding='utf-8')
1015
1016
        if 'point_id' not in new_values['data'].keys() or \
1017
                not isinstance(new_values['data']['point_id'], int) or \
1018
                new_values['data']['point_id'] <= 0:
1019
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
1020
                                   description='API.INVALID_POINT_ID')
1021
        point_id = new_values['data']['point_id']
1022
1023
        cnx = mysql.connector.connect(**config.myems_system_db)
1024
        cursor = cnx.cursor()
1025
1026
        cursor.execute(" SELECT name "
1027
                       " from tbl_stores "
1028
                       " WHERE id = %s ", (id_,))
1029
        if cursor.fetchone() is None:
1030
            cursor.close()
1031
            cnx.disconnect()
1032
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1033
                                   description='API.STORE_NOT_FOUND')
1034
1035
        cursor.execute(" SELECT name "
1036
                       " FROM tbl_points "
1037
                       " WHERE id = %s ", (point_id,))
1038
        if cursor.fetchone() is None:
1039
            cursor.close()
1040
            cnx.disconnect()
1041
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
1042
                                   description='API.POINT_NOT_FOUND')
1043
1044
        query = (" SELECT id " 
1045
                 " FROM tbl_stores_points "
1046
                 " WHERE store_id = %s AND point_id = %s")
1047
        cursor.execute(query, (id_, point_id,))
1048
        if cursor.fetchone() is not None:
1049
            cursor.close()
1050
            cnx.disconnect()
1051
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
1052
                                   description='API.STORE_POINT_RELATION_EXISTED')
1053
1054
        add_row = (" INSERT INTO tbl_stores_points (store_id, point_id) "
1055
                   " VALUES (%s, %s) ")
1056
        cursor.execute(add_row, (id_, point_id,))
1057
        new_id = cursor.lastrowid
1058
        cnx.commit()
1059
        cursor.close()
1060
        cnx.disconnect()
1061
1062
        resp.status = falcon.HTTP_201
1063
        resp.location = '/stores/' + str(id_) + '/points/' + str(point_id)
1064
1065
1066
class StorePointItem: