From f992e03b80da5a96cd6df5c12a2d6b628c7e0aa4 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 11:19:05 +0100 Subject: [PATCH 01/24] Linting run --- plugwise/__init__.py | 2 +- plugwise/connections/__init__.py | 1 + plugwise/connections/connection.py | 39 +++++++++-------- plugwise/connections/serial.py | 16 +++---- plugwise/connections/socket.py | 17 +++----- plugwise/exceptions.py | 2 +- plugwise/message.py | 23 +++------- plugwise/messages/__init__.py | 2 +- plugwise/messages/requests.py | 16 ++----- plugwise/messages/responses.py | 13 ++---- plugwise/node.py | 37 +++++++--------- plugwise/nodes/__init__.py | 2 +- plugwise/nodes/circle.py | 18 +++----- plugwise/nodes/circle_plus.py | 9 +--- plugwise/nodes/scan.py | 9 +--- plugwise/nodes/sed.py | 22 ++++------ plugwise/nodes/sense.py | 7 +-- plugwise/nodes/stealth.py | 10 +---- plugwise/nodes/switch.py | 6 +-- plugwise/parser.py | 6 +-- plugwise/smile.py | 7 +-- plugwise/stick.py | 69 ++++++++++++++---------------- plugwise/util.py | 3 -- tests/test_smile.py | 12 +++--- 24 files changed, 129 insertions(+), 219 deletions(-) diff --git a/plugwise/__init__.py b/plugwise/__init__.py index 1b05cd9f3..7d1f4dc2a 100644 --- a/plugwise/__init__.py +++ b/plugwise/__init__.py @@ -1,6 +1,6 @@ """Plugwise module.""" -__version__ = "0.8.2a0" +__version__ = "0.8.3a0" 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..1c067c703 100644 --- a/plugwise/connections/socket.py +++ b/plugwise/connections/socket.py @@ -1,23 +1,16 @@ -""" -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 +20,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 +82,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..93af9b112 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 diff --git a/plugwise/messages/responses.py b/plugwise/messages/responses.py index 690cdadbd..efd8f1ea1 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 ( @@ -66,10 +62,9 @@ def deserialize(self, response): response = response[16:] response = self._parse_params(response) - # TODO: unused crc - # crc = response[:4] + crc = response[:4] - if response[4:] != MESSAGE_FOOTER: + if crc != MESSAGE_FOOTER: raise ProtocolError("Invalid message footer") def _parse_params(self, response): @@ -143,7 +138,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..00855aa94 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,7 +28,7 @@ class PlugwiseNode: - """Base class for a Plugwise node.""" + """ Base class for a Plugwise node """ def __init__(self, mac, address, stick): mac = mac.upper() @@ -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: @@ -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..91665a809 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, @@ -46,9 +40,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 +57,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 +105,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..204f877f8 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 diff --git a/plugwise/smile.py b/plugwise/smile.py index 6b293170a..2a14795c5 100644 --- a/plugwise/smile.py +++ b/plugwise/smile.py @@ -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..f167929fd 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, @@ -98,7 +90,6 @@ 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 +97,7 @@ class stick: - """ - Plugwise connection stick - """ + """Plugwise connection stick.""" def __init__(self, port, callback=None, print_progress=False): self._mac_stick = None @@ -139,6 +128,18 @@ def __init__(self, port, callback=None, print_progress=False): self._run_send_message_thread = False self._run_update_thread = False + self._auto_update_timer = None + self._auto_update_first_run = None + 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 +296,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 @@ -346,10 +347,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 +411,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) @@ -465,10 +462,8 @@ def node_join(self, mac: str, callback=None) -> bool: if validate_mac(mac) is True: 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: @@ -479,10 +474,10 @@ def node_unjoin(self, mac: str, callback=None) -> bool: 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): @@ -1388,7 +1383,7 @@ def _update_loop(self): # noqa: C901 minutes=( self._plugwise_nodes[ mac - ]._maintenance_interval + ].maintenance_interval + 1 ) ) @@ -1398,7 +1393,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 +1403,7 @@ def _update_loop(self): # noqa: C901 minutes=( self._plugwise_nodes[ mac - ]._maintenance_interval + ].maintenance_interval + 1 ) ) @@ -1455,23 +1450,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( @@ -1534,7 +1529,7 @@ 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") 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/tests/test_smile.py b/tests/test_smile.py index 9b0870ca2..81d67c0c5 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 @@ -36,6 +35,10 @@ class TestPlugwise: """Tests for Plugwise Smile.""" + def __init__(self): + """Initialize tests.""" + self.smile_setup = None + def _write_json(self, call, data): """Store JSON data to per-setup files for HA component testing.""" path = os.path.join( @@ -782,14 +785,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 +1299,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 From 6f9456607f30011613c15025b0bf6db0a0224918 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 11:23:01 +0100 Subject: [PATCH 02/24] Linting run - additionals after merging --- plugwise/connections/socket.py | 1 - plugwise/nodes/sed.py | 1 - plugwise/stick.py | 1 - 3 files changed, 3 deletions(-) diff --git a/plugwise/connections/socket.py b/plugwise/connections/socket.py index 1c067c703..69efe43cf 100644 --- a/plugwise/connections/socket.py +++ b/plugwise/connections/socket.py @@ -3,7 +3,6 @@ import socket from plugwise.connections.connection import StickConnection -from plugwise.constants import SLEEP_TIME from plugwise.exceptions import PortError _LOGGER = logging.getLogger(__name__) diff --git a/plugwise/nodes/sed.py b/plugwise/nodes/sed.py index 91665a809..7556bf2bc 100644 --- a/plugwise/nodes/sed.py +++ b/plugwise/nodes/sed.py @@ -22,7 +22,6 @@ SENSOR_RSSI_IN, SENSOR_RSSI_OUT, ) -from plugwise.message import PlugwiseMessage from plugwise.messages.requests import ( NodeInfoRequest, NodePingRequest, diff --git a/plugwise/stick.py b/plugwise/stick.py index f167929fd..ff20ea23f 100644 --- a/plugwise/stick.py +++ b/plugwise/stick.py @@ -87,7 +87,6 @@ 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.parser import PlugwiseParser From 042e487a42a3f4be44dd11c37741ce1a37f54a24 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 11:26:47 +0100 Subject: [PATCH 03/24] Linting run - additionals after merging - fix tests --- tests/test_smile.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/test_smile.py b/tests/test_smile.py index 81d67c0c5..451c2bca9 100644 --- a/tests/test_smile.py +++ b/tests/test_smile.py @@ -35,10 +35,6 @@ class TestPlugwise: """Tests for Plugwise Smile.""" - def __init__(self): - """Initialize tests.""" - self.smile_setup = None - def _write_json(self, call, data): """Store JSON data to per-setup files for HA component testing.""" path = os.path.join( From 4d426a45932b222fb4e302f360bb78d6b160e78e Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 11:48:26 +0100 Subject: [PATCH 04/24] Add defusedxml instead of lxml --- plugwise/smile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugwise/smile.py b/plugwise/smile.py index 2a14795c5..8c1b5d44d 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 From 11b781a52ae45018f99380d2a6b1778d9851f505 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 11:58:08 +0100 Subject: [PATCH 05/24] Correct exception handling for defusedxml over lxml --- plugwise/smile.py | 2 +- pylintrc | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugwise/smile.py b/plugwise/smile.py index 8c1b5d44d..5232fa0f2 100644 --- a/plugwise/smile.py +++ b/plugwise/smile.py @@ -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 diff --git a/pylintrc b/pylintrc index 311ffc964..6d8642e52 100644 --- a/pylintrc +++ b/pylintrc @@ -5,7 +5,7 @@ jobs=2 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/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", From 7a3ffe6f48870045bd7b9770ae8393725e485643 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 12:17:28 +0100 Subject: [PATCH 06/24] Improve sh to bash --- scripts/pre-commit.sh | 2 +- scripts/tests_and_coverage.sh | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) 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 From cf845316a8b2c0266c0321828f849c26702dc7f9 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 12:28:27 +0100 Subject: [PATCH 07/24] Tinker bandit --- .bandit | 2 ++ tests/bandit.yaml | 18 ------------------ 2 files changed, 2 insertions(+), 18 deletions(-) create mode 100644 .bandit delete mode 100644 tests/bandit.yaml 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/tests/bandit.yaml b/tests/bandit.yaml deleted file mode 100644 index faf439ec4..000000000 --- a/tests/bandit.yaml +++ /dev/null @@ -1,18 +0,0 @@ -# https://bandit.readthedocs.io/en/latest/config.html - -tests: - - B108 - - B306 - - B307 - - B313 - - B314 - - B315 - - B316 - - B317 - - B318 - - B319 - - B320 - - B325 - - B602 - - B604 - From 3b64ef8d301cf02c41f48f2ea27866e40c91c802 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 12:32:01 +0100 Subject: [PATCH 08/24] Tinker pylint --- pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pylintrc b/pylintrc index 6d8642e52..08a56d8b6 100644 --- a/pylintrc +++ b/pylintrc @@ -3,7 +3,7 @@ # 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,defusedxml From 6b5cd2bb6864f0890e57bf930be9175f69de19f3 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 12:33:40 +0100 Subject: [PATCH 09/24] Tinker bandit --- tests/bandit.yaml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 tests/bandit.yaml diff --git a/tests/bandit.yaml b/tests/bandit.yaml new file mode 100644 index 000000000..ebd284eaa --- /dev/null +++ b/tests/bandit.yaml @@ -0,0 +1,17 @@ +# https://bandit.readthedocs.io/en/latest/config.html + +tests: + - B108 + - B306 + - B307 + - B313 + - B314 + - B315 + - B316 + - B317 + - B318 + - B319 + - B320 + - B325 + - B602 + - B604 From 4347dbb0d254cf752866b154acbed8aed1c64fbc Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 16:10:58 +0100 Subject: [PATCH 10/24] Correct versioning --- plugwise/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugwise/__init__.py b/plugwise/__init__.py index 7d1f4dc2a..34efdbcf3 100644 --- a/plugwise/__init__.py +++ b/plugwise/__init__.py @@ -1,6 +1,6 @@ """Plugwise module.""" -__version__ = "0.8.3a0" +__version__ = "0.8.2a1" from plugwise.smile import Smile from plugwise.stick import stick From 60ef5b77cd847cd80944976e171825829164ce6b Mon Sep 17 00:00:00 2001 From: Bouwe Westerdijk Date: Sat, 31 Oct 2020 18:14:32 +0100 Subject: [PATCH 11/24] Fix all "is True/False" --- plugwise/messages/requests.py | 18 +++++++++--------- plugwise/node.py | 8 ++++---- plugwise/parser.py | 2 +- plugwise/stick.py | 8 ++++---- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/plugwise/messages/requests.py b/plugwise/messages/requests.py index 93af9b112..2807772b4 100644 --- a/plugwise/messages/requests.py +++ b/plugwise/messages/requests.py @@ -60,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) @@ -85,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)) @@ -183,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)) @@ -286,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)) @@ -335,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)) @@ -382,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 += [ @@ -479,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, @@ -524,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/node.py b/plugwise/node.py index 00855aa94..198a5e6d6 100644 --- a/plugwise/node.py +++ b/plugwise/node.py @@ -32,7 +32,7 @@ class PlugwiseNode: 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), @@ -99,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", @@ -110,7 +110,7 @@ def set_available(self, state, request_info=False): if request_info: self._request_info() else: - if self._available is True: + if self._available: self._available = False _LOGGER.debug( "Mark node %s unavailable", diff --git a/plugwise/parser.py b/plugwise/parser.py index 204f877f8..5f7d6bf7e 100644 --- a/plugwise/parser.py +++ b/plugwise/parser.py @@ -68,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/stick.py b/plugwise/stick.py index ff20ea23f..c03d2581e 100644 --- a/plugwise/stick.py +++ b/plugwise/stick.py @@ -322,7 +322,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] = ( @@ -458,7 +458,7 @@ 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 @@ -467,7 +467,7 @@ def node_join(self, mac: str, callback=None) -> bool: 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, @@ -1344,7 +1344,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( From 214db89be10651c5274d1809fb8fed02018af089 Mon Sep 17 00:00:00 2001 From: Bouwe Westerdijk Date: Sat, 31 Oct 2020 18:36:07 +0100 Subject: [PATCH 12/24] Remove unneeded guarding --- plugwise/nodes/circle.py | 37 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/plugwise/nodes/circle.py b/plugwise/nodes/circle.py index bf21c68c1..bb0440964 100644 --- a/plugwise/nodes/circle.py +++ b/plugwise/nodes/circle.py @@ -319,27 +319,26 @@ 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 - if log_address is not None: - if bool(self.power_history): - # Only request last 2 power buffer logs - self.stick.send( - CirclePowerBufferRequest(self.mac, log_address - 1), - ) - self.stick.send( - CirclePowerBufferRequest(self.mac, log_address), - callback, - ) - else: - # Collect power history info of today and yesterday - # Each request contains 4 hours except last request - for req_log_address in range(log_address - 13, log_address): - self.stick.send( - CirclePowerBufferRequest(self.mac, req_log_address), - ) + if bool(self.power_history): + # Only request last 2 power buffer logs + self.stick.send( + CirclePowerBufferRequest(self.mac, log_address - 1), + ) + self.stick.send( + CirclePowerBufferRequest(self.mac, log_address), + callback, + ) + else: + # Collect power history info of today and yesterday + # Each request contains 4 hours except last request + for req_log_address in range(log_address - 13, log_address): self.stick.send( - CirclePowerBufferRequest(self.mac, log_address), - callback, + CirclePowerBufferRequest(self.mac, req_log_address), ) + self.stick.send( + CirclePowerBufferRequest(self.mac, log_address), + callback, + ) def _response_power_buffer(self, message): """returns information about historical power usage From 3e636b9465d00b28d21c378e970cc488232cd6d7 Mon Sep 17 00:00:00 2001 From: Bouwe Westerdijk Date: Sat, 31 Oct 2020 18:38:05 +0100 Subject: [PATCH 13/24] Blacked via VSC --- plugwise/nodes/circle.py | 35 +++++++++++------------------------ 1 file changed, 11 insertions(+), 24 deletions(-) diff --git a/plugwise/nodes/circle.py b/plugwise/nodes/circle.py index bb0440964..c3507e86e 100644 --- a/plugwise/nodes/circle.py +++ b/plugwise/nodes/circle.py @@ -83,22 +83,19 @@ def __init__(self, mac, address, stick): def _request_calibration(self, callback=None): """Request calibration info""" self.stick.send( - CircleCalibrationRequest(self.mac), - callback, + CircleCalibrationRequest(self.mac), callback, ) def _request_switch(self, state, callback=None): """Request to switch relay state and request state info""" self.stick.send( - CircleSwitchRelayRequest(self.mac, state), - callback, + CircleSwitchRelayRequest(self.mac, state), callback, ) def update_power_usage(self, callback=None): """Request power usage""" self.stick.send( - CirclePowerUsageRequest(self.mac), - callback, + CirclePowerUsageRequest(self.mac), callback, ) def _on_message(self, message): @@ -204,16 +201,14 @@ def _node_ack_response(self, message): if message.ack_id == ACK_ON: if not self._relay_state: _LOGGER.debug( - "Switch relay on for %s", - self.get_mac(), + "Switch relay on for %s", self.get_mac(), ) self._relay_state = True self.do_callback(SWITCH_RELAY["id"]) elif message.ack_id == ACK_OFF: if self._relay_state: _LOGGER.debug( - "Switch relay off for %s", - self.get_mac(), + "Switch relay off for %s", self.get_mac(), ) self._relay_state = False self.do_callback(SWITCH_RELAY["id"]) @@ -321,23 +316,17 @@ def request_power_buffer(self, log_address=None, callback=None): log_address = self._last_log_address if bool(self.power_history): # Only request last 2 power buffer logs + self.stick.send(CirclePowerBufferRequest(self.mac, log_address - 1),) self.stick.send( - CirclePowerBufferRequest(self.mac, log_address - 1), - ) - self.stick.send( - CirclePowerBufferRequest(self.mac, log_address), - callback, + CirclePowerBufferRequest(self.mac, log_address), callback, ) else: # Collect power history info of today and yesterday # Each request contains 4 hours except last request for req_log_address in range(log_address - 13, log_address): - self.stick.send( - CirclePowerBufferRequest(self.mac, req_log_address), - ) + self.stick.send(CirclePowerBufferRequest(self.mac, req_log_address),) self.stick.send( - CirclePowerBufferRequest(self.mac, log_address), - callback, + CirclePowerBufferRequest(self.mac, log_address), callback, ) def _response_power_buffer(self, message): @@ -415,15 +404,13 @@ def _response_clock(self, message): def get_clock(self, callback=None): """ get current datetime of internal clock of Circle """ self.stick.send( - CircleClockGetRequest(self.mac), - callback, + CircleClockGetRequest(self.mac), callback, ) def set_clock(self, callback=None): """ set internal clock of CirclePlus """ self.stick.send( - CircleClockSetRequest(self.mac, datetime.utcnow()), - callback, + CircleClockSetRequest(self.mac, datetime.utcnow()), callback, ) def sync_clock(self, max_drift=0): From 909d14fd366ff35a0363af40a1f490320f7a2401 Mon Sep 17 00:00:00 2001 From: brefra Date: Sat, 31 Oct 2020 18:40:19 +0100 Subject: [PATCH 14/24] Correct crc and message_footer mixup --- plugwise/messages/responses.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugwise/messages/responses.py b/plugwise/messages/responses.py index efd8f1ea1..3610f9125 100644 --- a/plugwise/messages/responses.py +++ b/plugwise/messages/responses.py @@ -64,7 +64,7 @@ def deserialize(self, response): response = self._parse_params(response) crc = response[:4] - if crc != MESSAGE_FOOTER: + if response[4:] != MESSAGE_FOOTER: raise ProtocolError("Invalid message footer") def _parse_params(self, response): From ce5e3968924b3c64164e0c2c7551154f09206908 Mon Sep 17 00:00:00 2001 From: Bouwe Westerdijk Date: Sat, 31 Oct 2020 18:38:05 +0100 Subject: [PATCH 15/24] Revert "Blacked via VSC" This reverts commit 3e636b9465d00b28d21c378e970cc488232cd6d7. --- plugwise/nodes/circle.py | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/plugwise/nodes/circle.py b/plugwise/nodes/circle.py index c3507e86e..bb0440964 100644 --- a/plugwise/nodes/circle.py +++ b/plugwise/nodes/circle.py @@ -83,19 +83,22 @@ def __init__(self, mac, address, stick): def _request_calibration(self, callback=None): """Request calibration info""" self.stick.send( - CircleCalibrationRequest(self.mac), callback, + CircleCalibrationRequest(self.mac), + callback, ) def _request_switch(self, state, callback=None): """Request to switch relay state and request state info""" self.stick.send( - CircleSwitchRelayRequest(self.mac, state), callback, + CircleSwitchRelayRequest(self.mac, state), + callback, ) def update_power_usage(self, callback=None): """Request power usage""" self.stick.send( - CirclePowerUsageRequest(self.mac), callback, + CirclePowerUsageRequest(self.mac), + callback, ) def _on_message(self, message): @@ -201,14 +204,16 @@ def _node_ack_response(self, message): if message.ack_id == ACK_ON: if not self._relay_state: _LOGGER.debug( - "Switch relay on for %s", self.get_mac(), + "Switch relay on for %s", + self.get_mac(), ) self._relay_state = True self.do_callback(SWITCH_RELAY["id"]) elif message.ack_id == ACK_OFF: if self._relay_state: _LOGGER.debug( - "Switch relay off for %s", self.get_mac(), + "Switch relay off for %s", + self.get_mac(), ) self._relay_state = False self.do_callback(SWITCH_RELAY["id"]) @@ -316,17 +321,23 @@ def request_power_buffer(self, log_address=None, callback=None): log_address = self._last_log_address if bool(self.power_history): # Only request last 2 power buffer logs - self.stick.send(CirclePowerBufferRequest(self.mac, log_address - 1),) self.stick.send( - CirclePowerBufferRequest(self.mac, log_address), callback, + CirclePowerBufferRequest(self.mac, log_address - 1), + ) + self.stick.send( + CirclePowerBufferRequest(self.mac, log_address), + callback, ) else: # Collect power history info of today and yesterday # Each request contains 4 hours except last request for req_log_address in range(log_address - 13, log_address): - self.stick.send(CirclePowerBufferRequest(self.mac, req_log_address),) + self.stick.send( + CirclePowerBufferRequest(self.mac, req_log_address), + ) self.stick.send( - CirclePowerBufferRequest(self.mac, log_address), callback, + CirclePowerBufferRequest(self.mac, log_address), + callback, ) def _response_power_buffer(self, message): @@ -404,13 +415,15 @@ def _response_clock(self, message): def get_clock(self, callback=None): """ get current datetime of internal clock of Circle """ self.stick.send( - CircleClockGetRequest(self.mac), callback, + CircleClockGetRequest(self.mac), + callback, ) def set_clock(self, callback=None): """ set internal clock of CirclePlus """ self.stick.send( - CircleClockSetRequest(self.mac, datetime.utcnow()), callback, + CircleClockSetRequest(self.mac, datetime.utcnow()), + callback, ) def sync_clock(self, max_drift=0): From cc4db3a360c221c12ca40bf5c448a7af359530ce Mon Sep 17 00:00:00 2001 From: Bouwe Westerdijk Date: Sat, 31 Oct 2020 18:36:07 +0100 Subject: [PATCH 16/24] Revert "Remove unneeded guarding" This reverts commit 214db89be10651c5274d1809fb8fed02018af089. --- plugwise/nodes/circle.py | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/plugwise/nodes/circle.py b/plugwise/nodes/circle.py index bb0440964..bf21c68c1 100644 --- a/plugwise/nodes/circle.py +++ b/plugwise/nodes/circle.py @@ -319,26 +319,27 @@ 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 - if bool(self.power_history): - # Only request last 2 power buffer logs - self.stick.send( - CirclePowerBufferRequest(self.mac, log_address - 1), - ) - self.stick.send( - CirclePowerBufferRequest(self.mac, log_address), - callback, - ) - else: - # Collect power history info of today and yesterday - # Each request contains 4 hours except last request - for req_log_address in range(log_address - 13, log_address): + if log_address is not None: + if bool(self.power_history): + # Only request last 2 power buffer logs self.stick.send( - CirclePowerBufferRequest(self.mac, req_log_address), + CirclePowerBufferRequest(self.mac, log_address - 1), + ) + self.stick.send( + CirclePowerBufferRequest(self.mac, log_address), + callback, + ) + else: + # Collect power history info of today and yesterday + # Each request contains 4 hours except last request + for req_log_address in range(log_address - 13, log_address): + self.stick.send( + CirclePowerBufferRequest(self.mac, req_log_address), + ) + self.stick.send( + CirclePowerBufferRequest(self.mac, log_address), + callback, ) - self.stick.send( - CirclePowerBufferRequest(self.mac, log_address), - callback, - ) def _response_power_buffer(self, message): """returns information about historical power usage From 24a1c8c6471d6def33b68889238b289887afc1d3 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 19:20:32 +0100 Subject: [PATCH 17/24] Add black before commit checks --- .github/workflows/verify.yml | 2 ++ 1 file changed, 2 insertions(+) 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 From 67a12be534a081fadd87e219453e74d93b1ce391 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 19:23:53 +0100 Subject: [PATCH 18/24] Re-remove crc --- plugwise/messages/responses.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugwise/messages/responses.py b/plugwise/messages/responses.py index 3610f9125..e23e8508a 100644 --- a/plugwise/messages/responses.py +++ b/plugwise/messages/responses.py @@ -62,7 +62,8 @@ def deserialize(self, response): response = response[16:] response = self._parse_params(response) - crc = response[:4] + # TODO: unused crc + # crc = response[:4] if response[4:] != MESSAGE_FOOTER: raise ProtocolError("Invalid message footer") From 2553027f853c5ef6eeef7f195a5345f772685fc7 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 20:09:46 +0100 Subject: [PATCH 19/24] stick auto_update typo fix --- plugwise/stick.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugwise/stick.py b/plugwise/stick.py index c03d2581e..9da663dc2 100644 --- a/plugwise/stick.py +++ b/plugwise/stick.py @@ -1541,7 +1541,7 @@ def auto_update(self, timer=None): self._auto_update_timer = 0 else: self._auto_update_timer = 5 - if timer is not None: + if timer is None: # Timer based on number of nodes and 3 seconds per node self._auto_update_timer = len(self._plugwise_nodes) * 3 elif timer > 5: From 09bae007062cfcad8b0e5aad261302355ff53891 Mon Sep 17 00:00:00 2001 From: brefra Date: Sat, 31 Oct 2020 20:40:23 +0100 Subject: [PATCH 20/24] Make auto_update_first_run local --- plugwise/stick.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/plugwise/stick.py b/plugwise/stick.py index 9da663dc2..30f79c7de 100644 --- a/plugwise/stick.py +++ b/plugwise/stick.py @@ -128,7 +128,6 @@ def __init__(self, port, callback=None, print_progress=False): self._run_update_thread = False self._auto_update_timer = None - self._auto_update_first_run = None self._nodes_discovered = None self._receive_timeout_thread = None self._run_watchdog = None @@ -1367,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: @@ -1425,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( @@ -1473,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: From 150d695883a6c7e0ece2656b921c8fe3b5e99788 Mon Sep 17 00:00:00 2001 From: brefra Date: Sat, 31 Oct 2020 20:43:57 +0100 Subject: [PATCH 21/24] Rewrite auto_update() --- plugwise/stick.py | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/plugwise/stick.py b/plugwise/stick.py index 30f79c7de..278da4869 100644 --- a/plugwise/stick.py +++ b/plugwise/stick.py @@ -127,7 +127,7 @@ def __init__(self, port, callback=None, print_progress=False): self._run_send_message_thread = False self._run_update_thread = False - self._auto_update_timer = None + self._auto_update_timer = 0 self._nodes_discovered = None self._receive_timeout_thread = None self._run_watchdog = None @@ -1532,18 +1532,14 @@ def _update_loop(self): # noqa: C901 _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 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() From 0d167e5aa4fefe56e806eaaa714559b200d103d7 Mon Sep 17 00:00:00 2001 From: brefra Date: Sat, 31 Oct 2020 20:48:05 +0100 Subject: [PATCH 22/24] Correct request_info() in node.py --- plugwise/node.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugwise/node.py b/plugwise/node.py index 198a5e6d6..5c6d6268e 100644 --- a/plugwise/node.py +++ b/plugwise/node.py @@ -108,7 +108,7 @@ 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: self._available = False @@ -160,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), From f99470291b121bf6e7e34aae1f005c293fef0fe5 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 21:29:30 +0100 Subject: [PATCH 23/24] Commit coverage idea of brefra --- .coveragerc | 1 + 1 file changed, 1 insertion(+) 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/* From fa2a9df545728a14cc260c5b9c21988ddd402977 Mon Sep 17 00:00:00 2001 From: Tom Scholten Date: Sat, 31 Oct 2020 21:38:32 +0100 Subject: [PATCH 24/24] Changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) 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