Code Duplication    Length = 187-187 lines in 2 locations

myems-api/core/microgrid.py 1 location

@@ 4593-4779 (lines=187) @@
4590
        resp.location = '/energystoragecontainerschedules/' + str(new_id)
4591
4592
4593
class MicrogridScheduleItem:
4594
    def __init__(self):
4595
        """Initializes Class"""
4596
        pass
4597
4598
    @staticmethod
4599
    def on_options(req, resp, id_, sid):
4600
        resp.status = falcon.HTTP_200
4601
4602
    @staticmethod
4603
    def on_get(req, resp, id_, sid):
4604
        access_control(req)
4605
        if not id_.isdigit() or int(id_) <= 0:
4606
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4607
                                   description='API.INVALID_MICROGRID_ID')
4608
        if not sid.isdigit() or int(sid) <= 0:
4609
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4610
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4611
4612
        cnx = mysql.connector.connect(**config.myems_system_db)
4613
        cursor = cnx.cursor()
4614
4615
        cursor.execute(" SELECT name "
4616
                       " FROM tbl_microgrids "
4617
                       " WHERE id = %s ", (id_,))
4618
        if cursor.fetchone() is None:
4619
            cursor.close()
4620
            cnx.close()
4621
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4622
                                   description='API.MICROGRID_NOT_FOUND')
4623
4624
        query = (" SELECT id, name, uuid "
4625
                 " FROM tbl_microgrids ")
4626
        cursor.execute(query)
4627
        rows_energystoragecontainers = cursor.fetchall()
4628
4629
        microgrid_dict = dict()
4630
        if rows_energystoragecontainers is not None and len(rows_energystoragecontainers) > 0:
4631
            for row in rows_energystoragecontainers:
4632
                microgrid_dict[row[0]] = {"id": row[0],
4633
                                          "name": row[1],
4634
                                          "uuid": row[2]}
4635
4636
        query = (" SELECT id, start_time_of_day, end_time_of_day, peak_type, power "
4637
                 " FROM tbl_microgrids_schedules "
4638
                 " WHERE id = %s ")
4639
        cursor.execute(query, (sid,))
4640
        row = cursor.fetchone()
4641
        cursor.close()
4642
        cnx.close()
4643
4644
        if row is None:
4645
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4646
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4647
        else:
4648
            meta_result = {"id": row[0],
4649
                           "start_time_of_day": str(row[1]),
4650
                           "end_time_of_day": str(row[2]),
4651
                           "peak_type": row[3],
4652
                           "power": row[4]}
4653
4654
        resp.text = json.dumps(meta_result)
4655
4656
    @staticmethod
4657
    @user_logger
4658
    def on_delete(req, resp, id_, sid):
4659
        admin_control(req)
4660
        if not id_.isdigit() or int(id_) <= 0:
4661
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4662
                                   description='API.INVALID_MICROGRID_ID')
4663
        if not sid.isdigit() or int(sid) <= 0:
4664
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4665
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4666
4667
        cnx = mysql.connector.connect(**config.myems_system_db)
4668
        cursor = cnx.cursor()
4669
4670
        cursor.execute(" SELECT name "
4671
                       " FROM tbl_microgrids "
4672
                       " WHERE id = %s ", (id_,))
4673
        if cursor.fetchone() is None:
4674
            cursor.close()
4675
            cnx.close()
4676
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4677
                                   description='API.MICROGRID_NOT_FOUND')
4678
4679
        cursor.execute(" SELECT id "
4680
                       " FROM tbl_microgrids_schedules "
4681
                       " WHERE id = %s ", (sid,))
4682
        if cursor.fetchone() is None:
4683
            cursor.close()
4684
            cnx.close()
4685
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4686
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4687
4688
        cursor.execute(" DELETE FROM tbl_microgrids_schedules "
4689
                       " WHERE id = %s ", (sid,))
4690
        cnx.commit()
4691
4692
        cursor.close()
4693
        cnx.close()
4694
4695
        resp.status = falcon.HTTP_204
4696
4697
    @staticmethod
4698
    @user_logger
4699
    def on_put(req, resp, id_, sid):
4700
        """Handles PUT requests"""
4701
        admin_control(req)
4702
        try:
4703
            raw_json = req.stream.read().decode('utf-8')
4704
        except Exception as ex:
4705
            raise falcon.HTTPError(status=falcon.HTTP_400,
4706
                                   title='API.BAD_REQUEST',
4707
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4708
        if not id_.isdigit() or int(id_) <= 0:
4709
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4710
                                   description='API.INVALID_MICROGRID_ID')
4711
        if not sid.isdigit() or int(sid) <= 0:
4712
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4713
                                   description='API.INVALID_MICROGRID_SCHEDULE_ID')
4714
4715
        new_values = json.loads(raw_json)
4716
4717
        if 'start_time_of_day' not in new_values['data'].keys() or \
4718
                not isinstance(new_values['data']['start_time_of_day'], str) or \
4719
                len(str.strip(new_values['data']['start_time_of_day'])) == 0:
4720
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4721
                                   description='API.INVALID_START_TIME_OF_DAY')
4722
        start_time_of_day = str.strip(new_values['data']['start_time_of_day'])
4723
4724
        if 'end_time_of_day' not in new_values['data'].keys() or \
4725
                not isinstance(new_values['data']['end_time_of_day'], str) or \
4726
                len(str.strip(new_values['data']['end_time_of_day'])) == 0:
4727
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4728
                                   description='API.INVALID_END_TIME_OF_DAY')
4729
        end_time_of_day = str.strip(new_values['data']['end_time_of_day'])
4730
4731
        if 'peak_type' not in new_values['data'].keys() or \
4732
                not isinstance(new_values['data']['peak_type'], str) or \
4733
                len(str.strip(new_values['data']['peak_type'])) == 0:
4734
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4735
                                   description='API.INVALID_PEAK_TYPE')
4736
        peak_type = str.strip(new_values['data']['peak_type'])
4737
4738
        if 'power' not in new_values['data'].keys() or \
4739
                not (isinstance(new_values['data']['power'], float) or
4740
                     isinstance(new_values['data']['power'], int)):
4741
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4742
                                   description='API.INVALID_POWER')
4743
        power = float(new_values['data']['power'])
4744
4745
        cnx = mysql.connector.connect(**config.myems_system_db)
4746
        cursor = cnx.cursor()
4747
4748
        cursor.execute(" SELECT name "
4749
                       " FROM tbl_microgrids "
4750
                       " WHERE id = %s ", (id_,))
4751
        if cursor.fetchone() is None:
4752
            cursor.close()
4753
            cnx.close()
4754
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4755
                                   description='API.MICROGRID_NOT_FOUND')
4756
4757
        cursor.execute(" SELECT id "
4758
                       " FROM tbl_microgrids_schedules "
4759
                       " WHERE id = %s ", (sid,))
4760
        if cursor.fetchone() is None:
4761
            cursor.close()
4762
            cnx.close()
4763
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4764
                                   description='API.MICROGRID_SCHEDULE_NOT_FOUND')
4765
4766
        update_row = (" UPDATE tbl_microgrids_schedules "
4767
                      " SET start_time_of_day = %s, end_time_of_day = %s, peak_type = %s, power = %s "
4768
                      " WHERE id = %s ")
4769
        cursor.execute(update_row, (start_time_of_day,
4770
                                    end_time_of_day,
4771
                                    peak_type,
4772
                                    power,
4773
                                    sid))
4774
        cnx.commit()
4775
4776
        cursor.close()
4777
        cnx.close()
4778
4779
        resp.status = falcon.HTTP_200
4780
4781
4782
class MicrogridSensorCollection:

myems-api/core/energystoragecontainer.py 1 location

@@ 5069-5255 (lines=187) @@
5066
        resp.location = '/energystoragecontainerschedules/' + str(new_id)
5067
5068
5069
class EnergyStorageContainerScheduleItem:
5070
    def __init__(self):
5071
        """Initializes Class"""
5072
        pass
5073
5074
    @staticmethod
5075
    def on_options(req, resp, id_, sid):
5076
        resp.status = falcon.HTTP_200
5077
5078
    @staticmethod
5079
    def on_get(req, resp, id_, sid):
5080
        access_control(req)
5081
        if not id_.isdigit() or int(id_) <= 0:
5082
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5083
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5084
        if not sid.isdigit() or int(sid) <= 0:
5085
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5086
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_SCHEDULE_ID')
5087
5088
        cnx = mysql.connector.connect(**config.myems_system_db)
5089
        cursor = cnx.cursor()
5090
5091
        cursor.execute(" SELECT name "
5092
                       " FROM tbl_energy_storage_containers "
5093
                       " WHERE id = %s ", (id_,))
5094
        if cursor.fetchone() is None:
5095
            cursor.close()
5096
            cnx.close()
5097
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5098
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
5099
5100
        query = (" SELECT id, name, uuid "
5101
                 " FROM tbl_energy_storage_containers ")
5102
        cursor.execute(query)
5103
        rows_energystoragecontainers = cursor.fetchall()
5104
5105
        energy_storage_container_dict = dict()
5106
        if rows_energystoragecontainers is not None and len(rows_energystoragecontainers) > 0:
5107
            for row in rows_energystoragecontainers:
5108
                energy_storage_container_dict[row[0]] = {"id": row[0],
5109
                                                         "name": row[1],
5110
                                                         "uuid": row[2]}
5111
5112
        query = (" SELECT id, start_time_of_day, end_time_of_day, peak_type, power "
5113
                 " FROM tbl_energy_storage_containers_schedules "
5114
                 " WHERE id = %s ")
5115
        cursor.execute(query, (sid,))
5116
        row = cursor.fetchone()
5117
        cursor.close()
5118
        cnx.close()
5119
5120
        if row is None:
5121
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5122
                                   description='API.ENERGY_STORAGE_CONTAINER_SCHEDULE_NOT_FOUND')
5123
        else:
5124
            meta_result = {"id": row[0],
5125
                           "start_time_of_day": str(row[1]),
5126
                           "end_time_of_day": str(row[2]),
5127
                           "peak_type": row[3],
5128
                           "power": row[4]}
5129
5130
        resp.text = json.dumps(meta_result)
5131
5132
    @staticmethod
5133
    @user_logger
5134
    def on_delete(req, resp, id_, sid):
5135
        admin_control(req)
5136
        if not id_.isdigit() or int(id_) <= 0:
5137
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5138
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5139
        if not sid.isdigit() or int(sid) <= 0:
5140
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5141
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_SCHEDULE_ID')
5142
5143
        cnx = mysql.connector.connect(**config.myems_system_db)
5144
        cursor = cnx.cursor()
5145
5146
        cursor.execute(" SELECT name "
5147
                       " FROM tbl_energy_storage_containers "
5148
                       " WHERE id = %s ", (id_,))
5149
        if cursor.fetchone() is None:
5150
            cursor.close()
5151
            cnx.close()
5152
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5153
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
5154
5155
        cursor.execute(" SELECT id "
5156
                       " FROM tbl_energy_storage_containers_schedules "
5157
                       " WHERE id = %s ", (sid,))
5158
        if cursor.fetchone() is None:
5159
            cursor.close()
5160
            cnx.close()
5161
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5162
                                   description='API.ENERGY_STORAGE_CONTAINER_SCHEDULE_NOT_FOUND')
5163
5164
        cursor.execute(" DELETE FROM tbl_energy_storage_containers_schedules "
5165
                       " WHERE id = %s ", (sid,))
5166
        cnx.commit()
5167
5168
        cursor.close()
5169
        cnx.close()
5170
5171
        resp.status = falcon.HTTP_204
5172
5173
    @staticmethod
5174
    @user_logger
5175
    def on_put(req, resp, id_, sid):
5176
        """Handles PUT requests"""
5177
        admin_control(req)
5178
        try:
5179
            raw_json = req.stream.read().decode('utf-8')
5180
        except Exception as ex:
5181
            raise falcon.HTTPError(status=falcon.HTTP_400,
5182
                                   title='API.BAD_REQUEST',
5183
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5184
        if not id_.isdigit() or int(id_) <= 0:
5185
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5186
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5187
        if not sid.isdigit() or int(sid) <= 0:
5188
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5189
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_SCHEDULE_ID')
5190
5191
        new_values = json.loads(raw_json)
5192
5193
        if 'start_time_of_day' not in new_values['data'].keys() or \
5194
                not isinstance(new_values['data']['start_time_of_day'], str) or \
5195
                len(str.strip(new_values['data']['start_time_of_day'])) == 0:
5196
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5197
                                   description='API.INVALID_START_TIME_OF_DAY')
5198
        start_time_of_day = str.strip(new_values['data']['start_time_of_day'])
5199
5200
        if 'end_time_of_day' not in new_values['data'].keys() or \
5201
                not isinstance(new_values['data']['end_time_of_day'], str) or \
5202
                len(str.strip(new_values['data']['end_time_of_day'])) == 0:
5203
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5204
                                   description='API.INVALID_END_TIME_OF_DAY')
5205
        end_time_of_day = str.strip(new_values['data']['end_time_of_day'])
5206
5207
        if 'peak_type' not in new_values['data'].keys() or \
5208
                not isinstance(new_values['data']['peak_type'], str) or \
5209
                len(str.strip(new_values['data']['peak_type'])) == 0:
5210
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5211
                                   description='API.INVALID_PEAK_TYPE')
5212
        peak_type = str.strip(new_values['data']['peak_type'])
5213
5214
        if 'power' not in new_values['data'].keys() or \
5215
                not (isinstance(new_values['data']['power'], float) or
5216
                     isinstance(new_values['data']['power'], int)):
5217
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5218
                                   description='API.INVALID_POWER')
5219
        power = Decimal(new_values['data']['power'])
5220
5221
        cnx = mysql.connector.connect(**config.myems_system_db)
5222
        cursor = cnx.cursor()
5223
5224
        cursor.execute(" SELECT name "
5225
                       " FROM tbl_energy_storage_containers "
5226
                       " WHERE id = %s ", (id_,))
5227
        if cursor.fetchone() is None:
5228
            cursor.close()
5229
            cnx.close()
5230
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5231
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
5232
5233
        cursor.execute(" SELECT id "
5234
                       " FROM tbl_energy_storage_containers_schedules "
5235
                       " WHERE id = %s ", (sid,))
5236
        if cursor.fetchone() is None:
5237
            cursor.close()
5238
            cnx.close()
5239
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5240
                                   description='API.ENERGY_STORAGE_CONTAINER_SCHEDULE_NOT_FOUND')
5241
5242
        update_row = (" UPDATE tbl_energy_storage_containers_schedules "
5243
                      " SET start_time_of_day = %s, end_time_of_day = %s, peak_type = %s, power = %s "
5244
                      " WHERE id = %s ")
5245
        cursor.execute(update_row, (start_time_of_day,
5246
                                    end_time_of_day,
5247
                                    peak_type,
5248
                                    power,
5249
                                    sid))
5250
        cnx.commit()
5251
5252
        cursor.close()
5253
        cnx.close()
5254
5255
        resp.status = falcon.HTTP_200
5256
5257
5258
class EnergyStorageContainerSTSCollection: