Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
nengyuanzhang committed Jan 8, 2024
2 parents d1fdcac + b5c8ea7 commit 4464c33
Show file tree
Hide file tree
Showing 4 changed files with 263 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- added background image to login page in myems-web
- added energy storage power station reports to myems-api and myems-web
- added data source export and import actions to myems-api
- added energy storage power station export and import actions to myems-api
-
### Changed
- changed microgrid monitoring in myems-web
Expand Down
5 changes: 5 additions & 0 deletions myems-api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,11 @@
energystoragepowerstation.EnergyStoragePowerStationUserCollection())
api.add_route('/energystoragepowerstations/{id_}/users/{uid}',
energystoragepowerstation.EnergyStoragePowerStationUserItem())
api.add_route('/energystoragepowerstations/{id_}/export',
energystoragepowerstation.EnergyStoragePowerStationExport())
api.add_route('/energystoragepowerstations/import',
energystoragepowerstation.EnergyStoragePowerStationImport())


api.add_route('/equipments',
equipment.EquipmentCollection())
Expand Down
9 changes: 6 additions & 3 deletions myems-api/core/datasource.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import simplejson as json
from core.useractivity import user_logger, admin_control
import config
import random


class DataSourceCollection:
Expand Down Expand Up @@ -566,13 +565,17 @@ def on_post(req, resp):
description='API.FAILED_TO_READ_REQUEST_STREAM')

new_values = json.loads(raw_json)
print(new_values)

if 'name' not in new_values.keys() or \
not isinstance(new_values['name'], str) or \
len(str.strip(new_values['name'])) == 0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_DATA_SOURCE_NAME')
name = str.strip(new_values['name']) + str(random.randint(0, 1000))
timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
if config.utc_offset[0] == '-':
timezone_offset = -timezone_offset
name = str.strip(new_values['name']) + \
(datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds')

if 'gateway' not in new_values.keys() or \
'id' not in new_values['gateway'].keys() or \
Expand Down
253 changes: 251 additions & 2 deletions myems-api/core/energystoragepowerstation.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import uuid
from datetime import datetime, timezone, timedelta
import falcon
import mysql.connector
import simplejson as json
Expand Down Expand Up @@ -182,7 +183,7 @@ def on_post(req, resp):
cursor.execute(" SELECT name "
" FROM tbl_contacts "
" WHERE id = %s ",
(new_values['data']['contact_id'],))
(contact_id,))
row = cursor.fetchone()
if row is None:
cursor.close()
Expand All @@ -193,7 +194,7 @@ def on_post(req, resp):
cursor.execute(" SELECT name "
" FROM tbl_cost_centers "
" WHERE id = %s ",
(new_values['data']['cost_center_id'],))
(cost_center_id,))
row = cursor.fetchone()
if row is None:
cursor.close()
Expand Down Expand Up @@ -842,3 +843,251 @@ def on_delete(req, resp, id_, uid):
cnx_user.close()

resp.status = falcon.HTTP_204


class EnergyStoragePowerStationImport:
@staticmethod
def __init__():
""""Initializes Class"""
pass

@staticmethod
def on_options(req, resp):
resp.status = falcon.HTTP_200

@staticmethod
@user_logger
def on_post(req, resp):
"""Handles POST requests"""
admin_control(req)
try:
upload = req.get_param('file')
# Read upload file as binary
raw_blob = upload.file.read()
except Exception as ex:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
description='API.FAILED_TO_UPLOAD_IMPORT_FILE')

try:
raw_json = raw_blob.decode('utf-8')
except Exception as ex:
raise falcon.HTTPError(status=falcon.HTTP_400,
title='API.BAD_REQUEST',
description='API.FAILED_TO_READ_REQUEST_STREAM')

new_values = json.loads(raw_json)
print(new_values)
if 'name' not in new_values.keys() or \
not isinstance(new_values['name'], str) or \
len(str.strip(new_values['name'])) == 0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_ENERGY_STORAGE_POWER_STATION_NAME')
timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
if config.utc_offset[0] == '-':
timezone_offset = -timezone_offset
name = str.strip(new_values['name']) + \
(datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds')

if 'address' not in new_values.keys() or \
not isinstance(new_values['address'], str) or \
len(str.strip(new_values['address'])) == 0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_ADDRESS_VALUE')
address = str.strip(new_values['address'])

if 'postal_code' not in new_values.keys() or \
not isinstance(new_values['postal_code'], str) or \
len(str.strip(new_values['postal_code'])) == 0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_POSTAL_CODE_VALUE')
postal_code = str.strip(new_values['postal_code'])

if 'latitude' not in new_values.keys() or \
not (isinstance(new_values['latitude'], float) or
isinstance(new_values['latitude'], int)) or \
new_values['latitude'] < -90.0 or \
new_values['latitude'] > 90.0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_LATITUDE_VALUE')
latitude = new_values['latitude']

if 'longitude' not in new_values.keys() or \
not (isinstance(new_values['longitude'], float) or
isinstance(new_values['longitude'], int)) or \
new_values['longitude'] < -180.0 or \
new_values['longitude'] > 180.0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_LONGITUDE_VALUE')
longitude = new_values['longitude']

if 'capacity' not in new_values.keys() or \
not (isinstance(new_values['capacity'], float) or
isinstance(new_values['capacity'], int)) or \
new_values['capacity'] <= 0.0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_CAPACITY_VALUE')
capacity = new_values['capacity']

if 'contact' not in new_values.keys() or \
'id' not in new_values['contact'].keys() or \
not isinstance(new_values['contact']['id'], int) or \
new_values['contact']['id'] <= 0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_CONTACT_ID')
contact_id = new_values['contact']['id']

if 'cost_center' not in new_values.keys() or \
'id' not in new_values['cost_center'].keys() or \
not isinstance(new_values['cost_center']['id'], int) or \
new_values['cost_center']['id'] <= 0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_COST_CENTER_ID')
cost_center_id = new_values['cost_center']['id']

if 'svg' not in new_values.keys() or \
not isinstance(new_values['svg'], str) or \
len(str.strip(new_values['svg'])) == 0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_SVG')
svg = str.strip(new_values['svg'])

if 'description' in new_values.keys() and \
new_values['description'] is not None and \
len(str(new_values['description'])) > 0:
description = str.strip(new_values['description'])
else:
description = None

cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()

cursor.execute(" SELECT name "
" FROM tbl_energy_storage_power_stations "
" WHERE name = %s ", (name,))
if cursor.fetchone() is not None:
cursor.close()
cnx.close()
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.ENERGY_STORAGE_POWER_STATION_NAME_IS_ALREADY_IN_USE')

cursor.execute(" SELECT name "
" FROM tbl_contacts "
" WHERE id = %s ",
(contact_id,))
row = cursor.fetchone()
if row is None:
cursor.close()
cnx.close()
raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
description='API.CONTACT_NOT_FOUND')

cursor.execute(" SELECT name "
" FROM tbl_cost_centers "
" WHERE id = %s ",
(cost_center_id,))
row = cursor.fetchone()
if row is None:
cursor.close()
cnx.close()
raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
description='API.COST_CENTER_NOT_FOUND')

add_values = (" INSERT INTO tbl_energy_storage_power_stations "
" (name, uuid, address, postal_code, latitude, longitude, capacity, "
" contact_id, cost_center_id, svg, description) "
" VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
cursor.execute(add_values, (name,
str(uuid.uuid4()),
address,
postal_code,
latitude,
longitude,
capacity,
contact_id,
cost_center_id,
svg,
description))
new_id = cursor.lastrowid
cnx.commit()
cursor.close()
cnx.close()

resp.status = falcon.HTTP_201
resp.location = '/energystoragepowerstations/' + str(new_id)


class EnergyStoragePowerStationExport:
@staticmethod
def __init__():
""""Initializes Class"""
pass

@staticmethod
def on_options(req, resp, id_):
resp.status = falcon.HTTP_200

@staticmethod
def on_get(req, resp, id_):
access_control(req)
if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_ENERGY_STORAGE_POWER_STATION_ID')

cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()

query = (" SELECT id, name, uuid "
" FROM tbl_contacts ")
cursor.execute(query)
rows_contacts = cursor.fetchall()

contact_dict = dict()
if rows_contacts is not None and len(rows_contacts) > 0:
for row in rows_contacts:
contact_dict[row[0]] = {"id": row[0],
"name": row[1],
"uuid": row[2]}

query = (" SELECT id, name, uuid "
" FROM tbl_cost_centers ")
cursor.execute(query)
rows_cost_centers = cursor.fetchall()

cost_center_dict = dict()
if rows_cost_centers is not None and len(rows_cost_centers) > 0:
for row in rows_cost_centers:
cost_center_dict[row[0]] = {"id": row[0],
"name": row[1],
"uuid": row[2]}

query = (" SELECT id, name, uuid, "
" address, postal_code, latitude, longitude, capacity, "
" contact_id, cost_center_id, svg, description "
" FROM tbl_energy_storage_power_stations "
" WHERE id = %s ")
cursor.execute(query, (id_,))
row = cursor.fetchone()
cursor.close()
cnx.close()

if row is None:
raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
description='API.ENERGY_STORAGE_POWER_STATION_NOT_FOUND')
else:
contact = contact_dict.get(row[8], None)
cost_center = cost_center_dict.get(row[9], None)
meta_result = {"id": row[0],
"name": row[1],
"uuid": row[2],
"address": row[3],
"postal_code": row[4],
"latitude": row[5],
"longitude": row[6],
"capacity": row[7],
"contact": contact,
"cost_center": cost_center,
"svg": row[10],
"description": row[11],
"qrcode": 'energystoragepowerstation:' + row[2]}

resp.text = json.dumps(meta_result)

0 comments on commit 4464c33

Please sign in to comment.