Reduce complexity and line length for flake8

This commit is contained in:
Andre Basche 2023-07-16 04:42:29 +02:00
parent 442e7a07dd
commit e1c8bc5835
8 changed files with 89 additions and 77 deletions

View File

@ -28,9 +28,7 @@ jobs:
python -m pip install -r requirements_dev.txt python -m pip install -r requirements_dev.txt
- name: Lint with flake8 - name: Lint with flake8
run: | run: |
# stop the build if there are Python syntax errors or undefined names flake8 . --count --max-complexity=7 --max-line-length=88 --statistics
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=88 --statistics
- name: Type check with mypy - name: Type check with mypy
run: | run: |
mypy pyhon/ mypy pyhon/

View File

@ -188,12 +188,8 @@ class HonAppliance:
async def update(self, force: bool = False) -> None: async def update(self, force: bool = False) -> None:
now = datetime.now() now = datetime.now()
if ( min_age = now - timedelta(seconds=self._MINIMAL_UPDATE_INTERVAL)
force if force or not self._last_update or self._last_update < min_age:
or not self._last_update
or self._last_update
< now - timedelta(seconds=self._MINIMAL_UPDATE_INTERVAL)
):
self._last_update = now self._last_update = now
await self.load_attributes() await self.load_attributes()
self.sync_params_to_command("settings") self.sync_params_to_command("settings")
@ -272,18 +268,23 @@ class HonAppliance:
for command, data in self.commands.items(): for command, data in self.commands.items():
if command == main or target and command not in target: if command == main or target and command not in target:
continue continue
for name, parameter in data.parameters.items():
if base_value := base.parameters.get(name): for name, target_param in data.parameters.items():
if isinstance(base_value, HonParameterRange) and isinstance( if not (base_param := base.parameters.get(name)):
parameter, HonParameterRange return
self.sync_parameter(base_param, target_param)
def sync_parameter(self, main: Parameter, target: Parameter) -> None:
if isinstance(main, HonParameterRange) and isinstance(
target, HonParameterRange
): ):
parameter.max = base_value.max target.max = main.max
parameter.min = base_value.min target.min = main.min
parameter.step = base_value.step target.step = main.step
elif isinstance(parameter, HonParameterRange): elif isinstance(target, HonParameterRange):
parameter.max = int(base_value.value) target.max = int(main.value)
parameter.min = int(base_value.value) target.min = int(main.value)
parameter.step = 1 target.step = 1
elif isinstance(parameter, HonParameterEnum): elif isinstance(target, HonParameterEnum):
parameter.values = base_value.values target.values = main.values
parameter.value = base_value.value target.value = main.value

View File

@ -60,7 +60,8 @@ class ConnectionHandler:
if self._session is None: if self._session is None:
raise exceptions.NoSessionException() raise exceptions.NoSessionException()
response: aiohttp.ClientResponse response: aiohttp.ClientResponse
async with self._intercept(self._session.get, *args, **kwargs) as response: # type: ignore[arg-type] args = self._session.get, *args
async with self._intercept(*args, **kwargs) as response:
yield response yield response
@asynccontextmanager @asynccontextmanager
@ -70,7 +71,8 @@ class ConnectionHandler:
if self._session is None: if self._session is None:
raise exceptions.NoSessionException() raise exceptions.NoSessionException()
response: aiohttp.ClientResponse response: aiohttp.ClientResponse
async with self._intercept(self._session.post, *args, **kwargs) as response: # type: ignore[arg-type] args = self._session.post, *args
async with self._intercept(*args, **kwargs) as response:
yield response yield response
async def close(self) -> None: async def close(self) -> None:

View File

@ -2,8 +2,10 @@ AUTH_API = "https://account2.hon-smarthome.com"
API_URL = "https://api-iot.he.services" API_URL = "https://api-iot.he.services"
API_KEY = "GRCqFhC6Gk@ikWXm1RmnSmX1cm,MxY-configuration" API_KEY = "GRCqFhC6Gk@ikWXm1RmnSmX1cm,MxY-configuration"
APP = "hon" APP = "hon"
# All seen id's (different accounts, different devices) are the same, so I guess this hash is static CLIENT_ID = (
CLIENT_ID = "3MVG9QDx8IX8nP5T2Ha8ofvlmjLZl5L_gvfbT9.HJvpHGKoAS_dcMN8LYpTSYeVFCraUnV.2Ag1Ki7m4znVO6" "3MVG9QDx8IX8nP5T2Ha8ofvlmjLZl5L_gvfbT9."
"HJvpHGKoAS_dcMN8LYpTSYeVFCraUnV.2Ag1Ki7m4znVO6"
)
APP_VERSION = "2.1.2" APP_VERSION = "2.1.2"
OS_VERSION = 31 OS_VERSION = 31
OS = "android" OS = "android"

View File

@ -41,13 +41,15 @@ class HonParameterProgram(HonParameterEnum):
@property @property
def ids(self) -> Dict[int, str]: def ids(self) -> Dict[int, str]:
values = { values: Dict[int, str] = {}
int(p.parameters["prCode"].value): n for name, parameter in self._programs.items():
for i, (n, p) in enumerate(self._programs.items()) if "iot_" in name:
if "iot_" not in n continue
and p.parameters.get("prCode") if parameter.parameters.get("prCode"):
and not ((fav := p.parameters.get("favourite")) and fav.value == "1") continue
} if (fav := parameter.parameters.get("favourite")) and fav.value == "1":
continue
values[int(parameter.parameters["prCode"].value)] = name
return dict(sorted(values.items())) return dict(sorted(values.items()))
def set_value(self, value: str) -> None: def set_value(self, value: str) -> None:

View File

@ -64,9 +64,8 @@ class HonParameterRange(HonParameter):
self._value = value self._value = value
self.check_trigger(value) self.check_trigger(value)
else: else:
raise ValueError( allowed = f"min {self.min} max {self.max} step {self.step}"
f"Allowed: min {self.min} max {self.max} step {self.step} But was: {value}" raise ValueError(f"Allowed: {allowed} But was: {value}")
)
@property @property
def values(self) -> List[str]: def values(self) -> List[str]:

View File

@ -29,33 +29,26 @@ def pretty_print(
whitespace: str = " ", whitespace: str = " ",
) -> str: ) -> str:
result = "" result = ""
if isinstance(data, list): space = whitespace * intend
if key: if (isinstance(data, list) or isinstance(data, dict)) and key:
result += f"{whitespace * intend}{'- ' if is_list else ''}{key}:\n" result += f"{space}{'- ' if is_list else ''}{key}:\n"
intend += 1 intend += 1
if isinstance(data, list):
for i, value in enumerate(data): for i, value in enumerate(data):
result += pretty_print( result += pretty_print(
value, intend=intend, is_list=True, whitespace=whitespace value, intend=intend, is_list=True, whitespace=whitespace
) )
elif isinstance(data, dict): elif isinstance(data, dict):
if key:
result += f"{whitespace * intend}{'- ' if is_list else ''}{key}:\n"
intend += 1
for i, (key, value) in enumerate(sorted(data.items())): for i, (key, value) in enumerate(sorted(data.items())):
if is_list and not i:
result += pretty_print( result += pretty_print(
value, key=key, intend=intend, is_list=True, whitespace=whitespace value,
) key=key,
elif is_list: intend=intend + (is_list if i else 0),
result += pretty_print( is_list=is_list and not i,
value, key=key, intend=intend + 1, whitespace=whitespace whitespace=whitespace,
) )
else: else:
result += pretty_print( result += f"{space}{'- ' if is_list else ''}{key}{': ' if key else ''}{data}\n"
value, key=key, intend=intend, whitespace=whitespace
)
else:
result += f"{whitespace * intend}{'- ' if is_list else ''}{key}{': ' if key else ''}{data}\n"
return result return result

View File

@ -3,6 +3,7 @@ from typing import List, Dict, TYPE_CHECKING, Any, Optional
from pyhon.parameter.enum import HonParameterEnum from pyhon.parameter.enum import HonParameterEnum
from pyhon.parameter.range import HonParameterRange from pyhon.parameter.range import HonParameterRange
from pyhon.typedefs import Parameter
if TYPE_CHECKING: if TYPE_CHECKING:
from pyhon.commands import HonCommand from pyhon.commands import HonCommand
@ -83,29 +84,43 @@ class HonRuleSet:
for rule in rules: for rule in rules:
self._rules.setdefault(key, []).append(rule) self._rules.setdefault(key, []).append(rule)
def _add_trigger(self, parameter: "HonParameter", data: HonRule) -> None: def _extra_rules_matches(self, rule: HonRule) -> bool:
def apply(rule: HonRule) -> None: if rule.extras:
if rule.extras is not None:
for key, value in rule.extras.items(): for key, value in rule.extras.items():
if not self._command.parameters.get(key):
return False
if str(self._command.parameters.get(key)) != str(value): if str(self._command.parameters.get(key)) != str(value):
return return False
if param := self._command.parameters.get(rule.param_key): return True
if value := rule.param_data.get("fixedValue", ""):
if isinstance(param, HonParameterEnum) and set(param.values) != { def _apply_fixed(self, param: Parameter, value: str | float) -> None:
str(value) if isinstance(param, HonParameterEnum) and set(param.values) != {str(value)}:
}:
param.values = [str(value)] param.values = [str(value)]
param.value = str(value)
elif isinstance(param, HonParameterRange): elif isinstance(param, HonParameterRange):
param.value = float(value) param.value = float(value)
return return
param.value = str(value) param.value = str(value)
elif rule.param_data.get("typology") == "enum":
if isinstance(param, HonParameterEnum): def _apply_enum(self, param: Parameter, rule: HonRule) -> None:
if not isinstance(param, HonParameterEnum):
return
if enum_values := rule.param_data.get("enumValues"): if enum_values := rule.param_data.get("enumValues"):
param.values = enum_values.split("|") param.values = enum_values.split("|")
if default_value := rule.param_data.get("defaultValue"): if default_value := rule.param_data.get("defaultValue"):
param.value = default_value param.value = default_value
def _add_trigger(self, parameter: "HonParameter", data: HonRule) -> None:
def apply(rule: HonRule) -> None:
if not self._extra_rules_matches(rule):
return
if not (param := self._command.parameters.get(rule.param_key)):
return
if fixed_value := rule.param_data.get("fixedValue", ""):
self._apply_fixed(param, fixed_value)
elif rule.param_data.get("typology") == "enum":
self._apply_enum(param, rule)
parameter.add_trigger(data.trigger_value, apply, data) parameter.add_trigger(data.trigger_value, apply, data)
def patch(self) -> None: def patch(self) -> None: