Skip to content

Commit f521fa7

Browse files
ArnoutDbouwew
authored andcommitted
ruff format according to ruless
1 parent 27e3273 commit f521fa7

28 files changed

+137
-94
lines changed

plugwise_usb/__init__.py

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,41 +20,43 @@
2020

2121
FuncT = TypeVar("FuncT", bound=Callable[..., Any])
2222

23-
NOT_INITIALIZED_STICK_ERROR: Final[StickError] = StickError("Cannot load nodes when network is not initialized")
23+
NOT_INITIALIZED_STICK_ERROR: Final[StickError] = StickError(
24+
"Cannot load nodes when network is not initialized"
25+
)
2426
_LOGGER = logging.getLogger(__name__)
2527

2628

2729
def raise_not_connected(func: FuncT) -> FuncT:
2830
"""Validate existence of an active connection to Stick. Raise StickError when there is no active connection."""
31+
2932
@wraps(func)
3033
def decorated(*args: Any, **kwargs: Any) -> Any:
3134
if not args[0].is_connected:
32-
raise StickError(
33-
"Not connected to USB-Stick, connect to USB-stick first."
34-
)
35+
raise StickError("Not connected to USB-Stick, connect to USB-stick first.")
3536
return func(*args, **kwargs)
37+
3638
return cast(FuncT, decorated)
3739

3840

3941
def raise_not_initialized(func: FuncT) -> FuncT:
4042
"""Validate if active connection is initialized. Raise StickError when not initialized."""
43+
4144
@wraps(func)
4245
def decorated(*args: Any, **kwargs: Any) -> Any:
4346
if not args[0].is_initialized:
4447
raise StickError(
45-
"Connection to USB-Stick is not initialized, " +
46-
"initialize USB-stick first."
48+
"Connection to USB-Stick is not initialized, "
49+
+ "initialize USB-stick first."
4750
)
4851
return func(*args, **kwargs)
52+
4953
return cast(FuncT, decorated)
5054

5155

5256
class Stick:
5357
"""Plugwise connection stick."""
5458

55-
def __init__(
56-
self, port: str | None = None, cache_enabled: bool = True
57-
) -> None:
59+
def __init__(self, port: str | None = None, cache_enabled: bool = True) -> None:
5860
"""Initialize Stick."""
5961
self._loop = get_running_loop()
6062
self._loop.set_debug(True)
@@ -170,13 +172,8 @@ def port(self) -> str | None:
170172
@port.setter
171173
def port(self, port: str) -> None:
172174
"""Path to serial port of USB-Stick."""
173-
if (
174-
self._controller.is_connected
175-
and port != self._port
176-
):
177-
raise StickError(
178-
"Unable to change port while connected. Disconnect first"
179-
)
175+
if self._controller.is_connected and port != self._port:
176+
raise StickError("Unable to change port while connected. Disconnect first")
180177

181178
self._port = port
182179

@@ -238,7 +235,9 @@ def subscribe_to_node_events(
238235
Returns the function to be called to unsubscribe later.
239236
"""
240237
if self._network is None:
241-
raise SubscriptionError("Unable to subscribe to node events without network connection initialized")
238+
raise SubscriptionError(
239+
"Unable to subscribe to node events without network connection initialized"
240+
)
242241
return self._network.subscribe_to_node_events(
243242
node_event_callback,
244243
events,
@@ -252,9 +251,7 @@ def _validate_node_discovery(self) -> None:
252251
if self._network is None or not self._network.is_running:
253252
raise StickError("Plugwise network node discovery is not active.")
254253

255-
async def setup(
256-
self, discover: bool = True, load: bool = True
257-
) -> None:
254+
async def setup(self, discover: bool = True, load: bool = True) -> None:
258255
"""Fully connect, initialize USB-Stick and discover all connected nodes."""
259256
if not self.is_connected:
260257
await self.connect()
@@ -271,17 +268,17 @@ async def connect(self, port: str | None = None) -> None:
271268
"""Connect to USB-Stick. Raises StickError if connection fails."""
272269
if self._controller.is_connected:
273270
raise StickError(
274-
f"Already connected to {self._port}, " +
275-
"Close existing connection before (re)connect."
271+
f"Already connected to {self._port}, "
272+
+ "Close existing connection before (re)connect."
276273
)
277274

278275
if port is not None:
279276
self._port = port
280277

281278
if self._port is None:
282279
raise StickError(
283-
"Unable to connect. " +
284-
"Path to USB-Stick is not defined, set port property first"
280+
"Unable to connect. "
281+
+ "Path to USB-Stick is not defined, set port property first"
285282
)
286283

287284
await self._controller.connect_to_stick(
@@ -319,9 +316,7 @@ async def load_nodes(self) -> bool:
319316
if self._network is None:
320317
raise NOT_INITIALIZED_STICK_ERROR
321318
if not self._network.is_running:
322-
raise StickError(
323-
"Cannot load nodes when network is not started"
324-
)
319+
raise StickError("Cannot load nodes when network is not started")
325320
return await self._network.discover_nodes(load=True)
326321

327322
@raise_not_connected

plugwise_usb/api.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -704,5 +704,4 @@ async def message_for_node(self, message: Any) -> None:
704704
705705
"""
706706

707-
708707
# endregion

plugwise_usb/connection/__init__.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -209,19 +209,15 @@ async def get_node_details(
209209
ping_response: NodePingResponse | None = None
210210
if ping_first:
211211
# Define ping request with one retry
212-
ping_request = NodePingRequest(
213-
self.send, bytes(mac, UTF8), retries=1
214-
)
212+
ping_request = NodePingRequest(self.send, bytes(mac, UTF8), retries=1)
215213
try:
216214
ping_response = await ping_request.send()
217215
except StickError:
218216
return (None, None)
219217
if ping_response is None:
220218
return (None, None)
221219

222-
info_request = NodeInfoRequest(
223-
self.send, bytes(mac, UTF8), retries=1
224-
)
220+
info_request = NodeInfoRequest(self.send, bytes(mac, UTF8), retries=1)
225221
try:
226222
info_response = await info_request.send()
227223
except StickError:

plugwise_usb/connection/queue.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,8 @@ async def submit(self, request: PlugwiseRequest) -> PlugwiseResponse | None:
102102
if isinstance(request, NodePingRequest):
103103
# For ping requests it is expected to receive timeouts, so lower log level
104104
_LOGGER.debug(
105-
"%s, cancel because timeout is expected for NodePingRequests", exc
105+
"%s, cancel because timeout is expected for NodePingRequests",
106+
exc,
106107
)
107108
elif request.resend:
108109
_LOGGER.debug("%s, retrying", exc)
@@ -146,7 +147,9 @@ async def _send_queue_worker(self) -> None:
146147
if self._stick.queue_depth > 3:
147148
await sleep(0.125)
148149
if self._stick.queue_depth > 3:
149-
_LOGGER.warning("Awaiting plugwise responses %d", self._stick.queue_depth)
150+
_LOGGER.warning(
151+
"Awaiting plugwise responses %d", self._stick.queue_depth
152+
)
150153

151154
await self._stick.write_to_stick(request)
152155
self._submit_queue.task_done()

plugwise_usb/connection/receiver.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,4 +513,5 @@ async def _notify_node_response_subscribers(
513513
name=f"Postpone subscription task for {node_response.seq_id!r} retry {node_response.retries}",
514514
)
515515

516+
516517
# endregion

plugwise_usb/connection/sender.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,9 @@ async def write_request_to_port(self, request: PlugwiseRequest) -> None:
7979

8080
# Write message to serial port buffer
8181
serialized_data = request.serialize()
82-
_LOGGER.debug("write_request_to_port | Write %s to port as %s", request, serialized_data)
82+
_LOGGER.debug(
83+
"write_request_to_port | Write %s to port as %s", request, serialized_data
84+
)
8385
self._transport.write(serialized_data)
8486
# Don't timeout when no response expected
8587
if not request.no_response:
@@ -106,7 +108,11 @@ async def write_request_to_port(self, request: PlugwiseRequest) -> None:
106108
_LOGGER.warning("Exception for %s: %s", request, exc)
107109
request.assign_error(exc)
108110
else:
109-
_LOGGER.debug("write_request_to_port | USB-Stick replied with %s to request %s", response, request)
111+
_LOGGER.debug(
112+
"write_request_to_port | USB-Stick replied with %s to request %s",
113+
response,
114+
request,
115+
)
110116
if response.response_type == StickResponseType.ACCEPT:
111117
if request.seq_id is not None:
112118
request.assign_error(
@@ -121,7 +127,9 @@ async def write_request_to_port(self, request: PlugwiseRequest) -> None:
121127
self._receiver.subscribe_to_stick_responses,
122128
self._receiver.subscribe_to_node_responses,
123129
)
124-
_LOGGER.debug("write_request_to_port | request has subscribed : %s", request)
130+
_LOGGER.debug(
131+
"write_request_to_port | request has subscribed : %s", request
132+
)
125133
elif response.response_type == StickResponseType.TIMEOUT:
126134
_LOGGER.warning(
127135
"USB-Stick directly responded with communication timeout for %s",
@@ -143,7 +151,6 @@ async def write_request_to_port(self, request: PlugwiseRequest) -> None:
143151
self._stick_response.cancel()
144152
self._stick_lock.release()
145153

146-
147154
async def _process_stick_response(self, response: StickResponse) -> None:
148155
"""Process stick response."""
149156
if self._stick_response is None or self._stick_response.done():

plugwise_usb/constants.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Plugwise Stick constants."""
2+
23
from __future__ import annotations
34

45
import datetime as dt

plugwise_usb/helpers/cache.py

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ async def initialize_cache(self, create_root_folder: bool = False) -> None:
5353
"""Set (and create) the plugwise cache directory to store cache file."""
5454
if self._root_dir != "":
5555
if not create_root_folder and not await ospath.exists(self._root_dir):
56-
raise CacheError(f"Unable to initialize caching. Cache folder '{self._root_dir}' does not exists.")
56+
raise CacheError(
57+
f"Unable to initialize caching. Cache folder '{self._root_dir}' does not exists."
58+
)
5759
cache_dir = self._root_dir
5860
else:
5961
cache_dir = self._get_writable_os_dir()
@@ -72,13 +74,17 @@ def _get_writable_os_dir(self) -> str:
7274
if os_name == "nt":
7375
if (data_dir := os_getenv("APPDATA")) is not None:
7476
return os_path_join(data_dir, CACHE_DIR)
75-
raise CacheError("Unable to detect writable cache folder based on 'APPDATA' environment variable.")
77+
raise CacheError(
78+
"Unable to detect writable cache folder based on 'APPDATA' environment variable."
79+
)
7680
return os_path_join(os_path_expand_user("~"), CACHE_DIR)
7781

7882
async def write_cache(self, data: dict[str, str], rewrite: bool = False) -> None:
79-
""""Save information to cache file."""
83+
""" "Save information to cache file."""
8084
if not self._initialized:
81-
raise CacheError(f"Unable to save cache. Initialize cache file '{self._file_name}' first.")
85+
raise CacheError(
86+
f"Unable to save cache. Initialize cache file '{self._file_name}' first."
87+
)
8288

8389
current_data: dict[str, str] = {}
8490
if not rewrite:
@@ -111,19 +117,20 @@ async def write_cache(self, data: dict[str, str], rewrite: bool = False) -> None
111117
if not self._cache_file_exists:
112118
self._cache_file_exists = True
113119
_LOGGER.debug(
114-
"Saved %s lines to cache file %s",
115-
str(len(data)),
116-
self._cache_file
120+
"Saved %s lines to cache file %s", str(len(data)), self._cache_file
117121
)
118122

119123
async def read_cache(self) -> dict[str, str]:
120124
"""Return current data from cache file."""
121125
if not self._initialized:
122-
raise CacheError(f"Unable to save cache. Initialize cache file '{self._file_name}' first.")
126+
raise CacheError(
127+
f"Unable to save cache. Initialize cache file '{self._file_name}' first."
128+
)
123129
current_data: dict[str, str] = {}
124130
if not self._cache_file_exists:
125131
_LOGGER.debug(
126-
"Cache file '%s' does not exists, return empty cache data", self._cache_file
132+
"Cache file '%s' does not exists, return empty cache data",
133+
self._cache_file,
127134
)
128135
return current_data
129136
try:
@@ -146,10 +153,10 @@ async def read_cache(self) -> dict[str, str]:
146153
_LOGGER.warning(
147154
"Skip invalid line '%s' in cache file %s",
148155
data,
149-
str(self._cache_file)
156+
str(self._cache_file),
150157
)
151158
break
152-
current_data[data[:index_separator]] = data[index_separator + 1:]
159+
current_data[data[:index_separator]] = data[index_separator + 1 :]
153160
return current_data
154161

155162
async def delete_cache(self) -> None:

plugwise_usb/helpers/util.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Plugwise utility helpers."""
2+
23
from __future__ import annotations
34

45
import re
@@ -21,7 +22,7 @@ def validate_mac(mac: str) -> bool:
2122
return True
2223

2324

24-
def version_to_model(version: str | None) -> tuple[str|None, str]:
25+
def version_to_model(version: str | None) -> tuple[str | None, str]:
2526
"""Translate hardware_version to device type."""
2627
if version is None:
2728
return (None, "Unknown")

plugwise_usb/messages/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ class Priority(Enum):
1919
MEDIUM = 2
2020
LOW = 3
2121

22+
2223
class PlugwiseMessage:
2324
"""Plugwise message base class."""
2425

plugwise_usb/messages/properties.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@
99
from ..exceptions import MessageError
1010
from ..helpers.util import int_to_uint
1111

12-
DESERIALIZE_ERROR: Final[MessageError] = MessageError("Unable to return value. Deserialize data first")
12+
DESERIALIZE_ERROR: Final[MessageError] = MessageError(
13+
"Unable to return value. Deserialize data first"
14+
)
15+
1316

1417
class BaseType:
1518
"""Generic single instance property."""

plugwise_usb/messages/requests.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,9 @@ async def _process_stick_response(self, stick_response: StickResponse) -> None:
311311
self,
312312
)
313313

314-
async def _send_request(self, suppress_node_errors=False) -> PlugwiseResponse | None:
314+
async def _send_request(
315+
self, suppress_node_errors=False
316+
) -> PlugwiseResponse | None:
315317
"""Send request."""
316318
if self._send_fn is None:
317319
return None

plugwise_usb/messages/responses.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -778,19 +778,19 @@ def log_data(self) -> dict[int, tuple[datetime | None, int | None]]:
778778
if self.logdate1.value_set:
779779
log_data[1] = (self.logdate1.value, self.pulses1.value)
780780
else:
781-
log_data[1] = (None, None)
781+
log_data[1] = (None, None)
782782
if self.logdate2.value_set:
783783
log_data[2] = (self.logdate2.value, self.pulses2.value)
784784
else:
785-
log_data[2] = (None, None)
785+
log_data[2] = (None, None)
786786
if self.logdate3.value_set:
787787
log_data[3] = (self.logdate3.value, self.pulses3.value)
788788
else:
789-
log_data[3] = (None, None)
789+
log_data[3] = (None, None)
790790
if self.logdate4.value_set:
791791
log_data[4] = (self.logdate4.value, self.pulses4.value)
792792
else:
793-
log_data[4] = (None, None)
793+
log_data[4] = (None, None)
794794
return log_data
795795

796796
def __repr__(self) -> str:
@@ -856,12 +856,13 @@ def __init__(self) -> None:
856856
@property
857857
def switch_state(self) -> bool:
858858
"""Return state of switch (True = On, False = Off)."""
859-
return (self._power_state.value != 0)
859+
return self._power_state.value != 0
860860

861861
def __repr__(self) -> str:
862862
"""Convert request into writable str."""
863863
return f"{super().__repr__()[:-1]}, power_state={self._power_state.value}, group={self.group.value})"
864864

865+
865866
class NodeFeaturesResponse(PlugwiseResponse):
866867
"""Returns supported features of node.
867868

0 commit comments

Comments
 (0)