Skip to content

Commit

Permalink
stateengine plugin: minor code adjustments
Browse files Browse the repository at this point in the history
  • Loading branch information
onkelandy committed Sep 11, 2024
1 parent a3aceb2 commit a45bbb5
Show file tree
Hide file tree
Showing 9 changed files with 98 additions and 91 deletions.
1 change: 0 additions & 1 deletion stateengine/StateEngineAction.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,6 @@ def check_getitem_fromeval(self, check_item, check_value=None, check_mindelta=No
def check_complete(self, state, check_item, check_status, check_mindelta, check_value, action_type, evals_items=None, use=None):
_issue = {self._name: {'issue': None,
'issueorigin': [{'state': state.id, 'action': self._function}]}}
self._log_develop("For action {} check item {} status {} mindelta {} value {} actiontype {}, use {} evals_items {}", self, check_item, check_status, check_mindelta, check_value, action_type, use, evals_items)
try:
_name = evals_items.get(self.name)
if _name is not None:
Expand Down
8 changes: 4 additions & 4 deletions stateengine/StateEngineActions.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,12 +334,12 @@ def __ensure_action_exists(self, func, name):
return True, _issue_list

def __handle_combined_action_attribute(self, name, value_list):
def remove_action(ex):
def remove_action(e):
if name in self.__actions:
del self.__actions[name]
_issue = {name: {'issue': [ex], 'issueorigin': [{'state': 'unknown', 'action': parameter['function']}], 'ignore': True}}
_issue_list.append(_issue)
self._log_warning("Ignoring action {0} because: {1}", name, ex)
i = {name: {'issue': [e], 'issueorigin': [{'state': 'unknown', 'action': parameter['function']}], 'ignore': True}}
_issue_list.append(i)
self._log_warning("Ignoring action {0} because: {1}", name, e)

parameter = {'function': None, 'force': None, 'repeat': None, 'delay': 0, 'order': None, 'nextconditionset': None, 'conditionset': None,
'previousconditionset': None, 'previousstate_conditionset': None, 'mode': None, 'instanteval': None}
Expand Down
70 changes: 35 additions & 35 deletions stateengine/StateEngineCondition.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,14 +292,14 @@ def complete(self, state, use):
if all(item is None for item in [self.__item, self.__status, self.__eval, self.__status_eval]):
raise ValueError("Neither 'item' nor 'status' nor '(status)eval' given!")

if any(item is not None for item in [self.__item, self.__status, self.__eval, self.__status_eval])\
and not self.__changedby.is_empty() and self.__changedbynegate is None:
if any(item is not None for item in [self.__item, self.__status, self.__eval, self.__status_eval]) \
and not self.__changedby.is_empty() and self.__changedbynegate is None:
self.__changedbynegate = False
if any(item is not None for item in [self.__item, self.__status, self.__eval, self.__status_eval])\
and not self.__updatedby.is_empty() and self.__updatedbynegate is None:
if any(item is not None for item in [self.__item, self.__status, self.__eval, self.__status_eval]) \
and not self.__updatedby.is_empty() and self.__updatedbynegate is None:
self.__updatedbynegate = False
if any(item is not None for item in [self.__item, self.__status, self.__eval, self.__status_eval])\
and not self.__triggeredby.is_empty() and self.__triggeredbynegate is None:
if any(item is not None for item in [self.__item, self.__status, self.__eval, self.__status_eval]) \
and not self.__triggeredby.is_empty() and self.__triggeredbynegate is None:
self.__triggeredbynegate = False

# cast stuff
Expand Down Expand Up @@ -462,19 +462,19 @@ def __convert(convert_value, convert_current):
self.__value.set_cast(StateEngineTools.cast_str)
convert_value = StateEngineTools.cast_str(convert_value)
convert_current = StateEngineTools.cast_str(convert_current)
if not type(_oldvalue) == type(convert_value):
if not type(_oldvalue) is type(convert_value):
self._log_debug("Value {} was type {} and therefore not the same"
" type as item value {}. It got converted to {}.",
_oldvalue, type(_oldvalue), convert_current, type(convert_value))
return convert_value, convert_current

current = self.__get_current(eval_type='changedby') if valuetype == "changedby" else\
self.__get_current(eval_type='updatedby') if valuetype == "updatedby" else\
self.__get_current(eval_type='triggeredby') if valuetype == "triggeredby" else\
current = self.__get_current(eval_type='changedby') if valuetype == "changedby" else \
self.__get_current(eval_type='updatedby') if valuetype == "updatedby" else \
self.__get_current(eval_type='triggeredby') if valuetype == "triggeredby" else \
self.__get_current(eval_type='value')
negate = self.__changedbynegate if valuetype == "changedby" else\
self.__updatedbynegate if valuetype == "updatedby" else\
self.__triggeredbynegate if valuetype == "triggeredby" else\
negate = self.__changedbynegate if valuetype == "changedby" else \
self.__updatedbynegate if valuetype == "updatedby" else \
self.__triggeredbynegate if valuetype == "triggeredby" else \
self.__negate
_key_current = ['{}'.format(state.id), 'conditionsets', '{}'.format(
self._abitem.get_variable('current.conditionset_name')), '{}'.format(self.__name),
Expand All @@ -490,20 +490,20 @@ def __convert(convert_value, convert_current):
for i, element in enumerate(value):
regex_result = None
regex_check = False
if valuetype == "value" and type(element) != type(current) and current is not None:
if valuetype == "value" and type(element) is not type(current) and current is not None:
element, current = __convert(element, current)
if isinstance(element, re.Pattern):
regex_result = element.fullmatch(str(current))
regex_check = True
if negate:
if (regex_result is not None and regex_check is True)\
or (current == element and regex_check is False):
if (regex_result is not None and regex_check is True) \
or (current == element and regex_check is False):
self._log_debug("{0} found but negated -> not matching", element)
self._abitem.update_webif(_key_match, 'no')
return False
else:
if (regex_result is not None and regex_check is True)\
or (current == element and regex_check is False):
if (regex_result is not None and regex_check is True) \
or (current == element and regex_check is False):
self._log_debug("{0} found -> matching", element)
self._abitem.update_webif(_key_match, 'yes')
return True
Expand All @@ -522,7 +522,7 @@ def __convert(convert_value, convert_current):
regex_result = None
regex_check = False
# If current and value have different types, convert both to string
if valuetype == "value" and type(value) != type(current) and current is not None:
if valuetype == "value" and type(value) is not type(current) and current is not None:
value, current = __convert(value, current)
text = "Condition '{0}': {1}={2} negate={3} current={4}"
self._abitem.update_webif(_key_current, str(current))
Expand All @@ -532,14 +532,14 @@ def __convert(convert_value, convert_current):
regex_result = value.fullmatch(str(current))
regex_check = True
if negate:
if (regex_result is None and regex_check is True)\
or (current != value and regex_check is False):
if (regex_result is None and regex_check is True) \
or (current != value and regex_check is False):
self._log_debug("not OK but negated -> matching")
self._abitem.update_webif(_key_match, 'yes')
return True
else:
if (regex_result is not None and regex_check is True)\
or (current == value and regex_check is False):
if (regex_result is not None and regex_check is True) \
or (current == value and regex_check is False):
self._log_debug("OK -> matching")
self._abitem.update_webif(_key_match, 'yes')
return True
Expand Down Expand Up @@ -823,10 +823,10 @@ def check_eval(eval_or_status_eval):
eval_result = eval(eval_or_status_eval)
if isinstance(eval_result, self.__itemClass):
value = eval_result.property.last_change_age if eval_type == 'age' else \
eval_result.property.last_change_by if eval_type == 'changedby' else \
eval_result.property.last_update_by if eval_type == 'updatedby' else \
eval_result.property.last_trigger_by if eval_type == 'triggeredby' else \
eval_result.property.value
eval_result.property.last_change_by if eval_type == 'changedby' else \
eval_result.property.last_update_by if eval_type == 'updatedby' else \
eval_result.property.last_trigger_by if eval_type == 'triggeredby' else \
eval_result.property.value
else:
value = eval_result
except Exception as ex:
Expand All @@ -840,10 +840,10 @@ def check_eval(eval_or_status_eval):
if self.__status is not None:
# noinspection PyUnusedLocal
self._log_debug("Trying to get {} of status item {}", eval_type, self.__status.property.path)
return self.__status.property.last_change_age if eval_type == 'age' else\
self.__status.property.last_change_by if eval_type == 'changedby' else\
self.__status.property.last_update_by if eval_type == 'updatedby' else\
self.__status.property.last_trigger_by if eval_type == 'triggeredby' else\
return self.__status.property.last_change_age if eval_type == 'age' else \
self.__status.property.last_change_by if eval_type == 'changedby' else \
self.__status.property.last_update_by if eval_type == 'updatedby' else \
self.__status.property.last_trigger_by if eval_type == 'triggeredby' else \
self.__status.property.value
elif self.__status_eval is not None:
self._log_debug("Trying to get {} of statuseval {}", eval_type, self.__status_eval)
Expand All @@ -852,10 +852,10 @@ def check_eval(eval_or_status_eval):
elif self.__item is not None:
# noinspection PyUnusedLocal
self._log_debug("Trying to get {} of item {}", eval_type, self.__item.property.path)
return self.__item.property.last_change_age if eval_type == 'age' else\
self.__item.property.last_change_by if eval_type == 'changedby' else\
self.__item.property.last_update_by if eval_type == 'updatedby' else\
self.__item.property.last_trigger_by if eval_type == 'triggeredby' else\
return self.__item.property.last_change_age if eval_type == 'age' else \
self.__item.property.last_change_by if eval_type == 'changedby' else \
self.__item.property.last_update_by if eval_type == 'updatedby' else \
self.__item.property.last_trigger_by if eval_type == 'triggeredby' else \
self.__item.property.value
elif self.__eval is not None:
self._log_debug("Trying to get {} of eval {}", eval_type, self.__eval)
Expand Down
12 changes: 6 additions & 6 deletions stateengine/StateEngineFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,14 @@ def check_include_exclude(entry_type):
# If current value is in list -> Return "Trigger"
for e in conf_entry:
e = re.compile(e, re.IGNORECASE)
result = e.match(original)
elog.info("Checking regex result {}", result)
if result is not None:
r = e.match(original)
elog.info("Checking regex result {}", r)
if r is not None:
elog.info("{0}: matching.", e)
elog.decrease_indent()
returnvalue = retval_trigger if entry_type == "include" else retval_no_trigger
elog.info("Writing value {0}", returnvalue)
return returnvalue
retval = retval_trigger if entry_type == "include" else retval_no_trigger
elog.info("Writing value {0}", retval)
return retval
elog.info("{0}: not matching", e)
elog.decrease_indent()
return None
Expand Down
41 changes: 21 additions & 20 deletions stateengine/StateEngineItem.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,9 @@ def __init__(self, smarthome, item, se_plugin):
self.__log_level = StateEngineValue.SeValue(self, "Log Level", False, "num")

_default_log_level = self.__logger.default_log_level.get()
_returnvalue, _returntype, _using_default, _issue, _ = self.__log_level.set_from_attr(self.__item, "se_log_level",
_default_log_level)
_returnvalue, _returntype, _using_default, _issue, _ = self.__log_level.set_from_attr(self.__item,
"se_log_level",
_default_log_level)
self.__using_default_log_level = _using_default
_returnvalue = self.__log_level.get()
if isinstance(_returnvalue, list) and len(_returnvalue) == 1:
Expand Down Expand Up @@ -880,10 +881,10 @@ def __update_can_release(self, can_release, new_state=None):

def __handle_releasedby(self, new_state, last_state, instant_leaveaction):
def update_can_release_list():
for e in _returnvalue:
e = self.__update_release_item_value(e, new_state)
e = e if isinstance(e, list) else [e]
for entry in e:
for r in _returnvalue:
r = self.__update_release_item_value(r, new_state)
r = r if isinstance(r, list) else [r]
for entry in r:
if entry and state.id not in can_release.setdefault(entry, [state.id]):
can_release[entry].append(state.id)

Expand Down Expand Up @@ -1046,19 +1047,19 @@ def update_list(existing, new_entries):
existing.append(entry)
return existing

combined_dict = dict1.copy()
comb_dict = dict1.copy()

for key, value in dict2.items():
if key not in combined_dict:
combined_dict[key] = value
if key not in comb_dict:
comb_dict[key] = value
continue
combined_entry = combined_dict[key]
combined_entry = comb_dict[key]
if 'issue' in value:
combined_entry['issue'] = update_list(combined_entry.get('issue', []), value['issue'])
if 'issueorigin' in value:
combined_entry['issueorigin'] = update_list(combined_entry.get('issueorigin', []), value['issueorigin'])

return combined_dict
return comb_dict

if issue_type == "state":
combined_dict = combine_dicts(issues, self.__state_issues)
Expand Down Expand Up @@ -1317,7 +1318,7 @@ def __initialize_state(self, item_state, _statecount):
_issue = _state.update_order(_statecount)
if _issue:
self.__config_issues.update({item_state.property.path:
{'issue': _issue, 'attribute': 'se_stateorder'}})
{'issue': _issue, 'attribute': 'se_stateorder'}})
self.__logger.error("Issue with state {0} while setting order: {1}",
item_state.property.path, _issue)
self.__states.append(_state)
Expand All @@ -1330,13 +1331,13 @@ def __initialize_state(self, item_state, _statecount):
return _statecount + 1
except ValueError as ex:
self.update_issues('state', {item_state.property.path: {'issue': ex, 'issueorigin':
[{'conditionset': 'None', 'condition': 'ValueError'}]}})
[{'conditionset': 'None', 'condition': 'ValueError'}]}})
self.__logger.error("Ignoring state {0} because ValueError: {1}",
item_state.property.path, ex)
return _statecount
except Exception as ex:
self.update_issues('state', {item_state.property.path: {'issue': ex, 'issueorigin':
[{'conditionset': 'None', 'condition': 'GeneralError'}]}})
[{'conditionset': 'None', 'condition': 'GeneralError'}]}})
self.__logger.error("Ignoring state {0} because: {1}",
item_state.property.path, ex)
return _statecount
Expand Down Expand Up @@ -1790,11 +1791,11 @@ def process_returnvalue(value):
return _returnvalue_issue

def update_can_release_list():
for i, value in enumerate(_convertedlist):
if _converted_typelist[i] == 'item':
value = self.__update_release_item_value(_converted_evaluatedlist[i], state)
elif _converted_typelist[i] == 'eval':
value = _converted_evaluatedlist[i]
for z, value in enumerate(_convertedlist):
if _converted_typelist[z] == 'item':
value = self.__update_release_item_value(_converted_evaluatedlist[z], state)
elif _converted_typelist[z] == 'eval':
value = _converted_evaluatedlist[z]
value = value if isinstance(value, list) else [value]
for v in value:
if v and can_release.get(v) and state.id not in can_release.get(v):
Expand Down Expand Up @@ -1913,7 +1914,7 @@ def cli_detail(self, handler):
handler.push("\tPrevious conditionset: {0} ('{1}')\n".format(self.get_previousconditionset_id(),
self.get_previousconditionset_name()))
handler.push("\tNext conditionset: {0} ('{1}')\n".format(self.get_nextconditionset_id(),
self.get_nextconditionset_name()))
self.get_nextconditionset_name()))
handler.push(self.__startup_delay.get_text("\t", "\n"))
handler.push("\tCycle: {0}\n".format(cycles))
handler.push("\tCron: {0}\n".format(crons))
Expand Down
Loading

0 comments on commit a45bbb5

Please sign in to comment.