diff --git a/.bandit b/.bandit new file mode 100644 index 000000000..3464de149 --- /dev/null +++ b/.bandit @@ -0,0 +1,2 @@ +[bandit] +skips: B106 diff --git a/.coveragerc b/.coveragerc index aee14b00d..4f0c6b29c 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,6 +2,7 @@ source = plugwise omit= */venv/* + setup.py plugwise/connections/* plugwise/message.py plugwise/messages/* diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 35012fd31..82c7b95ce 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -77,6 +77,8 @@ jobs: uses: actions/setup-python@v2 with: python-version: ${{ env.DEFAULT_PYTHON }} + - name: Pre-black + uses: psf/black@stable - name: Restore base Python ${{ env.DEFAULT_PYTHON }} virtual environment id: cache-venv uses: actions/cache@v2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 2349a6ffc..5c3f3202b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 0.8.2 - Code quality improvements + - Switch Smile to defusedxml from lxml (improving security) + - Lint and flake recommendations fixed + - Project CI changes + ## 0.8.1 - Standardize logging for stick ## 0.8.0 - Merged Smile/USB module diff --git a/plugwise/__init__.py b/plugwise/__init__.py index 1b05cd9f3..34efdbcf3 100644 --- a/plugwise/__init__.py +++ b/plugwise/__init__.py @@ -1,6 +1,6 @@ """Plugwise module.""" -__version__ = "0.8.2a0" +__version__ = "0.8.2a1" from plugwise.smile import Smile from plugwise.stick import stick diff --git a/plugwise/connections/__init__.py b/plugwise/connections/__init__.py index e69de29bb..dde3e99d0 100644 --- a/plugwise/connections/__init__.py +++ b/plugwise/connections/__init__.py @@ -0,0 +1 @@ +"""Plugwise connections.""" diff --git a/plugwise/connections/connection.py b/plugwise/connections/connection.py index b4b6ab290..cf430e650 100644 --- a/plugwise/connections/connection.py +++ b/plugwise/connections/connection.py @@ -1,8 +1,4 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Base for serial or socket connections -""" +"""Base for serial or socket connections.""" import logging import queue import threading @@ -15,9 +11,10 @@ class StickConnection: - """ Generic Plugwise stick connection""" + """Generic Plugwise stick connection.""" def __init__(self, port, stick=None): + """Initialize StickConnection.""" self.port = port self.stick = stick self.run_reader_thread = False @@ -25,17 +22,21 @@ def __init__(self, port, stick=None): self._is_connected = False self._writer = None + self._reader_thread = None + self._write_queue = None + self._writer_thread = None + ################################################ ### Open connection ### ################################################ def connect(self): - """Open the connection""" + """Open the connection.""" if not self._is_connected: self._open_connection() def _open_connection(self): - """Placeholder to initialize the connection""" + """Placeholder to initialize the connection.""" raise NotImplementedError ################################################ @@ -43,13 +44,13 @@ def _open_connection(self): ################################################ def _reader_start(self, name): - """Start the reader thread to receive data""" - self._reader_thread = threading.Thread(None, self._reader_daemon, name, (), {}) + """Start the reader thread to receive data.""" + self._reader_thread = threading.Thread(None, self._reader_deamon, name, (), {}) self.run_reader_thread = True self._reader_thread.start() - def _reader_daemon(self): - """Thread to collect available data from connection""" + def _reader_deamon(self): + """Thread to collect available data from connection.""" while self.run_reader_thread: data = self._read_data() if data: @@ -58,7 +59,7 @@ def _reader_daemon(self): _LOGGER.debug("Reader daemon stopped") def _read_data(self): - """Placeholder to receive message from the connection""" + """Placeholder to receive message from the connection.""" raise NotImplementedError ################################################ @@ -66,7 +67,7 @@ def _read_data(self): ################################################ def _writer_start(self, name: str): - """Start the writer thread to send data""" + """Start the writer thread to send data.""" self._write_queue = queue.Queue() self._writer_thread = threading.Thread(None, self._writer_daemon, name, (), {}) self._writer_thread.daemon = True @@ -105,15 +106,15 @@ def send(self, message: PlugwiseMessage, callback=None): ################################################ def is_connected(self): - """Return connection state""" + """Return connection state.""" return self._is_connected def read_thread_alive(self): - """Return state of write thread""" + """Return state of write thread.""" return self._reader_thread.isAlive() if self.run_reader_thread else False def write_thread_alive(self): - """Return state of write thread""" + """Return state of write thread.""" return self._writer_thread.isAlive() if self.run_writer_thread else False ################################################ @@ -121,7 +122,7 @@ def write_thread_alive(self): ################################################ def disconnect(self): - """Close the connection""" + """Close the connection.""" if self._is_connected: self._is_connected = False self.run_writer_thread = False @@ -133,5 +134,5 @@ def disconnect(self): self._close_connection() def _close_connection(self): - """Placeholder to close the port""" + """Placeholder to close the port.""" raise NotImplementedError diff --git a/plugwise/connections/serial.py b/plugwise/connections/serial.py index d98378866..6dcecd08d 100644 --- a/plugwise/connections/serial.py +++ b/plugwise/connections/serial.py @@ -1,8 +1,4 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Serial connection -""" +"""Serial connection.""" import logging import serial @@ -11,13 +7,11 @@ from plugwise.constants import BAUD_RATE, BYTE_SIZE, STOPBITS from plugwise.exceptions import PortError -# from plugwise.message import PlugwiseMessage - _LOGGER = logging.getLogger(__name__) class PlugwiseUSBConnection(StickConnection): - """simple wrapper around serial module""" + """Simple wrapper around serial module.""" def __init__(self, port, stick=None): super().__init__(port, stick) @@ -26,8 +20,10 @@ def __init__(self, port, stick=None): self._stopbits = STOPBITS self._parity = serial.PARITY_NONE + self._serial = None + def _open_connection(self): - """Open serial port""" + """Open serial port.""" _LOGGER.debug("Open serial port %s", self.port) try: self._serial = serial.Serial( @@ -83,7 +79,7 @@ def _read_data(self): return None def _write_data(self, data): - """Write data to serial port""" + """Write data to serial port.""" try: self._serial.write(data) except serial.serialutil.SerialException as err: diff --git a/plugwise/connections/socket.py b/plugwise/connections/socket.py index 49b204cd3..69efe43cf 100644 --- a/plugwise/connections/socket.py +++ b/plugwise/connections/socket.py @@ -1,23 +1,15 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Socket connection -""" +"""Socket connection.""" import logging import socket from plugwise.connections.connection import StickConnection -from plugwise.constants import SLEEP_TIME from plugwise.exceptions import PortError -from plugwise.message import PlugwiseMessage _LOGGER = logging.getLogger(__name__) class SocketConnection(StickConnection): - """ - Wrapper for Socket connection configuration - """ + """Wrapper for Socket connection configuration.""" def __init__(self, port, stick=None): super().__init__(port, stick) @@ -27,8 +19,10 @@ def __init__(self, port, stick=None): self._socket_port = int(port_split[1]) self._socket_address = (self._socket_host, self._socket_port) + self._socket = None + def _open_connection(self): - """Open socket""" + """Open socket.""" _LOGGER.debug( "Open socket to host '%s' at port %s", self._socket_host, @@ -87,7 +81,7 @@ def _read_data(self): return None def _write_data(self, data): - """Write data to socket""" + """Write data to socket.""" try: self._socket.send(data) except Exception as err: diff --git a/plugwise/exceptions.py b/plugwise/exceptions.py index 10b39dc04..215ec81ce 100644 --- a/plugwise/exceptions.py +++ b/plugwise/exceptions.py @@ -1,4 +1,4 @@ -""" Copyright (C) 2011 Sven Petai , use of this source code is governed by the MIT license found in the LICENSE file.""" +"""Plugwise Exceptions.""" class PlugwiseException(Exception): diff --git a/plugwise/message.py b/plugwise/message.py index 24eb91c62..5367846ab 100644 --- a/plugwise/message.py +++ b/plugwise/message.py @@ -1,28 +1,16 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Base for Plugwise messages -""" +"""Base for Plugwise messages.""" from plugwise.constants import MESSAGE_FOOTER, MESSAGE_HEADER, UTF8_DECODE from plugwise.util import crc_fun -class ParserError(Exception): - """ - Error when invalid message is received - """ - - pass +class PlugwiseMessage: + """Plugwise message base.""" + # TODO: none of the self objects are predefined -class PlugwiseMessage: def serialize(self): - """ - return message in a serialized format that can be sent out on wire - - return: bytes - """ + """Return message in a serialized format that can be sent out on wire.""" args = b"".join(a.serialize() for a in self.args) msg = self.ID if self.mac != "": @@ -32,4 +20,5 @@ def serialize(self): return MESSAGE_HEADER + msg + checksum + MESSAGE_FOOTER def calculate_checksum(self, s): + """Calculate crc checksum.""" return bytes("%04X" % crc_fun(s), UTF8_DECODE) diff --git a/plugwise/messages/__init__.py b/plugwise/messages/__init__.py index 5f06c84b9..fa8ccd849 100644 --- a/plugwise/messages/__init__.py +++ b/plugwise/messages/__init__.py @@ -1 +1 @@ -# Use of this source code is governed by the MIT license found in the LICENSE file. +"""Plugwise messaging.""" diff --git a/plugwise/messages/requests.py b/plugwise/messages/requests.py index 2d182fbd6..2807772b4 100644 --- a/plugwise/messages/requests.py +++ b/plugwise/messages/requests.py @@ -1,8 +1,4 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -All known request messages to be send to plugwise devices -""" +"""All known request messages to be send to plugwise devices.""" from plugwise.constants import MESSAGE_FOOTER, MESSAGE_HEADER from plugwise.message import PlugwiseMessage from plugwise.util import ( @@ -18,9 +14,7 @@ class NodeRequest(PlugwiseMessage): - """ - Base class for request messages to be send from by USB-Stick. - """ + """Base class for request messages to be send from by USB-Stick.""" def __init__(self, mac): PlugwiseMessage.__init__(self) @@ -29,8 +23,7 @@ def __init__(self, mac): class NodeNetworkInfoRequest(NodeRequest): - """ - TODO: PublicNetworkInfoRequest + """TODO: PublicNetworkInfoRequest No arguments """ @@ -47,9 +40,6 @@ class CirclePlusConnectRequest(NodeRequest): ID = b"0004" - def __init__(self, mac): - super().__init__(self, mac) - # This message has an exceptional format and therefore need to override the serialize method def serialize(self): # This command has args: byte: key, byte: networkinfo.index, ulong: networkkey = 0 @@ -70,7 +60,7 @@ class NodeAddRequest(NodeRequest): def __init__(self, mac, accept: bool): super().__init__(mac) - accept_value = 1 if accept is True else 0 + accept_value = 1 if accept else 0 self.args.append(Int(accept_value, length=2)) # This message has an exceptional format (MAC at end of message) @@ -95,7 +85,7 @@ class NodeAllowJoiningRequest(NodeRequest): def __init__(self, accept: bool): super().__init__("") # TODO: Make sure that '01' means enable, and '00' disable joining - val = 1 if accept is True else 0 + val = 1 if accept else 0 self.args.append(Int(val, length=2)) @@ -193,7 +183,7 @@ class CircleSwitchRelayRequest(NodeRequest): def __init__(self, mac, on): super().__init__(mac) - val = 1 if on is True else 0 + val = 1 if on else 0 self.args.append(Int(val, length=2)) @@ -296,7 +286,7 @@ class CircleEnableScheduleRequest(NodeRequest): def __init__(self, mac, on): super().__init__(mac) - val = 1 if on is True else 0 + val = 1 if on else 0 self.args.append(Int(val, length=2)) # the second parameter is always 0x01 self.args.append(Int(1, length=2)) @@ -345,7 +335,7 @@ class NodeBroadcastGroupSwitchRequest(NodeRequest): def __init__(self, group_mac, switch_state: bool): super().__init__(group_mac) - val = 1 if switch_state is True else 0 + val = 1 if switch_state else 0 self.args.append(Int(val, length=2)) @@ -392,7 +382,7 @@ def __init__( stay_active_val = Int(stay_active, length=2) sleep_for_val = Int(sleep_for, length=4) maintenance_interval_val = Int(maintenance_interval, length=4) - val = 1 if sync_clock is True else 0 + val = 1 if sync_clock else 0 clock_sync_val = Int(val, length=2) clock_interval_val = Int(clock_interval, length=4) self.args += [ @@ -489,7 +479,7 @@ def __init__(self, mac, reset_timer: int, sensitivity: int, light: bool): reset_timer_value = Int(reset_timer, length=2) # Sensitivity: HIGH(0x14), MEDIUM(0x1E), OFF(0xFF) sensitivity_value = Int(sensitivity, length=2) - light_temp = 1 if light is True else 0 + light_temp = 1 if light else 0 light_value = Int(light_temp, length=2) self.args += [ sensitivity_value, @@ -534,6 +524,6 @@ class CircleInitialRelaisStateRequest(NodeRequest): def __init__(self, mac, configure: bool, relais_state: bool): super().__init__(mac) - set_or_get = Int(1 if configure is True else 0, length=2) - relais = Int(1 if relais_state is True else 0, length=2) + set_or_get = Int(1 if configure else 0, length=2) + relais = Int(1 if relais_state else 0, length=2) self.args += [set_or_get, relais] diff --git a/plugwise/messages/responses.py b/plugwise/messages/responses.py index 690cdadbd..e23e8508a 100644 --- a/plugwise/messages/responses.py +++ b/plugwise/messages/responses.py @@ -1,8 +1,4 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -All known response messages to be received from plugwise devices -""" +"""All known response messages to be received from plugwise devices.""" from datetime import datetime from plugwise.constants import ( @@ -143,7 +139,7 @@ def __len__(self): return 18 + arglen def deserialize(self, response): - super().deserialize(self, response) + super().deserialize(response) # Clear first two characters of mac ID, as they contain part of the short PAN-ID self.new_node_mac_id.value = b"00" + self.new_node_mac_id.value[2:] diff --git a/plugwise/node.py b/plugwise/node.py index a7b619db5..5c6d6268e 100644 --- a/plugwise/node.py +++ b/plugwise/node.py @@ -1,13 +1,8 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -General node object to control associated plugwise nodes like: Circle+, Circle, Scan, Stealth -""" +"""General node object to control associated plugwise nodes like: Circle+, Circle, Scan, Stealth.""" from datetime import datetime import logging from plugwise.constants import ( - HA_SWITCH, HW_MODELS, SENSOR_AVAILABLE, SENSOR_PING, @@ -33,11 +28,11 @@ class PlugwiseNode: - """Base class for a Plugwise node.""" + """ Base class for a Plugwise node """ def __init__(self, mac, address, stick): mac = mac.upper() - if validate_mac(mac) is False: + if not validate_mac(mac): _LOGGER.debug( "MAC address is in unexpected format: %s", str(mac), @@ -60,8 +55,8 @@ def __init__(self, mac, address, stick): self._firmware_version = None self._relay_state = False self._last_log_address = None - self._last_log_collected = False - self._last_info_message = None + self.last_log_collected = False + self.last_info_message = None self._features = None def get_node_type(self) -> str: @@ -70,16 +65,16 @@ def get_node_type(self) -> str: hw_model = HW_MODELS.get(self._hardware_version[4:10], None) if hw_model: return hw_model - else: - # Try again with reversed order - hw_model = HW_MODELS.get( - self._hardware_version[-2:] - + self._hardware_version[-4:-2] - + self._hardware_version[-6:-4], - None, - ) - if hw_model: - return hw_model + + # Try again with reversed order + hw_model = HW_MODELS.get( + self._hardware_version[-2:] + + self._hardware_version[-4:-2] + + self._hardware_version[-6:-4], + None, + ) + if hw_model: + return hw_model return "Unknown" def is_sed(self) -> bool: @@ -104,8 +99,8 @@ def get_available(self) -> bool: def set_available(self, state, request_info=False): """Set current network state of plugwise node.""" - if state is True: - if self._available is False: + if state: + if not self._available: self._available = True _LOGGER.debug( "Mark node %s available", @@ -113,9 +108,9 @@ def set_available(self, state, request_info=False): ) self.do_callback(SENSOR_AVAILABLE["id"]) if request_info: - self._request_info() + self.request_info() else: - if self._available is True: + if self._available: self._available = False _LOGGER.debug( "Mark node %s unavailable", @@ -165,7 +160,7 @@ def get_ping(self) -> int: return self.ping_ms return 0 - def _request_info(self, callback=None): + def request_info(self, callback=None): """Request info from node""" self.stick.send( NodeInfoRequest(self.mac), @@ -271,10 +266,10 @@ def _process_info_response(self, message): self._hardware_version = message.hw_ver.value.decode(UTF8_DECODE) self._firmware_version = message.fw_ver.value self._node_type = message.node_type.value - self._last_info_message = message.timestamp + self.last_info_message = message.timestamp if self._last_log_address != message.last_logaddr.value: self._last_log_address = message.last_logaddr.value - self._last_log_collected = False + self.last_log_collected = False _LOGGER.debug("Node type = %s", self.get_node_type()) if not self.is_sed: _LOGGER.debug("Relay state = %s", str(self._relay_state)) diff --git a/plugwise/nodes/__init__.py b/plugwise/nodes/__init__.py index 646e80544..7845294f4 100644 --- a/plugwise/nodes/__init__.py +++ b/plugwise/nodes/__init__.py @@ -1,4 +1,4 @@ -# Use of this source code is governed by the MIT license found in the LICENSE file. +"""Plugwise nodes.""" from plugwise.nodes.circle import PlugwiseCircle from plugwise.nodes.circle_plus import PlugwiseCirclePlus diff --git a/plugwise/nodes/circle.py b/plugwise/nodes/circle.py index ba5c48c8c..bf21c68c1 100644 --- a/plugwise/nodes/circle.py +++ b/plugwise/nodes/circle.py @@ -1,9 +1,5 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Plugwise Circle node object -""" -from datetime import date, datetime, timedelta +"""Plugwise Circle node object.""" +from datetime import datetime, timedelta import logging from plugwise.constants import ( @@ -20,14 +16,12 @@ SENSOR_POWER_CONSUMPTION_TODAY, SENSOR_POWER_CONSUMPTION_YESTERDAY, SENSOR_POWER_PRODUCTION_CURRENT_HOUR, - SENSOR_POWER_PRODUCTION_PREVIOUS_HOUR, SENSOR_POWER_USE, SENSOR_POWER_USE_LAST_8_SEC, SENSOR_RSSI_IN, SENSOR_RSSI_OUT, SWITCH_RELAY, ) -from plugwise.message import PlugwiseMessage from plugwise.messages.requests import ( CircleCalibrationRequest, CircleClockGetRequest, @@ -39,13 +33,11 @@ from plugwise.messages.responses import ( CircleCalibrationResponse, CircleClockResponse, - CirclePlusScanResponse, CirclePowerBufferResponse, CirclePowerUsageResponse, NodeAckLargeResponse, ) from plugwise.node import PlugwiseNode -from plugwise.util import Int _LOGGER = logging.getLogger(__name__) @@ -319,11 +311,11 @@ def pulses_to_kWs(self, pulses, seconds=1): ) calc_value = corrected_pulses / PULSES_PER_KW_SECOND / seconds # Fix minor miscalculations - if calc_value < 0.001 and calc_value > -0.001: + if -0.001 < calc_value < 0.001: calc_value = 0.0 return calc_value - def _request_power_buffer(self, log_address=None, callback=None): + def request_power_buffer(self, log_address=None, callback=None): """Request power log of specified address""" if log_address is None: log_address = self._last_log_address @@ -354,7 +346,7 @@ def _response_power_buffer(self, message): each response contains 4 log buffers and each log buffer contains data for 1 hour """ if message.logaddr.value == self._last_log_address: - self._last_log_collected = True + self.last_log_collected = True # Collect logged power usage for i in range(1, 5): if getattr(message, "logdate%d" % (i,)).value is not None: diff --git a/plugwise/nodes/circle_plus.py b/plugwise/nodes/circle_plus.py index 0f19b378b..46cff7862 100644 --- a/plugwise/nodes/circle_plus.py +++ b/plugwise/nodes/circle_plus.py @@ -1,13 +1,8 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Plugwise Circle+ node object -""" +"""Plugwise Circle+ node object.""" from datetime import datetime import logging from plugwise.constants import MAX_TIME_DRIFT, UTF8_DECODE -from plugwise.message import PlugwiseMessage from plugwise.messages.requests import ( CirclePlusRealTimeClockGetRequest, CirclePlusRealTimeClockSetRequest, @@ -110,7 +105,7 @@ def _process_scan_response(self, message): CirclePlusScanRequest(self.mac, node_address) ) break - elif node_address == 63: + if node_address == 63: scan_complete = True if scan_complete and self._scan_for_nodes_callback: self._scan_for_nodes_callback(self._plugwise_nodes) diff --git a/plugwise/nodes/scan.py b/plugwise/nodes/scan.py index d73b6faf0..c677dda3e 100644 --- a/plugwise/nodes/scan.py +++ b/plugwise/nodes/scan.py @@ -1,18 +1,12 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Plugwise Scan node object -""" +"""Plugwise Scan node object.""" import logging from plugwise.constants import ( ACK_SCAN_PARAMETERS_SET, HA_BINARY_SENSOR, HA_SENSOR, - NACK_SCAN_PARAMETERS_SET, SCAN_DAYLIGHT_MODE, SCAN_MOTION_RESET_TIMER, - SCAN_SENSITIVITY, SCAN_SENSITIVITY_HIGH, SCAN_SENSITIVITY_MEDIUM, SCAN_SENSITIVITY_OFF, @@ -22,7 +16,6 @@ SENSOR_RSSI_IN, SENSOR_RSSI_OUT, ) -from plugwise.message import PlugwiseMessage from plugwise.messages.requests import ScanConfigureRequest, ScanLightCalibrateRequest from plugwise.messages.responses import NodeAckResponse, NodeSwitchGroupResponse from plugwise.nodes.sed import NodeSED diff --git a/plugwise/nodes/sed.py b/plugwise/nodes/sed.py index a1c454919..7556bf2bc 100644 --- a/plugwise/nodes/sed.py +++ b/plugwise/nodes/sed.py @@ -1,24 +1,18 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. +"""Plugwise SED (Sleeping Endpoint Device) base object.""" -Plugwise SED (Sleeping Endpoint Device) base object +# TODO: +# - Expose awake state as sensor +# - Set available state after 2 missed awake messages -TODO: -- Expose awake state as sensor -- Set available state after 2 missed awake messages - -""" import logging from plugwise.constants import ( ACK_SLEEP_SET, - NACK_SLEEP_SET, SED_AWAKE_BUTTON, SED_AWAKE_FIRST, SED_AWAKE_MAINTENANCE, SED_AWAKE_STARTUP, SED_AWAKE_STATE, - SED_AWAKE_UNKNOWN, SED_CLOCK_INTERVAL, SED_CLOCK_SYNC, SED_MAINTENANCE_INTERVAL, @@ -28,7 +22,6 @@ SENSOR_RSSI_IN, SENSOR_RSSI_OUT, ) -from plugwise.message import PlugwiseMessage from plugwise.messages.requests import ( NodeInfoRequest, NodePingRequest, @@ -46,9 +39,11 @@ class NodeSED(PlugwiseNode): def __init__(self, mac, address, stick): super().__init__(mac, address, stick) self._SED_requests = {} - self._maintenance_interval = SED_MAINTENANCE_INTERVAL + self.maintenance_interval = SED_MAINTENANCE_INTERVAL self._new_maintenance_interval = None + self._wake_up_interval = None + def is_sed(self) -> bool: """ Return if True if node SED (battery powered)""" return True @@ -61,7 +56,7 @@ def _on_message(self, message): self._process_awake_response(message) elif isinstance(message, NodeAckLargeResponse): if message.ack_id == ACK_SLEEP_SET: - self._maintenance_interval = self._new_maintenance_interval + self.maintenance_interval = self._new_maintenance_interval else: self._on_SED_message(message) else: @@ -109,7 +104,7 @@ def _queue_request(self, request_message, callback=None): callback, ) - def _request_info(self, callback=None): + def request_info(self, callback=None): """ Request info from node""" self._queue_request( NodeInfoRequest(self.mac), diff --git a/plugwise/nodes/sense.py b/plugwise/nodes/sense.py index 565bf23be..a00dced44 100644 --- a/plugwise/nodes/sense.py +++ b/plugwise/nodes/sense.py @@ -1,8 +1,4 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Plugwise Sense node object -""" +"""Plugwise Sense node object.""" import logging from plugwise.constants import ( @@ -18,7 +14,6 @@ SENSOR_RSSI_OUT, SENSOR_TEMPERATURE, ) -from plugwise.message import PlugwiseMessage from plugwise.messages.responses import SenseReportResponse from plugwise.nodes.sed import NodeSED diff --git a/plugwise/nodes/stealth.py b/plugwise/nodes/stealth.py index ad6aa9fe2..a0c34d60c 100644 --- a/plugwise/nodes/stealth.py +++ b/plugwise/nodes/stealth.py @@ -1,14 +1,6 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Plugwise Stealth node object -""" -from plugwise.node import PlugwiseNode +"""Plugwise Stealth node object.""" from plugwise.nodes.circle import PlugwiseCircle class PlugwiseStealth(PlugwiseCircle): """provides interface to the Plugwise Stealth nodes""" - - def __init__(self, mac, address, stick): - super().__init__(mac, address, stick) diff --git a/plugwise/nodes/switch.py b/plugwise/nodes/switch.py index a2843c331..5f4e9df58 100644 --- a/plugwise/nodes/switch.py +++ b/plugwise/nodes/switch.py @@ -1,8 +1,4 @@ -""" -Use of this source code is governed by the MIT license found in the LICENSE file. - -Plugwise switch node object -""" +"""Plugwise switch node object.""" import logging from plugwise.constants import HA_BINARY_SENSOR, HA_SENSOR, SENSOR_SWITCH diff --git a/plugwise/parser.py b/plugwise/parser.py index 12b7e4964..5f7d6bf7e 100644 --- a/plugwise/parser.py +++ b/plugwise/parser.py @@ -1,4 +1,4 @@ -# Use of this source code is governed by the MIT license found in the LICENSE file. +"""Transform Plugwise message from wire format to response message object.""" import logging @@ -31,9 +31,7 @@ class PlugwiseParser: - """ - Transform Plugwise message from wire format to response message object - """ + """Transform Plugwise message from wire format to response message object.""" def __init__(self, stick): self.stick = stick @@ -70,7 +68,7 @@ def parse_data(self): # noqa: C901 """ # TODO: flake8 indicates scan is too complex, level 35 indenting is indeed too complex _LOGGER.debug("Parse data: %s ", str(self._buffer)) - if self._parsing is False: + if not self._parsing: self._parsing = True # Lookup header of message in buffer diff --git a/plugwise/smile.py b/plugwise/smile.py index 6b293170a..5232fa0f2 100644 --- a/plugwise/smile.py +++ b/plugwise/smile.py @@ -7,7 +7,7 @@ import aiohttp import async_timeout from dateutil.parser import parse -from lxml import etree +from defusedxml import ElementTree as etree # Time related import pytz @@ -259,7 +259,7 @@ async def request( try: # Encode to ensure utf8 parsing xml = etree.XML(escape_illegal_xml_characters(result).encode()) - except etree.XMLSyntaxError: + except etree.ParseError: _LOGGER.error("Smile returns invalid XML for %s", self._endpoint) raise InvalidXMLError @@ -746,7 +746,7 @@ def get_device_data(self, dev_id): if power_data is not None: device_data.update(power_data) - ## Switching Groups + # Switching Groups if details["class"] in SWITCH_GROUP_TYPES: counter = 0 for member in details["members"]: @@ -794,10 +794,7 @@ def get_appliance_data(self, dev_id): ): continue # The presence of either indicates a local active device, e.g. heat-pump or gas-fired heater - if ( - measurement == "compressor_state" - or measurement == "flame_state" - ): + if measurement in ["compressor_state", "flame_state"]: self.active_device_present = True data[name] = format_measure(measure) diff --git a/plugwise/stick.py b/plugwise/stick.py index 7e2602a58..278da4869 100644 --- a/plugwise/stick.py +++ b/plugwise/stick.py @@ -10,8 +10,6 @@ import threading import time -import serial - from plugwise.connections.serial import PlugwiseUSBConnection from plugwise.connections.socket import SocketConnection from plugwise.constants import ( @@ -21,14 +19,12 @@ ACK_ERROR, ACK_OFF, ACK_ON, - ACK_REAL_TIME_CLOCK_SET, ACK_SCAN_PARAMETERS_SET, ACK_SLEEP_SET, ACK_SUCCESS, ACK_TIMEOUT, CB_JOIN_REQUEST, CB_NEW_NODE, - MAX_TIME_DRIFT, MESSAGE_RETRY, MESSAGE_TIME_OUT, NACK_ON_OFF, @@ -42,7 +38,6 @@ NODE_TYPE_SCAN, NODE_TYPE_SENSE, NODE_TYPE_STEALTH, - NODE_TYPE_STICK, NODE_TYPE_SWITCH, SLEEP_TIME, UTF8_DECODE, @@ -55,13 +50,10 @@ StickInitError, TimeoutException, ) -from plugwise.message import PlugwiseMessage from plugwise.messages.requests import ( CircleCalibrationRequest, CircleClockGetRequest, - CircleClockSetRequest, CirclePlusRealTimeClockGetRequest, - CirclePlusRealTimeClockSetRequest, CirclePlusScanRequest, CirclePowerUsageRequest, CircleSwitchRelayRequest, @@ -95,10 +87,8 @@ from plugwise.nodes.circle import PlugwiseCircle from plugwise.nodes.circle_plus import PlugwiseCirclePlus from plugwise.nodes.scan import PlugwiseScan -from plugwise.nodes.sed import NodeSED from plugwise.nodes.sense import PlugwiseSense from plugwise.nodes.stealth import PlugwiseStealth -from plugwise.nodes.switch import PlugwiseSwitch from plugwise.parser import PlugwiseParser from plugwise.util import inc_seq_id, validate_mac @@ -106,9 +96,7 @@ class stick: - """ - Plugwise connection stick - """ + """Plugwise connection stick.""" def __init__(self, port, callback=None, print_progress=False): self._mac_stick = None @@ -139,6 +127,17 @@ def __init__(self, port, callback=None, print_progress=False): self._run_send_message_thread = False self._run_update_thread = False + self._auto_update_timer = 0 + self._nodes_discovered = None + self._receive_timeout_thread = None + self._run_watchdog = None + self._send_message_queue = None + self._send_message_thread = None + self._update_thread = None + self._watchdog_thread = None + self.init_callback = None + self.connection = None + if callback: self.auto_initialize(callback) @@ -295,7 +294,7 @@ def do_callback(self, callback_type, callback_arg=None): def _discover_after_scan(self): """ Helper to do callback for new node """ node_discovered = None - for mac in self._nodes_not_discovered.keys(): + for mac, _values in self._nodes_not_discovered: if self._plugwise_nodes.get(mac, None): node_discovered = mac break @@ -322,7 +321,7 @@ def node(self, mac: str) -> PlugwiseNode: def discover_node(self, mac: str, callback=None, force_discover=False) -> bool: """ Discovery of plugwise node """ - if validate_mac(mac) is True: + if validate_mac(mac): if not self._plugwise_nodes.get(mac): if mac not in self._nodes_not_discovered.keys(): self._nodes_not_discovered[mac] = ( @@ -346,10 +345,8 @@ def discover_node(self, mac: str, callback=None, force_discover=False) -> bool: callback, ) return True - else: - return False - else: return False + return False def scan(self, callback=None): # noqa: C901 """ scan for connected plugwise nodes """ @@ -412,9 +409,7 @@ def timeout_expired(): discover_timeout = ( 10 + (len(nodes_to_discover) * 2) + (MESSAGE_TIME_OUT * MESSAGE_RETRY) ) - self.discover_timeout = threading.Timer( - discover_timeout, timeout_expired - ).start() + threading.Timer(discover_timeout, timeout_expired).start() _LOGGER.debug("Start discovery of linked node types...") for mac in nodes_to_discover: self.discover_node(mac, node_discovered) @@ -462,27 +457,25 @@ def allow_join_requests(self, enable: bool, accept: bool): def node_join(self, mac: str, callback=None) -> bool: """Accept node to join Plugwise network by adding it in Circle+ memory""" - if validate_mac(mac) is True: + if validate_mac(mac): self.send(NodeAddRequest(bytes(mac, UTF8_DECODE), True), callback) return True - else: - _LOGGER.warning( - "Invalid mac '%s' address, unable to join node manually.", mac - ) + + _LOGGER.warning("Invalid mac '%s' address, unable to join node manually.", mac) return False def node_unjoin(self, mac: str, callback=None) -> bool: """Remove node from the Plugwise network by deleting it from the Circle+ memory""" - if validate_mac(mac) is True: + if validate_mac(mac): self.send( NodeRemoveRequest(bytes(self.circle_plus_mac, UTF8_DECODE), mac), callback, ) return True - else: - _LOGGER.warning( - "Invalid mac '%s' address, unable to unjoin node manually.", mac - ) + + _LOGGER.warning( + "Invalid mac '%s' address, unable to unjoin node manually.", mac + ) return False def _append_node(self, mac, address, node_type): @@ -1350,7 +1343,7 @@ def _watchdog_loop(self): self._update_thread.daemon = True self._update_thread.start() # Circle+ discovery - if self._circle_plus_discovered is False: + if not self._circle_plus_discovered: # First hour every once an hour if self._circle_plus_retries < 60 or circle_plus_retry_counter > 60: _LOGGER.info( @@ -1373,7 +1366,7 @@ def _update_loop(self): # noqa: C901 """ # TODO: flake8 indicates scan is too complex, level 28 indenting is indeed complex self._run_update_thread = True - self._auto_update_first_run = True + _auto_update_first_run = True day_of_month = datetime.now().day try: while self._run_update_thread: @@ -1388,7 +1381,7 @@ def _update_loop(self): # noqa: C901 minutes=( self._plugwise_nodes[ mac - ]._maintenance_interval + ].maintenance_interval + 1 ) ) @@ -1398,7 +1391,7 @@ def _update_loop(self): # noqa: C901 str( self._plugwise_nodes[ mac - ]._maintenance_interval + ].maintenance_interval ), mac, str(self._plugwise_nodes[mac].last_update), @@ -1408,7 +1401,7 @@ def _update_loop(self): # noqa: C901 minutes=( self._plugwise_nodes[ mac - ]._maintenance_interval + ].maintenance_interval + 1 ) ) @@ -1431,7 +1424,7 @@ def _update_loop(self): # noqa: C901 ): # Don't check at first time _LOGGER.debug("Request current power usage for node %s", mac) - if not self._auto_update_first_run and self._run_update_thread: + if not _auto_update_first_run and self._run_update_thread: # Only request update if node is available if self._plugwise_nodes[mac].get_available(): _LOGGER.debug( @@ -1455,23 +1448,23 @@ def _update_loop(self): # noqa: C901 self._plugwise_nodes[mac].update_power_usage() # Refresh node info once per hour and request power use afterwards if ( - self._plugwise_nodes[mac]._last_info_message + self._plugwise_nodes[mac].last_info_message is not None ): - if self._plugwise_nodes[mac]._last_info_message < ( + if self._plugwise_nodes[mac].last_info_message < ( datetime.now().replace( minute=0, second=0, microsecond=0, ) ): - self._plugwise_nodes[mac]._request_info( + self._plugwise_nodes[mac].request_info( self._plugwise_nodes[ mac - ]._request_power_buffer + ].request_power_buffer ) - if not self._plugwise_nodes[mac]._last_log_collected: - self._plugwise_nodes[mac]._request_power_buffer() + if not self._plugwise_nodes[mac].last_log_collected: + self._plugwise_nodes[mac].request_power_buffer() else: if self._run_update_thread: _LOGGER.debug( @@ -1479,7 +1472,7 @@ def _update_loop(self): # noqa: C901 mac, ) self._plugwise_nodes[mac].update_power_usage() - self._auto_update_first_run = False + _auto_update_first_run = False # Sync internal clock of all available Circle and Circle+ nodes once a day if datetime.now().day != day_of_month: @@ -1534,23 +1527,19 @@ def _update_loop(self): # noqa: C901 update_loop_checker += 1 except Exception as e: - exc_type, exc_obj, exc_tb = sys.exc_info() + _exc_type, _exc_obj, exc_tb = sys.exc_info() _LOGGER.error("Error at line %s of _update_loop : %s", exc_tb.tb_lineno, e) _LOGGER.debug("Update loop stopped") def auto_update(self, timer=None): - """ - setup auto update polling for power usage. - """ - if timer == 0: - self._run_update_thread = False + """ Configure auto update polling daemon for power usage and availability state. """ + if timer: + self._auto_update_timer = timer + elif timer == 0: self._auto_update_timer = 0 + self._run_update_thread = False else: - self._auto_update_timer = 5 - if timer is not None: - # Timer based on number of nodes and 3 seconds per node - self._auto_update_timer = len(self._plugwise_nodes) * 3 - elif timer > 5: - self._auto_update_timer = timer - if not self._run_update_thread: - self._update_thread.start() + # Timer based on number of nodes and 3 seconds per node + self._auto_update_timer = len(self._plugwise_nodes) * 3 + if not self._run_update_thread: + self._update_thread.start() diff --git a/plugwise/util.py b/plugwise/util.py index 43dd88061..30d6a05e1 100644 --- a/plugwise/util.py +++ b/plugwise/util.py @@ -5,15 +5,12 @@ """ import binascii import datetime -import logging import re import struct -import sys import crcmod from .constants import LOGADDR_OFFSET, PLUGWISE_EPOCH, UTF8_DECODE -from .exceptions import * crc_fun = crcmod.mkCrcFun(0x11021, rev=False, initCrc=0x0000, xorOut=0x0000) diff --git a/pylintrc b/pylintrc index 311ffc964..08a56d8b6 100644 --- a/pylintrc +++ b/pylintrc @@ -3,9 +3,9 @@ # Use a conservative default here; 2 should speed up most setups and not hurt # any too bad. Override on command line as appropriate. jobs=2 - load-plugins=pylint_strict_informational + #load-plugins=pylint_strict_informational persistent=no - extension-pkg-whitelist=ciso8601,lxml + extension-pkg-whitelist=ciso8601,defusedxml [BASIC] good-names=id,i,j,k,ex,Run,_,fp diff --git a/scripts/pre-commit.sh b/scripts/pre-commit.sh index adb634429..8479e1bd5 100755 --- a/scripts/pre-commit.sh +++ b/scripts/pre-commit.sh @@ -3,7 +3,7 @@ grep -r --include="*.xml" '' userdata/* | grep -v '0123456789AB' && grep -r --include="*.xml" '' userdata/* | grep -v 'abcdefgh' && echo "COMMIT REJECTED, found a real short_id, modify domain_objects and set short_id to abcdefgh!" && exit 1 grep -r --include="*.xml" '' userdata/* | grep -v '_ip>' userdata/* | grep -v '_ip>' userdata/* | grep -v 'smile000000' | grep -v 'stretch000000' && echo "COMMIT REJECTED, found a Smile(/Stretch) hostname, modify system_status or domain_objects and set hostname to smile000000!" && exit 1 grep -r --include="*.xml" '' userdata/* | grep -v '4.49' && echo "COMMIT REJECTED, found your hometown, modify domain_objects and set longitude to 4.49 (that is: Plugwise HQ)!" && exit 1 grep -r --include="*.xml" '' userdata/* | grep -v '52.21' && echo "COMMIT REJECTED, found your hometown, modify domain_objects and set latitude to 52.21 (that is: Plugwise HQ)!" && exit 1 diff --git a/scripts/tests_and_coverage.sh b/scripts/tests_and_coverage.sh index aa6661d3a..e69c6f4a1 100755 --- a/scripts/tests_and_coverage.sh +++ b/scripts/tests_and_coverage.sh @@ -1,9 +1,5 @@ -#!/bin/sh +#!/bin/bash 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 -pytest=`echo $?` -echo "-----------------------------------------------------------------" -echo "pytest exit code: ${pytest}" -echo "-----------------------------------------------------------------" +PYTHONPATH=$(pwd) pytest -rpP --log-level debug tests/test_smile.py --cov='.' --no-cov-on-fail diff --git a/setup.py b/setup.py index 188b30089..9b55a9206 100644 --- a/setup.py +++ b/setup.py @@ -39,7 +39,7 @@ def readme(): "aiohttp", "async_timeout<4.0", "crcmod", - "lxml", + "defusedxml", "pyserial", "pytz", "python-dateutil", diff --git a/tests/bandit.yaml b/tests/bandit.yaml index faf439ec4..ebd284eaa 100644 --- a/tests/bandit.yaml +++ b/tests/bandit.yaml @@ -15,4 +15,3 @@ tests: - B325 - B602 - B604 - diff --git a/tests/test_smile.py b/tests/test_smile.py index 9b0870ca2..451c2bca9 100644 --- a/tests/test_smile.py +++ b/tests/test_smile.py @@ -1,9 +1,8 @@ -"""Test Plugwise Home Assistant module and generate test JSONs.""" +"""Test Plugwise Home Assistant module and generate test JSON fixtures.""" import asyncio # Fixture writing -import io import logging import os from pprint import PrettyPrinter @@ -782,14 +781,13 @@ async def test_connect_anna_without_boiler_fw4(self): await smile.close_connection() await self.disconnect(server, client) - """ - # TODO: This device setup needs work - doesn't seem to work straightforard # currently breaks on setting thermostat setpoint # Actual test for directory 'Adam' # living room floor radiator valve and separate zone thermostat # an three rooms with conventional radiators + """ @pytest.mark.asyncio async def test_connect_adam(self): testdata = { @@ -1297,7 +1295,7 @@ async def test_fail_legacy_system(self): """Test erroneous legacy stretch system.""" self.smile_setup = "faulty_stretch" try: - server, smile, client = await self.connect_wrapper() + _server, _smile, _client = await self.connect_wrapper() assert False except ConnectionFailedError: assert True