Skip to content

Commit

Permalink
DB_ADDON:
Browse files Browse the repository at this point in the history
- Code Improvements
  • Loading branch information
sisamiwe committed Jul 8, 2024
1 parent 3c4ce44 commit 371d724
Showing 1 changed file with 19 additions and 24 deletions.
43 changes: 19 additions & 24 deletions db_addon/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def __init__(self, sh):
self.current_values = {} # Dict to hold min and max value of current day / week / month / year for items
self.previous_values = {} # Dict to hold value of end of last day / week / month / year for items
self.item_cache = {} # Dict to hold item_id, oldest_log_ts and oldest_entry for items
self.value_list_raw_data = {} # List to hold raw data
self.value_list_raw_data = {} # Dict to hold value list raw data

# define variables for database, database connection, working queue and status
self.item_queue = queue.Queue() # Queue containing all to be executed items
Expand Down Expand Up @@ -413,15 +413,12 @@ def get_query_parameters_from_db_addon_fct() -> Union[dict, None]:
self.logger.warning(f"For calculating '{db_addon_fct}' at Item '{item.property.path}' no mandatory parameters given.")
return

if required_params and None in required_params:
self.logger.warning(f"For calculating '{db_addon_fct}' at Item '{item.property.path}' not all mandatory parameters given. Definitions are: {func=}, {timeframe=}, {timedelta=}, {start=}, {end=}, {group=}, {group2=}, {data_con_func=}")
return

# create dict and reduce dict to keys with value != None
param_dict = {'func': func, 'timeframe': timeframe, 'timedelta': timedelta, 'start': start, 'end': end, 'group': group, 'group2': group2, 'data_con_func': data_con_func}
if None in required_params:
missing_params = [attr for attr, val in zip(['func', 'timeframe', 'timedelta', 'start', 'end', 'group', 'group2', 'data_con_func'], required_params) if val is None]
self.logger.warning(f"Missing mandatory parameters for {db_addon_fct} at Item '{item.property.path}': {', '.join(missing_params)}")
return None

# return reduced dict w keys with value != None
return {k: v for k, v in param_dict.items() if v is not None}
return {k: v for k, v in locals().items() if k in ['func', 'timeframe', 'timedelta', 'start', 'end', 'group', 'group2', 'data_con_func'] and v is not None}

def get_query_parameters_from_db_addon_params() -> Union[dict, None]:
"""derives parameters from item attribute db_addon_params, if parameter for db_addon_fct are not sufficient
Expand Down Expand Up @@ -1661,6 +1658,7 @@ def _handle_zaehlerstand(self, query_params: dict) -> Union[float, int, None]:
# get last value of timeframe
query_params.update({'func': 'next'})
last_value = self._query_item(**query_params)[0][1]

if self.debug_log.prepare:
self.logger.debug(f"{last_value=}")

Expand Down Expand Up @@ -1930,9 +1928,9 @@ def _count(op, minmax: str, limit: int) -> int:

# define start_date, end_date
if month is None:
((s_y, s_m, s_d), (e_y, e_m, e_d)) = defaults.get(func, {}).get('start_end', timeframe[3])
start_date = datetime.date(int(year) + s_y, s_m, s_d)
end_date = datetime.date(int(year) + e_y, e_m, e_d)
((start_year, start_month, start_day), (end_year, end_month, end_day)) = defaults.get(func, {}).get('start_end', timeframe[3])
start_date = datetime.date(int(year) + start_year, start_month, start_day)
end_date = datetime.date(int(year) + end_year, end_month, end_day)
elif self._valid_month(month):
start_date = datetime.date(int(year), int(month), 1)
end_date = start_date + relativedelta(months=+1) - datetime.timedelta(days=1)
Expand Down Expand Up @@ -2126,10 +2124,10 @@ def _check_db_existence(self) -> bool:
if not _db_plugin:
self.logger.error(f"Database plugin not loaded or given ConfigName {self.db_configname} not correct. No need for DatabaseAddOn Plugin.")
return False
else:
self.logger.debug(f"Corresponding plugin 'database' with given config name '{self.db_configname}' found.")
self._db_plugin = _db_plugin
return self._get_db_parameter()

self.logger.debug(f"Corresponding plugin 'database' with given config name '{self.db_configname}' found.")
self._db_plugin = _db_plugin
return self._get_db_parameter()

def _get_db_parameter(self) -> bool:
"""
Expand Down Expand Up @@ -2157,11 +2155,10 @@ def _get_db_parameter(self) -> bool:
self.item_attribute_search_str = f"{self.item_attribute_search_str}@{self.db_instance}"
self.connection_data = self._db_plugin.get_parameter_value('connect') # pymsql ['host:localhost', 'user:smarthome', 'passwd:smarthome', 'db:smarthome', 'port:3306']
self.logger.debug(f"Database Plugin available with instance={self.db_instance} and connection={self.connection_data}")
return True
except Exception as e:
self.logger.error(f"Error {e} occurred during getting database plugin parameters. DatabaseAddOn Plugin not loaded.")
return False
else:
return True

def _check_db_connection_setting(self) -> None:
"""
Expand Down Expand Up @@ -2506,17 +2503,15 @@ def _valid_year(self, year: Union[int, str]) -> bool:
if ((isinstance(year, int) or (isinstance(year, str) and year.isdigit())) and (
1980 <= int(year) <= self.shtime.today(offset=0).year)) or (isinstance(year, str) and year == 'current'):
return True
else:
return False
return False

@staticmethod
def _valid_month(month: Union[int, str]) -> bool:
"""Check if given month is digit and within allowed range"""

if (isinstance(month, int) or (isinstance(month, str) and month.isdigit())) and (1 <= int(month) <= 12):
return True
else:
return False
return False

#################################
# Database Query Preparation
Expand Down Expand Up @@ -2965,7 +2960,7 @@ def timeframe_to_timeframe(timeframe_in: str, timeframe_out: str) -> int:
_w_in_m = _w_in_y / _m_in_y
_d_in_m = _d_in_y / _m_in_y

lookup = {
conversion_factors = {
'hour': {'hour': 1,
'day': _h_in_d,
'week': _h_in_d * _d_in_w,
Expand Down Expand Up @@ -2998,7 +2993,7 @@ def timeframe_to_timeframe(timeframe_in: str, timeframe_out: str) -> int:
}
}

return lookup[timeframe_in][timeframe_out]
return conversion_factors[timeframe_in][timeframe_out]


def to_int(arg) -> Union[int, None]:
Expand Down

0 comments on commit 371d724

Please sign in to comment.