Code Duplication    Length = 190-190 lines in 2 locations

myems-api/core/energystoragecontainer.py 1 location

@@ 5179-5368 (lines=190) @@
5176
        resp.location = '/energystoragecontainerschedules/' + str(new_id)
5177
5178
5179
class EnergyStorageContainerScheduleItem:
5180
    def __init__(self):
5181
        pass
5182
5183
    @staticmethod
5184
    def on_options(req, resp, id_, sid):
5185
        _ = req
5186
        resp.status = falcon.HTTP_200
5187
        _ = id_
5188
5189
    @staticmethod
5190
    def on_get(req, resp, id_, sid):
5191
        access_control(req)
5192
        if not id_.isdigit() or int(id_) <= 0:
5193
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5194
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5195
        if not sid.isdigit() or int(sid) <= 0:
5196
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5197
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_SCHEDULE_ID')
5198
5199
        cnx = mysql.connector.connect(**config.myems_system_db)
5200
        cursor = cnx.cursor()
5201
5202
        cursor.execute(" SELECT name "
5203
                       " FROM tbl_energy_storage_containers "
5204
                       " WHERE id = %s ", (id_,))
5205
        if cursor.fetchone() is None:
5206
            cursor.close()
5207
            cnx.close()
5208
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5209
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
5210
5211
        query = (" SELECT id, name, uuid "
5212
                 " FROM tbl_energy_storage_containers ")
5213
        cursor.execute(query)
5214
        rows_energystoragecontainers = cursor.fetchall()
5215
5216
        energy_storage_container_dict = dict()
5217
        if rows_energystoragecontainers is not None and len(rows_energystoragecontainers) > 0:
5218
            for row in rows_energystoragecontainers:
5219
                energy_storage_container_dict[row[0]] = {"id": row[0],
5220
                                                         "name": row[1],
5221
                                                         "uuid": row[2]}
5222
5223
        query = (" SELECT id, start_time_of_day, end_time_of_day, peak_type, power "
5224
                 " FROM tbl_energy_storage_containers_schedules "
5225
                 " WHERE id = %s ")
5226
        cursor.execute(query, (sid,))
5227
        row = cursor.fetchone()
5228
        cursor.close()
5229
        cnx.close()
5230
5231
        if row is None:
5232
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5233
                                   description='API.ENERGY_STORAGE_CONTAINER_SCHEDULE_NOT_FOUND')
5234
        else:
5235
            meta_result = {"id": row[0],
5236
                           "start_time_of_day": str(row[1]),
5237
                           "end_time_of_day": str(row[2]),
5238
                           "peak_type": row[3],
5239
                           "power": row[4]}
5240
5241
        resp.text = json.dumps(meta_result)
5242
5243
    @staticmethod
5244
    @user_logger
5245
    def on_delete(req, resp, id_, sid):
5246
        admin_control(req)
5247
        if not id_.isdigit() or int(id_) <= 0:
5248
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5249
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5250
        if not sid.isdigit() or int(sid) <= 0:
5251
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5252
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_SCHEDULE_ID')
5253
5254
        cnx = mysql.connector.connect(**config.myems_system_db)
5255
        cursor = cnx.cursor()
5256
5257
        cursor.execute(" SELECT name "
5258
                       " FROM tbl_energy_storage_containers "
5259
                       " WHERE id = %s ", (id_,))
5260
        if cursor.fetchone() is None:
5261
            cursor.close()
5262
            cnx.close()
5263
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5264
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
5265
5266
        cursor.execute(" SELECT id "
5267
                       " FROM tbl_energy_storage_containers_schedules "
5268
                       " WHERE id = %s ", (sid,))
5269
        if cursor.fetchone() is None:
5270
            cursor.close()
5271
            cnx.close()
5272
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5273
                                   description='API.ENERGY_STORAGE_CONTAINER_SCHEDULE_NOT_FOUND')
5274
5275
        cursor.execute(" DELETE FROM tbl_energy_storage_containers_schedules "
5276
                       " WHERE id = %s ", (sid,))
5277
        cnx.commit()
5278
5279
        cursor.close()
5280
        cnx.close()
5281
5282
        resp.status = falcon.HTTP_204
5283
5284
    @staticmethod
5285
    @user_logger
5286
    def on_put(req, resp, id_, sid):
5287
        """Handles PUT requests"""
5288
        admin_control(req)
5289
        try:
5290
            raw_json = req.stream.read().decode('utf-8')
5291
        except Exception as ex:
5292
            print(str(ex))
5293
            raise falcon.HTTPError(status=falcon.HTTP_400,
5294
                                   title='API.BAD_REQUEST',
5295
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5296
        if not id_.isdigit() or int(id_) <= 0:
5297
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5298
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5299
        if not sid.isdigit() or int(sid) <= 0:
5300
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5301
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_SCHEDULE_ID')
5302
5303
        new_values = json.loads(raw_json)
5304
5305
        if 'start_time_of_day' not in new_values['data'].keys() or \
5306
                not isinstance(new_values['data']['start_time_of_day'], str) or \
5307
                len(str.strip(new_values['data']['start_time_of_day'])) == 0:
5308
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5309
                                   description='API.INVALID_START_TIME_OF_DAY')
5310
        start_time_of_day = str.strip(new_values['data']['start_time_of_day'])
5311
5312
        if 'end_time_of_day' not in new_values['data'].keys() or \
5313
                not isinstance(new_values['data']['end_time_of_day'], str) or \
5314
                len(str.strip(new_values['data']['end_time_of_day'])) == 0:
5315
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5316
                                   description='API.INVALID_END_TIME_OF_DAY')
5317
        end_time_of_day = str.strip(new_values['data']['end_time_of_day'])
5318
5319
        if 'peak_type' not in new_values['data'].keys() or \
5320
                not isinstance(new_values['data']['peak_type'], str) or \
5321
                len(str.strip(new_values['data']['peak_type'])) == 0:
5322
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5323
                                   description='API.INVALID_PEAK_TYPE')
5324
        peak_type = str.strip(new_values['data']['peak_type'])
5325
5326
        if 'power' not in new_values['data'].keys() or \
5327
                not (isinstance(new_values['data']['power'], float) or
5328
                     isinstance(new_values['data']['power'], int)):
5329
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5330
                                   description='API.INVALID_POWER')
5331
        power = Decimal(new_values['data']['power'])
5332
5333
        cnx = mysql.connector.connect(**config.myems_system_db)
5334
        cursor = cnx.cursor()
5335
5336
        cursor.execute(" SELECT name "
5337
                       " FROM tbl_energy_storage_containers "
5338
                       " WHERE id = %s ", (id_,))
5339
        if cursor.fetchone() is None:
5340
            cursor.close()
5341
            cnx.close()
5342
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5343
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
5344
5345
        cursor.execute(" SELECT id "
5346
                       " FROM tbl_energy_storage_containers_schedules "
5347
                       " WHERE id = %s ", (sid,))
5348
        if cursor.fetchone() is None:
5349
            cursor.close()
5350
            cnx.close()
5351
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5352
                                   description='API.ENERGY_STORAGE_CONTAINER_SCHEDULE_NOT_FOUND')
5353
5354
        update_row = (" UPDATE tbl_energy_storage_containers_schedules "
5355
                      " SET start_time_of_day = %s, end_time_of_day = %s, peak_type = %s, power = %s "
5356
                      " WHERE id = %s ")
5357
        cursor.execute(update_row, (start_time_of_day,
5358
                                    end_time_of_day,
5359
                                    peak_type,
5360
                                    power,
5361
                                    sid))
5362
        cnx.commit()
5363
5364
        cursor.close()
5365
        cnx.close()
5366
5367
        resp.status = falcon.HTTP_200
5368
5369
5370
class EnergyStorageContainerSTSCollection:
5371
    def __init__(self):

myems-api/core/microgrid.py 1 location

@@ 4691-4880 (lines=190) @@
4688
        resp.location = '/energystoragecontainerschedules/' + str(new_id)
4689
4690
4691
class MicrogridScheduleItem:
4692
    def __init__(self):
4693
        pass
4694
4695
    @staticmethod
4696
    def on_options(req, resp, id_, sid):
4697
        _ = req
4698
        resp.status = falcon.HTTP_200
4699
        _ = id_
4700
4701
    @staticmethod
4702
    def on_get(req, resp, id_, sid):
4703
        access_control(req)
4704
        if not id_.isdigit() or int(id_) <= 0:
4705
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4706
                                   description='API.INVALID_MICROGRID_ID')
4707
        if not sid.isdigit() or int(sid) <= 0:
4708
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4709
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4710
4711
        cnx = mysql.connector.connect(**config.myems_system_db)
4712
        cursor = cnx.cursor()
4713
4714
        cursor.execute(" SELECT name "
4715
                       " FROM tbl_microgrids "
4716
                       " WHERE id = %s ", (id_,))
4717
        if cursor.fetchone() is None:
4718
            cursor.close()
4719
            cnx.close()
4720
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4721
                                   description='API.MICROGRID_NOT_FOUND')
4722
4723
        query = (" SELECT id, name, uuid "
4724
                 " FROM tbl_microgrids ")
4725
        cursor.execute(query)
4726
        rows_energystoragecontainers = cursor.fetchall()
4727
4728
        microgrid_dict = dict()
4729
        if rows_energystoragecontainers is not None and len(rows_energystoragecontainers) > 0:
4730
            for row in rows_energystoragecontainers:
4731
                microgrid_dict[row[0]] = {"id": row[0],
4732
                                          "name": row[1],
4733
                                          "uuid": row[2]}
4734
4735
        query = (" SELECT id, start_time_of_day, end_time_of_day, peak_type, power "
4736
                 " FROM tbl_microgrids_schedules "
4737
                 " WHERE id = %s ")
4738
        cursor.execute(query, (sid,))
4739
        row = cursor.fetchone()
4740
        cursor.close()
4741
        cnx.close()
4742
4743
        if row is None:
4744
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4745
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4746
        else:
4747
            meta_result = {"id": row[0],
4748
                           "start_time_of_day": str(row[1]),
4749
                           "end_time_of_day": str(row[2]),
4750
                           "peak_type": row[3],
4751
                           "power": row[4]}
4752
4753
        resp.text = json.dumps(meta_result)
4754
4755
    @staticmethod
4756
    @user_logger
4757
    def on_delete(req, resp, id_, sid):
4758
        admin_control(req)
4759
        if not id_.isdigit() or int(id_) <= 0:
4760
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4761
                                   description='API.INVALID_MICROGRID_ID')
4762
        if not sid.isdigit() or int(sid) <= 0:
4763
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4764
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4765
4766
        cnx = mysql.connector.connect(**config.myems_system_db)
4767
        cursor = cnx.cursor()
4768
4769
        cursor.execute(" SELECT name "
4770
                       " FROM tbl_microgrids "
4771
                       " WHERE id = %s ", (id_,))
4772
        if cursor.fetchone() is None:
4773
            cursor.close()
4774
            cnx.close()
4775
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4776
                                   description='API.MICROGRID_NOT_FOUND')
4777
4778
        cursor.execute(" SELECT id "
4779
                       " FROM tbl_microgrids_schedules "
4780
                       " WHERE id = %s ", (sid,))
4781
        if cursor.fetchone() is None:
4782
            cursor.close()
4783
            cnx.close()
4784
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4785
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4786
4787
        cursor.execute(" DELETE FROM tbl_microgrids_schedules "
4788
                       " WHERE id = %s ", (sid,))
4789
        cnx.commit()
4790
4791
        cursor.close()
4792
        cnx.close()
4793
4794
        resp.status = falcon.HTTP_204
4795
4796
    @staticmethod
4797
    @user_logger
4798
    def on_put(req, resp, id_, sid):
4799
        """Handles PUT requests"""
4800
        admin_control(req)
4801
        try:
4802
            raw_json = req.stream.read().decode('utf-8')
4803
        except Exception as ex:
4804
            print(str(ex))
4805
            raise falcon.HTTPError(status=falcon.HTTP_400,
4806
                                   title='API.BAD_REQUEST',
4807
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4808
        if not id_.isdigit() or int(id_) <= 0:
4809
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4810
                                   description='API.INVALID_MICROGRID_ID')
4811
        if not sid.isdigit() or int(sid) <= 0:
4812
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4813
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4814
4815
        new_values = json.loads(raw_json)
4816
4817
        if 'start_time_of_day' not in new_values['data'].keys() or \
4818
                not isinstance(new_values['data']['start_time_of_day'], str) or \
4819
                len(str.strip(new_values['data']['start_time_of_day'])) == 0:
4820
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4821
                                   description='API.INVALID_START_TIME_OF_DAY')
4822
        start_time_of_day = str.strip(new_values['data']['start_time_of_day'])
4823
4824
        if 'end_time_of_day' not in new_values['data'].keys() or \
4825
                not isinstance(new_values['data']['end_time_of_day'], str) or \
4826
                len(str.strip(new_values['data']['end_time_of_day'])) == 0:
4827
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4828
                                   description='API.INVALID_END_TIME_OF_DAY')
4829
        end_time_of_day = str.strip(new_values['data']['end_time_of_day'])
4830
4831
        if 'peak_type' not in new_values['data'].keys() or \
4832
                not isinstance(new_values['data']['peak_type'], str) or \
4833
                len(str.strip(new_values['data']['peak_type'])) == 0:
4834
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4835
                                   description='API.INVALID_PEAK_TYPE')
4836
        peak_type = str.strip(new_values['data']['peak_type'])
4837
4838
        if 'power' not in new_values['data'].keys() or \
4839
                not (isinstance(new_values['data']['power'], float) or
4840
                     isinstance(new_values['data']['power'], int)):
4841
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4842
                                   description='API.INVALID_POWER')
4843
        power = float(new_values['data']['power'])
4844
4845
        cnx = mysql.connector.connect(**config.myems_system_db)
4846
        cursor = cnx.cursor()
4847
4848
        cursor.execute(" SELECT name "
4849
                       " FROM tbl_microgrids "
4850
                       " WHERE id = %s ", (id_,))
4851
        if cursor.fetchone() is None:
4852
            cursor.close()
4853
            cnx.close()
4854
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4855
                                   description='API.MICROGRID_NOT_FOUND')
4856
4857
        cursor.execute(" SELECT id "
4858
                       " FROM tbl_microgrids_schedules "
4859
                       " WHERE id = %s ", (sid,))
4860
        if cursor.fetchone() is None:
4861
            cursor.close()
4862
            cnx.close()
4863
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4864
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4865
4866
        update_row = (" UPDATE tbl_microgrids_schedules "
4867
                      " SET start_time_of_day = %s, end_time_of_day = %s, peak_type = %s, power = %s "
4868
                      " WHERE id = %s ")
4869
        cursor.execute(update_row, (start_time_of_day,
4870
                                    end_time_of_day,
4871
                                    peak_type,
4872
                                    power,
4873
                                    sid))
4874
        cnx.commit()
4875
4876
        cursor.close()
4877
        cnx.close()
4878
4879
        resp.status = falcon.HTTP_200
4880
4881
4882
class MicrogridSensorCollection:
4883
    def __init__(self):