Skip to content

Commit

Permalink
enhance solarDevicesManager.py and config.py code
Browse files Browse the repository at this point in the history
  • Loading branch information
bastoscorp committed Jul 17, 2024
1 parent 2b7748a commit 7e86403
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 52 deletions.
50 changes: 25 additions & 25 deletions business/solarDevicesManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
from exception.HuaweiApiFrequencyException import HuaweiApiFrequencyException
from exception.HuaweiApiException import HuaweiApiException

class SolarDevicesManager:

class SolarDevicesManager:
session_mgmt = ""
station_code = ""
inverter = InverterDevice()
Expand All @@ -32,12 +32,12 @@ def load_station_and_devices_info(self):
cache_info_file = self.session_mgmt.config.cacheInfoFile
ret = False
if file_exists(cache_info_file):
with open(cache_info_file, 'rb') as f1:
#in case of cacheInfoFile is older than 24h --> need to delete it and create another
c_timestamp = os.path.getctime(cache_info_file)
duration = self.session_mgmt.config.cacheInfoFileDuration
age = (time.time() - c_timestamp)
if age < duration:
with open(cache_info_file, 'rb') as f1:
# in case of cacheInfoFile is older than 24h --> need to delete it and create another
c_timestamp = os.path.getctime(cache_info_file)
duration = self.session_mgmt.config.cacheInfoFileDuration
age = (time.time() - c_timestamp)
if age < duration:
data = pickle.load(f1)
self.station_code = data['station_code']
self.inverter.device_id = data['inverter_device_id']
Expand All @@ -64,8 +64,9 @@ def save_station_and_devices_info(self):
def get_station_code(self):
# max 24 calls per day
uri = self.session_mgmt.config.stationUri
headers = {"XSRF-TOKEN": self.session_mgmt.session_cookie["XSRF-TOKEN"], "Content-Type": self.session_mgmt.contentType["Content-Type"]}
data = {"pageNo":1, "pageSize":100}
headers = {"XSRF-TOKEN": self.session_mgmt.session_cookie["XSRF-TOKEN"],
"Content-Type": self.session_mgmt.contentType["Content-Type"]}
data = {"pageNo": 1, "pageSize": 100}
json_data = json.dumps(data)
try:
response = requests.post(uri, headers=headers, data=json_data)
Expand All @@ -81,15 +82,15 @@ def get_station_code(self):
logging.error("Error Connecting:", errc)
raise SystemExit(errc)


def get_devices(self):
#max 24 calls per day
# max 24 calls per day
uri = self.session_mgmt.config.devicesUri
headers = {"XSRF-TOKEN": self.session_mgmt.session_cookie["XSRF-TOKEN"], "Content-Type": self.session_mgmt.contentType["Content-Type"]}
headers = {"XSRF-TOKEN": self.session_mgmt.session_cookie["XSRF-TOKEN"],
"Content-Type": self.session_mgmt.contentType["Content-Type"]}
data = {"stationCodes": self.station_code}
json_data = json.dumps(data)
try:
response = requests.post(uri, headers=headers , data=json_data)
response = requests.post(uri, headers=headers, data=json_data)
rep_data = response.json()
if rep_data['success']:
data = rep_data["data"]
Expand All @@ -116,12 +117,13 @@ def get_devices(self):

def get_inverter_data(self):
uri = self.session_mgmt.config.deviceKpiUri
headers = {"XSRF-TOKEN": self.session_mgmt.session_cookie["XSRF-TOKEN"], "Content-Type": self.session_mgmt.contentType["Content-Type"]}
headers = {"XSRF-TOKEN": self.session_mgmt.session_cookie["XSRF-TOKEN"],
"Content-Type": self.session_mgmt.contentType["Content-Type"]}
data = {"devIds": self.inverter.device_id, "devTypeId": self.inverter.device_type_code}
json_data = json.dumps(data)
response = requests.post(uri, headers=headers, data=json_data)
rep_data = response.json()
try:
response = requests.post(uri, headers=headers , data=json_data)
rep_data = response.json()
if rep_data['success']:
data = rep_data["data"][0]
kpi = data["dataItemMap"]
Expand All @@ -131,12 +133,12 @@ def get_inverter_data(self):
elif not rep_data["success"] and rep_data["failCode"] == 407:
err = rep_data["data"]
msg = "Query Frequency Too High"
logging.error(msg,err)
logging.error(msg, err)
raise HuaweiApiFrequencyException(msg, err)
else:
err = rep_data["data"]
msg = rep_data["message"]
logging.error(msg,err)
logging.error(msg, err)
raise HuaweiApiException("issue with Huawei API", rep_data)
except requests.exceptions.HTTPError as err:
logging.error("Error HTTP:", err)
Expand All @@ -150,20 +152,20 @@ def get_inverter_data(self):
if rep_data["failCode"] == 305:
err = rep_data["failCode"]
msg = "User must Relogin"
logging.error(msg,err)
logging.error(msg, err)
logging.info("deleting session...")
if (self.session_mgmt.delete_session()):
if self.session_mgmt.delete_session():
logging.info("Session Deleted !")
raise HuaweiApiException(msg, rep_data)


def get_powersensor_data(self):
uri = self.session_mgmt.config.deviceKpiUri
headers = {"XSRF-TOKEN": self.session_mgmt.session_cookie["XSRF-TOKEN"], "Content-Type": self.session_mgmt.contentType["Content-Type"]}
headers = {"XSRF-TOKEN": self.session_mgmt.session_cookie["XSRF-TOKEN"],
"Content-Type": self.session_mgmt.contentType["Content-Type"]}
data = {"devIds": self.ps.device_id, "devTypeId": self.ps.device_type_code}
json_data = json.dumps(data)
try:
response = requests.post(uri, headers=headers , data=json_data)
response = requests.post(uri, headers=headers, data=json_data)
rep_data = response.json()
if rep_data['success']:
data = rep_data["data"][0]
Expand All @@ -183,5 +185,3 @@ def get_powersensor_data(self):
except requests.exceptions.ConnectionError as errc:
logging.error("Error Connecting:", errc)
raise SystemExit(errc)


48 changes: 21 additions & 27 deletions config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ class Config:
devicesUri = ''
deviceKpiUri = ''


hue_discovery_url = ''
hue_url_all_dev = ''
hue_username = ''
Expand All @@ -29,60 +28,55 @@ class Config:
alert_title = ""
alert_configured_url = ""


def __init__(self, file: str) -> object:
def __init__(self, file: str):
"""
:rtype: Config object with all vars
"""
config = configparser.ConfigParser()
config.read(file)

configDir =os.path.dirname(__file__)
pvHome = os.path.dirname(configDir)
config_dir = os.path.dirname(__file__)
pv_home = os.path.dirname(config_dir)

self.baseUrl = config.get('General', 'domain')
self.userName = config.get('General', 'user')
self.systemCode = config.get('General', 'password')

sessFile = config.get('Session', 'connectionFile')
self.sessionFile = os.path.join(pvHome, sessFile)
self.checkDirs(self.sessionFile)


sess_file = config.get('Session', 'connectionFile')
self.sessionFile = os.path.join(pv_home, sess_file)
self.check_dirs(self.sessionFile)

self.sessionDuration = int(config.get('Session', 'duration'))

self.loginUri = urljoin(self.baseUrl, config.get('Login', 'urn'))
self.logoutUri = urljoin(self.baseUrl, config.get('Logout', 'urn'))
self.stationUri = urljoin(self.baseUrl, config.get('Station', 'urn'))

stationInfoFile = config.get('Station', 'cacheInfoFile')
self.cacheInfoFile = os.path.join(pvHome,stationInfoFile)
self.checkDirs(self.cacheInfoFile)

station_info_file = config.get('Station', 'cacheInfoFile')
self.cacheInfoFile = os.path.join(pv_home, station_info_file)
self.check_dirs(self.cacheInfoFile)

self.cacheInfoFileDuration = int(config.get('Station', 'duration'))
self.devicesUri = urljoin(self.baseUrl, config.get('Devices', 'urn'))
self.deviceKpiUri = urljoin(self.baseUrl, config.get('DevicesKpi', 'urn'))

self.alert_configured_url = urljoin(config.get("alert","url"),config.get("alert","topic"))
self.alert_title = config.get("alert","title")

self.hue_discovery_url = config.get("action_philips_hue","discover_url")
self.hue_url_all_dev = config.get("action_philips_hue","bridge_all_light_devices")
self.hue_username = config.get("action_philips_hue","hue_username")
self.hue_client_key = config.get("action_philips_hue","hue_client_key")
self.alert_configured_url = urljoin(config.get("alert", "url"), config.get("alert", "topic"))
self.alert_title = config.get("alert", "title")

hue_cache = config.get("action_philips_hue","cacheFile")
self.hue_cache_file = os.path.join(pvHome,hue_cache)
self.checkDirs(self.hue_cache_file)
self.hue_discovery_url = config.get("action_philips_hue", "discover_url")
self.hue_url_all_dev = config.get("action_philips_hue", "bridge_all_light_devices")
self.hue_username = config.get("action_philips_hue", "hue_username")
self.hue_client_key = config.get("action_philips_hue", "hue_client_key")

self.hue_cache_duration = int(config.get("action_philips_hue","cache_duration"))
hue_cache = config.get("action_philips_hue", "cacheFile")
self.hue_cache_file = os.path.join(pv_home, hue_cache)
self.check_dirs(self.hue_cache_file)

self.hue_cache_duration = int(config.get("action_philips_hue", "cache_duration"))

def checkDirs(self,path):
@staticmethod
def check_dirs(path):
parent = os.path.dirname(path)
if not (os.path.exists(parent)):
os.makedirs(parent)

0 comments on commit 7e86403

Please sign in to comment.