diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index e9b9c1102..e5be84334 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -4,7 +4,7 @@ name: Latest commit env: - CACHE_VERSION: 1 + CACHE_VERSION: 3 DEFAULT_PYTHON: "3.9" PRE_COMMIT_HOME: ~/.cache/pre-commit diff --git a/.gitignore b/.gitignore index c07a06a80..834ef6eae 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ build.sh .DS_Store *.pyc +.*.swp __pycache__ /dist/ /*.egg-info diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ee5cdc0a4..582416e2b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,5 +1,22 @@ repos: # Run manually in CI skipping the branch checks + - repo: https://github.com/PyCQA/pylint + rev: v2.12.2 + hooks: + - id: pylint + name: pylint + entry: pylint + language: system + types: [python] + args: + [ + "-rn", # Only display messages + "-sn", # Don't display the score + ] + - repo: https://github.com/PyCQA/isort + rev: 5.10.1 + hooks: + - id: isort - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.1.0 hooks: @@ -75,7 +92,3 @@ repos: types: [python] require_serial: true files: ^plugwise/.+\.py$ -# - repo: https://github.com/PyCQA/isort -# rev: 5.10.1 -# hooks: -# - id: isort diff --git a/plugwise/connections/__init__.py b/plugwise/connections/__init__.py index 0eb4e370a..c06ec122d 100644 --- a/plugwise/connections/__init__.py +++ b/plugwise/connections/__init__.py @@ -27,7 +27,7 @@ def __init__(self, port, parser): self._writer_thread = None ################################################ - ### Open connection ### + # Open connection # ################################################ def connect(self) -> bool: @@ -40,7 +40,7 @@ def _open_connection(self): """Placeholder.""" ################################################ - ### Reader ### + # Reader # ################################################ def _reader_start(self, name): @@ -58,12 +58,14 @@ def _reader_deamon(self): time.sleep(0.01) _LOGGER.debug("Reader daemon stopped") + # TODO: 20220125 function instead of self + # pylint: disable=no-self-use def _read_data(self): """placeholder.""" return b"0000" ################################################ - ### Writer ### + # Writer # ################################################ def _writer_start(self, name: str): @@ -101,7 +103,7 @@ def send(self, message: NodeRequest, callback=None): self._write_queue.put_nowait((message, callback)) ################################################ - ### Connection state ### + # Connection state # ################################################ def is_connected(self): @@ -117,7 +119,7 @@ def write_thread_alive(self): return self._writer_thread.is_alive() if self.run_writer_thread else False ################################################ - ### Close connection ### + # Close connection # ################################################ def disconnect(self): diff --git a/plugwise/controller.py b/plugwise/controller.py index 4396b1a8f..a3382fc12 100644 --- a/plugwise/controller.py +++ b/plugwise/controller.py @@ -280,11 +280,7 @@ def message_handler(self, message): else: self._log_status_message(message) self.message_processor(message) - if ( - message.seq_id != b"FFFF" - and message.seq_id != b"FFFE" - and message.seq_id != b"FFFD" - ): + if message.seq_id not in [b"FFFF", b"FFFE", b"FFFD"]: self._post_message_action( message.seq_id, None, message.__class__.__name__ ) diff --git a/plugwise/helper.py b/plugwise/helper.py index de734e4e5..818081126 100644 --- a/plugwise/helper.py +++ b/plugwise/helper.py @@ -7,7 +7,6 @@ # This way of importing aiohttp is because of patch/mocking in testing (aiohttp timeouts) from aiohttp import BasicAuth, ClientSession, ClientTimeout, ServerTimeoutError -from dateutil import tz from dateutil.parser import parse from defusedxml import ElementTree as etree from munch import Munch @@ -17,24 +16,16 @@ from .constants import ( APPLIANCES, - ATTR_ICON, - ATTR_ID, ATTR_NAME, - ATTR_STATE, ATTR_TYPE, ATTR_UNIT_OF_MEASUREMENT, BINARY_SENSORS, - COOLING_ICON, DEVICE_MEASUREMENTS, - DOMAIN_OBJECTS, ENERGY_KILO_WATT_HOUR, ENERGY_WATT_HOUR, FAKE_LOC, - FLAME_ICON, HEATER_CENTRAL_MEASUREMENTS, - HEATING_ICON, HOME_MEASUREMENTS, - IDLE_ICON, LOCATIONS, POWER_WATT, SENSORS, @@ -49,7 +40,6 @@ ResponseError, ) from .util import ( - determine_selected, escape_illegal_xml_characters, format_measure, in_between, @@ -165,9 +155,9 @@ def schemas_schedule_temp(schedules, name): for i in range(length): result_1 = schema_list[i][0] start = schema_list[i][1] - n = (i + 1) % (length - 1) - result_2 = schema_list[n][0] - end = schema_list[n][1] + j = (i + 1) % (length - 1) + result_2 = schema_list[j][0] + end = schema_list[j][1] now = dt.datetime.now().time() if ( result_1 == dt.datetime.now().weekday() @@ -326,6 +316,39 @@ async def close_connection(self): class SmileHelper: """The SmileHelper class.""" + def __init__(self): + """Set the constructor for this class.""" + self._appl_data = None + self._appliances = None + self._cooling_present = None + self._cp_state = None + self._devices = None + self._domain_objects = None + self._heater_id = None + self._home_location = None + self._last_active = {} + self._loc_data = None + self._locations = None + self._modules = None + self._on_off_device = None + self._ot_device = None + self._outdoor_temp = None + self._sm_thermostat = None + self._thermo_locs = None + + self._smile_legacy = None + self._stretch_v2 = None + self._stretch_v3 = None + + self.cooling_active = None + self.gateway_id = None + self.gw_data = {} + self.gw_devices = {} + + self.smile_name = None + self.smile_type = None + self.smile_version = [] + def _locations_legacy(self): """Helper-function for _all_locations(). Create locations for legacy devices. @@ -420,7 +443,8 @@ def _get_module_data(self, appliance, locator, mod_type): if appl_search is not None: link_id = appl_search.attrib["id"] locator = f".//{mod_type}[@id='{link_id}']...." - if (module := self._modules.find(locator)) is not None: + module = self._modules.find(locator) + if module is not None: v_name = module.find("vendor_name").text v_model = module.find("vendor_model").text hw_version = module.find("hardware_version").text diff --git a/plugwise/messages/responses.py b/plugwise/messages/responses.py index 30c1e490c..50380bd64 100644 --- a/plugwise/messages/responses.py +++ b/plugwise/messages/responses.py @@ -66,7 +66,7 @@ def deserialize(self, response): self.msg_id = response[4:8] self.seq_id = response[8:12] response = response[12:] - if self.format_size == MESSAGE_SMALL or self.format_size == MESSAGE_LARGE: + if self.format_size in [MESSAGE_SMALL, MESSAGE_LARGE]: self.ack_id = response[:4] response = response[4:] if self.format_size != MESSAGE_SMALL: @@ -337,6 +337,8 @@ def __init__(self): self.datetime = DateTime() self.last_logaddr = LogAddr(0, length=8) self.relay_state = Int(0, length=2) + # TODO: 20220126 snake-style + # pylint: disable=invalid-name self.hz = Int(0, length=2) self.hw_ver = String(None, length=12) self.fw_ver = UnixTimestamp(0) diff --git a/plugwise/nodes/circle.py b/plugwise/nodes/circle.py index 59760eb63..f215e2b85 100644 --- a/plugwise/nodes/circle.py +++ b/plugwise/nodes/circle.py @@ -685,8 +685,9 @@ def _response_energy_counters(self, message: CircleEnergyCountersResponse): self._energy_last_populated_slot = _slot # Store most recent timestamp of collected pulses - if self._energy_last_collected_timestamp < _log_timestamp: - self._energy_last_collected_timestamp = _log_timestamp + self._energy_last_collected_timestamp = max( + self._energy_last_collected_timestamp, _log_timestamp + ) # Trigger history rollover if ( @@ -746,11 +747,11 @@ def _response_energy_counters(self, message: CircleEnergyCountersResponse): ) self._update_energy_today_now(False, _history_rollover, _midnight_rollover) else: - _LOGGER.info( - "_response_energy_counters for %s | self._energy_history_collecting running", - self.mac, - str(_local_midnight_timestamp), + logstring = ( + "_response_energy_counters for %s | self._energy_history_collecting running %s" + % (self.mac, str(_local_midnight_timestamp)) ) + _LOGGER.info(logstring) # Cleanup energy history for more than 8 day's ago _8_days_ago = datetime.utcnow().replace( diff --git a/plugwise/nodes/scan.py b/plugwise/nodes/scan.py index 0d63092ea..32ee88093 100644 --- a/plugwise/nodes/scan.py +++ b/plugwise/nodes/scan.py @@ -97,10 +97,14 @@ def _process_switch_group(self, message): self.mac, ) + # TODO: 20220125 snakestyle name + # pylint: disable=invalid-name def CalibrateLight(self, callback=None): """Queue request to calibration light sensitivity""" self._queue_request(ScanLightCalibrateRequest(self._mac), callback) + # TODO: 20220125 snakestyle name + # pylint: disable=invalid-name def Configure_scan( self, motion_reset_timer=SCAN_MOTION_RESET_TIMER, @@ -126,6 +130,8 @@ def Configure_scan( callback, ) + # TODO: 20220125 snakestyle name + # pylint: disable=invalid-name def SetMotionAction(self, callback=None): """Queue Configure Scan to signal motion""" # TODO: diff --git a/plugwise/nodes/sed.py b/plugwise/nodes/sed.py index 128a572ea..d92c124d1 100644 --- a/plugwise/nodes/sed.py +++ b/plugwise/nodes/sed.py @@ -75,14 +75,13 @@ def _process_awake_response(self, message): str(message.awake_type.value), self.mac, ) - if ( - message.awake_type.value == SED_AWAKE_MAINTENANCE - or message.awake_type.value == SED_AWAKE_FIRST - or message.awake_type.value == SED_AWAKE_STARTUP - or message.awake_type.value == SED_AWAKE_BUTTON - ): - for request in self._sed_requests: - (request_message, callback) = self._sed_requests[request] + if message.awake_type.value in [ + SED_AWAKE_MAINTENANCE, + SED_AWAKE_FIRST, + SED_AWAKE_STARTUP, + SED_AWAKE_BUTTON, + ]: + for request_message, callback in self._sed_requests.items(): _LOGGER.info( "Send queued %s message to SED node %s", request_message.__class__.__name__, @@ -136,6 +135,8 @@ def _wake_up_interval_accepted(self): """Callback after wake up interval is received and accepted by SED.""" self._wake_up_interval = self._new_maintenance_interval + # TODO: 20220125 snakestyle name + # pylint: disable=invalid-name def Configure_SED( self, stay_active=SED_STAY_ACTIVE, diff --git a/plugwise/smile.py b/plugwise/smile.py index b0f87f1e3..bf069fbee 100644 --- a/plugwise/smile.py +++ b/plugwise/smile.py @@ -1,14 +1,10 @@ """Use of this source code is governed by the MIT license found in the LICENSE file. Plugwise backend module for Home Assistant Core. """ -import asyncio -import copy import logging import aiohttp -from defusedxml import ElementTree as etree - # Dict as class from munch import Munch @@ -74,11 +70,11 @@ def _all_device_data(self): self._append_special(data, dev_id, temp_bs_dict, temp_s_dict) dev_and_data.update(data) - if temp_bs_dict != {}: + if temp_bs_dict: dev_and_data["binary_sensors"] = temp_bs_dict - if temp_s_dict != {}: + if temp_s_dict: dev_and_data["sensors"] = temp_s_dict - if temp_sw_dict != {}: + if temp_sw_dict: dev_and_data["switches"] = temp_sw_dict self.gw_devices[dev_id] = dev_and_data @@ -278,34 +274,10 @@ def __init__( timeout, websession, ) + SmileData.__init__(self) - self._on_off_device = False - self._ot_device = False - self._appliances = None - self._appl_data = None - self._cooling_present = False - self._domain_objects = None - self._heater_id = None - self._home_location = None - self._last_active = {} - self._locations = None - self._modules = None self._notifications = {} - self._outdoor_temp = None - self._sm_thermostat = None - self._smile_legacy = False - self._stretch_v2 = False - self._stretch_v3 = False - self._thermo_locs = None - - self.cooling_active = False - self.gateway_id = None - self.gw_data = {} - self.gw_devices = {} self.smile_hostname = None - self.smile_name = None - self.smile_type = None - self.smile_version = () async def connect(self): """Connect to Plugwise device and determine its name, type and version.""" @@ -468,7 +440,7 @@ async def async_update(self): data = self._get_device_data(dev_id) for key, value in list(data.items()): if key in dev_dict: - self.gw_devices[dev_id][key] = value + dev_dict[key] = value if "binary_sensors" in dev_dict: for key, value in list(data.items()): update_helper( @@ -531,7 +503,7 @@ async def set_schedule_state(self, loc_id, name, state): return await self._set_schedule_state_legacy(name, state) schema_rule = self._rule_ids_by_name(str(name), loc_id) - if schema_rule == {} or schema_rule is None: + if not schema_rule or schema_rule is None: return False schema_rule_id = next(iter(schema_rule)) diff --git a/plugwise/stick.py b/plugwise/stick.py index c14b416f1..8c1fd98a1 100644 --- a/plugwise/stick.py +++ b/plugwise/stick.py @@ -610,21 +610,21 @@ def _update_loop(self): if datetime.now().day != day_of_month: day_of_month = datetime.now().day _sync_clock = True - for mac in self._device_nodes: - if self._device_nodes[mac]: - if self._device_nodes[mac].battery_powered: + for mac, device in self._device_nodes.items(): + if device: + if device.battery_powered: # Check availability state of SED's self._check_availability_of_seds(mac) else: # Do ping request for all non SED's - self._device_nodes[mac].do_ping() + device.do_ping() - if self._device_nodes[mac].measures_power: + if device.measures_power: # Request current power usage - self._device_nodes[mac].request_power_update() + device.request_power_update() # Sync internal clock of power measure nodes once a day if _sync_clock: - self._device_nodes[mac].sync_clock() + device.sync_clock() _sync_clock = False # Do a single ping for undiscovered nodes once per 10 update cycles @@ -669,8 +669,8 @@ def auto_update(self, timer=None): # Timer based on a minimum of 5 seconds + 1 second for each node supporting power measurement if not self._auto_update_manually: count_nodes = 0 - for mac in self._device_nodes: - if self._device_nodes[mac].measures_power: + for _, node in self._device_nodes.items(): + if node.measures_power: count_nodes += 1 self._auto_update_timer = 5 + (count_nodes * 1) _LOGGER.info( @@ -680,7 +680,7 @@ def auto_update(self, timer=None): if not self._run_update_thread: self._update_thread.start() - ### Helper functions ### + # Helper functions def do_callback(self, callback_type, callback_arg=None): """Helper to execute registered callbacks for specified callback type.""" if callback_type in self._stick_callbacks: diff --git a/pyproject.toml b/pyproject.toml index 28bc2041b..cb1bca1de 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,11 +24,11 @@ ignore = [ # Use a conservative default here; 2 should speed up most setups and not hurt # any too bad. Override on command line as appropriate. # Disabled for now: https://github.com/PyCQA/pylint/issues/3584 -#jobs = 2 +jobs = 2 # Disabled pylint_strict_informational for codefactor -#load-plugins = [ -# "pylint_strict_informational", -#] +load-plugins = [ + "pylint_strict_informational", +] persistent = false extension-pkg-whitelist = [ "ciso8601", @@ -67,8 +67,10 @@ disable = [ "format", "abstract-class-little-used", "abstract-method", + "consider-using-f-string", "cyclic-import", "duplicate-code", + "fixme", "inconsistent-return-statements", "locally-disabled", "not-context-manager", diff --git a/scripts/tests_and_coverage.sh b/scripts/tests_and_coverage.sh index 769a634f7..2269173cf 100755 --- a/scripts/tests_and_coverage.sh +++ b/scripts/tests_and_coverage.sh @@ -17,7 +17,7 @@ if [ -f "${my_venv}/bin/activate" ]; then echo "-----------------------------------------------------------" echo "Running plugwise/smile.py through pytest including coverage" echo "-----------------------------------------------------------" - PYTHONPATH=$(pwd) pytest -rpP --log-level debug tests/test_smile.py --cov='.' --no-cov-on-fail --cov-report term-missing + PYTHONPATH=$(pwd) pytest -rpP --log-level debug tests/test_smile.py --cov='.' --no-cov-on-fail --cov-report term-missing && echo "... flake8-ing ..." && flake8 plugwise/ tests/ && echo "... pylint-ing ..." && pylint plugwise/ tests/ && echo "... black-ing ..." && black plugwise/ tests/ else echo "Virtualenv available, bailing out" exit 2